<x-app-layout>
<x-module-hero
    :title="'Chat: ' . ($conversation->visitor_name ?? 'Guest Visitor')"
    :description="($conversation->category->name ?? 'General') . ' • ' . ucfirst($conversation->status)"
    icon="fa-comment-dots">
    <x-slot name="backButton">
        <a href="{{ route('chat.conversations') }}" class="inline-flex items-center gap-2 text-white/80 hover:text-white text-sm transition">
            <i class="fas fa-arrow-left"></i> Back to Conversations
        </a>
    </x-slot>
    <x-slot name="tabs">
        @can('view chats')
        <a href="{{ route('chat.index') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-tachometer-alt"></i> Dashboard
        </a>
        @endcan
        @can('handle chats')
        <a href="{{ route('chat.conversations') }}"
           class="module-hero-tab border-b-2 border-[#1e293b] inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-comments"></i> Conversations
        </a>
        @endcan
        @can('handle chats')
        <a href="{{ route('chat.agent-dashboard') }}"
           class="module-hero-tab opacity-70 hover:opacity-100 inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium transition">
            <i class="fas fa-headset"></i> Agent Dashboard
        </a>
        @endcan
    </x-slot>
</x-module-hero>

{{-- Full-height chat interface --}}
<div class="flex" style="height: calc(100vh - 160px);"
     x-data="agentChatSession({{ $conversation->id }}, {{ $conversation->messages->last()?->id ?? 0 }}, '{{ $conversation->status }}')">

    {{-- Chat Area --}}
    <div class="flex-1 flex flex-col bg-white border-r border-gray-200">

        {{-- Chat Header --}}
        <div class="px-6 py-3 border-b border-gray-200 bg-gray-50 flex items-center justify-between flex-shrink-0">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 rounded-full bg-gradient-to-br from-green-500 to-green-700 flex items-center justify-center text-white font-semibold text-sm">
                    {{ strtoupper(substr($conversation->visitor_name ?? 'G', 0, 1)) }}
                </div>
                <div>
                    <h3 class="font-semibold text-gray-800 text-sm">{{ $conversation->visitor_name ?? 'Guest Visitor' }}</h3>
                    <p class="text-xs text-gray-500">{{ $conversation->visitor_email ?? 'No email provided' }}</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <span class="px-2 py-1 text-xs rounded-full font-semibold" :class="statusClass" x-text="statusLabel"></span>
                <span class="text-xs text-gray-400">{{ $conversation->created_at->diffForHumans() }}</span>
                {{-- Live indicator --}}
                @if(in_array($conversation->status, ['active', 'waiting']))
                <span class="flex items-center gap-1 text-xs text-green-600">
                    <span class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span> Live
                </span>
                @endif
            </div>
        </div>

        {{-- Messages --}}
        <div id="messages-container" class="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">

            {{-- Server-rendered initial messages --}}
            @forelse($conversation->messages as $message)
                @if($message->isSystemMessage())
                    <div class="text-center">
                        <span class="text-xs text-gray-400 bg-white px-3 py-1 rounded-full border border-gray-200">
                            {{ $message->message }}
                        </span>
                    </div>
                @else
                    <div class="flex {{ $message->isFromAgent() ? 'justify-end' : 'justify-start' }}">
                        @if($message->isFromVisitor())
                            <div class="w-7 h-7 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 text-xs font-semibold mr-2 flex-shrink-0 mt-1">
                                {{ strtoupper(substr($conversation->visitor_name ?? 'G', 0, 1)) }}
                            </div>
                        @endif
                        <div class="max-w-[70%]">
                            @if($message->is_internal)
                                <div class="text-xs text-yellow-600 mb-1 flex items-center gap-1">
                                    <i class="fas fa-lock"></i> Internal Note
                                </div>
                            @endif
                            <div class="{{ $message->bubble_classes }}">
                                <p class="text-sm leading-relaxed">{{ $message->message }}</p>
                            </div>
                            <div class="text-xs text-gray-400 mt-1 {{ $message->isFromAgent() ? 'text-right' : '' }}">
                                {{ $message->sender_display_name }} • {{ $message->created_at->format('H:i') }}
                            </div>
                        </div>
                        @if($message->isFromAgent())
                            <div class="w-7 h-7 rounded-full bg-[#1a4731] flex items-center justify-center text-white text-xs font-semibold ml-2 flex-shrink-0 mt-1">
                                {{ strtoupper(substr($message->sender_display_name, 0, 1)) }}
                            </div>
                        @endif
                    </div>
                @endif
            @empty
                <div class="text-center py-12 text-gray-500">
                    <i class="fas fa-comments text-4xl mb-3 block opacity-40"></i>
                    <p class="text-sm">No messages yet</p>
                </div>
            @endforelse

            {{-- New messages injected by Alpine polling --}}
            <template x-for="msg in newMessages" :key="msg.id">
                <div>
                    {{-- System --}}
                    <div x-show="msg.is_system" class="text-center">
                        <span class="text-xs text-gray-400 bg-white px-3 py-1 rounded-full border border-gray-200"
                              x-text="msg.message"></span>
                    </div>
                    {{-- Agent --}}
                    <div x-show="!msg.is_system && msg.sender_type === 'agent'" class="flex justify-end">
                        <div class="max-w-[70%]">
                            <template x-if="msg.is_internal">
                                <div class="text-xs text-yellow-600 mb-1 flex items-center gap-1">
                                    <i class="fas fa-lock"></i> Internal Note
                                </div>
                            </template>
                            <div :class="msg.is_internal
                                    ? 'px-4 py-2.5 rounded-2xl text-sm leading-relaxed bg-yellow-50 border border-yellow-200 text-yellow-800'
                                    : 'px-4 py-2.5 rounded-2xl text-sm leading-relaxed bg-white border border-gray-200 text-gray-800 rounded-bl-sm'"
                                 x-text="msg.message"></div>
                            <div class="text-xs text-gray-400 mt-1 text-right">
                                <span x-text="msg.sender_name"></span> • <span x-text="msg.time"></span>
                            </div>
                        </div>
                        <div class="w-7 h-7 rounded-full bg-[#1a4731] flex items-center justify-center text-white text-xs font-semibold ml-2 flex-shrink-0 mt-1"
                             x-text="msg.sender_name.charAt(0).toUpperCase()"></div>
                    </div>
                    {{-- Visitor --}}
                    <div x-show="!msg.is_system && msg.sender_type === 'visitor'" class="flex justify-start">
                        <div class="w-7 h-7 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 text-xs font-semibold mr-2 flex-shrink-0 mt-1">
                            {{ strtoupper(substr($conversation->visitor_name ?? 'G', 0, 1)) }}
                        </div>
                        <div class="max-w-[70%]">
                            <div class="px-4 py-2.5 rounded-2xl text-sm leading-relaxed bg-[#1a4731] text-white rounded-br-sm"
                                 x-text="msg.message"></div>
                            <div class="text-xs text-gray-400 mt-1">
                                <span x-text="msg.sender_name"></span> • <span x-text="msg.time"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </template>

            {{-- Scroll anchor --}}
            <div id="scroll-anchor"></div>
        </div>

        {{-- Reply Form --}}
        <div x-show="conversationStatus === 'active' || conversationStatus === 'waiting'"
             class="p-4 border-t border-gray-200 bg-white flex-shrink-0">
            <form action="{{ route('chat.conversation.message', $conversation) }}" method="POST" id="reply-form">
                @csrf
                <div class="flex gap-2 items-end">
                    <div class="flex-1">
                        <textarea name="message" rows="2" id="message-input"
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 resize-none"
                            placeholder="Type your message… (Enter to send, Shift+Enter for new line)"
                            required></textarea>
                    </div>
                    <div class="flex flex-col gap-2">
                        <button type="submit"
                            class="px-4 py-2 bg-[#1a4731] text-white rounded-lg text-sm hover:bg-[#276749] transition flex items-center gap-1">
                            <i class="fas fa-paper-plane"></i> Send
                        </button>
                    </div>
                </div>
                <div class="mt-2 flex items-center gap-3">
                    <label class="flex items-center gap-2 cursor-pointer text-xs text-gray-500">
                        <input type="checkbox" name="is_internal" value="1"
                            class="rounded border-gray-300 text-yellow-500 focus:ring-yellow-500">
                        <i class="fas fa-lock text-yellow-500"></i> Internal note (not visible to visitor)
                    </label>
                </div>
            </form>
        </div>

        <div x-show="conversationStatus !== 'active' && conversationStatus !== 'waiting'"
             class="p-4 border-t border-gray-200 bg-gray-50 text-center text-gray-500 text-sm flex-shrink-0">
            <i class="fas fa-lock mr-2"></i>This conversation has ended.
        </div>
    </div>

    {{-- Sidebar --}}
    <div class="w-72 flex-shrink-0 overflow-y-auto bg-white">

        {{-- Conversation Info --}}
        <div class="p-4 border-b border-gray-200">
            <h4 class="font-semibold text-gray-800 text-sm mb-3">Conversation Info</h4>
            <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                    <span class="text-gray-500">Status</span>
                    <span class="font-medium capitalize" x-text="statusLabel"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Category</span>
                    <span class="font-medium text-gray-800">{{ $conversation->category->name ?? 'General' }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Started</span>
                    <span class="font-medium text-gray-800">{{ $conversation->created_at->format('M d, H:i') }}</span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Messages</span>
                    <span class="font-medium text-gray-800">{{ $conversation->message_count }}</span>
                </div>
                @if($conversation->agent)
                    <div class="flex justify-between">
                        <span class="text-gray-500">Agent</span>
                        <span class="font-medium text-gray-800">{{ $conversation->agent->name }}</span>
                    </div>
                @endif
                @if($conversation->wait_time > 0)
                    <div class="flex justify-between">
                        <span class="text-gray-500">Wait Time</span>
                        <span class="font-medium text-gray-800">{{ $conversation->formatted_wait_time }}</span>
                    </div>
                @endif
            </div>
        </div>

        {{-- Visitor Details --}}
        <div class="p-4 border-b border-gray-200">
            <h4 class="font-semibold text-gray-800 text-sm mb-3">Visitor Details</h4>
            <div class="space-y-2 text-sm">
                <div>
                    <span class="text-gray-500 text-xs">Name</span>
                    <p class="font-medium text-gray-800">{{ $conversation->visitor_name ?? 'Not provided' }}</p>
                </div>
                <div>
                    <span class="text-gray-500 text-xs">Email</span>
                    <p class="font-medium text-gray-800">{{ $conversation->visitor_email ?? 'Not provided' }}</p>
                </div>
                @if($conversation->visitor_phone)
                    <div>
                        <span class="text-gray-500 text-xs">Phone</span>
                        <p class="font-medium text-gray-800">{{ $conversation->visitor_phone }}</p>
                    </div>
                @endif
            </div>
        </div>

        {{-- Actions --}}
        <div x-show="conversationStatus === 'active' || conversationStatus === 'waiting'"
             class="p-4 space-y-3">
            <h4 class="font-semibold text-gray-800 text-sm">Actions</h4>
            <form action="{{ route('chat.conversation.end', $conversation) }}" method="POST">
                @csrf
                <button type="submit"
                    class="w-full px-3 py-2 bg-red-600 text-white rounded-lg text-sm hover:bg-red-700 transition flex items-center justify-center gap-2"
                    onclick="return confirm('End this conversation?')">
                    <i class="fas fa-stop-circle"></i> End Chat
                </button>
            </form>
        </div>

        {{-- Satisfaction Rating --}}
        @if($conversation->satisfaction_rating)
            <div class="p-4 border-t border-gray-200">
                <h4 class="font-semibold text-gray-800 text-sm mb-2">Visitor Rating</h4>
                <div class="flex items-center gap-1">
                    @for($i = 1; $i <= 5; $i++)
                        <i class="fas fa-star {{ $i <= $conversation->satisfaction_rating ? 'text-yellow-400' : 'text-gray-300' }}"></i>
                    @endfor
                    <span class="text-sm text-gray-600 ml-1">{{ $conversation->satisfaction_rating }}/5</span>
                </div>
                @if($conversation->satisfaction_comment)
                    <p class="text-xs text-gray-500 mt-2 italic">"{{ $conversation->satisfaction_comment }}"</p>
                @endif
            </div>
        @endif
    </div>
</div>

@push('scripts')
<script>
Alpine.data('agentChatSession', (conversationId, lastId, initialStatus) => ({
    newMessages:        [],
    lastMessageId:      lastId,
    conversationStatus: initialStatus,
    pollTimer:          null,

    get statusLabel() {
        const labels = { active: 'Active', waiting: 'Waiting', resolved: 'Resolved', closed: 'Closed', missed: 'Missed' };
        return labels[this.conversationStatus] ?? this.conversationStatus;
    },

    get statusClass() {
        const classes = {
            active:   'bg-green-100 text-green-700',
            waiting:  'bg-yellow-100 text-yellow-700',
            resolved: 'bg-blue-100 text-blue-700',
            closed:   'bg-gray-100 text-gray-700',
            missed:   'bg-red-100 text-red-700',
        };
        return classes[this.conversationStatus] ?? 'bg-gray-100 text-gray-700';
    },

    init() {
        this.scrollToBottom();
        if (this.conversationStatus === 'active' || this.conversationStatus === 'waiting') {
            this.startPolling();
        }
    },

    startPolling() {
        this.pollTimer = setInterval(() => this.poll(), 3000);
    },

    stopPolling() {
        if (this.pollTimer) clearInterval(this.pollTimer);
    },

    async poll() {
        try {
            const res = await fetch(`/chat/conversations/${conversationId}/poll?since=${this.lastMessageId}`, {
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                }
            });
            if (!res.ok) return;
            const data = await res.json();

            if (data.messages && data.messages.length > 0) {
                this.newMessages.push(...data.messages);
                this.lastMessageId = data.messages[data.messages.length - 1].id;
                this.$nextTick(() => this.scrollToBottom());
            }

            if (data.status !== this.conversationStatus) {
                this.conversationStatus = data.status;
                if (data.status !== 'active' && data.status !== 'waiting') {
                    this.stopPolling();
                }
            }
        } catch (e) {
            // Network error — retry next tick
        }
    },

    scrollToBottom() {
        const anchor = document.getElementById('scroll-anchor');
        if (anchor) anchor.scrollIntoView({ behavior: 'smooth' });
    },
}));

// Enter to send (without Shift)
document.addEventListener('DOMContentLoaded', () => {
    const msgInput = document.getElementById('message-input');
    if (msgInput) {
        msgInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('reply-form').submit();
            }
        });
    }

    // Initial scroll
    const anchor = document.getElementById('scroll-anchor');
    if (anchor) anchor.scrollIntoView();
});
</script>
@endpush
</x-app-layout>
