// JammSanté Dentiste — Odontogramme FDI interactif (canvas clinique par surface)

// Retourne la config des 4 zones latérales + centre selon quadrant/arcade
function zonesFor(n) {
  const up = isUpper(n);
  const q = Math.floor(n/10);
  const rightIsMesial = (q===1||q===4); // moitié gauche du chart => mésial à droite
  const vest = up ? 'top' : 'bottom';
  const ling = up ? 'bottom' : 'top';
  const mes = rightIsMesial ? 'right' : 'left';
  const dis = rightIsMesial ? 'left' : 'right';
  const map = {}; map[vest]='V'; map[ling]='L'; map[mes]='M'; map[dis]='D';
  return { top:map.top, right:map.right, bottom:map.bottom, left:map.left, center: isAnterior(n) ? 'I' : 'O' };
}

const ZONE_PATH = {
  top:    'M0,0 L30,0 L20,10 L10,10 Z',
  right:  'M30,0 L30,30 L20,20 L20,10 Z',
  bottom: 'M0,30 L30,30 L20,20 L10,20 Z',
  left:   'M0,0 L0,30 L10,20 L10,10 Z',
  center: 'M10,10 L20,10 L20,20 L10,20 Z',
};

function toothFindings(findings, tooth, layer) {
  return findings.filter(f => f.tooth === tooth && (layer === 'both' || f.layer === layer));
}

// Couleur d'une surface donnée
function surfaceColor(fs, zoneLabel) {
  // priorité: carie/extraction/fracture > actes
  const rank = { carie:5, extraction:5, fracture:5, endo:4, amalg:3, obt:3, sealant:2 };
  let best=null, br=-1;
  for (const f of fs) {
    if (f.s && f.s.includes(zoneLabel)) {
      const r = rank[f.code] ?? 1;
      if (r > br) { br=r; best=f; }
    }
  }
  return best ? { color: LEG[best.code].color, layer: best.layer, code: best.code } : null;
}

function Tooth({ n, findings, layer, selected, selectedSurface, onSelect, onSurface }) {
  const z = zonesFor(n);
  const fs = toothFindings(findings, n, layer);
  const whole = fs.find(f => f.s === null);
  const absente = whole && whole.code === 'absente';
  const extraction = fs.find(f => f.code === 'extraction' && f.s === null);
  const couronne = whole && whole.code === 'couronne';
  const implant = whole && whole.code === 'implant';
  const endoWhole = fs.find(f => f.code === 'endo');
  const isSel = selected === n;

  const zoneFill = (pos, label) => {
    if (label === undefined) return 'transparent';
    const sc = surfaceColor(fs, label);
    if (!sc) return 'transparent';
    const dashed = sc.layer === 'plan';
    return { fill: sc.color, dashed };
  };

  return <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:3, width:34 }}>
    <div style={{ fontSize:10, fontWeight:700, color: isSel ? '#0369A1' : 'var(--d-fg-faint)', fontFamily:'JetBrains Mono, monospace' }}>{n}</div>
    <svg width={32} height={32} viewBox="-1 -1 32 32" onClick={() => onSelect(n)}
      style={{ cursor:'pointer', borderRadius:6, background: isSel ? 'var(--d-sky-bg)' : 'transparent', outline: isSel ? '2px solid #0369A1' : 'none', transition:'all 120ms' }}>
      {couronne && <rect x="-1" y="-1" width="32" height="32" rx="4" fill="#F59E0B" opacity="0.18" />}
      {['top','right','bottom','left','center'].map(pos => {
        const label = z[pos];
        const sc = surfaceColor(fs, label);
        const fill = sc ? sc.color : 'var(--d-tooth)';
        const dashed = sc && sc.layer === 'plan';
        const isSurfSel = isSel && selectedSurface === label;
        return <path key={pos} d={ZONE_PATH[pos]} fill={sc ? fill : 'var(--d-tooth)'}
          fillOpacity={sc ? (dashed ? 0.42 : 0.92) : 1}
          stroke={isSurfSel ? '#0369A1' : (dashed ? sc.color : 'var(--d-border-strong)')}
          strokeWidth={isSurfSel ? 1.6 : (dashed ? 1.2 : 0.6)} strokeDasharray={dashed ? '2 1.5' : 'none'}
          onClick={(e) => { e.stopPropagation(); onSelect(n); onSurface(label); }}
          style={{ cursor:'pointer' }} />;
      })}
      {endoWhole && <circle cx="15" cy="15" r="2.4" fill="#8B5CF6" />}
      {implant && <g stroke="#0D9488" strokeWidth="1.6"><line x1="15" y1="7" x2="15" y2="23"/><line x1="11" y1="11" x2="19" y2="11"/><line x1="11" y1="15" x2="19" y2="15"/><line x1="11" y1="19" x2="19" y2="19"/></g>}
      {absente && <g stroke="#94A3B8" strokeWidth="1.6"><line x1="4" y1="4" x2="26" y2="26"/><line x1="26" y1="4" x2="4" y2="26"/></g>}
      {extraction && <g stroke="#B91C1C" strokeWidth="2"><line x1="4" y1="4" x2="26" y2="26"/><line x1="26" y1="4" x2="4" y2="26"/></g>}
    </svg>
  </div>;
}

