/**
 * earth-now.co
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File:    apps/web/components/YearProgress.tsx
 * Purpose: Live progress of the current UTC year — deterministic astronomy-style ticker with a thin accent meter
 */

"use client";

import { useEffect, useState } from "react";
import { formatValue, startOfUtcYear } from "@earth-now/counter";
import { useI18n } from "@/lib/i18n";

const PERCENT_HINTS = { decimals: 6, unit: "%" } as const;

export default function YearProgress() {
  const { locale, t } = useI18n();
  const [now, setNow] = useState<number | null>(null);

  useEffect(() => {
    let raf = 0;
    const tick = () => {
      setNow(Date.now());
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  if (now === null) return null;
  const start = startOfUtcYear(now);
  const end = Date.UTC(new Date(now).getUTCFullYear() + 1, 0, 1);
  const fraction = (now - start) / (end - start);
  const year = new Date(now).getUTCFullYear();

  return (
    <div className="mb-8 flex items-center gap-3 text-xs text-ink2">
      <span className="shrink-0">
        {year} : {formatValue(fraction * 100, PERCENT_HINTS, { locale })} % {t("year.elapsed")}
      </span>
      <span className="h-1 min-w-0 flex-1 rounded-full bg-line" aria-hidden>
        <span
          className="block h-1 rounded-full bg-accent"
          style={{ width: `${fraction * 100}%` }}
        />
      </span>
    </div>
  );
}
