// ConditionGuide.jsx — the patient condition flow on the results screen.
// Answers the four questions every worried patient actually has:
//   1. What is it?        — three likely conditions + why one is most likely
//   2. Do I really need it? — an honest necessity read, not a hard sell
//   3. What will it cost?   — UCR (full fee), insurance-negotiated fee, and the
//                             patient's own portion; insurance typed or scanned
//   4. Will it hurt?        — the procedure in calm, professional language, with
//                             a patient-education video to watch
//
// The clinical detail is a reviewed, deterministic knowledge base (PROCEDURE_INFO)
// rather than free model output — clinical content stays HITL-auditable per
// CLAUDE.md §5 / SB 1120. The AI snapshot only picks which condition is likely;
// the guide fills in the procedure detail.

const { useState: useCGs } = React;

// ─── Procedure knowledge base ────────────────────────────────────────────────
// tier drives the insurance math: preventive ~100% covered, basic ~80%, major ~50%.
const PROCEDURE_INFO = {
  exam: {
    label: 'A dental exam', cdt: 'D0150', tier: 'preventive',
    what: 'A full look at your teeth, gums, and bite — usually with X-rays — so a dentist can tell you exactly what is going on.',
    necessity: {
      verdict: 'Yes — this is the step that turns guesswork into an answer.',
      why: 'Everything else on this page is an informed possibility. An exam is how a licensed dentist confirms what is actually happening and what, if anything, needs treating.',
      if_you_wait: 'Small problems stay invisible until they hurt. By then the fix is usually bigger.',
      alternatives: 'There is no real substitute for an in-person exam — but it is quick, and often the news is good.',
    },
    comfort: {
      level: 'none',
      anesthesia: 'None needed. An exam does not involve drilling or numbing.',
      during: 'A dentist looks, gently checks each tooth, and may take a few X-rays. It takes about 20–30 minutes.',
      after: 'Nothing to recover from. You walk out knowing where you stand.',
    },
    eduTags: ['exam', 'checkup', 'x-rays'],
  },
  cleaning: {
    label: 'A professional cleaning', cdt: 'D1110', tier: 'preventive',
    what: 'A hygienist removes hardened plaque (tartar) from your teeth and along the gumline — the buildup a toothbrush cannot reach.',
    necessity: {
      verdict: 'Yes — gum inflammation reverses with a cleaning, but only if it is done in time.',
      why: 'Early gum disease (gingivitis) is fully reversible. A cleaning removes the bacteria driving it so the gums can heal.',
      if_you_wait: 'Gingivitis can progress to periodontitis, where the bone holding your teeth is lost. That damage does not come back.',
      alternatives: 'Better brushing and flossing help going forward, but they cannot remove tartar that has already hardened.',
    },
    comfort: {
      level: 'minimal',
      anesthesia: 'Usually none. If your gums are tender, the hygienist can apply a numbing gel.',
      during: 'You feel scraping and water spray, plus a polish at the end. It takes 30–45 minutes.',
      after: 'Gums may feel slightly tender for a day. Teeth often feel noticeably smoother and cleaner.',
    },
    eduTags: ['cleaning', 'gingivitis', 'gum-health'],
  },
  'deep-cleaning': {
    label: 'A deep cleaning (scaling & root planing)', cdt: 'D4341', tier: 'basic',
    what: 'A thorough cleaning below the gumline that removes bacteria and smooths the tooth roots so the gums can reattach.',
    necessity: {
      verdict: 'Usually yes, once gum disease has reached the bone.',
      why: 'When gum pockets deepen, a regular cleaning can no longer reach the bacteria. A deep cleaning stops the bone loss from continuing.',
      if_you_wait: 'Periodontitis is the leading cause of adult tooth loss. The bone it destroys does not regrow.',
      alternatives: 'There is no at-home substitute once pockets are deep, but catching it early can mean fewer areas need treatment.',
    },
    comfort: {
      level: 'mild',
      anesthesia: 'The area is numbed with local anesthetic, so the cleaning itself is comfortable.',
      during: 'Often done one section of the mouth at a time. Each visit takes about 45–60 minutes.',
      after: 'Gums can be tender and teeth sensitive for a few days. Over-the-counter pain relief is usually enough.',
    },
    eduTags: ['deep-cleaning', 'periodontitis', 'gum-health'],
  },
  filling: {
    label: 'A filling', cdt: 'D2392', tier: 'basic',
    what: 'The dentist removes the decayed part of the tooth and rebuilds it with a tooth-colored composite material.',
    necessity: {
      verdict: 'Usually yes, once decay has reached the inner tooth.',
      why: 'A cavity is bacteria dissolving the tooth. It does not heal on its own — the only choice is to repair it while it is small.',
      if_you_wait: 'Decay spreads toward the nerve. A simple filling can become a root canal plus a crown — more visits, more cost.',
      alternatives: 'If the decay is still only in the outer enamel, a dentist may watch it and strengthen it with fluoride instead. An exam tells you which stage you are at.',
    },
    comfort: {
      level: 'minimal',
      anesthesia: 'A dab of numbing gel, then local anesthetic. Most people feel only a brief pinch.',
      during: 'You feel pressure and vibration — not pain. It usually takes 20–40 minutes.',
      after: 'Mild cold sensitivity for a day or two is normal and fades on its own.',
    },
    eduTags: ['fillings', 'cavities', 'composite'],
  },
  crown: {
    label: 'A crown', cdt: 'D2740', tier: 'major',
    what: 'A custom cap that covers the whole tooth, protecting a tooth that is cracked or too damaged for a filling to hold.',
    necessity: {
      verdict: 'Often yes, when a tooth is cracked or heavily broken down.',
      why: 'A crown holds a weakened tooth together so it can keep working. It is what keeps a cracked tooth from splitting.',
      if_you_wait: 'A crack can deepen until the tooth splits below the gumline — at which point the tooth often cannot be saved.',
      alternatives: 'For smaller damage an onlay or a large filling may be enough. A dentist will tell you whether the tooth needs full coverage.',
    },
    comfort: {
      level: 'minimal',
      anesthesia: 'The tooth is fully numbed with local anesthetic before any work begins.',
      during: 'The tooth is shaped, an impression or scan is taken, and a temporary crown is placed. About 60–90 minutes.',
      after: 'Some tenderness and cold sensitivity for a few days while a temporary crown is on. It settles once the final crown is fitted.',
    },
    eduTags: ['crown', 'cracked-tooth'],
  },
  'root-canal': {
    label: 'A root canal', cdt: 'D3330', tier: 'major',
    what: 'The dentist removes the infected or inflamed nerve from inside the tooth, cleans the canal, and seals it — saving the tooth.',
    necessity: {
      verdict: 'Yes, when the nerve is infected — it is what saves the tooth.',
      why: 'Once the nerve is infected it will not recover. A root canal removes the infection and lets you keep your natural tooth.',
      if_you_wait: 'The infection can spread into the jaw and form an abscess. The tooth may then need to be removed entirely.',
      alternatives: 'The main alternative is removing the tooth and replacing it with an implant or bridge — usually more involved and more expensive than saving it.',
    },
    comfort: {
      level: 'mild',
      anesthesia: 'The tooth is thoroughly numbed. Modern root canals feel much like getting a filling.',
      during: 'You feel pressure, not pain. The visit takes 60–90 minutes; it is often the appointment that ends a toothache.',
      after: 'The tooth may be tender to bite on for a few days. Over-the-counter pain relief usually handles it.',
    },
    eduTags: ['root-canal', 'pulpitis', 'abscess'],
  },
  extraction: {
    label: 'A tooth extraction', cdt: 'D7140', tier: 'basic',
    what: 'Removing a tooth that is too damaged, infected, or crowded to keep — the area is numbed so it is comfortable.',
    necessity: {
      verdict: 'Sometimes — only when a tooth genuinely cannot be saved.',
      why: 'A good dentist tries to save a tooth first. Extraction is the right call when the damage or infection is beyond repair.',
      if_you_wait: 'A badly infected tooth left in place can spread infection. A crowded tooth can keep pushing others out of line.',
      alternatives: 'Ask whether a root canal and crown could save the tooth instead. If it does come out, ask about an implant or bridge to fill the gap.',
    },
    comfort: {
      level: 'mild',
      anesthesia: 'The area is fully numbed with local anesthetic. Sedation options are available if you are anxious.',
      during: 'You feel firm pressure as the tooth is loosened and lifted out — not sharp pain. Often just 10–30 minutes.',
      after: 'Some swelling and soreness for a few days, managed with rest, cold compresses, and pain relief. Follow the post-op instructions closely.',
    },
    eduTags: ['extraction', 'post-op'],
  },
  bonding: {
    label: 'Dental bonding', cdt: 'D2330', tier: 'basic',
    what: 'A tooth-colored resin is shaped onto a chipped or worn tooth and hardened with a light — usually in a single visit.',
    necessity: {
      verdict: 'Optional but worthwhile when a chip exposes the inner tooth.',
      why: 'Bonding restores the shape and seals the exposed surface so the chip does not collect bacteria or worsen.',
      if_you_wait: 'A small chip can grow and let decay in. A purely cosmetic chip can wait, but it is an easy fix.',
      alternatives: 'For larger damage, a veneer or crown lasts longer. A dentist will say which suits the tooth.',
    },
    comfort: {
      level: 'none',
      anesthesia: 'Usually none — bonding rarely involves drilling.',
      during: 'The dentist shapes the resin and hardens it with a light. Often done in 30–60 minutes.',
      after: 'Nothing to recover from. You can eat and drink as normal right away.',
    },
    eduTags: ['bonding', 'cracked-tooth'],
  },
  'night-guard': {
    label: 'A night guard', cdt: 'D9944', tier: 'major',
    what: 'A custom-fit guard worn while you sleep that cushions your teeth from grinding and clenching.',
    necessity: {
      verdict: 'Recommended when grinding is wearing teeth down or causing sensitivity.',
      why: 'A night guard absorbs the force of grinding so it does not crack teeth or wear away enamel.',
      if_you_wait: 'Ongoing grinding flattens teeth, causes sensitivity, and can crack them — damage a guard would have prevented.',
      alternatives: 'Stress reduction and an over-the-counter guard can help, but a custom guard fits better and lasts far longer.',
    },
    comfort: {
      level: 'none',
      anesthesia: 'None — fitting a night guard is just an impression or a digital scan.',
      during: 'A quick scan or mold of your teeth. The guard is made and fitted at a later visit.',
      after: 'Nothing to recover from. It can take a few nights to get used to sleeping with the guard.',
    },
    eduTags: ['night-guard', 'grinding', 'attrition'],
  },
};

