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

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

<style>
    /* Ocultar scrollbar en los filtros rápidos si los añadieras */
    .no-scrollbar::-webkit-scrollbar { display: none; }
    .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

    /* Animación para el menú lateral en móvil */
    @media (max-width: 1023px) {
        #filter-sidebar {
            transform: translateX(-100%);
            transition: transform 0.3s ease-in-out;
        }
        #filter-sidebar.active {
            transform: translateX(0);
        }
    }
</style>

<div class="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 lg:hidden">
    <button onclick="toggleFilters()" class="flex items-center gap-2 bg-primary text-white px-8 py-3.5 rounded-full shadow-[0_10px_30px_rgba(238,43,91,0.4)] font-black text-sm uppercase tracking-widest active:scale-95 transition-all border border-white/10 backdrop-blur-sm">
        <span class="material-symbols-outlined text-xl">tune</span>
        Filtrar
    </button>
</div>

<div class="container mx-auto flex flex-col gap-8 px-4 py-6 lg:flex-row lg:px-8">

    <aside id="filter-sidebar" class="fixed inset-0 z-[60] lg:relative lg:z-0 lg:block lg:w-72 lg:shrink-0 hidden">
        
        <div class="absolute inset-0 bg-black/80 backdrop-blur-sm lg:hidden" onclick="toggleFilters()"></div>

        <form action="<?= base_url('buscar') ?>" method="GET" id="filterForm" class="relative z-10 h-full lg:h-auto">
            <div class="sticky top-24 flex h-full lg:h-auto flex-col gap-6 lg:rounded-xl border-r lg:border border-[#39282c] bg-surface-dark p-6 lg:p-5 shadow-2xl lg:shadow-xl w-[85%] max-w-xs lg:w-full overflow-y-auto">
                
                <div class="flex items-center justify-between border-b border-[#39282c] pb-4">
                    <div>
                        <h1 class="text-lg font-bold text-white uppercase italic">Filtros</h1>
                        <p class="text-xs text-[#b99da4]">Refina tu búsqueda</p>
                    </div>
                    <div class="flex items-center gap-4">
                        <a href="<?= base_url('buscar') ?>" class="text-xs font-medium text-primary hover:text-white">Limpiar</a>
                        <button type="button" onclick="toggleFilters()" class="lg:hidden text-white">
                            <span class="material-symbols-outlined">close</span>
                        </button>
                    </div>
                </div>

                <div class="space-y-4">
                    <p class="text-[10px] font-bold uppercase tracking-widest text-[#b99da4]">Estado y Promociones</p>
                    
                    <label class="flex cursor-pointer items-center justify-between group">
                        <span class="text-sm text-white group-hover:text-primary transition-colors">Disponible Ahora</span>
                        <div class="relative">
                            <input type="checkbox" name="online" value="1" <?= (isset($_GET['online']) && $_GET['online'] == '1') ? 'checked' : '' ?> class="peer sr-only">
                            <div class="h-5 w-9 rounded-full bg-[#181113] border border-[#39282c] after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:bg-gray-400 after:transition-all peer-checked:bg-green-500 peer-checked:after:translate-x-4 peer-checked:after:bg-white"></div>
                        </div>
                    </label>

                    <label class="flex cursor-pointer items-center justify-between group">
                        <span class="text-sm text-white group-hover:text-primary transition-colors">Con Historias</span>
                        <div class="relative">
                            <input type="checkbox" name="con_historias" value="1" <?= (isset($_GET['con_historias']) && $_GET['con_historias'] == '1') ? 'checked' : '' ?> class="peer sr-only">
                            <div class="h-5 w-9 rounded-full bg-[#181113] border border-[#39282c] after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:bg-gray-400 after:transition-all peer-checked:bg-primary peer-checked:after:translate-x-4 peer-checked:after:bg-white"></div>
                        </div>
                    </label>

                    <label class="flex cursor-pointer items-center justify-between group">
                        <span class="text-sm text-white group-hover:text-primary transition-colors">En Oferta</span>
                        <div class="relative">
                            <input type="checkbox" name="oferta" value="1" <?= (isset($_GET['oferta']) && $_GET['oferta'] == '1') ? 'checked' : '' ?> class="peer sr-only">
                            <div class="h-5 w-9 rounded-full bg-[#181113] border border-[#39282c] after:absolute after:top-[2px] after:left-[2px] after:h-4 after:w-4 after:rounded-full after:bg-gray-400 after:transition-all peer-checked:bg-yellow-500 peer-checked:after:translate-x-4 peer-checked:after:bg-white"></div>
                        </div>
                    </label>
                </div>

                <div class="space-y-3 pt-4 border-t border-[#39282c]">
                    <label class="flex items-center gap-2 text-sm font-medium text-white uppercase italic">
                        <span class="material-symbols-outlined text-primary text-[18px]">category</span>
                        Categoría
                    </label>
                    <select name="categoria" class="w-full rounded-lg border border-[#39282c] bg-[#181113] px-3 py-2 text-sm text-white focus:border-primary outline-none">
                        <option value="">Todas las categorías</option>
                        <option value="escort" <?= (isset($_GET['categoria']) && $_GET['categoria'] == 'escort') ? 'selected' : '' ?>>Escort</option>
                        <option value="masajista" <?= (isset($_GET['categoria']) && $_GET['categoria'] == 'masajista') ? 'selected' : '' ?>>Masajista</option>
                    </select>
                </div>

                <div class="space-y-3 pt-2 border-t border-[#39282c]">
                    <label class="flex items-center gap-2 text-sm font-medium text-white uppercase italic">
                        <span class="material-symbols-outlined text-primary text-[18px]">location_on</span>
                        Ubicación
                    </label>
                    <select name="region" id="region_id" class="w-full rounded-lg border border-[#39282c] bg-[#181113] px-3 py-2 text-sm text-white focus:border-primary outline-none">
                        <option value="">Todas las Regiones</option>
                        <?php foreach($regiones as $r): ?>
                            <option value="<?= $r['id'] ?>" <?= (isset($filtros['region']) && $filtros['region'] == $r['id']) ? 'selected' : '' ?>><?= $r['nombre'] ?></option>
                        <?php endforeach; ?>
                    </select>
                    <select name="ciudad" id="ciudad_id" class="w-full rounded-lg border border-[#39282c] bg-[#181113] px-3 py-2 text-sm text-white focus:border-primary outline-none">
                        <option value="">Todas las Comunas</option>
                    </select>
                </div>

                <div class="space-y-3 pt-4 border-t border-[#39282c]">
                    <label class="flex items-center gap-2 text-sm font-medium text-white uppercase italic">
                        <span class="material-symbols-outlined text-primary text-[18px]">search</span>
                        Servicio o Nombre
                    </label>
                    <input type="text" name="q" value="<?= $_GET['q'] ?? '' ?>" placeholder="Ej: Anal, Masaje..." class="w-full rounded-lg border border-[#39282c] bg-[#181113] px-3 py-2 text-sm text-white placeholder-[#b99da4] focus:border-primary outline-none">
                </div>

                <button type="submit" class="mt-2 w-full rounded-lg bg-primary py-3.5 text-sm font-black text-white shadow-lg shadow-primary/20 uppercase tracking-widest">
                    Aplicar Filtros
                </button>
            </div>
        </form>
    </aside>

    <main class="flex-1 min-w-0">
        <div class="mb-8 flex flex-col gap-2 sm:flex-row sm:items-end sm:justify-between">
            <div>
                <h1 class="text-3xl font-black uppercase tracking-tight text-white lg:text-4xl italic">
                    Directorio <span class="text-primary">Calientitas</span>
                </h1>
                <p class="mt-2 text-[#b99da4] flex items-center gap-2 text-xs uppercase font-bold tracking-wider">
                    <span class="flex h-2 w-2 rounded-full bg-green-500 animate-pulse"></span>
                    Encontradas: <span class="text-white"><?= count($modelos) ?></span> modelos
                </p>
            </div>
        </div>

        <section class="grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-4">
            <?php if(!empty($modelos)): ?>
            <?php foreach($modelos as $m): ?>
            <div class="group relative flex flex-col overflow-hidden rounded-xl bg-surface-dark shadow-md transition-all hover:shadow-xl hover:shadow-primary/10 border border-white/5">
                <div class="relative aspect-[3/4] overflow-hidden">
                    
                    <div class="h-full w-full <?= (isset($m['total_historias']) && $m['total_historias'] > 0) ? 'p-[3px] bg-gradient-to-tr from-yellow-400 via-primary to-purple-600 animate-gradient-xy' : '' ?>">
                        <img alt="<?= $m['nombre_artistico'] ?>" 
                        class="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105 <?= (isset($m['total_historias']) && $m['total_historias'] > 0) ? 'rounded-lg border-2 border-surface-dark' : '' ?>" 
                        src="<?= base_url('uploads/modelos/'.$m['foto_principal']) ?>"/>
                    </div>

                    <div class="absolute top-3 left-3 flex flex-col gap-2 z-10">
                        <?php if(isset($m['disponible_ahora']) && $m['disponible_ahora'] == 1): ?>
                        <span class="px-2 py-1 rounded-md bg-green-500 text-white text-[9px] font-black uppercase tracking-tighter flex items-center gap-1 shadow-lg">
                            <span class="w-1.5 h-1.5 rounded-full bg-white animate-pulse"></span> Online
                        </span>
                        <?php endif; ?>

                        <?php if(isset($m['precio_oferta']) && $m['precio_oferta'] > 0 && ($m['precio_clp'] ?? 0) > 0): 
                            $ahorro = round(100 - ($m['precio_oferta'] * 100 / $m['precio_clp']));
                        ?>
                            <span class="px-2 py-1 rounded-md bg-red-600 text-white text-[9px] font-black uppercase tracking-wide shadow-lg shadow-red-500/30 animate-pulse italic flex items-center gap-1">
                                <span class="material-symbols-outlined text-[10px]">sell</span>
                                <?= $ahorro ?>% OFF 🔥
                            </span>
                        <?php endif; ?>
                    </div>

                    <div class="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-black/60 opacity-0 backdrop-blur-[2px] transition-opacity duration-300 group-hover:opacity-100 z-20">
                        <a target="_blank" href="https://wa.me/<?= str_replace(['+', ' '], '', $m['telefono']) ?>" class="hidden lg:flex items-center gap-2 rounded-full bg-[#25D366] px-5 py-2 text-sm font-bold text-white shadow-lg transition-transform hover:scale-105">
                            <span class="material-symbols-outlined text-[18px]">chat</span> WhatsApp
                        </a>
                        
                        <a href="<?= base_url('modelo/'.$m['slug']) ?>" class="rounded-full bg-white px-5 py-2 text-sm font-bold text-black shadow-lg transition-transform hover:scale-105 text-center">
                            Ver Perfil
                        </a>
                    </div>

                    <div class="absolute bottom-3 right-3 bg-black/80 backdrop-blur-md px-3 py-1.5 rounded-2xl border border-white/10 z-10 flex flex-col items-end shadow-2xl">
                        <?php if(isset($m['precio_oferta']) && $m['precio_oferta'] > 0): ?>
                            <p class="text-[7px] font-bold text-gray-400 line-through leading-none mb-0.5 opacity-80">
                                $<?= number_format(($m['precio_clp'] ?? 0), 0, ',', '.') ?>
                            </p>
                            <p class="text-[11px] font-black text-yellow-400 italic leading-none tracking-tighter">
                                $<?= number_format($m['precio_oferta'], 0, ',', '.') ?>
                            </p>
                        <?php else: ?>
                            <p class="text-[10px] font-black text-white italic leading-none">
                                $<?= number_format($m['precio_clp'] ?? 0, 0, ',', '.') ?>
                            </p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="flex flex-col gap-1 p-3">
                    <div class="flex items-center justify-between">
                        <h3 class="text-sm font-black text-white truncate uppercase tracking-tighter"><?= $m['nombre_artistico'] ?>, <?= $m['edad'] ?></h3>
                        <?php if($m['verificada'] == 1): ?>
                        <span class="material-symbols-outlined text-[16px] text-blue-400" style="font-variation-settings: 'FILL' 1">verified</span>
                        <?php endif; ?>
                    </div>
                    <p class="text-[10px] text-[#b99da4] flex items-center gap-1 font-medium">
                        <span class="material-symbols-outlined text-[14px] text-primary">location_on</span>
                        <?= $m['ciudad_nombre'] ?? 'Chile' ?>
                    </p>
                    
                    <div class="mt-2 flex items-center justify-between">
                        <span class="rounded bg-primary/10 border border-primary/20 px-1.5 py-0.5 text-[8px] text-primary font-black uppercase tracking-widest">
                            <?= $m['categoria'] ?: 'Modelo' ?>
                        </span>
                        <?php if(isset($m['total_historias']) && $m['total_historias'] > 0): ?>
                        <div class="flex items-center gap-1">
                            <span class="text-[8px] text-yellow-500 font-black uppercase animate-pulse">Historias</span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php else: ?>
            <div class="col-span-full py-20 text-center bg-surface-dark rounded-3xl border border-dashed border-[#39282c]">
                <span class="material-symbols-outlined text-6xl text-[#39282c] mb-4">search_off</span>
                <p class="text-[#b99da4] font-medium">No encontramos modelos con estos criterios.</p>
                <a href="<?= base_url('buscar') ?>" class="text-primary text-sm font-black mt-4 inline-block uppercase tracking-widest hover:underline">Reiniciar filtros</a>
            </div>
            <?php endif; ?>
        </section>
    </main>
