/* eslint-disable */
// ============================================================
// ASTEM — Tooth chart (32 teeth, FDI numbering)
// Schematic occlusal view, panoramic convention:
//   viewer LEFT  = Quad 1 (max right) + Quad 4 (mand right)
//   viewer RIGHT = Quad 2 (max left)  + Quad 3 (mand left)
// ============================================================

const { useState, useMemo, useRef, useEffect } = React;

// ---- FDI layout around an oval ----
const TEETH = (() => {
  const list = [];
  const q1 = [11,12,13,14,15,16,17,18];
  q1.forEach((n,i) => list.push({ num: n, q: 1, idx: i, angle: 355 - i*10 }));
  const q2 = [21,22,23,24,25,26,27,28];
  q2.forEach((n,i) => list.push({ num: n, q: 2, idx: i, angle: 5 + i*10 }));
  const q3 = [31,32,33,34,35,36,37,38];
  q3.forEach((n,i) => list.push({ num: n, q: 3, idx: i, angle: 175 - i*10 }));
  const q4 = [41,42,43,44,45,46,47,48];
  q4.forEach((n,i) => list.push({ num: n, q: 4, idx: i, angle: 185 + i*10 }));
  return list;
})();

function toothType(n) {
  const pos = n % 10;
  if (pos === 1 || pos === 2) return "incisor";
  if (pos === 3) return "canine";
  if (pos === 4 || pos === 5) return "premolar";
  return "molar";
}

const CX = 350, CY = 350;
const RX = 230, RY = 280;
const NUM_RX = RX + 55, NUM_RY = RY + 38;

function polar(rx, ry, angleDeg, cx, cy) {
  const ccx = cx !== undefined ? cx : CX;
  const ccy = cy !== undefined ? cy : CY;
  const a = (angleDeg * Math.PI) / 180;
  return [ccx + rx * Math.sin(a), ccy - ry * Math.cos(a)];
}

// Colors for guide chirurgical arc bands
const GUIDE_COLORS = {
  dentaire: "#3B82F6",
  muqueux:  "#F472B6",
  osseux:   "#F59E0B",
};
const GUIDE_LABELS = {
  dentaire: "Appui dentaire",
  muqueux:  "Appui muqueux",
  osseux:   "Appui osseux",
};

// Anneau de guide chirurgical entre couronne et racine
function GuideRing({ type, color }) {
  const W = type === "molar" ? 30 : type === "premolar" ? 24 : type === "canine" ? 22 : 20;
  const rx = W / 2 + 3.5;
  return (
    <ellipse
      cx={0} cy={9}
      rx={rx} ry={5.5}
      fill={color + "55"}
      stroke={color}
      strokeWidth={2.8}
      opacity={0.92}
    />
  );
}

