document.addEventListener("DOMContentLoaded", () => {

    // Select the element that contains the shipping cutoff time
    const shippingTime = document.querySelector('#shipping-time');
    // Select the element where we will display the time left
    const timeLeft = document.querySelector('.time_left');

    // Exit early if either element is missing
    if (!shippingTime || !timeLeft) return;

    // Target minutes = shipping cutoff time in hours converted to minutes
    const targetMinutes = Number(shippingTime.dataset.shippingtime) * 60;
    const MINUTES_IN_DAY = 1440; // Total minutes in a day

    // Helper function to format minutes as HHhMM
    function minutesToHHMM(minutes) {
        const hours = Math.floor(minutes / 60);
        const mins = minutes % 60;
        return `${String(hours).padStart(2, '0')}h${String(mins).padStart(2, '0')}`;
    }

    // Function to update the countdown display
    function updateTimeLeft() {
        const now = new Date();
        // Current time in minutes since midnight
        const currentMinutes = now.getHours() * 60 + now.getMinutes();

        let difference;

        if (currentMinutes < targetMinutes) {
            // Today: remaining time until cutoff
            difference = targetMinutes - currentMinutes;
        } else {
            // Tomorrow: remaining time until next shipping cutoff
            difference = (MINUTES_IN_DAY - currentMinutes) + targetMinutes;
        }

        // Update the text content with formatted time
        timeLeft.textContent = minutesToHHMM(difference);
    }

    // Initial update
    updateTimeLeft();
    // Update every minute
    setInterval(updateTimeLeft, 60000);
});