// screen-discharge.jsx — Discharge Summary module.
// Picker (choose patient journey) + stepped workspace:
//   1 Admission · 2 Progress & labs · 3 Synthesis & review · 4 Sign & PDF

const DT = window.PCT;

// ════════════════════════════════════════════════════════
// PICKER
// ════════════════════════════════════════════════════════
function DischargePicker() {
  const store = useRStore();
  const mode = store.state.mode;
  const journeys = window.PRD.journeys;

  const startJourney = (j, linkedCounseling) => {
    const id = store.createSession('discharge', {
      journeyId: j.id, specialty: j.specialty, procedure: j.procedure,
      profile: { ...j.profile },
      progressNotes: j.progressNotes.map(n => ({ ...n })),
      labResults: j.labResults, medications: j.medications,
      step: 1, summary: null, edits: {}, omitLabs: false,
      linkedCounseling: linkedCounseling || null,
    });
    rNav('#/discharge/' + id);
  };

  const importFromCounseling = (cs) => {
    const journey = window.PRD.journeys.find(j => j.id === cs.profileId.replace('C-', 'J-')) || window.PRD.journeys[0];
    const proc = cs.procedure ? window.PR.procedures[cs.procedure] : null;
    startJourney(journey, { counselingDate: cs.createdAt, procedureLabel: proc ? proc.label : 'the procedure', doctorName: cs.doctorName, patientAdmissionId: cs.patientAdmissionId });
  };

  const linkedCounselings = store.recentCounselingSessions();

  return (
    <RShell crumb={['Discharge Summary']}>
      <div style={{ maxWidth:1000, margin:'0 auto', padding:'36px 28px 100px' }}>
        <div style={{ marginBottom:8 }}>
          <h1 style={{ fontSize:26, fontWeight:600, letterSpacing:'-.02em', margin:0 }}>
            {mode==='integrated' ? 'Patients ready for discharge' : 'Start a discharge summary'}
          </h1>
          <p style={{ fontSize:14, color:DT.c.textMuted, marginTop:8, lineHeight:1.55, maxWidth:640 }}>
            {mode==='integrated'
              ? <>These inpatients are flagged ready-for-discharge in <strong style={{color:DT.c.text}}>PulseChart HMS</strong>. Their admission, daily progress notes and labs are already in the record — pick one and PulseChart loads everything.</>
              : <>Pick a sample admission journey to load a worked example, then edit anything. In a real standalone deployment your resident would enter this incrementally during the stay.</>}
          </p>
        </div>

        {mode==='integrated' && (
          <div style={{ display:'flex', alignItems:'center', gap:9, margin:'14px 0 20px', padding:'10px 14px', background:DT.c.brandSoft, borderRadius:9, fontSize:12.5, color:'#4C1D95' }}>
            <RHmsBadge>HMS</RHmsBadge>
            <span>Live from <strong>ipd-service</strong> · admission, SOAP progress notes and labs auto-loaded · no manual entry needed.</span>
          </div>
        )}

        {/* Import from counselling (when sessions are linked) */}
        {linkedCounselings.length > 0 && (
          <div style={{ margin:'18px 0 6px', padding:'16px 18px', background:DT.c.surface, border:`1px solid ${DT.c.brand}40`, borderRadius:12 }}>
            <div style={{ display:'flex', alignItems:'center', gap:9, marginBottom:12 }}>
              <RIcon name="link" size={16} color={DT.c.brand}/>
              <span style={{ fontSize:13.5, fontWeight:600 }}>Continue from a counselling session</span>
              <span style={{ fontSize:11.5, color:DT.c.textMuted }}>· these patients were counselled earlier and linked for discharge</span>
            </div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
              {linkedCounselings.map(cs => {
                const proc = cs.procedure ? window.PR.procedures[cs.procedure] : null;
                return (
                  <div key={cs.id} onClick={()=>importFromCounseling(cs)} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', background:DT.c.brandSoft, borderRadius:9, cursor:'pointer' }}>
                    <div style={{ width:34, height:34, borderRadius:8, background:'#fff', color:DT.c.brand, display:'grid', placeItems:'center', flexShrink:0 }}><RIcon name="shield" size={16}/></div>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:13, fontWeight:600 }}>{cs.profile.patientIdentifier}</div>
                      <div style={{ fontSize:11, color:'#5B21B6', marginTop:1 }}>{proc ? proc.label : ''} · counselled {window.PR.dayLabel(cs.createdAt)}</div>
                    </div>
                    <RHmsBadge>{cs.patientAdmissionId}</RHmsBadge>
                    <RIcon name="right" size={14} color={DT.c.brand}/>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        {/* Specialty groups */}
        {['OBGYN','ORTHO'].map(spec => {
          const group = journeys.filter(j => j.specialty === spec);
          const sp = window.PR.specialties[spec];
          return (
            <div key={spec} style={{ marginTop:24 }}>
              <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
                <RSpecChip specialty={spec}/>
                <span style={{ fontSize:12.5, color:DT.c.textMuted }}>{sp.label}</span>
                {!sp.validated && <RUnverifiedBadge small/>}
                <div style={{ flex:1, height:1, background:DT.c.border }}/>
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                {group.map(j => <PatientJourneyCard key={j.id} j={j} mode={mode} onStart={()=>startJourney(j)}/>)}
              </div>
            </div>
          );
        })}

        {mode==='standalone' && (
          <div style={{ marginTop:28, padding:'16px 20px', background:DT.c.surface, border:`1px dashed ${DT.c.borderStrong}`, borderRadius:12, display:'flex', alignItems:'center', justifyContent:'space-between', gap:14 }}>
            <div style={{ fontSize:13, color:DT.c.textMuted, lineHeight:1.55 }}>
              <strong style={{ color:DT.c.text }}>Enter a patient manually instead.</strong> Standalone deployments capture the admission, progress notes and labs by hand. (Demo: loading a sample journey is faster — every field stays editable.)
            </div>
            <RBtn kind="ghost" icon="plus" onClick={()=>startJourney(journeys[0])}>Manual entry</RBtn>
          </div>
        )}
      </div>
    </RShell>
  );
}

function PatientJourneyCard({ j, mode, onStart }) {
  const p = j.profile;
  const proc = j.procedure ? window.PR.procedures[j.procedure] : null;
  return (
    <div onClick={onStart} style={{ background:DT.c.surface, border:`1px solid ${DT.c.border}`, borderRadius:12, padding:18, cursor:'pointer', transition:'border-color .12s, box-shadow .12s' }}
      onMouseEnter={e=>{ e.currentTarget.style.borderColor=DT.c.accent; e.currentTarget.style.boxShadow='0 6px 16px -8px rgba(0,0,0,.12)'; }}
      onMouseLeave={e=>{ e.currentTarget.style.borderColor=DT.c.border; e.currentTarget.style.boxShadow='none'; }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:12 }}>
        <div style={{ minWidth:0 }}>
          <div style={{ fontSize:15, fontWeight:600 }}>{p.patientIdentifier}</div>
          <div style={{ fontSize:11, color:DT.c.textMuted, fontFamily:DT.f.mono, marginTop:2 }}>{p.uhid} · {p.age}{p.gender} · {p.ward}</div>
        </div>
        {mode==='integrated' && <RHmsBadge source="ipd">HMS</RHmsBadge>}
      </div>
      <div style={{ fontSize:12.5, color:DT.c.text, marginTop:10, lineHeight:1.5 }}>{proc ? proc.label : 'Normal vaginal delivery'}</div>
      <div style={{ fontSize:11.5, color:DT.c.textMuted, marginTop:6, lineHeight:1.5 }}>{p.primaryDiagnosis}</div>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:12, paddingTop:12, borderTop:`1px solid ${DT.c.border}` }}>
        <span style={{ fontSize:11, color:DT.c.textDim, fontFamily:DT.f.mono }}>{j.progressNotes.length} progress notes · labs · meds</span>
        <div style={{ flex:1 }}/>
        <span style={{ display:'flex', alignItems:'center', gap:4, fontSize:12, color:DT.c.accent, fontWeight:500 }}>Open <RIcon name="right" size={13} color={DT.c.accent}/></span>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════
// WORKSPACE
// ════════════════════════════════════════════════════════
function DischargeWorkspace({ sessionId }) {
  const store = useRStore();
  const session = store.getSession(sessionId);
  if (!session) { rNav('#/discharge'); return null; }

  const step = session.step || 1;
  const setStep = (n) => store.updateSession(sessionId, { step:n });
  const specialty = session.specialty;
  const sp = window.PR.specialties[specialty];
  const proc = session.procedure ? window.PR.procedures[session.procedure] : null;

  const steps = [
    { n:1, label:'Admission' },
    { n:2, label:'Progress & labs' },
    { n:3, label:'Synthesis & review' },
    { n:4, label:'Generate PDF' },
  ];

  return (
    <RShell crumb={['Discharge Summary', session.profile.patientIdentifier]}
      headerRight={<div style={{ display:'flex', alignItems:'center', gap:10 }}><RSpecChip specialty={specialty}/>{!sp.validated && <RUnverifiedBadge small/>}</div>}>
      <div style={{ display:'grid', gridTemplateColumns:'220px 1fr', gap:0, minHeight:'calc(100vh - 60px)' }}>
        {/* Step rail */}
        <div style={{ borderRight:`1px solid ${DT.c.border}`, background:DT.c.surface, padding:'24px 16px' }}>
          <div data-demo="rec-patient" style={{ marginBottom:18, padding:'0 8px' }}>
            <div style={{ fontSize:13.5, fontWeight:600 }}>{session.profile.patientIdentifier}</div>
            <div style={{ fontSize:11, color:DT.c.textMuted, fontFamily:DT.f.mono, marginTop:2 }}>{session.profile.uhid}</div>
            <div style={{ fontSize:11.5, color:DT.c.textMuted, marginTop:6, lineHeight:1.4 }}>{proc ? proc.label : 'Normal vaginal delivery'}</div>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:2 }}>
            {steps.map(s => {
              const done = step > s.n, cur = step === s.n;
              return (
                <button key={s.n} onClick={()=>setStep(s.n)} style={{
                  display:'flex', alignItems:'center', gap:11, padding:'9px 10px', borderRadius:8, border:'none', cursor:'pointer',
                  background: cur?DT.c.brandSoft:'transparent', color: cur?DT.c.brand:done?DT.c.text:DT.c.textMuted, textAlign:'left', fontFamily:DT.f.sans }}>
                  <span style={{ width:22, height:22, borderRadius:'50%', flexShrink:0, display:'grid', placeItems:'center',
                    background: done?DT.c.success:cur?DT.c.brand:'#fff', color: done||cur?'#fff':DT.c.textMuted,
                    border: done||cur?'0':`1.5px solid ${DT.c.borderStrong}`, fontFamily:DT.f.mono, fontSize:10.5, fontWeight:700 }}>
                    {done ? <RIcon name="check" size={11} color="#fff" stroke={2.8}/> : s.n}
                  </span>
                  <span style={{ fontSize:13, fontWeight: cur?600:500 }}>{s.label}</span>
                </button>
              );
            })}
          </div>
          <div style={{ marginTop:24, padding:'0 8px' }}>
            <a href="#/discharge" style={{ fontSize:11.5, color:DT.c.textMuted, textDecoration:'none', display:'flex', alignItems:'center', gap:5 }}><RIcon name="left" size={12} color={DT.c.textMuted}/>All patients</a>
          </div>
        </div>

        {/* Step body */}
        <div style={{ overflow:'auto', padding:'28px 32px 100px', maxWidth:980 }}>
          {step===1 && <DStepAdmission session={session} sessionId={sessionId} onNext={()=>setStep(2)}/>}
          {step===2 && <DStepProgress session={session} sessionId={sessionId} onBack={()=>setStep(1)} onNext={()=>setStep(3)}/>}
          {step===3 && <DStepSynthesis session={session} sessionId={sessionId} onBack={()=>setStep(2)} onNext={()=>setStep(4)}/>}
          {step===4 && <DStepSign session={session} sessionId={sessionId} onBack={()=>setStep(3)}/>}
        </div>
      </div>
    </RShell>
  );
}

// ── STEP 1: Admission ─────────────────────────────────────
function DStepAdmission({ session, sessionId, onNext }) {
  const store = useRStore();
  const mode = store.state.mode;
  const p = session.profile;
  const setP = (patch) => store.updateSession(sessionId, s => ({ ...s, profile: { ...s.profile, ...patch } }));

  return (
    <div>
      <StepHead n={1} title="Admission profile"
        sub={mode==='integrated' ? 'Loaded from the HMS admission record. Review and edit if needed.' : 'Loaded from the sample journey. Every field is editable.'}/>
      {mode==='integrated' && <HmsLoadedBanner text="Demographics, diagnosis and admission exam pulled from patient-service + ipd-service."/>}

      <RCard style={{ marginTop:16 }}>
        <RLabel>Patient</RLabel>
        <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr 1fr', gap:14, marginTop:14 }}>
          <RField label="Name"><RInput value={p.patientIdentifier} onChange={v=>setP({patientIdentifier:v})}/></RField>
          <RField label="UHID"><RInput value={p.uhid} onChange={v=>setP({uhid:v})} mono/></RField>
          <RField label="Age / Sex"><RInput value={`${p.age} / ${p.gender}`} onChange={()=>{}}/></RField>
        </div>
        {session.specialty==='OBGYN' ? (
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14, marginTop:14 }}>
            <RField label="Obstetric formula"><RInput value={p.parity} onChange={v=>setP({parity:v})} mono/></RField>
            <RField label="Gestational age (wk)"><RInput value={p.gestationalAgeWeeks} onChange={v=>setP({gestationalAgeWeeks:v})} mono/></RField>
            <RField label="Prior caesareans"><RInput value={p.priorCaesareans} onChange={v=>setP({priorCaesareans:v})} mono/></RField>
          </div>
        ) : (
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:14, marginTop:14 }}>
            <RField label="BMI"><RInput value={p.bmi} onChange={v=>setP({bmi:v})} mono/></RField>
            <RField label="ASA grade"><RInput value={p.asa} onChange={v=>setP({asa:v})} mono/></RField>
            <RField label="Admission Hb"><RInput value={p.hb} onChange={v=>setP({hb:v})} mono/></RField>
          </div>
        )}
      </RCard>

      <RCard style={{ marginTop:14 }}>
        <RLabel>Clinical</RLabel>
        <div style={{ display:'flex', flexDirection:'column', gap:14, marginTop:14 }}>
          <RField label="Presenting complaint"><RTextarea value={p.presentingComplaint} onChange={v=>setP({presentingComplaint:v})} rows={2}/></RField>
          <RField label="Primary diagnosis"><RTextarea value={p.primaryDiagnosis} onChange={v=>setP({primaryDiagnosis:v})} rows={2}/></RField>
          <RField label="Examination on admission"><RTextarea value={p.admissionExamination} onChange={v=>setP({admissionExamination:v})} rows={2}/></RField>
          <RField label="Initial investigations"><RTextarea value={p.initialInvestigations} onChange={v=>setP({initialInvestigations:v})} rows={2}/></RField>
        </div>
      </RCard>

      <StepNav onNext={onNext} nextLabel="Continue to progress notes"/>
    </div>
  );
}

