<x-app-layout>

    <x-module-hero
        title="Edit Slider"
        :description="Str::limit($slider->title, 60)"
        icon="fa-edit"
    >
        <x-slot name="backButton">
            <a href="{{ route('admin.sliders.index') }}"
               class="inline-flex items-center gap-2 text-[#475569] hover:text-[#1e293b] text-sm transition">
                <i class="fas fa-arrow-left"></i> Back to Sliders
            </a>
        </x-slot>
        <x-slot name="tabs">
            @role('Manager|Super Manager')
            <a href="{{ route('admin.sliders.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.sliders.index') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-list text-sm"></i> All Sliders
            </a>
            <a href="{{ route('admin.sliders.create') }}"
               class="module-hero-tab {{ request()->routeIs('admin.sliders.create') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-plus text-sm"></i> Add Slider
            </a>
            <a href="{{ route('admin.hero-cards.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.hero-cards.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-th-large text-sm"></i> Hero Cards
            </a>
            @endrole
            @can('manage what we do images')
            <a href="{{ route('admin.what-we-do-images.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.what-we-do-images.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-image text-sm"></i> What We Do Images
            </a>
            @endcan
            @can('view pages')
            <a href="{{ route('admin.pages.index') }}"
               class="module-hero-tab {{ request()->routeIs('admin.pages.*') ? 'border-b-2 border-[#1e293b]' : 'opacity-70 hover:opacity-100 transition-opacity' }}
                      inline-flex items-center gap-2 px-4 py-3 text-[#1e293b] text-sm font-medium
                      md:w-auto w-full border-b border-[#cbd5e1] md:border-b-0">
                <i class="fas fa-file-alt text-sm"></i> Pages
            </a>
            @endcan
        </x-slot>
    </x-module-hero>

    <div class="p-6">

        @if($errors->any())
            <div class="mb-6 p-4 bg-red-100 border border-red-400 text-red-700 rounded-lg">
                <div class="flex items-center gap-2 mb-2">
                    <i class="fas fa-exclamation-circle"></i>
                    <strong>Please fix the following errors:</strong>
                </div>
                <ul class="list-disc list-inside space-y-1 text-sm">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('admin.sliders.update', $slider) }}" method="POST" enctype="multipart/form-data"
              x-data="sliderForm()" @submit.prevent="submitForm">
            @csrf
            @method('PUT')

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Form Section -->
                <div class="lg:col-span-2 space-y-6">

                    <!-- Title Section -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                            <i class="fas fa-heading mr-2 text-indigo-600"></i> Slide Title
                        </h3>
                        <div>
                            <label for="title" class="block text-sm font-medium text-gray-700 mb-2">
                                Title <span class="text-red-500">*</span>
                            </label>
                            <input type="text" id="title" name="title" value="{{ old('title', $slider->title) }}"
                                   maxlength="191"
                                   placeholder="e.g. Advancing Digital Health in South Sudan"
                                   class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent @error('title') border-red-400 @enderror"
                                   required>
                            @error('title')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                            <p class="mt-1 text-xs text-gray-500">Maximum 191 characters</p>
                        </div>
                    </div>

                    <!-- Image Upload Section -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                            <i class="fas fa-image mr-2 text-indigo-600"></i> Image Upload
                        </h3>

                        <!-- Upload Mode Selector -->
                        <div class="mb-6">
                            <label class="block text-sm font-medium text-gray-700 mb-3">
                                Choose Upload Method <span class="text-red-500">*</span>
                            </label>
                            <div class="grid grid-cols-2 gap-4">
                                <label class="relative flex items-start p-4 border-2 border-gray-200 rounded-lg cursor-pointer hover:border-indigo-300 transition"
                                       :class="imageSource === 'upload' ? 'border-indigo-500 bg-indigo-50' : ''">
                                    <input type="radio" name="image_source" value="upload" x-model="imageSource"
                                           class="mt-1 w-4 h-4 text-indigo-600 cursor-pointer" required>
                                    <div class="ml-3">
                                        <p class="text-sm font-medium text-gray-900">
                                            <i class="fas fa-cloud-upload-alt mr-2"></i> Direct Upload
                                        </p>
                                        <p class="text-xs text-gray-500 mt-1">Upload image from your device</p>
                                    </div>
                                </label>

                                <label class="relative flex items-start p-4 border-2 border-gray-200 rounded-lg cursor-pointer hover:border-indigo-300 transition"
                                       :class="imageSource === 'url' ? 'border-indigo-500 bg-indigo-50' : ''">
                                    <input type="radio" name="image_source" value="url" x-model="imageSource"
                                           class="mt-1 w-4 h-4 text-indigo-600 cursor-pointer" required>
                                    <div class="ml-3">
                                        <p class="text-sm font-medium text-gray-900">
                                            <i class="fas fa-link mr-2"></i> URL Link
                                        </p>
                                        <p class="text-xs text-gray-500 mt-1">Link to image from web</p>
                                    </div>
                                </label>
                            </div>
                        </div>

                        <!-- File Upload Area (when upload mode is selected) -->
                        <div x-show="imageSource === 'upload'" class="space-y-4">
                            <p class="text-xs text-gray-600 p-3 bg-blue-50 rounded-lg border border-blue-200">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Current:</strong> {{ $slider->isUploadedImage() ? 'Uploaded file (' . $slider->getFormattedFileSize() . ')' : 'No uploaded file' }}
                            </p>

                            <div class="relative">
                                <input type="file" id="image_file" name="image_file" accept="image/*"
                                       @change="handleFileSelect"
                                       class="hidden">

                                <label for="image_file"
                                       class="block cursor-pointer p-8 border-2 border-dashed border-gray-300 rounded-lg hover:border-indigo-500 transition
                                              bg-gradient-to-br from-gray-50 to-gray-100 hover:from-indigo-50 hover:to-indigo-100/50">
                                    <div class="flex flex-col items-center justify-center text-center">
                                        <i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
                                        <p class="text-sm font-medium text-gray-700">
                                            <span class="text-indigo-600">Click to upload</span> or drag and drop
                                        </p>
                                        <p class="text-xs text-gray-500 mt-1">
                                            PNG, JPG, GIF, WebP up to 10MB (Recommended: 1920×400px)
                                        </p>
                                    </div>
                                </label>
                                @error('image_file')<p class="mt-2 text-xs text-red-600">{{ $message }}</p>@enderror
                            </div>

                            <!-- File Info Display -->
                            <div x-show="uploadedFile" class="p-4 bg-green-50 border border-green-200 rounded-lg">
                                <div class="flex items-start justify-between">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-check-circle text-green-600 text-lg"></i>
                                        </div>
                                        <div>
                                            <p class="text-sm font-medium text-gray-800" x-text="uploadedFile?.name"></p>
                                            <p class="text-xs text-gray-500 mt-0.5" x-text="formatFileSize(uploadedFile?.size)"></p>
                                        </div>
                                    </div>
                                    <button type="button" @click="clearUpload"
                                            class="text-red-600 hover:text-red-700 transition">
                                        <i class="fas fa-times text-lg"></i>
                                    </button>
                                </div>
                            </div>
                        </div>

                        <!-- URL Input Area (when URL mode is selected) -->
                        <div x-show="imageSource === 'url'" class="space-y-4">
                            <div>
                                <label for="image_url" class="block text-sm font-medium text-gray-700 mb-2">
                                    Image URL <span class="text-red-500">*</span>
                                </label>
                                <input type="url" id="image_url" name="image_url" value="{{ old('image_url', $slider->image_path) }}"
                                       maxlength="500"
                                       placeholder="https://example.com/image.jpg"
                                       x-model="imageUrl"
                                       @input="previewUrl"
                                       class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent @error('image_url') border-red-400 @enderror"
                                       :required="imageSource === 'url'">
                                @error('image_url')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                                <p class="mt-1 text-xs text-gray-500">Enter the full URL to the image</p>
                            </div>
                        </div>
                    </div>

                    <!-- Status & Order Section -->
                    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                        <h3 class="text-base font-semibold text-gray-800 border-b border-gray-200 pb-3 mb-4">
                            <i class="fas fa-cog mr-2 text-indigo-600"></i> Settings
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <label for="status" class="block text-sm font-medium text-gray-700 mb-2">
                                    Status <span class="text-red-500">*</span>
                                </label>
                                <select id="status" name="status"
                                        class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent @error('status') border-red-400 @enderror"
                                        required>
                                    <option value="draft" {{ old('status', $slider->status) === 'draft' ? 'selected' : '' }}>Draft</option>
                                    <option value="published" {{ old('status', $slider->status) === 'published' ? 'selected' : '' }}>Published</option>
                                    <option value="archived" {{ old('status', $slider->status) === 'archived' ? 'selected' : '' }}>Archived</option>
                                </select>
                                @error('status')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                            </div>

                            <div>
                                <label for="order" class="block text-sm font-medium text-gray-700 mb-2">
                                    Display Order
                                </label>
                                <input type="number" id="order" name="order" value="{{ old('order', $slider->order) }}" min="0"
                                       class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent @error('order') border-red-400 @enderror">
                                @error('order')<p class="mt-1 text-xs text-red-600">{{ $message }}</p>@enderror
                                <p class="mt-1 text-xs text-gray-500">Lower numbers display first</p>
                            </div>
                        </div>
                    </div>

                </div>

                <!-- Preview Section (Sidebar) -->
                <div class="lg:col-span-1">
                    <div class="sticky top-6 bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                        <div class="bg-gradient-to-r from-indigo-600 to-indigo-700 px-6 py-4">
                            <p class="text-white font-semibold flex items-center gap-2">
                                <i class="fas fa-eye"></i> Image Preview
                            </p>
                        </div>

                        <div class="p-6">
                            <!-- Preview Image -->
                            <div class="mb-4">
                                <div class="w-full aspect-video rounded-lg overflow-hidden bg-gray-100 flex items-center justify-center border-2 border-dashed border-gray-300">
                                    <!-- Upload Preview (new file) -->
                                    <img x-show="imageSource === 'upload' && previewData"
                                         :src="previewData"
                                         class="w-full h-full object-cover"
                                         alt="Preview">

                                    <!-- Upload Preview (existing file) -->
                                    <img x-show="imageSource === 'upload' && !previewData && existingImageUrl"
                                         :src="existingImageUrl"
                                         class="w-full h-full object-cover"
                                         alt="Current image">

                                    <!-- URL Preview -->
                                    <img x-show="imageSource === 'url' && imageUrl"
                                         :src="imageUrl"
                                         @error="previewError = true"
                                         @load="previewError = false"
                                         class="w-full h-full object-cover"
                                         alt="Preview"
                                         onerror="this.style.display='none'">

                                    <!-- Placeholder -->
                                    <div x-show="!previewData && !imageUrl && !existingImageUrl"
                                         class="text-center">
                                        <i class="fas fa-image text-4xl text-gray-300 mb-2 block"></i>
                                        <p class="text-sm text-gray-400">Preview will appear here</p>
                                    </div>

                                    <!-- Error State -->
                                    <div x-show="previewError" class="text-center">
                                        <i class="fas fa-exclamation-triangle text-3xl text-red-300 mb-2 block"></i>
                                        <p class="text-xs text-red-500">Image failed to load</p>
                                    </div>
                                </div>
                            </div>

                            <!-- File Details -->
                            <div x-show="uploadedFile" class="space-y-2 text-sm">
                                <div class="flex justify-between py-2 border-b border-gray-200">
                                    <span class="text-gray-600">Size:</span>
                                    <span class="font-medium text-gray-800" x-text="formatFileSize(uploadedFile?.size)"></span>
                                </div>
                                <div class="flex justify-between py-2 border-b border-gray-200">
                                    <span class="text-gray-600">Type:</span>
                                    <span class="font-medium text-gray-800" x-text="uploadedFile?.type?.split('/')[1]?.toUpperCase() || 'Unknown'"></span>
                                </div>
                                <div class="flex justify-between py-2">
                                    <span class="text-gray-600">Dimensions:</span>
                                    <span class="font-medium text-gray-800" x-text="imageDimensions || 'Loading...'"></span>
                                </div>
                            </div>

                            <!-- Info Box -->
                            <div class="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                                <p class="text-xs text-blue-700">
                                    <i class="fas fa-info-circle mr-2"></i>
                                    <strong>Tip:</strong> Recommended image size is 1920×400px for best results.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Form Actions -->
            <div class="mt-6 flex items-center justify-between">
                <form action="{{ route('admin.sliders.destroy', $slider) }}" method="POST"
                      onsubmit="return confirm('Delete this slider? This cannot be undone.')">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn-action-delete">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </form>

                <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <a href="{{ route('admin.sliders.index') }}"
                       class="px-5 py-2.5 bg-gray-100 text-gray-700 font-medium rounded-lg hover:bg-gray-200 transition">
                        <i class="fas fa-times mr-2"></i> Cancel
                    </a>
                    <button type="submit" :disabled="isSubmitting"
                            class="px-5 py-2.5 bg-[#1a4731] text-white font-semibold rounded-lg hover:bg-[#276749] disabled:opacity-50 disabled:cursor-not-allowed transition flex items-center gap-2">
                        <i class="fas fa-save" :class="{ 'fa-spinner fa-spin': isSubmitting, 'fa-save': !isSubmitting }"></i>
                        <span x-text="isSubmitting ? 'Updating...' : 'Update Slider'"></span>
                    </button>
                </div>
            </div>

        </form>

    </div>

    <script>
        function sliderForm() {
            return {
                imageSource: '{{ old('image_source', $slider->image_source) }}',
                imageUrl: '{{ old('image_url', $slider->image_source === 'url' ? $slider->image_path : '') }}',
                uploadedFile: null,
                previewData: null,
                previewError: false,
                imageDimensions: null,
                isSubmitting: false,
                existingImageUrl: '{{ $slider->getImageUrl() }}',

                handleFileSelect(event) {
                    const file = event.target.files[0];
                    if (!file) return;

                    this.uploadedFile = file;

                    // Create preview
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        this.previewData = e.target.result;
                        // Get image dimensions
                        this.getImageDimensions(e.target.result);
                    };
                    reader.readAsDataURL(file);
                },

                getImageDimensions(src) {
                    const img = new Image();
                    img.onload = () => {
                        this.imageDimensions = `${img.width}×${img.height}px`;
                    };
                    img.src = src;
                },

                clearUpload() {
                    this.uploadedFile = null;
                    this.previewData = null;
                    this.imageDimensions = null;
                    document.getElementById('image_file').value = '';
                },

                previewUrl() {
                    // URL preview is handled by the img element's src binding
                },

                formatFileSize(bytes) {
                    if (!bytes) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
                },

                submitForm() {
                    this.isSubmitting = true;
                    // Form will submit naturally
                    document.querySelector('form').submit();
                }
            }
        }
    </script>

</x-app-layout>
