// screen-frontdesk.jsx — Front desk IPD admit screen with embedded RCM panel.
// This screen does NOT use the admin Shell — it uses the triageFlow (teal) front-desk
// layout to prove the integrated mode UI lives natively inside HMS.

const PCFS_t = window.PCT;
const PCFS_d = window.PCA;

// Teal palette (triageFlow theme from packages/ui/tokens.ts)
const FD_TEAL = { primary:'#0D9488', primaryHover:'#0F766E', tint:'#CCFBF1', tint2:'#99F6E4' };

function FrontDeskAdmitScreen({ claimId }) {
  const store = useStore();
  const claim = store.findClaim(claimId) || store.state.claims[0];

  return (
    <div style={{
      display:'grid',
      gridTemplateColumns: '232px 1fr',
      gridTemplateRows: '56px 1fr',
      height:'100vh',
      background: PCFS_t.c.bg,
      fontFamily: PCFS_t.f.sans,
      color: PCFS_t.c.text,
      overflow:'hidden',
    }}>
      <FrontDeskSidebarNav/>
      <FrontDeskTopBar claim={claim}/>
      <main style={{ overflow:'auto' }}>
        <div style={{
          padding:'24px 28px 80px',
          display:'grid', gridTemplateColumns:'1fr 380px', gap:20,
        }}>
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <PatientCardFD claim={claim}/>
            <AdmissionCardFD claim={claim}/>
            <ChargesEstimateCardFD claim={claim}/>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <RCMPanelFD claim={claim}/>
          </div>
        </div>
      </main>
      <ToastHost/>
    </div>
  );
}

function FrontDeskSidebarNav() {
  const items = [
    { id:'today',    label:'Today',        icon:'home', active:true },
    { id:'queue',    label:'Queue',        icon:'list', badge: 14 },
    { id:'register', label:'Register',     icon:'plus' },
    { id:'admit',    label:'IPD admit',    icon:'bed', highlight:true },
    { id:'bill',     label:'Billing',      icon:'money' },
    { id:'token',    label:'Tokens',       icon:'docs' },
  ];
  return (
    <aside style={{
      gridRow:'1 / span 2',
      background: PCFS_t.c.surface,
      borderRight: `1px solid ${PCFS_t.c.border}`,
      padding:'18px 12px', display:'flex', flexDirection:'column', gap:14,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'4px 8px 14px', borderBottom: `1px solid ${PCFS_t.c.border}` }}>
        <div style={{
          width:28, height:28, borderRadius:7,
          background: FD_TEAL.primary,
          display:'grid', placeItems:'center', color:'#fff',
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M2 12h4l2-6 4 12 3-9 2 3h5" stroke="#fff" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </div>
        <div>
          <div style={{ fontSize:14, fontWeight:600 }}>PulseChart</div>
          <div style={{ fontSize:10, color: FD_TEAL.primary, fontFamily: PCFS_t.f.mono, letterSpacing:'.06em', textTransform:'uppercase', fontWeight:600 }}>
            Front desk
          </div>
        </div>
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
        {items.map(it => (
          <div key={it.id} onClick={() => { if (!it.active) window.demoNote && window.demoNote({ title: it.label + ' — front desk' }); }} style={{
            display:'flex', alignItems:'center', gap:10,
            padding:'8px 10px', borderRadius:7,
            background: it.active ? FD_TEAL.primary : 'transparent',
            color: it.active ? '#fff' : PCFS_t.c.text,
            cursor:'pointer',
          }}>
            <AppIcon name={it.icon} size={15} color={it.active ? '#fff' : PCFS_t.c.textMuted}/>
            <span style={{ fontSize:13, flex:1, fontWeight: it.active ? 500 : 400 }}>{it.label}</span>
            {it.badge && (
              <span style={{
                background: it.active ? 'rgba(255,255,255,.2)' : FD_TEAL.primary,
                color:'#fff', fontSize:10, fontWeight:600,
                padding:'1px 6px', borderRadius:10,
                fontFamily: PCFS_t.f.mono,
              }}>{it.badge}</span>
            )}
            {it.highlight && !it.active && (
              <span style={{
                background: FD_TEAL.tint, color: FD_TEAL.primary,
                fontSize:9, fontWeight:700,
                padding:'1px 5px', borderRadius:3,
                fontFamily: PCFS_t.f.mono, letterSpacing:'.05em',
              }}>NEW</span>
            )}
          </div>
        ))}
      </div>

      <div style={{ flex:1 }}/>

      <div style={{
        display:'flex', alignItems:'center', gap:10,
        padding:'10px', borderTop: `1px solid ${PCFS_t.c.border}`,
      }}>
        <AppAvatar name="Anjali R" size={28} bg={FD_TEAL.tint}/>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:12.5, fontWeight:500 }}>Anjali Ramamurthy</div>
          <div style={{ fontSize:10, color: PCFS_t.c.textMuted, fontFamily: PCFS_t.f.mono }}>Front desk</div>
        </div>
      </div>

      {/* Hidden link back to admin app */}
      <a href="#/" style={{
        marginTop:6, padding:'6px 10px',
        textAlign:'center', borderRadius:6,
        background: PCFS_t.c.surface2, color: PCFS_t.c.textMuted,
        fontFamily: PCFS_t.f.mono, fontSize:10,
        textDecoration:'none', letterSpacing:'.06em', textTransform:'uppercase',
      }}>
        ← back to Claims app
      </a>
    </aside>
  );
}

