// tab-dossier.jsx — F7 Self-pay conversion + Reimbursement dossier + Reminders
// Two modes within one tab:
//   - If pre-auth denied → Self-pay conversion engine
//   - If patient paid out-of-pocket → Reimbursement dossier assembler

const PCDS_t = window.PCT;
const PCDS_d = window.PCA;

function DossierTab({ claim, insurer }) {
  const store = useStore();
  const isDenied = ['PREAUTH_DENIED','DENIED'].includes(claim.status);
  const isReimbursement = claim.claimType === 'REIMBURSEMENT';

  // Tabs within dossier
  const [section, setSection] = React.useState(isDenied ? 'self-pay' : isReimbursement ? 'dossier' : 'self-pay');

  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:14 }}>
      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        {/* Section switcher */}
        <div style={{
          display:'flex', gap:2, padding:4,
          background: PCDS_t.c.surface2,
          borderRadius:8, width:'fit-content',
        }}>
          {[
            { id:'self-pay', label:'Self-pay conversion', icon:'money' },
            { id:'dossier',  label:'Reimbursement dossier', icon:'docs' },
            { id:'reminders',label:'Post-discharge reminders', icon:'bell' },
          ].map(s => (
            <button key={s.id} onClick={() => setSection(s.id)} style={{
              display:'flex', alignItems:'center', gap:7,
              padding:'8px 14px', borderRadius:6,
              background: section === s.id ? '#fff' : 'transparent',
              color: section === s.id ? PCDS_t.c.text : PCDS_t.c.textMuted,
              border:'none', cursor:'pointer',
              fontSize:12.5, fontWeight: section === s.id ? 600 : 500,
              boxShadow: section === s.id ? '0 1px 2px rgba(0,0,0,.06)' : 'none',
              fontFamily: PCDS_t.f.sans,
            }}>
              <AppIcon name={s.icon} size={13}/>
              {s.label}
            </button>
          ))}
        </div>

        {section === 'self-pay'  && <SelfPaySection claim={claim} insurer={insurer}/>}
        {section === 'dossier'   && <DossierSection claim={claim} insurer={insurer}/>}
        {section === 'reminders' && <RemindersSection claim={claim} insurer={insurer}/>}
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
        <DossierSidebar claim={claim} insurer={insurer}/>
      </div>
    </div>
  );
}