// Map a likely-condition name to the procedure a dentist would most commonly use.
function resolveProcedure(name) {
  const k = String(name || '').toLowerCase();
  if (k.includes('irreversible') || k.includes('abscess') || k.includes('infection')) return 'root-canal';
  if (k.includes('pulpitis') || k.includes('cavity') || k.includes('caries') || k.includes('decay')) return 'filling';
  if (k.includes('cracked') || k.includes('crack')) return 'crown';
  if (k.includes('periodont')) return 'deep-cleaning';
  if (k.includes('gingivitis') || k.includes('gum')) return 'cleaning';
  if (k.includes('restorative') || k.includes('chip') || k.includes('broken') || k.includes('lost filling')) return 'bonding';
  if (k.includes('recession') || k.includes('grinding') || k.includes('attrition') || k.includes('wear')) return 'night-guard';
  if (k.includes('extract')) return 'extraction';
  return 'exam';
}

// Coverage assumptions when a real eligibility check is not available.
const TIER_COVERAGE = { preventive: 1.00, basic: 0.80, major: 0.50 };
const NEGOTIATED_FACTOR = 0.74; // typical in-network PPO discount vs. UCR
const usd = (n) => '$' + Math.round(n).toLocaleString();

// ─── Collapsible answer card ─────────────────────────────────────────────────
function GuideCard({ icon, q, sub, defaultOpen, children }) {
  const [open, setOpen] = useCGs(!!defaultOpen);
  return (
    <div className="card card-paper" style={{padding:0,overflow:'hidden'}}>
      <button type="button" onClick={()=>setOpen(o=>!o)} aria-expanded={open}
        style={{width:'100%',display:'flex',alignItems:'center',gap:'var(--s-3)',padding:'var(--s-4)',
                background:'transparent',border:0,cursor:'pointer',textAlign:'left'}}>
        <span style={{flexShrink:0,width:40,height:40,borderRadius:'50%',background:'var(--bone)',
                      display:'flex',alignItems:'center',justifyContent:'center',color:'var(--ink-1)'}}>
          <Icon d={icon} size={20}/>
        </span>
        <span style={{flex:1}}>
          <span style={{display:'block',fontFamily:'var(--font-display)',fontSize:18,fontWeight:500,color:'var(--ink-1)'}}>{q}</span>
          {sub && <span style={{display:'block',fontSize:13,color:'var(--ink-3)',marginTop:2}}>{sub}</span>}
        </span>
        <span style={{flexShrink:0,color:'var(--ink-3)',transform:open?'rotate(180deg)':'none',transition:'transform .15s'}}>
          <Icon d={ICONS.chevD} size={20}/>
        </span>
      </button>
      {open && <div style={{padding:'0 var(--s-4) var(--s-4)',borderTop:'1px solid var(--ink-5)'}}>{children}</div>}
    </div>
  );
}

