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

<?= $this->section('content') ?>
<div class="fixed bottom-0 left-0 right-0 z-[100] lg:hidden bg-[#1a0f11]/90 backdrop-blur-xl border-t border-white/10 p-4 shadow-[0_-10px_40px_rgba(0,0,0,0.5)]">
    <div class="flex gap-3 max-w-md mx-auto">
        <a href="tel:<?= str_replace(['+', ' '], '', $modelo['telefono']) ?>"
           onclick="contarClic(<?= $modelo['id'] ?>, 'llamada')"
           class="flex-1 flex items-center justify-center gap-2 bg-white/10 text-white font-black py-4 rounded-2xl border border-white/10 active:scale-95 transition-all">
            <span class="material-symbols-outlined">call</span>
            <span class="text-[10px] uppercase tracking-widest font-black">Llamar</span>
        </a>
        <a href="https://wa.me/<?= str_replace(['+', ' '], '', $modelo['telefono']) ?>?text=Hola <?= $modelo['nombre_artistico'] ?>, te vi en Calientitas" 
           target="_blank"
           onclick="contarClic(<?= $modelo['id'] ?>, 'whatsapp')"
           class="flex-[2] flex items-center justify-center gap-2 bg-[#25D366] text-white font-black py-4 rounded-2xl shadow-lg shadow-green-500/20 active:scale-95 transition-all">
            <span class="material-symbols-outlined">chat</span>
            <span class="text-[10px] uppercase tracking-widest font-black">WhatsApp</span>
        </a>
    </div>
</div>

<div class="layout-container flex h-full grow flex-col max-w-[1400px] mx-auto w-full px-4 lg:px-8 pb-24 lg:pb-10">
<!-- Breadcrumbs -->
<div class="lg:hidden mt-6 mb-2 px-1">
    <button onclick="window.history.back()" class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/5 border border-white/10 text-gray-400 active:bg-primary/20 active:text-primary transition-all shadow-sm">
        <span class="material-symbols-outlined text-[18px]">arrow_back</span>
        <span class="text-[10px] font-black uppercase tracking-[2px]">Volver a resultados</span>
    </button>
</div>
<div class="py-4">
    <div class="flex flex-wrap items-center gap-2 text-sm">
        <a class="text-gray-500 dark:text-[#b99da4] hover:text-primary" href="/">Inicio</a>
        <span class="text-gray-500 dark:text-[#b99da4] material-symbols-outlined text-[12px]">chevron_right</span>
        <a class="text-gray-500 dark:text-[#b99da4] hover:text-primary" href="#"><?= $modelo['ciudad_nombre'] ?? 'Chile' ?></a>
        <span class="text-gray-500 dark:text-[#b99da4] material-symbols-outlined text-[12px]">chevron_right</span>
        <span class="text-gray-900 dark:text-white font-medium"><?= $modelo['nombre_artistico'] ?></span>
    </div>
</div>
<div class="lg:hidden mb-6 mt-4">
    <div class="flex justify-between items-start">
        <div>
            <div class="flex items-center gap-2 mb-1">
                <h1 class="text-4xl font-black text-white leading-tight uppercase italic"><?= $modelo['nombre_artistico'] ?></h1>
                <?php if ($modelo['verificada'] == 1): ?>
                    <span class="material-symbols-outlined text-blue-400 fill-1 text-[28px]" style="font-variation-settings: 'FILL' 1;">verified</span>
                <?php endif; ?>
            </div>
            <div class="flex items-center gap-1 text-sm text-primary font-bold uppercase tracking-widest">
                <span class="material-symbols-outlined text-[18px]">location_on</span>
                <span><?= $modelo['ciudad_nombre'] ?? 'Chile' ?></span>
            </div>
        </div>
    </div>
</div>

<div class="grid grid-cols-1 lg:grid-cols-12 gap-8 mt-2">
<!-- LEFT COLUMN: Gallery & Visuals (Span 7) -->
<div class="lg:col-span-7 flex flex-col gap-4">
<!-- Main Image Hero -->
<div class="lg:col-span-7 flex flex-col gap-4">
    
    <div class="relative w-full aspect-[3/4] md:aspect-[4/3] rounded-3xl overflow-hidden group bg-surface-dark border border-white/5 cursor-zoom-in">
        <img id="main-hero-img" 
        src="<?= base_url('uploads/modelos/'.$modelo['foto_principal']) ?>" 
        onclick="openLightbox(0)" 
        class="w-full h-full object-cover transition-all duration-500 group-hover:scale-105"
        alt="Foto Principal">
        
        <div class="absolute bottom-4 right-4 bg-black/40 backdrop-blur-md text-white p-2 rounded-full border border-white/10 opacity-0 group-hover:opacity-100 transition-opacity">
            <span class="material-symbols-outlined text-sm">fullscreen</span>
        </div>

        <div class="absolute top-4 left-4 bg-black/60 backdrop-blur-md text-white px-4 py-2 rounded-full flex items-center gap-2 border border-white/10 z-20">
            <span class="material-symbols-outlined text-yellow-400 text-sm fill-1">trophy</span>
            <span class="text-[10px] font-black uppercase tracking-widest">#4 EN <?= $modelo['ciudad_nombre'] ?? 'CHILE' ?></span>
        </div>
    </div>

    <div class="flex gap-3 overflow-x-auto scrollbar-hide pb-2 snap-x snap-mandatory" id="gallery-container">
        
        <div class="shrink-0 snap-start">
            <img src="<?= base_url('uploads/modelos/'.$modelo['foto_principal']) ?>" 
            onclick="changeHero(this.src, this, 0)"
            class="gallery-item thumb-item size-20 md:size-24 rounded-2xl object-cover cursor-pointer border-2 border-primary ring-2 ring-primary/20 transition-all"
            alt="Miniatura">
        </div>

        <?php foreach($galeria as $index => $foto): ?>
            <div class="shrink-0 snap-start">
                <img src="<?= base_url('uploads/modelos/fotos/'.$foto['ruta']) ?>" 
                onclick="changeHero(this.src, this, <?= $index + 1 ?>)"
                class="gallery-item thumb-item size-20 md:size-24 rounded-2xl object-cover cursor-pointer border-2 border-transparent hover:border-white/30 transition-all opacity-70 hover:opacity-100"
                alt="Miniatura">
            </div>
        <?php endforeach; ?>
    </div>
