// GapFeatures.jsx — G1–G12 gap feature screens (React 18 CDN, window globals, no imports)

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

const AB3030 =
  'Information only — not a clinical recommendation. Review with your dentist. AI-assisted content (AB 3030).';
const AI_BADGE = 'AI-assisted · HITL reviewed';

function DisclaimerBanner({ extra }) {
  return (
    <div className="disclaimer-banner t-fine">
      {AB3030} {extra || ''}
    </div>
  );
}

function AiBadge() {
  return <span className="hitl-badge badge badge-gray">{AI_BADGE}</span>;
}

function PageShell({ title, children, go }) {
  return (
    <div className="screen-container gap-screen animate-fade-in-up">
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => (go ? go('landing') : window.TDA_go?.('landing'))} style={{ marginBottom: 16, paddingLeft: 0 }}>
        ← Home
      </button>
      <div className="screen-hero">
        <h1>{title}</h1>
      </div>
      {children}
    </div>
  );
}

const PROCEDURES = [
  { id: 'prophy', label: 'Cleaning (prophy)' },
  { id: 'bws', label: 'Bitewing X-rays' },
  { id: 'filling', label: 'Filling' },
  { id: 'crown', label: 'Crown' },
  { id: 'rct', label: 'Root canal' },
  { id: 'extraction', label: 'Extraction' },
  { id: 'night_guard', label: 'Night guard' },
  { id: 'implant', label: 'Implant' },
];

function BenefitBomber({ go }) {
  const daysLeft = useMemo(() => {
    const end = new Date(new Date().getFullYear(), 11, 31);
    return Math.max(0, Math.ceil((end - new Date()) / 86400000));
  }, []);
  const month = new Date().toLocaleString('en-US', { month: 'long' });
  const [deductible, setDeductible] = useState('');
  const [annualMax, setAnnualMax] = useState('');
  const [planType, setPlanType] = useState('PPO');
  const [selected, setSelected] = useState(['prophy', 'bws']);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState(null);
  const [error, setError] = useState('');

  const toggle = (id) => {
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  };

  const calculate = async () => {
    setLoading(true);
    setError('');
    try {
      const resp = await fetch('/api/benefit-bomber', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          deductibleRemaining: Number(deductible) || 0,
          annualMaxRemaining: Number(annualMax) || 0,
          planType,
          procedures: selected,
        }),
      });
      const data = await resp.json();
      if (!resp.ok || !data.ok) throw new Error(data.error || 'Calculation failed');
      setResults(data.ranked || []);
    } catch (e) {
      setError(String(e.message || e));
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Benefit Bomber" go={go}>
      <p className="section-subtitle" style={{ marginBottom: 16 }}>
        Make the most of your remaining benefits — {month}, {daysLeft} days left in the plan year.
      </p>
      <DisclaimerBanner />
      <div className="field-stack">
        <label>
          <span className="field-label">Deductible remaining ($)</span>
          <input type="number" className="input" value={deductible} onChange={(e) => setDeductible(e.target.value)} />
        </label>
        <label>
          <span className="field-label">Annual max remaining ($)</span>
          <input type="number" className="input" value={annualMax} onChange={(e) => setAnnualMax(e.target.value)} />
        </label>
        <label>
          <span className="field-label">Plan type</span>
          <select className="input" value={planType} onChange={(e) => setPlanType(e.target.value)}>
            {['PPO', 'HMO', 'Indemnity', 'Self-Pay'].map((p) => <option key={p} value={p}>{p}</option>)}
          </select>
        </label>
      </div>
      <div style={{ marginBottom: 16 }}>
        <p className="section-title" style={{ fontSize: '1rem', marginBottom: 8 }}>Procedures to compare</p>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {PROCEDURES.map((p) => (
            <label key={p.id} className={`chip-select${selected.includes(p.id) ? ' selected' : ''}`}>
              <input type="checkbox" checked={selected.includes(p.id)} onChange={() => toggle(p.id)} style={{ margin: 0 }} />
              {p.label}
            </label>
          ))}
        </div>
      </div>
      <button type="button" className="btn btn-primary btn-lg btn-block" onClick={calculate} disabled={loading || !selected.length}>
        {loading ? 'Calculating…' : 'Calculate'}
      </button>
      {error && <p style={{ color: 'var(--color-danger)', marginTop: 12 }}>{error}</p>}
      {results && (
        <div style={{ marginTop: 24 }}>
          <h2 className="section-title" style={{ fontSize: '1.125rem', marginBottom: 12 }}>Best value now</h2>
          {results.map((r, i) => (
            <div key={r.procedure} className="card" style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <strong>#{i + 1} {r.procedure}</strong>
                <span className="badge badge-green">${r.patientCost} est. out-of-pocket</span>
              </div>
              <p style={{ fontSize: 13, color: '#6B7280', margin: '8px 0 0' }}>
                Fee ${r.fee} · {r.coverage}% covered · Save ~${r.savingsIfDoneNow} vs waiting
              </p>
            </div>
          ))}
          <p className="t-fine" style={{ marginTop: 12 }}>Estimates based on typical plan structures. Verify benefits with your insurer.</p>
        </div>
      )}
    </PageShell>
  );
}