// ---- Tooth shape draw (from origin, oriented with crown UP) ----
// crownOnly = true → show only the crown (no root post), used for plural implant pontics
function ToothShape({ type, crownOnly }) {
  const W = type === "molar" ? 30 : type === "premolar" ? 24 : type === "canine" ? 22 : 20;
  const H = type === "molar" ? 32 : type === "premolar" ? 30 : type === "canine" ? 34 : 28;
  const hw = W / 2, hh = H / 2;
  const CLIP_Y = 4;   // close crown at this y (slightly below equator)
  const hw2 = hw - 2;

  let pathD = "";
  if (crownOnly) {
    if (type === "incisor") {
      pathD = `M ${-hw} ${-hh} Q 0 ${-hh - 4} ${hw} ${-hh} L ${hw2} ${CLIP_Y} Q 0 ${CLIP_Y + 4} ${-hw2} ${CLIP_Y} Z`;
    } else if (type === "canine") {
      pathD = `M ${-hw} ${-hh + 6} Q 0 ${-hh - 6} ${hw} ${-hh + 6} L ${hw2} ${CLIP_Y} Q 0 ${CLIP_Y + 4} ${-hw2} ${CLIP_Y} Z`;
    } else if (type === "premolar") {
      pathD = `M ${-hw} ${-hh + 4} Q ${-hw/2} ${-hh - 4} 0 ${-hh + 2} Q ${hw/2} ${-hh - 4} ${hw} ${-hh + 4} L ${hw2} ${CLIP_Y} Q 0 ${CLIP_Y + 4} ${-hw2} ${CLIP_Y} Z`;
    } else {
      pathD = `M ${-hw} ${-hh + 4} Q ${-hw/2} ${-hh - 4} 0 ${-hh + 2} Q ${hw/2} ${-hh - 4} ${hw} ${-hh + 4} L ${hw} ${CLIP_Y} Q ${hw/2} ${CLIP_Y + 4} 0 ${CLIP_Y + 2} Q ${-hw/2} ${CLIP_Y + 4} ${-hw} ${CLIP_Y} Z`;
    }
  } else {
    if (type === "incisor") {
      pathD = `M ${-hw} ${-hh} Q 0 ${-hh - 4} ${hw} ${-hh} L ${hw - 2} ${hh - 6} Q 0 ${hh + 4} ${-hw + 2} ${hh - 6} Z`;
    } else if (type === "canine") {
      pathD = `M ${-hw} ${-hh + 6} Q 0 ${-hh - 6} ${hw} ${-hh + 6} L ${hw - 2} ${hh - 4} Q 0 ${hh + 4} ${-hw + 2} ${hh - 4} Z`;
    } else if (type === "premolar") {
      pathD = `M ${-hw} ${-hh + 4} Q ${-hw / 2} ${-hh - 4} 0 ${-hh + 2} Q ${hw / 2} ${-hh - 4} ${hw} ${-hh + 4} L ${hw - 2} ${hh - 4} Q 0 ${hh + 4} ${-hw + 2} ${hh - 4} Z`;
    } else {
      pathD = `M ${-hw} ${-hh + 4} Q ${-hw / 2} ${-hh - 4} 0 ${-hh + 2} Q ${hw / 2} ${-hh - 4} ${hw} ${-hh + 4} L ${hw} ${hh - 4} Q ${hw / 2} ${hh + 4} 0 ${hh - 2} Q ${-hw / 2} ${hh + 4} ${-hw} ${hh - 4} Z`;
    }
  }

  return (
    <g>
      <path d={pathD} className="tooth-body" />
      {!crownOnly && type === "molar" && (
        <g opacity="0.35">
          <ellipse cx={-W * 0.22} cy={-H * 0.18} rx={2.2} ry={2.6} fill="#9088B5" />
          <ellipse cx={W * 0.22} cy={-H * 0.18} rx={2.2} ry={2.6} fill="#9088B5" />
          <ellipse cx={-W * 0.22} cy={H * 0.18} rx={2.2} ry={2.6} fill="#9088B5" />
          <ellipse cx={W * 0.22} cy={H * 0.18} rx={2.2} ry={2.6} fill="#9088B5" />
        </g>
      )}
      {!crownOnly && type === "premolar" && (
        <g opacity="0.35">
          <ellipse cx={-W * 0.2} cy={-H * 0.1} rx={2} ry={2.4} fill="#9088B5" />
          <ellipse cx={W * 0.2} cy={-H * 0.1} rx={2} ry={2.4} fill="#9088B5" />
        </g>
      )}
      {!crownOnly && type === "canine" && (
        <ellipse cx={0} cy={-H * 0.2} rx={1.8} ry={3} fill="#9088B5" opacity="0.35" />
      )}
    </g>
  );
}

function stateClass(planning) {
  if (!planning) return "tooth-state-natural";
  // Prothèse takes visual priority over clinical status
  const p = planning.prothese || {};
  if (p.implant) return "tooth-state-implant";
  if (p.couronne) return "tooth-state-crown";
  if (p.bridge) return "tooth-state-bridge";
  if (planning.programme === "absente") return "tooth-state-absent";
  if (planning.programme === "extraction") return "tooth-state-extraction";
  return "tooth-state-natural";
}

