"use client";

import { useEffect, useState } from "react";

export function Countdown({ endsAt }: { endsAt: string }) {
  const [label, setLabel] = useState("…");

  useEffect(() => {
    function tick() {
      const remaining = new Date(endsAt).getTime() - Date.now();
      if (remaining <= 0) {
        setLabel("Closed");
        return;
      }
      const hours = Math.floor(remaining / 3_600_000);
      const mins = Math.floor((remaining % 3_600_000) / 60_000);
      const secs = Math.floor((remaining % 60_000) / 1000);
      setLabel(`${hours}h ${mins}m ${secs}s`);
    }
    tick();
    const timer = window.setInterval(tick, 1000);
    return () => window.clearInterval(timer);
  }, [endsAt]);

  return <span className="countdown tabular-nums">{label}</span>;
}
