import { useState, useEffect } from "preact/hooks";

interface CountdownProps {
  target: string; // ISO date string
  label?: string;
}

function calc(target: string) {
  const diff = new Date(target).getTime() - Date.now();
  if (diff <= 0) return { days: 0, hours: 0, mins: 0, secs: 0, expired: true };
  return {
    days: Math.floor(diff / 86400000),
    hours: Math.floor((diff % 86400000) / 3600000),
    mins: Math.floor((diff % 3600000) / 60000),
    secs: Math.floor((diff % 60000) / 1000),
    expired: false,
  };
}

export function Countdown({ target, label }: CountdownProps) {
  const [time, setTime] = useState(calc(target));

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

  const units = [
    { v: time.days, l: "d" },
    { v: time.hours, l: "h" },
    { v: time.mins, l: "m" },
    { v: time.secs, l: "s" },
  ];

  return (
    <div class="mb-4">
      {label && <p class="text-[var(--z-font-sm)] font-mono mb-2" style={{ color: "var(--z-muted)" }}>{label}</p>}
      <div class="flex gap-2">
        {units.map((u) => (
          <div key={u.l} class="flex flex-col items-center px-3 py-2 rounded-[var(--z-radius-card)] min-w-[52px]" style={{ background: "var(--z-card-bg)", border: "var(--z-card-border)", boxShadow: "var(--z-card-shadow)" }}>
            <span class="font-mono text-xl font-semibold" style={{ color: time.expired ? "var(--z-muted)" : "var(--z-text)" }}>
              {String(u.v).padStart(2, "0")}
            </span>
            <span class="text-[var(--z-font-xs)] font-mono" style={{ color: "var(--z-muted)" }}>{u.l}</span>
          </div>
        ))}
      </div>
      {time.expired && <p class="text-xs mt-2" style={{ color: "var(--z-muted)" }}>Expired</p>}
    </div>
  );
}
