// InsuranceAnalyzer.jsx
// Patient-facing explainer + office-staff pricing breakdown
// Props: { insurance: parsed scan object, mode: 'patient' | 'office' }
// Exported as: window.InsuranceAnalyzer

const { useState: useIA, useMemo: useIAMemo } = React;

function Fi({ name, size = 20, color = 'currentColor', style }) {
  return window.FlatIcon
    ? React.createElement(window.FlatIcon, { name, size, color, style })
    : null;
}

// ── Common dental procedures with typical fee ranges (SF Bay Area 2026) ──────
const PROCEDURES = [
  { cdt:'D0120', name:'Periodic exam',       fee:95,   category:'Preventive' },
  { cdt:'D0150', name:'Comprehensive exam',  fee:175,  category:'Preventive' },
  { cdt:'D0210', name:'Full-mouth X-rays',   fee:265,  category:'Preventive' },
  { cdt:'D0274', name:'Bitewing X-rays (4)', fee:130,  category:'Preventive' },
  { cdt:'D1110', name:'Adult cleaning',      fee:175,  category:'Preventive' },
  { cdt:'D1120', name:'Child cleaning',      fee:145,  category:'Preventive' },
  { cdt:'D1206', name:'Fluoride varnish',    fee:55,   category:'Preventive' },
  { cdt:'D2140', name:'Amalgam filling (1)', fee:185,  category:'Basic' },
  { cdt:'D2391', name:'Resin filling (1)',   fee:210,  category:'Basic' },
  { cdt:'D7140', name:'Simple extraction',   fee:185,  category:'Basic' },
  { cdt:'D7210', name:'Surgical extraction', fee:350,  category:'Basic' },
  { cdt:'D2740', name:'Porcelain crown',     fee:1650, category:'Major' },
  { cdt:'D3330', name:'Molar root canal',    fee:1450, category:'Major' },
  { cdt:'D5110', name:'Complete denture',    fee:2200, category:'Major' },
  { cdt:'D6010', name:'Implant placement',   fee:2800, category:'Implants' },
  { cdt:'D6065', name:'Implant crown',       fee:1800, category:'Implants' },
  { cdt:'D4341', name:'Perio scaling (4 teeth)', fee:320, category:'Periodontics' },
  { cdt:'D8080', name:'Comprehensive ortho', fee:6500, category:'Orthodontics' },
];

// ── Coverage lookup from parsed insurance data ────────────────────────────────
function getCoverage(insurance, procedureCategory) {
  if (!insurance?.benefits) return null;
  const ben = insurance.benefits.find(b => {
    const cat = (b.category || '').toLowerCase();
    const pc  = procedureCategory.toLowerCase();
    if (pc === 'preventive')    return cat.includes('prevent');
    if (pc === 'basic')         return cat.includes('basic') || cat.includes('restor');
    if (pc === 'major')         return cat.includes('major');
    if (pc === 'orthodontics')  return cat.includes('ortho');
    if (pc === 'implants')      return cat.includes('implant');
    if (pc === 'periodontics')  return cat.includes('perio');
    return false;
  });
  return ben || null;
}

function calcPatientCost(fee, coveragePct, deductibleRemaining = 0) {
  if (coveragePct === null || coveragePct === undefined) return { insurancePays: 0, patientPays: fee, note: 'Coverage unknown' };
  const afterDeductible = Math.max(0, fee - deductibleRemaining);
  const insurancePays   = Math.round((afterDeductible * coveragePct) / 100);
  const patientPays     = fee - insurancePays;
  return { insurancePays, patientPays, deductibleApplied: Math.min(fee, deductibleRemaining) };
}

// ── Colour helpers ────────────────────────────────────────────────────────────
const CAT_COLOR = {
  Preventive:    '#27c1a3',
  Basic:         '#4da3ff',
  Major:         '#e8b339',
  Implants:      '#a78bfa',
  Periodontics:  '#fb923c',
  Orthodontics:  '#f472b6',
};

