// CostEstimate.jsx — UI for the /api/cost-estimate cascade.
// FAIR Health regional median (estimate) → live eligibility (Stedi if configured)
// → dentist-published fee with last_updated date.
const { useState: useCEs, useEffect: useCEe } = React;

const COMMON_CDT = [
  { code: 'D0150', label: 'New patient exam' },
  { code: 'D1110', label: 'Adult cleaning' },
  { code: 'D2392', label: 'Filling (2-surface posterior)' },
  { code: 'D2740', label: 'Crown (porcelain)' },
  { code: 'D3330', label: 'Root canal (molar)' },
  { code: 'D4341', label: 'Deep scaling' },
  { code: 'D7140', label: 'Tooth extraction' },
  { code: 'D8080', label: 'Comprehensive orthodontics' },
];

function CostEstimateScreen({ go, state, set, lang, setLang }) {
  const [cdt, setCdt] = useCEs('D2392');
  const [zip, setZip] = useCEs(state?.zip || '94110');
  const [insurance, setInsurance] = useCEs(state?.insurance || '');
  const [memberId, setMemberId] = useCEs(state?._insurance_card?.memberId || '');
  const [dentistNpi, setDentistNpi] = useCEs(state?._selectedDentist?.npi || '');
  const [data, setData] = useCEs(null);
  const [busy, setBusy] = useCEs(false);

  const run = async () => {
    setBusy(true);
    try {
      const resp = await fetch('/api/cost-estimate', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cdt_code: cdt, zip, insurance, member_id: memberId, dentist_npi: dentistNpi }),
      });
      const d = await resp.json();
      if (resp.ok) setData(d);
    } catch {}
    setBusy(false);
  };
  useCEe(() => { run(); }, []);

  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main>
        <div className="container" style={{padding:'var(--s-6) 0',maxWidth:760}}>
          <div className="t-eyebrow">Cost estimate</div>
          <h1 style={{fontFamily:'var(--font-display)',fontSize:30,fontWeight:500,margin:'0 0 var(--s-4)'}}>What this might cost you</h1>
          <div style={{display:'grid',gridTemplateColumns:'repeat(auto-fit, minmax(180px, 1fr))',gap:'var(--s-3)',marginBottom:'var(--s-4)'}}>
            <Lbl label="Procedure">
              <select value={cdt} onChange={(e)=>setCdt(e.target.value)} style={inp}>
                {COMMON_CDT.map(o => <option key={o.code} value={o.code}>{o.code} · {o.label}</option>)}
              </select>
            </Lbl>
            <Lbl label="ZIP code">
              <input type="text" value={zip} onChange={(e)=>setZip(e.target.value)} style={inp}/>
            </Lbl>
            <Lbl label="Insurance">
              <input type="text" value={insurance} onChange={(e)=>setInsurance(e.target.value)} placeholder="Delta PPO" style={inp}/>
            </Lbl>
            <Lbl label="Member ID (optional, enables live eligibility)">
              <input type="text" value={memberId} onChange={(e)=>setMemberId(e.target.value)} placeholder="ABC1234567" style={inp}/>
            </Lbl>
            <Lbl label="Dentist NPI (optional)">
              <input type="text" value={dentistNpi} onChange={(e)=>setDentistNpi(e.target.value)} placeholder="1234567893" style={inp}/>
            </Lbl>
            <Lbl label="&nbsp;">
              <button className="btn btn-primary btn-md" onClick={run} disabled={busy} style={{height:'100%'}}>{busy ? 'Estimating…' : 'Estimate'}</button>
            </Lbl>
          </div>

          {data && (
            <div style={{display:'flex',flexDirection:'column',gap:'var(--s-3)'}}>
              {data.baseline && <Row title="Regional median" amount={data.baseline.amount} source={data.baseline.source} note={data.baseline.note} estimate/>}
              {data.eligibility
                ? <Row title="Your plan (live eligibility)" amount={data.eligibility.copay} source={data.eligibility.source} note={data.eligibility.coinsurance ? `Coinsurance ${data.eligibility.coinsurance}%` : null}/>
                : <Row title="Your plan (live eligibility)" source="Not configured" note="Add your member ID and the practice runs a real 270/271 check (where we have payer coverage)." disabled/>}
              {data.practice
                ? <Row title="Dentist's published fee" amount={data.practice.amount} source={data.practice.source} note={data.practice.last_updated ? `Last updated ${data.practice.last_updated}` : null}/>
                : <Row title="Dentist's published fee" source="Not on file" note="Pick a dentist in the directory to surface their published rates." disabled/>}
              {data.final_range && (
                <div style={{padding:'var(--s-4)',background:'var(--ink-1)',color:'var(--paper)',borderRadius:12,marginTop:'var(--s-3)'}}>
                  <div className="t-eyebrow" style={{color:'var(--paper)',opacity:.7,marginBottom:6}}>Estimated range</div>
                  <div style={{fontFamily:'var(--font-display)',fontSize:32,fontWeight:500}}>${data.final_range.low.toLocaleString()} – ${data.final_range.high.toLocaleString()}</div>
                  <div style={{fontSize:13,opacity:.8,marginTop:4}}>{data.final_range.note}</div>
                </div>
              )}
              <p className="t-fine">{data.disclosure}</p>
            </div>
          )}
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

const inp = { padding:'8px 10px',border:'1px solid var(--ink-5)',borderRadius:8,fontSize:14,background:'var(--paper)',width:'100%' };
function Lbl({ label, children }) {
  return <label style={{display:'flex',flexDirection:'column',gap:4,fontSize:12,color:'var(--ink-3)',fontWeight:600}}>{label}{children}</label>;
}
function Row({ title, amount, source, note, estimate, disabled }) {
  return (
    <div style={{display:'grid',gridTemplateColumns:'1fr auto',gap:8,padding:'var(--s-3)',background:'var(--paper)',border:`1px solid ${disabled?'var(--ink-5)':'var(--ink-4)'}`,borderRadius:10,opacity:disabled?.7:1}}>
      <div>
        <div style={{fontWeight:600,fontSize:14}}>{title} {estimate && <span style={{fontSize:11,padding:'2px 8px',background:'var(--bone)',color:'var(--ink-3)',borderRadius:999,marginLeft:6,fontWeight:500}}>Estimate</span>}</div>
        <div style={{fontSize:12,color:'var(--ink-3)',marginTop:2}}>{source}{note ? ` · ${note}` : ''}</div>
      </div>
      <div style={{fontFamily:'var(--font-display)',fontSize:22,fontWeight:500,alignSelf:'center'}}>
        {amount != null ? `$${Number(amount).toLocaleString()}` : '—'}
      </div>
    </div>
  );
}

window.CostEstimateScreen = CostEstimateScreen;
