import { useEffect, useState } from "react";

function diff(target: number) {
  const ms = Math.max(0, target - Date.now());
  const days = Math.floor(ms / 86400000);
  const hours = Math.floor((ms % 86400000) / 3600000);
  const mins = Math.floor((ms % 3600000) / 60000);
  const secs = Math.floor((ms % 60000) / 1000);
  return { days, hours, mins, secs, ended: ms <= 0 };
}

export default function Countdown({
  target,
  compact = false,
}: {
  target: number;
  compact?: boolean;
}) {
  const [t, setT] = useState(() => diff(target));

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

  const box = (v: number, label: string) => (
    <div className="flex flex-col items-center">
      <span
        className="min-w-[38px] h-[38px] px-2 rounded-[10px] bg-foreground-950 text-background-50 text-[16px] font-bold flex items-center justify-center"
        dir="ltr"
      >
        {String(v).padStart(2, "0")}
      </span>
      {!compact && <span className="text-[9.5px] text-foreground-600 mt-1">{label}</span>}
    </div>
  );

  if (t.ended) {
    return (
      <span className="inline-flex items-center gap-1 rounded-full bg-background-200 text-foreground-700 px-3 py-1.5 text-[11.5px] font-semibold">
        <i className="ri-time-line text-[13px] leading-none" />
        انتهى وقت الفرصة
      </span>
    );
  }

  return (
    <div className="flex items-center gap-2">
      {box(t.days, "يوم")}
      <span className="text-foreground-400 font-bold">:</span>
      {box(t.hours, "ساعة")}
      <span className="text-foreground-400 font-bold">:</span>
      {box(t.mins, "دقيقة")}
      <span className="text-foreground-400 font-bold">:</span>
      {box(t.secs, "ثانية")}
    </div>
  );
}