// ── Self-Pay Conversion ──────────────────────────────────
function SelfPaySection({ claim, insurer }) {
  const store = useStore();
  const isDenied = ['PREAUTH_DENIED','DENIED'].includes(claim.status);
  const totalCharges = (claim.charges || []).reduce((s, c) => s + c.amount * (c.qty || 1), 0);
  const approved = claim.approvedAmount || 0;
  const deposit = claim.depositCollected || 0;
  const base = totalCharges > 0 ? totalCharges : claim.estimatedCost;
  const netDue = Math.max(0, base - approved - deposit);

  const [converted, setConverted] = React.useState(claim.status === 'SELF_PAY');

  const handleConvert = () => {
    store.updateClaim(claim.id, {
      status: 'SELF_PAY',
      patientShare: netDue,
      flags: [...(claim.flags || []).filter(f => f !== 'denied'), 'self-pay-conv'],
    });
    store.toast({ icon:'whatsapp', title:'Converted to self-pay', body:`Net due ${PCDS_d.inr(netDue)} · billing desk notified` });
    setConverted(true);
  };

  return (
    <AppCard>
      <AppSectionLabel>Self-pay conversion</AppSectionLabel>

      {!isDenied && !converted && (
        <div style={{
          marginTop:14, padding:'14px 16px',
          background: PCDS_t.c.accentTint, borderRadius:7,
          fontSize:12.5, color:'#075985', lineHeight:1.55,
          display:'flex', gap:10, alignItems:'flex-start',
        }}>
          <AppIcon name="info" size={14} color={PCDS_t.c.accent}/>
          <span>
            Self-pay conversion is typically triggered when pre-auth is denied or partially approved.
            This claim's pre-auth is currently <strong>{PCDS_d.statusMeta[claim.status]?.label || claim.status}</strong>.
            You can still calculate the patient share for reference.
          </span>
        </div>
      )}

      {converted && (
        <div style={{
          marginTop:14, padding:'14px 16px',
          background: PCDS_t.c.successTint, borderRadius:7,
          fontSize:12.5, color:'#14532D', lineHeight:1.55,
          display:'flex', gap:10, alignItems:'flex-start',
        }}>
          <AppIcon name="check" size={14} color={PCDS_t.c.success}/>
          <span><strong>Converted.</strong> Billing desk has been notified · {claim.id} marked as self-pay in HMS.</span>
        </div>
      )}

      {/* Calculation breakdown */}
      <div style={{
        marginTop:14, padding:18,
        background: PCDS_t.c.surface2, borderRadius:8,
      }}>
        <div style={{
          fontFamily: PCDS_t.f.mono, fontSize:9.5, fontWeight:600,
          letterSpacing:'.1em', textTransform:'uppercase', color: PCDS_t.c.textMuted,
          marginBottom:14,
        }}>Patient bill calculation</div>

        <SelfPayRow label="Total charges accumulated" value={base} sub={`${(claim.charges || []).length} entries · including all services to date`}/>
        <SelfPayRow label="Less: approved cashless" value={-approved} sub={approved > 0 ? `Cashless portion from ${insurer.name}` : 'No approval'} muted={approved === 0}/>
        <SelfPayRow label="Less: deposit collected" value={-deposit} sub={deposit > 0 ? 'Already paid by patient at admission' : 'No deposit'} muted={deposit === 0}/>
        <div style={{
          marginTop:14, paddingTop:14,
          borderTop: `2px solid ${PCDS_t.c.text}`,
          display:'flex', justifyContent:'space-between', alignItems:'baseline',
        }}>
          <div>
            <div style={{ fontSize:14, fontWeight:700, color: PCDS_t.c.text }}>Net amount due from patient</div>
            <div style={{ fontSize:11, color: PCDS_t.c.textMuted, marginTop:3 }}>
              Show this at the billing counter · {insurer.claimType === 'REIMBURSEMENT' ? 'patient can claim reimbursement later' : 'patient pays direct'}
            </div>
          </div>
          <span style={{
            fontFamily: PCDS_t.f.mono, fontSize:26, fontWeight:600,
            color: netDue > 0 ? PCDS_t.c.text : PCDS_t.c.success,
            letterSpacing:'-.02em', fontVariantNumeric:'tabular-nums',
          }}>{PCDS_d.inr(netDue)}</span>
        </div>
      </div>

      <div style={{ marginTop:14, display:'flex', gap:8 }}>
        {!converted ? (
          <AppBtn kind="primary" icon="check" onClick={handleConvert}>
            Convert &amp; notify billing desk
          </AppBtn>
        ) : (
          <AppBtn kind="ghost" icon="download">Download self-pay summary PDF</AppBtn>
        )}
        <AppBtn kind="ghost" icon="phone">Call patient</AppBtn>
        <AppBtn kind="ghost" icon="send">WhatsApp the breakdown</AppBtn>
      </div>

      {converted && (
        <div style={{
          marginTop:14, padding:'10px 12px',
          background: PCDS_t.c.brandSoft, borderRadius:6,
          fontSize:11.5, color:'#4C1D95', lineHeight:1.55,
          display:'flex', gap:8,
        }}>
          <AppIcon name="info" size={14} color={PCDS_t.c.brand}/>
          <span><strong>Next step:</strong> If patient pays cash now, they can still claim reimbursement from {insurer.name} later — use the <strong>Reimbursement dossier</strong> tab to assemble the package.</span>
        </div>
      )}
    </AppCard>
  );
}

function SelfPayRow({ label, value, sub, muted }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'baseline',
      padding:'8px 0',
      borderBottom: `1px solid ${PCDS_t.c.border}`,
      opacity: muted ? 0.55 : 1,
    }}>
      <div>
        <div style={{ fontSize:13, color: PCDS_t.c.text, fontWeight:500 }}>{label}</div>
        {sub && <div style={{ fontSize:11, color: PCDS_t.c.textMuted, marginTop:2 }}>{sub}</div>}
      </div>
      <AppMoney value={Math.abs(value)} strong neg={value < 0}/>
    </div>
  );
}