function Line({ label, children }) {
  return (
    <p style={{margin:'var(--s-3) 0 0',fontSize:14,lineHeight:1.6,color:'var(--ink-2)'}}>
      <strong style={{color:'var(--ink-1)'}}>{label}</strong> {children}
    </p>
  );
}

// ─── Cost section ────────────────────────────────────────────────────────────
function CostAnswer({ proc, state }) {
  const [zip, setZip] = useCGs(state?.zip || '');
  const [mode, setMode] = useCGs('insured');           // 'insured' | 'uninsured'
  const [tier, setTier] = useCGs(proc.tier);           // coverage class for the procedure
  const [carrier, setCarrier] = useCGs(state?.insurance || '');
  const [memberId, setMemberId] = useCGs('');
  const [ucr, setUcr] = useCGs(null);
  const [busy, setBusy] = useCGs(false);
  const [scanMsg, setScanMsg] = useCGs('');
  const fileRef = React.useRef(null);

  // Pull the FAIR Health regional median for this procedure (the UCR baseline).
  const fetchUcr = async () => {
    setBusy(true);
    try {
      const r = await fetch('/api/cost-estimate', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cdt_code: proc.cdt, zip, insurance: carrier }),
      });
      const d = await r.json();
      if (d?.baseline?.amount) setUcr(d.baseline.amount);
      else setUcr(null);
    } catch { setUcr(null); }
    setBusy(false);
  };
  React.useEffect(() => { fetchUcr(); }, []);

  // Scan an insurance card → /api/scan-insurance returns coverage tiers.
  const onScan = async (file) => {
    if (!file) return;
    setBusy(true); setScanMsg('Reading your card…');
    try {
      const fd = new FormData();
      fd.append('image', file);
      const r = await fetch('/api/scan-insurance', { method: 'POST', body: fd });
      const d = await r.json();
      if (d?.parsed) {
        if (d.parsed.carrier) setCarrier(d.parsed.carrier);
        if (d.parsed.member_id && !/unavailable/i.test(d.parsed.member_id)) setMemberId(d.parsed.member_id);
        setScanMsg('Card read. Coverage applied below.');
      } else {
        setScanMsg('Could not read the card — enter your plan below.');
      }
    } catch {
      setScanMsg('Scan unavailable — enter your plan below.');
    }
    setBusy(false);
  };

  const covered = TIER_COVERAGE[tier] ?? 0.8;
  const negotiated = ucr != null ? ucr * NEGOTIATED_FACTOR : null;
  const patientPortion = ucr == null ? null
    : mode === 'uninsured' ? ucr
    : negotiated * (1 - covered);
  const tierLabel = { preventive: 'Preventive (often 100% covered)', basic: 'Basic (often ~80% covered)', major: 'Major (often ~50% covered)' };

  return (
    <div>
      <Line label="The procedure:">{proc.label} ({proc.cdt}).</Line>

      <div style={{display:'flex',gap:8,flexWrap:'wrap',margin:'var(--s-3) 0'}}>
        <label style={{display:'flex',flexDirection:'column',gap:4,fontSize:12,fontWeight:600,color:'var(--ink-3)'}}>
          ZIP code
          <input value={zip} onChange={(e)=>setZip(e.target.value)} onBlur={fetchUcr} placeholder="94110"
            inputMode="numeric" maxLength={5}
            style={{padding:'8px 10px',border:'1px solid var(--ink-5)',borderRadius:8,fontSize:14,width:110}}/>
        </label>
        <div style={{display:'flex',flexDirection:'column',gap:4}}>
          <span style={{fontSize:12,fontWeight:600,color:'var(--ink-3)'}}>Do you have dental insurance?</span>
          <div style={{display:'inline-flex',border:'1px solid var(--ink-5)',borderRadius:8,overflow:'hidden'}}>
            {[['insured','I have insurance'],['uninsured','No insurance / out of network']].map(([k,lbl])=>(
              <button key={k} type="button" onClick={()=>setMode(k)}
                style={{padding:'8px 12px',fontSize:13,fontWeight:600,border:0,cursor:'pointer',
                        background: mode===k ? 'var(--ink-1)' : 'transparent',
                        color: mode===k ? 'var(--paper)' : 'var(--ink-2)'}}>{lbl}</button>
            ))}
          </div>
        </div>
      </div>

      {mode === 'insured' && (
        <div style={{padding:'var(--s-3)',background:'var(--bone)',borderRadius:10,margin:'var(--s-3) 0'}}>
          <div style={{fontSize:12,fontWeight:600,color:'var(--ink-3)',marginBottom:8}}>Add your plan — type it in, or scan your card</div>
          <div style={{display:'flex',gap:8,flexWrap:'wrap',alignItems:'flex-end'}}>
            <label style={{display:'flex',flexDirection:'column',gap:4,fontSize:12,color:'var(--ink-3)',flex:'1 1 160px'}}>
              Carrier
              <input value={carrier} onChange={(e)=>setCarrier(e.target.value)} placeholder="Delta Dental PPO"
                style={{padding:'8px 10px',border:'1px solid var(--ink-5)',borderRadius:8,fontSize:14}}/>
            </label>
            <label style={{display:'flex',flexDirection:'column',gap:4,fontSize:12,color:'var(--ink-3)',flex:'1 1 140px'}}>
              Member ID
              <input value={memberId} onChange={(e)=>setMemberId(e.target.value)} placeholder="Optional"
                style={{padding:'8px 10px',border:'1px solid var(--ink-5)',borderRadius:8,fontSize:14}}/>
            </label>
            <button type="button" className="btn btn-secondary btn-sm" onClick={()=>fileRef.current && fileRef.current.click()}
              style={{display:'flex',alignItems:'center',gap:6}}>
              <Icon d={ICONS.scan} size={16}/> Scan card
            </button>
            <input ref={fileRef} type="file" accept="image/*" capture="environment"
              onChange={(e)=>onScan(e.target.files && e.target.files[0])}
              style={{position:'absolute',width:1,height:1,opacity:0,pointerEvents:'none'}}/>
          </div>
          {scanMsg && <div style={{fontSize:12,color:'var(--ink-3)',marginTop:6}}>{scanMsg}</div>}
          <label style={{display:'flex',flexDirection:'column',gap:4,fontSize:12,color:'var(--ink-3)',marginTop:8}}>
            How this procedure is usually covered
            <select value={tier} onChange={(e)=>setTier(e.target.value)}
              style={{padding:'8px 10px',border:'1px solid var(--ink-5)',borderRadius:8,fontSize:14,background:'var(--paper)'}}>
              {Object.keys(tierLabel).map(t => <option key={t} value={t}>{tierLabel[t]}</option>)}
            </select>
          </label>
        </div>
      )}

      {/* Cost cascade */}
      <div style={{display:'grid',gap:8,margin:'var(--s-3) 0'}}>
        <CostRow label="Full fee (UCR)"
          hint="The dentist's usual fee — what you pay out of network or without insurance."
          amount={busy ? null : ucr} busy={busy}/>
        {mode === 'insured' && (
          <CostRow label="In-network negotiated fee"
            hint="The lower rate an in-network dentist has agreed with your plan."
            amount={busy ? null : negotiated} busy={busy} muted/>
        )}
        <CostRow label="Your estimated portion" highlight
          hint={mode === 'uninsured'
            ? 'With no insurance, you pay the full fee — ask the practice about payment plans or a membership plan.'
            : 'Your share after your plan pays, before any unmet deductible.'}
          amount={busy ? null : patientPortion} busy={busy}/>
      </div>

      <p className="t-fine" style={{marginTop:'var(--s-2)'}}>
        Estimate only. Real costs depend on your specific plan, remaining deductible, and what the dentist finds at the exam.
        For a live eligibility check, the practice can run a 270/271 against your member ID.
      </p>
    </div>
  );
}

