// Smile Audit screens — dual-axis (pain + concern), expandable conditions,
// examination-order recommendations.
// Uses window.t(lang, key) from i18n.js when available.
const useS = React.useState;
const _T = (lang, k, fb) => (window.t ? window.t(lang, k) : fb);

const AUDIT_CRUMBS = [
  { step: 1, label: 'Where' },
  { step: 2, label: 'What'  },
  { step: 3, label: 'Who'   },
];

function AuditTopBar({ step, total, go, lang, setLang }) {
  return (
    <>
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <div style={{
        display:'flex', alignItems:'center', justifyContent:'center', gap:'var(--s-3)',
        padding:'var(--s-4) var(--s-6)', borderBottom:'0.5px solid var(--ink-5)',
        background:'var(--paper)',
      }}>
        {AUDIT_CRUMBS.map((c, i) => (
          <React.Fragment key={c.step}>
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <span style={{
                display:'inline-flex', alignItems:'center', justifyContent:'center',
                width:24, height:24, borderRadius:'50%',
                background: c.step === step ? 'var(--ink-1)' : c.step < step ? 'var(--seal)' : 'var(--ink-5)',
                color: c.step <= step ? 'var(--paper)' : 'var(--ink-2)',
                fontFamily:'var(--font-display)', fontSize:13, fontWeight:500,
              }}>{c.step < step ? '✓' : c.step}</span>
              <span style={{
                fontSize:13,
                color: c.step === step ? 'var(--ink-1)' : 'var(--ink-3)',
                fontWeight: c.step === step ? 500 : 400,
              }}>{c.label}</span>
            </div>
            {i < AUDIT_CRUMBS.length - 1 && (
              <span style={{width:24, height:1, background:'var(--ink-5)'}} aria-hidden="true"/>
            )}
          </React.Fragment>
        ))}
      </div>
    </>
  );
}

function Audit1({ go, state, set, lang, setLang }) {
  const t1 = (k, fb) => _T(lang, k, fb);

  const onChartChange = (next) => {
    set({
      ...state,
      teeth: next.teeth,
      toothScope: next.scope,
      toothLevel: next.level,
      toothUrgency: next.urgency,
    });
  };

  return (
    <div className="audit">
      <AuditTopBar step={1} total={3} go={go} lang={lang} setLang={setLang}/>
      <div className="audit-body">
        <h1 className="audit-h">{t1('audit1.h', "Where's the problem?")}</h1>
        <p className="audit-sub">{t1('audit1.sub', 'Tap the tooth or teeth that need attention. Not one specific tooth? Use Whole mouth or Not a specific tooth.')}</p>
        <div className="toothmap" style={{padding:'var(--s-3)'}}>
          {window.ToothChart
            ? <window.ToothChart
                teeth={state.teeth || []}
                scope={state.toothScope || 'specific'}
                level={state.toothLevel ?? null}
                urgency={state.toothUrgency ?? null}
                onChange={onChartChange}/>
            : <div style={{color:'var(--ink-3)'}}>Tooth chart loading…</div>}
        </div>
      </div>
      <div className="audit-foot">
        <a href="#" onClick={(e)=>{e.preventDefault();go('audit-2');}}>{t1('audit1.skip', 'Skip this step →')}</a>
        <Button variant="primary" onClick={()=>go('audit-2')}>Continue</Button>
      </div>
    </div>
  );
}

const SYMPTOMS_COMMON = [
  'Tooth pain', 'Gum bleeding', 'Sensitive to cold', 'Sensitive to hot',
  'Swelling', 'Chipped or broken', 'Lost filling', 'Bad breath',
  'Grinding or clenching', 'Bite feels off',
  'Looks discolored', 'Overdue for cleaning', 'Anxious about visits', 'Want a checkup',
];

