// screen-cfo.jsx — CFO / Admin RCM dashboard (R19) in the app shell.
// Hero metric: revenue leakage. Computed live from the store's claims.

const PCC_t = window.PCT;
const PCC_d = window.PCA;

function CFOScreen() {
  const store = useStore();
  const claims = store.state.claims;
  const mode = store.state.mode;

  // ── Live KPI calculations ────────────────────────────
  const totals = React.useMemo(() => {
    const billed = claims.reduce((s, c) => s + (c.estimatedCost || 0), 0);
    const collected = claims.filter(c => c.status === 'SETTLED').reduce((s, c) => s + (c.finalSettled || c.approvedAmount || 0), 0);
    const inAr = claims.filter(c => ['CLAIM_SUBMITTED','CLAIM_QUERY','PREAUTH_PARTIAL','PREAUTH_APPROVED','ACTIVE_STAY','CLAIM_READY'].includes(c.status))
                       .reduce((s, c) => s + (c.approvedAmount || c.estimatedCost || 0), 0);

    // Leakage = idle claims > 48h that need action + SLA breaches + missing items
    const now = Date.now();
    const idle48 = claims.filter(c =>
      ['PREAUTH_QUERY','CLAIM_QUERY'].includes(c.status) &&
      c.queries && c.queries.some(q => q.status === 'OPEN' && (now - q.raisedAt) > 48 * 3600 * 1000)
    );
    const slaBreach = claims.filter(c => c.slaDeadlineAt && c.slaDeadlineAt < now && c.status === 'PREAUTH_SUBMITTED');
    const implantMissing = claims.filter(c => (c.charges || []).some(ch => ch.implantMissing));
    const leakage = [...idle48, ...slaBreach, ...implantMissing].reduce((s, c) => s + (c.approvedAmount || c.estimatedCost || 0) * 0.15, 0);

    const approved = claims.filter(c => c.approvedAmount != null && c.approvedAmount > 0).length;
    const responded = claims.filter(c => c.approvedAmount != null).length;
    const approvalRate = responded > 0 ? (approved / responded) * 100 : 0;
    const denied = claims.filter(c => ['PREAUTH_DENIED','DENIED'].includes(c.status)).length;
    const denialRate = responded > 0 ? (denied / responded) * 100 : 0;

    const cashless = claims.filter(c => c.claimType === 'CASHLESS').length;
    const reimb = claims.filter(c => c.claimType === 'REIMBURSEMENT').length;

    return {
      billed, collected, inAr, leakage,
      approvalRate, denialRate,
      cashlessSplit: cashless ? Math.round(cashless * 100 / (cashless + reimb)) : 0,
      reimbursementSplit: reimb ? Math.round(reimb * 100 / (cashless + reimb)) : 0,
      idleClaims: idle48,
      slaBreaches: slaBreach,
      implantMissing,
    };
  }, [claims]);

  // ── Aging by claim age ───────────────────────────────
  const aging = React.useMemo(() => {
    const buckets = [
      { label:'0–30',  min:0,   max:30,  amount:0, count:0 },
      { label:'31–60', min:31,  max:60,  amount:0, count:0 },
      { label:'61–90', min:61,  max:90,  amount:0, count:0 },
      { label:'90+',   min:91,  max:9999,amount:0, count:0 },
    ];
    const now = Date.now();
    claims.filter(c => !['SETTLED','CLOSED'].includes(c.status)).forEach(c => {
      const days = Math.floor((now - c.admittedAt) / (24*3600*1000));
      const b = buckets.find(x => days >= x.min && days <= x.max);
      if (b) {
        b.amount += c.approvedAmount || c.estimatedCost || 0;
        b.count += 1;
      }
    });
    return buckets;
  }, [claims]);

  // ── Payer scorecard ──────────────────────────────────
  const payerScores = React.useMemo(() => {
    return PCC_d.insurers.map(ins => {
      const own = claims.filter(c => c.insurer === ins.id);
      const billed = own.reduce((s, c) => s + (c.estimatedCost || 0), 0);
      const settled = own.filter(c => c.status === 'SETTLED');
      const collected = settled.reduce((s, c) => s + (c.finalSettled || c.approvedAmount || 0), 0);
      const responded = own.filter(c => c.approvedAmount != null);
      const approved = responded.filter(c => c.approvedAmount > 0);
      const approvalRate = responded.length > 0 ? Math.round(approved.length * 100 / responded.length) : 0;
      const daysToSettle = settled.length > 0
        ? Math.round(settled.reduce((s, c) => s + (c.settledAt - c.admittedAt) / (24*3600*1000), 0) / settled.length)
        : 0;
      const sla = own.filter(c => c.slaDeadlineAt && c.slaDeadlineAt > 0);
      const slaPass = sla.length === 0 ? 100 :
        Math.round(sla.filter(c => c.slaDeadlineAt > c.preauthSubmittedAt + 60 * 60 * 1000).length * 100 / Math.max(sla.length, 1));
      return { insurer: ins, billed, collected, approvalRate, daysToSettle, sla: 100 - Math.min(slaPass, 20), claimCount: own.length };
    }).filter(p => p.claimCount > 0).sort((a, b) => b.billed - a.billed);
  }, [claims]);

  return (
    <Shell
      active="cfo"
      breadcrumb={[mode === 'standalone' ? 'Reports' : 'Dashboard', 'Revenue cycle insights']}
      headerRight={
        <div style={{ display:'flex', gap:8 }}>
          <DateRangeButton/>
          <AppBtn icon="download">Export</AppBtn>
        </div>
      }
    >
      <div style={{ padding:'24px 24px 80px', display:'flex', flexDirection:'column', gap:18 }}>
        <HeroStrip d={totals}/>

        <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap:14 }}>
          <CashFlowCard d={totals}/>
          <AgingCard aging={aging}/>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:14 }}>
          <PayerScorecard scores={payerScores}/>
          <LeakageReasonsCard d={totals}/>
        </div>

        <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:14 }}>
          <OpsMetric label="Approval rate"   value={totals.approvalRate.toFixed(0) + '%'}     tone="success"/>
          <OpsMetric label="Denial rate"     value={totals.denialRate.toFixed(0) + '%'}       tone={totals.denialRate > 10 ? 'warning' : 'success'}/>
          <OpsMetric label="Cashless split"  value={totals.cashlessSplit + '%'}/>
          <OpsMetric label="SLA breaches"    value={totals.slaBreaches.length} tone={totals.slaBreaches.length > 0 ? 'error' : 'success'}/>
        </div>
      </div>
    </Shell>
  );
}

