<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('AI Wellness Assistant') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6">
                    <div id="chat-messages" class="space-y-4 h-96 overflow-y-auto p-4 border rounded dark:border-gray-600">
                    </div>

                    <form id="chat-form" class="mt-4 flex space-x-2">
                        @csrf
                        <input type="text" id="message-input" class="flex-1 rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200" placeholder="Type your message..." required>
                        <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">Send</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @push('scripts')
    <script>
        document.getElementById('chat-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const input = document.getElementById('message-input');
            const message = input.value;
            if (!message) return;

            const messagesDiv = document.getElementById('chat-messages');
            messagesDiv.innerHTML += `<div class="text-right"><span class="inline-block bg-blue-100 dark:bg-blue-900 p-2 rounded">${message}</span></div>`;

            fetch('{{ route('ai.send') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({ message })
            })
            .then(res => res.json())
            .then(data => {
                messagesDiv.innerHTML += `<div class="text-left"><span class="inline-block bg-gray-100 dark:bg-gray-700 p-2 rounded">${data.response}</span></div>`;
                input.value = '';
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            })
            .catch(err => console.error(err));
        });
    </script>
    @endpush
</x-app-layout>
