'use client';
import { useEffect, useState } from "react";

export function DealCountdown({ endTime }: { endTime: number }) {
    const [mounted, setMounted] = useState(false);
    const [timeLeft, setTimeLeft] = useState(getTimeLeft(endTime));

    useEffect(() => {
        setMounted(true);

        const timer = setInterval(() => {
            setTimeLeft(getTimeLeft(endTime));
        }, 1000);

        return () => clearInterval(timer);
    }, [endTime]);

    if (!mounted) return null;

    if (timeLeft.total <= 0) {
        return <span className="text-red-500">Deal đã kết thúc</span>;
    }

    return (
        <>
            <p>{timeLeft.days}</p>
            <p>{timeLeft.hours}</p>
            <p>{timeLeft.minutes}</p>
            <p>{timeLeft.seconds}</p>
        </>
    );
}

export function getTimeLeft(endTime: number) {
    const now = Math.floor(Date.now() / 1000);
    const distance = endTime - now;

    if (distance <= 0) {
        return { 
            total   : 0, 
            days    : '00', 
            hours   : '00', 
            minutes : '00', 
            seconds : '00' 
        };
    }

    return {
        total   : distance,
        days    : String(Math.floor(distance / 86400)).padStart(2, '0'),
        hours   : String(Math.floor((distance % 86400) / 3600)).padStart(2, '0'),
        minutes : String(Math.floor((distance % 3600) / 60)).padStart(2, '0'),
        seconds : String(distance % 60).padStart(2, '0'),
    };
}