const SYMPTOMS_MORE = [
  'TMJ / jaw clicking', 'Dry mouth', 'Mouth sores',
  'Loose tooth', 'Gum recession', 'Food gets stuck', 'Missing tooth',
  'Crooked or shifting teeth', 'Sleep grinding / snoring', 'Recent trauma',
  'Crown or bridge issue', 'Wisdom teeth', "Kid's tooth concern",
  'Cosmetic — straighten', 'Cosmetic — whiten', 'Cosmetic — reshape',
  'Bleeding when flossing', 'Taste changed', 'Recent extraction healing',
];

function Audit2({ go, state, set, lang, setLang }) {
  const t2 = (k, fb) => _T(lang, k, fb);
  const sel    = state.symptoms || [];
  const sev    = state.severity ?? 0;
  const concern= state.concern  ?? 0;
  const [expanded, setExpanded] = useS(false);
  const showEm = sev >= 8 && sel.includes('Swelling');
  const toggle = (s) => set({...state, symptoms: sel.includes(s) ? sel.filter(x=>x!==s) : [...sel,s]});

  return (
    <div className="audit">
      <AuditTopBar step={2} total={3} go={go} lang={lang} setLang={setLang}/>
      <div className="audit-body">
        <h1 className="audit-h">{t2('audit2.h', "What's going on?")}</h1>
        <p className="audit-sub">{t2('audit2.sub', "Pick anything that fits. There's no wrong answer.")}</p>

        <div className="symptoms" style={{marginBottom:'var(--s-5)'}}>
          {SYMPTOMS_COMMON.map(s => (
            <span key={s} className={`symptom-chip ${sel.includes(s)?'sel':''}`} onClick={()=>toggle(s)}>{s}</span>
          ))}
          {expanded && SYMPTOMS_MORE.map(s => (
            <span key={s} className={`symptom-chip ${sel.includes(s)?'sel':''}`} onClick={()=>toggle(s)}>{s}</span>
          ))}
        </div>
        <button
          type="button"
          onClick={()=>setExpanded(v=>!v)}
          style={{
            background:'transparent', border:'1px dashed var(--ink-4)', color:'var(--ink-2)',
            padding:'8px 14px', borderRadius:999, cursor:'pointer', fontSize:13,
            marginBottom:'var(--s-8)',
          }}
        >
          {expanded ? `− ${t2('audit2.fewer','Show fewer conditions')}` : `+ ${t2('audit2.more','More conditions')} (${SYMPTOMS_MORE.length})`}
        </button>

        <div className="card" style={{marginBottom:'var(--s-4)'}}>
          <div className="severity">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
              <div>
                <h3 style={{margin:0,fontSize:16}}>{t2('audit2.sev.label','How much does it hurt right now?')}</h3>
                <div style={{fontSize:12,color:'var(--ink-3)',marginTop:2}}>{t2('audit2.sev.help','Physical pain — only count what hurts today.')}</div>
              </div>
              <span className="severity-readout">{sev}<span style={{fontSize:14,color:'var(--ink-3)',fontFamily:'var(--font-body)',fontWeight:400}}> / 10</span></span>
            </div>
            <input type="range" min={0} max={10} value={sev} onChange={(e)=>set({...state,severity:+e.target.value})}/>
            <div className="severity-anchors"><span>{t2('audit2.nopain','no pain')}</span><span>{t2('audit2.constpain','constant pain')}</span></div>
          </div>
        </div>

        <div className="card">
          <div className="severity">
            <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline'}}>
              <div>
                <h3 style={{margin:0,fontSize:16}}>{t2('audit2.con.label','How much is it on your mind?')}</h3>
                <div style={{fontSize:12,color:'var(--ink-3)',marginTop:2}}>{t2('audit2.con.help','Includes how much it bothers, worries, or affects daily life.')}</div>
              </div>
              <span className="severity-readout">{concern}<span style={{fontSize:14,color:'var(--ink-3)',fontFamily:'var(--font-body)',fontWeight:400}}> / 10</span></span>
            </div>
            <input type="range" min={0} max={10} value={concern} onChange={(e)=>set({...state,concern:+e.target.value})}/>
            <div className="severity-anchors"><span>{t2('audit2.notreally','not really')}</span><span>{t2('audit2.constantly','constantly')}</span></div>
          </div>
        </div>

        {(sev > 0 && concern > 0 && Math.abs(sev - concern) >= 3) && (
          <p style={{marginTop:'var(--s-4)',fontSize:13,color:'var(--ink-2)',lineHeight:1.5,padding:'var(--s-3) var(--s-4)',background:'var(--bone)',borderRadius:'var(--r-3)'}}>
            Got it — your pain and concern levels are different. That's useful. A small pain can still
            be a big worry (or vice versa), and our recommendations will weight both.
          </p>
        )}
      </div>
      <div className="audit-foot">
        <a href="#" onClick={(e)=>{e.preventDefault();go('audit-1');}}>← Back</a>
        <Button variant="primary" onClick={()=> showEm ? go('emergency') : go('audit-3')}>Continue</Button>
      </div>
    </div>
  );
}