// ── Reimbursement Dossier ────────────────────────────────
function DossierSection({ claim, insurer }) {
  const store = useStore();
  const checklist = insurer.reimbursementChecklist;
  const uploaded = claim.documents || [];

  const present = checklist.filter(c => uploaded.includes(c.docType));
  const missing = checklist.filter(c => c.required && !uploaded.includes(c.docType));

  return (
    <>
      <AppCard>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
          <div>
            <AppSectionLabel>Reimbursement dossier · {insurer.name}</AppSectionLabel>
            <div style={{ fontSize:15, fontWeight:600, marginTop:8 }}>
              {missing.length === 0
                ? <span style={{ color: PCDS_t.c.success }}>All documents collected — ready to package</span>
                : `${present.length} of ${checklist.length} documents collected`}
            </div>
            <div style={{ fontSize:12.5, color: PCDS_t.c.textMuted, marginTop:4, lineHeight:1.55 }}>
              {insurer.name} accepts {claim.claimType === 'REIMBURSEMENT' ? 'physical originals' : 'digital scans'}.
              The dossier PDF includes a cover index in the TPA's required sequence.
            </div>
          </div>
          <ProgressRingDossier value={present.length} total={checklist.length}/>
        </div>

        {insurer.sequenceNote && (
          <div style={{
            marginTop:14, padding:'10px 12px',
            background: PCDS_t.c.accentTint, borderRadius:6,
            fontSize:11.5, color:'#075985', lineHeight:1.55,
            display:'flex', gap:8, alignItems:'flex-start',
          }}>
            <AppIcon name="info" size={13} color={PCDS_t.c.accent}/>
            <span><strong>Sequence:</strong> {insurer.sequenceNote}</span>
          </div>
        )}
      </AppCard>

      {/* Checklist */}
      <AppCard pad={0}>
        <div style={{ padding:'14px 18px', borderBottom: `1px solid ${PCDS_t.c.border}` }}>
          <AppSectionLabel>Document checklist · in submission sequence</AppSectionLabel>
        </div>
        <div style={{ padding:14 }}>
          {checklist.map((item, i) => {
            const isUp = uploaded.includes(item.docType);
            return (
              <div key={item.docType} style={{
                display:'grid', gridTemplateColumns:'28px 1fr 1fr 100px',
                gap:12, padding:'10px 0', alignItems:'center',
                borderBottom: i < checklist.length - 1 ? `1px solid ${PCDS_t.c.border}` : 'none',
              }}>
                <div style={{
                  width:24, height:24, borderRadius:6,
                  background: isUp ? PCDS_t.c.success : PCDS_t.c.surface2,
                  color: isUp ? '#fff' : PCDS_t.c.textDim,
                  display:'grid', placeItems:'center',
                  fontFamily: PCDS_t.f.mono, fontSize:11, fontWeight:700,
                }}>
                  {isUp ? <AppIcon name="check" size={12} color="#fff" stroke={2.8}/> : (i + 1)}
                </div>
                <div style={{ fontSize:12.5, fontWeight:500 }}>{item.label}</div>
                <div style={{
                  fontSize:10.5, color: PCDS_t.c.textDim, fontFamily: PCDS_t.f.mono,
                  letterSpacing:'.04em', textTransform:'uppercase',
                }}>{item.docType}</div>
                <div style={{ textAlign:'right' }}>
                  {isUp
                    ? <span style={{ fontSize:11, color: PCDS_t.c.success, fontWeight:600 }}>Collected</span>
                    : <button onClick={() => {
                        store.addDocument(claim.id, item.docType);
                        store.toast({ icon:'whatsapp', title:`${PCDS_d.docTypes[item.docType]?.label} attached` });
                      }} style={{
                        border:'none', background:'transparent', color: PCDS_t.c.accent,
                        cursor:'pointer', fontSize:11, fontWeight:600, fontFamily: PCDS_t.f.sans,
                      }}>+ Attach</button>}
                </div>
              </div>
            );
          })}
        </div>
      </AppCard>

      {/* Generate dossier */}
      <AppCard>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
          <div>
            <AppSectionLabel>Generate dossier</AppSectionLabel>
            <div style={{ fontSize:15, fontWeight:600, marginTop:8 }}>
              {missing.length === 0
                ? 'Ready to package'
                : `Need ${missing.length} more document${missing.length > 1 ? 's' : ''}`}
            </div>
            <div style={{ fontSize:12.5, color: PCDS_t.c.textMuted, marginTop:4 }}>
              {present.length} documents · single PDF · cover index with page numbers · ROHINI stamped
            </div>
          </div>
          <AppBtn kind={missing.length === 0 ? 'brand' : 'ghost'} icon="download" disabled={missing.length > 0}>
            Download dossier PDF
          </AppBtn>
        </div>

        <div style={{
          marginTop:14, padding:'14px 16px',
          background: PCDS_t.c.surface2, borderRadius:7,
          display:'grid', gridTemplateColumns:'auto 1fr', gap:14, alignItems:'center',
        }}>
          <div style={{
            width:42, height:42, borderRadius:8,
            background:'#fff', color: PCDS_t.c.accent,
            display:'grid', placeItems:'center', border:`1px solid ${PCDS_t.c.border}`,
          }}>
            <AppIcon name="docs" size={20}/>
          </div>
          <div>
            <div style={{ fontSize:13, fontWeight:600 }}>{claim.id}_REIMB_DOSSIER.pdf</div>
            <div style={{ fontSize:11, color: PCDS_t.c.textMuted, fontFamily: PCDS_t.f.mono, marginTop:2 }}>
              {present.length} docs · sequence-ordered · ~{(present.length * 0.4).toFixed(1)} MB
            </div>
          </div>
        </div>

        <div style={{ marginTop:14, display:'flex', gap:8 }}>
          <AppBtn kind="ghost" icon="send">Send dossier link via WhatsApp</AppBtn>
          <AppBtn kind="ghost">Mark original as lost (regenerate)</AppBtn>
        </div>
      </AppCard>
    </>
  );
}