</div>
<!-- Thumbnail Slider -->
<!-- Historias Slider -->
<div class="lg:hidden mb-8 mt-2">
    <div class="flex items-center justify-between mb-4 px-1">
        <h4 class="text-[11px] font-black uppercase tracking-[2px] text-primary flex items-center gap-2">
            <span class="relative flex h-2 w-2">
                <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"></span>
                <span class="relative inline-flex rounded-full h-2 w-2 bg-primary"></span>
            </span>
            Historias Recientes
        </h4>
        <?php if (!empty($historias)): ?>
            <button onclick="abrirVisorHistorias(0)" class="text-[10px] font-black uppercase text-white bg-white/5 px-3 py-1 rounded-full border border-white/10">Ver todas</button>
        <?php endif; ?>
    </div>
    
    <div class="flex gap-4 overflow-x-auto no-scrollbar pb-2 px-1">
        <?php if (empty($historias)): ?>
            <p class="text-[10px] text-gray-500 italic uppercase tracking-widest">Sin historias activas</p>
        <?php else: ?>
            <?php foreach ($historias as $index => $h): ?>
                <div class="flex flex-col items-center gap-2 shrink-0 group active:scale-95 transition-all" onclick="abrirVisorHistorias(<?= $index ?>)">
                    <div class="p-[2.5px] rounded-full bg-gradient-to-tr from-yellow-400 via-primary to-purple-600 shadow-lg shadow-primary/20">
                        <div class="size-16 rounded-full border-2 border-[#1a0f11] bg-cover bg-center bg-no-repeat shadow-inner" 
                        style='background-image: url("<?= base_url('uploads/modelos/historias/' . $h['ruta']) ?>");'>
                        
                        <?php 
                        $ext = strtolower(pathinfo($h['ruta'], PATHINFO_EXTENSION));
                        if (in_array($ext, ['mp4', 'mov', 'webm'])): 
                           ?>
                           <div class="w-full h-full flex items-center justify-center bg-black/30 rounded-full backdrop-blur-[1px]">
                             <span class="material-symbols-outlined text-white text-2xl fill-1">play_arrow</span>
                           </div>
                        <?php endif; ?>
                        </div>
                    </div>
                    <span class="text-[9px] font-black text-[#b99da4] uppercase tracking-tighter">
                        <?= time_ago($h['creado_at']) ?>
                    </span>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
<!-- Description & Bio -->
<div class="bg-white dark:bg-surface-dark rounded-xl p-6 shadow-sm border border-gray-100 dark:border-[#39282c]">
    <div class="lg:hidden grid grid-cols-3 gap-2 mb-6">
    <div class="flex flex-col items-center justify-center p-3 rounded-2xl bg-white/5 border border-white/5">
        <span class="text-[9px] text-primary font-black uppercase tracking-tighter mb-1">Edad</span>
        <span class="text-lg font-black text-white leading-none"><?= $modelo['edad'] ?></span>
    </div>

    <div class="flex flex-col items-center justify-center p-3 rounded-2xl bg-white/5 border border-white/5">
        <span class="text-[9px] text-primary font-black uppercase tracking-tighter mb-1">Altura</span>
        <span class="text-lg font-black text-white leading-none">
            <?= !empty($modelo['estatura']) ? str_replace(',', '.', $modelo['estatura']) . 'm' : '--' ?>
        </span>
    </div>

    <div class="flex flex-col items-center justify-center p-3 rounded-2xl bg-white/5 border border-white/5">
        <span class="text-[9px] text-primary font-black uppercase tracking-tighter mb-1">Medidas</span>
        <span class="text-[13px] font-black text-white leading-none truncate w-full text-center">
            <?= !empty($modelo['medidas']) ? $modelo['medidas'] : '--' ?>
        </span>
    </div>
