<x-app-layout>
    <x-slot name="header">
        <h2 class="font-bold text-xl text-slate-800 leading-tight flex items-center gap-2">
            <i class="ph-duotone ph-robot text-indigo-600"></i>
            {{ __('AI Legal Assistant') }}
        </h2>
    </x-slot>

    <div class="h-[calc(100vh-140px)] flex flex-col bg-slate-50 relative">

        <div id="chat-container" class="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">

            <div class="flex justify-start">
                <div class="flex items-end gap-2 max-w-lg">
                    <div class="h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center text-white shrink-0">
                        <i class="ph-bold ph-robot"></i>
                    </div>
                    <div class="bg-white p-4 rounded-2xl rounded-bl-none shadow-sm text-sm text-slate-700 border border-slate-100">
                        <p class="font-bold text-indigo-600 mb-1">Legal Assistant</p>
                        Hello! I am your 24/7 AI assistant. I can help explain legal terms, draft simple emails, or guide you through our portal. How can I help you today?
                        <p class="text-[10px] text-slate-400 mt-2 italic">Disclaimer: I am an AI, not a lawyer. My advice is for informational purposes only.</p>
                    </div>
                </div>
            </div>

            @foreach($messages as $msg)
                @if($msg->role == 'user')
                    <div class="flex justify-end">
                        <div class="bg-indigo-600 text-white p-3 rounded-2xl rounded-br-none shadow-md text-sm max-w-md">
                            {{ $msg->content }}
                        </div>
                    </div>
                @else
                    <div class="flex justify-start">
                        <div class="flex items-end gap-2 max-w-lg">
                            <div class="h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center text-white shrink-0">
                                <i class="ph-bold ph-robot"></i>
                            </div>
                            <div class="bg-white p-4 rounded-2xl rounded-bl-none shadow-sm text-sm text-slate-700 border border-slate-100">
                                {!! nl2br(e($msg->content)) !!}
                            </div>
                        </div>
                    </div>
                @endif
            @endforeach

            <div id="typing-indicator" class="hidden flex justify-start">
                <div class="flex items-end gap-2">
                    <div class="h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center text-white shrink-0">
                        <i class="ph-bold ph-robot"></i>
                    </div>
                    <div class="bg-white p-3 rounded-2xl rounded-bl-none shadow-sm border border-slate-100 flex gap-1 items-center h-10">
                        <span class="w-2 h-2 bg-slate-400 rounded-full animate-bounce"></span>
                        <span class="w-2 h-2 bg-slate-400 rounded-full animate-bounce delay-75"></span>
                        <span class="w-2 h-2 bg-slate-400 rounded-full animate-bounce delay-150"></span>
                    </div>
                </div>
            </div>

            <div id="scroll-anchor"></div>
        </div>

        <div class="bg-white border-t border-slate-200 p-4">
            <div class="max-w-4xl mx-auto relative">
                <form id="chat-form" class="flex gap-2">
                    @csrf
                    <input type="text" id="user-input"
                        class="w-full bg-slate-50 border-slate-200 rounded-full pl-5 pr-12 py-3 focus:ring-indigo-500 focus:border-indigo-500 shadow-sm"
                        placeholder="Type your legal question here..." autocomplete="off">

                    <button type="submit"
                        class="absolute right-2 top-1.5 bg-indigo-600 hover:bg-indigo-700 text-white p-2 rounded-full transition shadow-md flex items-center justify-center h-9 w-9">
                        <i class="ph-bold ph-paper-plane-right"></i>
                    </button>
                </form>
            </div>
            <p class="text-center text-[10px] text-slate-400 mt-2">
                Messages are secured and private. Not a substitute for professional legal counsel.
            </p>
        </div>

    </div>

    <script>
        const chatContainer = document.getElementById('chat-container');
        const scrollAnchor = document.getElementById('scroll-anchor');
        const form = document.getElementById('chat-form');
        const userInput = document.getElementById('user-input');
        const typingIndicator = document.getElementById('typing-indicator');

        // Scroll to bottom on load
        scrollAnchor.scrollIntoView();

        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            const message = userInput.value.trim();
            if (!message) return;

            // 1. Add User Message to UI
            appendMessage('user', message);
            userInput.value = '';

            // 2. Show Typing Indicator
            typingIndicator.classList.remove('hidden');
            scrollAnchor.scrollIntoView({ behavior: "smooth" });

            // 3. Send to Backend
            try {
                const response = await fetch("{{ route('client.chat.send') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    },
                    body: JSON.stringify({ message: message })
                });

                const data = await response.json();

                // 4. Hide Typing & Add AI Message
                typingIndicator.classList.add('hidden');
                appendMessage('assistant', data.reply);

            } catch (error) {
                typingIndicator.classList.add('hidden');
                appendMessage('assistant', "Sorry, I encountered an error connecting to the server.");
            }
        });

        function appendMessage(role, text) {
            const div = document.createElement('div');

            if (role === 'user') {
                div.className = "flex justify-end";
                div.innerHTML = `
                    <div class="bg-indigo-600 text-white p-3 rounded-2xl rounded-br-none shadow-md text-sm max-w-md animate-fade-in-up">
                        ${text}
                    </div>
                `;
            } else {
                div.className = "flex justify-start";
                // Convert newlines to <br> for AI response
                const formattedText = text.replace(/\n/g, '<br>');
                div.innerHTML = `
                    <div class="flex items-end gap-2 max-w-lg animate-fade-in-up">
                        <div class="h-8 w-8 rounded-full bg-indigo-600 flex items-center justify-center text-white shrink-0">
                            <i class="ph-bold ph-robot"></i>
                        </div>
                        <div class="bg-white p-4 rounded-2xl rounded-bl-none shadow-sm text-sm text-slate-700 border border-slate-100">
                            ${formattedText}
                        </div>
                    </div>
                `;
            }

            // Insert before typing indicator
            chatContainer.insertBefore(div, typingIndicator);
            scrollAnchor.scrollIntoView({ behavior: "smooth" });
        }
    </script>
</x-app-layout>