function ProgressRingDossier({ value, total }) {
  const pct = total === 0 ? 100 : Math.round((value / total) * 100);
  const r = 32, c = 2 * Math.PI * r;
  const offset = c * (1 - pct / 100);
  const tone = pct === 100 ? PCDS_t.c.success : pct >= 60 ? PCDS_t.c.warning : PCDS_t.c.error;
  return (
    <div style={{ position:'relative', width:80, height:80, flexShrink:0 }}>
      <svg width="80" height="80" viewBox="0 0 80 80">
        <circle cx="40" cy="40" r={r} stroke={PCDS_t.c.surface2} strokeWidth="6" fill="none"/>
        <circle cx="40" cy="40" r={r} stroke={tone} strokeWidth="6" fill="none"
          strokeDasharray={c} strokeDashoffset={offset}
          strokeLinecap="round" transform="rotate(-90 40 40)"/>
      </svg>
      <div style={{
        position:'absolute', inset:0,
        display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
      }}>
        <div style={{ fontFamily: PCDS_t.f.mono, fontSize:16, fontWeight:600, color: tone }}>{pct}%</div>
      </div>
    </div>
  );
}

// ── Reminders ────────────────────────────────────────────
function RemindersSection({ claim, insurer }) {
  const dischargedAt = claim.dischargedAt;
  const now = Date.now();
  const DAY = 24 * 3600 * 1000;
  const d7 = dischargedAt ? dischargedAt + 7 * DAY : null;
  const d21 = dischargedAt ? dischargedAt + 21 * DAY : null;

  const reminders = [
    { id:'d7',  at: d7,  fired: d7 && d7 < now,
      title: 'D+7 reminder · submit pharmacy bills',
      body: PCDS_d.notifTemplates.REMINDER_D7({ tpa: insurer.name }) },
    { id:'d21', at: d21, fired: d21 && d21 < now,
      title: 'D+21 reminder · 9 days left',
      body: PCDS_d.notifTemplates.REMINDER_D21({ tpa: insurer.name }) },
  ];

  return (
    <AppCard>
      <AppSectionLabel>Post-discharge WhatsApp reminders</AppSectionLabel>
      {!dischargedAt && (
        <div style={{
          marginTop:14, padding:'12px 14px',
          background: PCDS_t.c.surface2, borderRadius:7,
          fontSize:12.5, color: PCDS_t.c.textMuted, lineHeight:1.55,
        }}>
          Reminders are scheduled automatically when discharge date is logged.
          This patient has not been discharged yet.
        </div>
      )}
      {dischargedAt && (
        <div style={{ marginTop:14 }}>
          <div style={{ fontSize:12, color: PCDS_t.c.textMuted, marginBottom:14, lineHeight:1.55 }}>
            Discharged <strong style={{ color: PCDS_t.c.text }}>{PCDS_d.dayOnly(dischargedAt)}</strong>.
            Reminders auto-send to <strong style={{ color: PCDS_t.c.text, fontFamily: PCDS_t.f.mono }}>{claim.patient.phone}</strong>.
          </div>
          {reminders.map(r => (
            <div key={r.id} style={{
              display:'grid', gridTemplateColumns:'48px 1fr auto', gap:12,
              padding:'14px 0', alignItems:'center',
              borderBottom: `1px solid ${PCDS_t.c.border}`,
            }}>
              <div style={{
                width:40, height:40, borderRadius:8,
                background: r.fired ? PCDS_t.c.successTint : PCDS_t.c.surface2,
                color: r.fired ? PCDS_t.c.success : PCDS_t.c.textDim,
                display:'grid', placeItems:'center',
              }}>
                <AppIcon name={r.fired ? 'check' : 'clock'} size={16}/>
              </div>
              <div>
                <div style={{ fontSize:13, fontWeight:600 }}>{r.title}</div>
                <div style={{ fontSize:11.5, color: PCDS_t.c.textMuted, marginTop:4, lineHeight:1.5 }}>{r.body}</div>
                <div style={{ fontSize:10.5, color: PCDS_t.c.textDim, marginTop:4, fontFamily: PCDS_t.f.mono }}>
                  {r.fired
                    ? `Sent on ${PCDS_d.dayOnly(r.at)}`
                    : `Scheduled for ${PCDS_d.dayOnly(r.at)}`}
                </div>
              </div>
              <div>
                <span style={{
                  fontSize:10, fontWeight:600, fontFamily: PCDS_t.f.mono,
                  padding:'2px 7px', borderRadius:4, letterSpacing:'.06em', textTransform:'uppercase',
                  background: r.fired ? PCDS_t.c.successTint : PCDS_t.c.surface2,
                  color: r.fired ? PCDS_t.c.success : PCDS_t.c.textMuted,
                }}>{r.fired ? 'Sent' : 'Pending'}</span>
              </div>
            </div>
          ))}
        </div>
      )}
    </AppCard>
  );
}