</div>
    <h3 class="text-xl font-bold mb-4">Sobre Mí</h3>
    <div class="prose prose-invert max-w-none text-gray-600 dark:text-[#d0c0c4] text-sm leading-relaxed">
        <?php if (!empty($modelo['descripcion'])): ?>
            <?php 
            // Convertimos los saltos de línea de la BD en párrafos HTML
            // nl2br es bueno, pero para mantener tus clases <p class="mb-3"> 
            // lo ideal es limpiar el texto y mostrarlo así:
            echo '<p class="mb-3">' . nl2br(htmlspecialchars($modelo['descripcion'])) . '</p>'; 
            ?>
        <?php else: ?>
            <p class="mb-3">
                ¡Hola! Soy <?= $modelo['nombre_artistico'] ?>. 
                Te invito a conocer mis servicios y disfrutar de un momento inolvidable. 
                Contáctame para más detalles.
            </p>
        <?php endif; ?>
    </div>


    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-8 pt-6 border-t border-gray-100 dark:border-[#39282c]">
        
        <div class="flex items-center gap-4">
            <div class="size-12 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                <span class="material-symbols-outlined">schedule</span>
            </div>
            <div>
                <p class="text-white font-bold leading-none"><?= $modelo['horario_tipo'] ?></p>
                <p class="text-text-muted text-xs"><?= $modelo['horario_detalle'] ?: 'Consulta por interno' ?></p>
            </div>
        </div>

        <div class="flex items-center gap-4">
            <div class="size-12 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                <span class="material-symbols-outlined">apartment</span>
            </div>
            <div>
                <p class="text-white font-bold leading-none">Lugar de Atención</p>
                <p class="text-text-muted text-xs"><?= $modelo['lugar_atencion'] ?: 'A convenir' ?></p>
            </div>
        </div>

        <div class="flex items-center gap-4">
            <div class="size-12 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-500">
                <span class="material-symbols-outlined">payments</span>
            </div>
            <div>
                <p class="text-white font-bold leading-none">$<?= number_format($modelo['precio_clp'], 0, ',', '.') ?></p>
                <p class="text-text-muted text-xs">Valor normal por hora</p>
            </div>
        </div>

        <?php if(!empty($modelo['precio_oferta'])): ?>
            <div class="flex items-center gap-4">
                <div class="size-12 rounded-full bg-amber-500/10 flex items-center justify-center text-amber-500">
                    <span class="material-symbols-outlined">sell</span>
                </div>
                <div>
                    <p class="text-amber-500 font-bold leading-none">$<?= number_format($modelo['precio_oferta'], 0, ',', '.') ?></p>
                    <p class="text-text-muted text-xs">¡Precio en oferta!</p>
                </div>
            </div>
        <?php endif; ?>

        <div class="flex items-center gap-4">
            <div class="size-12 rounded-full bg-blue-500/10 flex items-center justify-center text-blue-500">
                <span class="material-symbols-outlined">local_parking</span>
            </div>
            <div>
                <p class="text-white font-bold leading-none">Estacionamiento</p>
                <p class="text-text-muted text-xs"><?= ($modelo['estacionamiento'] == 1) ? 'Disponible y Privado' : 'No cuenta con propio' ?></p>
            </div>
        </div>

        <div class="flex items-center gap-4">
            <div class="size-12 rounded-full bg-purple-500/10 flex items-center justify-center text-purple-500">
                <span class="material-symbols-outlined">credit_card</span>
            </div>
            <div>
                <p class="text-white font-bold leading-none">Medios de Pago</p>
                <p class="text-text-muted text-xs"><?= $modelo['medios_pago'] ?: 'Efectivo / Transferencia' ?></p>
            </div>
        </div>
    </div>

</div>

<div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-8">
    <div class="bg-white/5 border border-white/5 p-5 rounded-2xl">
        <h4 class="text-white font-bold text-sm mb-4 flex items-center gap-2">
            <span class="material-symbols-outlined text-primary text-lg">check_circle</span>
            Servicios Incluidos
        </h4>
        <div class="flex flex-wrap gap-2">
            <?php 
            $incluidos = explode(',', $modelo['servicios_incluidos']);
            foreach($incluidos as $tag): if(trim($tag) != ''): ?>
                <span class="bg-primary/10 text-primary text-[11px] px-3 py-1.5 rounded-lg font-bold border border-primary/20">
                    <?= trim($tag) ?>
                </span>
            <?php endif; endforeach; ?>
        </div>
    </div>

    <div class="bg-white/5 border border-white/5 p-5 rounded-2xl">
        <h4 class="text-white font-bold text-sm mb-4 flex items-center gap-2">
            <span class="material-symbols-outlined text-gold text-lg">add_circle</span>
            Servicios Adicionales
        </h4>
        <div class="flex flex-wrap gap-2">
            <?php 
            $extras = explode(',', $modelo['servicios_adicionales']);
            foreach($extras as $tag): if(trim($tag) != ''): ?>
                <span class="bg-gold/10 text-gold text-[11px] px-3 py-1.5 rounded-lg font-bold border border-gold/20">
                    <?= trim($tag) ?>
                </span>
            <?php endif; endforeach; ?>
        </div>
    </div>
</div>
<div class="mt-10 space-y-6">
    <div id="seccion-resenas" class="flex items-center justify-between border-b border-white/5 pb-4">
        <h3 class="text-xl font-bold text-white flex items-center gap-2">
            <span class="material-symbols-outlined text-primary">reviews</span>
            Experiencias de Usuarios
        </h3>
        <span class="text-xs font-bold text-text-muted uppercase tracking-widest">
            <?= count($resenas) ?> Reseñas
        </span>
    </div>

    <?php if (empty($resenas)): ?>
        <div class="py-10 text-center bg-white/5 rounded-3xl border border-dashed border-white/10">
            <p class="text-sm text-text-muted italic">Aún no hay reseñas para esta modelo. ¡Sé el primero en comentar!</p>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 gap-4">
            <?php foreach ($resenas as $r): ?>
                <div class="bg-[#181113] border border-[#2a1d21] p-6 rounded-2xl space-y-3">
                    <div class="flex justify-between items-start">
                        <div>
                            <p class="text-white font-bold text-sm"><?= $r['nombre'] ?></p>
                            <p class="text-[10px] text-text-muted uppercase font-bold tracking-tighter">
                                <?= date('d M, Y', strtotime($r['created_at'])) ?>
                            </p>
                        </div>
                        <div class="flex text-gold">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <span class="material-symbols-outlined text-sm <?= $i <= $r['puntuacion'] ? 'fill-1' : '' ?>" 
                                  style="font-variation-settings: 'FILL' <?= $i <= $r['puntuacion'] ? '1' : '0' ?>;">star</span>
                                  <?php endfor; ?>
                              </div>
                          </div>
                          <p class="text-gray-300 text-sm leading-relaxed">
                            "<?= $r['comentario'] ?>"
                        </p>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    <?php if (session()->get('rol') == 'usuario'): ?>
    <form action="<?= base_url('modelo/dejar-resena') ?>" method="POST" class="bg-[#181113] p-6 rounded-2xl mt-8">
        <?= csrf_field() ?>
        <input type="hidden" name="modelo_id" value="<?= $modelo['id'] ?>">
        
        <h3 class="text-white font-bold mb-4 text-lg text-primary">Deja tu reseña</h3>
        
        <div class="mb-4">
            <label class="text-xs text-text-muted font-bold block mb-2 uppercase">Calificación</label>
            <select name="puntuacion" class="w-full bg-black border-[#2a1d21] rounded-xl text-white">
                <option value="5">⭐⭐⭐⭐⭐ (Excelente)</option>
                <option value="4">⭐⭐⭐⭐ (Muy buena)</option>
                <option value="3">⭐⭐⭐ (Buena)</option>
                <option value="2">⭐⭐ (Regular)</option>
                <option value="1">⭐ (No lo recomiendo)</option>
            </select>
        </div>

        <div class="mb-4">
            <textarea name="comentario" required placeholder="Cuéntanos tu experiencia..." 
            class="w-full bg-black border-[#2a1d21] rounded-xl text-white p-4 h-24"></textarea>
        </div>

        <button type="submit" class="w-full bg-primary py-3 rounded-xl font-bold text-white uppercase tracking-widest text-sm hover:brightness-110">
            Enviar Reseña para aprobación
        </button>
    </form>
<?php elseif(!session()->get('isLoggedIn')): ?>
<div class="p-6 bg-[#181113] rounded-2xl text-center mt-8 border border-dashed border-[#2a1d21]">
    <p class="text-sm text-text-muted mb-3">Debes estar registrado para dejar una reseña.</p>
    <a href="<?= base_url('login') ?>" class="text-primary font-bold hover:underline">Iniciar Sesión</a>
</div>
<?php endif; ?>
</div>

<div class="lg:col-span-5 flex flex-col gap-6 relative hidden lg:block">
    <div class="bg-white dark:bg-surface-dark rounded-xl p-6 shadow-xl border border-gray-200 dark:border-[#39282c] lg:sticky lg:top-24 z-10">
        <div class="flex justify-between items-start mb-4">
            <div>
                <div class="flex items-center gap-2 mb-1">
                    <h1 class="text-3xl font-black text-gray-900 dark:text-white leading-tight">
                        <?= $modelo['nombre_artistico'] ?>
                    </h1>
                    <?php if ($modelo['verificada'] == 1): ?>
                        <div class="bg-primary/10 p-1 rounded-full" title="Cuenta Verificada">
                            <span class="material-symbols-outlined text-yellow-500 fill-1 text-[24px]" style="font-variation-settings: 'FILL' 1, 'wght' 700;">verified</span>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="flex items-center gap-1 text-sm text-gray-500 dark:text-[#b99da4]">
                    <span class="material-symbols-outlined text-[16px]">location_on</span>
                    <span><?= $modelo['ciudad_nombre'] ?? 'Chile' ?></span>
                </div>
            </div>
            <div class="flex flex-col items-end">
                <?php if (isset($total_resenas) && $total_resenas > 0): ?>
                    <div class="flex items-center text-yellow-400">
                        <span class="material-symbols-outlined text-[20px] fill-1" style="font-variation-settings: 'FILL' 1;">star</span>
                        <span class="text-lg font-bold ml-1 text-gray-900 dark:text-white">
                            <?= number_format($promedio_resenas, 1) ?>
                        </span>
                    </div>
                    <a class="text-xs text-primary underline decoration-primary/30 hover:decoration-primary transition-all" href="#seccion-resenas">
                        <?= $total_resenas ?> reseñas
                    </a>
                <?php else: ?>
                    <div class="flex items-center text-gray-400 opacity-60">
                        <span class="material-symbols-outlined text-[18px]">star_rate</span>
                        <span class="text-[10px] font-bold ml-1 uppercase">Sin reseñas</span>
                    </div>
                    <span class="text-[9px] text-gray-500 italic">¡Sé el primero!</span>
                <?php endif; ?>
            </div>
        </div>

        <div class="flex flex-wrap gap-2 mb-6">
            <?php if (isset($modelo['membresia'])): ?>
                <?php if ($modelo['membresia'] === 'vip'): ?>
                    <div class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-yellow-500/10 border border-yellow-500/20 text-yellow-600 dark:text-yellow-400 shadow-sm">
                        <span class="material-symbols-outlined text-[16px] filled" style="font-variation-settings: 'FILL' 1">diamond</span>
                        <span class="text-xs font-bold uppercase tracking-wider">VIP Gold</span>
                    </div>
            
                <?php elseif ($modelo['membresia'] === 'premium'): ?>
                    <div class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-blue-500/10 border border-blue-500/20 text-blue-600 dark:text-blue-400 shadow-sm">
                        <span class="material-symbols-outlined text-[16px]">verified</span>
                        <span class="text-xs font-bold uppercase tracking-wider">Premium</span>
                    </div>
                <?php endif; ?>
                
            <?php endif; ?>

            <?php if ($modelo['disponible_ahora'] == 1): ?>
                <div class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-500/10 border border-green-500/20 text-green-600 dark:text-green-400">
                    <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-[10px] font-black uppercase tracking-widest">Disponible Ahora</span>
                </div>
            <?php endif; ?>
        </div>

        <div class="flex flex-col gap-3 mb-6">
    <a href="https://wa.me/<?= str_replace(['+', ' '], '', $modelo['telefono']) ?>?text=Hola <?= $modelo['nombre_artistico'] ?>, te vi en Calientitas" 
   target="_blank"
   onclick="contarClic(<?= $modelo['id'] ?>, 'whatsapp')"
   class="w-full flex items-center justify-center gap-2 bg-[#25D366] hover:bg-green-500 text-white font-bold text-lg py-3 rounded-xl shadow-lg shadow-green-900/20 transition-all hover:-translate-y-0.5 cursor-pointer <?= ($modelo['disponible_ahora'] == 1) ? 'ring-2 ring-green-400 ring-offset-2 ring-offset-background-dark' : '' ?>">
    
    <span class="material-symbols-outlined <?= ($modelo['disponible_ahora'] == 1) ? 'animate-bounce' : '' ?>">
        <?= ($modelo['disponible_ahora'] == 1) ? 'bolt' : 'chat' ?>
    </span>
    
    <span>
        <?= ($modelo['disponible_ahora'] == 1) ? 'Contactar Ahora (Online)' : 'Contactar por WhatsApp' ?>
    </span>
</a>
    
    <div class="flex gap-3">
        <a href="tel:<?= str_replace(['+', ' '], '', $modelo['telefono']) ?>"
           onclick="contarClic(<?= $modelo['id'] ?>, 'llamada')"
           class="flex-1 flex items-center justify-center gap-2 bg-gray-100 dark:bg-[#39282c] hover:bg-gray-200 dark:hover:bg-[#4a353a] text-gray-900 dark:text-white font-semibold py-3 rounded-xl transition-colors cursor-pointer text-center">
            <span class="material-symbols-outlined">call</span>
            <span>Llamar</span>
        </a>
        
        <?php 
            $esFavorito = false;
            if(session()->get('isLoggedIn')) {
                $db = \Config\Database::connect();
                $check = $db->table('favoritos')
                            ->where(['usuario_id' => session()->get('user_id'), 'modelo_id' => $modelo['id']])
                            ->get()->getRow();
                $esFavorito = ($check) ? true : false;
            }
        ?>
        
        <button onclick="toggleFavorito(this, <?= $modelo['id'] ?>)" 
            class="aspect-square flex items-center justify-center rounded-xl transition-all group border <?= $esFavorito ? 'bg-primary/10 border-primary text-primary' : 'bg-gray-100 dark:bg-[#39282c] border-transparent text-gray-400 dark:text-[#b99da4] hover:bg-primary/10 hover:text-primary' ?>"
            title="<?= $esFavorito ? 'Quitar de favoritas' : 'Guardar en favoritas' ?>">
            <span class="material-symbols-outlined group-hover:scale-110 transition-transform" 
                  style="<?= $esFavorito ? "font-variation-settings: 'FILL' 1;" : "font-variation-settings: 'FILL' 0;" ?>">
                favorite
            </span>
        </button>
    </div>
</div>

<div class="grid grid-cols-3 gap-3 border-t border-gray-100 dark:border-[#39282c] pt-5">
    <div class="flex flex-col items-center p-2 rounded-lg bg-gray-50 dark:bg-[#2a1d21]">
        <span class="text-xs text-gray-500 dark:text-[#b99da4] uppercase mb-1">Edad</span>
        <span class="font-bold text-lg"><?= $modelo['edad'] ?></span>
    </div>
    <div class="flex flex-col items-center p-2 rounded-lg bg-gray-50 dark:bg-[#2a1d21]">
        <span class="text-xs text-gray-500 dark:text-[#b99da4] uppercase mb-1">Altura</span>
        <span class="font-bold text-lg">
            <?php 
            if (!empty($modelo['estatura'])) {
                            // Reemplazamos la coma por punto por si acaso
                $altura = str_replace(',', '.', $modelo['estatura']);
                            // Agregamos el "m" al final
                echo $altura . ' m';
            } else {
                echo '--';
            }
            ?>
        </span>
    </div>
    <div class="flex flex-col items-center p-2 rounded-lg bg-gray-50 dark:bg-[#2a1d21]">
        <span class="text-xs text-gray-500 dark:text-[#b99da4] uppercase mb-1">Medidas</span>
        <span class="font-bold text-base leading-tight">
            <?= !empty($modelo['medidas']) ? $modelo['medidas'] : '--' ?>
        </span>
    </div>
</div>
</div>

<div class="flex flex-col gap-4">
    <div>
        <div class="flex items-center justify-between mb-3 px-1">
            <h4 class="text-sm font-bold uppercase tracking-wider text-gray-500 dark:text-[#b99da4]">Historias</h4>
            <?php if (!empty($historias)): ?>
                <span class="text-xs text-primary cursor-pointer font-bold" onclick="abrirVisorHistorias(0)">Ver todas</span>
            <?php endif; ?>
        </div>
        
        <div class="flex gap-4 overflow-x-auto scrollbar-hide pb-2">
            <?php if (empty($historias)): ?>
                <p class="text-xs text-gray-500 italic px-1">Sin historias activas en este momento</p>
            <?php else: ?>
                <?php foreach ($historias as $index => $h): ?>
                    <div class="flex flex-col items-center gap-2 shrink-0 group cursor-pointer" onclick="abrirVisorHistorias(<?= $index ?>)">
                        <div class="p-[2px] rounded-full bg-gradient-to-tr from-yellow-400 to-primary group-hover:from-yellow-300 group-hover:to-pink-400 transition-all">
                            <div class="size-16 rounded-full border-2 border-white dark:border-[#1a0f11] bg-cover bg-center bg-no-repeat" 
                            style='background-image: url("<?= base_url('uploads/modelos/historias/' . $h['ruta']) ?>");'>
                            
                            <?php 
                            $ext = strtolower(pathinfo($h['ruta'], PATHINFO_EXTENSION));
                            if (in_array($ext, ['mp4', 'mov', 'webm'])): 
                               ?>
                               <div class="w-full h-full flex items-center justify-center bg-black/20 rounded-full">
                                <span class="material-symbols-outlined text-white text-xl">play_circle</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                <span class="text-[10px] font-medium text-gray-500">
                    <?= time_ago($h['creado_at']) ?>
                </span>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
</div>
</div>
</div>
</div>
<!-- mMdelos relacionadas por ciudad -->
<?php if(!empty($relacionadas)): ?>
<div class="col-span-full mt-20 border-t border-white/5 pt-12 mb-10">
    <div class="flex flex-col md:items-end justify-between mb-8 gap-4 px-1">
        <div>
            <h3 class="text-2xl font-black uppercase tracking-tighter text-white leading-none">
                Otras <span class="text-primary"><?= ucfirst($modelo['categoria']) ?>s</span>
            </h3>
            <p class="text-xs text-gray-500 uppercase tracking-widest mt-2 italic">En <?= $modelo['ciudad_nombre'] ?? 'tu zona' ?></p>
        </div>
        <a href="<?= base_url('buscar?categoria='.$modelo['categoria'].'&ciudad='.$modelo['ciudad_id']) ?>" class="hidden md:flex items-center gap-2 text-xs font-black text-primary hover:text-white transition-all uppercase tracking-widest group">
            Ver todas <span class="material-symbols-outlined text-sm group-hover:translate-x-1 transition-transform">arrow_forward</span>
        </a>
    </div>

    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 md:gap-6">
        <?php foreach($relacionadas as $mr): ?>
            <a href="<?= base_url('modelo/'.$mr['slug']) ?>" class="group flex flex-col gap-3">
                <div class="relative aspect-[3/4] rounded-2xl overflow-hidden border border-white/5 bg-surface-dark shadow-2xl">
                    <img src="<?= base_url('uploads/modelos/'.$mr['foto_principal']) ?>" 
                         class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110" 
                         alt="<?= $mr['nombre_artistico'] ?>"
                         onerror="this.src='<?= base_url('assets/img/placeholder.jpg') ?>'">
                    
                    <div class="absolute inset-0 bg-gradient-to-t from-black/90 via-transparent to-transparent opacity-60 group-hover:opacity-80 transition-opacity"></div>
                    
                    <?php if(isset($mr['disponible_ahora']) && $mr['disponible_ahora'] == 1): ?>
                        <div class="absolute top-3 left-3 flex items-center gap-1.5 bg-black/50 backdrop-blur-sm px-2 py-1 rounded-full border border-green-500/30">
                            <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] font-black text-green-500 uppercase tracking-tighter">Online</span>
                        </div>
                    <?php endif; ?>

                    <div class="absolute bottom-4 left-0 right-0 text-center px-2">
                        <p class="text-white font-black text-xs uppercase truncate tracking-tight group-hover:text-primary transition-colors"><?= $mr['nombre_artistico'] ?></p>
                        <p class="text-[#b99da4] text-[9px] font-bold uppercase"><?= $mr['ciudad_nombre'] ?></p>
                    </div>
                </div>
            </a>
        <?php endforeach; ?>

        <a href="<?= base_url('buscar?categoria='.$modelo['categoria'].'&ciudad='.$modelo['ciudad_id']) ?>" 
           class="md:hidden flex flex-col items-center justify-center aspect-[3/4] rounded-2xl border-2 border-dashed border-white/10 bg-white/5 group active:bg-white/10 transition-all">
            <div class="size-12 rounded-full bg-primary/10 flex items-center justify-center mb-3 group-active:scale-110 transition-transform">
                <span class="material-symbols-outlined text-primary text-3xl">add_circle</span>
            </div>
            <span class="text-[10px] font-black text-white uppercase tracking-tighter text-center px-4">
                Ver más en<br><?= $modelo['ciudad_nombre'] ?>
            </span>
        </a>
    </div>
