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

<?= $this->section('content') ?>
<div class="flex flex-col gap-8 p-6 lg:p-10 max-w-7xl mx-auto w-full">
    
    <div class="flex flex-col gap-2">
        <h1 class="text-3xl font-black text-white uppercase tracking-tighter">Mis Historias</h1>
        <p class="text-text-muted text-sm italic italic">Sube contenido exclusivo que desaparecerá automáticamente en 24 horas.</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        
        <div class="lg:col-span-1">
            <form action="<?= base_url('modelo/subir-historia') ?>" id="form-historia" method="POST" enctype="multipart/form-data" class="bg-surface-dark p-8 rounded-3xl border border-surface-border space-y-6 shadow-2xl">
                <?= csrf_field() ?>
                
                <div class="flex flex-col items-center gap-6">
                    <div id="preview-container" class="relative size-32 rounded-2xl bg-[#181113] border-2 border-dashed border-primary/40 flex items-center justify-center text-primary overflow-hidden group hover:border-primary transition-all shadow-inner">
                        <span id="preview-icon" class="material-symbols-outlined text-5xl">add_a_photo</span>
                        
                        <div id="preview-render" class="absolute inset-0 hidden"></div>
                    </div>
                    
                    <div class="text-center">
                        <label class="bg-primary hover:bg-primary-hover text-white px-6 py-3 rounded-xl cursor-pointer font-bold text-xs uppercase tracking-widest transition-all shadow-lg shadow-primary/20 inline-block">
                            <span id="btn-text">Elegir Multimedia</span>
                            <input type="file" id="input-historia" name="foto_historia" class="hidden" accept="image/*,video/*" required>
                        </label>
                        
                        <p id="file-name" class="text-[10px] text-emerald-400 mt-2 uppercase font-black tracking-widest hidden">
                            <span class="material-symbols-outlined text-[12px] align-middle">check_circle</span> Archivo seleccionado
                        </p>
            
                        <p class="text-[10px] text-text-muted mt-4 uppercase font-black tracking-widest opacity-60">
                            Formato vertical (9:16) recomendado
                        </p>
                    </div>
                </div>
            
                <div class="h-px bg-surface-border w-full"></div>
            
                <button type="submit" class="w-full bg-white text-black font-black py-4 rounded-xl hover:bg-primary hover:text-white transition-all shadow-xl uppercase text-xs tracking-widest">
                    Publicar Historia
                </button>
            </form>
            
            <div class="mt-6 p-4 bg-blue-500/5 border border-blue-500/20 rounded-2xl flex gap-3">
                <span class="material-symbols-outlined text-blue-500 text-sm">info</span>
                <p class="text-[10px] text-blue-200/60 leading-tight">Recuerda que las historias ayudan a subir tu posición en el ranking de "Disponibles Ahora".</p>
            </div>
        </div>

        <div class="lg:col-span-2 bg-surface-dark p-8 rounded-3xl border border-surface-border shadow-2xl">
            <div class="flex items-center justify-between mb-8">
                <h3 class="text-white font-black uppercase text-sm tracking-widest flex items-center gap-2">
                    <span class="material-symbols-outlined text-primary">visibility</span>
                    Historias Activas
                </h3>
                <span class="text-[10px] font-bold text-gray-500 uppercase"><?= count($historias) ?> publicadas</span>
            </div>

            <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4">
                <?php if(empty($historias)): ?>
                    <div class="col-span-full py-20 flex flex-col items-center justify-center text-center opacity-40">
                        <span class="material-symbols-outlined text-6xl mb-2">auto_awesome_motion</span>
                        <p class="text-sm italic">No tienes historias activas en este momento.</p>
                    </div>
                <?php else: ?>
                    <?php foreach($historias as $h): ?>
                        <div class="relative aspect-[9/16] rounded-2xl overflow-hidden border border-surface-border group bg-black shadow-lg">
                            <?php 
                                $extension = strtolower(pathinfo($h['ruta'], PATHINFO_EXTENSION));
                                $es_video = in_array($extension, ['mp4', 'webm', 'ogg', 'mov']);
                                $url_archivo = base_url('uploads/modelos/historias/'.$h['ruta']);
                            ?>
                    
                            <?php if($es_video): ?>
                                <video class="w-full h-full object-cover" muted loop playsinline autoplay>
                                    <source src="<?= $url_archivo ?>" type="video/<?= $extension == 'mov' ? 'mp4' : $extension ?>">
                                </video>
                            <?php else: ?>
                                <img src="<?= $url_archivo ?>" alt="Historia" class="w-full h-full object-cover">
                            <?php endif; ?>
                    
                            <div class="absolute inset-0 bg-gradient-to-t from-black via-transparent to-transparent opacity-80 group-hover:opacity-100 transition-opacity"></div>
                            
                            <div class="absolute bottom-3 left-3 right-3 flex justify-between items-center z-10">
                                <div class="flex items-center gap-1 bg-black/40 backdrop-blur-md px-2 py-1 rounded-lg border border-white/10">
                                    <span class="material-symbols-outlined text-[12px] text-primary">timer</span>
                                    <span class="text-[9px] text-white font-black uppercase tracking-tighter">
                                        <?= (function_exists('calcularTiempoRestante')) ? calcularTiempoRestante($h['expira_at']) : 'Activa' ?>
                                    </span>
                                </div>
                                
                                <button onclick="confirmarEliminar('<?= $h['id'] ?>')" class="bg-primary/20 hover:bg-primary text-white size-7 rounded-lg transition-all flex items-center justify-center">
                                    <span class="material-symbols-outlined text-[16px]">delete</span>
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<div class="h-32 lg:hidden w-full"></div>
<script>
function confirmarEliminar(id) {
    if (confirm('¿Estás segura de que deseas eliminar esta historia?')) {
        window.location.href = "<?= base_url('modelo/eliminar-historia/') ?>" + id;
    }
}
document.getElementById('input-historia').addEventListener('change', function(e) {
    const file = e.target.files[0];
    const previewContainer = document.getElementById('preview-render');
    const previewIcon = document.getElementById('preview-icon');
    const fileNameDisplay = document.getElementById('file-name');
    const btnText = document.getElementById('btn-text');
    const containerBox = document.getElementById('preview-container');

    if (file) {
        const reader = new FileReader();
        const isVideo = file.type.includes('video');

        reader.onload = function(event) {
            previewContainer.innerHTML = ''; // Limpiar previo
            
            if (isVideo) {
                // Crear preview de video
                const video = document.createElement('video');
                video.src = event.target.result;
                video.className = 'w-full h-full object-cover';
                video.muted = true;
                video.autoplay = true;
                video.loop = true;
                previewContainer.appendChild(video);
            } else {
                // Crear preview de imagen
                const img = document.createElement('img');
                img.src = event.target.result;
                img.className = 'w-full h-full object-cover';
                previewContainer.appendChild(img);
            }

            // Cambios visuales
            previewContainer.classList.remove('hidden');
            previewIcon.classList.add('hidden');
            fileNameDisplay.classList.remove('hidden');
            btnText.innerText = 'Cambiar Archivo';
            containerBox.classList.remove('border-dashed');
            containerBox.classList.add('border-solid', 'border-primary');
        }
        reader.readAsDataURL(file);
    }
});

// Activar el Loading al publicar la historia
document.getElementById('form-historia').addEventListener('submit', function(e) {
    // Verificamos si la función mostrarLoading existe (la que creamos para la ficha)
    if (typeof mostrarLoading === "function") {
        mostrarLoading();
    } else {
        // Si por alguna razón no está en el layout, la definimos rápido aquí:
        const overlay = document.getElementById('loading-overlay');
        if (overlay) {
            overlay.classList.remove('hidden');
            overlay.classList.add('flex');
            
            // Opcional: Cambiar el mensaje a algo específico de historias
            const msg = document.getElementById('loading-msg');
            if (msg) msg.innerText = "Subiendo tu historia... esto puede tardar unos segundos si es video.";
        }
    }
});
</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 Historia</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>
<?= $this->endSection() ?>