// tab-charges.jsx — F5 concurrent stay charge capture
// Daily charge log · running total vs approved cap · room rent penalty
// calculator · implant barcode reconciliation gate.

const PCCT_t = window.PCT;
const PCCT_d = window.PCA;

function ChargesTab({ claim, insurer }) {
  const store = useStore();
  const integrated = useIntegrated();
  const [addOpen, setAddOpen] = React.useState(false);
  const [roomCalcOpen, setRoomCalcOpen] = React.useState(false);
  const [implantUpload, setImplantUpload] = React.useState(null); // chargeId
  const [syncing, setSyncing] = React.useState(false);
  const [lastSyncAt, setLastSyncAt] = React.useState(claim.charges && claim.charges.length > 0 ? Date.now() - 22 * 60 * 1000 : null);

  const charges = claim.charges || [];
  const total = charges.reduce((s, c) => s + (c.amount * (c.qty || 1)), 0);
  const cap = claim.approvedAmount || claim.estimatedCost;
  const pct = cap > 0 ? Math.min(100, (total / cap) * 100) : 0;
  const over = total > cap;

  const tariff = store.tariffFor(claim.insurer);
  const implantsMissing = charges.filter(c => c.category === 'IMPLANT' && c.implantMissing);

  // Group charges by day
  const byDay = {};
  charges.forEach(c => {
    const day = PCCT_d.dayOnly(c.date);
    if (!byDay[day]) byDay[day] = [];
    byDay[day].push(c);
  });
  const days = Object.keys(byDay);

  // Bucket totals by category
  const byCat = {};
  charges.forEach(c => {
    if (!byCat[c.category]) byCat[c.category] = 0;
    byCat[c.category] += c.amount * (c.qty || 1);
  });

  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:14 }}>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        {/* Running total card */}
        <AppCard>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:0 }}>
            <CapStat label="Approved cap"    value={<AppMoney value={cap} strong size={20}/>} sub={`${insurer.name} · pre-auth`}/>
            <CapStat label="Charges to date" value={<AppMoney value={total} strong size={20}/>} sub={`${charges.length} entries · ${days.length} days`} border/>
            <CapStat label={over ? 'OVERAGE' : 'Headroom'}
                     value={<AppMoney value={Math.abs(cap - total)} strong size={20} neg={over}/>}
                     sub={over ? 'Approve add-on or write off' : `${Math.round(100 - pct)}% under cap`}
                     border tone={over ? 'error' : 'success'}/>
          </div>

          {cap > 0 && (
            <div style={{ marginTop:18 }}>
              <div style={{
                height:8, background: PCCT_t.c.surface2, borderRadius:4,
                position:'relative', overflow:'hidden',
              }}>
                <div style={{
                  position:'absolute', inset:0,
                  width: `${pct}%`,
                  background: over ? PCCT_t.c.error : pct > 85 ? PCCT_t.c.warning : PCCT_t.c.success,
                  transition: 'width .4s',
                }}/>
              </div>
              <div style={{
                marginTop:6, display:'flex', justifyContent:'space-between',
                fontSize:11, color: PCCT_t.c.textDim, fontFamily: PCCT_t.f.mono,
              }}>
                <span>0</span>
                <span>{Math.round(pct)}% of cap</span>
                <span>{PCCT_d.inr(cap)}</span>
              </div>
            </div>
          )}
        </AppCard>

        {/* HMS sync strip (integrated only) */}
        {integrated && (
          <div style={{
            padding:'10px 14px',
            background: PCCT_t.c.brandSoft,
            border:`1px solid ${PCCT_t.c.brand}30`,
            borderRadius:9,
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{
              width:32, height:32, borderRadius:7,
              background:'#fff', color: PCCT_t.c.brand,
              display:'grid', placeItems:'center', flexShrink:0,
            }}>
              <AppIcon name={syncing ? 'clock' : 'refresh'} size={15}/>
            </div>
            <div style={{ flex:1, fontSize:12.5, color:'#4C1D95', lineHeight:1.55 }}>
              <div><strong>Live sync with PulseChart HMS</strong> · <span style={{ fontFamily: PCCT_t.f.mono, fontSize:11 }}>billing-service v2.4</span></div>
              <div style={{ fontSize:11, color:'#5B21B6', marginTop:2 }}>
                {syncing ? 'Syncing…' :
                  lastSyncAt ? `Last synced ${syncAgo(lastSyncAt)} · next auto-sync in ${Math.max(0, Math.round((6*60 - (Date.now() - lastSyncAt)/60000)/60*10)/10)}h` :
                  'No data synced yet · click to pull from billing-service'}
              </div>
            </div>
            <AppBtn size="sm" kind="ghost" icon="refresh" disabled={syncing}
              onClick={() => {
                setSyncing(true);
                setTimeout(() => {
                  // Add a couple of newly-synced charges to demo the sync
                  const now = Date.now();
                  const synced = [
                    { date: now, category:'PHARMACY', description:'Inj. Atorvastatin 40mg', qty:1, amount: 280, source:'hms-sync' },
                    { date: now, category:'DIAGNOSTIC', description:'Lipid profile (post-op)', qty:1, amount: 1450, source:'hms-sync' },
                  ];
                  synced.forEach(c => store.addCharge(claim.id, c));
                  setLastSyncAt(now);
                  setSyncing(false);
                  store.toast({ icon:'whatsapp', title:`${synced.length} charges synced from HMS`, body:'billing-service · pulled live' });
                }, 1100);
              }}>
              {syncing ? 'Syncing…' : 'Sync now'}
            </AppBtn>
          </div>
        )}

        {/* Implant gate banner */}
        {implantsMissing.length > 0 && (
          <div style={{
            padding:'12px 16px',
            background: PCCT_t.c.warningTint,
            border:`1px solid ${PCCT_t.c.warning}30`,
            borderRadius:9,
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{
              width:32, height:32, borderRadius:7,
              background:'#fff', color: PCCT_t.c.warning,
              display:'grid', placeItems:'center', flexShrink:0,
            }}>
              <AppIcon name="alert" size={16}/>
            </div>
            <div style={{ flex:1, fontSize:12.5, color:'#92400E', lineHeight:1.55 }}>
              <strong>Implant barcode missing.</strong> {implantsMissing.length} implant charge{implantsMissing.length > 1 ? 's' : ''}
              {' '}without a barcode upload. Discharge submission will be <strong>blocked</strong> until reconciled.
            </div>
            <AppBtn size="sm" kind="ghost" icon="upload" onClick={() => setImplantUpload(implantsMissing[0].id)}>
              Upload barcode
            </AppBtn>
          </div>
        )}

        {/* Charges list */}
        <AppCard pad={0}>
          <div style={{
            padding:'14px 18px',
            borderBottom: `1px solid ${PCCT_t.c.border}`,
            display:'flex', justifyContent:'space-between', alignItems:'center',
          }}>
            <AppSectionLabel>Daily charges</AppSectionLabel>
            <div style={{ display:'flex', gap:8, alignItems:'center' }}>
              {!integrated && (
                <span style={{
                  fontSize:10.5, color: PCCT_t.c.textDim, fontFamily: PCCT_t.f.mono,
                  letterSpacing:'.04em', textTransform:'uppercase', marginRight:4,
                }}>Standalone · manual entry only</span>
              )}
              <AppBtn size="sm" kind="ghost" icon="refresh" disabled={!integrated}>{integrated ? 'Re-sync HMS' : 'HMS sync (integrated only)'}</AppBtn>
              <AppBtn size="sm" kind="primary" icon="plus" onClick={() => setAddOpen(true)}>Add charge</AppBtn>
            </div>
          </div>

          {charges.length === 0 ? (
            <AppEmpty
              icon="money"
              title="No charges logged yet"
              body="Log charges day-by-day to see the running total against the approved cap. In HMS mode, charges sync from billing-service every 6 hours."
              action={<AppBtn kind="primary" icon="plus" onClick={() => setAddOpen(true)}>Add first charge</AppBtn>}
            />
          ) : (
            <ChargesTable byDay={byDay} days={days} tariff={tariff} onUploadImplant={setImplantUpload}/>
          )}
        </AppCard>

        {/* Charge breakdown by category */}
        {charges.length > 0 && (
          <AppCard>
            <AppSectionLabel>Breakdown by category</AppSectionLabel>
            <div style={{ marginTop:14, display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:10 }}>
              {PCCT_d.chargeCategories.filter(c => byCat[c.id]).map(c => (
                <div key={c.id} style={{
                  padding:'11px 13px',
                  background: PCCT_t.c.surface2, borderRadius:7,
                }}>
                  <div style={{
                    fontFamily: PCCT_t.f.mono, fontSize:9, fontWeight:600,
                    letterSpacing:'.08em', textTransform:'uppercase',
                    color: PCCT_t.c.textMuted, marginBottom:5,
                  }}>{c.label}</div>
                  <AppMoney value={byCat[c.id]} strong size={14}/>
                  <div style={{ fontSize:10, color: PCCT_t.c.textDim, marginTop:2, fontFamily: PCCT_t.f.mono }}>
                    {Math.round((byCat[c.id]/total)*100)}% of total
                  </div>
                </div>
              ))}
            </div>
          </AppCard>
        )}
      </div>

      {/* RIGHT */}
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <RoomRentCalculatorCard claim={claim} onOpen={() => setRoomCalcOpen(true)}/>
        <DailyAuditCard claim={claim}/>
        <ProcedureGuidanceCard claim={claim} insurer={insurer}/>
      </div>

      <AddChargeModal open={addOpen} onClose={() => setAddOpen(false)} claim={claim}/>
      <RoomRentCalcModal open={roomCalcOpen} onClose={() => setRoomCalcOpen(false)} claim={claim}/>
      <ImplantBarcodeModal open={!!implantUpload} onClose={() => setImplantUpload(null)} claim={claim} chargeId={implantUpload}/>
    </div>
  );
}

