@extends('layouts.app') {{-- Or your main user-facing layout --}}

@section('title', 'AI Image Studio')
@section('header_title', 'AI Image Studio')

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="mb-8 text-center">
        <h1 class="text-4xl font-bold text-gray-800 dark:text-white">AI Image Studio</h1>
        <p class="mt-2 text-lg text-gray-600 dark:text-gray-300">
            Generate unique images or find the perfect stock photo for your website.
        </p>
    </div>

    @include('webpilotai::user.partials._session_messages')

    <div x-data="{ activeTab: '{{ ($dalleEnabled || count($aiImageModels) > 0) ? 'ai_generate' : ($pexelsEnabled ? 'stock_photos' : '') }}' }" class="bg-white dark:bg-gray-800 shadow-xl rounded-lg p-6 md:p-8">
        <!-- Tabs Navigation -->
        <div class="mb-6 border-b border-gray-200 dark:border-gray-700">
            <nav class="-mb-px flex space-x-8" aria-label="Tabs">
                @if($dalleEnabled || count($aiImageModels) > 0) {{-- Check if any AI image model is enabled --}}
                <button @click="activeTab = 'ai_generate'"
                        :class="{ 'border-indigo-500 text-indigo-600 dark:text-indigo-400': activeTab === 'ai_generate', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-200 dark:hover:border-gray-600': activeTab !== 'ai_generate' }"
                        class="whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm focus:outline-none">
                    AI Image Generation
                </button>
                @endif

                @if($pexelsEnabled)
                <button @click="activeTab = 'stock_photos'"
                        :class="{ 'border-indigo-500 text-indigo-600 dark:text-indigo-400': activeTab === 'stock_photos', 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-200 dark:hover:border-gray-600': activeTab !== 'stock_photos' }"
                        class="whitespace-nowrap py-3 px-1 border-b-2 font-medium text-sm focus:outline-none">
                    Stock Photo Library
                </button>
                @endif
            </nav>
        </div>

        <!-- AI Image Generation Tab Content -->
        @if($dalleEnabled || count($aiImageModels) > 0)
        <div x-show="activeTab === 'ai_generate'" x-transition>
            <h3 class="text-xl font-semibold text-gray-800 dark:text-white mb-4">Generate Image with AI</h3>
            <form id="aiImageForm">
                @csrf
                <div class="mb-4">
                    <label for="ai_image_prompt" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Image Prompt <span class="text-red-500">*</span></label>
                    <textarea name="prompt" id="ai_image_prompt" rows="3" required
                              class="mt-1 block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200"
                              placeholder="e.g., A futuristic cityscape at sunset, cyberpunk style"></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    @if(count($aiImageModels) > 0 && $dalleConfig)
                        <div>
                            <label for="ai_image_model" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">AI Model</label>
                            <select name="model" id="ai_image_model"
                                    class="mt-1 block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200">
                                @foreach($aiImageModels as $model)
                                    <option value="{{ $model->id }}" {{ $model->id == $dalleConfig['default_model'] ? 'selected' : '' }}>{{ $model->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label for="ai_image_size" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Image Size</label>
                            <select name="size" id="ai_image_size"
                                    class="mt-1 block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200">
                                {{-- Options will be populated by JS based on selected model --}}
                            </select>
                        </div>
                        <div id="dalle3_options" class="{{ $dalleConfig['default_model'] === 'dall-e-3' ? '' : 'hidden' }} md:col-span-2 grid grid-cols-1 md:grid-cols-2 gap-4">
                             <div>
                                <label for="ai_image_quality" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Quality (DALL-E 3)</label>
                                <select name="quality" id="ai_image_quality"
                                        class="mt-1 block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200">
                                    <option value="standard" {{ $dalleConfig['default_quality'] === 'standard' ? 'selected' : '' }}>Standard</option>
                                    <option value="hd" {{ $dalleConfig['default_quality'] === 'hd' ? 'selected' : '' }}>HD</option>
                                </select>
                            </div>
                            <div>
                                <label for="ai_image_style" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Style (DALL-E 3)</label>
                                <select name="style" id="ai_image_style"
                                        class="mt-1 block w-full py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200">
                                    <option value="vivid" {{ $dalleConfig['default_style'] === 'vivid' ? 'selected' : '' }}>Vivid</option>
                                    <option value="natural" {{ $dalleConfig['default_style'] === 'natural' ? 'selected' : '' }}>Natural</option>
                                </select>
                            </div>
                        </div>
                    @else
                        <p class="text-gray-500 dark:text-gray-400 md:col-span-2">AI Image models are not configured.</p>
                    @endif
                </div>

                <button type="submit" id="generateImageButton"
                        @if(!$dalleEnabled && count($aiImageModels) == 0) disabled @endif
                        class="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800 disabled:opacity-50">
                    <svg id="aiImageSpinner" class="animate-spin -ml-1 mr-3 h-5 w-5 text-white hidden" 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>
                    <span id="aiImageButtonText">Generate Image</span>
                </button>
            </form>
            <div id="aiImageErrorAlert" class="hidden p-4 my-4 text-sm text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">
                <span class="font-medium">Error!</span> <span id="aiImageErrorMessage"></span>
            </div>
            <div id="aiImageResult" class="mt-6 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                <p class="text-center text-gray-500 dark:text-gray-400 col-span-full">Generated images will appear here.</p>
            </div>
        </div>
        @endif

        <!-- Stock Photo Library Tab Content -->
        @if($pexelsEnabled)
        <div x-show="activeTab === 'stock_photos'" x-transition>
            <h3 class="text-xl font-semibold text-gray-800 dark:text-white mb-4">Search Stock Photos (Pexels)</h3>
             <form id="stockPhotoForm">
                @csrf
                <div class="flex mb-4">
                    <input type="text" name="query" id="stock_photo_query" required
                           class="flex-grow py-2 px-3 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 rounded-l-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm dark:text-gray-200"
                           placeholder="e.g., Nature, Business, Technology">
                    <button type="submit" id="searchStockButton"
                            class="inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-r-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800">
                        <svg id="stockPhotoSpinner" class="animate-spin -ml-1 mr-3 h-5 w-5 text-white hidden" 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>
                        <span id="searchStockButtonText">Search</span>
                    </button>
                </div>
            </form>
            <div id="stockPhotoErrorAlert" class="hidden p-4 my-4 text-sm text-red-700 bg-red-100 rounded-lg dark:bg-red-200 dark:text-red-800" role="alert">
                <span class="font-medium">Error!</span> <span id="stockPhotoErrorMessage"></span>
            </div>
            <div id="stockPhotoResults" class="mt-6 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                <p class="text-center text-gray-500 dark:text-gray-400 col-span-full">Search results will appear here.</p>
            </div>
            <div id="stockPagination" class="mt-6 flex justify-center">
                {{-- Pagination controls will be added here by JS --}}
            </div>
        </div>
        @endif

        @if(!$dalleEnabled && count($aiImageModels) == 0 && !$pexelsEnabled)
            <p class="text-center text-gray-600 dark:text-gray-400">The AI Image Studio is not currently configured. Please contact an administrator.</p>
        @endif
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    // --- AI Image Generation ---
    const aiImageForm = document.getElementById('aiImageForm');
    const generateImageButton = document.getElementById('generateImageButton');
    const aiImageButtonText = document.getElementById('aiImageButtonText');
    const aiImageSpinner = document.getElementById('aiImageSpinner');
    const aiImageResultDiv = document.getElementById('aiImageResult');
    const aiImageErrorAlert = document.getElementById('aiImageErrorAlert');
    const aiImageErrorMessage = document.getElementById('aiImageErrorMessage');
    const aiImageModelSelect = document.getElementById('ai_image_model');
    const aiImageSizeSelect = document.getElementById('ai_image_size');
    const dalle3OptionsDiv = document.getElementById('dalle3_options');

    const dalleSizes = {
        'dall-e-3': ['1024x1024', '1792x1024', '1024x1792'],
        'dall-e-2': ['256x256', '512x512', '1024x1024']
    };
    const dalleDefaultSizes = @json($dalleConfig['default_size'] ?? '1024x1024');

    function updateImageSizeOptions() {
        if (!aiImageModelSelect || !aiImageSizeSelect) return;
        const selectedModel = aiImageModelSelect.value;
        aiImageSizeSelect.innerHTML = ''; // Clear existing options

        const sizes = dalleSizes[selectedModel] || [];
        let defaultSizeForModel = dalleDefaultSizes; // Use overall default as fallback

        // Attempt to find a suitable default size for the selected model
        if (selectedModel === 'dall-e-3' && !dalleSizes['dall-e-3'].includes(defaultSizeForModel)) {
            defaultSizeForModel = '1024x1024'; // Fallback for DALL-E 3
        } else if (selectedModel === 'dall-e-2' && !dalleSizes['dall-e-2'].includes(defaultSizeForModel)) {
            defaultSizeForModel = '1024x1024'; // Fallback for DALL-E 2
        }


        sizes.forEach(size => {
            const option = document.createElement('option');
            option.value = size;
            option.textContent = size;
            if (size === defaultSizeForModel) {
                option.selected = true;
            }
            aiImageSizeSelect.appendChild(option);
        });

        if (dalle3OptionsDiv) {
            dalle3OptionsDiv.classList.toggle('hidden', selectedModel !== 'dall-e-3');
        }
    }

    if (aiImageModelSelect) {
        aiImageModelSelect.addEventListener('change', updateImageSizeOptions);
        updateImageSizeOptions(); // Initial population
    }

    if (aiImageForm && generateImageButton) {
        aiImageForm.addEventListener('submit', function(e) {
            e.preventDefault();
            generateImageButton.disabled = true;
            aiImageSpinner.classList.remove('hidden');
            aiImageButtonText.textContent = 'Generating...';
            aiImageResultDiv.innerHTML = '<p class="text-center text-gray-500 dark:text-gray-400 col-span-full">Generating image, please wait...</p>';
            aiImageErrorAlert.classList.add('hidden');

            const formData = new FormData(aiImageForm);

            fetch('{{ route("frontend.webpilotai.imagestudio.generate") }}', {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                aiImageResultDiv.innerHTML = ''; // Clear previous results or placeholder
                if (data.success && data.images && data.images.length > 0) {
                    data.images.forEach(image => {
                        const imgContainer = document.createElement('div');
                        imgContainer.classList.add('relative', 'group', 'border', 'dark:border-gray-700', 'rounded-md', 'overflow-hidden', 'shadow-lg');
                        
                        const imgElement = document.createElement('img');
                        imgElement.src = image.url;
                        imgElement.alt = image.prompt || 'AI Generated Image';
                        imgElement.classList.add('w-full', 'h-auto', 'object-contain', 'aspect-square'); // Added aspect-square
                        
                        const overlay = document.createElement('div');
                        overlay.classList.add('absolute', 'inset-0', 'bg-black', 'bg-opacity-0', 'group-hover:bg-opacity-50', 'transition-opacity', 'duration-300', 'flex', 'items-center', 'justify-center', 'p-2', 'opacity-0', 'group-hover:opacity-100');
                        
                        const downloadButton = document.createElement('a');
                        downloadButton.href = image.url;
                        downloadButton.target = '_blank'; 
                        downloadButton.download = `webpilotai_image_${Date.now()}.png`; 
                        downloadButton.classList.add('text-white', 'bg-indigo-600', 'hover:bg-indigo-700', 'px-3', 'py-1.5', 'rounded-md', 'text-xs', 'font-medium', 'inline-flex', 'items-center');
                        downloadButton.innerHTML = '<i class="fas fa-download mr-1.5"></i> Download';
                        
                        overlay.appendChild(downloadButton);
                        imgContainer.appendChild(imgElement);
                        imgContainer.appendChild(overlay);
                        aiImageResultDiv.appendChild(imgContainer);
                    });
                } else {
                    aiImageErrorMessage.textContent = data.error || 'An unknown error occurred while generating the image.';
                    aiImageErrorAlert.classList.remove('hidden');
                    aiImageResultDiv.innerHTML = '<p class="text-center text-red-500 dark:text-red-400 col-span-full">Image generation failed.</p>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                aiImageResultDiv.innerHTML = '';
                aiImageErrorMessage.textContent = 'A network or server error occurred. Please try again.';
                aiImageErrorAlert.classList.remove('hidden');
            })
            .finally(() => {
                generateImageButton.disabled = false;
                aiImageSpinner.classList.add('hidden');
                aiImageButtonText.textContent = 'Generate Image';
            });
        });
    }

    // --- Stock Photo Search ---
    const stockPhotoForm = document.getElementById('stockPhotoForm');
    const searchStockButton = document.getElementById('searchStockButton');
    const searchStockButtonText = document.getElementById('searchStockButtonText');
    const stockPhotoSpinner = document.getElementById('stockPhotoSpinner');
    const stockPhotoResultsDiv = document.getElementById('stockPhotoResults');
    const stockPhotoErrorAlert = document.getElementById('stockPhotoErrorAlert');
    const stockPhotoErrorMessage = document.getElementById('stockPhotoErrorMessage');
    const stockPaginationDiv = document.getElementById('stockPagination');
    let currentStockPage = 1;
    let currentStockQuery = '';

    function fetchStockPhotos(query, page = 1) {
        if (!searchStockButton) return;
        searchStockButton.disabled = true;
        stockPhotoSpinner.classList.remove('hidden');
        searchStockButtonText.textContent = 'Searching...';
        if (page === 1) { // Only show placeholder on initial search for a new query
            stockPhotoResultsDiv.innerHTML = '<p class="text-center text-gray-500 dark:text-gray-400 col-span-full">Searching for stock photos...</p>';
        }
        stockPhotoErrorAlert.classList.add('hidden');
        currentStockQuery = query; // Store current query for pagination

        const formData = new FormData();
        formData.append('query', query);
        formData.append('page', page);
        formData.append('per_page', 12); // Or make this configurable

        fetch('{{ route("frontend.webpilotai.imagestudio.searchstock") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (page === 1) {
                stockPhotoResultsDiv.innerHTML = ''; // Clear for new search
            }
            if (data.success && data.images) {
                if (data.images.length === 0 && page === 1) {
                    stockPhotoResultsDiv.innerHTML = '<p class="text-center text-gray-500 dark:text-gray-400 col-span-full">No images found for your query.</p>';
                }
                data.images.forEach(image => {
                    const imgContainer = document.createElement('div');
                    imgContainer.classList.add('relative', 'group', 'border', 'dark:border-gray-700', 'rounded-md', 'overflow-hidden', 'shadow-lg');
                    
                    const imgLink = document.createElement('a'); // Link to photographer's page
                    imgLink.href = image.photographer_url;
                    imgLink.target = '_blank';
                    imgLink.rel = 'noopener noreferrer';

                    const imgElement = document.createElement('img');
                    imgElement.src = image.thumbnail_url; // Use thumbnail for grid
                    imgElement.dataset.fullUrl = image.url; // Store full URL for potential modal/download
                    imgElement.alt = image.alt || `Stock photo by ${image.photographer}`;
                    imgElement.classList.add('w-full', 'h-48', 'object-cover', 'cursor-pointer'); // Fixed height for grid consistency
                    
                    imgLink.appendChild(imgElement);

                    const overlay = document.createElement('div');
                    overlay.classList.add('absolute', 'bottom-0', 'left-0', 'right-0', 'bg-black', 'bg-opacity-60', 'p-2', 'text-white', 'text-xs', 'opacity-0', 'group-hover:opacity-100', 'transition-opacity', 'duration-300');
                    
                    const photographerLink = document.createElement('a');
                    photographerLink.href = image.photographer_url;
                    photographerLink.target = '_blank';
                    photographerLink.rel = 'noopener noreferrer';
                    photographerLink.textContent = `By: ${image.photographer}`;
                    photographerLink.classList.add('hover:underline');
                    
                    const downloadButton = document.createElement('a');
                    downloadButton.href = image.url;
                    downloadButton.target = '_blank';
                    downloadButton.download = `pexels_${image.id}_${image.photographer.toLowerCase().replace(/\s+/g, '_')}.jpg`;
                    downloadButton.classList.add('text-indigo-300', 'hover:text-indigo-100', 'float-right', 'ml-2');
                    downloadButton.innerHTML = '<i class="fas fa-download"></i>';
                    downloadButton.title = 'Download Original';

                    overlay.appendChild(photographerLink);
                    overlay.appendChild(downloadButton);
                    
                    imgContainer.appendChild(imgLink);
                    imgContainer.appendChild(overlay);
                    stockPhotoResultsDiv.appendChild(imgContainer);
                });
                renderStockPagination(data.total_results, data.page, data.per_page);
            } else {
                stockPhotoErrorMessage.textContent = data.error || 'An unknown error occurred while searching for stock photos.';
                stockPhotoErrorAlert.classList.remove('hidden');
                if (page === 1) {
                    stockPhotoResultsDiv.innerHTML = '<p class="text-center text-red-500 dark:text-red-400 col-span-full">Failed to fetch stock photos.</p>';
                }
            }
        })
        .catch(error => {
            console.error('Stock Photo Error:', error);
            if (page === 1) {
                stockPhotoResultsDiv.innerHTML = '';
            }
            stockPhotoErrorMessage.textContent = 'A network or server error occurred. Please try again.';
            stockPhotoErrorAlert.classList.remove('hidden');
        })
        .finally(() => {
            if (searchStockButton) {
                searchStockButton.disabled = false;
            }
            stockPhotoSpinner.classList.add('hidden');
            if (searchStockButtonText) {
                searchStockButtonText.textContent = 'Search';
            }
        });
    }

    function renderStockPagination(totalResults, currentPage, perPage) {
        stockPaginationDiv.innerHTML = '';
        if (totalResults <= perPage) return;

        const totalPages = Math.ceil(totalResults / perPage);
        currentStockPage = parseInt(currentPage);

        const ul = document.createElement('ul');
        ul.classList.add('flex', 'items-center', '-space-x-px', 'h-8', 'text-sm');

        // Previous Button
        const prevLi = document.createElement('li');
        const prevA = document.createElement('a');
        prevA.href = '#';
        prevA.innerHTML = `<svg class="w-2.5 h-2.5 rtl:rotate-180" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 6 10"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 1 1 5l4 4"/></svg>`;
        prevA.classList.add('flex', 'items-center', 'justify-center', 'px-3', 'h-8', 'ms-0', 'leading-tight', 'text-gray-500', 'bg-white', 'border', 'border-gray-300', 'rounded-s-lg', 'hover:bg-gray-100', 'hover:text-gray-700', 'dark:bg-gray-800', 'dark:border-gray-700', 'dark:text-gray-400', 'dark:hover:bg-gray-700', 'dark:hover:text-white');
        if (currentStockPage === 1) {
            prevA.classList.add('opacity-50', 'cursor-not-allowed');
        } else {
            prevA.addEventListener('click', (e) => { e.preventDefault(); fetchStockPhotos(currentStockQuery, currentStockPage - 1); });
        }
        prevLi.appendChild(prevA);
        ul.appendChild(prevLi);

        // Page Numbers (simplified: first, current, last, with ellipses)
        let pagesToShow = [];
        if (totalPages <= 5) {
            for (let i = 1; i <= totalPages; i++) pagesToShow.push(i);
        } else {
            pagesToShow.push(1);
            if (currentStockPage > 3) pagesToShow.push('...');
            if (currentStockPage > 2) pagesToShow.push(currentStockPage - 1);
            if (currentStockPage !== 1 && currentStockPage !== totalPages) pagesToShow.push(currentStockPage);
            if (currentStockPage < totalPages - 1) pagesToShow.push(currentStockPage + 1);
            if (currentStockPage < totalPages - 2) pagesToShow.push('...');
            pagesToShow.push(totalPages);
        }
        
        // Remove duplicates that might occur from the logic above
        pagesToShow = [...new Set(pagesToShow)];


        pagesToShow.forEach(pageNum => {
            const pageLi = document.createElement('li');
            const pageA = document.createElement('a');
            pageA.href = '#';
            pageA.textContent = pageNum;
            pageA.classList.add('flex', 'items-center', 'justify-center', 'px-3', 'h-8', 'leading-tight', 'text-gray-500', 'bg-white', 'border', 'border-gray-300', 'hover:bg-gray-100', 'hover:text-gray-700', 'dark:bg-gray-800', 'dark:border-gray-700', 'dark:text-gray-400', 'dark:hover:bg-gray-700', 'dark:hover:text-white');
            
            if (pageNum === '...') {
                pageA.classList.add('cursor-default');
            } else if (parseInt(pageNum) === currentStockPage) {
                pageA.classList.remove('bg-white', 'text-gray-500', 'hover:bg-gray-100', 'hover:text-gray-700', 'dark:bg-gray-800', 'dark:text-gray-400', 'dark:hover:bg-gray-700', 'dark:hover:text-white');
                pageA.classList.add('z-10', 'text-blue-600', 'border-blue-300', 'bg-blue-50', 'hover:bg-blue-100', 'hover:text-blue-700', 'dark:border-gray-700', 'dark:bg-gray-700', 'dark:text-white');
                pageA.setAttribute('aria-current', 'page');
            } else {
                pageA.addEventListener('click', (e) => { e.preventDefault(); fetchStockPhotos(currentStockQuery, parseInt(pageNum)); });
            }
            pageLi.appendChild(pageA);
            ul.appendChild(pageLi);
        });


        // Next Button
        const nextLi = document.createElement('li');
        const nextA = document.createElement('a');
        nextA.href = '#';
        nextA.innerHTML = `<svg class="w-2.5 h-2.5 rtl:rotate-180" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 6 10"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 9 4-4-4-4"/></svg>`;
        nextA.classList.add('flex', 'items-center', 'justify-center', 'px-3', 'h-8', 'leading-tight', 'text-gray-500', 'bg-white', 'border', 'border-gray-300', 'rounded-e-lg', 'hover:bg-gray-100', 'hover:text-gray-700', 'dark:bg-gray-800', 'dark:border-gray-700', 'dark:text-gray-400', 'dark:hover:bg-gray-700', 'dark:hover:text-white');
        if (currentStockPage === totalPages) {
            nextA.classList.add('opacity-50', 'cursor-not-allowed');
        } else {
            nextA.addEventListener('click', (e) => { e.preventDefault(); fetchStockPhotos(currentStockQuery, currentStockPage + 1); });
        }
        nextLi.appendChild(nextA);
        ul.appendChild(nextLi);

        stockPaginationDiv.appendChild(ul);
    }


    if (stockPhotoForm) {
        stockPhotoForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const query = document.getElementById('stock_photo_query').value;
            if (query.trim() === '') return;
            currentStockPage = 1; // Reset page for new search
            fetchStockPhotos(query, currentStockPage);
        });
    }

    // Initialize default tab based on availability
    const firstAvailableTab = '{{ ($dalleEnabled || count($aiImageModels) > 0) ? 'ai_generate' : ($pexelsEnabled ? 'stock_photos' : '') }}';
    if (firstAvailableTab) {
        // This is handled by x-data initial value now.
        // If you needed to programmatically set it:
        // const alpineComponent = document.querySelector('[x-data]');
        // if (alpineComponent && alpineComponent.__x) {
        //     alpineComponent.__x.data.activeTab = firstAvailableTab;
        // }
    }

});
</script>
@endpush
