// BEGIN CHANGE: vocation preference matcher (create char)
"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import Link from "next/link";
import { useI18n } from "@/i18n/LanguageProvider";
import { apiUrl } from "@/lib/api";

// BEGIN CHANGE: eixo control (paralyze / CC)
type ScoreKey = "damage" | "heal" | "sustain" | "difficulty" | "team" | "control";

type GuideVoc = {
  id: number;
  name: string;
  createChoice?: boolean;
  scores: Partial<Record<ScoreKey, number>>;
};

type Prefs = Record<ScoreKey, number>;

const AXES: ScoreKey[] = ["damage", "heal", "sustain", "difficulty", "team", "control"];

const DEFAULT_PREFS: Prefs = {
  damage: 50,
  heal: 50,
  sustain: 50,
  difficulty: 50,
  team: 50,
  control: 50,
};
// END CHANGE

function clampScore(n: unknown): number {
  const v = typeof n === "number" ? n : Number(n);
  if (!Number.isFinite(v)) return 0;
  return Math.max(0, Math.min(100, v));
}

/** 0-100: how close prefs are to vocation scores (Euclidean). */
export function vocationMatchPercent(prefs: Prefs, scores: Partial<Record<ScoreKey, number>>): number {
  let sumSq = 0;
  for (const k of AXES) {
    const d = (prefs[k] - clampScore(scores[k])) / 100;
    sumSq += d * d;
  }
  const dist = Math.sqrt(sumSq);
  const maxDist = Math.sqrt(AXES.length);
  return Math.round(100 * Math.max(0, 1 - dist / maxDist));
}

type Props = {
  /** Current vocation id from the form radios */
  value: number;
  /** Apply suggested vocation (parent updates radio) while dragging prefs */
  onSuggest: (vocationId: number) => void;
  className?: string;
};

export function VocationMatcher({ value, onSuggest, className = "" }: Props) {
  const { t } = useI18n();
  const m = t.auth.vocMatcher;
  const g = t.vocationsGuide;
  // BEGIN CHANGE: label control
  const labels: Record<ScoreKey, string> = {
    damage: g.damage,
    heal: g.heal,
    sustain: g.sustain,
    difficulty: g.difficulty,
    team: g.team,
    control: g.control,
  };
  // END CHANGE

  const [status, setStatus] = useState<"loading" | "ok" | "error">("loading");
  const [vocs, setVocs] = useState<GuideVoc[]>([]);
  const [prefs, setPrefs] = useState<Prefs>(DEFAULT_PREFS);
  const [touched, setTouched] = useState(false);
  const lastSuggested = useRef<number | null>(null);

  useEffect(() => {
    let cancelled = false;
    fetch(apiUrl("vocation-guide.php"))
      .then((r) => {
        if (!r.ok) throw new Error("http");
        return r.json();
      })
      .then((json) => {
        if (cancelled) return;
        const list = ((json?.data?.vocations ?? []) as GuideVoc[]).filter(
          (v) => v.createChoice !== false && typeof v.id === "number",
        );
        // Prefer explicit createChoice; if API omits flag, keep base starter ids 1-4
        const starters = list.filter((v) => v.createChoice === true);
        setVocs(starters.length ? starters : list.filter((v) => v.id >= 1 && v.id <= 4));
        setStatus("ok");
      })
      .catch(() => {
        if (!cancelled) setStatus("error");
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const ranked = useMemo(() => {
    return vocs
      .map((v) => ({
        id: v.id,
        name: v.name,
        pct: vocationMatchPercent(prefs, v.scores || {}),
      }))
      .sort((a, b) => b.pct - a.pct || a.id - b.id);
  }, [vocs, prefs]);

  const best = ranked[0] ?? null;

  // Auto-apply best match while the player is adjusting prefs
  useEffect(() => {
    if (!touched || !best) return;
    if (lastSuggested.current === best.id) return;
    lastSuggested.current = best.id;
    if (best.id !== value) onSuggest(best.id);
  }, [touched, best, value, onSuggest]);

  function setAxis(key: ScoreKey, raw: number) {
    setTouched(true);
    lastSuggested.current = null;
    setPrefs((prev) => ({ ...prev, [key]: clampScore(raw) }));
  }

  function reset() {
    setPrefs(DEFAULT_PREFS);
    setTouched(false);
    lastSuggested.current = null;
  }

  if (status === "loading") {
    return (
      <div className={`rounded-xl border border-border bg-background/40 px-3 py-3 text-xs text-muted ${className}`}>
        {t.common.loading}
      </div>
    );
  }
  if (status === "error" || !vocs.length) {
    return null;
  }

  return (
    <div className={`rounded-xl border border-border bg-background/50 p-3 sm:p-4 ${className}`}>
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div>
          <h3 className="text-sm font-semibold text-foreground">{m.title}</h3>
          <p className="mt-0.5 text-xs leading-relaxed text-muted">{m.hint}</p>
        </div>
        {touched && (
          <button
            type="button"
            onClick={reset}
            className="shrink-0 text-xs text-muted underline-offset-2 hover:text-foreground hover:underline"
          >
            {m.reset}
          </button>
        )}
      </div>

      <div className="mt-3 space-y-3">
        {AXES.map((key) => (
          <label key={key} className="block">
            <div className="mb-1 flex justify-between text-xs text-muted">
              <span>{labels[key]}</span>
              <span className="font-medium tabular-nums text-foreground">{prefs[key]}</span>
            </div>
            <input
              type="range"
              min={0}
              max={100}
              step={5}
              value={prefs[key]}
              onChange={(e) => setAxis(key, Number(e.target.value))}
              className="h-2 w-full cursor-pointer"
              style={{ accentColor: "var(--brand)" }}
              aria-label={labels[key]}
            />
          </label>
        ))}
      </div>

      {touched && best && (
        <div className="mt-4 rounded-lg border border-brand/40 bg-brand/10 px-3 py-2.5">
          <p className="text-xs text-muted">{m.bestLabel}</p>
          <p className="mt-0.5 text-sm font-semibold text-foreground">
            {best.name}{" "}
            <span className="font-normal text-brand">
              ({best.pct}% {m.match})
            </span>
          </p>
          {ranked.length > 1 && (
            <ul className="mt-2 space-y-0.5 text-xs text-muted">
              {ranked.slice(1, 3).map((r) => (
                <li key={r.id}>
                  {r.name} - {r.pct}% {m.match}
                </li>
              ))}
            </ul>
          )}
          <p className="mt-2 text-xs">
            <Link href="/vocations" className="text-brand hover:underline">
              {t.auth.compareVocations}
            </Link>
          </p>
        </div>
      )}

      {!touched && (
        <p className="mt-3 text-xs text-muted">{m.idleHint}</p>
      )}
    </div>
  );
}
// END CHANGE
