"use client";

import { useEffect, useState } from "react";

export type ScoreColor = "auto" | "success" | "warning" | "danger";

const COLORS: Record<Exclude<ScoreColor, "auto">, string> = {
  success: "#22c55e",
  warning: "#f97316",
  danger: "#ef4444",
};

function pickColor(score: number, color: ScoreColor): string {
  if (color !== "auto") return COLORS[color];
  if (score >= 90) return COLORS.success;
  if (score >= 50) return COLORS.warning;
  return COLORS.danger;
}

export function ScoreGauge({
  target,
  label,
  active,
  delay = 0,
  size = "md",
  color = "auto",
}: {
  target: number;
  label: string;
  active: boolean;
  delay?: number;
  size?: "sm" | "md";
  color?: ScoreColor;
}) {
  const r = 32;
  const c = 2 * Math.PI * r;
  const [value, setValue] = useState(0);

  useEffect(() => {
    if (!active) return;
    let raf = 0;
    let startTs = 0;
    const duration = 1400;
    const startTimer = window.setTimeout(() => {
      const tick = (ts: number) => {
        if (!startTs) startTs = ts;
        const t = Math.min(1, (ts - startTs) / duration);
        const eased = 1 - Math.pow(1 - t, 3);
        setValue(Math.round(target * eased));
        if (t < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    }, delay);
    return () => {
      window.clearTimeout(startTimer);
      cancelAnimationFrame(raf);
    };
  }, [active, target, delay]);

  const offset = c * (1 - value / 100);
  const stroke = pickColor(target, color);
  const dim = size === "sm" ? "size-16" : "size-20";
  const num = size === "sm" ? "text-xl" : "text-2xl";

  return (
    <div className="flex flex-col items-center">
      <div className={`relative ${dim}`}>
        <svg viewBox="0 0 80 80" className="size-full -rotate-90">
          <circle
            cx="40"
            cy="40"
            r={r}
            fill="none"
            stroke={stroke}
            strokeOpacity="0.15"
            strokeWidth="5"
          />
          <circle
            cx="40"
            cy="40"
            r={r}
            fill="none"
            stroke={stroke}
            strokeWidth="5"
            strokeLinecap="round"
            strokeDasharray={c}
            strokeDashoffset={offset}
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <span
            className={`font-editorial ${num} font-medium tabular-nums`}
            style={{ color: stroke }}
          >
            {value}
          </span>
        </div>
      </div>
      <div className="mt-2 text-xs text-text-muted text-center leading-tight">{label}</div>
    </div>
  );
}
