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

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

    <?php 
        // --- LÓGICA DE FILTRADO PREVIA ---
        $vips     = array_filter($modelos, fn($m) => ($m['membresia'] ?? '') === 'vip');
        $premiums = array_filter($modelos, fn($m) => ($m['membresia'] ?? '') === 'premium');
        $normales = array_filter($modelos, fn($m) => ($m['membresia'] ?? 'normal') === 'normal');
    ?>
<!-- Hero Section -->
<div class="relative w-full h-[320px] lg:h-[380px] bg-background-dark overflow-hidden">
    <div class="absolute inset-0 w-full h-full bg-cover bg-center" style="background-image: linear-gradient(to bottom, rgba(24, 17, 19, 0.8) 0%, rgba(24, 17, 19, 0.95) 100%), url('https://lh3.googleusercontent.com/aida-public/AB6AXuABgaJX8BkZ7Xl2DLvSkEE3N8oJKP6szDq19u-jUwnbp4aqPKny-kE4r9FR5p_yXF3-g-THvgBEDYcJ-I3cdU5sG8bOLp7VT3iMN3OhR4rGTcJkBdPJ29sL7OJteHwiWELO2o38oVQlCgM8Ocw7uYhIYYt4nCYs6GwpcJTA3rv7Cd2pqv5-Ze1ZIPuf9-fxAyn9JtvyZUX-aErEl5MgcLJ8X-NvQS79xW2n434EjIYxCUWxyy936RyuPPxWtEq5jQzAH8Q2FnLeVph3');">
    </div>

    <div class="relative z-10 h-full max-w-[1440px] mx-auto px-6 lg:px-20 flex flex-col justify-center items-center text-center">
        <span class="inline-block px-3 py-1 rounded-full bg-primary/20 border border-primary/40 text-primary text-[10px] font-bold mb-4 tracking-widest uppercase">
            Plataforma Verificada #1 en Chile
        </span>

        <h1 class="text-white text-4xl lg:text-6xl font-black leading-tight tracking-tighter mb-6">
            MODELOS <span id="rotating-text" class="text-primary transition-all duration-500 ease-in-out">DISPONIBLES</span> AHORA
        </h1>

        <div class="flex gap-3">
            <a href="<?= base_url('buscar?online=1') ?>">
                <button class="flex h-12 px-6 items-center justify-center rounded-xl bg-primary text-white text-xs font-black shadow-[0_0_15px_rgba(238,43,91,0.4)] hover:scale-105 transition-transform uppercase tracking-widest">
                    <span class="material-symbols-outlined mr-2 text-sm">bolt</span>
                    Ver Online
                </button>
            </a>
            <button class="flex h-12 px-6 items-center justify-center rounded-xl bg-white/5 border border-white/10 text-white text-xs font-black hover:bg-white/10 transition-colors uppercase tracking-widest backdrop-blur-sm">
                Explorar VIP
            </button>
        </div>
    </div>
