/**
 * modules/ui/loginBackground.js — Fondo de pantalla de acceso (vídeo o galería).
 */
(function (g) {
    g.modules = g.modules || {};
    g.modules.ui = g.modules.ui || {};

    function defaults() {
        return {
            bgType: 'default',
            videoUrl: '',
            imageUrls: [],
            slideshowMode: 'sequential',
            fixedImageIndex: 0,
            slideshowIntervalSec: 18,
        };
    }

    function mergeLoginScreen(cfg) {
        return Object.assign(defaults(), (cfg && cfg.loginScreen) || {});
    }

    function resolveMediaUrl(path) {
        if (!path || typeof path !== 'string') return '';
        var p = path.trim();
        if (/^https?:\/\//i.test(p)) return p;
        var base = typeof BASE_URL !== 'undefined' ? BASE_URL : '';
        return base + p.replace(/^\//, '');
    }

    var rootEl = null;
    var clockEl = null;
    var slideTimer = null;
    var clockTimer = null;
    var seqIndex = 0;
    var imgA = null;
    var imgB = null;
    var activeImg = 0;
    var videoEl = null;

    function clearTimers() {
        if (slideTimer) {
            clearInterval(slideTimer);
            slideTimer = null;
        }
        if (clockTimer) {
            clearInterval(clockTimer);
            clockTimer = null;
        }
    }

    function stopVideo() {
        if (!videoEl) return;
        try {
            videoEl.pause();
            videoEl.removeAttribute('src');
            videoEl.load();
        } catch (_) {}
        videoEl = null;
    }

    function formatClockLine() {
        var now = new Date();
        try {
            if (typeof window !== 'undefined' && window.AntaraClockFormat && typeof window.AntaraClockFormat.lines === 'function') {
                return window.AntaraClockFormat.lines(now);
            }
        } catch (_) {}
        var timeStr = now.toLocaleTimeString('es-ES', { hour: '2-digit', minute: '2-digit', hour12: false });
        var dateStr = String(now.toLocaleDateString('es-ES', {
            weekday: 'short',
            day: 'numeric',
            month: 'short',
            year: 'numeric',
        })).toUpperCase();
        return { time: timeStr, date: dateStr };
    }

    function updateClock() {
        if (!clockEl) return;
        var lines = formatClockLine();
        clockEl.innerHTML =
            '<span class="grid-auth-clock-time">' +
            lines.time +
            '</span>' +
            '<span class="grid-auth-clock-date">' +
            lines.date +
            '</span>';
    }

    function pickRandomDiff(len, current) {
        if (len <= 1) return 0;
        var n;
        var guard = 0;
        do {
            n = Math.floor(Math.random() * len);
            guard++;
        } while (n === current && guard < 32);
        return n;
    }

    function apply(cfg) {
        clearTimers();
        stopVideo();
        seqIndex = 0;
        activeImg = 0;
        imgA = null;
        imgB = null;

        var ls = mergeLoginScreen(cfg);
        if (!rootEl) return;

        rootEl.innerHTML = '';
        var defaultGrad = document.createElement('div');
        defaultGrad.className = 'grid-auth-bg-default';
        rootEl.appendChild(defaultGrad);

        function showDefault() {
            defaultGrad.style.display = '';
        }

        if (ls.bgType === 'video' && ls.videoUrl) {
            defaultGrad.style.display = 'none';
            videoEl = document.createElement('video');
            videoEl.className = 'grid-auth-bg-video';
            videoEl.setAttribute('autoplay', '');
            videoEl.setAttribute('muted', '');
            videoEl.setAttribute('loop', '');
            videoEl.setAttribute('playsinline', '');
            videoEl.src = resolveMediaUrl(ls.videoUrl);
            videoEl.addEventListener('error', function () {
                showDefault();
                if (videoEl && videoEl.parentNode) videoEl.parentNode.removeChild(videoEl);
                videoEl = null;
            });
            rootEl.appendChild(videoEl);
            videoEl.play().catch(function () {});
            return;
        }

        if (ls.bgType === 'images' && ls.imageUrls && ls.imageUrls.length) {
            var rawList = ls.imageUrls.filter(function (u) {
                return u && String(u).trim() !== '';
            });
            var urls = rawList.map(function (r) {
                return resolveMediaUrl(String(r).trim());
            }).filter(Boolean);

            if (!urls.length) {
                showDefault();
                return;
            }

            defaultGrad.style.display = 'none';
            var wrap = document.createElement('div');
            wrap.className = 'grid-auth-bg-slideshow';
            imgA = document.createElement('img');
            imgB = document.createElement('img');
            imgA.className = 'grid-auth-bg-slide grid-auth-bg-slide--visible';
            imgB.className = 'grid-auth-bg-slide';
            imgA.alt = '';
            imgB.alt = '';
            imgA.draggable = false;
            imgB.draggable = false;
            wrap.appendChild(imgA);
            wrap.appendChild(imgB);
            rootEl.appendChild(wrap);

            var mode = ls.slideshowMode || 'sequential';
            var fixedIx = Math.min(Math.max(0, parseInt(ls.fixedImageIndex, 10) || 0), urls.length - 1);

            function bindErr(img) {
                img.addEventListener('error', function () {
                    showDefault();
                });
            }
            bindErr(imgA);
            bindErr(imgB);

            if (mode === 'fixed') {
                seqIndex = fixedIx;
                imgA.src = urls[seqIndex];
                return;
            }

            seqIndex = 0;
            imgA.src = urls[0];

            if (urls.length < 2) return;

            var intervalMs = Math.max(5000, (parseInt(ls.slideshowIntervalSec, 10) || 18) * 1000);

            function advance() {
                var modeCur = ls.slideshowMode || 'sequential';
                if (modeCur === 'random') {
                    seqIndex = pickRandomDiff(urls.length, seqIndex);
                } else {
                    seqIndex = (seqIndex + 1) % urls.length;
                }
                var nextSrc = urls[seqIndex];
                var nextEl = activeImg === 0 ? imgB : imgA;
                var prevEl = activeImg === 0 ? imgA : imgB;

                function swap() {
                    nextEl.onload = null;
                    nextEl.onerror = null;
                    nextEl.classList.add('grid-auth-bg-slide--visible');
                    prevEl.classList.remove('grid-auth-bg-slide--visible');
                    activeImg = activeImg === 0 ? 1 : 0;
                }

                nextEl.onload = swap;
                nextEl.onerror = swap;
                nextEl.src = nextSrc;
            }

            slideTimer = setInterval(advance, intervalMs);
            return;
        }

        showDefault();
    }

    function mount(bgRoot, clock) {
        rootEl = bgRoot;
        clockEl = clock;
        clearTimers();
        if (clockEl) {
            updateClock();
            clockTimer = setInterval(updateClock, 1000);
        }
    }

    function teardown() {
        clearTimers();
        stopVideo();
        if (rootEl) rootEl.innerHTML = '';
        rootEl = null;
        clockEl = null;
        imgA = null;
        imgB = null;
    }

    g.modules.ui.loginBackground = {
        defaults: defaults,
        mergeLoginScreen: mergeLoginScreen,
        resolveMediaUrl: resolveMediaUrl,
        mount: mount,
        apply: apply,
        teardown: teardown,
    };
})(typeof window !== 'undefined' ? window : this);