function ArchRow({ teeth, ...rest }) {
  return <div style={{ display:'flex', gap:3 }}>
    {teeth.map((n,i) => <React.Fragment key={n}>
      {i === teeth.length/2 && <div style={{ width:10 }} />}
      <Tooth n={n} {...rest} />
    </React.Fragment>)}
  </div>;
}

function Odontogram({ findings, layer, selected, selectedSurface, onSelect, onSurface, showTemp }) {
  const rest = { findings, layer, selected, selectedSurface, onSelect, onSurface };
  return <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:10 }}>
    <ArchRow teeth={[...FDI.perm.ur, ...FDI.perm.ul]} {...rest} />
    {showTemp && <div style={{ display:'flex', gap:3, opacity:0.95 }}>
      <div style={{ width:'calc(4 * 37px)' }} />
      <ArchRow teeth={[...FDI.temp.ur, ...FDI.temp.ul]} {...rest} />
    </div>}
    <div style={{ width:'70%', height:1, background:'var(--d-border)', margin:'2px 0' }} />
    {showTemp && <div style={{ display:'flex', gap:3, opacity:0.95 }}>
      <div style={{ width:'calc(4 * 37px)' }} />
      <ArchRow teeth={[...FDI.temp.lr, ...FDI.temp.ll]} {...rest} />
    </div>}
    <ArchRow teeth={[...FDI.perm.lr, ...FDI.perm.ll]} {...rest} />
  </div>;
}

function OdontoLegend() {
  return <div style={{ display:'flex', flexWrap:'wrap', gap:'8px 16px' }}>
    {D_LEGEND.filter(l => l.code!=='sain').map(l => (
      <div key={l.code} style={{ display:'flex', alignItems:'center', gap:6, fontSize:11.5, color:'var(--d-fg-muted)' }}>
        <span style={{ width:12, height:12, borderRadius:3, background:l.color, opacity: l.code==='absente'?0.4:0.9, flexShrink:0 }} />{l.label}
      </div>
    ))}
    <div style={{ display:'flex', alignItems:'center', gap:6, fontSize:11.5, color:'var(--d-fg-muted)' }}>
      <span style={{ width:12, height:12, borderRadius:3, border:'1.4px dashed var(--d-fg-subtle)', flexShrink:0 }} />Planifié (contour)
    </div>
  </div>;
}