</div>
<!-- Sticky Filters Bar -->
<div class="sticky top-[73px] z-40 bg-surface-dark/95 backdrop-blur border-b border-surface-border py-4 shadow-md hidden lg:block">
    <form action="<?= base_url('buscar') ?>" method="GET" id="homeFilterForm" class="max-w-[1440px] mx-auto px-6 lg:px-20 flex flex-col lg:flex-row gap-4 items-center justify-between">

        <div class="flex items-center gap-2 text-white font-medium whitespace-nowrap">
            <span class="material-symbols-outlined text-primary">filter_list</span>
            Filtros:
        </div>
        
        <div class="flex flex-1 w-full gap-3 overflow-x-auto pb-1 lg:pb-0 scrollbar-hide items-center">

            <div class="relative min-w-[150px]">
                <select name="categoria" class="w-full h-10 pl-4 pr-10 rounded-lg bg-background-dark border border-surface-border text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary appearance-none cursor-pointer" onchange="enviarLimpio()">
                    <option value="">Categoría</option>
                    <option value="escort" <?= (service('request')->getGet('categoria') == 'escort') ? 'selected' : '' ?>>Escort</option>
                    <option value="masajista" <?= (service('request')->getGet('categoria') == 'masajista') ? 'selected' : '' ?>>Masajista</option>
                </select>
                <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-[20px]">category</span>
            </div>

            <div class="relative min-w-[180px]">
                <select name="region" id="home_region_id" class="w-full h-10 pl-4 pr-10 rounded-lg bg-background-dark border border-surface-border text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary appearance-none cursor-pointer">
                    <option value="">Todas las Regiones</option>
                    <?php foreach($regiones as $r): ?>
                    <option value="<?= $r['id'] ?>" <?= (service('request')->getGet('region') == $r['id']) ? 'selected' : '' ?>><?= $r['nombre'] ?></option>
                    <?php endforeach; ?>
                </select>
                <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-[20px]">expand_more</span>
            </div>

            <div class="relative min-w-[180px]">
                <select name="ciudad" id="home_ciudad_id" onchange="enviarLimpio()" class="w-full h-10 pl-4 pr-10 rounded-lg bg-background-dark border border-surface-border text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary appearance-none cursor-pointer">
                    <option value="">Todas las Comunas</option>
                </select>
                <span class="material-symbols-outlined absolute right-3 top-2.5 text-gray-400 pointer-events-none text-[20px]">expand_more</span>
            </div>

            <div class="flex gap-2 min-w-max px-2">
                <label class="cursor-pointer">
                    <input type="checkbox" name="online" value="1" <?= service('request')->getGet('online') ? 'checked' : '' ?> class="hidden peer" onchange="enviarLimpio()">
                    <div class="h-10 px-4 rounded-full border border-surface-border flex items-center gap-2 text-xs font-bold transition-all peer-checked:bg-green-500 peer-checked:border-green-500 peer-checked:text-white text-gray-400 bg-background-dark hover:border-green-500">
                        <span class="w-2 h-2 rounded-full bg-green-500 <?= service('request')->getGet('online') ? 'bg-white animate-pulse' : '' ?>"></span>
                        ONLINE
                    </div>
                </label>

                <label class="cursor-pointer">
                    <input type="checkbox" name="con_historias" value="1" <?= service('request')->getGet('con_historias') ? 'checked' : '' ?> class="hidden peer" onchange="enviarLimpio()">
                    <div class="h-10 px-4 rounded-full border border-surface-border flex items-center gap-2 text-xs font-bold transition-all peer-checked:bg-gradient-to-r peer-checked:from-yellow-500 peer-checked:to-primary peer-checked:border-transparent peer-checked:text-white text-gray-400 bg-background-dark hover:border-primary">
                        <span class="material-symbols-outlined text-sm">history_toggle_off</span>
                        HISTORIAS
                    </div>
                </label>

                <label class="cursor-pointer">
                    <input type="checkbox" name="oferta" value="1" <?= service('request')->getGet('oferta') ? 'checked' : '' ?> class="hidden peer" onchange="enviarLimpio()">
                    <div class="h-10 px-4 rounded-full border border-surface-border flex items-center gap-2 text-xs font-bold transition-all peer-checked:bg-yellow-500 peer-checked:border-yellow-500 peer-checked:text-black text-gray-400 bg-background-dark hover:border-yellow-500">
                        <span class="material-symbols-outlined text-sm">local_offer</span>
                        OFERTAS
                    </div>
                </label>
            </div>
        </div>

        <div class="hidden lg:block w-px h-8 bg-surface-border mx-2"></div>

        <div class="relative w-full lg:w-auto min-w-[300px] flex gap-2">
            <div class="relative flex-1">
                <input name="q" id="input_busqueda" value="<?= service('request')->getGet('q') ?>" class="w-full h-10 pl-10 pr-4 rounded-lg bg-background-dark border border-surface-border text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary placeholder:text-gray-500" placeholder="Nombre o servicio..." type="text"/>
                <span class="material-symbols-outlined absolute left-3 top-2.5 text-gray-500 text-[20px]">search</span>
            </div>
            <button type="button" onclick="enviarLimpio()" class="bg-primary text-white px-4 rounded-lg font-bold text-sm hover:brightness-110 transition-all">
                BUSCAR
            </button>
        </div>
    </form>
