// Interactive dental arch SVG (Universal numbering 1–32).
// Upper arch: 1–16 (right molar to left molar from patient view, drawn L→R as viewer sees).
// Lower arch: 17–32 (left molar to right molar).
// Each tooth has a health status: healthy | watch | issue.

const TEETH = [
  // upper (semicircle, top arc) — 16 teeth, viewer-perspective L→R = patient's right→left = numbers 1..16
  { n: 1,  status: 'healthy', name: '3rd Molar (UR)' },
  { n: 2,  status: 'healthy', name: '2nd Molar (UR)' },
  { n: 3,  status: 'watch',   name: '1st Molar (UR)', note: 'Early occlusal wear detected' },
  { n: 4,  status: 'healthy', name: '2nd Premolar (UR)'},
  { n: 5,  status: 'healthy', name: '1st Premolar (UR)'},
  { n: 6,  status: 'healthy', name: 'Canine (UR)'},
  { n: 7,  status: 'healthy', name: 'Lateral Incisor (UR)'},
  { n: 8,  status: 'healthy', name: 'Central Incisor (UR)'},
  { n: 9,  status: 'healthy', name: 'Central Incisor (UL)'},
  { n: 10, status: 'healthy', name: 'Lateral Incisor (UL)'},
  { n: 11, status: 'healthy', name: 'Canine (UL)'},
  { n: 12, status: 'healthy', name: '1st Premolar (UL)'},
  { n: 13, status: 'watch',   name: '2nd Premolar (UL)', note: 'Mild gingival recession' },
  { n: 14, status: 'issue',   name: '1st Molar (UL)', note: 'Suspected caries — distal surface' },
  { n: 15, status: 'healthy', name: '2nd Molar (UL)'},
  { n: 16, status: 'healthy', name: '3rd Molar (UL)'},
  // lower — 17..32 (viewer L→R = patient's left→right)
  { n: 17, status: 'healthy', name: '3rd Molar (LL)'},
  { n: 18, status: 'healthy', name: '2nd Molar (LL)'},
  { n: 19, status: 'healthy', name: '1st Molar (LL)'},
  { n: 20, status: 'healthy', name: '2nd Premolar (LL)'},
  { n: 21, status: 'healthy', name: '1st Premolar (LL)'},
  { n: 22, status: 'healthy', name: 'Canine (LL)'},
  { n: 23, status: 'healthy', name: 'Lateral Incisor (LL)'},
  { n: 24, status: 'watch',   name: 'Central Incisor (LL)', note: 'Mild plaque accumulation' },
  { n: 25, status: 'healthy', name: 'Central Incisor (LR)'},
  { n: 26, status: 'healthy', name: 'Lateral Incisor (LR)'},
  { n: 27, status: 'healthy', name: 'Canine (LR)'},
  { n: 28, status: 'healthy', name: '1st Premolar (LR)'},
  { n: 29, status: 'healthy', name: '2nd Premolar (LR)'},
  { n: 30, status: 'healthy', name: '1st Molar (LR)'},
  { n: 31, status: 'healthy', name: '2nd Molar (LR)'},
  { n: 32, status: 'healthy', name: '3rd Molar (LR)'},
];

const STATUS_LABEL = {
  healthy: { l:'Healthy',    bg:'var(--accent-soft)', fg:'var(--accent)' },
  watch:   { l:'Monitoring', bg:'var(--warn-soft)',   fg:'var(--warn)'   },
  issue:   { l:'Action needed', bg:'var(--danger-soft)', fg:'var(--danger)' },
};