const SYMPTOMS = [
  { id: 'severe_pain', label: 'Severe pain', weight: 3 },
  { id: 'swelling', label: 'Swelling face/jaw', weight: 4 },
  { id: 'knocked_out', label: 'Knocked-out tooth', weight: 5 },
  { id: 'broken_tooth', label: 'Broken tooth', weight: 2 },
  { id: 'bleeding', label: "Bleeding won't stop", weight: 4 },
  { id: 'breathing', label: 'Difficulty breathing/swallowing', weight: 5 },
  { id: 'fever_pain', label: 'Fever + dental pain', weight: 4 },
  { id: 'lost_filling', label: 'Lost filling/crown (no pain)', weight: 1 },
  { id: 'braces_wire', label: 'Broken braces wire', weight: 1 },
];

function computeSeverity(selected) {
  let score = 0;
  for (const s of SYMPTOMS) {
    if (selected.includes(s.id)) score += s.weight;
  }
  return Math.min(10, Math.max(1, score));
}

function Dental911({ go }) {
  const [selected, setSelected] = useState([]);
  const [aiResult, setAiResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const severity = computeSeverity(selected);

  const toggle = (id) => setSelected((p) => (p.includes(id) ? p.filter((x) => x !== id) : [...p, id]));

  const urgencyLabel =
    severity >= 9 ? 'Call 911 or ER NOW' :
    severity >= 7 ? 'Same-day urgency' :
    severity >= 4 ? 'Within 24 hours' : 'Schedule soon';

  const fetchAi = async () => {
    if (severity >= 8) return;
    setLoading(true);
    try {
      const resp = await fetch('/api/dental-911', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          symptoms: selected.map((id) => SYMPTOMS.find((s) => s.id === id)?.label || id),
          severityScore: severity,
        }),
      });
      const data = await resp.json();
      setAiResult(data);
    } catch {
      setAiResult({ message: 'Could not load additional guidance.' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Dental Emergency? Start Here." go={go}>
      <div className="emergency-banner">
        <strong>Rule-based triage first — no AI for severity 8+</strong>
      </div>
      <p className="section-subtitle" style={{ marginBottom: 16 }}>Tap all symptoms that apply:</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 8, marginBottom: 16 }}>
        {SYMPTOMS.map((s) => (
          <button key={s.id} type="button" onClick={() => toggle(s.id)} className={`chip-select${selected.includes(s.id) ? ' selected' : ''}`} style={{ textAlign: 'left', width: '100%' }}>
            {s.label}
          </button>
        ))}
      </div>
      {selected.length > 0 && (
        <div className={severity >= 9 ? 'emergency-banner' : 'card'} style={{
          marginBottom: 16,
          background: severity >= 9 ? undefined : severity >= 7 ? 'var(--color-warning-light)' : 'var(--color-accent-light)',
          color: severity >= 9 ? undefined : 'var(--color-text-primary)',
        }}>
          <p style={{ fontSize: 13, opacity: 0.9 }}>Severity {severity}/10</p>
          <h2 style={{ margin: '8px 0', fontSize: 22 }}>{urgencyLabel}</h2>
          {severity >= 9 && (
            <a href="tel:911" style={{ display: 'inline-block', marginTop: 12, background: '#fff', color: '#DC2626', padding: '12px 20px', borderRadius: 12, fontWeight: 700, textDecoration: 'none' }}>
              Call 911
            </a>
          )}
          {selected.includes('knocked_out') && (
            <p style={{ marginTop: 12, fontWeight: 600 }}>Keep tooth moist — milk, saline, or saliva. Call NOW.</p>
          )}
        </div>
      )}
      {severity >= 7 && severity < 9 && (
        <button type="button" className="btn btn-secondary btn-block" onClick={() => go?.('directory')} style={{ marginBottom: 12 }}>
          Find emergency dentist near me
        </button>
      )}
      {selected.length > 0 && severity <= 7 && (
        <button type="button" className="btn btn-primary btn-block" onClick={fetchAi} disabled={loading}>
          {loading ? 'Loading…' : 'Get more guidance (AI)'}
        </button>
      )}
      {aiResult && severity <= 7 && (
        <div className="card card-raised" style={{ marginTop: 16 }}>
          <AiBadge />
          <DisclaimerBanner />
          <p style={{ marginTop: 8 }}>{aiResult.summary || aiResult.message || aiResult.doNow}</p>
        </div>
      )}
    </PageShell>
  );
}