function DateRangeButton() {
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:8,
      height:34, padding:'0 12px',
      background: PCC_t.c.surface, border: `1px solid ${PCC_t.c.border}`,
      borderRadius:7, fontSize:12.5, color: PCC_t.c.text, fontWeight:500,
    }}>
      <AppIcon name="clock" size={13} color={PCC_t.c.textMuted}/>
      <span>May 2026 · MTD</span>
      <AppIcon name="down" size={12} color={PCC_t.c.textMuted}/>
    </div>
  );
}

function HeroStrip({ d }) {
  return (
    <div data-demo="clm-money" style={{
      background: PCC_t.c.surface, border: `1px solid ${PCC_t.c.border}`, borderRadius:12,
      overflow:'hidden',
      display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr 1fr',
    }}>
      <div style={{
        padding:'24px 26px',
        background: 'linear-gradient(135deg, #FFFBEB 0%, #FFF7E6 100%)',
        borderRight: `1px solid ${PCC_t.c.border}`,
      }}>
        <div style={{
          fontFamily: PCC_t.f.mono, fontSize:10, fontWeight:700,
          letterSpacing:'.12em', textTransform:'uppercase',
          color: PCC_t.c.warning, display:'flex', alignItems:'center', gap:6,
        }}>
          <AppIcon name="alert" size={11} color={PCC_t.c.warning}/>
          Revenue leakage · MTD
        </div>
        <div style={{
          marginTop:8, fontFamily: PCC_t.f.mono, fontSize:38, fontWeight:600,
          color: PCC_t.c.warning, letterSpacing:'-.02em', lineHeight:1,
          fontVariantNumeric:'tabular-nums',
        }}>{PCC_d.inr(d.leakage)}</div>
        <div style={{ marginTop:10, fontSize:12, color:'#78350F', lineHeight:1.55, maxWidth:320 }}>
          Recoverable money sitting idle <strong>&gt; 48 hours</strong> in claims that need an action.
          <span style={{ color:'#92400E', fontWeight:500 }}> Click a reason on the right to open the worklist.</span>
        </div>
      </div>
      <HeroNum label="Billed"    value={d.billed}/>
      <HeroNum label="Collected" value={d.collected} tone="success" sub={d.billed > 0 ? `${Math.round(d.collected/d.billed*100)}% of billed` : ''}/>
      <HeroNum label="In AR"     value={d.inAr} sub={d.billed > 0 ? `${Math.round(d.inAr/d.billed*100)}% of billed` : ''}/>
    </div>
  );
}

