/**
 * Countdown timer for mtcontabilita attempts.
 *
 * @module mod_mtcontabilita/timer
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
define([], function() {

    const fmt = (s) => {
        s = Math.max(0, s|0);
        let h = Math.floor(s / 3600);
        s %= 3600;
        let m = Math.floor(s / 60);
        let sec = s % 60;
        const p = x => (x < 10 ? '0' : '') + x;
        return (h > 0 ? (p(h) + ':') : '') + p(m) + ':' + p(sec);
    };

    /**
     * Avvia il countdown quando il DOM e il target sono pronti.
     * Fa retry per un breve periodo se il target non esiste ancora.
     * @param {{secondsleft:number, finishurl:string, targetId?:string}} cfg
     */
    const init = (cfg) => {
        const targetId = cfg.targetId || 'mtc-countdown';
        const finishurl = String(cfg.finishurl || '');
        let left = Number(cfg.secondsleft || 0) | 0;

        if (!finishurl) {
            if (window && window.console) { console.warn('mtc timer: missing finishurl'); }
            return;
        }

        const start = () => {
            let tries = 0;
            const maxTries = 50; // ~5s di retry
            const waitForEl = () => {
                const el = document.getElementById(targetId);
                if (el) {
                    run(el);
                    return;
                }
                if (tries++ < maxTries) {
                    setTimeout(waitForEl, 100);
                } else {
                    if (window && window.console) {
                        console.warn('mtc timer: target not found:', targetId);
                    }
                }
            };
            waitForEl();
        };

        const run = (el) => {
            if (window && window.console) { console.debug('mtc timer start', {left}); }

            // primo paint
            el.textContent = fmt(left);

            const tick = () => {
                if (left <= 0) {
                    window.location.replace(finishurl);
                    return;
                }
                left--;
                el.textContent = fmt(left);
                setTimeout(tick, 1000);
            };
            setTimeout(tick, 1000);

            // micro-resync quando cambia visibilità (tab background/foreground)
            let lastTs = Date.now();
            document.addEventListener('visibilitychange', () => {
                const now = Date.now();
                const delta = Math.floor((now - lastTs) / 1000);
                if (delta > 0) {
                    left = Math.max(0, left - delta);
                    el.textContent = fmt(left);
                }
                lastTs = now;
            }, {passive: true});
        };

        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', start, {once: true});
        } else {
            start();
        }
    };

    return { init };
});
