"use client";

/**
 * Countdown to the event (FR-1.4).
 *
 * Renders a server-safe value first and refines it after mount, so the number is present
 * in the HTML rather than appearing only once JavaScript runs.
 */
import { useEffect, useState } from "react";

import type { Dictionary } from "@/lib/i18n";

function partsUntil(target: number, from: number) {
  const ms = Math.max(0, target - from);
  return {
    days: Math.floor(ms / 86_400_000),
    hours: Math.floor((ms % 86_400_000) / 3_600_000),
    minutes: Math.floor((ms % 3_600_000) / 60_000),
  };
}

export function Countdown({
  startsAt,
  dict,
}: {
  startsAt: string;
  dict: Dictionary;
}) {
  const target = new Date(startsAt).getTime();
  const [parts, setParts] = useState(() => partsUntil(target, Date.now()));

  useEffect(() => {
    const id = setInterval(() => setParts(partsUntil(target, Date.now())), 30_000);
    return () => clearInterval(id);
  }, [target]);

  const cells = [
    { value: parts.days, label: dict.countdownDays },
    { value: parts.hours, label: dict.countdownHours },
    { value: parts.minutes, label: dict.countdownMinutes },
  ];

  return (
    <div className="flex justify-center gap-6" aria-live="off">
      {cells.map((cell) => (
        <div key={cell.label} className="text-center">
          <div className="text-3xl font-semibold tabular-nums">{cell.value}</div>
          <div className="text-xs uppercase tracking-wide opacity-70">{cell.label}</div>
        </div>
      ))}
    </div>
  );
}