function HeroNum({ label, value, tone, sub }) {
  const c = { success: PCC_t.c.success, warning: PCC_t.c.warning, error: PCC_t.c.error }[tone] || PCC_t.c.text;
  return (
    <div style={{ padding:'24px 22px', borderRight: `1px solid ${PCC_t.c.border}`, display:'flex', flexDirection:'column', gap:6 }}>
      <div style={{
        fontFamily: PCC_t.f.mono, fontSize:10, fontWeight:600,
        letterSpacing:'.1em', textTransform:'uppercase', color: PCC_t.c.textMuted,
      }}>{label}</div>
      <div style={{
        fontFamily: PCC_t.f.mono, fontSize:28, fontWeight:600,
        color: c, letterSpacing:'-.02em', lineHeight:1, fontVariantNumeric:'tabular-nums',
      }}>{PCC_d.inr(value)}</div>
      {sub && <div style={{ fontSize:11, color: PCC_t.c.textMuted, marginTop:4 }}>{sub}</div>}
    </div>
  );
}

function CashFlowCard({ d }) {
  // Daily series
  const days = 26;
  const series = Array.from({ length: days }, (_, i) => {
    const billed = 480000 + Math.sin(i * 0.7) * 120000 + (i > 18 ? 80000 : 0);
    const collected = billed * (0.55 + Math.sin(i * 0.4 + 2) * 0.15);
    return { day: i + 1, billed, collected };
  });
  const maxV = Math.max(...series.map(s => s.billed));

  return (
    <AppCard>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <div>
          <AppSectionLabel>Billed vs collected · daily</AppSectionLabel>
          <div style={{ fontSize:12.5, color: PCC_t.c.textMuted, marginTop:5 }}>
            <span style={{ display:'inline-flex', alignItems:'center', gap:5, marginRight:14 }}>
              <span style={{ width:8, height:8, borderRadius:2, background: PCC_t.c.accent }}/> Billed
            </span>
            <span style={{ display:'inline-flex', alignItems:'center', gap:5 }}>
              <span style={{ width:8, height:8, borderRadius:2, background: PCC_t.c.success }}/> Collected
            </span>
          </div>
        </div>
        <div style={{ fontSize:11, color: PCC_t.c.textDim, fontFamily: PCC_t.f.mono }}>1 → 26 May</div>
      </div>
      <div style={{ marginTop:18, display:'flex', alignItems:'flex-end', gap:3, height:140 }}>
        {series.map(s => (
          <div key={s.day} style={{ flex:1, display:'flex', flexDirection:'column', gap:2, justifyContent:'flex-end' }}>
            <div style={{ height: `${(s.billed / maxV) * 100}%`, background: PCC_t.c.accent, borderRadius:'2px 2px 0 0', opacity:.85 }}/>
            <div style={{ height: `${(s.collected / maxV) * 70}%`, background: PCC_t.c.success, borderRadius:'2px 2px 0 0' }}/>
          </div>
        ))}
      </div>
      <div style={{ display:'flex', justifyContent:'space-between', marginTop:8, fontSize:10, color: PCC_t.c.textDim, fontFamily: PCC_t.f.mono }}>
        <span>1</span><span>7</span><span>14</span><span>21</span><span>26</span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', marginTop:18, paddingTop:14, borderTop: `1px solid ${PCC_t.c.border}` }}>
        <Mini label="Cashless"      value={d.cashlessSplit + '%'}      sub="of total claims"/>
        <Mini label="Reimbursement" value={d.reimbursementSplit + '%'} sub="of total claims"/>
        <Mini label="Avg days admit→submit" value="4.8d" sub="−0.6 vs Apr"/>
      </div>
    </AppCard>
  );
}