function FrontDeskTopBar({ claim }) {
  return (
    <header style={{
      height:56, padding:'0 24px',
      borderBottom: `1px solid ${PCFS_t.c.border}`,
      background: PCFS_t.c.surface,
      display:'flex', alignItems:'center', gap:16,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, flex:1 }}>
        <span style={{ fontSize:13, color: PCFS_t.c.textMuted }}>Front desk</span>
        <AppIcon name="right" size={12} color={PCFS_t.c.textDim}/>
        <span style={{ fontSize:13, color: PCFS_t.c.textMuted }}>IPD admit</span>
        <AppIcon name="right" size={12} color={PCFS_t.c.textDim}/>
        <span style={{ fontSize:14, fontWeight:600 }}>{claim.patient.name}</span>
        <span style={{
          marginLeft:10, fontFamily: PCFS_t.f.mono, fontSize:11, color: PCFS_t.c.textMuted,
          padding:'2px 6px', borderRadius:4, background: PCFS_t.c.surface2,
        }}>{claim.patient.uhid}</span>
      </div>
      <div style={{
        display:'flex', alignItems:'center', gap:6,
        padding:'4px 8px', borderRadius:6,
        background:'#E0F2FE', color: PCFS_t.c.accent,
        fontFamily: PCFS_t.f.mono, fontSize:10, fontWeight:600,
        letterSpacing:'.08em', textTransform:'uppercase',
      }}>
        <span style={{ width:5, height:5, borderRadius:'50%', background: PCFS_t.c.accent }}/>
        Inside HMS
      </div>
      <AppBtn icon="check" kind="primary">Admit &amp; create claim</AppBtn>
    </header>
  );
}

function PatientCardFD({ claim }) {
  return (
    <AppCard>
      <AppSectionLabel>Patient details</AppSectionLabel>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:16, marginTop:14 }}>
        <FDField label="Full name"    value={claim.patient.name}/>
        <FDField label="Age / Gender" value={`${claim.patient.age} yrs · ${claim.patient.gender}`}/>
        <FDField label="UHID"         value={claim.patient.uhid} mono/>
        <FDField label="Phone"        value={claim.patient.phone}/>
        <FDField label="Aadhaar"      value="•••• •••• 4421" mono/>
        <FDField label="Attendant"    value="K. Ramachandran (son)"/>
      </div>
    </AppCard>
  );
}

function AdmissionCardFD({ claim }) {
  return (
    <AppCard>
      <AppSectionLabel>IPD admission</AppSectionLabel>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:16, marginTop:14 }}>
        <FDField label="Department"    value="Cardiology"               pill/>
        <FDField label="Consultant"    value={claim.doctor}/>
        <FDField label="Ward · Bed"    value={claim.ward}               mono/>
        <FDField label="Admission type" value="Emergency"               pill pillTone="warning"/>
        <FDField label="Provisional Dx" value={`${claim.icd} · ${claim.icdLabel.split('·')[0].trim()}`} mono/>
        <FDField label="Admitted"      value={PCFS_d.dateLabel(claim.admittedAt)} mono/>
      </div>
    </AppCard>
  );
}

