@extends('layouts.site')

@section('title', 'Live Chat — ' . config('app.name'))

@section('content')
{{-- Hero --}}
<div class="shadow-lg" style="background: linear-gradient(to right, #1a4731, #0f2819);">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div class="flex items-center gap-6">
            <div class="hidden md:flex w-20 h-20 rounded-xl shadow-lg bg-white/10 items-center justify-center flex-shrink-0">
                <i class="fas fa-comments text-white text-3xl"></i>
            </div>
            <div>
                <h1 class="text-3xl md:text-4xl font-serif font-bold text-white">Live Chat Session</h1>
                <p class="text-green-200 mt-2">You are connected with our support team.</p>
            </div>
        </div>
    </div>
</div>

{{-- Breadcrumb --}}
<div class="bg-gray-50 border-b border-gray-200">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3">
        <nav class="flex items-center space-x-2 text-sm text-gray-600" aria-label="Breadcrumb">
            <a href="{{ url('/') }}" class="hover:text-green-600 transition flex items-center">
                <i class="fas fa-home mr-1"></i>Home
            </a>
            <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
            <a href="{{ route('chat.public.start') }}" class="hover:text-green-600 transition">Live Chat</a>
            <i class="fas fa-chevron-right text-gray-400 text-xs"></i>
            <span class="text-gray-900 font-medium">Chat Session</span>
        </nav>
    </div>
</div>