function Mini({ label, value, sub }) {
  return (
    <div style={{ paddingRight:14 }}>
      <div style={{ fontFamily: PCC_t.f.mono, fontSize:9.5, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color: PCC_t.c.textMuted }}>{label}</div>
      <div style={{ fontFamily: PCC_t.f.mono, fontSize:18, fontWeight:600, color: PCC_t.c.text, marginTop:4, fontVariantNumeric:'tabular-nums' }}>{value}</div>
      <div style={{ fontSize:11, color: PCC_t.c.textDim, marginTop:2 }}>{sub}</div>
    </div>
  );
}

function AgingCard({ aging }) {
  const total = aging.reduce((s, b) => s + b.amount, 0);
  const tones = [PCC_t.c.success, PCC_t.c.accent, PCC_t.c.warning, PCC_t.c.error];
  return (
    <AppCard>
      <AppSectionLabel>AR aging buckets</AppSectionLabel>
      <div style={{ display:'flex', height:10, borderRadius:5, overflow:'hidden', marginTop:14, background: PCC_t.c.surface2 }}>
        {aging.map((b, i) => total > 0 && (
          <div key={b.label} style={{ flex: b.amount / total, background: tones[i] }}/>
        ))}
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:1, marginTop:14 }}>
        {aging.map((b, i) => (
          <div key={b.label} style={{
            display:'grid', gridTemplateColumns:'74px 1fr 90px 50px',
            alignItems:'center', gap:10, padding:'8px 0',
            borderBottom: i < aging.length - 1 ? `1px solid ${PCC_t.c.border}` : 'none',
          }}>
            <div style={{ display:'flex', alignItems:'center', gap:7 }}>
              <span style={{ width:7, height:7, borderRadius:2, background: tones[i] }}/>
              <span style={{ fontFamily: PCC_t.f.mono, fontSize:11.5, fontWeight:500 }}>{b.label} d</span>
            </div>
            <div style={{ height:4, borderRadius:2, background: PCC_t.c.surface2, position:'relative', overflow:'hidden' }}>
              <div style={{ position:'absolute', inset:0, width: total > 0 ? `${(b.amount/total)*100}%` : '0%', background: tones[i], opacity:.65 }}/>
            </div>
            <AppMoney value={b.amount} size={12}/>
            <span style={{ fontFamily: PCC_t.f.mono, fontSize:11, color: PCC_t.c.textMuted, textAlign:'right' }}>{b.count} clm</span>
          </div>
        ))}
      </div>
    </AppCard>
  );
}

function PayerScorecard({ scores }) {
  return (
    <AppCard pad={0}>
      <div style={{ padding:'18px 20px 14px', borderBottom:`1px solid ${PCC_t.c.border}` }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
          <AppSectionLabel>Payer scorecard</AppSectionLabel>
          <div style={{ fontSize:11, color: PCC_t.c.textDim, fontFamily: PCC_t.f.mono }}>Sorted by billed value</div>
        </div>
      </div>
      <div style={{
        display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr 100px 90px',
        gap:14, padding:'10px 20px',
        fontFamily: PCC_t.f.mono, fontSize:10, fontWeight:600,
        letterSpacing:'.06em', textTransform:'uppercase', color: PCC_t.c.textMuted,
        borderBottom: `1px solid ${PCC_t.c.border}`,
      }}>
        <div>Payer</div>
        <div style={{ textAlign:'right' }}>Billed</div>
        <div style={{ textAlign:'right' }}>Collected</div>
        <div style={{ textAlign:'right' }}>Approval</div>
        <div style={{ textAlign:'right' }}>Claims</div>
      </div>
      {scores.length === 0 && (
        <AppEmpty icon="claims" title="No claims yet" body="Once claims accumulate, payer-level metrics show up here."/>
      )}
      {scores.map((row, i) => (
        <div key={row.insurer.id} style={{
          display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr 100px 90px',
          gap:14, padding:'12px 20px', alignItems:'center',
          borderBottom: i < scores.length - 1 ? `1px solid ${PCC_t.c.border}` : 'none',
        }}>
          <AppPayerChip insurerId={row.insurer.id} size={26}/>
          <div style={{ textAlign:'right' }}><AppMoney value={row.billed} strong/></div>
          <div style={{ textAlign:'right' }}>
            <AppMoney value={row.collected}/>
            {row.billed > 0 && <div style={{ fontSize:10, color: PCC_t.c.textDim, marginTop:1, fontFamily: PCC_t.f.mono }}>{Math.round(row.collected/row.billed*100)}%</div>}
          </div>
          <BarCell value={row.approvalRate} good={row.approvalRate >= 88} bad={row.approvalRate < 80}/>
          <div style={{ textAlign:'right', fontFamily: PCC_t.f.mono, fontSize:12.5 }}>{row.claimCount}</div>
        </div>
      ))}
    </AppCard>
  );
}

function BarCell({ value, good, bad }) {
  const tone = good ? PCC_t.c.success : bad ? PCC_t.c.error : PCC_t.c.warning;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:4, alignItems:'flex-end' }}>
      <div style={{ fontFamily: PCC_t.f.mono, fontSize:12.5, fontWeight:600, color: tone }}>{value}%</div>
      <div style={{ width:60, height:3, borderRadius:2, background: PCC_t.c.surface2, position:'relative', overflow:'hidden' }}>
        <div style={{ position:'absolute', inset:0, width: value + '%', background: tone }}/>
      </div>
    </div>
  );
}

