<x-admin.layout :title="($conversation->title ?? 'New Conversation').' - AI Chat'">
    <style>
        .ai-visual-content {
            animation: fadeIn 0.3s ease-in-out;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .ai-product-card:hover,
        .ai-deal-card:hover,
        .ai-category-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
    </style>
    <div class="grid grid-cols-1 lg:grid-cols-6 gap-6">
        <!-- Chat Interface (Full Width) -->
        <div class="lg:col-span-6">
            <!-- Conversation Header -->
            <div class="mb-4 flex flex-wrap items-center justify-between gap-4 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 px-4 py-3">
                <div class="flex items-center gap-6">
                    <a href="{{ route('admin.ai-chat.index') }}" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                    </a>
                    <div>
                        <h1 class="text-lg font-semibold text-gray-900 dark:text-white">
                            {{ $conversation->title ?? 'Untitled Conversation' }}
                        </h1>
                        <p class="text-xs text-gray-500 dark:text-gray-400">
                            {{ $conversation->created_at->format('M d, Y H:i') }}
                            <span class="mx-1">•</span>
                            {{ $messages->count() }} messages
                            <span class="mx-1">•</span>
                            {{ $conversation->last_message_at?->diffForHumans() ?? 'Never' }}
                        </p>
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <form action="{{ route('admin.ai-chat.delete', $conversation->ulid) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this conversation?');">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 text-sm font-medium">
                            Delete
                        </button>
                    </form>
                </div>
            </div>

            <x-admin.card>
                <div class="flex flex-col h-[calc(100vh-200px)] min-h-[500px]">
                    <!-- Messages Container -->
                    <div id="messages-container" class="flex-1 overflow-y-auto space-y-4 p-4 bg-gray-50 dark:bg-gray-900 rounded-lg">
                        @forelse($messages as $message)
                            <div class="flex {{ $message->role === 'user' ? 'justify-end' : 'justify-start' }}">
                                <div class="max-w-[80%] rounded-lg px-4 py-3 {{ $message->role === 'user' ? 'bg-blue-600 text-white' : 'bg-white dark:bg-gray-800 text-gray-900 dark:text-white border border-gray-200 dark:border-gray-700' }}">
                                    <div class="flex items-center gap-2 mb-2">
                                        <span class="text-xs font-semibold {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-500 dark:text-gray-400' }}">
                                            {{ $message->role === 'user' ? 'You' : 'AI Assistant' }}
                                        </span>
                                        <span class="text-xs {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-400' }}">
                                            {{ $message->created_at->format('H:i') }}
                                        </span>
                                    </div>
                                    <div class="text-sm prose prose-sm dark:prose-invert max-w-none ai-markdown-content">
                                        {!! \App\Services\AiAssistant\MarkdownRenderer::render(e($message->content)) !!}
                                    </div>

                                    @if($message->visual_content)
                                        <div class="mt-3 ai-visual-content">
                                            @php
                                                $visualData = json_decode($message->visual_content, true);
                                                if ($visualData && is_array($visualData)) {
                                                    foreach ($visualData as $item) {
                                                        if (isset($item['html'])) {
                                                            echo $item['html'];
                                                        }
                                                    }
                                                }
                                            @endphp
                                        </div>
                                    @endif

                                    @if($message->tool_calls && count($message->tool_calls) > 0)
                                        <div class="mt-2 pt-2 border-t {{ $message->role === 'user' ? 'border-blue-400' : 'border-gray-200 dark:border-gray-700' }}">
                                            <p class="text-xs {{ $message->role === 'user' ? 'text-blue-200' : 'text-gray-500 dark:text-gray-400' }} mb-1">Tools Used:</p>
                                            <div class="flex flex-wrap gap-1">
                                                @foreach($message->tool_calls as $tool)
                                                    <span class="text-xs px-2 py-1 rounded {{ $message->role === 'user' ? 'bg-blue-500' : 'bg-gray-200 dark:bg-gray-700' }} {{ $message->role === 'user' ? 'text-white' : 'text-gray-700 dark:text-gray-300' }}">
                                                        {{ $tool['name'] }}
                                                    </span>
                                                @endforeach
                                            </div>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        @empty
                            <div class="flex items-center justify-center h-full">
                                <div class="text-center text-gray-500 dark:text-gray-400">
                                    <svg class="w-16 h-16 mx-auto mb-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
                                    </svg>
                                    <p>No messages yet. Start the conversation!</p>
                                </div>
                            </div>
                        @endforelse
                    </div>

                    <!-- Message Input -->
                    <div class="mt-4 border-t border-gray-200 dark:border-gray-700 pt-4">
                        <form id="chat-form" action="{{ route('admin.ai-chat.stream', $conversation->ulid) }}" method="POST">
                            @csrf
                            <div class="flex gap-2">
                                <input
                                    type="text"
                                    id="message-input"
                                    name="message"
                                    placeholder="Type your message..."
                                    class="flex-1 rounded-lg border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-white shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                    required
                                    autocomplete="off"
                                >
                                <button
                                    type="submit"
                                    id="send-button"
                                    class="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium py-2 px-6 rounded-lg transition-colors"
                                >
                                    Send
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </x-admin.card>
        </div>
    </div>

    <script>
        // Simple markdown parser for AI responses
        function parseMarkdown(text) {
            // Escape HTML first to prevent XSS
            let html = text
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');

            // Bold: **text** -> <strong>text</strong>
            html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');

            // Italic: *text* -> <em>text</em>
            html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');

            // Code: `code` -> <code>code</code>
            html = html.replace(/`([^`]+)`/g, '<code class="px-1 py-0.5 bg-gray-100 dark:bg-gray-700 rounded text-sm">$1</code>');

            // Links: [text](url) -> <a href="url">text</a>
            html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" class="text-blue-500 hover:text-blue-700 underline" target="_blank">$1</a>');

            // Line breaks
            html = html.replace(/\n/g, '<br>');

            return html;
        }

        // Auto-scroll to bottom of messages
        function scrollToBottom() {
            const container = document.getElementById('messages-container');
            if (container) {
                container.scrollTop = container.scrollHeight;
            }
        }

        // Initial scroll
        scrollToBottom();

        // Handle streaming response
        document.getElementById('chat-form').addEventListener('submit', async (e) => {
            e.preventDefault();

            const form = e.target;
            const input = document.getElementById('message-input');
            const button = document.getElementById('send-button');
            const container = document.getElementById('messages-container');
            const message = input.value.trim();

            if (!message) return;

            // Disable input and button
            input.disabled = true;
            button.disabled = true;
            button.textContent = 'Sending...';

            // Add user message
            const userMessageDiv = document.createElement('div');
            userMessageDiv.className = 'flex justify-end';
            userMessageDiv.innerHTML = `
                <div class="max-w-[80%] rounded-lg px-4 py-3 bg-blue-600 text-white">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs font-semibold text-blue-200">You</span>
                        <span class="text-xs text-blue-200">${new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    <div class="text-sm whitespace-pre-wrap">${message}</div>
                </div>
            `;
            container.appendChild(userMessageDiv);
            scrollToBottom();

            // Create assistant message placeholder
            const assistantMessageDiv = document.createElement('div');
            assistantMessageDiv.className = 'flex justify-start';
            const messageId = 'msg-' + Date.now();
            assistantMessageDiv.innerHTML = `
                <div class="max-w-[80%] rounded-lg px-4 py-3 bg-white dark:bg-gray-800 text-gray-900 dark:text-white border border-gray-200 dark:border-gray-700">
                    <div class="flex items-center gap-2 mb-2">
                        <span class="text-xs font-semibold text-gray-500 dark:text-gray-400">AI Assistant</span>
                        <span class="text-xs text-gray-400">${new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    <div class="text-sm whitespace-pre-wrap" id="${messageId}">
                        <span class="inline-block animate-pulse">Thinking...</span>
                    </div>
                </div>
            `;
            container.appendChild(assistantMessageDiv);
            scrollToBottom();

            // Get reference to content div
            const contentDiv = assistantMessageDiv.querySelector(`#${messageId}`);

            // Clear input
            input.value = '';

            try {
                const response = await fetch(form.action, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'text/event-stream',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    },
                    body: JSON.stringify({ message })
                });

                if (!response.ok) {
                    throw new Error(`Server returned ${response.status}: ${response.statusText}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullContent = '';
                let toolCalls = [];
                let hasReceivedContent = false;

                // Set timeout to detect if AI is not responding
                const timeout = setTimeout(() => {
                    if (!hasReceivedContent) {
                        contentDiv.innerHTML = `<span class="text-yellow-500">AI is taking longer than expected to respond. Please wait or try again.</span>`;
                    }
                }, 30000); // 30 seconds timeout

                // Clear thinking indicator on first content
                contentDiv.innerHTML = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            try {
                                const data = JSON.parse(line.slice(6));

                                if (data.type === 'content') {
                                    hasReceivedContent = true;
                                    clearTimeout(timeout);
                                    fullContent += data.content;
                                    contentDiv.innerHTML = parseMarkdown(fullContent);
                                    scrollToBottom();
                                } else if (data.type === 'tool_call') {
                                    hasReceivedContent = true;
                                    clearTimeout(timeout);
                                    toolCalls.push(data.tool);
                                } else if (data.type === 'tool_html_display') {
                                    // HTML display event - show the visual content
                                    if (data.html) {
                                        const htmlDiv = document.createElement('div');
                                        htmlDiv.className = 'mt-3 ai-visual-content animate-fade-in';
                                        htmlDiv.innerHTML = data.html;
                                        contentDiv.parentElement.appendChild(htmlDiv);
                                        scrollToBottom();
                                    }
                                } else if (data.type === 'done') {
                                    // Show tool calls if any
                                    if (toolCalls.length > 0) {
                                        const toolsDiv = document.createElement('div');
                                        toolsDiv.className = 'mt-2 pt-2 border-t border-gray-200 dark:border-gray-700';
                                        toolsDiv.innerHTML = `
                                            <p class="text-xs text-gray-500 dark:text-gray-400 mb-1">Tools Used:</p>
                                            <div class="flex flex-wrap gap-1">
                                                ${toolCalls.map(tool => `
                                                    <span class="text-xs px-2 py-1 rounded bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                                                        ${tool}
                                                    </span>
                                                `).join('')}
                                            </div>
                                        `;
                                        contentDiv.parentElement.appendChild(toolsDiv);
                                    }
                                } else if (data.type === 'error') {
                                    clearTimeout(timeout);
                                    contentDiv.innerHTML = `<span class="text-red-500">Error: ${data.error}</span>`;
                                }
                            } catch (e) {
                                console.error('Failed to parse SSE data:', e, line);
                            }
                        }
                    }
                }

                clearTimeout(timeout);
            } catch (error) {
                console.error('Stream error:', error);
                contentDiv.innerHTML = `<span class="text-red-500">Error: ${error.message}</span>`;
            } finally {
                // Re-enable input and button
                input.disabled = false;
                button.disabled = false;
                button.textContent = 'Send';
                input.focus();
            }
        });

        // Allow Enter key to submit
        document.getElementById('message-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                document.getElementById('chat-form').dispatchEvent(new Event('submit'));
            }
        });
    </script>
</x-admin.layout>