function ToothChart({ planning, selected, onSelect, hovered, onHover }) {
  return (
    <svg viewBox="0 0 700 700" className="tooth-chart" preserveAspectRatio="xMidYMid meet"
      style={{ height: "100%", width: "auto", maxWidth: "100%", display: "block" }}>
      <defs>
        <radialGradient id="tooth-grad" cx="50%" cy="35%" r="65%">
          <stop offset="0%" stopColor="#FFFFFF" />
          <stop offset="60%" stopColor="#F5F2FC" />
          <stop offset="100%" stopColor="#D9CFEF" />
        </radialGradient>
        <radialGradient id="bg-glow" cx="50%" cy="50%" r="55%">
          <stop offset="0%" stopColor="#FFFFFF" stopOpacity="0.7" />
          <stop offset="100%" stopColor="#FFFFFF" stopOpacity="0" />
        </radialGradient>
      </defs>

      {/* faint center glow */}
      <ellipse cx={CX} cy={CY} rx={RX - 30} ry={RY - 40} fill="url(#bg-glow)" />

      {/* ── Gum band (base, flesh tone) ── */}
      <ellipse cx={CX} cy={CY} rx={RX} ry={RY}
        fill="none" stroke="#F0C4B4" strokeWidth="13" opacity="0.38" />

      {/* ── Guide chirurgical arcs (colored overlay on gum band) ── */}
      {TEETH.map(t => {
        const p = planning[t.num];
        if (!p || !p.guide) return null;
        const color = GUIDE_COLORS[p.guide];
        if (!color) return null;
        const delta = 8; // degrees half-span per tooth
        const [x1, y1] = polar(RX, RY, t.angle - delta);
        const [x2, y2] = polar(RX, RY, t.angle + delta);
        return (
          <path key={`guide-${t.num}`}
            d={`M ${x1} ${y1} A ${RX} ${RY} 0 0 1 ${x2} ${y2}`}
            stroke={color} strokeWidth="13" fill="none" strokeLinecap="round" opacity="0.88"
          />
        );
      })}

      {/* ── Teeth ── */}
      {TEETH.map(t => {
        const type = toothType(t.num);
        const [x, y] = polar(RX, RY, t.angle);
        const [nx, ny] = polar(NUM_RX, NUM_RY, t.angle);
        // Vue du dessus : rotation 180° de l'arc maxillaire (Q1+Q2)
        const rot = (t.q === 1 || t.q === 2) ? t.angle + 180 : t.angle;
        const isSelected = selected === t.num;
        const isHovered = hovered === t.num;
        const cls = `tooth-shape ${stateClass(planning[t.num])} ${isSelected || isHovered ? "tooth-selected" : ""}`;

        // Crown-only for plural implant group members (not the root/pilier tooth)
        const crownOnly = !!planning[t.num]?.implant_group_root;

        return (
          <g key={t.num}>
            {/* number badge */}
            <g
              onClick={() => onSelect(t.num)}
              onMouseEnter={() => onHover(t.num)}
              onMouseLeave={() => onHover(null)}
              style={{ cursor: "pointer" }}
            >
              <circle cx={nx} cy={ny} r={13} className="tooth-num-bg" />
              <text x={nx} y={ny} className="tooth-num">{t.num}</text>
            </g>
            {/* tooth body */}
            <g
              className={cls}
              transform={`translate(${x} ${y}) rotate(${rot})`}
              onClick={() => onSelect(t.num)}
              onMouseEnter={() => onHover(t.num)}
              onMouseLeave={() => onHover(null)}
              style={{ cursor: "pointer" }}
            >
              <circle cx={0} cy={0} r={22} fill="transparent" stroke="none" />
              <ToothShape type={type} crownOnly={crownOnly} />
              {planning[t.num]?.guide && (
                <GuideRing type={type} color={GUIDE_COLORS[planning[t.num].guide]} />
              )}
            </g>
          </g>
        );
      })}

      {/* center midline indicator */}
      <g opacity="0.18">
        <line x1={CX} y1={CY - RY + 80} x2={CX} y2={CY + RY - 80}
          stroke="#1B0F8A" strokeDasharray="3 5" />
      </g>
    </svg>
  );
}

window.ToothChart = ToothChart;
window.ToothShape = ToothShape;
window.TEETH = TEETH;
window.toothType = toothType;
window.GUIDE_COLORS = GUIDE_COLORS;