function LeakageReasonsCard({ d }) {
  const reasons = [
    { reason:'Idle > 48h after query',       count: d.idleClaims.length,   amount: d.idleClaims.reduce((s, c) => s + (c.approvedAmount || c.estimatedCost || 0) * 0.2, 0) },
    { reason:'Pre-auth SLA breached',         count: d.slaBreaches.length,  amount: d.slaBreaches.reduce((s, c) => s + (c.estimatedCost || 0) * 0.1, 0) },
    { reason:'Missing implant barcode',       count: d.implantMissing.length, amount: d.implantMissing.reduce((s, c) => s + (c.approvedAmount || c.estimatedCost || 0) * 0.15, 0) },
    { reason:'Tariff overage acknowledged',   count: 6,  amount: 98000 },
    { reason:'Discharge summary incomplete',  count: 2,  amount: 84000 },
  ].filter(r => r.count > 0 || r.amount > 0);

  return (
    <AppCard>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <AppSectionLabel>Leakage by reason</AppSectionLabel>
        <span style={{ fontSize:11, color: PCC_t.c.textDim, fontFamily: PCC_t.f.mono }}>{reasons.length} reasons</span>
      </div>
      <div style={{ marginTop:14 }}>
        {reasons.map((r, i) => (
          <div key={r.reason} style={{
            display:'grid', gridTemplateColumns:'1fr 88px',
            gap:14, padding:'12px 0', alignItems:'center',
            borderBottom: i < reasons.length - 1 ? `1px solid ${PCC_t.c.border}` : 'none',
          }}>
            <div>
              <div style={{ fontSize:12.5, fontWeight:500 }}>{r.reason}</div>
              <div style={{ fontSize:10.5, color: PCC_t.c.textDim, fontFamily: PCC_t.f.mono, marginTop:2 }}>
                {r.count} claim{r.count !== 1 ? 's' : ''}
              </div>
            </div>
            <div style={{ textAlign:'right' }}><AppMoney value={r.amount} strong size={13}/></div>
          </div>
        ))}
      </div>
      <a href="#/" style={{ textDecoration:'none' }}>
        <AppBtn full kind="ghost" size="sm" icon="right">Open worklist</AppBtn>
      </a>
    </AppCard>
  );
}

function OpsMetric({ label, value, tone }) {
  const c = { success: PCC_t.c.success, warning: PCC_t.c.warning, error: PCC_t.c.error }[tone] || PCC_t.c.text;
  return (
    <AppCard>
      <div style={{
        fontFamily: PCC_t.f.mono, fontSize:10, fontWeight:600,
        letterSpacing:'.1em', textTransform:'uppercase', color: PCC_t.c.textMuted,
      }}>{label}</div>
      <div style={{
        fontFamily: PCC_t.f.mono, fontSize:26, fontWeight:600,
        color: c, marginTop:8, lineHeight:1, letterSpacing:'-.01em',
      }}>{value}</div>
    </AppCard>
  );
}

Object.assign(window, { CFOScreen });
