"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";

function partsUntil(target: number) {
  const diff = Math.max(0, target - Date.now());
  const hrs = Math.floor(diff / 3_600_000);
  const min = Math.floor((diff % 3_600_000) / 60_000);
  const sec = Math.floor((diff % 60_000) / 1000);
  return {
    hrs: String(hrs).padStart(2, "0"),
    min: String(min).padStart(2, "0"),
    sec: String(sec).padStart(2, "0"),
  };
}

/** Live flash-sale countdown ending at next local midnight. */
export function FlashCountdown() {
  const [target] = useState(() => {
    const end = new Date();
    end.setHours(24, 0, 0, 0);
    return end.getTime();
  });
  const [time, setTime] = useState(() => partsUntil(target));

  useEffect(() => {
    const id = window.setInterval(() => setTime(partsUntil(target)), 1000);
    return () => window.clearInterval(id);
  }, [target]);

  return (
    <div className="flex items-center gap-1.5">
      <span className="mr-1 text-xs text-muted">Ends in</span>
      {[time.hrs, time.min, time.sec].map((value, index) => (
        <div key={index} className="flex items-center gap-1.5">
          <motion.span
            key={value}
            initial={{ y: 6, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            className="inline-flex h-8 min-w-8 items-center justify-center rounded-lg bg-zinc-950 px-1.5 text-sm font-bold tabular-nums text-white dark:bg-white dark:text-zinc-950"
          >
            {value}
          </motion.span>
          {index < 2 ? <span className="font-bold text-muted">:</span> : null}
        </div>
      ))}
    </div>
  );
}
