// header-manager.js

// --- Cabecera y Títulos ---
document.addEventListener('DOMContentLoaded', () => {
    const titleEl = document.getElementById('page-title');
    const subEl = document.getElementById('page-subtitle');
    
    if (titleEl && subEl) {
        const { pageTitle = 'Dashboard', pageSubtitle = 'Bienvenido', pageIcon = 'home' } = document.body.dataset;

        const formatTitle = (text, icon) => {
            if (window.innerWidth < 768) {
                return `<i data-lucide="${icon}"></i><span class="main-title-part-1">${text.toUpperCase()}</span>`;
            }
            const words = text.split(' ');
            const mid = Math.ceil(words.length / 2);
            return `<i data-lucide="${icon}"></i><span class="main-title-part-1">${words.slice(0, mid).join(' ').toUpperCase()}</span><span class="main-title-part-2">${words.slice(mid).join(' ').toUpperCase()}</span>`;
        };

        titleEl.innerHTML = formatTitle(pageTitle, pageIcon);
        subEl.textContent = pageSubtitle.toUpperCase();

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

// --- Gestión de Videos (Widgets y Reproductor) ---
document.addEventListener('DOMContentLoaded', () => {
    const toggleVisibility = (id, hide) => {
        const widget = document.getElementById(id);
        const btn = document.querySelector(`.show-widget-btn[data-widget-id="${id}"]`);
        const container = btn?.closest('.show-widget-container');
        const video = widget?.querySelector('video');

        if (!widget || !container) return;

        widget.classList.toggle('hidden', hide);
        container.classList.toggle('hidden', !hide);
        if (hide && video) video.pause();
        
        localStorage.setItem(`hide_${id}`, hide);
    };

    document.querySelectorAll('.hide-widget-btn').forEach(b => 
        b.addEventListener('click', e => toggleVisibility(e.currentTarget.dataset.widgetId, true))
    );

    document.querySelectorAll('.show-widget-btn').forEach(b => 
        b.addEventListener('click', e => toggleVisibility(e.currentTarget.dataset.widgetId, false))
    );

    const initPlayer = (widget) => {
        const video = widget.querySelector('video');
        const overlay = widget.querySelector('.absolute.inset-0.cursor-pointer');
        
        if (!video || !overlay) return;

        video.controls = false;

        overlay.addEventListener('click', () => {
            overlay.classList.add('hidden');
            video.controls = true;
            video.play().catch(() => {});
        });

        video.addEventListener('ended', () => {
            overlay.classList.remove('hidden');
            video.controls = false;
        });
    };

    document.querySelectorAll('.video-widget').forEach(widget => {
        if (localStorage.getItem(`hide_${widget.id}`) === 'true') {
            toggleVisibility(widget.id, true);
        }
        initPlayer(widget);
    });
});