import { ready } from '@site/js/utils/dom.js';

/**
 * Delivery cutoff countdown timer (vanilla).
 *
 * The Twig template renders:
 *   <div class="deliveryTimer" data-cutoff="N">
 *       <span class="timer"></span>
 *   </div>
 *
 * `N` is the number of seconds remaining until the delivery cutoff. We tick
 * once a second, writing "Xhrs Ymins Zsecs" into `.timer` until the cutoff
 * is reached. The label switches to singular ("hr") when a unit equals 1,
 * matching the previous plugin's behaviour.
 */
ready(() => {
    const wrapper = document.querySelector('.deliveryTimer');
    const timer = wrapper?.querySelector('.timer');
    if (!wrapper || !timer) {
        return;
    }

    const cutoffSeconds = parseInt(wrapper.dataset.cutoff, 10);
    if (!Number.isFinite(cutoffSeconds) || cutoffSeconds <= 0) {
        return;
    }

    // Anchor to a wall-clock target so the timer self-corrects if the tab is
    // throttled or the system clock jumps — drift was a known issue with the
    // old plugin's tick-based counter.
    const target = Date.now() + cutoffSeconds * 1000;

    function format(remainingSeconds) {
        const safe = Math.max(0, remainingSeconds);
        const hours = Math.floor(safe / 3600);
        const minutes = Math.floor((safe % 3600) / 60);
        const seconds = safe % 60;
        const hoursLabel = hours === 1 ? 'hr' : 'hrs';
        const minutesLabel = minutes === 1 ? 'min' : 'mins';
        const secondsLabel = seconds === 1 ? 'sec' : 'secs';
        return `${hours}${hoursLabel} ${minutes}${minutesLabel} ${seconds}${secondsLabel}`;
    }

    let intervalId = null;

    function tick() {
        const remaining = Math.round((target - Date.now()) / 1000);
        timer.textContent = format(remaining);
        if (remaining <= 0 && intervalId !== null) {
            clearInterval(intervalId);
        }
    }

    tick();
    intervalId = setInterval(tick, 1000);
});