// ── STEP 2: Progress notes & labs ─────────────────────────
function DStepProgress({ session, sessionId, onBack, onNext }) {
  const store = useRStore();
  const mode = store.state.mode;
  const notes = session.progressNotes || [];
  const [activeDay, setActiveDay] = React.useState(notes[0]?.day || 1);
  const note = notes.find(n => n.day === activeDay) || notes[0];

  const setNote = (patch) => store.updateSession(sessionId, s => ({
    ...s, progressNotes: s.progressNotes.map(n => n.day===activeDay ? { ...n, ...patch } : n),
  }));
  const setLabs = (v) => store.updateSession(sessionId, { labResults:v });
  const setMeds = (v) => store.updateSession(sessionId, { medications:v });
  const toggleOmit = () => store.updateSession(sessionId, s => ({ ...s, omitLabs: !s.omitLabs }));

  return (
    <div>
      <StepHead n={2} title="Daily progress notes & labs"
        sub={mode==='integrated' ? 'Each day\u2019s SOAP note is synced from the resident\u2019s HMS entries.' : 'Pre-filled from the sample journey. Edit, or add days.'}/>
      {mode==='integrated' && <HmsLoadedBanner text={`${notes.length} daily SOAP notes synced from clinical-service · labs from lab-service.`}/>}

      {/* Day tabs */}
      <div data-demo="rec-progress" style={{ display:'flex', gap:6, marginTop:16, flexWrap:'wrap' }}>
        {notes.map(n => (
          <button key={n.day} onClick={()=>setActiveDay(n.day)} style={{
            padding:'7px 14px', borderRadius:8, border:`1px solid ${activeDay===n.day?DT.c.brand:DT.c.border}`,
            background: activeDay===n.day?DT.c.brandSoft:DT.c.surface, color: activeDay===n.day?DT.c.brand:DT.c.text,
            fontSize:12.5, fontWeight: activeDay===n.day?600:500, cursor:'pointer', fontFamily:DT.f.sans }}>
            Day {n.day}
          </button>
        ))}
      </div>

      {note && (
        <RCard style={{ marginTop:14 }}>
          <RLabel>Day {note.day} · SOAP {mode==='integrated' && <RHmsBadge source="clinical">HMS</RHmsBadge>}</RLabel>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:14 }}>
            <RField label="Subjective"><RTextarea value={note.subjective} onChange={v=>setNote({subjective:v})} rows={3}/></RField>
            <RField label="Objective"><RTextarea value={note.objective} onChange={v=>setNote({objective:v})} rows={3}/></RField>
            <RField label="Assessment"><RTextarea value={note.assessment} onChange={v=>setNote({assessment:v})} rows={2}/></RField>
            <RField label="Plan"><RTextarea value={note.plan} onChange={v=>setNote({plan:v})} rows={2}/></RField>
          </div>
        </RCard>
      )}

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:14 }}>
        <RCard>
          <RLabel right={
            <button onClick={toggleOmit} style={{ border:'none', background:'transparent', cursor:'pointer', fontSize:11, color:session.omitLabs?DT.c.error:DT.c.textMuted, fontFamily:DT.f.sans, display:'flex', alignItems:'center', gap:5 }}>
              <RIcon name={session.omitLabs?'check':'alert'} size={12}/>{session.omitLabs?'Labs omitted (guardrail demo)':'Omit labs (demo guardrail)'}
            </button>
          }>Lab results {mode==='integrated' && <RHmsBadge source="lab">HMS</RHmsBadge>}</RLabel>
          <div style={{ marginTop:12, opacity: session.omitLabs?0.4:1 }}>
            <RTextarea value={session.omitLabs ? '' : session.labResults} onChange={setLabs} rows={5} placeholder={session.omitLabs?'Labs omitted — section 4 will flag [INSUFFICIENT DATA] at synthesis':''}/>
          </div>
        </RCard>
        <RCard>
          <RLabel>Medications administered {mode==='integrated' && <RHmsBadge source="pharmacy">HMS</RHmsBadge>}</RLabel>
          <div style={{ marginTop:12 }}><RTextarea value={session.medications} onChange={setMeds} rows={5}/></div>
        </RCard>
      </div>

      <StepNav onBack={onBack} onNext={onNext} nextLabel="Continue to synthesis"/>
    </div>
  );
}

