"use client";
import type { ToothState } from "@/lib/types";

export const TOOTH_STATES: Record<ToothState, [string, string]> = {
  sano: ["Sano", "--t-sano"],
  caries: ["Caries", "--t-caries"],
  obt: ["Obturado", "--t-obt"],
  endo: ["Endodoncia", "--t-endo"],
  corona: ["Corona", "--t-corona"],
  ext: ["Ausente/extraído", "--t-ext"],
  imp: ["Implante", "--t-imp"],
  pend: ["Por tratar", "--t-pend"],
};

/** Numeración FDI, dentición permanente. */
const UPPER = [18, 17, 16, 15, 14, 13, 12, 11, 0, 21, 22, 23, 24, 25, 26, 27, 28];
const LOWER = [48, 47, 46, 45, 44, 43, 42, 41, 0, 31, 32, 33, 34, 35, 36, 37, 38];

function ToothSvg({ n, st }: { n: number; st?: ToothState }) {
  const molar = n % 10 >= 6, pre = n % 10 >= 4 && !molar;
  const w = molar ? 24 : pre ? 20 : 16;
  if (st === "ext")
    return (
      <svg viewBox="0 0 30 30" aria-hidden="true">
        <rect x={15 - w / 2} y={5} width={w} height={20} rx={5} fill="none" stroke="var(--line)" strokeDasharray="3 2" />
        <path d="M8 8l14 14M22 8L8 22" stroke="var(--t-ext)" strokeWidth={2.5} />
      </svg>
    );
  return (
    <svg viewBox="0 0 30 30" aria-hidden="true">
      <rect x={15 - w / 2} y={5} width={w} height={20} rx={molar ? 6 : 7} fill={`var(${TOOTH_STATES[st ?? "sano"][1]})`} stroke="var(--muted)" strokeWidth={1.2} />
      {st === "endo" && <path d="M15 8v14" stroke="#fff" strokeWidth={2} />}
      {st === "imp" && <path d="M11 12h8M11 16h8M11 20h8" stroke="#fff" strokeWidth={1.6} />}
    </svg>
  );
}

export function Odontogram({ teeth, selected, onSelect }: { teeth: Record<string, ToothState>; selected: string | null; onSelect: (t: string) => void }) {
  const arch = (list: number[]) => (
    <div className="arch">
      {list.map((n, i) =>
        n === 0 ? <span key={i} className="mid" /> : (
          <button key={n} className="tooth" aria-pressed={selected === String(n)} title={`Pieza ${n}: ${TOOTH_STATES[teeth[n] ?? "sano"][0]}`} onClick={() => onSelect(String(n))}>
            <ToothSvg n={n} st={teeth[n]} />
            <span className="num">{n}</span>
          </button>
        ),
      )}
    </div>
  );
  return (
    <>
      <div className="odo">{arch(UPPER)}<div style={{ height: 10 }} />{arch(LOWER)}</div>
      <div className="legend">
        {Object.entries(TOOTH_STATES).map(([k, [l, v]]) => <span key={k}><i style={{ background: `var(${v})` }} />{l}</span>)}
      </div>
    </>
  );
}
