import { useEffect, useState } from "react";
import flashSaleImage from "../../../../assets/images/flash-sale.png";

const Countdown = () => {
  // 👉 Set your target date here
  const targetDate = new Date("2026-05-12T23:59:59");

  const calculateTimeLeft = () => {
    const now = new Date();
    const difference = targetDate - now;

    if (difference <= 0) return null;

    return {
      days: Math.floor(difference / (1000 * 60 * 60 * 24)),
      hours: Math.floor((difference / (1000 * 60 * 60)) % 24),
      minutes: Math.floor((difference / 1000 / 60) % 60),
      seconds: Math.floor((difference / 1000) % 60),
    };
  };

  const [timeLeft, setTimeLeft] = useState(calculateTimeLeft());

  useEffect(() => {
    if (!timeLeft) return;

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

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

  // 👉 If time is up, render nothing
  if (!timeLeft) return null;

  const format = (num) => String(num).padStart(2, "0");

  return (
    <div className="wmx-flex wmx-items-center wmx-bg-primary/5 wmx-gap-2.5 wmx-rounded-lg wmx-p-2.5 wmx-mt-1">
      <div className="wmx-size-16 wmx-flex-shrink-0">
        <img className="wmx-w-full" src={flashSaleImage} />
      </div>
      <div className="wmx-flex-1 wmx-mt-0.5">
        <p className="wmx-font-bold wmx-leading-3 wmx-text-base wmx-mb-2">
          <span className="wmx-text-orange-500">HURRY!</span> 40% OFFER ENDS IN
        </p>

        <div className="wmx-flex wmx-gap-1 wmx-items-center">
          <TimeBox label="DAYS" value={format(timeLeft.days)} />
          <span className="wmx-text-base wmx-font-bold -wmx-mt-1">:</span>
          <TimeBox label="HRS" value={format(timeLeft.hours)} />
          <span className="wmx-text-base wmx-font-bold -wmx-mt-1">:</span>
          <TimeBox label="MINS" value={format(timeLeft.minutes)} />
          <span className="wmx-text-base wmx-font-bold -wmx-mt-1">:</span>
          <TimeBox label="SECS" value={format(timeLeft.seconds)} />
        </div>
      </div>
    </div>
  );
};

const TimeBox = ({ label, value }) => (
  <div className="wmx-flex wmx-flex-col wmx-gap-1 wmx-w-full wmx-items-center wmx-bg-primary/5 wmx-pb-2 wmx-pt-2.5 wmx-rounded-lg">
    <span className="wmx-text-base wmx-font-bold wmx-text-gray-950 wmx-leading-3">
      {value}
    </span>
    <span className="wmx-text-[10px] wmx-leading-3 wmx-text-gray-800">
      {label}
    </span>
  </div>
);

export default Countdown;