// Build tooth shapes positioned on an upper and lower arch.
// Returns { tooth, cx, cy, rot, w, h } per tooth.
function buildLayout(width, archYTop, archYBot) {
  const cx0 = width / 2;
  const rX = width * 0.42;
  const rY = 90;
  const upper = [];
  const lower = [];
  const COUNT = 16;
  for (let i = 0; i < COUNT; i++) {
    const t = (i + 0.5) / COUNT; // 0..1
    // upper arc: angle goes from PI (left) to 0 (right) along TOP half
    const aU = Math.PI - t * Math.PI;
    const ux = cx0 + Math.cos(aU) * rX;
    const uy = archYTop - Math.sin(aU) * rY * 0.6 + rY; // anchor
    const urot = (90 - (aU * 180 / Math.PI));
    upper.push({ idx: i, n: i + 1, cx: ux, cy: uy, rot: urot });

    // lower arc: from PI (left) to 0 (right) along BOTTOM half
    const aL = Math.PI - t * Math.PI;
    const lx = cx0 + Math.cos(aL) * rX;
    const ly = archYBot + Math.sin(aL) * rY * 0.6 - rY;
    const lrot = -(90 - (aL * 180 / Math.PI));
    lower.push({ idx: i + 16, n: i + 17, cx: lx, cy: ly, rot: lrot });
  }
  return [...upper, ...lower];
}

// Tooth shape: rounded "molar-ish" shape — slightly different by tooth type
function toothPath(idx) {
  // central incisors are flatter & wider, canines pointier, molars round-square
  const pos = idx % 16;
  const isIncisor = pos >= 6 && pos <= 9;
  const isCanine  = pos === 5 || pos === 10;
  const isMolar   = pos <= 2 || pos >= 13;
  if (isIncisor) return "M -7,-9 q 7,-4 14,0 q 2,9 0,16 q -7,3 -14,0 q -2,-7 0,-16 z";
  if (isCanine)  return "M -7,-10 q 7,-5 14,0 q 3,9 -1,18 q -6,2 -12,0 q -4,-9 -1,-18 z";
  if (isMolar)   return "M -10,-9 q 10,-4 20,0 q 3,9 0,18 q -10,3 -20,0 q -3,-9 0,-18 z";
  // premolar
  return "M -8,-9 q 8,-3 16,0 q 2,9 0,17 q -8,3 -16,0 q -2,-8 0,-17 z";
}

function DentalArch({ selectedN, onSelect, statusMap }) {
  const W = 520, H = 320;
  const layout = React.useMemo(() => buildLayout(W, 50, H - 50), []);

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
      <defs>
        <filter id="softShadow" x="-20%" y="-20%" width="140%" height="140%">
          <feDropShadow dx="0" dy="2" stdDeviation="2" floodOpacity=".08"/>
        </filter>
      </defs>

      {/* arch guides */}
      <path d={`M ${W*0.08} ${H/2 - 12} Q ${W/2} -20 ${W*0.92} ${H/2 - 12}`}
        fill="none" stroke="var(--line)" strokeDasharray="2 4" />
      <path d={`M ${W*0.08} ${H/2 + 12} Q ${W/2} ${H+20} ${W*0.92} ${H/2 + 12}`}
        fill="none" stroke="var(--line)" strokeDasharray="2 4" />

      {/* labels */}
      <text className="arch-label" x={W/2} y="20"     textAnchor="middle">UPPER · MAXILLA</text>
      <text className="arch-label" x={W/2} y={H - 10} textAnchor="middle">LOWER · MANDIBLE</text>

      {/* teeth */}
      {layout.map((p) => {
        const tooth = TEETH[p.idx];
        const status = statusMap?.[tooth.n] ?? tooth.status;
        const sel = selectedN === tooth.n;
        return (
          <g key={tooth.n} transform={`translate(${p.cx},${p.cy}) rotate(${p.rot})`} style={{ filter:'url(#softShadow)' }}>
            <path
              d={toothPath(p.idx)}
              className={`tooth ${status} ${sel ? 'selected' : ''}`}
              strokeWidth="1.2"
              onClick={() => onSelect(tooth.n)}
              onMouseEnter={() => onSelect(tooth.n, true)}
              style={{
                animation: `pop .5s var(--ease-out) ${0.02 * p.idx}s backwards`,
              }}
            />
            <text className="tooth-num" textAnchor="middle" y="2" transform={`rotate(${-p.rot})`}>
              {tooth.n}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

window.DentalArch = DentalArch;
window.TEETH = TEETH;
window.STATUS_LABEL = STATUS_LABEL;