</div>
<?php endif; ?>

<div id="modal-historias" class="fixed inset-0 z-[100] hidden bg-black/95 flex items-center justify-center p-4">
    <button onclick="cerrarVisorHistorias()" class="absolute top-5 right-5 text-white z-[110]">
        <span class="material-symbols-outlined text-4xl">close</span>
    </button>

    <div class="relative w-full max-w-[400px] aspect-[9/16] bg-black rounded-2xl overflow-hidden shadow-2xl">
        <div class="absolute top-0 left-0 right-0 p-2 flex gap-1 z-20">
            <?php foreach($historias as $i => $h): ?>
                <div class="h-1 flex-1 bg-white/30 rounded-full overflow-hidden">
                    <div id="progreso-<?= $i ?>" class="h-full bg-white w-0"></div>
                </div>
            <?php endforeach; ?>
        </div>

        <div id="contenedor-media-historias" class="w-full h-full flex items-center justify-center">
        </div>

        <div class="absolute inset-0 flex">
            <div class="w-1/2 h-full cursor-west-resize" onclick="historiaPrevia()"></div>
            <div class="w-1/2 h-full cursor-east-resize" onclick="historiaSiguiente()"></div>
        </div>
    </div>
</div>
<div id="lightbox" class="fixed inset-0 z-[100] hidden bg-black/95 backdrop-blur-xl flex flex-col">
    <button onclick="closeLightbox()" class="absolute top-6 right-6 text-white hover:text-primary z-[110]">
        <span class="material-symbols-outlined text-4xl">close</span>
    </button>
    
    <div class="flex-1 flex items-center justify-center p-4 relative">
        <button onclick="prevImg()" class="absolute left-4 p-2 text-white/50 hover:text-white transition-colors">
            <span class="material-symbols-outlined text-5xl">chevron_left</span>
        </button>
        
        <img id="lightbox-img" src="" class="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl">
        
        <button onclick="nextImg()" class="absolute right-4 p-2 text-white/50 hover:text-white transition-colors">
            <span class="material-symbols-outlined text-5xl">chevron_right</span>
        </button>
    </div>
    
    <div class="h-24 bg-black/50 border-t border-white/5 flex items-center justify-center px-6">
        <p id="lightbox-counter" class="text-white font-black italic text-sm tracking-widest uppercase"></p>
    </div>