function CapStat({ label, value, sub, border, tone }) {
  return (
    <div style={{
      padding:'4px 18px',
      borderLeft: border ? `1px solid ${PCCT_t.c.border}` : 'none',
    }}>
      <div style={{
        fontFamily: PCCT_t.f.mono, fontSize:9.5, fontWeight:600,
        letterSpacing:'.1em', textTransform:'uppercase',
        color: tone === 'error' ? PCCT_t.c.error : tone === 'success' ? PCCT_t.c.success : PCCT_t.c.textMuted,
      }}>{label}</div>
      <div style={{ marginTop:6 }}>{value}</div>
      <div style={{ fontSize:10.5, color: PCCT_t.c.textDim, marginTop:4 }}>{sub}</div>
    </div>
  );
}

// ── Charges table ────────────────────────────────────────
function ChargesTable({ byDay, days, tariff, onUploadImplant }) {
  const integrated = useIntegrated();
  return (
    <div>
      <div style={{
        display:'grid',
        gridTemplateColumns:'100px 100px 1fr 60px 100px 120px 40px',
        gap:12, padding:'10px 18px',
        borderBottom: `1px solid ${PCCT_t.c.border}`,
        fontFamily: PCCT_t.f.mono, fontSize:9.5, fontWeight:600,
        letterSpacing:'.06em', textTransform:'uppercase',
        color: PCCT_t.c.textMuted,
      }}>
        <div>Date</div>
        <div>Category</div>
        <div>Description</div>
        <div style={{ textAlign:'right' }}>Qty</div>
        <div style={{ textAlign:'right' }}>Rate</div>
        <div style={{ textAlign:'right' }}>Total</div>
        <div></div>
      </div>
      {days.map(day => (
        <div key={day}>
          <div style={{
            padding:'8px 18px', background:'#FAFAF9',
            fontFamily: PCCT_t.f.mono, fontSize:10.5, fontWeight:600,
            color: PCCT_t.c.text,
          }}>{day}</div>
          {byDay[day].map(c => {
            const tariffRow = tariff?.rows.find(r => r.description.toLowerCase().includes(c.description.toLowerCase().slice(0,15)));
            const overTariff = tariffRow && c.amount > tariffRow.maxAmount;
            return (
              <div key={c.id} style={{
                display:'grid',
                gridTemplateColumns:'100px 100px 1fr 60px 100px 120px 40px',
                gap:12, padding:'10px 18px', alignItems:'center',
                borderBottom: `1px solid ${PCCT_t.c.border}`,
                background: c.implantMissing ? PCCT_t.c.warningTint + '40' : 'transparent',
              }}>
                <div style={{ fontSize:11.5, color: PCCT_t.c.textMuted, fontFamily: PCCT_t.f.mono }}>{day.split(',')[0]}</div>
                <div>
                  <span style={{
                    fontSize:10, fontFamily: PCCT_t.f.mono, fontWeight:600,
                    padding:'2px 6px', borderRadius:4,
                    background: PCCT_t.c.surface2, color: PCCT_t.c.text,
                    letterSpacing:'.04em', textTransform:'uppercase',
                  }}>{c.category.replace('_',' ')}</span>
                </div>
                <div style={{ fontSize:12.5, color: PCCT_t.c.text, minWidth:0 }}>
                  <span>{c.description}</span>
                  {integrated && c.source !== 'manual' && (
                    <span style={{ marginLeft:8 }}><HmsBadge variant="chip">HMS</HmsBadge></span>
                  )}
                  {c.implantMissing && (
                    <span style={{
                      marginLeft:8, padding:'1px 5px', borderRadius:3,
                      background: PCCT_t.c.warning, color:'#fff',
                      fontSize:9, fontWeight:600, fontFamily: PCCT_t.f.mono,
                      letterSpacing:'.04em',
                    }}>BARCODE MISSING</span>
                  )}
                  {c.implantBarcode && (
                    <span style={{
                      marginLeft:8, padding:'1px 5px', borderRadius:3,
                      background: PCCT_t.c.successTint, color: PCCT_t.c.success,
                      fontSize:9, fontWeight:600, fontFamily: PCCT_t.f.mono,
                      letterSpacing:'.04em',
                    }}>BARCODE OK</span>
                  )}
                </div>
                <div style={{ textAlign:'right', fontSize:12, fontFamily: PCCT_t.f.mono, color: PCCT_t.c.textMuted }}>
                  {c.qty || 1}
                </div>
                <div style={{ textAlign:'right' }}>
                  <AppMoney value={c.amount} size={12}/>
                </div>
                <div style={{ textAlign:'right' }}>
                  <AppMoney value={c.amount * (c.qty || 1)} strong size={13}/>
                  {overTariff && (
                    <div style={{ fontSize:9.5, color: PCCT_t.c.error, fontFamily: PCCT_t.f.mono, marginTop:2 }}>
                      over tariff +{PCCT_d.inr(c.amount - tariffRow.maxAmount)}
                    </div>
                  )}
                </div>
                <div style={{ display:'flex', justifyContent:'flex-end' }}>
                  {c.implantMissing && (
                    <button onClick={() => onUploadImplant(c.id)} style={{
                      border:'none', background:'transparent', cursor:'pointer',
                      color: PCCT_t.c.warning,
                    }}>
                      <AppIcon name="upload" size={14}/>
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
}

// ── Add Charge Modal ─────────────────────────────────────
function AddChargeModal({ open, onClose, claim }) {
  const store = useStore();
  const [form, setForm] = React.useState({
    date: new Date().toISOString().slice(0,10),
    category: 'ROOM_RENT',
    description: '',
    qty: 1,
    amount: 0,
    roomType: 'Private',
  });

  const setF = (patch) => setForm(f => ({ ...f, ...patch }));

  const handleAdd = () => {
    if (!form.description || !form.amount) return;
    store.addCharge(claim.id, {
      date: new Date(form.date).getTime(),
      category: form.category,
      description: form.description,
      qty: Number(form.qty),
      amount: Number(form.amount),
      source: 'manual',
      ...(form.category === 'ROOM_RENT' ? { roomType: form.roomType } : {}),
      ...(form.category === 'IMPLANT' ? { implantMissing: true } : {}),
    });
    store.toast({ icon: 'whatsapp', title: 'Charge added', body: form.description });
    setForm({ date: new Date().toISOString().slice(0,10), category:'ROOM_RENT', description:'', qty:1, amount:0, roomType:'Private' });
    onClose();
  };

  return (
    <AppModal
      open={open} onClose={onClose}
      title="Log a charge"
      subtitle={`${claim.id} · ${claim.patient.name}`}
      width={580}
      footer={
        <>
          <AppBtn kind="ghost" onClick={onClose}>Cancel</AppBtn>
          <AppBtn kind="primary" icon="plus" onClick={handleAdd}
            disabled={!form.description || !form.amount}>Add charge</AppBtn>
        </>
      }
    >
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
          <AppField label="Date">
            <AppInput type="date" value={form.date} onChange={v => setF({ date: v })}/>
          </AppField>
          <AppField label="Category" required>
            <AppSelect value={form.category} onChange={v => setF({ category: v })}
              options={PCCT_d.chargeCategories.map(c => ({ value: c.id, label: c.label }))}/>
          </AppField>
        </div>
        <AppField label="Description" required>
          <AppInput value={form.description} onChange={v => setF({ description: v })}
            placeholder="e.g. ICU room · day 1"/>
        </AppField>
        <div style={{ display:'grid', gridTemplateColumns:'80px 1fr', gap:12 }}>
          <AppField label="Qty">
            <AppInput type="number" value={form.qty} onChange={v => setF({ qty: v })} mono/>
          </AppField>
          <AppField label="Amount (₹)" required>
            <AppInput type="number" value={form.amount} onChange={v => setF({ amount: v })} mono/>
          </AppField>
        </div>
        {form.category === 'ROOM_RENT' && (
          <AppField label="Room type">
            <AppSelect value={form.roomType} onChange={v => setF({ roomType: v })}
              options={['General','Twin sharing','Private','Deluxe','ICU']}/>
          </AppField>
        )}
        {form.category === 'IMPLANT' && (
          <div style={{
            padding:'10px 12px',
            background: PCCT_t.c.warningTint, borderRadius:6,
            fontSize:11.5, color:'#92400E', lineHeight:1.55,
            display:'flex', gap:8,
          }}>
            <AppIcon name="info" size={14} color={PCCT_t.c.warning}/>
            <span>You'll need to upload the implant barcode sticker. Discharge submission is blocked until then.</span>
          </div>
        )}
      </div>
    </AppModal>
  );
}

// ── Room rent penalty calculator ─────────────────────────
function RoomRentCalculatorCard({ claim, onOpen }) {
  return (
    <AppCard>
      <AppSectionLabel>Room rent calculator</AppSectionLabel>
      <div style={{ marginTop:10, fontSize:12, color: PCCT_t.c.textMuted, lineHeight:1.5 }}>
        Estimate the proportional penalty if patient upgrades to a higher room category mid-stay.
      </div>
      <div style={{ marginTop:12 }}>
        <AppBtn full kind="ghost" icon="bed" iconRight="right" onClick={onOpen}>Open calculator</AppBtn>
      </div>
    </AppCard>
  );
}

function RoomRentCalcModal({ open, onClose, claim }) {
  const [eligible, setEligible] = React.useState(3000);
  const [actual,   setActual]   = React.useState(6500);
  const [docFee,   setDocFee]   = React.useState(2000);
  const [otFee,    setOtFee]    = React.useState(0);
  const [surgFee,  setSurgFee]  = React.useState(0);

  const ratio = eligible > 0 ? (actual - eligible) / eligible : 0;
  const docPenalty = Math.max(0, ratio * docFee);
  const otPenalty  = Math.max(0, ratio * otFee);
  const surgPenalty = Math.max(0, ratio * surgFee);
  const totalPenalty = docPenalty + otPenalty + surgPenalty;

  return (
    <AppModal
      open={open} onClose={onClose}
      title="Room rent penalty estimator"
      subtitle="Display only · does not modify billing"
      width={620}
      footer={<AppBtn kind="ghost" onClick={onClose}>Close</AppBtn>}
    >
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
          <AppField label="Approved room rent (eligible)">
            <AppInput type="number" value={eligible} onChange={v => setEligible(Number(v))} mono/>
          </AppField>
          <AppField label="Actual room rent (requested)">
            <AppInput type="number" value={actual} onChange={v => setActual(Number(v))} mono/>
          </AppField>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:12 }}>
          <AppField label="Doctor visit fee">
            <AppInput type="number" value={docFee} onChange={v => setDocFee(Number(v))} mono/>
          </AppField>
          <AppField label="OT charges">
            <AppInput type="number" value={otFee} onChange={v => setOtFee(Number(v))} mono/>
          </AppField>
          <AppField label="Surgeon fee">
            <AppInput type="number" value={surgFee} onChange={v => setSurgFee(Number(v))} mono/>
          </AppField>
        </div>

        <div style={{
          padding:'14px 16px',
          background: PCCT_t.c.warningTint, borderRadius:8,
        }}>
          <div style={{
            fontFamily: PCCT_t.f.mono, fontSize:10, fontWeight:600,
            letterSpacing:'.1em', textTransform:'uppercase',
            color: PCCT_t.c.warning, marginBottom:8,
          }}>Estimated patient out-of-pocket</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:8 }}>
            <div style={{ fontSize:13, color:'#92400E' }}>Doctor visit penalty</div><AppMoney value={docPenalty}/>
            <div style={{ fontSize:13, color:'#92400E' }}>OT penalty</div><AppMoney value={otPenalty}/>
            <div style={{ fontSize:13, color:'#92400E' }}>Surgeon penalty</div><AppMoney value={surgPenalty}/>
            <div style={{ fontSize:14, fontWeight:700, color:'#7C2D12', borderTop:`1px solid #FDBA74`, paddingTop:8 }}>Total</div>
            <div style={{ borderTop:`1px solid #FDBA74`, paddingTop:8, textAlign:'right' }}><AppMoney value={totalPenalty} strong size={15}/></div>
          </div>
          <div style={{ fontSize:11, color:'#92400E', marginTop:8, fontFamily: PCCT_t.f.mono }}>
            Penalty ratio: {(ratio * 100).toFixed(1)}%
          </div>
        </div>

        <div style={{ fontSize:11, color: PCCT_t.c.textMuted, lineHeight:1.55, fontStyle:'italic' }}>
          Formula: <span style={{ fontFamily: PCCT_t.f.mono }}>(actual − eligible) / eligible × procedure fee</span>.
          Standard IRDAI calculation used by most Indian TPAs.
        </div>
      </div>
    </AppModal>
  );
}

// ── Implant Barcode Upload Modal ─────────────────────────
function ImplantBarcodeModal({ open, onClose, claim, chargeId }) {
  const store = useStore();
  const charge = (claim.charges || []).find(c => c.id === chargeId);

  if (!open || !charge) return null;

  const handlePicked = (payload) => {
    const demo = payload.demoDoc || { brand:'Zimmer Biomet', batch:'ZB-2026-04-1812', serial:'SN-9087421' };
    store.attachImplantBarcode(claim.id, chargeId, demo);
    store.addDocument(claim.id, 'IMPLANT_BARCODE');
    store.toast({ icon:'whatsapp', title:'Implant barcode attached', body: `OCR extracted: ${demo.brand} · batch ${demo.batch}` });
    onClose();
  };

  return (
    <AppModal
      open={open} onClose={onClose}
      title="Upload implant barcode"
      subtitle={charge.description}
      width={560}
      footer={<AppBtn kind="ghost" onClick={onClose}>Cancel</AppBtn>}
    >
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <div style={{
          padding:'10px 12px', background: PCCT_t.c.accentTint, borderRadius:7,
          fontSize:11.5, color:'#075985', lineHeight:1.55,
          display:'flex', gap:8, alignItems:'flex-start',
        }}>
          <AppIcon name="info" size={14} color={PCCT_t.c.accent}/>
          <span>Photograph the physical manufacturer barcode sticker. OCR will extract brand, batch, and serial number.</span>
        </div>
        <UploadZone
          docType="IMPLANT_BARCODE"
          label="Implant barcode sticker"
          required
          onUpload={handlePicked}
        />
        <UploadZone
          docType="IMPLANT_INVOICE"
          label="Implant tax invoice (optional)"
          onUpload={(p) => {
            store.addDocument(claim.id, 'IMPLANT_INVOICE');
            store.toast({ icon:'whatsapp', title:'Implant invoice attached' });
          }}
        />
      </div>
    </AppModal>
  );
}

// ── Daily audit ──────────────────────────────────────────
function DailyAuditCard({ claim }) {
  const charges = claim.charges || [];
  const total = charges.reduce((s, c) => s + c.amount * (c.qty || 1), 0);
  const cap = claim.approvedAmount || claim.estimatedCost;
  const over = total > cap;
  return (
    <AppCard>
      <AppSectionLabel>Daily audit</AppSectionLabel>
      <div style={{ marginTop:12 }}>
        <AuditRow label="Days admitted" value={`${Math.max(1, Math.floor((Date.now() - claim.admittedAt) / 86400000))} days`} ok/>
        <AuditRow label="Charges logged" value={`${charges.length} entries`} ok/>
        <AuditRow label="Implant docs"
          value={charges.some(c => c.category === 'IMPLANT') ? (charges.some(c => c.implantMissing) ? 'Barcode pending' : 'Reconciled') : 'N/A'}
          ok={!charges.some(c => c.implantMissing)}/>
        <AuditRow label="vs. approved cap"
          value={cap > 0 ? `${Math.round((total/cap)*100)}% used` : 'No cap'}
          ok={!over} warn={over}/>
      </div>
    </AppCard>
  );
}

function AuditRow({ label, value, ok, warn }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'8px 0', borderBottom: `1px solid ${PCCT_t.c.border}`,
      fontSize:12.5,
    }}>
      <span style={{ color: PCCT_t.c.textMuted, display:'flex', alignItems:'center', gap:7 }}>
        <AppIcon name={ok ? 'check' : warn ? 'alert' : 'info'} size={12}
                 color={ok ? PCCT_t.c.success : warn ? PCCT_t.c.warning : PCCT_t.c.textDim}/>
        {label}
      </span>
      <span style={{ fontWeight:500, color: PCCT_t.c.text, fontFamily: PCCT_t.f.mono }}>{value}</span>
    </div>
  );
}

function ProcedureGuidanceCard({ claim, insurer }) {
  // Surface procedure-specific document requirements (from TPA reference doc)
  const guidance = {
    'I21.0': ['Coronary angiography report (CAG)', 'Stent invoice + barcode (NPPA price check)', 'Distributor tax invoice'],
    'I21.9': ['ECG + Troponin trend', 'Cath-lab report', 'Stent details if PCI done'],
    'S72.0': ['Pre-op X-ray with markers', 'Post-op X-ray', 'Implant invoice + barcode'],
    'K35.80':['Histopathology of appendix (post-op)', 'OT notes'],
    'O82':   ['Antenatal USG + films', 'GPLA history', 'Newborn details if covered'],
    'O80':   ['Antenatal records', 'GPLA history'],
    'J18.9': ['CXR + report', 'Sputum culture if available'],
  }[claim.icd];

  if (!guidance) return null;
  return (
    <AppCard>
      <AppSectionLabel>Procedure-specific docs</AppSectionLabel>
      <div style={{ fontSize:11.5, color: PCCT_t.c.textMuted, marginTop:4, lineHeight:1.5 }}>
        Additional docs typically required by {insurer.name} for <strong style={{ color: PCCT_t.c.text, fontFamily: PCCT_t.f.mono }}>{claim.icd}</strong>:
      </div>
      <ul style={{ paddingLeft:16, marginTop:10, marginBottom:0, fontSize:12, color: PCCT_t.c.text, lineHeight:1.7 }}>
        {guidance.map((g, i) => <li key={i}>{g}</li>)}
      </ul>
    </AppCard>
  );
}

function syncAgo(ts) {
  if (!ts) return 'never';
  const m = Math.floor((Date.now() - ts) / 60000);
  if (m < 1) return 'just now';
  if (m < 60) return m + 'm ago';
  if (m < 24*60) return Math.floor(m/60) + 'h ago';
  return Math.floor(m / 60 / 24) + 'd ago';
}

Object.assign(window, { ChargesTab });