function SecondOpinion({ go }) {
  const [treatment, setTreatment] = useState('');
  const [cost, setCost] = useState('');
  const [concern, setConcern] = useState('Cost');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const analyze = async () => {
    setLoading(true);
    try {
      const resp = await fetch('/api/second-opinion', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          treatmentDescription: treatment,
          estimatedCost: Number(cost) || 0,
          concernType: concern,
          sessionId: `so_${Date.now()}`,
        }),
      });
      const data = await resp.json();
      setResult(data);
    } catch {
      setResult({ error: 'Analysis unavailable' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Second Opinion" go={go}>
      <p className="section-subtitle">Not sure about a treatment recommendation? You have the right to a second opinion.</p>
      <DisclaimerBanner extra="Do not enter names, dates of birth, or member IDs." />
      <textarea className="input" value={treatment} onChange={(e) => setTreatment(e.target.value.slice(0, 500))} placeholder="Describe the recommended treatment (no PHI)" rows={4} style={{ marginBottom: 12 }} />
      <input type="number" className="input" value={cost} onChange={(e) => setCost(e.target.value)} placeholder="Estimated cost ($)" style={{ marginBottom: 12 }} />
      <select className="input" value={concern} onChange={(e) => setConcern(e.target.value)} style={{ marginBottom: 16 }}>
        {['Cost', 'Second opinion on necessity', 'Want alternatives', 'Just checking'].map((c) => <option key={c}>{c}</option>)}
      </select>
      <button type="button" className="btn btn-primary btn-block" onClick={analyze} disabled={loading || !treatment.trim()}>
        {loading ? 'Analyzing…' : 'Analyze'}
      </button>
      {result && !result.error && (
        <div className="card card-raised" style={{ marginTop: 20 }}>
          {result.flag && (
            <span className={`badge badge-${result.flag === 'GREEN' ? 'green' : result.flag === 'YELLOW' ? 'yellow' : 'red'}`}>
              {result.flag}
            </span>
          )}
          {result.hitlBanner && <p style={{ fontSize: 13, color: '#92400E', marginTop: 8 }}>{result.hitlBanner}</p>}
          <AiBadge />
          <ul style={{ marginTop: 12, paddingLeft: 20 }}>{(result.questions || []).map((q) => <li key={q} style={{ marginBottom: 6 }}>{q}</li>)}</ul>
          <p style={{ fontSize: 14, color: '#4B5563' }}>{result.costContext}</p>
          <p style={{ marginTop: 8 }}>{result.assessment}</p>
          <button type="button" className="btn btn-secondary btn-sm" onClick={() => go?.('directory')} style={{ marginTop: 12 }}>
            Find a dentist for second opinion
          </button>
        </div>
      )}
    </PageShell>
  );
}

const MCP_INTEGRATIONS = [
  { name: 'NexHealth', category: 'Scheduling', status: 'LIVE', blurb: 'Scheduling + patient messaging' },
  { name: 'Synchronizer.io', category: 'PMS', status: 'LIVE', blurb: 'PMS sync bridge' },
  { name: 'DentalXChange', category: 'Insurance', status: 'LIVE', blurb: 'Claims clearinghouse' },
  { name: 'FAIR Health', category: 'Analytics', status: 'LIVE', blurb: 'Regional cost benchmarks' },
  { name: 'Stedi', category: 'Insurance', status: 'LIVE', blurb: 'Eligibility 270/271' },
  { name: 'Trafft', category: 'Scheduling', status: 'LIVE', blurb: 'Online booking' },
  { name: 'Stripe', category: 'Analytics', status: 'LIVE', blurb: 'Payments' },
  { name: 'Encharge', category: 'Analytics', status: 'LIVE', blurb: 'Patient email journeys' },
  { name: 'Practice portal', category: 'PMS', status: 'COMING SOON', blurb: 'Secure B2B client workspace' },
  { name: 'Consolto', category: 'Scheduling', status: 'REQUEST', blurb: 'Video consults' },
];

function McpMarketplace({ go }) {
  const [filter, setFilter] = useState('All');
  const cats = ['All', 'PMS', 'Insurance', 'Lab', 'Analytics', 'Scheduling'];
  const items = MCP_INTEGRATIONS.filter((i) => filter === 'All' || i.category === filter);

  return (
    <PageShell title="Dental MCP Marketplace" go={go}>
      <p className="section-subtitle">Connect your practice stack — curated dental MCP integrations.</p>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', margin: '16px 0' }}>
        {cats.map((c) => (
          <button key={c} type="button" className={`nav-tab${filter === c ? ' active' : ''}`} onClick={() => setFilter(c)}>{c}</button>
        ))}
      </div>
      {items.map((item) => (
        <div key={item.name} className="card" style={{ marginBottom: 10 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <strong>{item.name}</strong>
            <span className={`badge badge-${item.status === 'LIVE' ? 'green' : 'gray'}`}>{item.status}</span>
          </div>
          <p className="section-subtitle" style={{ margin: '6px 0' }}>{item.blurb}</p>
          <span className="badge badge-blue">{item.category}</span>
        </div>
      ))}
    </PageShell>
  );
}

function DentalCoach({ go }) {
  const CONCERNS = ['Gum health', 'Whitening', 'Sensitivity', 'Cavity prevention', 'Fresh breath', "Kids' habits", 'Implant care', 'Post-treatment recovery'];
  const [concerns, setConcerns] = useState([]);
  const [habits, setHabits] = useState({ brush2x: true, floss: false, mouthwash: false, electric: false, nightGuard: false });
  const [plan, setPlan] = useState(null);
  const [loading, setLoading] = useState(false);

  const generate = async () => {
    setLoading(true);
    try {
      const resp = await fetch('/api/dental-coach', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ concerns, habits }),
      });
      const data = await resp.json();
      setPlan(data.plan);
      try { localStorage.setItem('td_coach_habits', JSON.stringify(habits)); } catch (_) {}
    } catch {
      setPlan(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Your personal oral health coach" go={go}>
      <DisclaimerBanner />
      <p className="section-title" style={{ fontSize: '1rem', marginBottom: 8 }}>Primary concerns</p>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 16 }}>
        {CONCERNS.map((c) => (
          <button key={c} type="button" className={`chip-select${concerns.includes(c) ? ' selected' : ''}`} onClick={() => setConcerns((p) => p.includes(c) ? p.filter((x) => x !== c) : [...p, c])}>{c}</button>
        ))}
      </div>
      {Object.entries({ brush2x: 'Brush 2x daily?', floss: 'Floss daily?', mouthwash: 'Use mouthwash?', electric: 'Electric toothbrush?', nightGuard: 'Night guard?' }).map(([k, label]) => (
        <label key={k} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
          <input type="checkbox" checked={!!habits[k]} onChange={(e) => setHabits((h) => ({ ...h, [k]: e.target.checked }))} />
          {label}
        </label>
      ))}
      <button type="button" className="btn btn-primary btn-block" onClick={generate} disabled={loading || !concerns.length} style={{ marginTop: 12 }}>
        {loading ? 'Generating…' : 'Generate My Plan'}
      </button>
      {plan?.weeks && (
        <div style={{ marginTop: 20 }}>
          <AiBadge />
          {plan.weeks.map((w) => (
            <div key={w.week} className="card" style={{ marginBottom: 10 }}>
              <strong>Week {w.week}: {w.focus}</strong>
              <ul style={{ margin: '8px 0', paddingLeft: 18 }}>{(w.actions || []).map((a) => <li key={a}>{a}</li>)}</ul>
              <p style={{ fontSize: 13, color: '#6B7280' }}>{w.tip}</p>
            </div>
          ))}
        </div>
      )}
    </PageShell>
  );
}