function DossierSidebar({ claim, insurer }) {
  return (
    <>
      <AppCard>
        <AppSectionLabel>{insurer.name} · format</AppSectionLabel>
        <div style={{ marginTop:10, fontSize:12, color: PCDS_t.c.text, lineHeight:1.6 }}>
          <strong>Pre-auth:</strong> Digital upload via {insurer.portal.replace(/https?:\/\/(www\.)?/,'')}<br/>
          <strong>Reimbursement:</strong> {claim.claimType === 'REIMBURSEMENT' ? 'Originals required by mail' : 'Digital scans acceptable for amounts &lt; ₹20k'}<br/>
          <strong>Window:</strong> {insurer.slaClaimDays} days post-discharge to submit
        </div>
        {insurer.specialRules && (
          <div style={{
            marginTop:12, padding:'10px 12px',
            background: PCDS_t.c.warningTint, borderRadius:6,
            fontSize:11, color:'#92400E', lineHeight:1.55,
          }}>
            <strong>Note:</strong> {insurer.specialRules}
          </div>
        )}
      </AppCard>

      <AppCard>
        <AppSectionLabel>If patient lost originals</AppSectionLabel>
        <div style={{ fontSize:11.5, color: PCDS_t.c.textMuted, marginTop:10, lineHeight:1.55 }}>
          PulseChart can generate a <strong>"True duplicate copy"</strong> stamped PDF with the hospital letterhead for any document type. The patient brings it to the cashier counter.
        </div>
        <div style={{ marginTop:12 }}>
          <AppBtn full size="sm" kind="ghost" icon="docs">Generate duplicate doc</AppBtn>
        </div>
      </AppCard>
    </>
  );
}

Object.assign(window, { DossierTab });