</div>
<script>
let currentImgIndex = 0;
const images = Array.from(document.querySelectorAll('.gallery-item')).map(img => img.src);

function changeHero(src, el, index) {
    currentImgIndex = index;
    // Cambiar imagen principal
    const hero = document.getElementById('main-hero-img');
    hero.src = src;
    
    // Actualizar estilos de bordes en miniaturas
    document.querySelectorAll('.thumb-item').forEach(item => {
        item.classList.remove('border-primary', 'ring-2', 'ring-primary/20', 'opacity-100');
        item.classList.add('border-transparent', 'opacity-70');
    });
    
    el.classList.add('border-primary', 'ring-2', 'ring-primary/20', 'opacity-100');
    el.classList.remove('border-transparent', 'opacity-70');
}

function openLightbox(index) {
    currentImgIndex = index;
    updateLightbox();
    document.getElementById('lightbox').classList.remove('hidden');
    document.body.style.overflow = 'hidden'; // Bloquear scroll
}

function closeLightbox() {
    document.getElementById('lightbox').classList.add('hidden');
    document.body.style.overflow = 'auto';
}

function updateLightbox() {
    const lbImg = document.getElementById('lightbox-img');
    const counter = document.getElementById('lightbox-counter');
    lbImg.src = images[currentImgIndex];
    counter.innerText = `Foto ${currentImgIndex + 1} de ${images.length}`;
}