function SchoolsNearMe({ go }) {
  const [zip, setZip] = useState('');
  const [filter, setFilter] = useState('dental');
  const [schools, setSchools] = useState(null);
  const [loading, setLoading] = useState(false);

  const search = async () => {
    setLoading(true);
    try {
      const resp = await fetch('/api/schools', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ zip, filter }),
      });
      const data = await resp.json();
      setSchools(data.schools || []);
    } catch {
      setSchools([]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Dental Schools Near Me" go={go}>
      <p className="section-subtitle">Quality care at dental school prices — supervised by licensed faculty.</p>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        <input className="input" value={zip} onChange={(e) => setZip(e.target.value.replace(/\D/g, '').slice(0, 5))} placeholder="ZIP code" style={{ flex: 1 }} />
        <button type="button" className="btn btn-primary" onClick={search} disabled={loading || zip.length !== 5}>Search</button>
      </div>
      <select className="input" value={filter} onChange={(e) => setFilter(e.target.value)} style={{ marginBottom: 16 }}>
        <option value="dental">Dental students</option>
        <option value="hygiene">Hygiene students</option>
        <option value="specialty">Specialty programs</option>
      </select>
      {(schools || []).map((s) => (
        <div key={s.name} className="card" style={{ marginBottom: 10 }}>
          <strong>{s.name}</strong>
          <p style={{ fontSize: 13, color: '#6B7280' }}>{s.city}, {s.state} · ~{s.distanceMi} mi · {s.savingsRange}</p>
          <a href={`tel:${s.phone}`} style={{ marginRight: 12, color: '#0057FF' }}>Call to schedule</a>
          <a href={s.website} target="_blank" rel="noopener noreferrer" style={{ color: '#0057FF' }}>Website</a>
        </div>
      ))}
      <p className="t-fine">Treatment is performed by students under licensed faculty supervision. CODA-accredited programs meet national standards.</p>
    </PageShell>
  );
}

