// ============================================
// bg.js - Optimized with WebM support
// ============================================
(function() {
    'use strict';
    
    const bgs = [
        "/data/fond/moon_1080p.webm",  // Changed to WebM
        "/data/fond/astro.webp",       // Changed to WebP
        "/data/fond/Pino.png",
    ];
    
    const bgIndex = Math.floor(Date.now() / (1000 * 60 * 60 * 24)) % bgs.length;
    
    let visibilityHandler = null;
    
    document.addEventListener("DOMContentLoaded", () => {
        const src = bgs[bgIndex];
        const video = document.getElementById("bg-video");
        const img = document.getElementById("bg-image");
        
        if (!video || !img) return;
        
        const isVideo = /\.(mp4|webm|ogg)$/i.test(src);
        const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        
        // Reduced motion → force image with WebP fallback
        if (prefersReducedMotion && isVideo) {
            const fallback = src.replace(/\.(mp4|webm|ogg)$/i, ".webp");
            img.src = fallback;
            img.style.display = "block";
            video.style.display = "none";
            return;
        }
        
        if (isVideo) {
            video.src = src;
            video.style.display = "block";
            img.style.display = "none";
            
            // Visibility handler for pause/play
            visibilityHandler = function() {
                if (document.hidden) {
                    video.pause();
                } else {
                    video.play().catch(e => console.log('Video play prevented:', e));
                }
            };
            
            document.addEventListener('visibilitychange', visibilityHandler);
            
            // Cleanup on page unload
            window.addEventListener('beforeunload', () => {
                if (visibilityHandler) {
                    document.removeEventListener('visibilitychange', visibilityHandler);
                }
                video.pause();
                video.src = '';
            });
            
            video.load();
        } else {
            img.src = src;
            img.style.display = "block";
            video.style.display = "none";
            video.pause();
            video.src = '';
        }
    });
})();