function nextImg() {
    currentImgIndex = (currentImgIndex + 1) % images.length;
    updateLightbox();
}

function prevImg() {
    currentImgIndex = (currentImgIndex - 1 + images.length) % images.length;
    updateLightbox();
}

// Soporte para teclas (Esc, Flechas)
document.addEventListener('keydown', (e) => {
    if (document.getElementById('lightbox').classList.contains('hidden')) return;
    if (e.key === 'Escape') closeLightbox();
    if (e.key === 'ArrowRight') nextImg();
    if (e.key === 'ArrowLeft') prevImg();
});
    let historias = <?= json_encode($historias) ?>;
    let indexActual = 0;
    let storyTimer;

    function abrirVisorHistorias(index = 0) {
        document.getElementById('modal-historias').classList.remove('hidden');
    indexActual = index; // Ahora empieza desde la que el usuario eligió
    mostrarHistoria();
}

function cerrarVisorHistorias() {
    document.getElementById('modal-historias').classList.add('hidden');
    document.getElementById('contenedor-media-historias').innerHTML = '';
    clearTimeout(storyTimer);
}

function mostrarHistoria() {
    const contenedor = document.getElementById('contenedor-media-historias');
    const h = historias[indexActual];
    const url = "<?= base_url('uploads/modelos/historias/') ?>/" + h.ruta;
    const extension = h.ruta.split('.').pop().toLowerCase();
    
    clearTimeout(storyTimer);

    if (['mp4', 'mov', 'webm'].includes(extension)) {
        contenedor.innerHTML = `<video src="${url}" autoplay muted class="w-full h-full object-cover" onended="historiaSiguiente()"></video>`;
    } else {
        contenedor.innerHTML = `<img src="${url}" class="w-full h-full object-cover">`;
        storyTimer = setTimeout(historiaSiguiente, 5000); // 5 segundos por imagen
    }
}

