"use client";

import { useEffect, useState } from "react";

/** Live countdown to an offer's end, with the end date spelled out. */
export default function Countdown({ ends, compact = false }: { ends: string; compact?: boolean }) {
  const end = Date.parse(ends);
  const [now, setNow] = useState<number | null>(null);

  useEffect(() => {
    const tick = () => setNow(Date.now());
    const first = setTimeout(tick, 0);
    const t = setInterval(tick, 1000);
    return () => { clearTimeout(first); clearInterval(t); };
  }, []);

  const endLabel = new Date(end).toLocaleDateString("en-AE", { day: "numeric", month: "short", year: "numeric" });
  if (now === null) return <span className="pb-countdown">Ends {endLabel}</span>;

  const left = Math.max(0, end - now);
  if (left === 0) return <span className="pb-countdown is-over">Offer ended</span>;
  const d = Math.floor(left / 86400000);
  const h = Math.floor((left % 86400000) / 3600000);
  const m = Math.floor((left % 3600000) / 60000);
  const s = Math.floor((left % 60000) / 1000);
  const pad = (n: number) => String(n).padStart(2, "0");

  return (
    <span className="pb-countdown" role="timer" aria-label={`Offer ends ${endLabel}`}>
      {compact ? (
        <>Ends in {d > 0 ? `${d}d ` : ""}{pad(h)}:{pad(m)}:{pad(s)}</>
      ) : (
        <>
          <span className="pb-countdown-cells">
            {d > 0 && <b>{d}<small>d</small></b>}
            <b>{pad(h)}<small>h</small></b>
            <b>{pad(m)}<small>m</small></b>
            <b>{pad(s)}<small>s</small></b>
          </span>
          <span className="pb-countdown-end">Ends {endLabel}</span>
        </>
      )}
    </span>
  );
}
