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

    <div class="py-12">
        <div class="max-w-4xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900">
                    
                    <header class="w-full mb-8 text-center">
                        <h1 class="text-3xl font-bold tracking-tight text-slate-900 sm:text-4xl">AI Description Generator</h1>
                        <p class="mt-4 text-lg text-slate-600">Enter a product name or a link, and let AI craft the perfect sales copy and hashtags for you.</p>
                    </header>

                    <form id="generator-form">
                        <!-- Input Field -->
                        <div>
                            <label for="product_info" class="block text-sm font-medium text-slate-700">Product Name or Link</label>
                            <input type="text" name="product_info" id="product_info" class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="e.g., WIWU EB302 Lightning Earbuds or www.sampleproduct.com/product01">
                        </div>

                        <!-- Generate Button -->
                        <div class="mt-6">
                            <button type="submit" id="generate-btn" class="w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:bg-indigo-400">
                                Generate Content
                            </button>
                        </div>
                    </form>

                    <div id="error-message" class="mt-4 text-center text-red-600 font-medium"></div>

                    <!-- Output Textareas -->
                    <div id="results" class="mt-8 space-y-6 hidden">
                        <div>
                            <label for="product-description" class="block text-sm font-medium text-slate-700">Generated Product Description (HTML)</label>
                            <textarea id="product-description" rows="15" class="mt-1 block w-full rounded-md border-slate-300 shadow-sm font-mono text-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                        </div>
                        <div>
                            <label for="product-hashtags" class="block text-sm font-medium text-slate-700">Generated Hashtags</label>
                            <textarea id="product-hashtags" rows="2" class="mt-1 block w-full rounded-md border-slate-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const generatorForm = document.getElementById('generator-form');
            const generateBtn = document.getElementById('generate-btn');
            const productInfoInput = document.getElementById('product_info');
            const resultsSection = document.getElementById('results');
            const descriptionTextarea = document.getElementById('product-description');
            const hashtagsTextarea = document.getElementById('product-hashtags');
            const errorMessage = document.getElementById('error-message');
            const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            const baseUrl = "{{ url('/') }}";

            generatorForm.addEventListener('submit', async function (e) {
                e.preventDefault();
                errorMessage.textContent = '';
                resultsSection.classList.add('hidden');
                generateBtn.disabled = true;
                generateBtn.innerHTML = `
                    <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Generating...
                `;

                const productInfo = productInfoInput.value;

                if (!productInfo) {
                    errorMessage.textContent = 'Please enter a product name or keywords.';
                    resetButton();
                    return;
                }

                try {
                    const response = await fetch(`${baseUrl}/generate-description`, {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Content-Type': 'application/json',
                            'Accept': 'application/json',
                        },
                        body: JSON.stringify({ product_info: productInfo })
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || `Server error: ${response.status}`);
                    }

                    const data = await response.json();
                    
                    descriptionTextarea.value = data.description;
                    hashtagsTextarea.value = data.hashtags;
                    resultsSection.classList.remove('hidden');

                } catch (error) {
                    console.error('Generation error:', error);
                    errorMessage.textContent = `Error: ${error.message}`;
                } finally {
                    resetButton();
                }
            });

            function resetButton() {
                generateBtn.disabled = false;
                generateBtn.innerHTML = 'Generate Content';
            }
        });
    </script>
</x-app-layout>