// ── STEP 3: Synthesis & review ────────────────────────────
function DStepSynthesis({ session, sessionId, onBack, onNext }) {
  const store = useRStore();
  const [synth, setSynth] = React.useState(!!session.summary);
  const [busy, setBusy] = React.useState(false);

  const runSynthesis = () => {
    setBusy(true);
    setTimeout(() => {
      const base = window.PRD.summaryFor(session.journeyId);
      const summary = JSON.parse(JSON.stringify(base));
      if (session.omitLabs) summary.investigations = '[INSUFFICIENT DATA: no lab results were entered for this admission. Enter investigations to complete this section — values were not invented.]';
      store.updateSession(sessionId, { summary, edits:{} });
      setBusy(false); setSynth(true);
    }, 1400);
  };

  if (!synth) {
    return (
      <div>
        <StepHead n={3} title="AI synthesis" sub="PulseChart synthesises the 10-section NABH discharge summary from everything entered — with strict hallucination guardrails."/>
        <RCard style={{ marginTop:16, textAlign:'center', padding:'40px 28px' }}>
          <div style={{ width:56, height:56, borderRadius:14, background:DT.c.brandSoft, color:DT.c.brand, display:'grid', placeItems:'center', margin:'0 auto 18px' }}>
            <RIcon name="sparkle" size={28} color={DT.c.brand}/>
          </div>
          <div style={{ fontSize:18, fontWeight:600, marginBottom:8 }}>Ready to synthesise</div>
          <p style={{ fontSize:13.5, color:DT.c.textMuted, maxWidth:480, margin:'0 auto 22px', lineHeight:1.6 }}>
            {session.progressNotes.length} daily notes, labs and medications will be synthesised into a structured discharge summary. The AI only uses data you entered — anything missing is flagged <strong style={{color:DT.c.text}}>[INSUFFICIENT DATA]</strong>, never invented.
            {session.omitLabs && <span style={{ display:'block', marginTop:10, color:DT.c.warning }}><strong>Guardrail demo active:</strong> labs were omitted — watch section 4 flag rather than fabricate.</span>}
          </p>
          {busy
            ? <div style={{ display:'inline-flex', alignItems:'center', gap:10, color:DT.c.brand, fontSize:14 }}><Spinner/> Synthesising 10 sections…</div>
            : <RBtn kind="brand" icon="sparkle" size="lg" onClick={runSynthesis}>Synthesise discharge summary</RBtn>}
        </RCard>
        <StepNav onBack={onBack}/>
      </div>
    );
  }

  return <DReview session={session} sessionId={sessionId} onBack={onBack} onNext={onNext} onResynth={()=>{ store.updateSession(sessionId,{summary:null}); setSynth(false); }}/>;
}