function DentalWallet({ go }) {
  const [authed, setAuthed] = useState(false);
  useEffect(() => {
    try {
      setAuthed(!!sessionStorage.getItem('sb-access-token') || !!localStorage.getItem('td_auth_token'));
      const preview = localStorage.getItem('td_wallet_preview');
      if (!preview) localStorage.setItem('td_wallet_preview', JSON.stringify({ count: 0, updated: new Date().toISOString() }));
    } catch (_) {}
  }, []);

  return (
    <PageShell title="Your dental health passport" go={go}>
      <div className="preview-banner">
        This vault is encrypted and private. Never share your wallet URL with others. No PHI in browser storage except authenticated uploads via SmileCam.
      </div>
      {!authed ? (
        <div className="card" style={{ textAlign: 'center', padding: 24, borderStyle: 'dashed' }}>
          <p>Create your secure dental wallet</p>
          <button type="button" className="btn btn-primary" onClick={() => go?.('folio')} style={{ marginTop: 12 }}>
            Sign in via SmileCam / Folio
          </button>
        </div>
      ) : (
        <div>
          <p>Sections: X-rays, treatment history, insurance cards, prescriptions, consent forms.</p>
          <button type="button" className="btn btn-primary" onClick={() => go?.('folio-capture')} style={{ marginTop: 12 }}>
            Upload document (PHI — R2 + RLS)
          </button>
        </div>
      )}
    </PageShell>
  );
}

const DEMO_LISTINGS = [
  { city: 'Oakland', state: 'CA', type: 'General', price: '$450k–$550k', ops: 4, reason: 'Retirement' },
  { city: 'San Jose', state: 'CA', type: 'Pedo', price: '$800k–$950k', ops: 5, reason: 'Relocation' },
  { city: 'Sacramento', state: 'CA', type: 'General', price: '$350k–$420k', ops: 3, reason: 'Partnership' },
];

