@extends('layouts.app')

@section('title', 'Edit My Website: ' . ($website->name ?: 'Untitled Website'))
@section('header_title', 'Edit My Website')

@section('content')
<div class="container mx-auto px-4 py-8">
    <div class="max-w-3xl mx-auto bg-white dark:bg-gray-800 shadow-xl rounded-lg p-6 md:p-8">
        <h1 class="text-3xl font-bold text-gray-800 dark:text-white mb-2">Edit: {{ $website->name ?: 'Untitled Website' }}</h1>
        <p class="text-gray-600 dark:text-gray-300 mb-6">Modify your website details below. Checking "Re-generate" will create a new version.</p>

        @include('webpilotai::user.partials._validation_errors')
        @include('webpilotai::user.partials._session_messages') {{-- Use user specific or ensure admin partial is suitable --}}

        <form action="{{ route('frontend.webpilotai.websites.update', $website->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="space-y-6">
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Website Name (Optional)</label>
                    <input type="text" id="name" name="name" value="{{ old('name', $website->name) }}"
                           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">
                </div>

                <div>
                    <label for="description_prompt" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Describe your website needs (The Prompt) <span class="text-red-500">*</span></label>
                    <textarea name="description_prompt" id="description_prompt" rows="8" 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">{{ old('description_prompt', $website->description_prompt) }}</textarea>
                </div>

                {{-- AI Template Selection --}}
                <div class="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <label class="block text-lg font-semibold text-gray-700 dark:text-gray-300 mb-3">Choose an AI Template (Optional)</label>
                    @if($aiTemplates->isEmpty())
                        <p class="text-gray-500 dark:text-gray-400">No AI templates are currently available.</p>
                    @else
                        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4 template-selection-container-user">
                            <label class="template-card-user p-4 border rounded-lg cursor-pointer hover:border-indigo-500 dark:border-gray-600 dark:hover:border-indigo-400 transition-colors">
                                <input type="radio" name="ai_template_id" value="" {{ old('ai_template_id', $website->ai_template_id) == '' ? 'checked' : '' }} class="mr-2">
                                <strong class="block text-md font-medium text-gray-800 dark:text-gray-100 mb-1">No Specific Template</strong>
                                <p class="text-xs text-gray-600 dark:text-gray-400">Use default AI behavior.</p>
                            </label>
                            @foreach($aiTemplates as $template)
                            <label class="template-card-user p-4 border rounded-lg cursor-pointer hover:border-indigo-500 dark:border-gray-600 dark:hover:border-indigo-400 transition-colors">
                                <input type="radio" name="ai_template_id" value="{{ $template->id }}" {{ old('ai_template_id', $website->ai_template_id) == $template->id ? 'checked' : '' }} class="mr-2">
                                @if($template->preview_image_path)
                                    <img src="{{ asset('storage/' . $template->preview_image_path) }}" alt="{{ $template->name }} preview" class="w-full h-24 object-cover rounded mb-2 border dark:border-gray-600">
                                @else
                                    <div class="w-full h-24 flex items-center justify-center bg-gray-100 dark:bg-gray-700 text-gray-400 dark:text-gray-500 rounded mb-2 text-xs">No Preview</div>
                                @endif
                                <strong class="block text-md font-medium text-gray-800 dark:text-gray-100 mb-1">
                                    {{ $template->name }}
                                    @if($template->is_premium)<span class="text-xs text-yellow-500 ml-1">[Premium]</span>@endif
                                </strong>
                                <p class="text-xs text-gray-600 dark:text-gray-400 truncate" title="{{ $template->description }}">{{ Str::limit($template->description, 50) }}</p>
                            </label>
                            @endforeach
                        </div>
                        <small class="block mt-2 text-xs text-gray-500 dark:text-gray-400">This will be applied if you choose to re-generate.</small>
                    @endif
                </div>

                {{-- AI Style Presets Selection --}}
                <div class="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <label class="block text-lg font-semibold text-gray-700 dark:text-gray-300 mb-3">Choose AI Style Presets (Optional)</label>
                    @if($aiStylePresets->isEmpty())
                        <p class="text-gray-500 dark:text-gray-400">No AI style presets are currently available.</p>
                    @else
                        @php
                            $groupedStylePresets = $aiStylePresets->groupBy('type');
                            $currentPresetIds = old('ai_style_preset_ids', $website->aiStylePresets->pluck('id')->toArray());
                        @endphp
                        @foreach($groupedStylePresets as $type => $presets)
                            <fieldset class="mb-4">
                                <legend class="text-md font-semibold text-gray-700 dark:text-gray-300 mb-2">{{ Str::title(str_replace('_', ' ', $type)) }}</legend>
                                <div class="space-y-2">
                                    @foreach($presets as $preset)
                                    <label for="ai_style_preset_{{ $preset->id }}" class="flex items-center text-sm text-gray-700 dark:text-gray-300">
                                        <input type="checkbox" name="ai_style_preset_ids[]" id="ai_style_preset_{{ $preset->id }}" value="{{ $preset->id }}"
                                               {{ (is_array($currentPresetIds) && in_array($preset->id, $currentPresetIds)) ? 'checked' : '' }}
                                               class="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 rounded focus:ring-indigo-500 mr-2">
                                        <span title="{{ $preset->description }}">{{ $preset->name }}</span>
                                        @if($preset->is_premium)<span class="text-xs text-yellow-500 ml-1">[Premium]</span>@endif
                                        @if($preset->preview_image_path)
                                            <img src="{{ asset('storage/' . $preset->preview_image_path) }}" alt="{{ $preset->name }} preview" class="h-5 w-8 object-cover ml-2 border dark:border-gray-600 rounded-sm">
                                        @endif
                                    </label>
                                    @endforeach
                                </div>
                            </fieldset>
                        @endforeach
                        <small class="block mt-2 text-xs text-gray-500 dark:text-gray-400">Changes will be applied if you choose to re-generate.</small>
                    @endif
                </div>

                {{-- Define Website Pages --}}
                <div class="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <label class="block text-lg font-semibold text-gray-700 dark:text-gray-300 mb-1">Define Your Website Pages</label>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">List the pages you want for your website. Changes will apply upon re-generation.</p>
                    <div id="pages-input-container" class="space-y-2">
                        @if(old('pages', $website->pages_structure))
                            @foreach(old('pages', $website->pages_structure) as $index => $page)
                                <div class="flex items-center space-x-2 page-input-group">
                                    <input type="text" name="pages[]" value="{{ is_array($page) ? ($page['name'] ?? '') : $page }}"
                                           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="Page Name (e.g., Our Team)">
                                    <button type="button" class="remove-page-btn text-red-500 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 font-bold text-xl" title="Remove Page">&times;</button>
                                </div>
                            @endforeach
                        @endif
                    </div>
                    <button type="button" id="add-page-btn" class="mt-2 text-sm text-indigo-600 hover:text-indigo-800 dark:text-indigo-400 dark:hover:text-indigo-300 font-medium">
                        + Add Page
                    </button>
                    <small class="block mt-2 text-xs text-gray-500 dark:text-gray-400">If you re-generate, the AI will attempt to create these pages. If not re-generating, this list is just updated for future reference.</small>
                </div>

                {{-- Website Assets --}}
                <div class="p-4 border border-gray-200 dark:border-gray-700 rounded-lg">
                    <label class="block text-lg font-semibold text-gray-700 dark:text-gray-300 mb-1">Website Assets (Images)</label>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mb-3">Manage images for your website. These can be referenced by the AI during generation.</p>

                    @if($website->assets->isNotEmpty())
                        <div class="mb-4">
                            <h4 class="text-md font-semibold text-gray-700 dark:text-gray-300 mb-2">Current Images:</h4>
                            <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
                                @foreach($website->assets as $asset)
                                    <div class="relative border dark:border-gray-600 rounded-md p-2 group">
                                        <img src="{{ asset('storage/' . $asset->path) }}" alt="{{ $asset->original_name }}" class="w-full h-24 object-contain rounded mb-2">
                                        <p class="text-xs text-gray-600 dark:text-gray-400 truncate mb-1" title="{{ $asset->original_name }}">{{ $asset->original_name }}</p>
                                        <input type="text" name="asset_descriptions[{{ $asset->id }}]"
                                               value="{{ old('asset_descriptions.' . $asset->id, $asset->description) }}"
                                               class="mt-1 block w-full py-1 px-2 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-xs dark:text-gray-200"
                                               placeholder="Describe this image (optional)">

                                        <label for="remove_asset_{{ $asset->id }}" class="absolute top-1 right-1 flex items-center text-xs text-red-500 hover:text-red-700 cursor-pointer bg-white dark:bg-gray-700 px-1 rounded opacity-75 group-hover:opacity-100 transition-opacity">
                                            <input type="checkbox" name="remove_assets[]" id="remove_asset_{{ $asset->id }}" value="{{ $asset->id }}" {{ (is_array(old('remove_assets')) && in_array($asset->id, old('remove_assets'))) ? 'checked' : '' }} class="h-3 w-3 text-red-600 border-gray-300 dark:border-gray-500 rounded focus:ring-red-500 mr-1">
                                            Remove
                                        </label>
                                    </div>
                                @endforeach
                            </div>
                        </div>
                    @endif

                    <div>
                        <label for="assets" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Upload New Images</label>
                        <input type="file" name="assets[]" id="assets" multiple accept="image/jpeg,image/png,image/gif,image/webp"
                               class="mt-1 block w-full text-sm text-gray-500 dark:text-gray-300 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 dark:file:bg-indigo-900 file:text-indigo-700 dark:file:text-indigo-300 hover:file:bg-indigo-100 dark:hover:file:bg-indigo-800">
                        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Accepted types: JPG, PNG, GIF, WEBP. Max 5MB per file.</p>
                    </div>
                </div>

                <div>
                    <label for="ai_model_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Choose AI Generation Model <span class="text-red-500">*</span></label>
                    @if($aiModels->isEmpty())
                        <p class="mt-1 text-orange-500">No AI models are currently available. Please contact support.</p>
                    @else
                        <select name="ai_model_id" id="ai_model_id" 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">
                            @foreach($aiModels as $model)
                                <option value="{{ $model->id }}" {{ old('ai_model_id', $website->ai_model_id) == $model->id ? 'selected' : '' }}>
                                    {{ $model->name }} ({{ $model->provider }})
                                    @if(isset($freeTierModelIdentifier) && $model->identifier === $freeTierModelIdentifier && !$model->is_premium) <span class="text-xs text-green-500">[Free Tier]</span> @endif
                                    @if($model->is_premium)<span class="text-xs text-yellow-500 ml-1">[Premium]</span>@endif
                                </option>
                            @endforeach
                        </select>
                    @endif
                </div>

                <div>
                    <label for="regenerate" class="flex items-center">
                        <input type="checkbox" id="regenerate" name="regenerate" value="1" {{ old('regenerate') ? 'checked' : '' }}
                               class="h-4 w-4 text-indigo-600 border-gray-300 dark:border-gray-600 rounded focus:ring-indigo-500 mr-2">
                        <span class="text-sm text-gray-700 dark:text-gray-300">Re-generate website content with these new details</span>
                    </label>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">If checked, the existing generated site will be replaced. If unchecked, only the associations will be updated.</p>
                </div>

                <div class="pt-5">
                    <div class="flex justify-end">
                        <a href="{{ route('frontend.webpilotai.websites.show', $website->id) }}" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-bold py-2 px-4 rounded-lg mr-3 transition duration-150 ease-in-out dark:bg-gray-600 dark:text-gray-200 dark:hover:bg-gray-500">
                            Cancel
                        </a>
                        <button type="submit"
                                class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out {{ $aiModels->isEmpty() ? 'opacity-50 cursor-not-allowed' : '' }}"
                                {{ $aiModels->isEmpty() ? 'disabled' : '' }}>
                            <i class="fas fa-save mr-2"></i> Update Website
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>
@endsection

