<?php 
    include 'files/guardiankey.php'; 
    include 'academy/videos.php'; 
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Centro De Aprendizaje FlowCRM Powered By OrozCO</title>
  <meta name="description" content="Tutoriales Para Aprovechas Las Funciones De Tu CRM">
  <meta name="robots" content="noindex, nofollow">

    <link rel="icon" type="image/png" href="img/favicon.png">
    <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

    <?php include 'files/gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></script>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Barlow:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="style.css"> 
    <script src="files/header-manager.js"></script>
    
<style>
    .off-canvas-panel {
        position: fixed; top: 0; right: 0;
        width: 100%; height: 100%;
        background: #f9fafb;
        box-shadow: -4px 0 10px rgba(0,0,0,.1);
        transform: translateX(100%);
        transition: transform .3s ease-out;
        z-index: 50; display: flex; flex-direction: column;
        overflow-y: auto;
    }
    .off-canvas-panel.is-open { transform: translateX(0); }
    .off-canvas-overlay {
        position: fixed; top: 0; left: 0;
        width: 100%; height: 100%;
        background: rgba(0,0,0,.5);
        z-index: 40; display: none;
    }
    .off-canvas-overlay.is-open { display: block; }

    .lesson-card {
        background-color: white; padding: 1.5rem; border-radius: 0.75rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
    }
    .account-card-header {
        font-weight: 800; font-size: 0.875rem; color: #6b7280;
        letter-spacing: 0.05em; display: flex; align-items: center;
        gap: 0.5rem; border-bottom: 2px solid #e5e7eb;
        padding-bottom: 0.5rem; margin-bottom: 1rem;
    }

    .btn-panel {
        font-weight: 700; padding: 0.75rem 1.25rem;
        border-radius: 0.5rem; text-transform: uppercase;
        text-align: center; display: flex; align-items: center;
        justify-content: center; gap: 0.5rem;
        transition: all 0.2s ease;
    }
    .btn-panel.btn-primary { background-color: var(--color-primary); color: #fff; }
    .btn-panel.btn-secondary { background-color: var(--color-secondary); color: #fff; }
    .btn-panel.btn-ghost { background-color: transparent; color: #6b7280; border: 1px solid #d1d5db; }
    .btn-panel:hover { opacity: 0.8; transform: translateY(-1px); }
    .btn-panel[disabled] { opacity: 0.5; cursor: not-allowed; transform: none; }
    .btn-panel [data-lucide] { width: 1rem; height: 1rem; }

</style>

</head>
<body data-page-title="Centro De Aprendizaje FlowCRM"
      data-page-subtitle="Tutoriales Para Aprender A Usar Las Funciones De Tu CRM"
      data-page-icon="tv-minimal-play">

    <div id="toast-container" class="toast-container"></div>
        
<?php include 'files/gtm-body.php'; ?>

<div class="relative min-h-screen md:flex">

    <div id="sidebar-overlay" class="fixed inset-0 bg-black bg-opacity-50 z-30 hidden md:hidden"></div>
    <div id="task-panel-overlay" class="off-canvas-overlay"></div> 
    
    <?php include 'menu.php'; ?>

    <main class="flex-1 overflow-y-auto">
        <header class="bg-white shadow-sm p-4 flex justify-between items-center sticky top-0 z-20">
            <button id="mobile-menu-button" class="md:hidden text-gray-600 hover:text-gray-800">
                <i data-lucide="menu" class="w-6 h-6"></i>
            </button>
            <div class="page-header-container">
                <h2 id="page-title"></h2>
                <p id="page-subtitle"></p>
            </div>
            
<div class="show-widget-container hidden flex justify-end  p-0" id="show-welcome-intro-video-container">
<button class="show-widget-btn inline-flex items-center gap-3 text-base font-bold text-white bg-[var(--color-primary)] rounded-lg shadow-lg shadow-[var(--color-primary)]/20 py-3 px-6 transform hover:-translate-y-1 hover:shadow-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[var(--color-secondary)]"
        data-widget-id="academia-intro-video">
        <i data-lucide="eye" class="w-5 h-5"></i>
        <span>VER VIDEO PRESENTACIÓN</span>
    </button>
</div>

        </header>
        
                <div id="content-area" class="p-4 md:p-8 space-y-8">
                    
<section id="academia-intro-video" class="p-6 md:p-10 video-widget">
    <div class="blob bl1"></div><div class="blob bl2"></div>
    <div class="relative grid grid-cols-1 lg:grid-cols-2 gap-8 items-center">
        <div class="text-white">
            <div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/10 ring-1 ring-white/15 mb-4">
                <i data-lucide="award" class="w-4 h-4"></i>
                <span class="text-xs tracking-wide uppercase">Aprende A Dominar Tu CRM</span>
            </div>
            <h1 class="text-3xl md:text-4xl lg:text-5xl font-black leading-tight flex items-center gap-3">
                <i data-lucide="graduation-cap" class="w-9 h-9 text-[var(--color-highlight)]"></i>
                Academia Flow
            </h1>
            <p class="mt-3 md:mt-4 text-base md:text-lg text-white/90">
                ¡Felicidades por dar el paso! En este video te daremos un recorrido rápido por la plataforma para que empieces con el pie derecho. Nuestro objetivo es que domines cada función para hacer crecer tu negocio.
            </p>
            <ul class="mt-6 space-y-3 text-white/90">
                <li class="flex items-center gap-3">
                    <i data-lucide="video" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                    <span>Tutoriales Paso A Paso Para Cada Módulo</span>
                </li>
                <li class="flex items-center gap-3">
                    <i data-lucide="zap" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                    <span>Consejos Rápidos Para Maximizar Tu Productividad</span>
                </li>
            </ul>
        </div>
        
        <div class="w-full">
                <div class="bg-black/40 rounded-xl ring-1 ring-white/10 overflow-hidden">
                    <div class="relative w-full" style="padding-bottom: 56.25%;">
                        <video class="absolute top-0 left-0 w-full h-full object-cover" id="videoPlayer" controls controlslist="nodownload nofullscreen" preload="metadata">
                            <source src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4" type="video/mp4">
                            TU NAVEGADOR NO SOPORTA LA ETIQUETA DE VIDEO
                        </video>
                        <div id="playOverlay" class="absolute inset-0 flex justify-center items-center cursor-pointer group">
                            <img src="img/VideoLeccion-IAMarketing.jpg" alt="VideoLeccion - IAMarketing" class="absolute inset-0 w-full h-full object-cover">
                            <div class="absolute inset-0 w-full h-full bg-black/40 transition-colors group-hover:bg-black/60"></div>
                            <i data-lucide="play" class="relative w-16 h-16 text-white opacity-80 group-hover:opacity-100 transition-opacity"></i>
                        </div>
                    </div>
                    <div class="p-4 text-white/90 text-sm flex items-center justify-between">
                        <span class="inline-flex items-center gap-2">
                            <i data-lucide="play-circle" class="w-4 h-4"></i>
                            Video Presentación
                        </span>

                        <button class="hide-widget-btn inline-flex items-center gap-2 text-xs text-xs font-black text-[var(--color-highlight)] hover:text-[var(--color-highlight)] transition-colors py-1 px-2 rounded-md" 
                                data-widget-id="academia-intro-video" 
                                title="Ocultar el video de bienvenida">
                            OCULTAR VIDEO
                            <i data-lucide="square-x" class="w-4 h-4"></i>
                        </button>
                    </div>
            </div>
        </div>
    </div>
</section>

        <section id="academia" class="dashboard-section">
            <div class="bg-white p-6 rounded-xl shadow-md">
                <div class="mb-6">
                    <h4 class="text-2xl font-extrabold text-gray-700 mb-4 uppercase flex items-center gap-3">
                        <i data-lucide="monitor-play" class="w-7 h-7 text-[var(--color-primary)]"></i> TUTORIALES DE LA PLATAFORMA FLOWCRM
                    </h4>
                    <div class="relative mb-6">
                        <input type="text" id="video-search" placeholder="Buscar Tutoriales Por Título..."
                               class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-primary)] focus:border-transparent text-gray-700">
                        <i data-lucide="search" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 transform -translate-y-1/2"></i>
                    </div>
                </div>
                
                <div id="videos-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-6">
                </div>
                
                <div id="load-more-container" class="text-center mt-8">
                    <button id="load-more-videos-btn" class="btn-primary font-bold py-3 px-8 rounded-lg uppercase hidden">
                        Cargar Más Tutoriales
                    </button>
                </div>
            </div>
        </section>
    </main>
</div>

<div id="lessonPanel" class="off-canvas-panel">
    <div class="flex flex-col h-full">
        <div class="bg-slate-800 text-white p-6 flex justify-between items-center flex-shrink-0">
            <div class="flex items-center">
                <i data-lucide="book-open" class="w-6 h-6 mr-3 text-[var(--color-highlight)]"></i>
                <h3 id="lessonPanelTitleText" class="text-xl font-bold uppercase"></h3>
            </div>
            <button onclick="closeLessonPanel()" class="text-gray-400 hover:text-gray-200">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>
        <div class="p-4 md:p-8 flex-grow overflow-y-auto pr-2 -mr-2">
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 items-start">
                <div class="lg:col-span-2 space-y-8">
                    <div class="w-full aspect-video bg-gray-900 rounded-lg overflow-hidden shadow-lg relative">
                        <video id="lessonVideoPlayer" class="w-full h-full object-cover" controls preload="metadata"></video>
                        <div id="lessonVideoPoster" class="absolute inset-0 bg-cover bg-center flex items-center justify-center cursor-pointer">
                            <i data-lucide="play" class="w-24 h-24 text-white opacity-90 transition-opacity duration-300 hover:opacity-100"></i>
                        </div>
                    </div>
                </div>

                <div class="space-y-8 lg:sticky lg:top-8">
                    <div class="lesson-card">
                        <div class="space-y-3">
                            <button class="btn-panel btn-primary w-full"><i data-lucide="check" class="w-4 h-4 mr-2"></i> Marcar Como Completado</button>
                            <a href="academy.php" class="btn-panel btn-ghost w-full justify-center"><i data-lucide="layout-grid" class="w-4 h-4 mr-2"></i> Volver a Módulos</a>
                        </div>
                    </div>
                    <div class="lesson-card">
                        <h3 class="account-card-header"><i data-lucide="navigation" class="w-5 h-5 text-[var(--color-secondary)] uppercase"></i> NAVEGACIÓN</h3>
                        <div class="grid grid-cols-2 gap-3">
                            <button id="prevLessonBtn" class="btn-panel btn-secondary w-full justify-center" disabled>
                                <i data-lucide="arrow-left" class="w-4 h-4 mr-2"></i> Anterior
                            </button>
                            <button id="nextLessonBtn" class="btn-panel btn-secondary w-full justify-center">
                                Siguiente <i data-lucide="arrow-right" class="w-4 h-4 ml-2"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    const ALL_VIDEOS_DATA = <?php echo json_encode($academy_videos ?? [], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
</script>

<script>
(function() {
    'use strict';

    // =================================================================
    // CONFIGURACIÓN Y VARIABLES GLOBALES
    // =================================================================
    let allVideosData = [];
    let filteredVideosData = [];
    let videosLoadedCount = 0;
    const videosPerPage = 6;
    let currentSearchTerm = '';
    let currentVideoIndex = -1;

    // Elementos del DOM en cache para el panel lateral
    const lessonPanel = document.getElementById('lessonPanel');
    const lessonPanelOverlay = document.getElementById('task-panel-overlay'); // Corregido para que coincida con el id del overlay
    const lessonVideoPlayer = document.getElementById('lessonVideoPlayer');
    const lessonVideoPoster = document.getElementById('lessonVideoPoster');
    const lessonPanelTitleText = document.getElementById('lessonPanelTitleText');
    const videosContainer = document.getElementById('videos-container');
    const loadMoreButton = document.getElementById('load-more-videos-btn');
    const searchInput = document.getElementById('video-search');
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebar-overlay');
    const prevLessonBtn = document.getElementById('prevLessonBtn');
    const nextLessonBtn = document.getElementById('nextLessonBtn');
    
    // Nuevos elementos para el primer video
    const mainVideoPlayer = document.getElementById('videoPlayer');
    const mainPlayOverlay = document.getElementById('playOverlay');

    // =================================================================
    // FUNCIÓN PARA CREAR EL HTML DE UNA TARJETA DE VIDEO
    // =================================================================
    const createVideoCardHTML = (video, index) => {
        const posterUrl = video.poster_url || `https://placehold.co/600x337/07162d/ffc857?text=VIDEO+${video.title || 'Tutorial'}`;
        const parser = new DOMParser();
        const sanitizedTitle = video.title ? parser.parseFromString(video.title, 'text/html').body.textContent : 'Sin Título';
        const sanitizedDescription = video.description ? parser.parseFromString(video.description, 'text/html').body.textContent : 'Sin descripción.';

        // Añadimos un elemento <video> oculto en cada tarjeta
        return `
            <div class="video-card flex flex-col rounded-xl overflow-hidden shadow-lg hover:shadow-xl transform hover:scale-102 transition-all duration-300 bg-white border border-gray-200" data-video-index="${index}">
                <div class="video-thumbnail-container relative w-full" style="padding-top: 56.25%;">
                    <img src="${posterUrl}" alt="Miniatura de video: ${sanitizedTitle}" class="absolute top-0 left-0 w-full h-full object-cover poster-image" loading="lazy">
                    <video class="absolute top-0 left-0 w-full h-full object-cover hidden" controls controlslist="nodownload fullscreen" preload="metadata" src="${video.video_url}"></video>
                    <div class="video-play-button absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 hover:bg-opacity-75 transition-opacity duration-300 cursor-pointer">
                        <i data-lucide="play" class="w-16 h-16 text-white transform hover:scale-110 transition-transform duration-200"></i>
                    </div>
                </div>
                <div class="p-4 flex flex-col flex-grow">
                    <h5 class="font-extrabold text-xl text-gray-800 mb-2 uppercase leading-tight flex items-center gap-2">
                        <i data-lucide="video" class="w-6 h-6 text-[var(--color-primary)] flex-shrink-0"></i> <span class="line-clamp-2">${sanitizedTitle}</span>
                    </h5>
                    <p class="text-sm text-gray-600 flex-grow line-clamp-3">${sanitizedDescription}</p>
                    <button type="button" class="btn-panel btn-primary mt-3 w-full py-2 px-4 rounded-lg flex items-center justify-center gap-2">
                        <i data-lucide="monitor" class="w-5 h-5"></i> Ver Lección
                    </button>
                </div>
            </div>
        `;
    };

    // =================================================================
    // FUNCIÓN CENTRAL PARA MOSTRAR VIDEOS EN PANTALLA
    // =================================================================
    const renderVideos = (isLoadMore = false) => {
        if (!videosContainer || !loadMoreButton) {
            console.error("No se encontraron los contenedores de video o el botón 'Cargar Más'.");
            return;
        }

        const lowerSearchTerm = currentSearchTerm.toLowerCase().trim();
        filteredVideosData = lowerSearchTerm ? allVideosData.filter(video =>
            (video.title?.toLowerCase().includes(lowerSearchTerm)) ||
            (video.description?.toLowerCase().includes(lowerSearchTerm))
        ) : allVideosData;

        if (!isLoadMore) {
            videosContainer.innerHTML = '';
            videosLoadedCount = 0;
        }

        const videosToDisplay = filteredVideosData.slice(videosLoadedCount, videosLoadedCount + videosPerPage);

        if (videosToDisplay.length > 0) {
            const startIndex = videosLoadedCount;
            const html = videosToDisplay.map((video, index) => createVideoCardHTML(video, startIndex + index)).join('');
            videosContainer.insertAdjacentHTML('beforeend', html);
            videosLoadedCount += videosToDisplay.length;
        }

        if (videosLoadedCount === 0 && currentSearchTerm) {
            videosContainer.innerHTML = `<p class="col-span-full text-center text-gray-500 p-8">No se encontraron tutoriales que coincidan con "${currentSearchTerm}".</p>`;
        }

        loadMoreButton.classList.toggle('hidden', videosLoadedCount >= filteredVideosData.length);

        if (typeof lucide !== 'undefined') {
            lucide.createIcons();
        }
    };

    // <-- CAMBIO 3: La función fetchAllVideos se reemplaza por loadAllVideos.
    // =================================================================
    // CONECTOR INICIAL: Carga los videos desde la variable pre-cargada
    // =================================================================
    const loadAllVideos = () => {
        if (!videosContainer) {
            console.error("No se encontró el contenedor de videos.");
            return;
        }
        try {
            // La variable ALL_VIDEOS_DATA fue creada por PHP
            allVideosData = ALL_VIDEOS_DATA || [];
            renderVideos(); // Muestra los videos iniciales
        } catch (error) {
            console.error('Error al procesar los datos de videos:', error);
            videosContainer.innerHTML = `<p class="col-span-full text-center text-red-500 p-8">No se pudo cargar el contenido. Error en los datos.</p>`;
        }
    };

    // =================================================================
    // FUNCIONES DE PANEL LATERAL Y REPRODUCCIÓN
    // =================================================================
    const openLessonPanel = (videoIndex) => {
        const video = filteredVideosData[videoIndex];
        if (!video) return;

        currentVideoIndex = videoIndex;
        lessonPanel.classList.add('is-open');
        lessonPanelOverlay.classList.add('is-open');
        document.body.classList.add('off-canvas-open');

        lessonVideoPlayer.src = video.video_url;
        lessonVideoPlayer.poster = video.poster_url;
        lessonPanelTitleText.textContent = video.title;
        const lessonVideoPosterDiv = document.getElementById('lessonVideoPoster');
        if (lessonVideoPosterDiv) {
            lessonVideoPosterDiv.style.backgroundImage = `url('${video.poster_url}')`;
        }

        lessonVideoPoster.style.display = 'flex';
        lessonVideoPlayer.style.display = 'none';

        updateNavigationButtons();
    };
    
    const closeLessonPanel = () => {
        lessonVideoPlayer.pause();
        lessonVideoPlayer.src = '';
        lessonPanel.classList.remove('is-open');
        lessonPanelOverlay.classList.remove('is-open');
        document.body.classList.remove('off-canvas-open');
        currentVideoIndex = -1;
    };

    const handleVideoNavigation = (direction) => {
        const newIndex = currentVideoIndex + direction;
        if (newIndex >= 0 && newIndex < filteredVideosData.length) {
            openLessonPanel(newIndex);
        }
    };

    const updateNavigationButtons = () => {
        if (prevLessonBtn) prevLessonBtn.disabled = currentVideoIndex <= 0;
        if (nextLessonBtn) nextLessonBtn.disabled = currentVideoIndex >= filteredVideosData.length - 1;
    };

    // =================================================================
    // INICIALIZACIÓN DE EVENTOS
    // =================================================================
    const init = () => {
        // <-- CAMBIO 4: Se llama a la nueva función de carga.
        loadAllVideos();

        if (mobileMenuButton && sidebar && sidebarOverlay) {
            mobileMenuButton.addEventListener('click', () => {
                sidebar.classList.toggle('-translate-x-full');
                sidebarOverlay.classList.toggle('hidden');
            });
            sidebarOverlay.addEventListener('click', () => {
                sidebar.classList.add('-translate-x-full');
                sidebarOverlay.classList.add('hidden');
            });
        }

        const urlParams = new URLSearchParams(window.location.search);
        const notificationType = urlParams.get('notification_type');
        const notificationMessage = urlParams.get('notification_message');
        if (notificationType && notificationMessage && typeof showToast === 'function') {
            showToast(notificationMessage, notificationType);
        }

        // Manejo del clic para el reproductor del primer video
        if (mainPlayOverlay && mainVideoPlayer) {
            mainPlayOverlay.addEventListener('click', () => {
                mainPlayOverlay.style.display = 'none';
                mainVideoPlayer.play();
            });
        }

        // === LÓGICA DE EVENTOS CORREGIDA Y SEPARADA PARA CADA ACCIÓN ===
        if (videosContainer) {
            videosContainer.addEventListener('click', (event) => {
                const videoCard = event.target.closest('.video-card');
                if (!videoCard) return;

                const videoPlayButton = event.target.closest('.video-play-button');
                const viewLessonButton = event.target.closest('.btn-panel');
                const videoElement = videoCard.querySelector('video');
                const posterImage = videoCard.querySelector('.poster-image');

                if (viewLessonButton) {
                    // Clic en el botón "Ver Lección": Abre el panel lateral
                    const videoIndex = parseInt(videoCard.dataset.videoIndex);
                    openLessonPanel(videoIndex);
                } else if (videoPlayButton) {
                    // Clic en el icono de play: Reproduce el video in-place
                    posterImage.classList.add('hidden');
                    videoPlayButton.classList.add('hidden');
                    videoElement.classList.remove('hidden');
                    videoElement.play();
                }
            });
        }
        // === FIN DE LÓGICA DE EVENTOS CORREGIDA Y SEPARADA ===

        // Reproducir video cuando se hace clic en el póster del panel lateral
        if (lessonVideoPoster && lessonVideoPlayer) {
            lessonVideoPoster.addEventListener('click', () => {
                lessonVideoPoster.style.display = 'none';
                lessonVideoPlayer.style.display = 'block';
                lessonVideoPlayer.play();
            });
        }

        if (prevLessonBtn) {
            prevLessonBtn.addEventListener('click', () => handleVideoNavigation(-1));
        }

        if (nextLessonBtn) {
            nextLessonBtn.addEventListener('click', () => handleVideoNavigation(1));
        }
        
        if (lessonPanelOverlay) {
            lessonPanelOverlay.addEventListener('click', closeLessonPanel);
        }

        if (searchInput) {
            searchInput.addEventListener('input', () => {
                currentSearchTerm = searchInput.value;
                renderVideos();
            });
        }

        if(loadMoreButton){
             loadMoreButton.addEventListener('click', () => renderVideos(true));
        }
    };

    window.closeLessonPanel = closeLessonPanel;
    
    document.addEventListener('DOMContentLoaded', init);
})();
</script>

<script>
document.addEventListener('DOMContentLoaded', () => {

    const toggleWidgetVisibility = (widgetId, isHidden) => {
        const widget = document.getElementById(widgetId);
        // Encuentra el contenedor del botón de mostrar usando el data-widget-id
        const showContainer = document.querySelector(`.show-widget-container [data-widget-id="${widgetId}"]`)?.closest('.show-widget-container');
        const videoPlayer = widget ? widget.querySelector('video') : null;

        if (!widget || !showContainer) return; // Se detiene si no encuentra los elementos

        if (isHidden) {
            // Acción para OCULTAR
            widget.classList.add('hidden');
            showContainer.classList.remove('hidden');
            // IMPORTANTE: Detiene el video para ahorrar recursos
            if (videoPlayer) videoPlayer.pause(); 
        } else {
            // Acción para MOSTRAR
            widget.classList.remove('hidden');
            showContainer.classList.add('hidden');
        }

        // Guarda la preferencia en Local Storage, individualmente para cada widget
        localStorage.setItem(`hide_${widgetId}`, isHidden ? 'true' : 'false');
    };

    // 1. Configurar los botones de OCULTAR (clase: hide-widget-btn)
    document.querySelectorAll('.hide-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a ocultar
            toggleWidgetVisibility(widgetId, true); 
        });
    });

    // 2. Configurar los botones de MOSTRAR (clase: show-widget-btn)
    document.querySelectorAll('.show-widget-btn').forEach(button => {
        button.addEventListener('click', (event) => {
            const widgetId = event.currentTarget.dataset.widgetId; // Obtiene el ID a mostrar
            toggleWidgetVisibility(widgetId, false); 
        });
    });

    // 3. Comprobar y aplicar el estado guardado al cargar la página para TODOS los widgets
    document.querySelectorAll('.video-widget').forEach(widget => {
        const widgetId = widget.id;
        const isHidden = localStorage.getItem(`hide_${widgetId}`) === 'true';
        if (isHidden) {
            // Si el usuario lo ocultó antes, se aplica el estado de oculto
            toggleWidgetVisibility(widgetId, true);
        }
    });
});
</script>

</body>
</html>