<div class="bg-gray-50 py-6 px-4">
    <div class="max-w-5xl mx-auto w-full">

        {{-- Chat Window --}}
        <div id="chat-window"
             class="bg-white rounded-2xl shadow-lg border border-gray-200 overflow-hidden flex flex-col"
             style="height: 600px;"
             x-data="publicChatSession('{{ $conversation->session_id }}', {{ $conversation->messages->last()?->id ?? 0 }}, '{{ $conversation->status }}')">

            {{-- Header --}}
            <div class="px-5 py-4 flex items-center justify-between flex-shrink-0" style="background-color: #1a4731;">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-full bg-white/20 flex items-center justify-center">
                        <i class="fas fa-headset text-white text-sm"></i>
                    </div>
                    <div>
                        <p class="text-white font-semibold text-sm">SSHIA Support</p>
                        <p class="text-green-200 text-xs" x-text="statusText"></p>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <span class="w-2 h-2 rounded-full" :class="statusDot"></span>
                    <span class="text-white/80 text-xs" x-text="statusLabel"></span>
                </div>
            </div>

            {{-- Messages --}}
            <div id="messages" class="flex-1 overflow-y-auto p-4 space-y-3 bg-gray-50">
                {{-- Initial messages rendered server-side --}}
                @forelse($conversation->messages->where('is_internal', false) as $msg)
                    @if($msg->isSystemMessage())
                        <div class="text-center">
                            <span class="text-xs text-gray-400 bg-white px-3 py-1 rounded-full border border-gray-200">
                                {{ $msg->message }}
                            </span>
                        </div>
                    @else
                        <div class="flex {{ $msg->isFromAgent() ? 'justify-start' : 'justify-end' }}">
                            @if($msg->isFromAgent())
                                <div class="w-7 h-7 rounded-full bg-[#1a4731] flex items-center justify-center text-white text-xs font-semibold mr-2 flex-shrink-0 mt-1">
                                    <i class="fas fa-headset text-xs"></i>
                                </div>
                            @endif
                            <div class="max-w-[75%]">
                                <div class="px-4 py-2.5 rounded-2xl text-sm leading-relaxed
                                    {{ $msg->isFromAgent() ? 'bg-white border border-gray-200 text-gray-800 rounded-bl-sm' : 'text-white rounded-br-sm' }}"
                                    @if(!$msg->isFromAgent()) style="background-color: #1a4731;" @endif>
                                    {{ $msg->message }}
                                </div>
                                <p class="text-xs text-gray-400 mt-1 {{ $msg->isFromAgent() ? '' : 'text-right' }}">
                                    {{ $msg->created_at->format('H:i') }}
                                </p>
                            </div>
                        </div>
                    @endif
                @empty
                    <div class="text-center py-8 text-gray-500">
                        <i class="fas fa-comments text-3xl mb-3 block opacity-40"></i>
                        <p class="text-sm">Your conversation has started. An agent will be with you shortly.</p>
                    </div>
                @endforelse

                {{-- New messages injected by Alpine polling --}}
                <template x-for="msg in newMessages" :key="msg.id">
                    <div>
                        {{-- System message --}}
                        <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 message --}}
                        <div x-show="!msg.is_system && msg.sender_type === 'agent'" class="flex justify-start">
                            <div class="w-7 h-7 rounded-full bg-[#1a4731] flex items-center justify-center text-white text-xs font-semibold mr-2 flex-shrink-0 mt-1">
                                <i class="fas fa-headset text-xs"></i>
                            </div>
                            <div class="max-w-[75%]">
                                <div class="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>
                                <p class="text-xs text-gray-400 mt-1" x-text="msg.time"></p>
                            </div>
                        </div>
                        {{-- Visitor message --}}
                        <div x-show="!msg.is_system && msg.sender_type === 'visitor'" class="flex justify-end">
                            <div class="max-w-[75%]">
                                <div class="px-4 py-2.5 rounded-2xl text-sm leading-relaxed text-white rounded-br-sm"
                                     style="background-color: #1a4731;"
                                     x-text="msg.message"></div>
                                <p class="text-xs text-gray-400 mt-1 text-right" x-text="msg.time"></p>
                            </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.public.message', $conversation->session_id) }}"
                      method="POST" id="chat-form">
                    @csrf
                    <div class="flex gap-2 items-end">
                        <textarea name="message" id="msg-input" rows="2" required
                            placeholder="Type your message..."
                            class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-green-500 resize-none"></textarea>
                        <button type="submit"
                            class="px-4 py-2 text-white rounded-lg text-sm font-medium transition hover:opacity-90 flex-shrink-0"
                            style="background-color: #1a4731;">
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </form>
                <div class="mt-2 flex justify-between items-center">
                    <p class="text-xs text-gray-400">Press Enter to send</p>
                    <form action="{{ route('chat.public.end', $conversation->session_id) }}"
                          method="POST" class="inline">
                        @csrf
                        <button type="submit" class="text-xs text-red-500 hover:text-red-700 transition"
                            onclick="return confirm('End this chat session?')">
                            <i class="fas fa-times mr-1"></i> End Chat
                        </button>
                    </form>
                </div>
            </div>

            {{-- Ended state --}}
            <div x-show="conversationStatus !== 'active' && conversationStatus !== 'waiting'"
                 class="p-4 border-t border-gray-200 bg-gray-50 text-center flex-shrink-0">
                <p class="text-sm text-gray-500 mb-3">This chat session has ended.</p>
                <a href="{{ route('chat.public.start') }}"
                   class="inline-flex items-center gap-2 px-4 py-2 text-white text-sm rounded-lg transition hover:opacity-90"
                   style="background-color: #1a4731;">
                    <i class="fas fa-plus"></i> Start New Chat
                </a>
            </div>
        </div>

        <p class="text-center text-xs text-gray-400 mt-3">
            Session ID: <span class="font-mono">{{ $conversation->session_id }}</span>
        </p>
    </div>
</div>
@endsection

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

    get statusText() {
        if (this.agentName) return this.agentName + ' is helping you';
        if (this.conversationStatus === 'waiting') return 'Waiting for an agent…';
        if (this.conversationStatus === 'active')  return 'Connected';
        return 'Session ended';
    },

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

    get statusDot() {
        const dots = { active: 'bg-green-400', waiting: 'bg-yellow-400', resolved: 'bg-blue-400', closed: 'bg-gray-400', missed: 'bg-red-400' };
        return dots[this.conversationStatus] ?? 'bg-gray-400';
    },

    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/session/${sessionId}/poll?since=${this.lastMessageId}`, {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            });
            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.agent) this.agentName = data.agent;

            if (data.status !== this.conversationStatus) {
                this.conversationStatus = data.status;
                if (data.status !== 'active' && data.status !== 'waiting') {
                    this.stopPolling();
                }
            }
        } catch (e) {
            // Network error — silently 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 input = document.getElementById('msg-input');
    if (input) {
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('chat-form').submit();
            }
        });
    }

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