@extends('layouts.app')
@section('title', 'Nuevo Registro de Set — Sampedro')

@section('content')
<div class="min-h-screen bg-gray-50 p-4 md:p-8 pb-24">
    <div class="max-w-2xl mx-auto bg-white rounded-2xl shadow-lg overflow-hidden">

        {{-- ── Header ─────────────────────────────────────────────── --}}
        <div class="bg-blue-600 p-6 text-white flex justify-between items-center">
            <div>
                <h2 class="text-xl font-bold">Registro de Set de Materiales</h2>
                <p class="text-blue-100 text-sm mt-1">Operador: {{ Auth::user()->name }}</p>
            </div>
            <svg class="h-10 w-10 text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                      d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0
                         012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2
                         2 0 012 2v2M7 7h10"/>
            </svg>
        </div>

        {{-- ── Errores ──────────────────────────────────────────────── --}}
        @if ($errors->any())
            <div class="mx-6 mt-6 bg-red-50 border border-red-200 text-red-700
                        px-4 py-3 rounded-xl text-sm">
                <ul class="list-disc list-inside space-y-1">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        {{-- ── Formulario ────────────────────────────────────────────── --}}
        <form method="POST" action="{{ route('sets.store') }}"
              enctype="multipart/form-data"
              class="p-6 space-y-6">
            @csrf

            {{-- PASO 1 y 2: Seleccionar Set y Referencia --}}
            <div x-data="{
                    sets: [],
                    referencias: [],
                    cargandoSets: true,
                    cargandoRefs: false,
                    errorSets: false,
                    errorRefs: false,
                    setSeleccionado: '',
                    referenciaSeleccionada: '',
                    async cargarSets() {
                        try {
                            const res = await fetch('{{ url('/api/sets') }}');
                            if (!res.ok) throw new Error();
                            this.sets = await res.json();
                            this.cargandoSets = false;
                        } catch(e) {
                            this.errorSets = true;
                            this.cargandoSets = false;
                        }
                    },
                    async cargarReferencias() {
                        if (!this.setSeleccionado) { this.referencias = []; return; }
                        this.cargandoRefs = true;
                        this.errorRefs = false;
                        this.referencias = [];
                        this.referenciaSeleccionada = '';
                        try {
                            const res = await fetch('{{ url('/api/sets') }}/' + this.setSeleccionado + '/referencias');
                            if (!res.ok) throw new Error();
                            this.referencias = await res.json();
                            this.cargandoRefs = false;
                        } catch(e) {
                            this.errorRefs = true;
                            this.cargandoRefs = false;
                        }
                    }
                }"
                x-init="cargarSets()">

                {{-- Set --}}
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Set <span class="text-red-500">*</span>
                    </label>

                    <select name="codigo_set" required
                            x-model="setSeleccionado"
                            @change="cargarReferencias()"
                            class="w-full p-3 border border-gray-300 rounded-xl outline-none
                                transition bg-white focus:ring-2 focus:ring-blue-500">

                        <template x-if="cargandoSets">
                            <option value="">⏳ Cargando sets...</option>
                        </template>
                        <template x-if="errorSets">
                            <option value="">❌ Error al cargar sets</option>
                        </template>
                        <template x-if="!cargandoSets && !errorSets">
                            <option value="">— Seleccione un set —</option>
                        </template>
                        <template x-for="set in sets" :key="set.Referencia">
                            <option :value="set.Referencia"
                                    x-text="set.Referencia + ' — ' + set.Descripcion">
                            </option>
                        </template>
                    </select>
                </div>

                {{-- Paso 2: Referencias del set --}}
                <div x-show="setSeleccionado" x-cloak class="mt-4">
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Referencia del Set <span class="text-red-500">*</span>
                    </label>

                    {{-- Cargando --}}
                    <div x-show="cargandoRefs"
                        class="w-full p-3 border border-gray-200 rounded-xl bg-gray-50
                                text-sm text-gray-400 text-center">
                        ⏳ Cargando referencias...
                    </div>

                    {{-- Error --}}
                    <div x-show="errorRefs && !cargandoRefs"
                        class="w-full p-3 border border-red-200 rounded-xl bg-red-50
                                text-sm text-red-500 text-center">
                        ❌ Error al cargar referencias
                    </div>

                    {{-- Select de referencias --}}
                    <select name="referencia"
                            x-show="!cargandoRefs && !errorRefs && referencias.length > 0"
                            x-model="referenciaSeleccionada"
                            class="w-full p-3 border border-gray-300 rounded-xl outline-none
                                transition bg-white focus:ring-2 focus:ring-blue-500">
                        <option value="">— Seleccione una referencia —</option>
                        <template x-for="ref in referencias" :key="ref.Referencia">
                            <option :value="ref.Referencia"
                                    x-text="ref.Referencia + ' — ' + ref['Descripcion'] + ' (x' + ref.CANTxSET + ')'">
                            </option>
                        </template>
                    </select>

                    {{-- Detalle de la referencia seleccionada --}}
                    <template x-if="referenciaSeleccionada">
                        <div class="mt-2 bg-blue-50 border border-blue-200 rounded-xl p-3 text-xs text-blue-800">
                            <template x-for="ref in referencias" :key="ref.Referencia">
                                <div x-show="referenciaSeleccionada === ref.Referencia"
                                    class="flex gap-4">
                                    <span>📦 Set: <strong x-text="ref.NomSet"></strong></span>
                                    <span>🔢 Cantidad: <strong x-text="ref.CANTxSET"></strong></span>
                                </div>
                            </template>
                        </div>
                    </template>

                    {{-- Campos ocultos reactivos --}}
                    <input type="hidden" name="referencia"             :value="referenciaSeleccionada" />
                    <input type="hidden" name="descripcion_referencia" :value="referencias.find(r => r.Referencia === referenciaSeleccionada)?.Descripcion ?? ''" />
                    <input type="hidden" name="cantidad"               :value="referencias.find(r => r.Referencia === referenciaSeleccionada)?.CANTxSET ?? ''" />
                    <input type="hidden" name="material"               :value="referenciaSeleccionada + ' - ' + (referencias.find(r => r.Referencia === referenciaSeleccionada)?.Descripcion ?? '')" />
                </div>

            </div>

            {{-- Sucursal --}}
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                    Sucursal <span class="text-red-500">*</span>
                </label>
                <select name="sucursal" required
                        class="w-full p-3 border rounded-xl outline-none transition bg-white
                               focus:ring-2 focus:ring-blue-500
                               {{ $errors->has('sucursal') ? 'border-red-400 bg-red-50' : 'border-gray-300' }}">
                    <option value="">— Seleccionar sucursal —</option>
                    @foreach ($sucursales as $suc)
                        <option value="{{ $suc }}" {{ old('sucursal') === $suc ? 'selected' : '' }}>
                            {{ $suc }}
                        </option>
                    @endforeach
                </select>
            </div>

            {{-- Evidencia — cámara del dispositivo --}}
            <div x-data="{
                    preview: null,
                    fileName: '',
                    handleFile(event) {
                        const file = event.target.files[0];
                        if (!file) return;
                        this.fileName = file.name;
                        const reader = new FileReader();
                        reader.onload = e => this.preview = e.target.result;
                        reader.readAsDataURL(file);
                    }
                }">
                <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                    Evidencia Fotográfica
                    <span class="text-gray-400 font-normal text-xs">(opcional)</span>
                </label>

                {{-- Vista previa de la foto tomada --}}
                <div x-show="preview" x-cloak
                     class="mb-3 border-2 border-blue-300 rounded-xl overflow-hidden bg-gray-50">
                    <img :src="preview" class="w-full max-h-72 object-contain" />
                </div>

                {{-- Botón para abrir la cámara --}}
                <label class="flex items-center justify-center gap-3 w-full py-5 px-4
                              border-2 border-dashed rounded-xl cursor-pointer transition"
                       :class="preview
                           ? 'border-blue-400 bg-blue-50 hover:bg-blue-100'
                           : 'border-gray-300 bg-gray-50 hover:bg-blue-50 hover:border-blue-400'">

                    <svg class="h-8 w-8 text-blue-500 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                              d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86
                                 a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2
                                 2H5a2 2 0 01-2-2V9z"/>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                              d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>

                    <div class="text-left">
                        <p class="text-sm font-semibold text-gray-700"
                           x-text="preview ? 'Tomar otra foto' : 'Tomar foto'"></p>
                        <p class="text-xs text-gray-400">Se abrirá la cámara del dispositivo</p>
                    </div>

                    <input type="file"
                           name="evidencia"
                           class="hidden"
                           accept="image/*"
                           capture="environment"
                           @change="handleFile($event)" />
                </label>

                <p x-show="fileName" x-cloak
                   class="mt-2 text-xs text-blue-600 flex items-center gap-1">
                    <svg class="h-3.5 w-3.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                    </svg>
                    <span x-text="fileName"></span>
                </p>
            </div>

            {{-- Notas --}}
            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                    Notas Adicionales
                </label>
                <textarea name="notas" rows="4"
                          class="w-full p-3 border border-gray-300 rounded-xl outline-none
                                 focus:ring-2 focus:ring-blue-500 resize-none transition"
                          placeholder="Describa el estado, faltantes o novedades del set...">{{ old('notas') }}</textarea>
            </div>

            {{-- Botón submit --}}
            <button type="submit"
                    id="btn-guardar"
                    onclick="mostrarLoader()"
                    class="w-full py-4 px-6 rounded-xl text-white font-bold text-lg flex
                        justify-center items-center gap-2 transition-all shadow-lg
                        bg-green-600 hover:bg-green-700 hover:-translate-y-0.5 active:scale-95">
                <span id="btn-texto" class="flex items-center gap-2">
                    <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                    Guardar Registro
                </span>
                <span id="btn-loader" class="hidden flex items-center gap-2">
                    <svg class="animate-spin h-6 w-6" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                        <path class="opacity-75" fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962
                                7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                    </svg>
                    Guardando... por favor espere
                </span>
            </button>

            {{-- Overlay de carga --}}
            <div id="overlay-loader"
                class="hidden fixed inset-0 bg-black/50 z-50 flex flex-col items-center justify-center gap-4">
                <div class="bg-white rounded-2xl px-10 py-8 flex flex-col items-center gap-4 shadow-2xl">
                    <svg class="animate-spin h-12 w-12 text-blue-600" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                        <path class="opacity-75" fill="currentColor"
                            d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962
                                7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
                    </svg>
                    <p class="text-gray-700 font-semibold text-lg">Guardando registro...</p>
                    <p class="text-gray-400 text-sm">Enviando correo de notificación</p>
                </div>
            </div>

            @push('scripts')
            <script>
            function mostrarLoader() {
                const btn = document.getElementById('btn-guardar');
                const texto = document.getElementById('btn-texto');
                const loader = document.getElementById('btn-loader');
                const overlay = document.getElementById('overlay-loader');

                btn.disabled = true;
                texto.classList.add('hidden');
                loader.classList.remove('hidden');
                overlay.classList.remove('hidden');
            }

            // Ocultar overlay cuando la página se redirige
            window.addEventListener('beforeunload', function() {
                const overlay = document.getElementById('overlay-loader');
                if (overlay) overlay.classList.add('hidden');
            });

            // Ocultar overlay si la página vuelve desde caché (botón atrás)
            window.addEventListener('pageshow', function(event) {
                const overlay = document.getElementById('overlay-loader');
                const btn = document.getElementById('btn-guardar');
                const texto = document.getElementById('btn-texto');
                const loader = document.getElementById('btn-loader');
                
                if (overlay) overlay.classList.add('hidden');
                if (btn) btn.disabled = false;
                if (texto) texto.classList.remove('hidden');
                if (loader) loader.classList.add('hidden');
            });
            </script>
            @endpush
        </form>

    </div>
</div>
@endsection