// Détail d'une dent : surfaces, historique, ajout d'acte/diagnostic
function ToothDetail({ tooth, findings, selectedSurface, onSurface, onAdd, onRemove }) {
  if (!tooth) return <div style={{ padding:'40px 20px', textAlign:'center', color:'var(--d-fg-faint)' }}>
    <Icon name="mouse-pointer-click" size={26} /><div style={{ fontSize:13, marginTop:10 }}>Cliquez une dent ou une surface</div>
    <div style={{ fontSize:11.5, marginTop:4 }}>Chairside : &lt; 3 s pour charter une lésion</div></div>;
  const z = zonesFor(tooth);
  const surfLabels = { M:'Mésiale', D:'Distale', V:'Vestibulaire', L:'Linguale/Palatine', O:'Occlusale', I:'Incisale' };
  const all = findings.filter(f => f.tooth === tooth).sort((a,b)=> (b.date||'').localeCompare(a.date||''));
  const surfaces = ['M','D', isAnterior(tooth)?'I':'O','V','L'];
  return <div>
    <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:14 }}>
      <div style={{ width:40, height:40, borderRadius:10, background:'var(--d-sky-bg)', color:'#0369A1', display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontFamily:'JetBrains Mono, monospace', fontSize:16 }}>{tooth}</div>
      <div><div style={{ fontSize:14, fontWeight:600, color:'var(--d-fg)' }}>Dent {tooth}</div>
        <div style={{ fontSize:11.5, color:'var(--d-fg-subtle)' }}>{isAnterior(tooth)?'Antérieure':'Postérieure'} · {isUpper(tooth)?'Maxillaire':'Mandibule'}</div></div>
    </div>
    <div style={{ fontSize:11, fontWeight:700, color:'var(--d-fg-subtle)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:8 }}>Surface</div>
    <div style={{ display:'flex', gap:5, marginBottom:16 }}>
      {surfaces.map(s => <button key={s} onClick={() => onSurface(selectedSurface===s?null:s)}
        style={{ flex:1, padding:'8px 0', borderRadius:8, border:'1px solid '+(selectedSurface===s?'#0369A1':'var(--d-border)'), background: selectedSurface===s?'var(--d-sky-bg)':'var(--d-surface)', color:selectedSurface===s?'#0369A1':'var(--d-fg-muted)', fontWeight:700, fontSize:12, cursor:'pointer', fontFamily:'inherit' }} title={surfLabels[s]}>{s}</button>)}
    </div>
    <div style={{ fontSize:11, fontWeight:700, color:'var(--d-fg-subtle)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:8 }}>Ajouter - {selectedSurface ? surfLabels[selectedSurface] : 'dent entière'}</div>
    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, marginBottom:18 }}>
      {D_LEGEND.filter(l => !['sain'].includes(l.code)).map(l => (
        <button key={l.code} onClick={() => onAdd({ tooth, s: selectedSurface? [selectedSurface] : null, code:l.code, layer:'plan', date:'2026-06-26', note:'' })}
          style={{ display:'flex', alignItems:'center', gap:7, padding:'7px 9px', borderRadius:8, border:'1px solid var(--d-border)', background:'var(--d-surface)', cursor:'pointer', fontSize:11.5, color:'var(--d-fg-muted)', fontFamily:'inherit', textAlign:'left' }}
          onMouseEnter={e=>e.currentTarget.style.background='var(--d-surface-2)'} onMouseLeave={e=>e.currentTarget.style.background='var(--d-surface)'}>
          <span style={{ width:11, height:11, borderRadius:3, background:l.color, flexShrink:0 }} />{l.label}</button>
      ))}
    </div>
    <div style={{ fontSize:11, fontWeight:700, color:'var(--d-fg-subtle)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:8 }}>Historique - dent {tooth}</div>
    {all.length === 0 ? <div style={{ fontSize:12.5, color:'var(--d-fg-faint)' }}>Aucun acte enregistré.</div> :
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {all.map((f,i) => <div key={i} style={{ display:'flex', gap:10, padding:'9px 11px', borderRadius:9, background:'var(--d-surface-2)', alignItems:'flex-start' }}>
          <span style={{ width:10, height:10, borderRadius:3, background:LEG[f.code].color, marginTop:3, flexShrink:0 }} />
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:12.5, fontWeight:600, color:'var(--d-fg)' }}>{LEG[f.code].label}{f.s?' · '+f.s.join(''):''}
              <span style={{ marginLeft:6, fontSize:10, fontWeight:600, color: f.layer==='plan'?'#B45309':'#0369A1' }}>{f.layer==='plan'?'planifié':'existant'}</span></div>
            <div style={{ fontSize:11, color:'var(--d-fg-subtle)', fontFamily:'JetBrains Mono, monospace', marginTop:1 }}>{f.date}</div>
            {f.note && <div style={{ fontSize:11.5, color:'var(--d-fg-muted)', marginTop:3, lineHeight:1.4 }}>{f.note}</div>}
          </div>
          {f.layer==='plan' && <button onClick={() => onRemove(f)} style={{ border:'none', background:'transparent', cursor:'pointer', color:'var(--d-fg-faint)', padding:2 }}><Icon name="x" size={14} /></button>}
        </div>)}
      </div>}
  </div>;
}

Object.assign(window, { Odontogram, OdontoLegend, ToothDetail, zonesFor });