function PracticeExchange({ go }) {
  return (
    <PageShell title="Practice Transitions — Buy, Sell, Partner" go={go}>
      <div className="disclaimer-banner" style={{ borderLeftColor: 'var(--color-warning)' }}>
        TheDentist.ai is not a licensed dental practice broker. Listings are informational. Engage a licensed dental broker and legal counsel before any transaction.
      </div>
      {DEMO_LISTINGS.map((l) => (
        <div key={l.city} className="card" style={{ marginBottom: 10 }}>
          <strong>{l.city}, {l.state} — {l.type}</strong>
          <p className="section-subtitle">{l.price} · {l.ops} ops · {l.reason}</p>
          <button type="button" className="btn btn-secondary btn-sm" onClick={() => go?.('forms')} style={{ marginTop: 8 }}>
            Contact about this listing
          </button>
        </div>
      ))}
      <button type="button" className="btn btn-primary btn-block" onClick={() => go?.('forms')} style={{ marginTop: 12 }}>
        Submit your listing
      </button>
    </PageShell>
  );
}

function PracticeInsider({ go }) {
  const [metrics, setMetrics] = useState({ production: '', collectionRate: '', newPatients: '', noShowRate: '', reappointmentRate: '' });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const compare = async () => {
    setLoading(true);
    const token = sessionStorage.getItem('sb-access-token') || localStorage.getItem('td_auth_token') || '';
    try {
      const resp = await fetch('/api/insider', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: token ? `Bearer ${token}` : '' },
        body: JSON.stringify({
          production: Number(metrics.production),
          collectionRate: Number(metrics.collectionRate),
          newPatients: Number(metrics.newPatients),
          noShowRate: Number(metrics.noShowRate),
          reappointmentRate: Number(metrics.reappointmentRate),
        }),
      });
      setResult(await resp.json());
    } catch {
      setResult({ error: 'insufficient_data' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Practice Insider" go={go}>
      <p className="section-subtitle">See how your practice compares — anonymized benchmarks (numbers only, no practice name).</p>
      {['production', 'collectionRate', 'newPatients', 'noShowRate', 'reappointmentRate'].map((k) => (
        <label key={k} style={{ display: 'block', marginBottom: 10 }}>
          <span className="field-label">{k}</span>
          <input className="input" value={metrics[k]} onChange={(e) => setMetrics((m) => ({ ...m, [k]: e.target.value }))} />
        </label>
      ))}
      <button type="button" className="btn btn-primary btn-block" onClick={compare} disabled={loading}>
        Compare
      </button>
      {result?.error === 'insufficient_data' && <p style={{ marginTop: 12, color: '#92400E' }}>{result.message || 'Insufficient data for your region.'}</p>}
      {result?.benchmarks && (
        <div style={{ marginTop: 16 }}>
          <p style={{ fontSize: 13 }}>{result.kAnonymizationNotice}</p>
          <pre style={{ fontSize: 12, background: '#F9FAFB', padding: 12, borderRadius: 8, overflow: 'auto' }}>{JSON.stringify(result.benchmarks, null, 2)}</pre>
        </div>
      )}
    </PageShell>
  );
}

function PrnConnect({ go }) {
  const [mode, setMode] = useState('clinician');
  return (
    <PageShell title="PRN Connect" go={go}>
      <div className="preview-banner">
        PREVIEW — PRN platform requires dental staffing insurance partner agreement before activation. Contact us to join the beta.
      </div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        <button type="button" className={`nav-tab${mode === 'clinician' ? ' active' : ''}`} style={{ flex: 1 }} onClick={() => setMode('clinician')}>I'm a clinician</button>
        <button type="button" className={`nav-tab${mode === 'practice' ? ' active' : ''}`} style={{ flex: 1 }} onClick={() => setMode('practice')}>I'm a practice</button>
      </div>
      <p className="section-subtitle">{mode === 'clinician' ? 'Browse PRN shifts and express interest.' : 'Post a shift and view applicants.'}</p>
      <button type="button" className="btn btn-primary btn-block" onClick={() => go?.('forms')}>
        Express Interest (lead capture)
      </button>
    </PageShell>
  );
}

function SupplyCoop({ go }) {
  const categories = ['Gloves & PPE', 'Composites & Cements', 'Impression Materials', 'Infection Control', 'Anesthetics', 'X-ray Supplies'];
  return (
    <PageShell title="Supply Co-op" go={go}>
      <p className="section-subtitle">Save 20–40% on dental supplies through group purchasing.</p>
      {categories.map((c) => (
        <div key={c} className="card" style={{ marginBottom: 10 }}>
          <strong>{c}</strong>
          <p className="section-subtitle">Typical co-op savings vs individual pricing</p>
        </div>
      ))}
      <button type="button" className="btn btn-primary btn-block" onClick={() => go?.('forms')}>
        Join the co-op waitlist
      </button>
    </PageShell>
  );
}

function HitlDraftBanner() {
  return (
    <div className="banner warn" role="note" style={{ marginBottom: 12 }}>
      <strong>Pending licensed review — informational draft only.</strong>{' '}
      AI output is educational information, not a clinical assessment.
    </div>
  );
}

function OralHealthOracle({ go }) {
  const [question, setQuestion] = useState('');
  const [history, setHistory] = useState(() => {
    try { return JSON.parse(sessionStorage.getItem('td_oracle_session') || '[]'); } catch { return []; }
  });
  const [loading, setLoading] = useState(false);

  const persist = useCallback((h) => {
    setHistory(h);
    try { sessionStorage.setItem('td_oracle_session', JSON.stringify(h)); } catch (_) {}
  }, []);

  const ask = async () => {
    if (!question.trim()) return;
    setLoading(true);
    const q = question.trim();
    setQuestion('');
    try {
      const resp = await fetch('/api/oracle', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: q, conversationId: `oracle_${Date.now()}` }),
      });
      const data = await resp.json();
      persist([
        ...history,
        { role: 'user', text: q },
        {
          role: 'oracle',
          text: data.answer || data.resources?.[0]?.body || data.disclaimer,
          emergency: data.emergency,
          pending_hitl_review: data.pending_hitl_review,
          source: data.source,
        },
      ]);
    } catch {
      persist([...history, { role: 'user', text: q }, { role: 'oracle', text: 'Unable to answer right now.' }]);
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageShell title="Oral Health Oracle" go={go}>
      <DisclaimerBanner extra="Educational information only — not a medical or dental assessment." />
      {history.some((m) => m.role === 'oracle' && m.pending_hitl_review) && <HitlDraftBanner />}
      <div style={{ maxHeight: 320, overflowY: 'auto', marginBottom: 16 }}>
        {history.map((m, i) => (
          <div key={i} style={{ textAlign: m.role === 'user' ? 'right' : 'left', marginBottom: 10 }}>
            <div style={{ display: 'inline-block', maxWidth: '85%', padding: 12, borderRadius: 16, background: m.role === 'user' ? '#2563EB' : '#F3F4F6', color: m.role === 'user' ? '#fff' : '#1A1A1A' }}>
              {m.emergency && <strong style={{ color: '#DC2626' }}>Emergency resources — </strong>}
              {m.text}
            </div>
            {m.role === 'oracle' && m.pending_hitl_review && (
              <p className="t-meta" style={{ marginTop: 4, fontSize: 12, color: 'var(--seal)' }}>
                Pending licensed review — informational draft only
              </p>
            )}
            {m.role === 'oracle' && <div style={{ marginTop: 4 }}><AiBadge /></div>}
          </div>
        ))}
      </div>
      <div style={{ display: 'flex', gap: 8 }}>
        <input className="input" value={question} onChange={(e) => setQuestion(e.target.value)} placeholder="Ask about oral health…" style={{ flex: 1 }} onKeyDown={(e) => e.key === 'Enter' && ask()} />
        <button type="button" className="btn btn-primary" onClick={ask} disabled={loading}>Ask</button>
      </div>
      <button type="button" className="btn btn-ghost btn-sm" onClick={() => { persist([]); try { sessionStorage.removeItem('td_oracle_session'); } catch (_) {} }} style={{ marginTop: 12 }}>
        Start over
      </button>
    </PageShell>
  );
}

window.BenefitBomber = BenefitBomber;
window.Dental911 = Dental911;
window.SecondOpinion = SecondOpinion;
window.McpMarketplace = McpMarketplace;
window.DentalCoach = DentalCoach;
window.SchoolsNearMe = SchoolsNearMe;
window.DentalWallet = DentalWallet;
window.PracticeExchange = PracticeExchange;
window.PracticeInsider = PracticeInsider;
window.PrnConnect = PrnConnect;
window.SupplyCoop = SupplyCoop;
window.OralHealthOracle = OralHealthOracle;
window.B5PageShell = PageShell;
window.B5DisclaimerBanner = DisclaimerBanner;
window.B5AiBadge = AiBadge;