</div>
<!-- filtros movile -->
<div id="mobile-filter-sidebar" class="fixed inset-0 z-[60] hidden">
    <div class="absolute inset-0 bg-black/80 backdrop-blur-sm" onclick="toggleMobileFilters()"></div>
    
    <div class="absolute bottom-0 left-0 right-0 bg-surface-dark rounded-t-[32px] p-8 border-t border-surface-border transition-transform transform translate-y-full" id="filter-content">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-white font-black uppercase tracking-widest text-lg">Ajustar Búsqueda</h3>
            <button type="button" onclick="toggleMobileFilters()" class="text-gray-400 p-2">
                <span class="material-symbols-outlined">close</span>
            </button>
        </div>

        <form id="mobileFilterForm" onsubmit="event.preventDefault(); enviarLimpio(true);" class="flex flex-col gap-5">
            
            <div class="space-y-2">
                <label class="text-[10px] font-bold text-primary uppercase ml-1">Categoría</label>
                <select name="categoria" class="w-full h-12 px-4 rounded-xl bg-background-dark border border-surface-border text-white outline-none focus:border-primary">
                    <option value="">Todas</option>
                    <option value="escort">Escort</option>
                    <option value="masajista">Masajista</option>
                </select>
            </div>

            <div class="space-y-2">
                <label class="text-[10px] font-bold text-primary uppercase ml-1">Región</label>
                <select name="region" id="mobile_region_id" onchange="cargarComunas(this.value, 'mobile_ciudad_id')" class="w-full h-12 px-4 rounded-xl bg-background-dark border border-surface-border text-white outline-none focus:border-primary">
                    <option value="">Todas las Regiones</option>
                    <?php foreach($regiones as $r): ?>
                        <option value="<?= $r['id'] ?>"><?= $r['nombre'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="space-y-2">
                <label class="text-[10px] font-bold text-primary uppercase ml-1">Comuna</label>
                <select name="ciudad" id="mobile_ciudad_id" class="w-full h-12 px-4 rounded-xl bg-background-dark border border-surface-border text-white outline-none focus:border-primary">
                    <option value="">Todas las Comunas</option>
                </select>
            </div>

            <div class="grid grid-cols-2 gap-3 py-2">
                 <label class="flex items-center justify-center gap-2 bg-background-dark border border-surface-border p-4 rounded-xl text-[10px] font-bold text-white has-[:checked]:border-green-500 has-[:checked]:bg-green-500/10 transition-all cursor-pointer">
                    <input type="checkbox" name="online" value="1" class="hidden"> 
                    <span class="w-2 h-2 rounded-full bg-green-500"></span> ONLINE
                 </label>
                 <label class="flex items-center justify-center gap-2 bg-background-dark border border-surface-border p-4 rounded-xl text-[10px] font-bold text-white has-[:checked]:border-primary has-[:checked]:bg-primary/10 transition-all cursor-pointer">
                    <input type="checkbox" name="con_historias" value="1" class="hidden"> 
                    <span class="material-symbols-outlined text-sm">history_toggle_off</span> HISTORIAS
                 </label>
            </div>

            <div class="space-y-2">
                <label class="text-[10px] font-bold text-primary uppercase ml-1">Nombre o Servicio</label>
                <input type="text" name="q" placeholder="Ej: morena, masajes..." class="w-full h-12 px-4 rounded-xl bg-background-dark border border-surface-border text-white outline-none focus:border-primary">
            </div>

            <button type="submit" class="w-full bg-primary text-white py-4 rounded-2xl font-black uppercase tracking-widest shadow-lg shadow-primary/20 mt-2 active:scale-95 transition-transform">
                APLICAR FILTROS
            </button>
        </form>
    </div>
</div>
<!-- Historias modelos -->
<?php if (!empty($modelosConHistorias)): ?>
<section class="max-w-[1440px] mx-auto px-6 lg:px-20 py-8 overflow-hidden">
    <div class="flex items-center gap-2 mb-6 border-l-4 border-primary pl-4">
        <h2 class="text-white text-xl font-black uppercase tracking-tighter italic">Momentos en Vivo</h2>
        <span class="bg-primary/20 text-primary text-[9px] font-bold px-2 py-0.5 rounded-full animate-pulse">LIVE</span>
    </div>

    <div class="flex gap-5 overflow-x-auto pb-4 scrollbar-hide snap-x select-none">
        <?php foreach($modelosConHistorias as $m): ?>
            <a href="<?= base_url('modelo/'.$m['slug']) ?>" class="flex flex-col items-center gap-2 shrink-0 snap-start group">
                <div class="p-[3px] rounded-full bg-gradient-to-tr from-yellow-400 via-primary to-purple-600 transition-transform duration-300 group-hover:scale-110 active:scale-95 shadow-lg shadow-primary/20">
                    <div class="p-[2px] bg-background-dark rounded-full">
                        <img src="<?= base_url('uploads/modelos/'.$m['foto_principal']) ?>" 
                             class="size-16 lg:size-20 rounded-full object-cover border-2 border-background-dark" 
                             alt="<?= $m['nombre_artistico'] ?>">
                    </div>
                </div>
                <span class="text-[10px] text-gray-400 font-black uppercase tracking-tighter group-hover:text-white transition-colors italic">
                    <?= explode(' ', $m['nombre_artistico'])[0] ?>
                </span>
            </a>
        <?php endforeach; ?>
    </div>
</section>
<?php endif; ?>

<!-- Modelos VIP -->
<div class="flex-1 max-w-[1440px] mx-auto w-full px-6 lg:px-20 py-12 space-y-20">

    <?php if (!empty($vips)): ?>
    <section>
        <div class="flex items-end justify-between mb-8 border-l-4 border-gold pl-4">
            <div>
                <h2 class="text-gold text-2xl lg:text-3xl font-black uppercase tracking-tighter">VIP GOLD EXCLUSIVE</h2>
                <p class="text-gray-500 text-xs uppercase tracking-widest font-bold text-shadow-sm">Máxima prioridad & Verificación garantizada</p>
            </div>
            <a class="text-gold text-[10px] font-black border-b border-gold uppercase hover:opacity-70 transition-opacity" href="#">Ver todas</a>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-4 gap-4">
            <?php foreach($vips as $m): ?>
            <a href="<?= base_url('modelo/'.$m['slug']) ?>" class="group relative aspect-[3/4] rounded-lg overflow-hidden border border-gold/20 hover:border-gold transition-all shadow-lg hover:shadow-gold/30">
                <img src="<?= base_url('uploads/modelos/'.$m['foto_principal']) ?>" class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110">

                <div class="absolute top-2 right-2 z-20 size-6 bg-gradient-to-br from-gold via-yellow-200 to-gold rounded-full flex items-center justify-center text-black shadow-lg">
                    <span class="material-symbols-outlined text-[14px] font-variation-settings: 'FILL' 1">star</span>
                </div>

                <?php if(($m['disponible_ahora'] ?? 0) == 1): ?>
                <div class="absolute top-2 left-2 flex items-center gap-1 bg-black/60 backdrop-blur-md px-2 py-0.5 rounded-full border border-green-500/50 z-20">
                    <span class="relative flex h-2 w-2">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                    </span>
                    <span class="text-[8px] text-green-500 font-black uppercase tracking-tighter">Online</span>
                </div>
                <?php endif; ?>

                <div class="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-90"></div>
                <div class="absolute bottom-3 left-3 right-3 text-left">
                    <p class="text-white text-[11px] font-black uppercase truncate italic tracking-tighter"><?= $m['nombre_artistico'] ?></p>
                    <div class="flex items-center gap-1 text-gold text-[8px] font-bold uppercase">
                        <span class="material-symbols-outlined text-[10px]">location_on</span>
                        <?= $m['ciudad_nombre'] ?? 'Chile' ?>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php if (!empty($premiums)): ?>
    <section>
        <div class="flex items-end justify-between mb-8 border-l-4 border-primary pl-4">
            <div>
                <h2 class="text-white text-2xl lg:text-3xl font-black uppercase tracking-tighter italic">Premium <span class="text-primary">Selection</span></h2>
                <p class="text-gray-500 text-xs uppercase tracking-widest font-bold">Modelos destacadas de la semana</p>
            </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-4 gap-4">
            <?php foreach($premiums as $m): ?>
            <div class="group relative flex flex-col bg-surface-dark rounded-xl overflow-hidden border border-surface-border hover:border-primary/50 transition-all shadow-2xl">
                <a href="<?= base_url('modelo/'.$m['slug']) ?>" class="relative aspect-[3/4] overflow-hidden">
                    <img src="<?= base_url('uploads/modelos/'.$m['foto_principal']) ?>" class="w-full h-full object-cover transition-transform duration-1000 group-hover:scale-105">

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

                    <div class="absolute top-3 right-3 bg-primary/90 backdrop-blur-sm text-white text-[9px] font-black px-2 py-1 rounded shadow-xl z-10 tracking-widest uppercase italic">Premium</div>
                    
                    <div class="absolute bottom-3 right-3 bg-black/80 backdrop-blur-md px-3 py-1.5 rounded-xl border border-white/10 text-white z-10">
                        <p class="text-xs font-black italic">$<?= number_format($m['precio_clp'] ?? 0, 0, ',', '.') ?></p>
                    </div>
                    <div class="absolute bottom-0 inset-x-0 h-1/2 bg-gradient-to-t from-black via-black/40 to-transparent"></div>
                </a>
                <div class="p-4 bg-gradient-to-b from-surface-dark to-black/40">
                    <h3 class="text-white text-lg font-black truncate italic tracking-tighter uppercase"><?= $m['nombre_artistico'] ?>, <?= $m['edad'] ?></h3>
                    <div class="flex items-center gap-1 text-gray-500 text-[10px] font-bold uppercase tracking-widest">
                        <span class="material-symbols-outlined text-xs text-primary">distance</span>
                        <?= $m['ciudad_nombre'] ?? 'Chile' ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <section class="bg-surface-dark/20 p-8 rounded-[2rem] border border-white/5 backdrop-blur-sm">
        <div class="flex flex-col md:flex-row md:items-center justify-between mb-8 gap-4">
            <div>
                <h2 class="text-white text-xl lg:text-2xl font-black uppercase tracking-widest italic">Independent <span class="text-primary underline decoration-2 underline-offset-4">Models</span></h2>
                <p class="text-gray-500 text-[10px] font-bold uppercase tracking-widest mt-1">Talento independiente verificado recientemente</p>
            </div>
            <span class="bg-primary/5 text-primary text-[10px] font-black px-4 py-2 rounded-xl border border-primary/20 italic tracking-tighter uppercase self-start">Actualizado ahora</span>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-6">
            <?php if (!empty($normales)): ?>
            <?php foreach(array_slice($normales, 0, 18) as $m): ?>
            <div class="flex flex-col gap-3 group cursor-pointer">
                <a href="<?= base_url('modelo/'.$m['slug']) ?>" class="relative aspect-[3/4] rounded-2xl overflow-hidden bg-background-dark border border-white/5 transition-all group-hover:border-primary/40 group-hover:translate-y-[-4px] shadow-xl">

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

                    <img class="w-full h-full object-cover transition-all duration-700 grayscale-[20%] group-hover:grayscale-0" src="<?= base_url('uploads/modelos/'.$m['foto_principal']) ?>"/>
                    <div class="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-80"></div>
                    <div class="absolute bottom-3 left-3 text-left">
                       <h4 class="text-white font-black text-xs truncate uppercase tracking-tighter italic"><?= $m['nombre_artistico'] ?></h4>
                       <p class="text-gray-400 text-[8px] font-bold uppercase truncate tracking-widest"><?= $m['ciudad_nombre'] ?? 'Chile' ?></p>
                   </div>
                </a>
            </div>
            <?php endforeach; ?>
            <?php else: ?>
            <div class="col-span-full py-16 text-center border border-dashed border-white/10 rounded-2xl">
                <span class="material-symbols-outlined text-primary text-4xl mb-4 opacity-50">search_off</span>
                <p class="text-gray-500 text-sm italic font-medium">Estamos buscando nuevos talentos para esta sección.</p>
            </div>
            <?php endif; ?>
        </div>
    </section>

</div>

<section class="w-full py-24 bg-gradient-to-b from-surface-dark to-background-dark border-t border-surface-border mt-20">
    <div class="max-w-4xl mx-auto px-6 text-center">
        <h2 class="text-4xl lg:text-6xl font-black text-white mb-6 uppercase tracking-tighter">¿Buscas visibilidad <span class="text-primary italic">total?</span></h2>
        <p class="text-gray-400 text-lg mb-10 max-w-2xl mx-auto font-body font-light">Únete a la plataforma más exclusiva de Chile. Más de 50.000 visitas mensuales garantizadas para tu perfil.</p>
        <button class="px-10 py-5 bg-white text-black font-black rounded-full text-sm hover:bg-primary hover:text-white transition-all shadow-[0_10px_30px_rgba(255,255,255,0.1)] uppercase tracking-widest">Publicar mi anuncio ahora</button>
    </div>
</section>
<div class="lg:hidden fixed bottom-6 right-6 z-50">
    <button type="button" onclick="toggleMobileFilters()" class="flex items-center gap-2 bg-primary text-white px-6 py-3 rounded-full shadow-2xl shadow-primary/40 font-black text-sm uppercase tracking-widest active:scale-95 transition-transform">
        <span class="material-symbols-outlined">tune</span>
        Filtrar
    </button>
</div>
<script>
/**
 * Redirige a /buscar eliminando parámetros vacíos
 * @param {boolean} isMobile Indica si el origen es el sidebar móvil
 */
function enviarLimpio(isMobile = false) {
    const formId = isMobile ? 'mobileFilterForm' : 'homeFilterForm';
    const form = document.getElementById(formId);
    const formData = new FormData(form);
    const params = new URLSearchParams();

    formData.forEach((value, key) => {
        // Solo agregamos a la URL si tiene valor
        if (value.trim() !== "") {
            params.append(key, value);
        }
    });

    // Redirigir
    window.location.href = "<?= base_url('buscar') ?>?" + params.toString();
}

/**
 * Función única para cargar comunas en cualquier select
 */
function cargarComunas(regionId, targetSelectId) {
    const targetSelect = document.getElementById(targetSelectId);
    if (!regionId) {
        targetSelect.innerHTML = '<option value="">Todas las Comunas</option>';
        return;
    }
    
    fetch('<?= base_url('api/get-ciudades/') ?>' + regionId)
        .then(r => r.json())
        .then(data => {
            targetSelect.innerHTML = '<option value="">Todas las Comunas</option>';
            data.forEach(c => {
                targetSelect.innerHTML += `<option value="${c.id}">${c.nombre}</option>`;
            });
        });
}


// Script para el texto rotativo
    document.addEventListener('DOMContentLoaded', function() {
        const rotatingTextElement = document.getElementById('rotating-text');
        const phrases = [
            'DISPONIBLES', 
            'EN SANTIAGO', 
            'EN VIÑA DEL MAR', 
            'EN CONCEPCIÓN', // Puedes agregar más ciudades
            'EN TU CIUDAD', 
            'VERIFICADAS'
        ];
        let currentPhraseIndex = 0;

        function updateRotatingText() {
            rotatingTextElement.style.opacity = 0; // Ocultar para la transición

            setTimeout(() => {
                rotatingTextElement.textContent = phrases[currentPhraseIndex];
                rotatingTextElement.style.opacity = 1; // Mostrar el nuevo texto

                currentPhraseIndex = (currentPhraseIndex + 1) % phrases.length;
            }, 500); // Duración de la transición de opacidad
        }

        // Iniciar la rotación
        setInterval(updateRotatingText, 3000); // Cambia cada 3 segundos
        updateRotatingText(); // Ejecutar una vez al cargar para mostrar la primera frase
    });
    
    const homeForm = document.getElementById('homeFilterForm');
    const homeRegionSelect = document.getElementById('home_region_id');
    const homeCiudadSelect = document.getElementById('home_ciudad_id');
    const categorySelect = homeForm.querySelector('select[name="categoria"]');
    
    document.getElementById('home_region_id').addEventListener('change', function() {
    const regionId = this.value;
    const ciudadSelect = document.getElementById('home_ciudad_id');

    if (!regionId) {
        ciudadSelect.innerHTML = '<option value="">Todas las Comunas</option>';
        // Si borra la región, quizás quieras enviar la búsqueda limpia
        enviarLimpio(); 
        return;
    }

    // Cargamos las comunas por API
    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 => {
                ciudadSelect.innerHTML += `<option value="${c.id}">${c.nombre}</option>`;
            });
            // NOTA: No enviamos el formulario aquí para dejar que el usuario elija ciudad
        })
        .catch(err => console.error('Error:', err));
});


