<?= $this->extend('layouts/modelo_layout') ?>

<?= $this->section('content') ?>

<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.bootstrap5.min.css" rel="stylesheet">
<style>
    /* Ajuste para que se vea bien con tu diseño oscuro/moderno */
    .ts-control { background: #1f2937; border: 1px solid #374151; color: white; border-radius: 0.5rem; padding: 10px; }
    .ts-dropdown { background: #1f2937; color: white; border: 1px solid #374151; }
    .ts-dropdown .active { background: #3b82f6; color: white; }
    .ts-control .item { background: #3b82f6; color: white; border-radius: 4px; }
    /* Añade esto a tu bloque de <style> */
.ts-wrapper.multi .ts-control > div {
    cursor: pointer;
    margin: 0 3px 3px 0;
    padding: 2px 8px;
    background: #ee2b5b !important; /* Color primary */
    color: #ffffff;
    border-radius: 5px;
    font-weight: bold;
    font-size: 12px;
}
.ts-control input {
    color: white !important; /* Para que lo que escribes sea legible */
}
.ts-dropdown {
    margin-top: 5px;
    border-radius: 12px;
    overflow: hidden;
}
</style>

<div class="flex flex-col gap-8 p-6 lg:p-10 max-w-7xl mx-auto w-full">
    
    <div class="flex justify-between items-center mb-2">
        <h1 class="text-2xl font-black uppercase text-white">Mi Perfil Profesional</h1>
    </div>

    <?php if ($modelo['verificada'] == 0): ?>
    <div class="mb-8 overflow-hidden rounded-2xl border border-yellow-500/30 bg-yellow-500/10 p-1 shadow-2xl shadow-yellow-500/5">
        <div class="flex flex-col md:flex-row items-center gap-6 p-6">
            <div class="flex size-16 shrink-0 items-center justify-center rounded-full bg-yellow-500/20 text-yellow-500 ring-8 ring-yellow-500/10">
                <span class="material-symbols-outlined text-4xl animate-pulse">id_card</span>
            </div>
            <div class="flex-1 text-center md:text-left">
                <h3 class="text-lg font-bold text-yellow-500 flex items-center justify-center md:justify-start gap-2 uppercase">
                    Acción Requerida: Verificación Pendiente
                </h3>
                <p class="mt-1 text-sm text-yellow-200/80 leading-relaxed">
                    Tu perfil se encuentra **oculto** actualmente. Para que los clientes puedan verte en el sitio, debes subir una foto de tu documento de identidad.
                </p>
            </div>
            <div class="shrink-0 hidden lg:block">
                <button type="button" onclick="irADocumentos(event)" class="inline-flex items-center gap-2 rounded-xl bg-yellow-500 px-6 py-3 text-sm font-black text-black transition-transform hover:scale-105 active:scale-95 shadow-lg shadow-yellow-500/20">
                    SUBIR DOCUMENTOS
                    <span class="material-symbols-outlined text-sm">arrow_downward</span>
                </button>
            </div>
        </div>
        <div class="h-1.5 w-full bg-yellow-500/10">
            <div class="h-full bg-yellow-500 animate-[progress_2s_ease-in-out_infinite]" style="width: 30%"></div>
        </div>
    </div>
    <?php elseif ($modelo['verificada'] == 1): ?>
        <div class="mb-8 flex items-center gap-3 rounded-xl border border-green-500/30 bg-green-500/10 p-4 text-green-400">
            <span class="material-symbols-outlined text-green-500">check_circle</span>
            <span class="text-sm font-bold uppercase tracking-wider">¡Tu perfil está verificado!</span>
        </div>
    <?php endif; ?>

    <form id="homeFilterForm" action="<?= base_url('modelo/guardar-ficha') ?>" method="POST" enctype="multipart/form-data" class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <?= csrf_field() ?>
        
        <div class="lg:col-span-2 space-y-6">
            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark space-y-4 shadow-xl">
                <h2 class="text-lg font-bold text-primary flex items-center gap-2">
                    <span class="material-symbols-outlined">person</span> Información Principal
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <input type="text" name="nombre_artistico" value="<?= $modelo['nombre_artistico'] ?? '' ?>" placeholder="Nombre Artístico" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-white" required>
                    <input type="text" name="telefono" value="<?= $modelo['telefono'] ?? '' ?>" placeholder="WhatsApp (+569...)" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-white" required>
                </div>
                
                <div class="grid grid-cols-3 gap-4">
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] uppercase font-bold text-gray-500 ml-2">Edad</label>
                        <input type="number" name="edad" value="<?= $modelo['edad'] ?? '' ?>" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-center text-white">
                    </div>
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] uppercase font-bold text-gray-500 ml-2">Estatura</label>
                        <input type="text" name="estatura" value="<?= $modelo['estatura'] ?? '' ?>" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-center text-white">
                    </div>
                    <div class="flex flex-col gap-1">
                        <label class="text-[10px] uppercase font-bold text-gray-500 ml-2">Medidas</label>
                        <input type="text" name="medidas" value="<?= $modelo['medidas'] ?? '' ?>" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-center text-white">
                    </div>
                </div>

                <div class="mb-6">
                    <label class="text-gold text-[10px] font-bold uppercase ml-2 mb-2 block tracking-widest">Categoría de Servicio</label>
                    <div class="grid grid-cols-2 gap-2">
                        <?php $catActual = $modelo['categoria'] ?? 'escort'; ?>
                        <label class="cursor-pointer">
                            <input type="radio" name="categoria" value="escort" class="hidden peer" <?= $catActual == 'escort' ? 'checked' : '' ?>>
                            <div class="text-center p-3 rounded-xl border border-white/10 bg-white/5 peer-checked:border-gold peer-checked:bg-gold/10 peer-checked:text-gold transition-all text-white">
                                <span class="material-symbols-outlined block mb-1">accessibility_new</span>
                                <span class="text-[10px] font-bold uppercase">Escort</span>
                            </div>
                        </label>
                        <label class="cursor-pointer">
                            <input type="radio" name="categoria" value="masajista" class="hidden peer" <?= $catActual == 'masajista' ? 'checked' : '' ?>>
                            <div class="text-center p-3 rounded-xl border border-white/10 bg-white/5 peer-checked:border-gold peer-checked:bg-gold/10 peer-checked:text-gold transition-all text-white">
                                <span class="material-symbols-outlined block mb-1">spa</span>
                                <span class="text-[10px] font-bold uppercase">Masajes</span>
                            </div>
                        </label>
                    </div>
                </div>

                <textarea name="descripcion" rows="4" placeholder="Tu descripción: Cuéntales sobre ti..." class="w-full bg-black/40 border-border-dark rounded-xl px-4 py-3 outline-none focus:border-primary text-white"><?= $modelo['descripcion'] ?? '' ?></textarea>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <select id="region_id" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none focus:border-primary text-white">
                        <option value="">Selecciona Región</option>
                        <?php foreach($regiones as $r): ?>
                            <option value="<?= $r['id'] ?>" <?= (isset($region_actual) && $region_actual == $r['id']) ? 'selected' : '' ?>><?= $r['nombre'] ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select id="ciudad_id" name="ciudad_id" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none focus:border-primary text-white">
                        <option value="">Comuna</option>
                    </select>
                </div>
            </section>

            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark space-y-6 shadow-xl">
                <h2 class="text-lg font-bold text-primary flex items-center gap-2">
                    <span class="material-symbols-outlined">auto_awesome</span> Gestión de Servicios
                </h2>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="flex flex-col gap-2 mb-6">
                        <label class="text-[10px] font-black uppercase tracking-widest text-emerald-500">Servicios Incluidos (En el valor de la hora)</label>
                        <select id="select-incluidos" name="servicios_incluidos[]" multiple placeholder="Selecciona o escribe servicios..." class="w-full">
                            <?php foreach($servicios_maestros as $s): ?>
                                <option value="<?= $s['nombre'] ?>"><?= $s['nombre'] ?></option>
                            <?php endforeach; ?>
                            
                            <?php 
                            $inc_actuales = explode(',', $modelo['servicios_incluidos'] ?? '');
                            foreach($inc_actuales as $val): if(trim($val)): ?>
                                <option value="<?= trim($val) ?>" selected><?= trim($val) ?></option>
                            <?php endif; endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="flex flex-col gap-2 mb-6">
                        <label class="text-[10px] font-black uppercase tracking-widest text-primary">Servicios Adicionales (Cobro aparte)</label>
                        <select id="select-adicionales" name="servicios_adicionales[]" multiple placeholder="Selecciona o escribe adicionales..." class="w-full">
                            <?php foreach($servicios_maestros as $s): ?>
                                <option value="<?= $s['nombre'] ?>"><?= $s['nombre'] ?></option>
                            <?php endforeach; ?>
                            
                            <?php 
                            $adi_actuales = explode(',', $modelo['servicios_adicionales'] ?? '');
                            foreach($adi_actuales as $val): if(trim($val)): ?>
                                <option value="<?= trim($val) ?>" selected><?= trim($val) ?></option>
                            <?php endif; endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="pt-4 border-t border-border-dark/50">
                    <div class="max-w-xs">
                        <label class="text-[11px] uppercase font-black text-primary ml-1">Precio Base por Hora (CLP)</label>
                        <div class="relative mt-1">
                            <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500 font-bold">$</span>
                            <input type="number" name="precio_clp" value="<?= $modelo['precio_clp'] ?? '' ?>" class="w-full bg-black/40 border-border-dark rounded-xl pl-8 pr-4 py-3 font-bold text-white outline-none focus:border-primary">
                        </div>
                    </div>
                </div>
            </section>

            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark space-y-6 shadow-xl">
                <h2 class="text-lg font-bold text-primary flex items-center gap-2">
                    <span class="material-symbols-outlined">info</span> Detalles de Atención
                </h2>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="flex flex-col gap-2">
                        <label class="text-[11px] uppercase font-black text-gray-400 ml-1">Horario de Disponibilidad</label>
                        <div class="flex gap-2">
                            <select name="horario_tipo" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none focus:border-primary text-white">
                                <option value="Full Time" <?= (isset($modelo['horario_tipo']) && $modelo['horario_tipo'] == 'Full Time') ? 'selected' : '' ?>>Full Time</option>
                                <option value="Part Time" <?= (isset($modelo['horario_tipo']) && $modelo['horario_tipo'] == 'Part Time') ? 'selected' : '' ?>>Part Time</option>
                                <option value="Horario Específico" <?= (isset($modelo['horario_tipo']) && $modelo['horario_tipo'] == 'Horario Específico') ? 'selected' : '' ?>>Específico</option>
                            </select>
                            <input type="text" name="horario_detalle" value="<?= $modelo['horario_detalle'] ?? '' ?>" placeholder="Ej: 08:00 a 22:00" class="flex-1 bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none text-white">
                        </div>
                    </div>

                    <div class="flex flex-col gap-2">
                        <label class="text-[11px] uppercase font-black text-gray-400 ml-1">Lugar de Atención</label>
                        <input type="text" name="lugar_atencion" value="<?= $modelo['lugar_atencion'] ?? '' ?>" placeholder="Depto propio, Hoteles..." class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none text-white">
                    </div>

                    <div class="flex flex-col gap-2">
                        <label class="text-[11px] uppercase font-black text-gray-400 ml-1">Extras y Pagos</label>
                        <div class="grid grid-cols-2 gap-2">
                            <select name="estacionamiento" class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none text-white">
                                <option value="0" <?= (isset($modelo['estacionamiento']) && $modelo['estacionamiento'] == 0) ? 'selected' : '' ?>>Sin Estacionamiento</option>
                                <option value="1" <?= (isset($modelo['estacionamiento']) && $modelo['estacionamiento'] == 1) ? 'selected' : '' ?>>Con Estacionamiento</option>
                            </select>
                            <input type="text" name="medios_pago" value="<?= $modelo['medios_pago'] ?? '' ?>" placeholder="Efectivo, Transfe..." class="bg-black/40 border-border-dark rounded-xl px-4 py-3 text-sm outline-none text-white">
                        </div>
                    </div>

                    <div class="flex flex-col gap-2">
                        <label class="text-[11px] uppercase font-black text-amber-500 ml-1">Precio Oferta (Opcional)</label>
                        <input type="number" name="precio_oferta" value="<?= $modelo['precio_oferta'] ?? '' ?>" placeholder="Ej: 40000" class="bg-black/40 border-amber-500/30 rounded-xl px-4 py-3 text-sm outline-none focus:border-amber-500 text-white">
                    </div>
                </div>
            </section>

            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark shadow-xl">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-bold text-primary flex items-center gap-2">
                        <span class="material-symbols-outlined">imagesmode</span> Galería de Fotos
                    </h2>
                    <label class="bg-primary/20 text-primary px-4 py-2 rounded-lg cursor-pointer text-xs font-black border border-primary/30 hover:bg-primary/30 transition-all uppercase tracking-widest text-white">
                        + ELEGIR FOTOS <input type="file" name="galeria[]" id="input-galeria" class="hidden" multiple accept="image/*">
                    </label>
                </div>
                <div id="gallery-grid" class="grid grid-cols-3 md:grid-cols-5 gap-3">
                    <?php if (!empty($galeria)): foreach ($galeria as $item): ?>
                        <div class="relative aspect-square rounded-xl overflow-hidden bg-black border border-border-dark group">
                            <img src="<?= base_url('uploads/modelos/fotos/'.$item['ruta']) ?>" class="w-full h-full object-cover">
                            <a href="<?= base_url('modelo/eliminar-media/'.$item['id']) ?>" onclick="return confirm('¿Eliminar esta foto?')" class="absolute inset-0 bg-black/60 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                <span class="material-symbols-outlined text-red-500">delete</span>
                            </a>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
            </section>
        </div>

        <div class="space-y-6">
            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark space-y-4 shadow-xl">
                <h2 class="text-center font-bold text-sm uppercase tracking-widest text-gray-500">Foto Principal</h2>
                <div class="aspect-[3/4] rounded-2xl border-2 border-dashed border-border-dark flex items-center justify-center overflow-hidden bg-black relative group shadow-inner">
                    <img id="main-preview" src="<?= (!empty($modelo['foto_principal'])) ? base_url('uploads/modelos/'.$modelo['foto_principal']) : '' ?>" class="w-full h-full object-cover <?= (empty($modelo['foto_principal']))?'hidden':'' ?>">
                    <span id="placeholder-icon" class="material-symbols-outlined text-4xl text-border-dark <?= (!empty($modelo['foto_principal']))?'hidden':'' ?>">add_a_photo</span>
                    <label class="absolute inset-0 cursor-pointer flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-all text-white">
                        <span class="text-[10px] font-bold uppercase">Cambiar Portada</span>
                        <input type="file" name="foto_principal" id="input-main" class="hidden" accept="image/*">
                    </label>
                </div>
                <button type="submit" class="w-full bg-primary py-4 rounded-2xl font-bold shadow-lg shadow-primary/20 hover:scale-[1.02] transition-all text-white uppercase tracking-widest text-xs">
                    GUARDAR CAMBIOS
                </button>
            </section>

            <section class="bg-surface-dark p-6 rounded-3xl border border-border-dark shadow-xl" id="seccion-documentos">
                <h2 class="text-gold font-bold mb-3 flex items-center gap-2 text-sm uppercase tracking-widest">
                    <span class="material-symbols-outlined">verified</span> Verificación de Identidad
                </h2>
                <?php 
                    $estaVerificada = ($modelo['verificada'] ?? 0) == 1;
                    $tieneDocumentos = (strlen($modelo['documento_identidad']) > 5) && (strlen($modelo['selfie_verificacion']) > 5);
                ?>
                <?php if ($estaVerificada): ?>
                    <div class="flex items-center gap-3 text-emerald-500 bg-emerald-500/10 p-4 rounded-xl border border-emerald-500/20">
                        <span class="material-symbols-outlined text-2xl">verified_user</span>
                        <div>
                            <p class="text-xs font-black uppercase italic">Perfil Verificado</p>
                        </div>
                    </div>
                <?php elseif ($tieneDocumentos): ?>
                    <div class="flex flex-col gap-3 bg-blue-500/10 p-4 rounded-xl border border-blue-500/30">
                        <div class="flex items-center gap-3 text-blue-400">
                            <span class="material-symbols-outlined animate-spin text-2xl">sync</span>
                            <p class="text-xs font-black uppercase italic leading-tight">En Revisión</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php if (!empty($modelo['observaciones_admin'])): ?>
                        <div class="mb-4 flex flex-col gap-2 rounded-xl border border-primary/40 bg-primary/5 p-4">
                            <p class="text-[11px] text-white leading-relaxed italic">"<?= esc($modelo['observaciones_admin']) ?>"</p>
                        </div>
                    <?php endif; ?>
                    <div class="space-y-3">
                    <input type="text" 
                           name="rut_verificacion" 
                           value="<?= $modelo['rut_verificacion'] ?? '' ?>" 
                           placeholder="RUT (12.345.678-9)" 
                           class="w-full bg-black/40 border-gold/20 focus:border-gold rounded-xl px-4 py-2 text-xs outline-none text-white transition-all" 
                           required>
                
                    <div class="grid grid-cols-2 gap-2">
                        <label class="bg-white/5 p-2 rounded-lg border border-border-dark text-[9px] flex flex-col items-center justify-center min-h-[80px] text-center cursor-pointer hover:bg-white/10 text-white transition-colors" id="preview-container-selfie">
                            <span class="material-symbols-outlined mb-1" id="icon-selfie">photo_camera</span>
                            <span id="text-selfie" class="font-bold">Selfie + RUT</span>
                            <input type="file" 
                                   name="selfie_verificacion" 
                                   class="hidden" 
                                   onchange="previewImage(this, 'preview-container-selfie', 'selfie')"
                                   <?= (empty($modelo['selfie_verificacion'])) ? 'required' : '' ?>>
                        </label>
                
                        <label class="bg-white/5 p-2 rounded-lg border border-border-dark text-[9px] flex flex-col items-center justify-center min-h-[80px] text-center cursor-pointer hover:bg-white/10 text-white transition-colors" id="preview-container-documento">
                            <span class="material-symbols-outlined mb-1" id="icon-documento">badge</span>
                            <span id="text-documento" class="font-bold">Foto RUT</span>
                            <input type="file" 
                                   name="documento_identidad" 
                                   class="hidden" 
                                   onchange="previewImage(this, 'preview-container-documento', 'documento')"
                                   <?= (empty($modelo['documento_identidad'])) ? 'required' : '' ?>>
                        </label>
                    </div>
                    
                    <?php if (empty($modelo['selfie_verificacion'])): ?>
                        <p class="text-[9px] text-gray-500 italic px-1">* Todos los campos de verificación son obligatorios la primera vez.</p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </section>
        </div>
    </form>
    <div class="h-32 lg:hidden w-full"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script>
<script>
const tsConfig = {
        create: true,          // Permite crear nuevos servicios escribiendo y dando Enter
        persist: false,
        createOnBlur: true,
        plugins: ['remove_button'],
        maxItems: 20,
        onItemAdd: function() {
            this.setTextboxValue(''); // Limpia el buscador al seleccionar
        }
    };

    // Inicializamos ambos selectores
    new TomSelect("#select-incluidos", tsConfig);
    new TomSelect("#select-adicionales", tsConfig);
    
    // Lógica de Comunas (RESTAURADA)
    const rSel = document.getElementById('region_id'), cSel = document.getElementById('ciudad_id');
    function loadC(rid, cur = null) {
        if (!rid) return;
        fetch('<?= base_url('api/get-ciudades/') ?>' + rid).then(r => r.json()).then(data => {
            cSel.innerHTML = '<option value="">Comuna</option>';
            data.forEach(c => { cSel.innerHTML += `<option value="${c.id}" ${cur==c.id?'selected':''}>${c.nombre}</option>`; });
        });
    }
    rSel.addEventListener('change', e => loadC(e.target.value));
    <?php if(isset($region_actual) && isset($modelo['ciudad_id'])): ?> loadC(<?= $region_actual ?>, <?= $modelo['ciudad_id'] ?>); <?php endif; ?>

    // Previews para Selfie y Documentos
    function previewImage(input, containerId, type) {
        const container = document.getElementById(containerId);
        const icon = document.getElementById('icon-' + type);
        const text = document.getElementById('text-' + type);
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                container.style.backgroundImage = `url('${e.target.result}')`;
                container.style.backgroundSize = 'cover';
                container.style.backgroundPosition = 'center';
                if(icon) icon.classList.add('hidden');
                text.innerHTML = '<span class="bg-black/80 px-2 py-1 rounded text-emerald-400 font-bold uppercase tracking-tighter">✓ Cargada</span>';
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    // Preview Portada Principal
    document.getElementById('input-main').addEventListener('change', e => {
        const reader = new FileReader();
        reader.onload = () => { 
            const img = document.getElementById('main-preview'); 
            img.src = reader.result; 
            img.classList.remove('hidden'); 
            document.getElementById('placeholder-icon').classList.add('hidden'); 
        }
        reader.readAsDataURL(e.target.files[0]);
    });

    // Preview Galería
    document.getElementById('input-galeria').addEventListener('change', e => {
        const grid = document.getElementById('gallery-grid');
        Array.from(e.target.files).forEach(f => {
            const reader = new FileReader();
            reader.onload = ev => {
                const d = document.createElement('div');
                d.className = "relative aspect-square rounded-xl overflow-hidden border-2 border-primary/50 shadow-lg";
                d.innerHTML = `<img src="${ev.target.result}" class="w-full h-full object-cover opacity-50"><div class="absolute inset-0 flex items-center justify-center text-[8px] font-black uppercase tracking-tighter text-white">Pre-cargada</div>`;
                grid.appendChild(d);
            }
            reader.readAsDataURL(f);
        });
    });
    // Listener para el formulario de guardado
document.getElementById('homeFilterForm')?.addEventListener('submit', function() {
    mostrarLoading();
});

// También lo vinculamos al botón de guardar específicamente por seguridad
const btnGuardar = document.querySelector('button[type="submit"]');
if(btnGuardar) {
    btnGuardar.addEventListener('click', function(e) {
        // Solo mostramos si el formulario es válido (HTML5 validation)
        const form = document.getElementById('homeFilterForm');
        if(form.checkValidity()) {
            mostrarLoading();
        }
    });
}

function mostrarLoading() {
    const overlay = document.getElementById('loading-overlay');
    const msg = document.getElementById('loading-msg');
    
    overlay.classList.remove('hidden');
    overlay.classList.add('flex');

    // Cambiamos el mensaje cada 3 segundos para mantener al usuario entretenido
    const mensajes = [
        "Optimizando tus fotografías...",
        "Aplicando marcas de agua de seguridad...",
        "Redimensionando para carga rápida...",
        "Casi listo, guardando información..."
    ];
    
    let i = 0;
    setInterval(() => {
        i = (i + 1) % mensajes.length;
        msg.innerText = mensajes[i];
    }, 3000);
}
function irADocumentos(e) {
    // 1. Detenemos cualquier acción por defecto del navegador
    if(e) e.preventDefault();

    const seccion = document.getElementById('seccion-documentos');
    if (seccion) {
        // 2. Usamos la API nativa que respeta el scroll-margin-top del CSS
        seccion.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start' 
        });
    }
}

// AJUSTE PARA EL LOADING: Asegúrate de que solo se active con el botón GUARDAR
const formFicha = document.querySelector('form[action*="guardar-ficha"]');
if(formFicha) {
    formFicha.addEventListener('submit', function(e) {
        // Solo si el botón presionado NO es el de documentos
        if (document.activeElement.innerText.indexOf('SUBIR DOCUMENTOS') === -1) {
            document.getElementById('loading-overlay').classList.remove('hidden');
            document.getElementById('loading-overlay').classList.add('flex');
        }
    });
}
</script>
<div id="loading-overlay" class="fixed inset-0 z-[100] hidden flex-col items-center justify-center bg-black/80 backdrop-blur-md">
    <div class="relative flex items-center justify-center">
        <div class="size-20 rounded-full border-4 border-white/10 border-t-primary animate-spin"></div>
        <span class="material-symbols-outlined absolute text-white animate-pulse">cloud_upload</span>
    </div>
    <div class="mt-6 text-center">
        <h3 id="loading-title" class="text-white font-black uppercase tracking-[3px] text-lg">Procesando Perfil</h3>
        <p id="loading-msg" class="text-[#b99da4] text-xs mt-2 uppercase font-bold tracking-widest italic">Optimizando y protegiendo tus fotografías...</p>
    </div>
    <div class="w-48 h-1 bg-white/10 rounded-full mt-6 overflow-hidden">
        <div class="h-full bg-primary animate-[loading_2s_ease-in-out_infinite]"></div>
    </div>
</div>

<style>
@keyframes loading {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
}

html {
    scroll-behavior: smooth;
}

/* Evitamos que el salto tape el título con el header */
#seccion-documentos {
    scroll-margin-top: 100px; 
}

/* Espacio al final para que el formulario no se corte */
form {
    padding-bottom: 120px !important;
}

/* Aseguramos que el overlay de carga esté realmente oculto al inicio */
#loading-overlay.hidden {
    display: none !important;
}
</style>
<?= $this->endSection() ?>