function ChargesEstimateCardFD({ claim }) {
  const rows = [
    { label:'ICU room × 3 days',          value: 55500 },
    { label:'Primary PCI procedure',      value: 142000 },
    { label:'DES stent (estimated 1)',    value: 68000 },
    { label:'Coronary angiography',       value: 32000 },
    { label:'Consultant fees × 3 visits', value: 4500 },
    { label:'Pharmacy + consumables',     value: 28000 },
  ];
  return (
    <AppCard>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:14 }}>
        <AppSectionLabel>Estimated charges &amp; deposit</AppSectionLabel>
        <span style={{ fontSize:10.5, color: PCFS_t.c.textDim, fontFamily: PCFS_t.f.mono }}>From chargemaster · primary PCI bundle</span>
      </div>
      {rows.map(r => (
        <div key={r.label} style={{
          padding:'10px 0', borderBottom: `1px solid ${PCFS_t.c.border}`,
          display:'flex', justifyContent:'space-between', alignItems:'baseline',
        }}>
          <span style={{ fontSize:12.5, color: PCFS_t.c.textMuted }}>{r.label}</span>
          <AppMoney value={r.value}/>
        </div>
      ))}
      <div style={{
        display:'flex', justifyContent:'space-between', alignItems:'center',
        marginTop:14, padding:'12px 14px',
        background: PCFS_t.c.surface2, borderRadius:8,
      }}>
        <div>
          <div style={{ fontSize:11, color: PCFS_t.c.textMuted, fontFamily: PCFS_t.f.mono, letterSpacing:'.05em', textTransform:'uppercase' }}>Estimated total</div>
          <div style={{ marginTop:2 }}><AppMoney value={claim.estimatedCost} strong size={20}/></div>
        </div>
        <div>
          <div style={{ fontSize:11, color: PCFS_t.c.textMuted, fontFamily: PCFS_t.f.mono, letterSpacing:'.05em', textTransform:'uppercase' }}>Deposit to collect</div>
          <div style={{ marginTop:2 }}><AppMoney value={claim.depositCollected} strong size={20}/></div>
          <div style={{ fontSize:10.5, color: PCFS_t.c.textDim, marginTop:2 }}>Auto: ₹0 if cashless approved</div>
        </div>
      </div>
    </AppCard>
  );
}

function FDField({ label, value, mono, pill, pillTone }) {
  const tones = {
    warning: { bg: PCFS_t.c.warningTint, fg: PCFS_t.c.warning },
    default: { bg: FD_TEAL.tint,         fg: FD_TEAL.primary },
  };
  const tone = tones[pillTone] || tones.default;
  return (
    <div>
      <div style={{
        fontFamily: PCFS_t.f.mono, fontSize:9.5, fontWeight:600,
        letterSpacing:'.1em', textTransform:'uppercase', color: PCFS_t.c.textMuted, marginBottom:6,
      }}>{label}</div>
      {pill ? (
        <span style={{
          display:'inline-flex', padding:'3px 9px', borderRadius:999,
          background: tone.bg, color: tone.fg,
          fontSize:12, fontWeight:600,
        }}>{value}</span>
      ) : (
        <div style={{ fontSize:13.5, fontFamily: mono ? PCFS_t.f.mono : PCFS_t.f.sans, color: PCFS_t.c.text }}>{value}</div>
      )}
    </div>
  );
}