// Opcional: Para que el botón "BUSCAR" también pase por aquí
document.getElementById('homeFilterForm').addEventListener('submit', limpiarFiltrosVacios);

    // 1. Lógica de cascada para ciudades
    homeRegionSelect.addEventListener('change', function() {
        const regionId = this.value;
        
        if (!regionId) {
            homeCiudadSelect.innerHTML = '<option value="">Todas las Comunas</option>';
            homeForm.submit(); 
            return;
        }

        // --- CAMBIO AQUÍ: Añadimos ?tipo=publico ---
        fetch('<?= base_url('api/get-ciudades/') ?>' + regionId + '?tipo=publico')
        .then(res => res.json())
        .then(data => {
            homeCiudadSelect.innerHTML = '<option value="">Todas las Comunas</option>';
            data.forEach(c => {
                homeCiudadSelect.innerHTML += `<option value="${c.id}">${c.nombre}</option>`;
            });
            
            // Opcional: Si quieres que al elegir región ya filtre
            // homeForm.submit(); 
        })
        .catch(err => console.error('Error:', err));
    });

    // 2. Evento para cuando elige una Ciudad específica
    homeCiudadSelect.addEventListener('change', () => {
        if(homeCiudadSelect.value !== "") homeForm.submit();
    });

    // 3. Evento para cuando elige una Categoría
    categorySelect.addEventListener('change', () => {
        homeForm.submit();
    });
</script>
<?= $this->endSection() ?>