
export const CountDownTimer = () => {
    const timerElement = document.getElementById('countdown-timer');
    if (!timerElement) return;

    const saleStartInDaysTimestamp = parseInt(timerElement.dataset.saleStartInDays);
    const saleStartTimestamp = parseInt(timerElement.dataset.saleStart);
    const saleEndInDaysTimestamp = parseInt(timerElement.dataset.saleEndInDays);

    countDownClock(saleStartTimestamp,saleStartInDaysTimestamp, saleEndInDaysTimestamp, 'days');
};

const countDownClock = (saleStartTimestamp,startOffset, endOffset = 100, format = 'seconds') => {
    const d = document;
    const daysElement = d.querySelector('.days');
    const hoursElement = d.querySelector('.hours');
    const minutesElement = d.querySelector('.minutes');
    const secondsElement = d.querySelector('.seconds');

    let countdown;
    convertFormat(format);

    function convertFormat(format) {
        switch (format) {
            case 'seconds':
                return timer(saleStartTimestamp,startOffset, endOffset);
            case 'minutes':
                return timer(saleStartTimestamp,startOffset, endOffset * 60);
            case 'hours':
                return timer(saleStartTimestamp,startOffset, endOffset * 60 * 60);
            case 'days':
                return timer(saleStartTimestamp,startOffset, endOffset * 86400);
        }
    }

    function timer(saleStartTimestamp, startOffset, countdownDurationSeconds) {
        const currentTime = Date.now();
        const startTime = currentTime + startOffset * 1000;

        if (currentTime < (saleStartTimestamp * 1000)) {
            return;
        }


        const endTime = startTime + countdownDurationSeconds * 1000;

        const delay = Math.max(0, startTime - Date.now());

        setTimeout(() => {
            countdown = setInterval(() => {
                const secondsLeft = Math.round((endTime - Date.now()) / 1000);

                if (secondsLeft <= 0) {
                    clearInterval(countdown);
                    return;
                }

                displayTimeLeft(secondsLeft);
            }, 1000);
        }, delay);
    }

    function displayTimeLeft(seconds) {
        if (seconds) {
            if (daysElement) {
                daysElement.textContent = Math.floor(seconds / 86400);
            }
            if (hoursElement) {
                hoursElement.textContent = Math.floor((seconds % 86400) / 3600);
            }
            if (minutesElement) {
                minutesElement.textContent = Math.floor((seconds % 3600) / 60);
            }
            if (secondsElement) {
                const sec = seconds % 60;
                secondsElement.textContent = sec < 10 ? `0${sec}` : sec;
            }
        }
    }
};

