@extends('layouts.admin')

@section('title', 'Add New Product')

@section('content')
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        var descInput = document.getElementById('description');
        var editorEl = document.getElementById('description-editor');
        if (window.Quill && descInput && editorEl) {
            var quill = new Quill(editorEl, {
                theme: 'snow',
                placeholder: 'Describe your product',
                modules: {
                    toolbar: [
                        [{ header: [false, 2, 3] }],
                        ['bold', 'italic', 'underline'],
                        [{ list: 'ordered' }, { list: 'bullet' }],
                        ['link']
                    ]
                }
            });
            window.descriptionEditor = quill;

            if (descInput.value) {
                quill.root.innerHTML = descInput.value.replace(/\n/g, '<br>');
            }

            var form = document.getElementById('product-form');
            if (form) {
                form.addEventListener('submit', function () {
                    var html = quill.root.innerHTML;
                    var text = html
                        .replace(/<\/p><p>/g, '\n\n')
                        .replace(/<br>/g, '\n')
                        .replace(/<\/?p>/g, '');
                    descInput.value = text.trim();
                });
            }
        }

        var seoTitleInput = document.getElementById('seo_title');
        var seoTitleCounter = document.getElementById('seo_title_counter');
        var seoDescriptionInput = document.getElementById('seo_description');
        var seoDescriptionCounter = document.getElementById('seo_description_counter');

        function updateCounter(input, counter, maxLength) {
            if (!input || !counter) return;
            var length = input.value ? input.value.length : 0;
            counter.textContent = length + ' / ' + maxLength;
        }

        if (seoTitleInput && seoTitleCounter) {
            updateCounter(seoTitleInput, seoTitleCounter, 60);
            seoTitleInput.addEventListener('input', function () {
                updateCounter(seoTitleInput, seoTitleCounter, 60);
            });
        }

        if (seoDescriptionInput && seoDescriptionCounter) {
            updateCounter(seoDescriptionInput, seoDescriptionCounter, 160);
            seoDescriptionInput.addEventListener('input', function () {
                updateCounter(seoDescriptionInput, seoDescriptionCounter, 160);
            });
        }
    });