// ── THE RCM PANEL ─────────────────────────────────────────
function RCMPanelFD({ claim }) {
  const insurer = PCFS_d.findInsurer(claim.insurer);
  return (
    <div style={{
      background: PCFS_t.c.surface,
      border: `1px solid ${PCFS_t.c.border}`,
      borderRadius:10, overflow:'hidden',
      position:'sticky', top:14,
    }}>
      <div style={{
        padding:'14px 18px',
        background:'linear-gradient(180deg, #FAFAF9 0%, #FFFFFF 100%)',
        borderBottom: `1px solid ${PCFS_t.c.border}`,
        display:'flex', alignItems:'center', gap:10,
      }}>
        <div style={{
          width:24, height:24, borderRadius:6,
          background:'linear-gradient(135deg, #6D28D9, #4C1D95)',
          color:'#fff', fontFamily: PCFS_t.f.mono, fontSize:12, fontWeight:700,
          display:'grid', placeItems:'center',
        }}>P</div>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:13.5, fontWeight:600 }}>Cashless &amp; claims</div>
          <div style={{ fontSize:10.5, color: PCFS_t.c.textMuted, fontFamily: PCFS_t.f.mono }}>PulseChart Claims · auto-attached</div>
        </div>
        <a href={`#/claims/${claim.id}/overview`} style={{
          fontSize:10, color: FD_TEAL.primary, textDecoration:'none', fontWeight:600,
          fontFamily: PCFS_t.f.mono, letterSpacing:'.04em', textTransform:'uppercase',
        }}>open →</a>
      </div>

      {/* Insurance */}
      <div style={{ padding:18, borderBottom: `1px solid ${PCFS_t.c.border}` }}>
        <AppSectionLabel>Insurance card</AppSectionLabel>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginTop:10 }}>
          <CardThumbFD side="front" insurer={insurer}/>
          <CardThumbFD side="back" insurer={insurer}/>
        </div>
        <div style={{
          marginTop:10, padding:'8px 10px',
          background: FD_TEAL.tint, borderRadius:6,
          fontSize:11.5, color:'#115E59', lineHeight:1.5,
          display:'flex', gap:8,
        }}>
          <AppIcon name="check" size={14} color={FD_TEAL.primary}/>
          <span>
            OCR extracted policy <strong style={{ fontFamily: PCFS_t.f.mono }}>{claim.policyNumber}</strong> ·
            <strong> {insurer.name}</strong>
            {' '}· DOB matches.
          </span>
        </div>
      </div>

      {/* Eligibility */}
      <div style={{ padding:18, borderBottom: `1px solid ${PCFS_t.c.border}` }}>
        <AppSectionLabel>Eligibility</AppSectionLabel>
        <div style={{
          display:'flex', justifyContent:'space-between', alignItems:'center',
          marginTop:10, padding:'10px 12px',
          background: PCFS_t.c.successTint, borderRadius:7,
        }}>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <AppIcon name="check" size={16} color={PCFS_t.c.success}/>
            <div>
              <div style={{ fontSize:12.5, fontWeight:600, color:'#14532D' }}>Active</div>
              <div style={{ fontSize:10.5, color:'#15803D', fontFamily: PCFS_t.f.mono, marginTop:1 }}>
                Sum insured ₹10,00,000 · ₹0 utilised this year
              </div>
            </div>
          </div>
          <span style={{ fontSize:10.5, color:'#15803D', fontFamily: PCFS_t.f.mono }}>checked 06:48</span>
        </div>
      </div>

      {/* Auto-draft */}
      <div style={{ padding:18, borderBottom: `1px solid ${PCFS_t.c.border}` }}>
        <AppSectionLabel>Auto-drafted claim</AppSectionLabel>
        <div style={{ marginTop:10, padding:12, background: PCFS_t.c.surface2, borderRadius:7 }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <div style={{ fontFamily: PCFS_t.f.mono, fontSize:13, fontWeight:600, color: PCFS_t.c.brand }}>{claim.id}</div>
            <span style={{ fontSize:10, fontFamily: PCFS_t.f.mono, fontWeight:600, color: PCFS_t.c.textMuted, letterSpacing:'.05em', textTransform:'uppercase' }}>
              {PCFS_d.statusMeta[claim.status]?.label}
            </span>
          </div>
          <div style={{ fontSize:11.5, color: PCFS_t.c.textMuted, marginTop:4, lineHeight:1.5 }}>
            Pre-filled from admission · {insurer.name} · {claim.claimType.toLowerCase()} · {claim.icd}
          </div>
        </div>
        <div style={{ marginTop:12 }}>
          <ToggleRowFD label="Send pre-auth on admit" value={true}/>
          <ToggleRowFD label="Notify patient on WhatsApp" value={true}/>
          <ToggleRowFD label="Assign to coordinator" value="Priya M." link/>
        </div>
      </div>

      <div style={{ padding:18 }}>
        <AppSectionLabel>Patient share preview</AppSectionLabel>
        <div style={{ marginTop:10 }}>
          <ShareRowFD label="If approved in full"            value={0}      positive/>
          <ShareRowFD label="If partial (typical 88%)"       value={Math.round(claim.estimatedCost * 0.12)}/>
          <ShareRowFD label="If denied → self-pay"           value={claim.estimatedCost} negative/>
        </div>
        <div style={{
          marginTop:10, fontSize:10.5, color: PCFS_t.c.textDim,
          fontFamily: PCFS_t.f.mono, letterSpacing:'.02em',
        }}>Based on {insurer.name} · last 6mo approval rate</div>
      </div>
    </div>
  );
}