function DReview({ session, sessionId, onBack, onNext, onResynth }) {
  const store = useRStore();
  const summary = session.summary;
  const edits = session.edits || {};
  const [editingKey, setEditingKey] = React.useState(null);
  const [draft, setDraft] = React.useState('');

  const value = (key) => edits[key] != null ? edits[key] : summary[key];
  const saveEdit = (key) => { store.updateSession(sessionId, s => ({ ...s, edits: { ...s.edits, [key]: draft } })); setEditingKey(null); };

  return (
    <div>
      <StepHead n={3} title="Review & edit" sub="Every section is editable. Sections flagged [INSUFFICIENT DATA] are highlighted — fill them in or re-synthesise."
        right={<RBtn kind="ghost" size="sm" icon="refresh" onClick={onResynth}>Re-synthesise</RBtn>}/>

      <div data-demo="rec-synth-banner" style={{ marginTop:8, marginBottom:14, padding:'10px 14px', background:DT.c.successTint, borderRadius:9, fontSize:12.5, color:'#15803D', display:'flex', alignItems:'center', gap:9 }}>
        <RIcon name="check" size={15} color={DT.c.success}/>
        <span><strong>Synthesised in 1.4s.</strong> What a resident writes in 30–45 min — for consultant review.</span>
      </div>

      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {window.PRD.sections.map(sec => {
          const raw = value(sec.key);
          const isSpecialty = sec.key === 'specialty';
          const insufficient = typeof raw === 'string' && raw.includes('[INSUFFICIENT DATA');
          return (
            <div key={sec.key} data-demo={'rec-sec-' + sec.key} style={{ background:DT.c.surface, border:`1px solid ${insufficient?DT.c.warning:DT.c.border}`, borderRadius:10, overflow:'hidden' }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:12, padding:'10px 16px', background: insufficient?DT.c.warningTint:DT.c.surface2, borderBottom:`1px solid ${DT.c.border}` }}>
                <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                  <span style={{ fontFamily:DT.f.mono, fontSize:10.5, fontWeight:700, color: insufficient?DT.c.warning:DT.c.textDim }}>{String(sec.n).padStart(2,'0')}</span>
                  <span style={{ fontSize:13, fontWeight:600 }}>{sec.title}</span>
                  {insufficient && <span style={{ fontSize:9.5, fontFamily:DT.f.mono, fontWeight:700, color:DT.c.warning, letterSpacing:'.06em' }}>FLAGGED</span>}
                </div>
                {!isSpecialty && editingKey!==sec.key && (
                  <button onClick={()=>{ setDraft(typeof raw==='string'?raw:''); setEditingKey(sec.key); }} style={{ border:'none', background:'transparent', cursor:'pointer', color:DT.c.accent, fontSize:11.5, fontWeight:500, display:'flex', alignItems:'center', gap:5, fontFamily:DT.f.sans }}><RIcon name="edit" size={12}/>Edit</button>
                )}
              </div>
              <div style={{ padding:'14px 16px' }}>
                {isSpecialty
                  ? <SpecialtySection data={raw}/>
                  : editingKey===sec.key
                    ? <div>
                        <RTextarea value={draft} onChange={setDraft} rows={5}/>
                        <div style={{ display:'flex', justifyContent:'flex-end', gap:8, marginTop:8 }}>
                          <RBtn kind="ghost" size="sm" onClick={()=>setEditingKey(null)}>Cancel</RBtn>
                          <RBtn kind="primary" size="sm" icon="check" onClick={()=>saveEdit(sec.key)}>Save</RBtn>
                        </div>
                      </div>
                    : <div style={{ fontSize:13, lineHeight:1.65, color: insufficient?DT.c.warning:DT.c.text, whiteSpace:'pre-wrap' }}>{raw}</div>}
              </div>
            </div>
          );
        })}
      </div>

      <StepNav onBack={onBack} onNext={onNext} nextLabel="Proceed to sign-off"/>
    </div>
  );
}