@push('styles')
<style>
    .template-card-user:has(input[type="radio"]:checked) {
        border-color: #4f46e5; /* indigo-600 */
        box-shadow: 0 0 0 2px rgba(79, 70, 229, .5);
    }
    .template-card-user input[type="radio"]:checked + img + strong,
    .template-card-user input[type="radio"]:checked + div + strong, /* For No Preview */
    .template-card-user input[type="radio"]:checked + strong /* For No Specific Template */ {
        color: #4f46e5; /* indigo-600 */
    }
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const pagesContainer = document.getElementById('pages-input-container');
    const addPageButton = document.getElementById('add-page-btn');

    function createPageInput(pageName = '') {
        const inputDiv = document.createElement('div');
        inputDiv.classList.add('flex', 'items-center', 'space-x-2', 'page-input-group');

        const newInput = document.createElement('input');
        newInput.type = 'text';
        newInput.name = 'pages[]';
        newInput.value = pageName;
        newInput.classList.add('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');
        newInput.placeholder = 'Page Name (e.g., Blog)';

        const removeButton = document.createElement('button');
        removeButton.type = 'button';
        removeButton.title = 'Remove Page';
        removeButton.classList.add('remove-page-btn', 'text-red-500', 'hover:text-red-700', 'dark:text-red-400', 'dark:hover:text-red-300', 'font-bold', 'text-xl');
        removeButton.innerHTML = '&times;';
        removeButton.addEventListener('click', function () {
            inputDiv.remove();
        });

        inputDiv.appendChild(newInput);
        inputDiv.appendChild(removeButton);
        pagesContainer.appendChild(inputDiv);
        if (!pageName) newInput.focus(); // Focus only if it's a new empty field
    }

    addPageButton.addEventListener('click', () => createPageInput());

    // Add event listeners to existing remove buttons (if any were rendered by PHP)
    document.querySelectorAll('.page-input-group .remove-page-btn').forEach(button => {
        button.addEventListener('click', function() {
            this.closest('.page-input-group').remove();
        });
    });
});
</script>
@endpush