function CostRow({ label, hint, amount, busy, highlight, muted }) {
  return (
    <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',gap:12,
                 padding:'var(--s-3)',borderRadius:10,
                 background: highlight ? 'var(--ink-1)' : 'var(--paper)',
                 color: highlight ? 'var(--paper)' : 'var(--ink-1)',
                 border:`1px solid ${highlight ? 'var(--ink-1)' : 'var(--ink-5)'}`,
                 opacity: muted ? 0.85 : 1}}>
      <div>
        <div style={{fontWeight:600,fontSize:14}}>{label}</div>
        <div style={{fontSize:12,opacity: highlight ? 0.75 : 0.6,marginTop:2,maxWidth:340}}>{hint}</div>
      </div>
      <div style={{fontFamily:'var(--font-display)',fontSize:22,fontWeight:500,flexShrink:0}}>
        {busy ? '…' : amount != null ? usd(amount) : '—'}
      </div>
    </div>
  );
}

// ─── The guide ───────────────────────────────────────────────────────────────
function ConditionGuide({ items = [], suggested, state = {}, go }) {
  // Pick the most likely condition: server `suggested`, else the highest-likelihood item.
  const RANK = { high: 3, moderate: 2, low: 1 };
  const sorted = [...items].sort((a, b) => (RANK[b.likelihood] || 0) - (RANK[a.likelihood] || 0));
  const top = suggested && suggested.name
    ? { name: suggested.name, rationale: suggested.rationale }
    : (sorted[0] ? {
        name: sorted[0].name,
        rationale: sorted[0].what_it_could_be
          || `Of the possibilities, this one best fits what you described${state.symptoms && state.symptoms.length ? ` (${state.symptoms.join(', ')})` : ''}.`,
      } : null);
  if (!top) return null;

  const procKey = suggested && suggested.procedure && PROCEDURE_INFO[suggested.procedure]
    ? suggested.procedure
    : resolveProcedure(top.name);
  const proc = PROCEDURE_INFO[procKey] || PROCEDURE_INFO.exam;
  // Deep-link into the education dashboard, scoped to this procedure.
  const eduHref = '/education/?topic=' + encodeURIComponent(procKey);
  const eduVideo = window.VideoCatalog ? window.VideoCatalog.forProcedure(procKey) : null;

  return (
    <section aria-label="Understanding your result" style={{margin:'var(--s-8) 0'}}>
      <h2 style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500,margin:'0 0 var(--s-2)'}}>Your questions, answered</h2>
      <p className="t-meta" style={{margin:'0 0 var(--s-4)'}}>
        The four things patients ask most. This is information to discuss with a dentist — not a diagnosis.
      </p>

      <div style={{display:'grid',gap:'var(--s-3)'}}>

        {/* 1 — What is it? */}
        <GuideCard icon={ICONS.tooth} q="What is it most likely?" sub={`Most likely: ${top.name}`} defaultOpen>
          <Line label="Why this one:">{top.rationale}</Line>
          <p style={{margin:'var(--s-3) 0 6px',fontSize:13,fontWeight:600,color:'var(--ink-3)'}}>The three a dentist would weigh:</p>
          <ol style={{margin:0,paddingLeft:18,display:'grid',gap:6}}>
            {sorted.map((it, i) => (
              <li key={it.name} style={{fontSize:14,lineHeight:1.55,color:'var(--ink-2)'}}>
                <strong style={{color:'var(--ink-1)'}}>{it.name}</strong>
                {it.likelihood && <span style={{
                  marginLeft:6,fontSize:11,padding:'1px 7px',borderRadius:999,
                  background: i===0 ? 'var(--seal)' : 'var(--bone)',
                  color: i===0 ? 'var(--paper)' : 'var(--ink-3)'}}>{i===0?'most likely':it.likelihood}</span>}
                {' — '}{it.description}
              </li>
            ))}
          </ol>
        </GuideCard>

        {/* 2 — Do I really need it? */}
        <GuideCard icon={ICONS.help} q={`Do I really need ${proc.label.replace(/^(A |An )/i,'').toLowerCase()}?`}
          sub="An honest read — not a hard sell">
          <Line label="Short answer:">{proc.necessity.verdict}</Line>
          <Line label="Why:">{proc.necessity.why}</Line>
          <Line label="If you wait:">{proc.necessity.if_you_wait}</Line>
          <Line label="Worth asking about:">{proc.necessity.alternatives}</Line>
          <p className="t-fine" style={{marginTop:'var(--s-3)'}}>
            A second opinion is always reasonable. A dentist should be able to show you why a treatment is needed.
          </p>
        </GuideCard>

        {/* 3 — What will it cost? */}
        <GuideCard icon={ICONS.wallet} q="How much is it going to cost?"
          sub="Full fee, in-network rate, and your portion">
          <CostAnswer proc={proc} state={state}/>
        </GuideCard>

        {/* 4 — Will it hurt? */}
        <GuideCard icon={ICONS.heart} q="Is it going to hurt?"
          sub={`Comfort level: ${proc.comfort.level === 'none' ? 'no discomfort expected' : proc.comfort.level}`}>
          <p style={{margin:'var(--s-3) 0 0',fontSize:14,lineHeight:1.6,color:'var(--ink-2)'}}>{proc.what}</p>
          <Line label="Numbing:">{proc.comfort.anesthesia}</Line>
          <Line label="During the visit:">{proc.comfort.during}</Line>
          <Line label="Afterwards:">{proc.comfort.after}</Line>
          <div style={{display:'flex',gap:8,flexWrap:'wrap',marginTop:'var(--s-3)'}}>
            <a href={eduHref} className="btn btn-secondary btn-sm"
              style={{display:'inline-flex',alignItems:'center',gap:6,textDecoration:'none'}}>
              <Icon d={ICONS.playCircle} size={16}/> {eduVideo ? `Watch: ${eduVideo.title}` : 'Watch: what to expect'}
            </a>
            <a href="/education/" className="btn btn-tertiary btn-sm"
              style={{display:'inline-flex',alignItems:'center',gap:6,textDecoration:'none'}}>
              <Icon d={ICONS.film} size={16}/> All patient videos
            </a>
          </div>
        </GuideCard>

      </div>
    </section>
  );
}

window.ConditionGuide = ConditionGuide;
window.PROCEDURE_INFO = PROCEDURE_INFO;