function SpecialtySection({ data }) {
  if (!data || typeof data !== 'object') return <div style={{ fontSize:13, color:DT.c.text }}>{String(data)}</div>;
  const rows = data._shape === 'OBGYN'
    ? [['Mother\u2019s postpartum status', data.maternalStatus], ['Newborn status', data.neonatalStatus], ['Feeding', data.feedingStatus], ['Contraception plan', data.contraceptionPlan]]
    : [['Weight-bearing', data.weightBearing], ['Implant record', data.implantRecord], ['Wound status', data.woundStatus], ['Range of motion', data.romAchieved], ['VTE prophylaxis', data.vteProphylaxis], ['Physiotherapy plan', data.physioPlan]];
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
      {rows.filter(r=>r[1]).map(([k,v],i)=>(
        <div key={i}>
          <div style={{ fontSize:10.5, fontFamily:DT.f.mono, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase', color: data._shape==='OBGYN'?'#BE185D':DT.c.accent, marginBottom:3 }}>{k}</div>
          <div style={{ fontSize:13, lineHeight:1.6, color:DT.c.text }}>{v}</div>
        </div>
      ))}
    </div>
  );
}

// ── STEP 4: Generate PDF (paper sign-off — no digital signature) ──
function DStepSign({ session, sessionId, onBack }) {
  const store = useRStore();
  const [showPdf, setShowPdf] = React.useState(session.pdfGenerated || false);

  if (showPdf) return <DPdfPreview session={session} onBack={()=>setShowPdf(false)}/>;

  return (
    <div>
      <StepHead n={4} title="Generate discharge PDF" sub="The reviewed summary is ready. The consultant signs the printed copy on paper — no digital signature is captured."/>
      <RCard style={{ marginTop:16 }}>
        <RLabel>Ready to generate</RLabel>
        <div style={{ marginTop:12, display:'flex', gap:14, alignItems:'flex-start' }}>
          <div style={{ width:40, height:40, borderRadius:10, background:DT.c.brandSoft, color:DT.c.brand, display:'grid', placeItems:'center', flexShrink:0 }}><RIcon name="discharge" size={20}/></div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:14.5, fontWeight:600 }}>{session.profile.patientIdentifier} · discharge summary</div>
            <div style={{ fontSize:12.5, color:DT.c.textMuted, marginTop:4, lineHeight:1.55 }}>
              10 sections · bilingual English + Kannada · ROHINI {window.PR.tenant.rohini} · NABH {window.PR.tenant.nabh}. The PDF carries a signature line for {session.doctorName} to sign on the printed copy.
            </div>
          </div>
        </div>
      </RCard>
      <StepNav onBack={onBack} customNext={<RBtn kind="brand" icon="download" onClick={()=>{ store.updateSession(sessionId,{pdfGenerated:true,completed:true}); setShowPdf(true); }}>Generate discharge PDF</RBtn>}/>
    </div>
  );
}