// ─────────────────────────────────────────────────────────────────────────────
// PATIENT VIEW — plain English explainer
// ─────────────────────────────────────────────────────────────────────────────
function PatientExplainer({ insurance }) {
  const ins = insurance || {};
  const benefits = ins.benefits || [];

  const cards = [
    {
      icon:'tooth', label:'Your plan',
      value: [ins.carrier, ins.plan_name, ins.plan_type].filter(Boolean).join(' · ') || 'Unknown plan',
      sub: ins.network_name ? `Network: ${ins.network_name}` : null,
    },
    {
      icon:'creditCard', label:'Member ID',
      value: ins.member_id || 'Not captured',
      sub: ins.group_id ? `Group: ${ins.group_id}` : null,
    },
    {
      icon:'cal', label:'Annual maximum',
      value: ins.annual_maximum || 'Check your plan',
      sub: 'The most your plan pays per year',
    },
    {
      icon:'dollar', label:'Annual deductible',
      value: ins.deductible_individual || 'Check your plan',
      sub: ins.deductible_applies_to ? `Applies to: ${ins.deductible_applies_to}` : null,
    },
  ];

  return (
    <div>
      <p style={{fontSize:14,color:'#8b9aa7',marginBottom:18,lineHeight:1.6}}>
        Here's what your insurance covers in plain English. These are estimates — your dentist's office will verify your exact benefits before treatment.
      </p>

      {/* Summary cards */}
      <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:12,marginBottom:24}}>
        {cards.map(c => (
          <div key={c.label} style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:'12px 14px'}}>
            <div style={{marginBottom:4}}><Fi name={c.icon} size={22} color="#27c1a3"/></div>
            <div style={{fontSize:11,color:'#8b9aa7',fontWeight:600,textTransform:'uppercase',letterSpacing:'0.5px',marginBottom:2}}>{c.label}</div>
            <div style={{fontSize:14,color:'#e6edf3',fontWeight:700}}>{c.value}</div>
            {c.sub && <div style={{fontSize:11,color:'#8b9aa7',marginTop:2}}>{c.sub}</div>}
          </div>
        ))}
      </div>

      {/* Coverage breakdown */}
      <div style={{marginBottom:20}}>
        <h4 style={{fontSize:13,color:'#e6edf3',margin:'0 0 12px',fontWeight:700}}>What's covered</h4>
        <div style={{display:'flex',flexDirection:'column',gap:8}}>
          {benefits.map((b, i) => {
            const pct = b.coverage_pct;
            const color = CAT_COLOR[b.category] || '#8b9aa7';
            return (
              <div key={i} style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:8,padding:'10px 14px'}}>
                <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:4}}>
                  <span style={{fontSize:13,color:'#e6edf3',fontWeight:600}}>{b.category}</span>
                  <span style={{fontSize:13,fontWeight:700,color: pct===100?'#3fb96b': pct>=70?color:'#e8b339'}}>
                    {pct !== null && pct !== undefined ? `${pct}% covered` : 'Check plan'}
                  </span>
                </div>
                {pct !== null && pct !== undefined && (
                  <div style={{height:4,background:'#1f2b36',borderRadius:4,marginBottom:6}}>
                    <div style={{height:4,width:`${pct}%`,background:color,borderRadius:4,transition:'width 0.4s'}}/>
                  </div>
                )}
                <div style={{fontSize:12,color:'#8b9aa7'}}>{b.services}</div>
                {b.notes && <div style={{fontSize:11,color:'#8b9aa7',marginTop:3,fontStyle:'italic'}}>{b.notes}</div>}
                {b.patient_copay && (
                  <div style={{fontSize:11,marginTop:4,color:'#e8b339'}}>
                    Your share: <strong style={{color:'#e6edf3'}}>{b.patient_copay}</strong>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Important notices */}
      {(ins.waiting_periods || ins.missing_teeth_clause || ins.frequency_limitations || ins.prior_auth_required) && (
        <div style={{background:'#1a1200',border:'1px solid #4a3800',borderRadius:10,padding:'12px 14px',marginBottom:16}}>
          <div style={{fontSize:12,fontWeight:700,color:'#e8b339',marginBottom:8,display:'flex',alignItems:'center',gap:6}}>
            <Fi name="alert" size={14} color="#e8b339"/> Things to know about your plan
          </div>
          {ins.waiting_periods && (
            <div style={{fontSize:12,color:'#b3a070',marginBottom:5}}>
              <strong style={{color:'#e8b339'}}>Waiting periods:</strong> {ins.waiting_periods}
            </div>
          )}
          {ins.frequency_limitations && (
            <div style={{fontSize:12,color:'#b3a070',marginBottom:5}}>
              <strong style={{color:'#e8b339'}}>Frequency limits:</strong> {ins.frequency_limitations}
            </div>
          )}
          {ins.missing_teeth_clause && (
            <div style={{fontSize:12,color:'#b3a070',marginBottom:5}}>
              <strong style={{color:'#e8b339'}}>Missing teeth clause:</strong> Teeth missing before your coverage started may not be covered for replacement.
            </div>
          )}
          {ins.prior_auth_required && (
            <div style={{fontSize:12,color:'#b3a070'}}>
              <strong style={{color:'#e8b339'}}>Pre-authorization needed for:</strong> {ins.prior_auth_required}
            </div>
          )}
        </div>
      )}

      {/* Contact */}
      {(ins.phone_member || ins.phone_provider || ins.website) && (
        <div style={{background:'#0f1a26',border:'1px solid #1f2b36',borderRadius:8,padding:'10px 14px'}}>
          <div style={{fontSize:11,fontWeight:700,color:'#8b9aa7',textTransform:'uppercase',marginBottom:6}}>Contact your insurer</div>
          {ins.phone_member && <div style={{fontSize:12,color:'#4da3ff',marginBottom:2}}>Member services: {ins.phone_member}</div>}
          {ins.phone_provider && <div style={{fontSize:12,color:'#4da3ff',marginBottom:2}}>Provider services: {ins.phone_provider}</div>}
          {ins.website && <div style={{fontSize:12,color:'#4da3ff'}}>{ins.website}</div>}
        </div>
      )}

      {ins.confidence === 'low' && (
        <div style={{marginTop:12,fontSize:11,color:'#8b9aa7',padding:'8px 10px',background:'#111',borderRadius:6,border:'1px solid #1f2b36'}}>
          {window.FlatIcon && React.createElement(window.FlatIcon, { name: 'info', size: 14, color: '#8b9aa7', style: { marginRight: 6, verticalAlign: 'middle' } })}
          These are estimates based on typical plan structures. Your office will verify exact benefits via insurance eligibility check before treatment.
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// OFFICE STAFF VIEW — pricing breakdown per procedure
// ─────────────────────────────────────────────────────────────────────────────
function OfficePricingBreakdown({ insurance }) {
  const [deductibleUsed, setDeductibleUsed] = useIA(0);
  const [annualUsed, setAnnualUsed] = useIA(0);
  const [filter, setFilter] = useIA('All');

  const ins = insurance || {};

  // Parse annual max as number
  const annualMax = parseInt((ins.annual_maximum || '').replace(/[^0-9]/g,'')) || 1500;
  const dedAmt    = parseInt((ins.deductible_individual || '').replace(/[^0-9]/g,'')) || 50;
  const dedRemain = Math.max(0, dedAmt - deductibleUsed);
  const maxRemain = Math.max(0, annualMax - annualUsed);

  const categories = ['All', 'Preventive', 'Basic', 'Major', 'Periodontics', 'Implants', 'Orthodontics'];
  const filtered   = filter === 'All' ? PROCEDURES : PROCEDURES.filter(p => p.category === filter);

  return (
    <div>
      <p style={{fontSize:13,color:'#8b9aa7',marginBottom:16,lineHeight:1.6}}>
        Estimated patient cost based on scanned benefits. Adjust deductible and annual maximum usage below to get accurate quotes.
      </p>

      {/* Insurance header bar */}
      <div style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:'12px 16px',marginBottom:16,display:'flex',gap:20,flexWrap:'wrap'}}>
        <div>
          <div style={{fontSize:11,color:'#8b9aa7',marginBottom:2}}>CARRIER</div>
          <div style={{fontSize:13,color:'#e6edf3',fontWeight:700}}>{ins.carrier || '—'}</div>
        </div>
        <div>
          <div style={{fontSize:11,color:'#8b9aa7',marginBottom:2}}>PLAN TYPE</div>
          <div style={{fontSize:13,color:'#27c1a3',fontWeight:700}}>{ins.plan_type || '—'}</div>
        </div>
        <div>
          <div style={{fontSize:11,color:'#8b9aa7',marginBottom:2}}>MEMBER ID</div>
          <div style={{fontSize:13,color:'#e6edf3',fontWeight:700}}>{ins.member_id || '—'}</div>
        </div>
        <div>
          <div style={{fontSize:11,color:'#8b9aa7',marginBottom:2}}>GROUP ID</div>
          <div style={{fontSize:13,color:'#e6edf3',fontWeight:700}}>{ins.group_id || '—'}</div>
        </div>
        {ins.network_name && (
          <div>
            <div style={{fontSize:11,color:'#8b9aa7',marginBottom:2}}>NETWORK</div>
            <div style={{fontSize:13,color:'#4da3ff',fontWeight:700}}>{ins.network_name}</div>
          </div>
        )}
      </div>

      {/* Adjustable usage sliders */}
      <div style={{background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:'14px 16px',marginBottom:16}}>
        <div style={{fontSize:12,fontWeight:700,color:'#e6edf3',marginBottom:12}}>Adjust benefit usage for this patient</div>
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
          <div>
            <label style={{fontSize:11,color:'#8b9aa7',fontWeight:600}}>
              Deductible already used: <span style={{color:'#27c1a3'}}>${deductibleUsed}</span> / ${dedAmt}
            </label>
            <input type="range" min={0} max={dedAmt} value={deductibleUsed}
              onChange={e => setDeductibleUsed(+e.target.value)}
              style={{width:'100%',accentColor:'var(--acc,#27c1a3)',marginTop:6}}/>
            <div style={{fontSize:11,color: dedRemain===0?'#3fb96b':'#e8b339',display:'flex',alignItems:'center',gap:4}}>
              {dedRemain === 0
                ? <>{React.createElement(Fi, { name: 'check', size: 12, color: '#3fb96b' })} Deductible met</>
                : `$${dedRemain} remaining`}
            </div>
          </div>
          <div>
            <label style={{fontSize:11,color:'#8b9aa7',fontWeight:600}}>
              Annual max used: <span style={{color:'#27c1a3'}}>${annualUsed}</span> / ${annualMax}
            </label>
            <input type="range" min={0} max={annualMax} step={50} value={annualUsed}
              onChange={e => setAnnualUsed(+e.target.value)}
              style={{width:'100%',accentColor:'var(--acc,#27c1a3)',marginTop:6}}/>
            <div style={{height:5,background:'#1f2b36',borderRadius:3,marginTop:4}}>
              <div style={{height:5,width:`${Math.min(100,(annualUsed/annualMax)*100)}%`,background: annualUsed>=annualMax?'#e5654f':'#27c1a3',borderRadius:3}}/>
            </div>
            <div style={{fontSize:11,color: annualUsed>=annualMax?'#e5654f':'#8b9aa7',marginTop:2,display:'flex',alignItems:'center',gap:4}}>
              {annualUsed >= annualMax
                ? <>{React.createElement(Fi, { name: 'alert', size: 12, color: '#e5654f' })} Annual max reached — patient pays 100%</>
                : `$${maxRemain} remaining`}
            </div>
          </div>
        </div>
      </div>

      {/* Category filter */}
      <div style={{display:'flex',gap:6,flexWrap:'wrap',marginBottom:14}}>
        {categories.map(c => (
          <button key={c} onClick={() => setFilter(c)}
            style={{padding:'4px 10px',borderRadius:20,border:'none',cursor:'pointer',fontSize:11,fontWeight:600,
              background: filter===c ? (CAT_COLOR[c]||'#27c1a3') : '#1f2b36',
              color: filter===c ? '#fff' : '#8b9aa7'}}>
            {c}
          </button>
        ))}
      </div>

      {/* Procedure pricing table */}
      <div style={{border:'1px solid #1f2b36',borderRadius:10,overflow:'hidden'}}>
        <div style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr 1fr',background:'#0d1117',padding:'8px 14px',fontSize:11,color:'#8b9aa7',fontWeight:700,textTransform:'uppercase',letterSpacing:'0.5px',gap:8}}>
          <span>Procedure</span><span>Fee</span><span>Insurance</span><span>Patient owes</span><span>Status</span>
        </div>
        {filtered.map((proc, i) => {
          const cov   = getCoverage(ins, proc.category);
          const pct   = cov?.coverage_pct ?? null;
          const maxExhausted = annualUsed >= annualMax;
          const effectivePct = maxExhausted ? 0 : pct;
          const { insurancePays, patientPays, deductibleApplied } = calcPatientCost(proc.fee, effectivePct, dedRemain);
          const color = CAT_COLOR[proc.category] || '#8b9aa7';

          return (
            <div key={proc.cdt} style={{display:'grid',gridTemplateColumns:'2fr 1fr 1fr 1fr 1fr',padding:'10px 14px',gap:8,
              background: i%2===0?'#0b1116':'#0f161d',borderTop:'1px solid #1a2535',alignItems:'center'}}>
              <div>
                <div style={{fontSize:13,color:'#e6edf3',fontWeight:500}}>{proc.name}</div>
                <div style={{fontSize:10,color:'#8b9aa7'}}>{proc.cdt} · <span style={{color}}>{proc.category}</span></div>
              </div>
              <div style={{fontSize:13,color:'#8b9aa7'}}>${proc.fee.toLocaleString()}</div>
              <div style={{fontSize:13,color:'#3fb96b',fontWeight:600}}>
                {pct === null ? '—' : maxExhausted ? '$0' : `$${insurancePays.toLocaleString()}`}
              </div>
              <div style={{fontSize:14,color: patientPays > proc.fee*0.6 ? '#e5654f' : patientPays > proc.fee*0.3 ? '#e8b339' : '#3fb96b',fontWeight:700}}>
                {maxExhausted ? `$${proc.fee.toLocaleString()}` : `$${patientPays.toLocaleString()}`}
              </div>
              <div style={{fontSize:10,color:'#8b9aa7'}}>
                {pct === null ? <span style={{color:'#e8b339'}}>Verify</span>
                  : pct === 100 ? <span style={{color:'#3fb96b',display:'inline-flex',alignItems:'center',gap:4}}><Fi name="check" size={12} color="#3fb96b"/> Covered</span>
                  : maxExhausted ? <span style={{color:'#e5654f'}}>Max reached</span>
                  : deductibleApplied > 0 ? <span style={{color:'#e8b339'}}>Ded. applies</span>
                  : <span style={{color:'#4da3ff'}}>{pct}% covered</span>}
              </div>
            </div>
          );
        })}
      </div>

      {/* Notices */}
      <div style={{marginTop:14,fontSize:11,color:'#8b9aa7',lineHeight:1.6,padding:'10px 12px',background:'#0f161d',borderRadius:8,border:'1px solid #1f2b36'}}>
        <span style={{display:'inline-flex',alignItems:'center',gap:6}}><Fi name="stetho" size={14} color="#e6edf3"/> <strong style={{color:'#e6edf3'}}>Pre-authorization:</strong></span> {ins.prior_auth_required || 'Check with carrier for major work.'}<br/>
        {ins.waiting_periods && <><strong style={{color:'#e8b339'}}>Waiting periods:</strong> {ins.waiting_periods}<br/></>}
        {ins.out_of_network && <><strong style={{color:'#e6edf3'}}>Out-of-network:</strong> {ins.out_of_network}<br/></>}
        <strong style={{color:'#e6edf3'}}>Disclaimer:</strong> Estimates only. Verify benefits via eligibility check (270/271) before quoting patients. Patient is responsible for final balance.
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// MAIN EXPORT
// ─────────────────────────────────────────────────────────────────────────────
function InsuranceAnalyzer({ insurance, defaultMode = 'patient' }) {
  const [mode, setMode] = useIA(defaultMode);

  if (!insurance) {
    return (
      <div style={{padding:24,textAlign:'center',color:'#8b9aa7',fontSize:13}}>
        Scan or enter insurance details above to see the coverage analyzer.
      </div>
    );
  }

  return (
    <div style={{fontFamily:"system-ui,'Segoe UI',sans-serif"}}>
      {/* Mode switcher */}
      <div style={{display:'flex',background:'#0f161d',border:'1px solid #1f2b36',borderRadius:10,padding:4,gap:4,marginBottom:18}}>
        {[['patient','user','Patient Explainer'],['office','building','Office Pricing Breakdown']].map(([k,icon,label]) => (
          <button key={k} onClick={() => setMode(k)}
            style={{flex:1,padding:'8px 12px',borderRadius:7,border:'none',cursor:'pointer',fontSize:12,fontWeight:700,
              background: mode===k ? '#27c1a3' : 'transparent',
              color: mode===k ? '#0b1116' : '#8b9aa7',display:'flex',alignItems:'center',justifyContent:'center',gap:6}}>
            <Fi name={icon} size={14} color={mode===k ? '#0b1116' : '#8b9aa7'}/> {label}
          </button>
        ))}
      </div>

      {mode === 'patient' && <PatientExplainer insurance={insurance}/>}
      {mode === 'office'  && <OfficePricingBreakdown insurance={insurance}/>}
    </div>
  );
}

window.InsuranceAnalyzer = InsuranceAnalyzer;
window.PatientExplainer  = PatientExplainer;
window.OfficePricingBreakdown = OfficePricingBreakdown;
