@extends('layouts.admin')

@section('title', 'Add New Sub-Category')

@section('content')
<div class="max-w-[1100px] mx-auto">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 leading-tight">Create sub-category</h1>
            <p class="text-gray-500 text-sm mt-1">Add a sub-category to better organize your products.</p>
        </div>
        <div class="flex items-center gap-3">
            <a href="{{ route('admin.subcategories.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="subcategory-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 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40">
                <i class="fas fa-check text-xs"></i>
                Save sub-category
            </button>
        </div>
    </div>

    <form action="{{ route('admin.subcategories.store') }}" method="POST" enctype="multipart/form-data" id="subcategory-form" class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        @csrf
        
        <!-- Left Column: Basic Info -->
        <div class="lg:col-span-8 space-y-6">
            <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-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">General information</h3>
                        <p class="text-xs text-gray-500">Basic details of the sub-category</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 gap-5">
                    <div class="space-y-2">
                        <label for="category_id" class="text-sm font-medium text-gray-700">Parent category</label>
                        <div class="relative">
                            <select name="category_id" id="category_id" 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 appearance-none cursor-pointer">
                                <option value="">Select parent 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>
                        @error('category_id')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="space-y-2">
                        <label for="name" class="text-sm font-medium text-gray-700">Sub-category 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="e.g. Fresh vegetables">
                        @error('name')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <div class="space-y-2">
                        <label for="description" class="text-sm font-medium text-gray-700">Description (optional)</label>
                        <textarea name="description" id="description" rows="4" 
                            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 resize-none"
                            placeholder="Briefly describe this sub-category">{{ old('description') }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Column: Media & Status -->
        <div class="lg:col-span-4 space-y-6">
            <!-- Thumbnail Upload with Editor -->
            <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-brand/10 rounded-xl flex items-center justify-center text-brand">
                        <i class="fas fa-image text-base"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold text-gray-900">Thumbnail 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 class="mr-1.5 inline-flex h-4 w-4 items-center justify-center rounded-full bg-emerald-500 text-white">
                                                    <i class="fas fa-wand-magic-sparkles text-[9px]"></i>
                                                </span>
                                                <span x-show="!isCleaning">Clean background</span>
                                                <span x-show="isCleaning" style="display:none;">Cleaning...</span>
                                            </span>
                                        </button>
                                        <button type="button" @click="resetImage" 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">
                                            Reset
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @error('image')
                    <p class="mt-3 text-sm text-red-600 text-center">{{ $message }}</p>
                @enderror
            </div>

            <!-- Status -->
            <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-brand/10 rounded-xl flex items-center justify-center text-brand">
                        <i class="fas fa-toggle-on text-base"></i>
                    </div>
                    <h3 class="text-sm font-semibold text-gray-900">Visibility</h3>
                </div>

                <div class="p-4 bg-gray-50 rounded-xl border border-gray-200">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-900">Active status</p>
                            <p class="text-xs text-gray-500 mt-0.5">Visible on the store</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"></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 || 'thumbnail-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) {
            }
        }
    }
</script>
@endsection
