// PerioChart.jsx — Periodontal charting MVP (6-site grid, BOP, recession, mobility).
const { useState, useEffect, useMemo, useCallback } = React;

const AB3030 =
  'Periodontal charting draft — clinical documentation for licensed dentist review only. ' +
  'Not submitted to patient chart. AB 3030 / SB 1120 HITL applies.';

function PerioChart() {
  const SS = () => window.SuiteState;
  const BR = () => window.SuiteBridge;

  const [chart, setChart] = useState(null);
  const [selectedTooth, setSelectedTooth] = useState(14);
  const [numbering, setNumbering] = useState('universal');
  const [suggestions, setSuggestions] = useState([]);
  const [copied, setCopied] = useState(false);
  const [msg, setMsg] = useState('');

  const loadChart = useCallback(() => {
    const s = SS();
    const b = BR();
    if (!s || !b) return;
    var c = s.getPerioChart();
    if (!c) {
      c = s.defaultPerioChart();
      s.savePerioChart(c);
    }
    setChart(c);
    setNumbering(s.getNumbering());
  }, []);

  useEffect(() => { loadChart(); }, [loadChart]);

  useEffect(() => {
    const s = SS();
    const b = BR();
    if (!s || !b) return;
    const scribe = s.getScribeNote();
    const text = (scribe && (scribe.transcript || '')) + ' ' + (scribe && scribe.note ? [scribe.note.objective, scribe.note.assessment].join(' ') : '');
    setSuggestions(b.parsePerioFromText(text));
  }, [chart]);

  const stats = useMemo(() => {
    const b = BR();
    return b && chart ? b.perioStats(chart) : null;
  }, [chart]);

  const sites = (BR() && BR().PERIO_SITES) || ['MB', 'B', 'DB', 'ML', 'L', 'DL'];
  const teeth = (BR() && BR().UNIVERSAL_TEETH) || [];

  const displayTooth = (univ) => {
    if (numbering === 'fdi' && BR()) return BR().UNIV_TO_FDI[univ] || univ;
    return univ;
  };

  const persist = useCallback((next) => {
    const s = SS();
    if (s) s.savePerioChart(next);
    setChart(next);
  }, []);

  const toggleNumbering = () => {
    const next = numbering === 'universal' ? 'fdi' : 'universal';
    setNumbering(next);
    const s = SS();
    if (s) s.setNumbering(next);
  };

  const updateSite = (tooth, site, field, val) => {
    const b = BR();
    if (!b || !chart) return;
    const next = JSON.parse(JSON.stringify(chart));
    const rec = b.ensureTooth(next, tooth);
    if (field === 'depth') rec.sites[site].depth = val;
    if (field === 'bop') rec.sites[site].bop = !!val;
    persist(next);
  };

  const updateToothField = (tooth, field, val) => {
    const b = BR();
    if (!b || !chart) return;
    const next = JSON.parse(JSON.stringify(chart));
    const rec = b.ensureTooth(next, tooth);
    rec[field] = val;
    persist(next);
  };

  const applySuggestions = () => {
    const b = BR();
    const s = SS();
    if (!b || !s || !chart) return;
    const next = b.applyPerioSuggestions(chart, suggestions.filter((x) => x.tooth));
    persist(next);
    setMsg('Applied ' + suggestions.filter((x) => x.tooth).length + ' scribe suggestion(s) to chart.');
  };

  const sendToTreatmentPlan = () => {
    const s = SS();
    const b = BR();
    if (!s || !b || !chart) return;
    const procs = b.proceduresFromPerio(chart);
    const existing = s.getTreatmentPlan();
    const base = existing || b.planFromSOAP({ assessment: '', plan: '' }, { title: 'Perio-driven plan', perioRef: chart.id });
    const merged = b.mergePerioIntoPlan(base, procs);
    merged.perioRef = chart.id;
    s.saveTreatmentPlan(merged);
    setMsg('Perio procedures added to treatment plan — open Treatment Plan tab to review.');
  };

  const copySummary = async () => {
    const b = BR();
    if (!b || !chart) return;
    try {
      await navigator.clipboard.writeText(b.formatPerioSummary(chart, stats));
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      setMsg('Copy failed.');
    }
  };

  const toothRec = chart && chart.teeth && chart.teeth[String(selectedTooth)]
    ? chart.teeth[String(selectedTooth)]
    : (BR() ? BR().emptyToothRecord() : { sites: {}, recession: '', mobility: '0' });

  return (
    <div className="wrap">
      <div className="banner info" style={{ marginBottom: 14 }}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--blue)" strokeWidth="1.8">
          <path d="M12 4l8.5 15H3.5z" /><path d="M12 10v4.5M12 17.4v.1" />
        </svg>
        <div>{AB3030}</div>
      </div>
      <div className="banner warn" style={{ marginBottom: 14 }}>
        <b>Clinical draft — not submitted to chart.</b> Status: PENDING_HITL_REVIEW.
      </div>

      {stats && stats.totalSites > 0 && (
        <div className="grid g4" style={{ marginBottom: 16 }}>
          <div className="kpi">
            <div className="k-l">Bleeding %</div>
            <div className="k-v">{stats.bleedingPct != null ? stats.bleedingPct + '%' : '—'}</div>
          </div>
          <div className="kpi">
            <div className="k-l">Sites ≥ 4 mm</div>
            <div className="k-v">{stats.sitesGe4}</div>
          </div>
          <div className="kpi">
            <div className="k-l">Teeth affected</div>
            <div className="k-v">{stats.teethAffected}</div>
          </div>
          <div className="kpi">
            <div className="k-l">Sites charted</div>
            <div className="k-v">{stats.totalSites}</div>
          </div>
        </div>
      )}

      <div className="card">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 10 }}>
          <h3 style={{ margin: 0 }}>Periodontal chart</h3>
          <div className="seg">
            <button type="button" className={numbering === 'universal' ? 'on' : ''} onClick={toggleNumbering}>Universal</button>
            <button type="button" className={numbering === 'fdi' ? 'on' : ''} onClick={toggleNumbering}>FDI</button>
          </div>
        </div>
        <div className="hint" style={{ marginTop: 8 }}>
          Select a tooth, enter 6-site probing depths (mm), BOP, recession, and mobility. Demo data stays in localStorage only.
        </div>

        {suggestions.length > 0 && (
          <div className="banner info" style={{ marginTop: 12 }}>
            <div>
              <b>Scribe perio hints ({suggestions.length})</b>
              <ul style={{ margin: '8px 0 0', paddingLeft: 18, fontSize: 12 }}>
                {suggestions.slice(0, 5).map((s, i) => (
                  <li key={i}>
                    {s.tooth ? 'Tooth #' + displayTooth(s.tooth) + (s.depth ? ': ' + s.depth + ' mm' : '') : s.note || 'Keyword match'}
                  </li>
                ))}
              </ul>
              <button type="button" className="btn btn-sm" style={{ marginTop: 10 }} onClick={applySuggestions}>
                Apply tooth-specific suggestions
              </button>
            </div>
          </div>
        )}

        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 14, maxHeight: 120, overflowY: 'auto' }}>
          {teeth.map((t) => (
            <button
              key={t}
              type="button"
              className={'btn btn-sm' + (selectedTooth === t ? ' btn-primary' : '')}
              style={{ minWidth: 36, padding: '4px 6px' }}
              onClick={() => setSelectedTooth(t)}
            >
              {displayTooth(t)}
            </button>
          ))}
        </div>
      </div>

      <div className="card" style={{ marginTop: 16 }}>
        <h3>Tooth {displayTooth(selectedTooth)} — 6-site grid</h3>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12, marginTop: 10 }}>
          <thead>
            <tr style={{ borderBottom: '1px solid var(--border)' }}>
              <th style={{ textAlign: 'left', padding: 6 }}>Site</th>
              <th style={{ textAlign: 'left', padding: 6 }}>Depth (mm)</th>
              <th style={{ textAlign: 'left', padding: 6 }}>BOP</th>
            </tr>
          </thead>
          <tbody>
            {sites.map((site) => (
              <tr key={site} style={{ borderBottom: '1px solid var(--border)' }}>
                <td style={{ padding: 6, fontWeight: 600 }}>{site}</td>
                <td style={{ padding: 6 }}>
                  <input
                    type="number"
                    min="0"
                    max="12"
                    value={(toothRec.sites && toothRec.sites[site] && toothRec.sites[site].depth) || ''}
                    onChange={(e) => updateSite(selectedTooth, site, 'depth', e.target.value)}
                    style={{ width: 56, padding: 4, borderRadius: 6, border: '1px solid var(--border2)', background: 'var(--bg)', color: 'var(--text)' }}
                  />
                </td>
                <td style={{ padding: 6 }}>
                  <input
                    type="checkbox"
                    checked={!!(toothRec.sites && toothRec.sites[site] && toothRec.sites[site].bop)}
                    onChange={(e) => updateSite(selectedTooth, site, 'bop', e.target.checked)}
                  />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        <div className="num-grid" style={{ marginTop: 14 }}>
          <div className="field">
            <label>Recession (mm)</label>
            <input value={toothRec.recession || ''} onChange={(e) => updateToothField(selectedTooth, 'recession', e.target.value)} />
          </div>
          <div className="field">
            <label>Mobility (0–3)</label>
            <select value={toothRec.mobility || '0'} onChange={(e) => updateToothField(selectedTooth, 'mobility', e.target.value)}>
              {['0', '1', '2', '3'].map((m) => <option key={m} value={m}>{m}</option>)}
            </select>
          </div>
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 16 }}>
        <button type="button" className="btn btn-primary btn-sm" onClick={sendToTreatmentPlan}>
          Send findings to treatment plan
        </button>
        <button type="button" className="btn btn-sm" onClick={copySummary}>
          {copied ? 'Copied' : 'Copy perio summary'}
        </button>
        <button type="button" className="btn btn-sm btn-ghost" onClick={() => { location.hash = '#scribe'; }}>
          Open Voice Scribe
        </button>
        <button type="button" className="btn btn-sm btn-ghost" onClick={() => { location.hash = '#treatment-plan'; }}>
          Open treatment plan
        </button>
      </div>
      {msg && <div className="banner ok" style={{ marginTop: 12, fontSize: 12 }}>{msg}</div>}
    </div>
  );
}

window.PerioChart = PerioChart;