function CardThumbFD({ side, insurer }) {
  return (
    <div style={{
      aspectRatio:'1.58/1', borderRadius:6,
      background: 'linear-gradient(135deg, ' + insurer.color + ', ' + insurer.color + 'DD)',
      position:'relative', padding:8, color:'#fff', overflow:'hidden',
    }}>
      <div style={{
        position:'absolute', inset:0,
        background:'repeating-linear-gradient(135deg, transparent 0, transparent 6px, rgba(255,255,255,.04) 6px, rgba(255,255,255,.04) 7px)',
      }}/>
      <div style={{ fontSize:7.5, fontWeight:700, letterSpacing:'.12em', fontFamily: PCFS_t.f.mono, position:'relative' }}>
        {insurer.name.toUpperCase().slice(0, 12)}
      </div>
      <div style={{ fontSize:6.5, opacity:.7, marginTop:3, position:'relative', fontFamily: PCFS_t.f.mono }}>
        {side === 'front' ? 'INSURED · LAKSHMI R.' : 'TPA · ' + insurer.type.toUpperCase()}
      </div>
      <div style={{
        position:'absolute', bottom:6, right:6,
        padding:'2px 5px', background:'rgba(0,0,0,.4)', borderRadius:3,
        fontSize:7, fontWeight:700, letterSpacing:'.06em', fontFamily: PCFS_t.f.mono, color:'#86EFAC',
      }}>OCR ✓</div>
    </div>
  );
}

function ToggleRowFD({ label, value, link }) {
  const isToggle = typeof value === 'boolean';
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'center',
      padding:'8px 0', borderBottom: `1px solid ${PCFS_t.c.border}`,
    }}>
      <span style={{ fontSize:12.5, color: PCFS_t.c.text }}>{label}</span>
      {isToggle ? (
        <div style={{
          width:30, height:18, borderRadius:9,
          background: value ? FD_TEAL.primary : PCFS_t.c.borderStrong,
          position:'relative',
        }}>
          <div style={{
            position:'absolute', top:2, left: value ? 14 : 2,
            width:14, height:14, borderRadius:'50%', background:'#fff',
            boxShadow:'0 1px 2px rgba(0,0,0,.2)',
          }}/>
        </div>
      ) : (
        <span style={{ fontSize:12.5, color: FD_TEAL.primary, fontWeight:500 }}>{value} <span style={{ color: PCFS_t.c.textDim, marginLeft:4 }}>change</span></span>
      )}
    </div>
  );
}

function ShareRowFD({ label, value, positive, negative }) {
  return (
    <div style={{
      display:'flex', justifyContent:'space-between', alignItems:'baseline',
      padding:'7px 0', borderBottom: `1px solid ${PCFS_t.c.border}`,
    }}>
      <span style={{ fontSize:12, color: positive ? PCFS_t.c.success : negative ? PCFS_t.c.error : PCFS_t.c.textMuted }}>{label}</span>
      <span style={{
        fontFamily: PCFS_t.f.mono, fontSize:13, fontWeight: positive || negative ? 600 : 500,
        color: positive ? PCFS_t.c.success : negative ? PCFS_t.c.error : PCFS_t.c.text,
        fontVariantNumeric:'tabular-nums',
      }}>{value === 0 ? '₹0' : PCFS_d.inr(value)}</span>
    </div>
  );
}

Object.assign(window, { FrontDeskAdmitScreen });
