import {numberDisplay} from './numberDisplay';

export const countdownTimerExternal = (selector ='.develux-timer-countdown-timer-js') => {
    const timers = document.querySelectorAll(selector);
    timers.forEach(timer => {
        const saleStartTimestamp = parseInt(timer.dataset.countdownStart) * 1000;
        const saleEndTimestamp = parseInt(timer.dataset.countdown) * 1000;
        const displayAnimation = parseInt(timer.dataset.animation);
        const updateTimer = () => {
            const currentTime = Date.now();
            if (currentTime < saleStartTimestamp) {
                return;
            }
            const difference = saleEndTimestamp - currentTime;
            const expired = difference < 0;
            const days = Math.floor(difference / (1000 * 60 * 60 * 24));
            const hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((difference % (1000 * 60)) / 1000);

            // Update each part of the timer
            if( displayAnimation ){
                numberDisplay(days, timer.querySelector('.develux-timer-block-days-js'), expired, hours === 0 && minutes === 0 && seconds === 0);
                numberDisplay(hours, timer.querySelector('.develux-timer-block-hours-js'), expired, minutes === 0 && seconds === 0);
                numberDisplay(minutes, timer.querySelector('.develux-timer-block-minutes-js'), expired, seconds === 0);
                numberDisplay(seconds, timer.querySelector('.develux-timer-block-seconds-js'), expired, true);
            }else{
                numberDisplay(days, timer.querySelector('.develux-timer-block-days-js'), expired, false);
                numberDisplay(hours, timer.querySelector('.develux-timer-block-hours-js'), expired, false);
                numberDisplay(minutes, timer.querySelector('.develux-timer-block-minutes-js'), expired, false);
                numberDisplay(seconds, timer.querySelector('.develux-timer-block-seconds-js'), expired, false);
            }


            if (expired) {
                clearInterval(timer.intervalId); // Clear only this timer's interval
                timer.remove(); // Remove the expired timer
            }
        };
        if (Date.now() >= saleStartTimestamp) {}
            // Save the interval ID in the timer element
            timer.intervalId = setInterval(updateTimer, 1000);

            // Run the update function immediately to display the initial state
            updateTimer();

    });
};