function Audit3({ go, state, set, lang, setLang }) {
  const t3 = (k, fb) => _T(lang, k, fb);
  const [busy, setBusy] = useS(false);
  const [err, setErr] = useS(null);
  const submit = async () => {
    setBusy(true);
    setErr(null);
    try {
      const payload = {
        symptoms: state.symptoms || [],
        severity: state.severity ?? 0,
        concern:  state.concern  ?? 0,
        teeth:    state.teeth    || [],
        tooth_scope:   state.toothScope   || 'specific',
        tooth_level:   state.toothLevel   ?? null,
        tooth_urgency: state.toothUrgency ?? null,
        zip:      state.zip      || '',
        insurance: state.insurance || '',
      };
      const triageResp = await fetch('/api/triage', {
        method:'POST', headers:{'content-type':'application/json'},
        body: JSON.stringify({ symptoms: payload.symptoms, severity: payload.severity }),
      });
      const triage = triageResp.ok ? await triageResp.json() : {};
      if (triage.gateEmergencyContent) {
        set({...state, _triage: triage});
        go('emergency'); return;
      }
      const snapResp = await fetch('/api/snapshot', {
        method:'POST', headers:{'content-type':'application/json'},
        body: JSON.stringify(payload),
      });
      const snap = snapResp.ok ? await snapResp.json() : null;
      const dirResp = await fetch(`/api/directory?zip=${encodeURIComponent(payload.zip)}&insurance=${encodeURIComponent(payload.insurance)}&language=${encodeURIComponent(state.language||'English')}&limit=3`);
      const dir = dirResp.ok ? await dirResp.json() : { results: [] };
      set({...state, _snapshot: snap, _directory: dir, _triage: triage});
      go('snapshot');
    } catch (e) {
      setErr("Couldn't reach the audit service. Please try again in a moment.");
      setBusy(false);
    }
  };
  return (
    <div className="audit">
      <AuditTopBar step={3} total={3} go={go} lang={lang} setLang={setLang}/>
      <div className="audit-body">
        <h1 className="audit-h">{t3('audit3.h','A few last things.')}</h1>
        <p className="audit-sub">{t3('audit3.sub','So we can match you with dentists who fit your situation.')}</p>
        <div style={{display:'grid',gap:'var(--s-4)'}}>
          <div className="field">
            <label>{t3('audit3.zip','ZIP code')}</label>
            <input value={state.zip || ''} placeholder="94102" onChange={(e)=>set({...state,zip:e.target.value})}/>
          </div>
          <div className="field">
            <label>{t3('audit3.ins','Insurance plan')}</label>
            <select value={state.insurance || 'No insurance'} onChange={(e)=>set({...state,insurance:e.target.value})}>
              <option>No insurance</option>
              <option>Delta Dental PPO</option>
              <option>Delta Dental HMO</option>
              <option>MetLife</option>
              <option>Cigna</option>
              <option>Aetna</option>
              <option>Guardian</option>
              <option>United Concordia</option>
              <option>Humana</option>
              <option>Anthem Blue Cross</option>
              <option>Medicaid / Denti-Cal</option>
              <option>Other / not sure</option>
            </select>
            <div className="field-help">Most plans are searchable. "No insurance" is the most common selection.</div>
          </div>
          <div className="field">
            <label>{t3('audit3.lang','Preferred language')}</label>
            <select value={state.language||'English'} onChange={(e)=>set({...state,language:e.target.value})}>
              <option>English</option><option>Español</option><option>中文</option>
            </select>
          </div>
        </div>
        {window.InsuranceCapture && (
          <div style={{marginTop:'var(--s-4)'}}>
            <div className="t-eyebrow" style={{marginBottom:8}}>Insurance details (optional — unlocks per-patient cost estimate)</div>
            <window.InsuranceCapture
              value={state._insurance_card || {}}
              onChange={(v)=>set({...state, _insurance_card: v, insurance: v.carrier || state.insurance })}
            />
          </div>
        )}
        {err && <div style={{padding:'var(--s-3)',background:'var(--alert-tint)',color:'var(--alert)',borderRadius:'var(--r-3)',marginTop:'var(--s-3)',fontSize:14}}>{err}</div>}
      </div>
      <div className="audit-foot">
        <a href="#" onClick={(e)=>{e.preventDefault();go('audit-2');}}>← Back</a>
        <Button variant="primary" onClick={submit} disabled={busy}>{busy ? t3('audit3.loading','Generating snapshot…') : t3('audit3.cta','Get my Smile Snapshot')}</Button>
      </div>
    </div>
  );
}