</script>
<div class="max-w-[1100px] mx-auto">
    <!-- Header Section -->
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-8 mb-12">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 leading-tight">Create product</h1>
            <p class="text-gray-500 text-sm mt-1">Add details, pricing, stock and visibility.</p>
        </div>
        <div class="flex items-center gap-3">
            <a href="{{ route('admin.products.index') }}" class="px-4 py-2.5 bg-white border border-gray-200 rounded-xl text-sm font-medium text-gray-700 hover:text-gray-900 hover:border-gray-300">
                Cancel
            </a>
            <button type="submit" form="product-form" class="flex items-center gap-2 bg-emerald-600 !bg-brand text-white !text-white px-5 py-2.5 rounded-xl text-sm font-medium hover:bg-emerald-700 hover:!bg-brand/90 transition-colors">
                Save
                <i class="fas fa-check text-xs"></i>
            </button>
        </div>
    </div>

    <form action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data" id="product-form" class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        @csrf
        
        <!-- Main Content -->
        <div class="lg:col-span-8 space-y-6">
            <!-- Product Details -->
            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm">
                <div class="flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-brand/10 rounded-xl flex items-center justify-center text-brand">
                            <i class="fas fa-info-circle text-lg"></i>
                        </div>
                        <div>
                            <h3 class="text-sm font-semibold text-gray-900">Product details</h3>
                            <p class="text-xs text-gray-500">Basic information</p>
                        </div>
                    </div>
                    <button
                        type="button"
                        id="ai-prepare-product-btn"
                        class="hidden lg:inline-flex items-center gap-2 px-3.5 py-2 rounded-full text-[11px] font-semibold bg-gray-900 text-white border border-gray-900/90 shadow-md shadow-gray-900/20 hover:bg-black hover:border-black transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400/40">
                        <span class="flex items-center justify-center h-6 w-6 rounded-full bg-gradient-to-tr from-emerald-500 via-brand to-emerald-400 text-white text-[9px] font-black tracking-[0.18em] uppercase shadow-sm shadow-emerald-200/80">
                            AI
                        </span>
                        <div class="flex flex-col items-start leading-none">
                            <span class="label text-[9px] font-semibold tracking-[0.2em] uppercase text-white">AI prepare</span>
                            <span class="text-[8px] font-semibold tracking-[0.18em] uppercase text-emerald-300">Category + description</span>
                        </div>
                    </button>
                </div>
                
                <div class="space-y-6">
                    <div class="space-y-2">
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Product name</label>
                        <input type="text" name="name" id="name" value="{{ old('name') }}" required 
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition"
                            placeholder="Enter product name">
                        @error('name')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="space-y-1.5">
                        <div class="flex items-center justify-between mb-1">
                            <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                            <button type="button"
                                id="ai-generate-description-btn"
                                class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[11px] font-semibold bg-white text-gray-900 border border-gray-200/80 hover:border-emerald-400/80 hover:bg-emerald-50/40 transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-400/40">
                                <span class="flex items-center justify-center h-6 w-6 rounded-full bg-emerald-500 text-white text-[9px] font-black tracking-[0.18em] uppercase shadow-sm shadow-emerald-200/80">
                                    AI
                                </span>
                                <div class="flex flex-col items-start leading-none">
                                    <span class="label text-[9px] font-semibold tracking-[0.2em] uppercase text-gray-900">AI generate</span>
                                    <span class="text-[8px] font-semibold tracking-[0.18em] uppercase text-emerald-500">Autofill description</span>
                                </div>
                            </button>
                        </div>
                        <p class="text-[11px] text-gray-400 mb-2">Let AI draft a professional description using the name, category and image.</p>
                        <textarea name="description" id="description" rows="6" class="hidden">{{ old('description') }}</textarea>
                        <div id="description-editor" class="bg-white border border-gray-300 rounded-lg text-sm text-gray-900 min-h-[180px]"></div>
                        <div class="mt-1 flex flex-col gap-0.5">
                            <p id="ai-generate-status" class="text-[11px] text-gray-400"></p>
                            <p id="ai-prepare-status" class="text-[11px] text-gray-400"></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm">
                <div class="flex items-center gap-3 mb-6">
                    <div class="w-10 h-10 bg-blue-500/10 rounded-xl flex items-center justify-center text-blue-500">
                        <i class="fas fa-tag text-lg"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900">Price & stock</h3>
                        <p class="text-xs text-gray-500">Inventory details</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="price" class="block text-sm font-medium text-gray-700 mb-1">Regular price</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-3 flex items-center text-gray-400">{{ $currencySymbol }}</span>
                            <input type="number" step="0.01" name="price" id="price" value="{{ old('price') }}" required
                                class="w-full pl-8 pr-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition"
                                placeholder="0.00">
                        </div>
                    </div>

                    <div>
                        <label for="discount_price" class="block text-sm font-medium text-gray-700 mb-1">Discount price (optional)</label>
                        <div class="relative">
                            <span class="absolute inset-y-0 left-3 flex items-center text-gray-400">{{ $currencySymbol }}</span>
                            <input type="number" step="0.01" name="discount_price" id="discount_price" value="{{ old('discount_price') }}"
                                class="w-full pl-8 pr-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition"
                                placeholder="0.00">
                        </div>
                    </div>

                    <div>
                        <label for="stock" class="block text-sm font-medium text-gray-700 mb-1">Stock quantity</label>
                        <input type="number" name="stock" id="stock" value="{{ old('stock', 0) }}" required
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition"
                            placeholder="0">
                    </div>

                    <div>
                        <label for="unit" class="block text-sm font-medium text-gray-700 mb-1">Measurement unit</label>
                        <input type="text" name="unit" id="unit" value="{{ old('unit', 'pcs') }}" required
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition"
                            placeholder="e.g. kg, pcs, box">
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm">
                <div class="flex items-center justify-between gap-4 mb-6">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 bg-emerald-500/10 rounded-xl flex items-center justify-center text-emerald-500">
                            <i class="fas fa-search text-lg"></i>
                        </div>
                        <div>
                            <h3 class="text-sm font-semibold text-gray-900">SEO & discovery</h3>
                            <p class="text-xs text-gray-500">Control how this product appears on search engines.</p>
                        </div>
                    </div>
                    <button
                        type="button"
                        id="ai-generate-seo-btn"
                        class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[11px] font-semibold bg-white text-gray-900 border border-gray-200 hover:border-emerald-400/80 hover:bg-emerald-50/40 transition-all duration-150">
                        <span class="flex items-center justify-center h-6 w-6 rounded-full bg-emerald-500 text-white text-[9px] font-black tracking-[0.18em] uppercase shadow-sm shadow-emerald-200/80">
                            AI
                        </span>
                        <div class="flex flex-col items-start leading-none">
                            <span class="label text-[9px] font-semibold tracking-[0.2em] uppercase text-gray-900">AI SEO</span>
                            <span class="text-[8px] font-semibold tracking-[0.18em] uppercase text-emerald-500">Meta title, description, keywords</span>
                        </div>
                    </button>
                </div>

                <div class="space-y-5">
                    <div class="space-y-1.5">
                        <div class="flex items-center justify-between">
                            <label for="seo_title" class="block text-sm font-medium text-gray-700">Meta title</label>
                            <span id="seo_title_counter" class="text-[11px] text-gray-400"></span>
                        </div>
                        <input
                            type="text"
                            name="seo_title"
                            id="seo_title"
                            value="{{ old('seo_title') }}"
                            maxlength="255"
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition text-sm"
                            placeholder="Write a concise, keyword-rich title"
                        >
                        @error('seo_title')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="space-y-1.5">
                        <div class="flex items-center justify-between">
                            <label for="seo_description" class="block text-sm font-medium text-gray-700">Meta description</label>
                            <span id="seo_description_counter" class="text-[11px] text-gray-400"></span>
                        </div>
                        <textarea
                            name="seo_description"
                            id="seo_description"
                            rows="3"
                            maxlength="160"
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition resize-none"
                            placeholder="Short summary that encourages clicks from search engines"
                        >{{ old('seo_description') }}</textarea>
                        @error('seo_description')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="space-y-1.5">
                        <label for="seo_keywords" class="block text-sm font-medium text-gray-700">Meta keywords</label>
                        <input
                            type="text"
                            name="seo_keywords"
                            id="seo_keywords"
                            value="{{ old('seo_keywords') }}"
                            maxlength="255"
                            class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition text-sm"
                            placeholder="grocery, organic vegetables, fresh fruits, daily essentials"
                        >
                        <p class="text-[11px] text-gray-400">Separate keywords with commas to help search engines understand this page.</p>
                        @error('seo_keywords')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <p id="ai-seo-status" class="text-[11px] text-gray-400"></p>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="lg:col-span-4 space-y-6">
            <!-- Categorization -->
            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-10 h-10 bg-purple-500/10 rounded-xl flex items-center justify-center text-purple-500">
                        <i class="fas fa-layer-group text-base"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900">Categorization</h3>
                        <p class="text-xs text-gray-500">Product organization</p>
                    </div>
                </div>

                <div class="space-y-6">
                    <div>
                        <label for="category_id" class="block text-sm font-medium text-gray-700 mb-1">Main category</label>
                        <div class="relative">
                            <select name="category_id" id="category_id" required onchange="loadSubCategories(this.value)"
                                class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 appearance-none focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition cursor-pointer">
                                <option value="">Select category</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                            <i class="fas fa-chevron-down absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"></i>
                        </div>
                    </div>

                    <div>
                        <label for="sub_category_id" class="block text-sm font-medium text-gray-700 mb-1">Sub category</label>
                        <div class="relative">
                            <select name="sub_category_id" id="sub_category_id"
                                class="w-full px-4 py-2.5 bg-white border border-gray-300 rounded-lg text-gray-900 appearance-none focus:outline-none focus:ring-2 focus:ring-brand/40 focus:border-brand/60 transition cursor-pointer disabled:opacity-50">
                                <option value="">Select subcategory</option>
                            </select>
                            <i class="fas fa-chevron-down absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none" id="subcategory-chevron"></i>
                            <i class="fas fa-spinner fa-spin absolute right-8 top-1/2 -translate-y-1/2 text-gray-400 hidden" id="subcategory-loader"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Product Image -->
            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm" x-data="imageUpload()">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-10 h-10 bg-orange-500/10 rounded-xl flex items-center justify-center text-orange-500">
                        <i class="fas fa-image text-base"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900">Product image</h3>
                        <p class="text-xs text-gray-500">Visual signature</p>
                    </div>
                </div>

                <div class="relative">
                    <div class="relative aspect-square rounded-xl border border-dashed border-gray-300 flex flex-col items-center justify-center overflow-hidden bg-white transition-all hover:border-brand/40"
                         :class="{'border-brand/40 bg-brand/5': previewUrl}">
                        
                        <div x-show="!previewUrl" class="text-center p-6">
                            <div class="w-14 h-14 bg-gray-50 rounded-xl flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-cloud-upload-alt text-xl text-gray-300"></i>
                            </div>
                            <p class="text-sm text-gray-700 mb-1">Upload image</p>
                            <p class="text-xs text-gray-500">JPG, PNG or GIF (max 2MB)</p>
                            
                            <label for="image" class="absolute inset-0 cursor-pointer">
                                <input id="image" name="image" type="file" class="sr-only" accept="image/*" @change="handleFileChange">
                            </label>
                        </div>

                        <div x-show="previewUrl" class="w-full h-full p-3" style="display: none;">
                            <div class="relative w-full h-full rounded-lg overflow-hidden bg-gray-50">
                                <img :src="previewUrl" class="w-full h-full object-cover rounded-lg shadow-sm">
                                <div class="absolute inset-x-3 bottom-3 flex items-center justify-end gap-2">
                                    <button type="button" @click="openEditor" class="inline-flex items-center px-3 py-1.5 rounded-full bg-white text-gray-800 text-[10px] font-semibold border border-gray-200 hover:bg-gray-900 hover:text-white hover:border-gray-900 transition-colors shadow-sm">
                                        <i class="fas fa-pen text-[9px] mr-1.5"></i>
                                        Edit image
                                    </button>
                                    <button type="button" @click="removeImage" class="inline-flex items-center px-3 py-1.5 rounded-full bg-white text-red-500 text-[10px] font-semibold border border-red-100 hover:bg-red-500 hover:text-white hover:border-red-500 transition-colors shadow-sm">
                                        <i class="fas fa-trash-alt text-[9px] mr-1.5"></i>
                                        Remove
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div x-show="showEditor" class="fixed inset-0 z-40 flex items-center justify-center bg-black/40 px-4" style="display: none;">
                        <div class="bg-white rounded-2xl shadow-2xl max-w-xl w-full p-4 sm:p-5 relative">
                            <div class="flex items-center justify-between mb-4">
                                <div>
                                    <p class="text-[11px] font-semibold text-gray-400 uppercase tracking-[0.22em]">Image editor</p>
                                    <p class="text-sm font-semibold text-gray-900">Adjust framing & background</p>
                                </div>
                                <button type="button" @click="closeEditor" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-900 hover:text-white transition-colors">
                                    <i class="fas fa-times text-xs"></i>
                                </button>
                            </div>

                            <div class="aspect-square mb-4">
                                <div class="w-full h-full rounded-3xl bg-gradient-to-br from-slate-50 via-slate-100 to-slate-50 border border-gray-200 shadow-sm flex items-center justify-center">
                                    <div class="relative w-[82%] h-[82%] bg-white rounded-2xl shadow-xl flex items-center justify-center overflow-hidden">
                                        <template x-if="previewUrl">
                                            <img
                                                :src="previewUrl"
                                                class="max-w-full max-h-full"
                                                :style="'transform: scale(' + zoom + ') rotate(' + rotation + 'deg); transition: transform 160ms ease-out;'"
                                            >
                                        </template>
                                    </div>
                                </div>
                            </div>

                            <div class="space-y-3">
                                <div class="flex items-center justify-between gap-3 px-3 py-2 rounded-2xl bg-gray-50 border border-gray-200">
                                    <div class="flex items-center gap-2">
                                        <span class="text-[9px] font-semibold text-gray-500 uppercase tracking-[0.18em]">Zoom</span>
                                        <input type="range" min="80" max="160" step="5" x-model="zoomSlider" @input="syncZoom" class="w-32 h-1.5 rounded-full bg-gray-100 accent-emerald-500">
                                    </div>
                                    <div class="flex items-center gap-1.5">
                                        <button type="button" @click="rotate(-90)" class="w-7 h-7 rounded-full bg-white flex items-center justify-center text-gray-500 hover:bg-gray-900 hover:text-white transition-colors text-[10px] border border-gray-200">
                                            <i class="fas fa-rotate-left"></i>
                                        </button>
                                        <button type="button" @click="rotate(90)" class="w-7 h-7 rounded-full bg-white flex items-center justify-center text-gray-500 hover:bg-gray-900 hover:text-white transition-colors text-[10px] border border-gray-200">
                                            <i class="fas fa-rotate-right"></i>
                                        </button>
                                        <button type="button" @click="resetView" class="px-2.5 h-7 rounded-full bg-white text-[10px] font-semibold text-gray-600 border border-gray-200 hover:bg-gray-100 transition-colors">
                                            Fit
                                        </button>
                                    </div>
                                </div>

                                <div class="flex items-center justify-between gap-3">
                                    <div class="inline-flex items-center px-3 py-1 rounded-full bg-emerald-50 border border-emerald-100 text-[10px] font-semibold text-emerald-700">
                                        <span class="mr-1.5 inline-flex h-5 w-5 items-center justify-center rounded-full bg-gradient-to-tr from-emerald-500 to-emerald-600 text-white text-[9px]">
                                            <i class="fas fa-magic"></i>
                                        </span>
                                        <span x-show="!isEdited">Smart clean: remove background + center framing</span>
                                        <span x-show="isEdited" style="display:none;">Background cleaned</span>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <button
                                            type="button"
                                            @click="cleanBackground"
                                            :disabled="isCleaning"
                                            class="inline-flex items-center px-3 py-1.5 rounded-full bg-gray-900 text-white text-[10px] font-semibold hover:bg-black transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
                                        >
                                            <span class="flex items-center">
                                                <span
                                                    x-show="isCleaning"
                                                    class="inline-flex h-3.5 w-3.5 mr-1.5 rounded-full border-[1.5px] border-white/60 border-t-transparent animate-spin"
                                                ></span>
                                                <i
                                                    x-show="!isCleaning"
                                                    class="fas fa-eraser text-[9px] mr-1.5"
                                                ></i>
                                            </span>
                                            <span x-show="!isCleaning">Remove background</span>
                                            <span x-show="isCleaning">Removing…</span>
                                        </button>
                                        <button type="button" @click="resetImage" x-show="isEdited" style="display:none;" class="inline-flex items-center px-3 py-1.5 rounded-full bg-white text-gray-700 text-[10px] font-semibold border border-gray-200 hover:bg-gray-50 transition-colors">
                                            <i class="fas fa-rotate-left text-[9px] mr-1.5"></i>
                                            Reset original
                                        </button>
                                    </div>
                                </div>

                                <div class="flex items-center justify-end gap-2 pt-1">
                                    <button type="button" @click="closeEditor" class="px-3 py-1.5 rounded-full bg-white text-[10px] font-semibold text-gray-600 border border-gray-200 hover:bg-gray-50 transition-colors">
                                        Close
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    @error('image')
                        <p class="mt-3 text-sm text-red-600 text-center">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- Publishing / Visibility -->
            <div class="bg-white rounded-2xl p-6 border border-gray-200 shadow-sm">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-10 h-10 bg-emerald-500/10 rounded-xl flex items-center justify-center text-emerald-600">
                        <i class="fas fa-toggle-on text-base"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900">Visibility</h3>
                        <p class="text-xs text-gray-500">Control where this product appears.</p>
                    </div>
                </div>

                <div class="space-y-4">
                    <div class="p-5 bg-gray-50 border border-gray-100 rounded-xl flex items-center justify-between group hover:bg-white hover:border-brand/20 transition-all duration-300">
                        <div>
                            <p class="text-sm font-medium text-gray-900">Active status</p>
                            <p class="text-xs text-gray-500 mt-1">Visible to customers</p>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="is_active" value="1" class="sr-only peer" checked>
                            <div class="w-12 h-7 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[3px] after:left-[3px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand shadow-inner"></div>
                        </label>
                    </div>

                    <div class="p-5 bg-gray-50 border border-gray-100 rounded-xl flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-900">Featured product</p>
                            <p class="text-xs text-gray-500 mt-1">Show in featured section</p>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="is_featured" value="1" class="sr-only peer">
                            <div class="w-12 h-7 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[3px] after:left-[3px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand shadow-inner"></div>
                        </label>
                    </div>

                    <div class="p-5 bg-gray-50 border border-gray-100 rounded-xl flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-900">Special offer</p>
                            <p class="text-xs text-gray-500 mt-1">Show in special offers page</p>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="is_special_offer" value="1" class="sr-only peer">
                            <div class="w-12 h-7 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[3px] after:left-[3px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand shadow-inner"></div>
                        </label>
                    </div>

                    <div class="p-5 bg-gray-50 border border-gray-100 rounded-xl flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-900">Premium shop</p>
                            <p class="text-xs text-gray-500 mt-1">Show in premium shop page</p>
                        </div>
                        <label class="relative inline-flex items-center cursor-pointer">
                            <input type="checkbox" name="is_premium" value="1" class="sr-only peer">
                            <div class="w-12 h-7 bg-gray-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[3px] after:left-[3px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-brand shadow-inner"></div>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
    function imageUpload() {
        return {
            previewUrl: null,
            file: null,
            originalFile: null,
            isEdited: false,
            showEditor: false,
            zoom: 1,
            zoomSlider: 100,
            rotation: 0,
            isCleaning: false,
            handleFileChange(event) {
                const file = event.target.files[0];
                if (file) {
                    this.file = file;
                    this.originalFile = file;
                    this.isEdited = false;
                    this.showEditor = false;
                    this.zoom = 1;
                    this.zoomSlider = 100;
                    this.rotation = 0;
                    if (this.previewUrl) {
                        URL.revokeObjectURL(this.previewUrl);
                    }
                    this.previewUrl = URL.createObjectURL(file);
                }
            },
            removeImage() {
                if (this.previewUrl) {
                    URL.revokeObjectURL(this.previewUrl);
                }
                this.previewUrl = null;
                this.showEditor = false;
                this.file = null;
                this.originalFile = null;
                this.isEdited = false;
                 this.zoom = 1;
                 this.zoomSlider = 100;
                 this.rotation = 0;
                var input = document.getElementById('image');
                if (input) {
                    input.value = '';
                }
            },
            resetImage() {
                if (!this.originalFile) {
                    return;
                }
                this.file = this.originalFile;
                this.isEdited = false;
                this.showEditor = false;
                this.zoom = 1;
                this.zoomSlider = 100;
                this.rotation = 0;
                var input = document.getElementById('image');
                if (input && window.DataTransfer) {
                    var dt = new DataTransfer();
                    dt.items.add(this.originalFile);
                    input.files = dt.files;
                }
                if (this.previewUrl) {
                    URL.revokeObjectURL(this.previewUrl);
                }
                this.previewUrl = URL.createObjectURL(this.originalFile);
            },
            openEditor() {
                if (!this.previewUrl) {
                    return;
                }
                this.showEditor = true;
            },
            closeEditor() {
                this.showEditor = false;
            },
            syncZoom() {
                var value = parseInt(this.zoomSlider, 10) || 100;
                if (value < 80) value = 80;
                if (value > 160) value = 160;
                this.zoomSlider = value;
                this.zoom = value / 100;
            },
            rotate(delta) {
                this.rotation = (this.rotation + delta) % 360;
            },
            resetView() {
                this.zoom = 1;
                this.zoomSlider = 100;
                this.rotation = 0;
            },
            cleanBackground() {
                var sourceFile = this.file || this.originalFile;
                if (!sourceFile || this.isCleaning) {
                    return;
                }
                var self = this;
                this.isCleaning = true;
                var formData = new FormData();
                formData.append('image', sourceFile);

                fetch('{{ url('/api/ai/remove-background') }}', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(function (res) {
                        if (!res.ok) {
                            return res.json().then(function (data) {
                                throw new Error((data && data.message) || 'Failed to remove background');
                            }).catch(function (err) {
                                throw err;
                            });
                        }
                        return res.blob();
                    })
                    .then(function (blob) {
                        if (!blob) {
                            throw new Error('Empty image from background remover');
                        }
                        var name = sourceFile.name || 'product-image.png';
                        var baseName = name.replace(/\.[^/.]+$/, '');
                        var editedFile = new File([blob], baseName + '-nobg.png', { type: 'image/png' });
                        self.applyEditedFile(editedFile);
                    })
                    .catch(function (error) {
                        var message = error && error.message ? error.message : 'Failed to remove background';
                        if (window.toastr && typeof window.toastr.error === 'function') {
                            window.toastr.error(message);
                        } else {
                            alert(message);
                        }
                    })
                    .finally(function () {
                        self.isCleaning = false;
                    });
            },
            applyEditedFile(editedFile) {
                this.file = editedFile;
                this.isEdited = true;
                this.zoom = 1;
                this.zoomSlider = 100;
                this.rotation = 0;
                var input = document.getElementById('image');
                if (input && window.DataTransfer) {
                    var dt = new DataTransfer();
                    dt.items.add(editedFile);
                    input.files = dt.files;
                }
                if (this.previewUrl) {
                    URL.revokeObjectURL(this.previewUrl);
                }
                this.previewUrl = URL.createObjectURL(editedFile);
            },
            applyEditedDataUrl(dataUrl, sourceFile) {
            }
        }
    }

    function loadSubCategories(categoryId) {
        const subCategorySelect = document.getElementById('sub_category_id');
        const loader = document.getElementById('subcategory-loader');
        const chevron = document.getElementById('subcategory-chevron');
        
        subCategorySelect.innerHTML = '<option value="">Select Subcategory</option>';
        subCategorySelect.disabled = true;

        if (!categoryId) return;

        loader.classList.remove('hidden');
        chevron.classList.add('hidden');

        fetch(`/admin/categories/${categoryId}/subcategories`)
            .then(response => response.json())
            .then(data => {
                data.forEach(subCategory => {
                    const option = document.createElement('option');
                    option.value = subCategory.id;
                    option.textContent = subCategory.name;
                    subCategorySelect.appendChild(option);
                });
                subCategorySelect.disabled = false;
            })
            .catch(error => {
                console.error('Error loading subcategories:', error);
            })
            .finally(() => {
                loader.classList.add('hidden');
                chevron.classList.remove('hidden');
            });
    }

    document.addEventListener('DOMContentLoaded', function() {
        const categoryId = document.getElementById('category_id').value;
        if (categoryId) {
            loadSubCategories(categoryId);
        }

        var aiBtn = document.getElementById('ai-generate-description-btn');
        var descriptionInput = document.getElementById('description');
        var status = document.getElementById('ai-generate-status');
        var nameInput = document.getElementById('name');
        var priceInput = document.getElementById('price');
        var unitInput = document.getElementById('unit');
        var categorySelect = document.getElementById('category_id');
        var imageInput = document.getElementById('image');
        var aiPrepareBtn = document.getElementById('ai-prepare-product-btn');
        var aiPrepareStatus = document.getElementById('ai-prepare-status');
        var seoTitleInput = document.getElementById('seo_title');
        var seoDescriptionInput = document.getElementById('seo_description');
        var seoKeywordsInput = document.getElementById('seo_keywords');
        var aiSeoBtn = document.getElementById('ai-generate-seo-btn');
        var aiSeoStatus = document.getElementById('ai-seo-status');

        if (aiBtn && descriptionInput && status) {
            aiBtn.addEventListener('click', function (e) {
                e.preventDefault();

                var name = nameInput ? nameInput.value.trim() : '';
                if (!name) {
                    status.textContent = 'Please enter a product name first.';
                    status.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                    if (nameInput) {
                        nameInput.focus();
                    }
                    return;
                }

                var categoryName = '';
                if (categorySelect && categorySelect.options.length) {
                    var selectedIndex = categorySelect.selectedIndex;
                    if (selectedIndex > 0) {
                        categoryName = categorySelect.options[selectedIndex].text;
                    }
                }

                var price = priceInput ? priceInput.value : '';
                var unit = unitInput ? unitInput.value : '';

                var lines = [];
                lines.push('Write a professional, concise product description for an online grocery product.');
                lines.push('');
                lines.push('Product name: ' + name);
                if (categoryName) {
                    lines.push('Category: ' + categoryName);
                }
                if (price) {
                    lines.push('Price: ' + price);
                }
                if (unit) {
                    lines.push('Unit: ' + unit);
                }
                lines.push('');
                lines.push('Focus on benefits, freshness, usage ideas and trust. Keep it 2-4 short sentences.');

                if (imageInput && imageInput.files && imageInput.files[0]) {
                    lines.push('');
                    lines.push('Use the attached product image to understand packaging, appearance and visual details.');
                }

                var prompt = lines.join('\n');

                aiBtn.disabled = true;
                aiBtn.classList.add('opacity-60', 'cursor-not-allowed');
                status.textContent = '';
                status.className = 'mt-1 text-[11px] text-gray-400';

                var label = aiBtn.querySelector('.label');
                if (label) {
                    label.textContent = 'Generating...';
                }

                fetch('{{ url('/api/ai/generate-description') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        prompt: prompt,
                        max_tokens: 220
                    })
                })
                    .then(function (res) {
                        return res.json().then(function (data) {
                            return { status: res.status, data: data };
                        });
                    })
                    .then(function (result) {
                        if (result.data && result.data.status === 'success' && result.data.data && result.data.data.text) {
                            var generated = result.data.data.text.trim();
                            if (!generated) {
                                status.textContent = 'AI response was empty. Try again.';
                                status.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                                return;
                            }

                            var current = descriptionInput.value.trim();
                            if (current) {
                                descriptionInput.value = current + '\n\n' + generated;
                            } else {
                                descriptionInput.value = generated;
                            }

                            if (window.descriptionEditor) {
                                window.descriptionEditor.root.innerHTML = descriptionInput.value.replace(/\n/g, '<br>');
                            }

                            status.textContent = 'Description generated by AI.';
                            status.className = 'mt-1 text-[11px] text-emerald-600 font-medium';
                        } else {
                            var message = (result.data && result.data.message) ? result.data.message : 'Failed to generate description. Please check AI settings.';
                            status.textContent = message;
                            status.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                        }
                    })
                    .catch(function () {
                        status.textContent = 'Network error. Please try again.';
                        status.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                    })
                    .finally(function () {
                        aiBtn.disabled = false;
                        aiBtn.classList.remove('opacity-60', 'cursor-not-allowed');
                        if (label) {
                            label.textContent = 'AI generate';
                        }
                    });
            });
        }

        function triggerSeoGeneration(afterPrepare) {
            if (!nameInput || !seoTitleInput || !seoDescriptionInput || !seoKeywordsInput || !aiSeoStatus) {
                return;
            }

            var title = nameInput.value.trim();
            if (!title) {
                if (!afterPrepare) {
                    aiSeoStatus.textContent = 'Please enter a product name first.';
                    aiSeoStatus.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                    nameInput.focus();
                }
                return;
            }

            var desc = descriptionInput ? descriptionInput.value.trim() : '';
            var categoryName = '';
            if (categorySelect && categorySelect.options.length) {
                var selectedIndex = categorySelect.selectedIndex;
                if (selectedIndex > 0) {
                    categoryName = categorySelect.options[selectedIndex].text;
                }
            }

            var price = priceInput ? priceInput.value : '';
            var unit = unitInput ? unitInput.value : '';

            if (!afterPrepare && aiSeoBtn) {
                aiSeoBtn.disabled = true;
                aiSeoBtn.classList.add('opacity-60', 'cursor-not-allowed');
            }

            aiSeoStatus.textContent = afterPrepare ? 'AI is generating SEO meta...' : '';
            aiSeoStatus.className = 'mt-1 text-[11px] text-gray-400';

            var labelSeo = aiSeoBtn ? aiSeoBtn.querySelector('.label') : null;
            var originalLabel = labelSeo ? labelSeo.textContent : null;
            if (!afterPrepare && labelSeo) {
                labelSeo.textContent = 'Generating...';
            }

            fetch('{{ url('/api/ai/generate-product-seo') }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({
                    product_title: title,
                    description: desc,
                    category: categoryName,
                    price: price,
                    unit: unit
                })
            })
                .then(function (res) {
                    return res.json().then(function (data) {
                        return { status: res.status, data: data };
                    });
                })
                .then(function (result) {
                    if (result.data && result.data.status === 'success' && result.data.data) {
                        var payload = result.data.data;

                        if (payload.seo_title) {
                            seoTitleInput.value = payload.seo_title;
                            seoTitleInput.dispatchEvent(new Event('input'));
                        }
                        if (payload.seo_description) {
                            seoDescriptionInput.value = payload.seo_description;
                            seoDescriptionInput.dispatchEvent(new Event('input'));
                        }
                        if (payload.seo_keywords) {
                            seoKeywordsInput.value = payload.seo_keywords;
                        }

                        aiSeoStatus.textContent = afterPrepare
                            ? 'Category, description and SEO meta generated by AI. Review before saving.'
                            : 'SEO meta generated by AI. Review before saving.';
                        aiSeoStatus.className = 'mt-1 text-[11px] text-emerald-600 font-medium';
                    } else {
                        var messageSeo = (result.data && result.data.message) ? result.data.message : 'Failed to generate SEO. Please check AI settings.';
                        aiSeoStatus.textContent = messageSeo;
                        aiSeoStatus.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                    }
                })
                .catch(function () {
                    aiSeoStatus.textContent = 'Network error while generating SEO. Please try again.';
                    aiSeoStatus.className = 'mt-1 text-[11px] text-rose-600 font-medium';
                })
                .finally(function () {
                    if (!afterPrepare && aiSeoBtn) {
                        aiSeoBtn.disabled = false;
                        aiSeoBtn.classList.remove('opacity-60', 'cursor-not-allowed');
                        if (labelSeo && originalLabel) {
                            labelSeo.textContent = originalLabel;
                        }
                    }
                });
        }

        if (aiPrepareBtn && nameInput && descriptionInput && categorySelect && aiPrepareStatus) {
            aiPrepareBtn.addEventListener('click', function (e) {
                e.preventDefault();

                var title = nameInput.value.trim();
                if (!title) {
                    aiPrepareStatus.textContent = 'Please enter a product name first.';
                    aiPrepareStatus.className = 'text-[11px] text-rose-600 font-medium';
                    nameInput.focus();
                    return;
                }

                aiPrepareBtn.disabled = true;
                aiPrepareBtn.classList.add('opacity-60', 'cursor-not-allowed');

                var labelEl = aiPrepareBtn.querySelector('.label');
                if (labelEl) {
                    labelEl.textContent = 'Preparing...';
                }

                aiPrepareStatus.textContent = 'AI is preparing category, description and SEO...';
                aiPrepareStatus.className = 'text-[11px] text-gray-500';

                fetch('{{ url('/api/ai/prepare-product') }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        product_title: title,
                        notes: ''
                    })
                })
                    .then(function (res) {
                        return res.json().then(function (data) {
                            return { status: res.status, data: data };
                        });
                    })
                    .then(function (result) {
                        if (result.data && result.data.status === 'success' && result.data.data) {
                            var payload = result.data.data;

                            var catId = payload.category_id || null;
                            var subId = payload.sub_category_id || null;
                            var desc = payload.description || '';

                            if (catId) {
                                var options = categorySelect.options;
                                for (var i = 0; i < options.length; i++) {
                                    if (String(options[i].value) === String(catId)) {
                                        categorySelect.selectedIndex = i;
                                        break;
                                    }
                                }
                                loadSubCategories(catId);
                            }

                            if (subId) {
                                var applySub = function () {
                                    var subSelect = document.getElementById('sub_category_id');
                                    if (!subSelect || subSelect.options.length <= 1) {
                                        setTimeout(applySub, 200);
                                        return;
                                    }
                                    var subOptions = subSelect.options;
                                    for (var j = 0; j < subOptions.length; j++) {
                                        if (String(subOptions[j].value) === String(subId)) {
                                            subSelect.selectedIndex = j;
                                            break;
                                        }
                                    }
                                };
                                setTimeout(applySub, 300);
                            }

                            if (desc) {
                                descriptionInput.value = desc;
                                if (window.descriptionEditor) {
                                    var htmlDesc = desc.replace(/\n/g, '<br>');
                                    window.descriptionEditor.root.innerHTML = htmlDesc;
                                }
                            }

                            aiPrepareStatus.textContent = 'AI suggestion applied. Generating SEO meta...';
                            aiPrepareStatus.className = 'text-[11px] text-emerald-600 font-medium';

                            triggerSeoGeneration(true);
                        } else {
                            var messagePrepare = (result.data && result.data.message) ? result.data.message : 'Failed to prepare product. Please check AI settings.';
                            aiPrepareStatus.textContent = messagePrepare;
                            aiPrepareStatus.className = 'text-[11px] text-rose-600 font-medium';
                        }
                    })
                    .catch(function () {
                        aiPrepareStatus.textContent = 'Network error. Please try again.';
                        aiPrepareStatus.className = 'text-[11px] text-rose-600 font-medium';
                    })
                    .finally(function () {
                        aiPrepareBtn.disabled = false;
                        aiPrepareBtn.classList.remove('opacity-60', 'cursor-not-allowed');
                        var labelReset = aiPrepareBtn.querySelector('.label');
                        if (labelReset) {
                            labelReset.textContent = 'AI prepare';
                        }
                    });
            });
        }

        if (aiSeoBtn && nameInput && seoTitleInput && seoDescriptionInput && seoKeywordsInput && aiSeoStatus) {
            aiSeoBtn.addEventListener('click', function (e) {
                e.preventDefault();
                triggerSeoGeneration(false);
            });
        }
    });
</script>
@endsection