// ── Shared step helpers ───────────────────────────────────
function StepHead({ n, title, sub, right }) {
  return (
    <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:16 }}>
      <div>
        <div style={{ fontFamily:DT.f.mono, fontSize:10.5, color:DT.c.brand, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', marginBottom:6 }}>Step {n} of 4</div>
        <h2 style={{ fontSize:22, fontWeight:600, letterSpacing:'-.015em', margin:0 }}>{title}</h2>
        {sub && <p style={{ fontSize:13.5, color:DT.c.textMuted, marginTop:6, lineHeight:1.55, maxWidth:620 }}>{sub}</p>}
      </div>
      {right}
    </div>
  );
}
function StepNav({ onBack, onNext, nextLabel, customNext }) {
  return (
    <div style={{ display:'flex', justifyContent:'space-between', marginTop:24 }}>
      {onBack ? <RBtn kind="ghost" icon="left" onClick={onBack}>Back</RBtn> : <span/>}
      {customNext || (onNext && <RBtn kind="primary" iconRight="right" onClick={onNext}>{nextLabel || 'Continue'}</RBtn>)}
    </div>
  );
}
function HmsLoadedBanner({ text }) {
  return (
    <div style={{ marginTop:14, padding:'10px 14px', background:DT.c.brandSoft, borderRadius:9, fontSize:12.5, color:'#4C1D95', display:'flex', alignItems:'center', gap:9 }}>
      <RHmsBadge>HMS</RHmsBadge><span>{text}</span>
    </div>
  );
}
function Spinner() {
  return <svg width="18" height="18" viewBox="0 0 16 16" style={{ animation:'pcSpin 1s linear infinite' }}><circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="2" fill="none" strokeDasharray="20" opacity="0.3"/><path d="M14 8a6 6 0 00-6-6" stroke="currentColor" strokeWidth="2" fill="none"/></svg>;
}

Object.assign(window, { DischargePicker, DischargeWorkspace });
