/**
 * Server-authoritative countdown timer for FlashSale
 * Never relies on client device time alone.
 */
let serverOffsetMs = 0;
let countdownInterval = null;

async function syncServerTime() {
    try {
        const clientStart = Date.now();
        const res = await fetch('/api/v1/time/');
        if (!res.ok) return;
        const data = await res.json();
        const clientEnd = Date.now();
        const roundTrip = (clientEnd - clientStart) / 2;
        const serverTimeMs = data.timestamp + roundTrip;
        serverOffsetMs = serverTimeMs - clientEnd;
    } catch (e) {
        console.warn('Server time sync failed, falling back to local time');
    }
}

function getCorrectedNow() {
    return Date.now() + serverOffsetMs;
}

async function initCountdown() {
    const el = document.getElementById('countdown');
    if (!el) return;

    await syncServerTime();
    // Re-sync server time every 20 seconds to prevent drift
    setInterval(syncServerTime, 20000);

    const targetIso = el.getAttribute('data-target-time');
    if (!targetIso) return;

    const targetMs = new Date(targetIso).getTime();

    function update() {
        const nowMs = getCorrectedNow();
        const diffSec = Math.floor((targetMs - nowMs) / 1000);

        if (diffSec <= 0) {
            clearInterval(countdownInterval);
            document.getElementById('cd-days').textContent = '00';
            document.getElementById('cd-hours').textContent = '00';
            document.getElementById('cd-minutes').textContent = '00';
            document.getElementById('cd-seconds').textContent = '00';
            // Reload page on state transition
            setTimeout(() => location.reload(), 1500);
            return;
        }

        const days = Math.floor(diffSec / 86400);
        const hours = Math.floor((diffSec % 86400) / 3600);
        const minutes = Math.floor((diffSec % 3600) / 60);
        const seconds = diffSec % 60;

        document.getElementById('cd-days').textContent = String(days).padStart(2, '0');
        document.getElementById('cd-hours').textContent = String(hours).padStart(2, '0');
        document.getElementById('cd-minutes').textContent = String(minutes).padStart(2, '0');
        document.getElementById('cd-seconds').textContent = String(seconds).padStart(2, '0');
    }

    update();
    countdownInterval = setInterval(update, 1000);
}