function historiaSiguiente() {
    if (indexActual < historias.length - 1) {
        indexActual++;
        mostrarHistoria();
    } else {
        cerrarVisorHistorias();
    }
}

function historiaPrevia() {
    if (indexActual > 0) {
        indexActual--;
        mostrarHistoria();
    }
}

function contarClic(id, tipoContacto) {
    const formData = new FormData();
    formData.append('modelo_id', id);
    formData.append('tipo', tipoContacto);
    formData.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

    fetch('<?= base_url('api/registrar-clic') ?>', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: formData
    })
    .catch(err => console.error('Tracking Error'));
}

function changeHero(src, element) {
    // 1. Cambiar la imagen principal con efecto suave
    const hero = document.getElementById('main-hero-img');
    hero.style.opacity = '0';
    
    setTimeout(() => {
        hero.src = src;
        hero.style.opacity = '1';
    }, 200);

    // 2. Actualizar estilos de las miniaturas (bordes y opacidad)
    document.querySelectorAll('.thumb-item').forEach(img => {
        img.classList.remove('border-primary', 'ring-2', 'ring-primary/20', 'opacity-100');
        img.classList.add('border-transparent', 'opacity-70');
    });

    element.classList.add('border-primary', 'ring-2', 'ring-primary/20', 'opacity-100');
    element.classList.remove('border-transparent', 'opacity-70');
}
function toggleFavorito(btn, modeloId) {
    const icon = btn.querySelector('.material-symbols-outlined');
    
    // Mostramos feedback inmediato (opcional)
    btn.classList.add('animate-pulse');

    fetch('<?= base_url('usuario/toggle-favorito/') ?>' + modeloId, {
        method: 'GET',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    })
    .then(response => response.json())
    .then(data => {
        btn.classList.remove('animate-pulse');
        
        if (data.status === 'added') {
            // Estilos activados
            btn.classList.remove('bg-gray-100', 'dark:bg-[#39282c]', 'text-gray-400', 'dark:text-[#b99da4]', 'border-transparent');
            btn.classList.add('bg-primary/10', 'border-primary', 'text-primary');
            icon.classList.add('filled');
            icon.style.fontVariationSettings = "'FILL' 1";
            btn.title = "Quitar de favoritas";
        } else if (data.status === 'removed') {
            // Estilos desactivados
            btn.classList.add('bg-gray-100', 'dark:bg-[#39282c]', 'text-gray-400', 'dark:text-[#b99da4]', 'border-transparent');
            btn.classList.remove('bg-primary/10', 'border-primary', 'text-primary');
            icon.classList.remove('filled');
            icon.style.fontVariationSettings = "'FILL' 0";
            btn.title = "Guardar en favoritas";
        } else {
            // Si no está logueado, lo mandamos al login
            window.location.href = '<?= base_url('login') ?>';
        }
    })
    .catch(error => {
        btn.classList.remove('animate-pulse');
        console.error('Error:', error);
    });
}
</script>
<?= $this->endSection() ?>