</div>

<script>
    const regionSelect = document.getElementById('region_id');
    const ciudadSelect = document.getElementById('ciudad_id');
    const filterForm   = document.getElementById('filterForm');
    const filterSidebar = document.getElementById('filter-sidebar');

    // 1. Usamos una variable de estado que no depende del DOM
let sidebarState = { isOpen: false };

// 2. Función principal optimizada
function toggleFilters() {
    const sidebar = document.getElementById('filter-sidebar');
    if (!sidebar) return;

    if (!sidebarState.isOpen) {
        // ABRIR
        sidebar.classList.remove('hidden');
        // Forzamos al navegador a reconocer el cambio antes de animar
        sidebar.offsetHeight; 
        sidebar.classList.add('active');
        document.body.style.overflow = 'hidden';
        sidebarState.isOpen = true;
    } else {
        // CERRAR
        sidebar.classList.remove('active');
        setTimeout(() => {
            if (!sidebarState.isOpen) {
                sidebar.classList.add('hidden');
            }
        }, 300);
        document.body.style.overflow = 'auto';
        sidebarState.isOpen = false;
    }
}

// 3. SEGURO DE VIDA: Si por alguna razón el botón de HTML falla, 
// este escuchador global atrapará el clic.
window.addEventListener('click', function(e) {
    // Si el clic fue en el botón de filtrar (o en algo dentro del botón)
    if (e.target.closest('button') && e.target.closest('button').getAttribute('onclick') === 'toggleFilters()') {
        console.log("Clic detectado por el escuchador global");
        // No necesitamos hacer nada extra aquí porque el onclick ya se dispara,
        // pero esto asegura que el navegador mantenga el foco en la función.
    }
});

    function loadComunas(regionId, selectedCiudad = null) {
        if (!regionId) {
            ciudadSelect.innerHTML = '<option value="">Todas las Comunas</option>';
            return;
        }

        fetch('<?= base_url('api/get-ciudades/') ?>' + regionId + '?tipo=publico')
            .then(res => res.json())
            .then(data => {
                ciudadSelect.innerHTML = '<option value="">Todas las Comunas</option>';
                data.forEach(c => {
                    const isSelected = (selectedCiudad == c.id) ? 'selected' : '';
                    ciudadSelect.innerHTML += `<option value="${c.id}" ${isSelected}>${c.nombre}</option>`;
                });
            })
            .catch(err => console.error('Error al cargar comunas:', err));
    }

    regionSelect.addEventListener('change', function() {
        loadComunas(this.value);
    });

    ciudadSelect.addEventListener('change', () => {
        filterForm.submit();
    });

    <?php if(isset($filtros['region'])): ?>
        loadComunas(<?= $filtros['region'] ?>, <?= $filtros['ciudad'] ?? 'null' ?>);
    <?php endif; ?>
</script>
<?= $this->endSection() ?>