function Emergency({ go }) {
  return (
    <div className="emergency-backdrop">
      <div className="emergency-modal" role="alertdialog" aria-labelledby="em-h">
        <h2 id="em-h"><Icon d={ICONS.alert} size={28} stroke={2}/>This may be a dental emergency.</h2>
        <p style={{margin:0,color:'var(--ink-1)'}}>Severe pain combined with swelling can signal a spreading infection. Take one of the actions below.</p>
        <div className="actions">
          <button className="btn btn-md btn-alert">Call 911 now (if breathing affected)</button>
          <button className="btn btn-md btn-alert-out">Find a 24-hour emergency dentist</button>
          <button className="btn btn-sm btn-ghost" onClick={()=>go('audit-3')} style={{justifyContent:'flex-start'}}>Continue to non-emergency triage (only if you're sure)</button>
        </div>
      </div>
    </div>
  );
}

// ── Examination-order recommendation engine ────────────────────────────────
// Given symptoms + severity + concern, return prioritized evaluation buckets
// in the order a clinician would address them: emergency → acute → periodontal
// → restorative → preventive → cosmetic → behavioral.

const EXAM_RULES = [
  { id:'emergency',  label:'Urgent care',           order:1, triggers:['Swelling'],                                                                           note:'Pain plus swelling can mean spreading infection. See someone within 24 hours.' },
  { id:'acute',      label:'Acute pain',            order:2, triggers:['Tooth pain','Sensitive to cold','Sensitive to hot'],                                  note:'Toothache patterns commonly stem from a deep cavity, cracked tooth, or nerve inflammation. A licensed dentist can confirm with an exam and X-ray.' },
  { id:'periodontal',label:'Gum & periodontal',     order:3, triggers:['Gum bleeding','Bleeding when flossing','Gum recession'],                              note:'Bleeding or receding gums suggest gingivitis or periodontitis — both are treatable, especially when caught early.' },
  { id:'restorative',label:'Restorative repair',    order:4, triggers:['Chipped or broken','Lost filling','Crown or bridge issue','Missing tooth','Recent trauma'], note:'Broken or missing structures need restoration to prevent further damage and shifting.' },
  { id:'occlusion',  label:'Bite & jaw',            order:5, triggers:['TMJ / jaw clicking','Grinding or clenching','Sleep grinding / snoring','Bite feels off'], note:'Grinding (bruxism) and bite problems affect sleep, wear, and headaches — often manageable with a night guard or bite evaluation.' },
  { id:'preventive', label:'Preventive care',       order:6, triggers:['Overdue for cleaning','Want a checkup','Food gets stuck','Bad breath','Wisdom teeth',"Kid's tooth concern",'Loose tooth','Taste changed','Dry mouth','Mouth sores','Recent extraction healing'], note:'Cleaning and a full exam set a baseline and catch issues early — the cheapest care you will ever buy.' },
  { id:'cosmetic',   label:'Cosmetic',              order:7, triggers:['Looks discolored','Cosmetic — straighten','Cosmetic — whiten','Cosmetic — reshape','Crooked or shifting teeth'], note:'Cosmetic options range from whitening to clear aligners — most are elective and can wait until urgent items are resolved.' },
  { id:'behavioral', label:'Comfort & anxiety',     order:8, triggers:['Anxious about visits'],                                                               note:'Anxious-friendly practices offer sedation options, longer first visits, and step-by-step explanations.' },
];

function buildExamPlan(symptoms, severity, concern) {
  if (!Array.isArray(symptoms)) symptoms = [];
  const buckets = [];
  for (const rule of EXAM_RULES) {
    const matched = rule.triggers.filter(t => symptoms.includes(t));
    if (!matched.length) continue;
    const isUrgentEmergency = rule.id === 'emergency' && severity >= 7;
    buckets.push({
      ...rule,
      matched,
      urgent: isUrgentEmergency,
      concernBoost: concern >= 7 ? 1 : 0,
    });
  }
  // Re-sort: emergency first, then by clinical order. Concern only nudges
  // adjacent ties — it never overrides clinical order.
  buckets.sort((a,b) => a.order - b.order);
  return buckets;
}

function Snapshot({ go, state, set, lang, setLang }) {
  const openProfile = (d) => { if (set) set(s => ({ ...s, _selectedDentist: d })); go('profile'); };
  const [shareMsg, setShareMsg] = useS('');
  const shareSnapshot = async () => {
    const id = state._snapshot && state._snapshot.audit_id;
    const url = window.location.origin + '/#snapshot' + (id ? ('/' + id) : '');
    const data = { title: 'My Smile Snapshot — TheDentist.ai', text: 'Here is my Smile Snapshot from TheDentist.ai.', url };
    try {
      if (navigator.share) { await navigator.share(data); setShareMsg('Shared'); }
      else { await navigator.clipboard.writeText(url); setShareMsg('Link copied'); }
    } catch (e) { setShareMsg('Link copied'); try { await navigator.clipboard.writeText(url); } catch (_) {} }
    setTimeout(() => setShareMsg(''), 2400);
  };
  const snap = state._snapshot;
  const dir = state._directory;
  const sev = state.severity ?? 0;
  const concern = state.concern ?? 0;
  const examPlan = buildExamPlan(state.symptoms || [], sev, concern);
  const urgencyLabel = snap?.urgency === 'emergency' ? 'Emergency' : snap?.urgency === 'urgent' ? 'Within 24–72 hours' : 'Within 1–2 weeks';
  const urgencyNote = snap?.urgency === 'emergency' ? 'See an emergency dentist now.' : snap?.urgency === 'urgent' ? 'Book promptly — symptoms suggest escalation risk.' : 'Not an emergency. Worth booking soon to prevent escalation.';
  const items = snap?.items || (examPlan.slice(0,3).map(b => ({ name: b.label, description: b.note }))) || [
    {name:'Reversible pulpitis', description:'Inflamed tooth nerve from a deep cavity. Often resolves with a filling if caught early.'},
    {name:'Cracked tooth syndrome', description:'A small crack lets cold reach the nerve. A crown often resolves it.'},
    {name:'Recession sensitivity', description:'Receding gums expose root surface. A desensitizing treatment may help.'},
  ];
  const cost = snap?.cost || { low: 285, high: 1420, note: 'Typical range across acute and preventive evaluation — practice-published rates.' };
  const matched = (dir?.results || []).slice(0, 3);
  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main className="snap-page">
        <div className="container article">
          <Breadcrumbs crumbs={[{label:'Home',screen:'landing'},{label:'Smile Audit',screen:'audit-1'},{label:'Your Snapshot'}]} go={go}/>
          <div className="snap-card">
            <div className="snap-eyebrow">Your Smile Snapshot · {new Date().toLocaleDateString('en-US',{month:'long',year:'numeric'})}</div>
            <h1 className="snap-title">Here's what we heard.</h1>
            <p style={{fontSize:18,color:'var(--ink-2)',maxWidth:560,margin:0}}>{snap?.summary || `Based on what you shared, here is a clinically ordered review — what a dentist would address first, second, and so on.`}</p>
            <div className="t-fine" style={{marginTop:'var(--s-4)',padding:'var(--s-3) var(--s-4)',background:'var(--bone)',borderRadius:'var(--r-3)',color:'var(--ink-2)',lineHeight:1.5}}>
              <strong style={{color:'var(--ink-1)'}}>AI-assisted information (CA AB 3030):</strong> {snap?.disclosure || 'This snapshot was generated with the help of an AI model and reviewed against our Editorial Council criteria. It is not a diagnosis. Under California SB 1120, clinical determinations require a licensed dentist.'}
            </div>
            <div style={{margin:'var(--s-6) 0',background:'var(--paper)',borderRadius:'var(--r-5)',padding:'var(--s-6)',display:'flex',justifyContent:'center'}}>
              <img src="./assets/illustrations/snapshot.svg" style={{maxWidth:480,width:'100%'}} alt=""/>
            </div>

            {/* ── Examination-order plan (always shown — fallback or augment) ── */}
            {examPlan.length > 0 && (
              <>
                <h2 style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500,margin:'0 0 var(--s-2)'}}>What a dentist would address, in order</h2>
                <p className="t-meta" style={{margin:'0 0 var(--s-4)'}}>Clinical order — based on what you reported. Urgency drives the first item; preventive and cosmetic come after.</p>
                <ol style={{listStyle:'none',margin:'0 0 var(--s-6)',padding:0,display:'grid',gap:'var(--s-3)'}}>
                  {examPlan.map((b, i) => (
                    <li key={b.id} className="card card-paper" style={{display:'flex',gap:'var(--s-4)',alignItems:'flex-start'}}>
                      <div style={{
                        flexShrink:0, width:36, height:36, borderRadius:'50%',
                        background: b.urgent ? 'var(--alert)' : 'var(--ink-1)',
                        color:'var(--paper)', display:'flex',alignItems:'center',justifyContent:'center',
                        fontFamily:'var(--font-display)', fontWeight:500, fontSize:16,
                      }}>{i+1}</div>
                      <div style={{flex:1}}>
                        <h3 style={{margin:'0 0 4px',fontFamily:'var(--font-display)',fontSize:18,fontWeight:500}}>
                          {b.label}{b.urgent && <span style={{marginLeft:8,fontSize:12,color:'var(--alert)',textTransform:'uppercase',letterSpacing:'0.08em'}}>· urgent</span>}
                        </h3>
                        <p style={{margin:'0 0 6px',fontSize:14,color:'var(--ink-2)',lineHeight:1.55}}>{b.note}</p>
                        <div className="t-meta" style={{fontSize:12}}>You mentioned: {b.matched.join(' · ')}</div>
                      </div>
                    </li>
                  ))}
                </ol>
              </>
            )}

            <h2 style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500,margin:'0 0 var(--s-3)'}}>Three things this commonly is</h2>
            <div className="snap-three">
              {items.map((it)=>{
                const learn = window.ForentoLinks ? window.ForentoLinks.lookup(it.name) : null;
                const tw = it.timely_label || it.timely_window;
                return (
                  <div className="card card-paper" key={it.name}>
                    <h3>{it.name}</h3>
                    <p>{it.description}</p>
                    {it.what_it_could_be && (
                      <p style={{margin:'8px 0 0',fontSize:13,color:'var(--ink-2)'}}><strong>What it could be:</strong> {it.what_it_could_be}</p>
                    )}
                    {it.what_if_untreated && (
                      <p style={{margin:'6px 0 0',fontSize:13,color:'var(--ink-2)'}}><strong>If untreated:</strong> {it.what_if_untreated}</p>
                    )}
                    {tw && (
                      <p style={{margin:'8px 0 0',fontSize:13}}>
                        <strong style={{color:'var(--seal)'}}>Timely action:</strong> <span style={{color:'var(--ink-1)',fontWeight:600}}>see a dentist {tw}</span>
                        {it.urgency_reason && <span style={{color:'var(--ink-3)'}}> — {it.urgency_reason}</span>}
                      </p>
                    )}
                    {learn && (
                      <p style={{margin:'8px 0 0',fontSize:13}}>
                        <a href={learn} target="_blank" rel="noopener noreferrer" style={{color:'var(--seal)',fontWeight:600}}>Learn more on Forento →</a>
                      </p>
                    )}
                  </div>
                );
              })}
            </div>
            <div style={{marginTop:'var(--s-3)',display:'flex',gap:8,flexWrap:'wrap'}}>
              <Button variant="secondary" size="sm" onClick={()=>{
                // Save this snapshot into a SmileCam case
                try {
                  const cases = JSON.parse(localStorage.getItem('td_folio_cases') || '[]');
                  cases.unshift({
                    id: 'case_'+Math.random().toString(36).slice(2,10),
                    title: 'Snapshot · ' + new Date().toLocaleDateString(),
                    date: new Date().toISOString(),
                    owner_role: 'patient',
                    photos: [], tags: [], notes: items.map(i=>i.name).join(' · '),
                    layout: 'grid', consent: null,
                  });
                  localStorage.setItem('td_folio_cases', JSON.stringify(cases));
                } catch{}
                go('folio');
              }}>Save snapshot to my SmileCam</Button>
            </div>

            {/* ── Patient condition flow — what is it, do I need it, cost, will it hurt ── */}
            {window.ConditionGuide && (
              <window.ConditionGuide items={items} suggested={snap?.suggested} state={state} go={go}/>
            )}

            <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:'var(--s-4)',margin:'var(--s-8) 0'}}>
              <div>
                <div className="t-eyebrow">In ZIP {state.zip||'94102'} · {state.insurance||'No insurance'}</div>
                <div className="snap-cost">${cost.low.toLocaleString()} – ${cost.high.toLocaleString()}</div>
                <div className="t-meta">{cost.note}</div>
              </div>
              <div>
                <div className="t-eyebrow">Urgency</div>
                <div className="snap-cost" style={{color:'var(--seal)'}}>{urgencyLabel}</div>
                <div className="t-meta">{urgencyNote}</div>
              </div>
            </div>

            <h2 style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500,margin:'var(--s-8) 0 var(--s-2)'}}>Three matched dentists near you</h2>
            <p className="t-meta" style={{margin:'0 0 var(--s-4)'}}>Ranked by Verified Performance Score (VPS) — earned algorithmically, never paid placement. <a href="/methodology/">See the methodology →</a></p>
            <div style={{display:'grid',gap:'var(--s-3)'}}>
              {matched.length === 0 && (
                <div className="t-meta" style={{padding:'var(--s-4)',background:'var(--bone)',borderRadius:'var(--r-3)'}}>Loading matched dentists…</div>
              )}
              {matched.map((d)=>(
                <div key={d.npi} className="card card-paper" style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:'var(--s-4)'}}>
                  <div style={{flex:1}}>
                    <h3 style={{margin:0,fontFamily:'var(--font-display)',fontSize:18,fontWeight:500}}>{d.name}</h3>
                    <div style={{color:'var(--ink-2)',fontSize:14}}>{d.practice} · {d.distance_mi} mi</div>
                    <div className="t-meta" style={{marginTop:4}}>{d.why}</div>
                  </div>
                  <div style={{display:'flex',gap:6}}>
                    {d.badges.map(([axis,tier])=> <Badge key={axis} axis={axis} tier={tier} size={48}/>)}
                  </div>
                  <div style={{display:'flex',flexDirection:'column',gap:6,flexShrink:0}}>
                    <Button variant="primary" size="sm"
                      onClick={()=>{ window.Enc?.bookedAppointment(d); window.open(window.buildTrafftUrl(d),'_blank','noopener'); }}>Book</Button>
                    <Button variant="secondary" size="sm" onClick={()=>openProfile(d)}>View</Button>
                  </div>
                </div>
              ))}
            </div>

            {/* ── Patient forms callout ── */}
            <div style={{marginTop:'var(--s-8)',padding:'var(--s-5)',background:'var(--bone)',borderRadius:'var(--r-5)',border:'1px solid var(--ink-5)'}}>
              <div style={{display:'flex',alignItems:'flex-start',justifyContent:'space-between',gap:'var(--s-4)',flexWrap:'wrap'}}>
                <div>
                  <div className="t-eyebrow" style={{marginBottom:4}}>Patient forms</div>
                  <h2 style={{fontFamily:'var(--font-display)',fontSize:20,fontWeight:500,margin:'0 0 var(--s-2)'}}>Ready to book? Start your intake now.</h2>
                  <p style={{margin:0,fontSize:14,color:'var(--ink-2)',lineHeight:1.55,maxWidth:480}}>
                    Complete new-patient registration, health history, and HIPAA acknowledgment before your visit.
                    Post-op instructions are available for every procedure — print or email them to yourself.
                  </p>
                </div>
                <div style={{display:'flex',flexDirection:'column',gap:8,flexShrink:0}}>
                  <Button variant="primary" size="sm"
                    onClick={()=>{ if(set) set(s=>({...s,_catFilter:'new-patient'})); go('forms'); }}>
                    New patient intake →
                  </Button>
                  <Button variant="secondary" size="sm"
                    onClick={()=>{ if(set) set(s=>({...s,_catFilter:'post-op'})); go('forms'); }}>
                    Post-op instructions →
                  </Button>
                </div>
              </div>
            </div>

            <div style={{marginTop:'var(--s-6)',padding:'var(--s-6)',background:'var(--ink)',color:'var(--paper)',borderRadius:'var(--r-5)',display:'grid',gridTemplateColumns:'1fr auto',gap:'var(--s-4)',alignItems:'center'}}>
              <div>
                <div style={{fontFamily:'var(--font-display)',fontSize:20,fontWeight:500}}>Keep this Snapshot for your next visit.</div>
                <div style={{fontSize:13,opacity:0.7,marginTop:4}}>Save the link · revisit costs, rebook, track follow-ups.</div>
              </div>
              <div style={{display:'flex',gap:8,flexWrap:'wrap',justifyContent:'flex-end',alignItems:'center'}}>
                {shareMsg && <span style={{fontSize:13,color:'var(--paper)',opacity:0.85}}>{shareMsg}</span>}
                <Button variant="seal" size="md" onClick={shareSnapshot}>Save snapshot</Button>
                <Button variant="secondary" style={{color:'var(--paper)',borderColor:'var(--paper)'}} onClick={shareSnapshot}><Icon d={ICONS.share} size={16}/> Share</Button>
              </div>
            </div>
            {/* ── After-visit survey CTA ── */}
            <div style={{marginTop:'var(--s-6)',padding:'var(--s-5) var(--s-6)',background:'var(--bone)',borderRadius:'var(--r-5)',border:'1px solid var(--ink-5)',display:'flex',alignItems:'center',justifyContent:'space-between',gap:'var(--s-4)',flexWrap:'wrap'}}>
              <div>
                <div className="t-eyebrow" style={{marginBottom:4}}>After your visit</div>
                <h3 style={{fontFamily:'var(--font-display)',fontSize:18,fontWeight:500,margin:'0 0 4px'}}>How did it go? Tell us in 90 seconds.</h3>
                <p style={{margin:0,fontSize:13,color:'var(--ink-3)',lineHeight:1.55,maxWidth:420}}>
                  Your experience helps assign Verified Performance Scores — never sold, never tied to your diagnosis.
                </p>
              </div>
              <Button variant="secondary" size="sm" onClick={()=>go('survey')}>
                Rate my visit →
              </Button>
            </div>
            <Disclosure/>
          </div>
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

Object.assign(window,{ Audit1, Audit2, Audit3, Emergency, Snapshot, AuditTopBar });
