// screen-counseling.jsx — Counseling Capture module.
// Picker (mode + patient) + stepped workspace:
//   1 Patient & risks · 2 Coverage & recording · 3 Review note · 4 Sign · 5 Consent PDF

const CT = window.PCT;

const NOTE_FIELDS = [
  ['patientUnderstanding','Patient understanding'],
  ['indication','Indication & urgency'],
  ['procedureExplained','Procedure explained'],
  ['risksDiscussed','Risks discussed'],
  ['patientSpecificRisks','Patient-specific risks'],
  ['alternativesDiscussed','Alternatives discussed'],
  ['anaesthesiaPlan','Anaesthesia plan'],
  ['bloodProducts','Blood products'],
  ['questionsRaised','Questions raised'],
  ['consentVoluntariness','Consent & voluntariness'],
  ['languageUsed','Language used'],
  ['additionalNotes','Additional notes'],
];

// ════════════════════════════════════════════════════════
// PICKER
// ════════════════════════════════════════════════════════
function CounselingPicker() {
  const store = useRStore();
  const mode = store.state.mode;
  const [entryMode, setEntryMode] = React.useState('EMERGENCY');
  const profiles = window.PRC.profiles;

  const start = (p) => {
    const id = store.createSession('counseling', {
      profileId:p.id, specialty:p.specialty, procedure:p.procedure, counselingMode:entryMode,
      profile:{ ...p.profile }, narrative:p.narrative, note:null, step:1, confirmed:false,
    });
    rNav('#/counseling/' + id);
  };

  return (
    <RShell crumb={['Counseling Capture']}>
      <div style={{ maxWidth:1000, margin:'0 auto', padding:'36px 28px 100px' }}>
        <h1 style={{ fontSize:26, fontWeight:600, letterSpacing:'-.02em', margin:0 }}>Start a counselling session</h1>
        <p style={{ fontSize:14, color:CT.c.textMuted, marginTop:8, lineHeight:1.55, maxWidth:640 }}>
          Capture the informed-consent conversation and produce structured, signed medico-legal evidence. Pick how you want to enter the patient, then choose the case.
        </p>

        {/* Entry mode */}
        <div style={{ marginTop:22, display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
          <ModeOption active={entryMode==='EMERGENCY'} onClick={()=>setEntryMode('EMERGENCY')}
            icon="mic" title="Emergency Mode" desc="Speak a 15–30s patient narrative; AI parses it into a profile in seconds. For time-critical cases."/>
          <ModeOption active={entryMode==='ROUTINE'} onClick={()=>setEntryMode('ROUTINE')}
            icon="edit" title="Routine Mode" desc="Enter the patient on a form, optionally pre-filled from the case. For planned procedures."/>
        </div>

        {mode==='integrated' && (
          <div style={{ display:'flex', alignItems:'center', gap:9, margin:'18px 0 0', padding:'10px 14px', background:CT.c.brandSoft, borderRadius:9, fontSize:12.5, color:'#4C1D95' }}>
            <RHmsBadge>HMS</RHmsBadge><span>In integrated mode the patient list comes from current HMS admissions — demographics pre-fill automatically.</span>
          </div>
        )}

        {/* Patient cards by specialty */}
        {['OBGYN','ORTHO'].map(spec => {
          const group = profiles.filter(p => p.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:CT.c.textMuted }}>{sp.label}</span>{!sp.validated && <RUnverifiedBadge small/>}
                <div style={{ flex:1, height:1, background:CT.c.border }}/>
              </div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
                {group.map(p => {
                  const proc = window.PR.procedures[p.procedure];
                  return (
                    <div key={p.id} onClick={()=>start(p)} style={{ background:CT.c.surface, border:`1px solid ${CT.c.border}`, borderRadius:12, padding:18, cursor:'pointer' }}
                      onMouseEnter={e=>{ e.currentTarget.style.borderColor=CT.c.brand; e.currentTarget.style.boxShadow='0 6px 16px -8px rgba(0,0,0,.12)'; }}
                      onMouseLeave={e=>{ e.currentTarget.style.borderColor=CT.c.border; e.currentTarget.style.boxShadow='none'; }}>
                      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:10 }}>
                        <div>
                          <div style={{ fontSize:15, fontWeight:600 }}>{p.profile.patientIdentifier}</div>
                          <div style={{ fontSize:11, color:CT.c.textMuted, fontFamily:CT.f.mono, marginTop:2 }}>{p.profile.uhid} · {p.profile.age}{p.profile.gender}</div>
                        </div>
                        {mode==='integrated' && <RHmsBadge source="patient">HMS</RHmsBadge>}
                      </div>
                      <div style={{ fontSize:12.5, color:CT.c.text, marginTop:10 }}>{proc.label}</div>
                      <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:12, paddingTop:12, borderTop:`1px solid ${CT.c.border}` }}>
                        <span style={{ fontSize:11, color:CT.c.textDim, fontFamily:CT.f.mono }}>{proc.urgency==='EMERGENCY'?'Emergency':'Elective'} · {entryMode==='EMERGENCY'?'voice':'form'} entry</span>
                        <div style={{ flex:1 }}/>
                        <span style={{ display:'flex', alignItems:'center', gap:4, fontSize:12, color:CT.c.brand, fontWeight:500 }}>Start <RIcon name="right" size={13} color={CT.c.brand}/></span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </RShell>
  );
}

function ModeOption({ active, onClick, icon, title, desc }) {
  return (
    <div onClick={onClick} style={{ background: active?CT.c.brandSoft:CT.c.surface, border:`2px solid ${active?CT.c.brand:CT.c.border}`, borderRadius:12, padding:'16px 18px', cursor:'pointer', display:'flex', gap:14, alignItems:'flex-start' }}>
      <div style={{ width:38, height:38, borderRadius:10, background: active?CT.c.brand:CT.c.surface2, color: active?'#fff':CT.c.textMuted, display:'grid', placeItems:'center', flexShrink:0 }}><RIcon name={icon} size={18}/></div>
      <div>
        <div style={{ fontSize:14.5, fontWeight:600, color: active?CT.c.brand:CT.c.text }}>{title}</div>
        <div style={{ fontSize:12.5, color:CT.c.textMuted, marginTop:3, lineHeight:1.5 }}>{desc}</div>
      </div>
    </div>
  );
}

// ════════════════════════════════════════════════════════
// WORKSPACE
// ════════════════════════════════════════════════════════
function CounselingWorkspace({ sessionId }) {
  const store = useRStore();
  const session = store.getSession(sessionId);
  if (!session) { rNav('#/counseling'); return null; }
  const step = session.step || 1;
  const setStep = (n) => store.updateSession(sessionId, { step:n });
  const sp = window.PR.specialties[session.specialty];

  const steps = [
    { n:1, label:'Patient & risks' },
    { n:2, label:'Coverage & recording' },
    { n:3, label:'Review note' },
    { n:4, label:'Consent PDF' },
  ];

  return (
    <RShell crumb={['Counseling Capture', session.profile.patientIdentifier]}
      headerRight={<div style={{ display:'flex', alignItems:'center', gap:10 }}><RSpecChip specialty={session.specialty}/>{!sp.validated && <RUnverifiedBadge small/>}</div>}>
      <div style={{ display:'grid', gridTemplateColumns:'220px 1fr', minHeight:'calc(100vh - 60px)' }}>
        <div style={{ borderRight:`1px solid ${CT.c.border}`, background:CT.c.surface, padding:'24px 16px' }}>
          <div style={{ marginBottom:18, padding:'0 8px' }}>
            <div style={{ fontSize:13.5, fontWeight:600 }}>{session.profile.patientIdentifier}</div>
            <div style={{ fontSize:11, color:CT.c.textMuted, fontFamily:CT.f.mono, marginTop:2 }}>{session.profile.uhid}</div>
            <div style={{ marginTop:8, display:'inline-flex', alignItems:'center', gap:5, padding:'2px 8px', borderRadius:5, background:CT.c.surface2, fontSize:10.5, fontFamily:CT.f.mono, color:CT.c.textMuted }}>
              <RIcon name={session.counselingMode==='EMERGENCY'?'mic':'edit'} size={11}/>{session.counselingMode==='EMERGENCY'?'Emergency':'Routine'} mode
            </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?CT.c.brandSoft:'transparent', color: cur?CT.c.brand:done?CT.c.text:CT.c.textMuted, textAlign:'left', fontFamily:CT.f.sans }}>
                  <span style={{ width:22, height:22, borderRadius:'50%', flexShrink:0, display:'grid', placeItems:'center', background: done?CT.c.success:cur?CT.c.brand:'#fff', color: done||cur?'#fff':CT.c.textMuted, border: done||cur?'0':`1.5px solid ${CT.c.borderStrong}`, fontFamily:CT.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="#/counseling" style={{ fontSize:11.5, color:CT.c.textMuted, textDecoration:'none', display:'flex', alignItems:'center', gap:5 }}><RIcon name="left" size={12} color={CT.c.textMuted}/>All patients</a>
          </div>
        </div>
        <div style={{ overflow:'auto', padding:'28px 32px 100px', maxWidth:1000 }}>
          {step===1 && <CStepPatient session={session} sessionId={sessionId} onNext={()=>setStep(2)}/>}
          {step===2 && <CStepRecord session={session} sessionId={sessionId} onBack={()=>setStep(1)} onNext={()=>setStep(3)}/>}
          {step===3 && <CStepReview session={session} sessionId={sessionId} onBack={()=>setStep(2)} onNext={()=>setStep(4)}/>}
          {step===4 && <CStepConsent session={session} sessionId={sessionId} onBack={()=>setStep(3)}/>}
        </div>
      </div>
    </RShell>
  );
}

// ── STEP 1: Patient & risk derivation ─────────────────────
function CStepPatient({ session, sessionId, onNext }) {
  const store = useRStore();
  const mode = store.state.mode;
  const isEmergency = session.counselingMode==='EMERGENCY';
  const [parsing, setParsing] = React.useState(false);
  const [parsed, setParsed] = React.useState(session.confirmed);

  const risks = window.PR.deriveRisks(session.profile, session.specialty);

  const doParse = () => { setParsing(true); setTimeout(()=>{ setParsing(false); setParsed(true); store.updateSession(sessionId,{confirmed:true}); }, 1400); };

  return (
    <div>
      <CHead n={1} title={isEmergency?'Voice quick-load & risk derivation':'Patient profile & risk derivation'}
        sub={isEmergency?'Speak the patient narrative; AI extracts the profile. Then the rule engine derives patient-specific risks.':'Profile pre-filled from the case. The rule engine derives patient-specific risks live.'}/>

      {isEmergency && !parsed && (
        <RCard style={{ marginTop:16 }}>
          <RLabel>Patient narrative {mode==='integrated' && <RHmsBadge source="patient">HMS-prefilled</RHmsBadge>}</RLabel>
          <div style={{ marginTop:12, padding:'14px 16px', background:CT.c.surface2, borderRadius:9, display:'flex', gap:14, alignItems:'center' }}>
            <div style={{ width:44, height:44, borderRadius:'50%', background: parsing?CT.c.brand:CT.c.brandSoft, color: parsing?'#fff':CT.c.brand, display:'grid', placeItems:'center', flexShrink:0, animation: parsing?'pcSpin 1.2s linear infinite':'none' }}><RIcon name="mic" size={20}/></div>
            <div style={{ flex:1, fontSize:13.5, color:CT.c.text, lineHeight:1.55, fontStyle:'italic' }}>"{session.narrative}"</div>
          </div>
          <div style={{ marginTop:14, display:'flex', justifyContent:'flex-end' }}>
            {parsing ? <span style={{ display:'inline-flex', alignItems:'center', gap:9, color:CT.c.brand, fontSize:13.5 }}><Spinner/> Parsing narrative into profile…</span>
              : <RBtn kind="brand" icon="sparkle" onClick={doParse}>Parse narrative with AI</RBtn>}
          </div>
        </RCard>
      )}

      {(!isEmergency || parsed) && (
        <>
          <RCard style={{ marginTop:16 }}>
            <RLabel>Patient profile {mode==='integrated' && <RHmsBadge source="patient">HMS</RHmsBadge>} {isEmergency && parsed && <span style={{ fontSize:10.5, color:CT.c.success, fontFamily:CT.f.mono }}>· extracted</span>}</RLabel>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginTop:14 }}>
              <PField label="Name" value={session.profile.patientIdentifier} wide/>
              <PField label="Age / Sex" value={`${session.profile.age} / ${session.profile.gender}`}/>
              {session.specialty==='OBGYN' ? <>
                <PField label="Obstetric" value={session.profile.parity}/>
                <PField label="GA (wk)" value={session.profile.gestationalAgeWeeks}/>
                <PField label="Prior LSCS" value={session.profile.priorCaesareans}/>
                <PField label="BMI" value={session.profile.bmi}/>
                <PField label="Hb" value={session.profile.hb}/>
              </> : <>
                <PField label="BMI" value={session.profile.bmi}/>
                <PField label="ASA" value={session.profile.asa}/>
                <PField label="Hb" value={session.profile.hb}/>
              </>}
            </div>
            {session.profile.conditions?.length>0 && (
              <div style={{ marginTop:14, display:'flex', flexWrap:'wrap', gap:6 }}>
                {session.profile.conditions.map(c => <span key={c} style={{ fontSize:11, fontFamily:CT.f.mono, padding:'2px 8px', borderRadius:5, background:CT.c.surface2, color:CT.c.text }}>{c}</span>)}
              </div>
            )}
          </RCard>

          <div data-demo="rec-risks" style={{ marginTop:16 }}>
            <RLabel right={<span style={{ fontSize:11, color:CT.c.textMuted }}>{risks.length} flags from rule engine</span>}>Derived patient-specific risks</RLabel>
            <div style={{ display:'flex', flexDirection:'column', gap:8, marginTop:12 }}>
              {risks.length===0 ? <div style={{ fontSize:13, color:CT.c.textMuted, padding:'8px 0' }}>No elevated risk flags for this profile.</div>
                : risks.map(r => <RRiskFlag key={r.id} risk={r}/>)}
            </div>
          </div>

          <CNav onNext={onNext} nextLabel="Continue to counselling"/>
        </>
      )}
    </div>
  );
}

function PField({ label, value, wide }) {
  return (
    <div style={{ gridColumn: wide?'span 2':'auto' }}>
      <div style={{ fontFamily:CT.f.mono, fontSize:9.5, fontWeight:600, letterSpacing:'.08em', textTransform:'uppercase', color:CT.c.textMuted, marginBottom:5 }}>{label}</div>
      <div style={{ fontSize:13.5, fontWeight:500 }}>{value}</div>
    </div>
  );
}

// ── STEP 2: Coverage template + recording ─────────────────
function CStepRecord({ session, sessionId, onBack, onNext }) {
  const store = useRStore();
  const proc = window.PR.procedures[session.procedure];
  const [phase, setPhase] = React.useState(session.note ? 'done' : 'idle'); // idle | recording | processing | done
  const [secs, setSecs] = React.useState(0);
  const timer = React.useRef(null);

  React.useEffect(()=>()=>clearInterval(timer.current), []);

  const startRec = () => { setPhase('recording'); setSecs(0); timer.current = setInterval(()=>setSecs(s=>s+1), 1000); };
  const stopRec = () => {
    clearInterval(timer.current); setPhase('processing');
    setTimeout(()=>{
      const p = window.PRC.findProfile(session.profileId);
      store.updateSession(sessionId, { note: { ...p.note }, recordingSecs: secs });
      setPhase('done');
    }, 1800);
  };

  return (
    <div>
      <CHead n={2} title="Coverage & counselling recording" sub="The required coverage areas are shown. Record the counselling — then AI extracts the 12-field structured note."/>

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14, marginTop:16 }}>
        {/* Coverage template */}
        <RCard>
          <RLabel>{proc.short} · required coverage</RLabel>
          <div style={{ marginTop:12, display:'flex', flexDirection:'column', gap:7 }}>
            {proc.coverageAreas.map((a,i)=>(
              <div key={i} style={{ display:'flex', gap:9, alignItems:'flex-start', fontSize:12.5, lineHeight:1.45 }}>
                <span style={{ width:18, height:18, borderRadius:5, background:CT.c.surface2, color:CT.c.textMuted, display:'grid', placeItems:'center', flexShrink:0, fontFamily:CT.f.mono, fontSize:9.5, fontWeight:600, marginTop:1 }}>{i+1}</span>
                <span>{a}</span>
              </div>
            ))}
          </div>
          {!window.PR.specialties[session.specialty].validated && <div style={{ marginTop:12 }}><RUnverifiedBadge small/></div>}
        </RCard>

        {/* Recorder */}
        <RCard>
          <RLabel>Counselling recording</RLabel>
          <div data-demo="rec-record" style={{ marginTop:14, display:'flex', flexDirection:'column', alignItems:'center', gap:16, padding:'14px 0' }}>
            <Waveform active={phase==='recording'}/>
            <div style={{ fontFamily:CT.f.mono, fontSize:28, fontWeight:600, color: phase==='recording'?CT.c.error:CT.c.text, fontVariantNumeric:'tabular-nums' }}>
              {String(Math.floor(secs/60)).padStart(2,'0')}:{String(secs%60).padStart(2,'0')}
            </div>
            {phase==='idle' && <RBtn kind="danger" icon="mic" size="lg" onClick={startRec}>Start recording</RBtn>}
            {phase==='recording' && <RBtn kind="dark" icon="stop" size="lg" onClick={stopRec}>Stop &amp; analyse</RBtn>}
            {phase==='processing' && <span style={{ display:'inline-flex', alignItems:'center', gap:9, color:CT.c.brand, fontSize:13.5 }}><Spinner/> Transcribing &amp; extracting note…</span>}
            {phase==='done' && <div style={{ display:'flex', alignItems:'center', gap:8, color:CT.c.success, fontSize:13.5, fontWeight:500 }}><RIcon name="check" size={16} color={CT.c.success}/>Structured note extracted</div>}
          </div>
          {phase==='idle' && <div style={{ fontSize:11.5, color:CT.c.textDim, textAlign:'center', lineHeight:1.5 }}>Counsel the family in mixed English–Kannada covering the areas on the left. Demo: any duration works; the note is pre-validated for this case.</div>}
        </RCard>
      </div>

      <CNav onBack={onBack} customNext={phase==='done' && <RBtn kind="primary" iconRight="right" onClick={onNext}>Review structured note</RBtn>}/>
    </div>
  );
}

function Waveform({ active }) {
  const bars = 32;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:3, height:56 }}>
      {Array.from({length:bars}).map((_,i)=>(
        <div key={i} style={{ width:4, borderRadius:2, background: active?CT.c.brand:CT.c.border,
          height: active ? `${20+Math.abs(Math.sin(i*0.9+Date.now()*0.005))*32}px` : '6px',
          animation: active?`pcWave 0.8s ease-in-out ${i*0.04}s infinite alternate`:'none' }}/>
      ))}
    </div>
  );
}

// ── STEP 3: Review structured note ────────────────────────
function CStepReview({ session, sessionId, onBack, onNext }) {
  const store = useRStore();
  const note = session.note || {};
  const edits = session.noteEdits || {};
  const [editKey, setEditKey] = React.useState(null);
  const [draft, setDraft] = React.useState('');
  const v = (k) => edits[k] != null ? edits[k] : note[k];
  const save = (k) => { store.updateSession(sessionId, s => ({ ...s, noteEdits:{ ...s.noteEdits, [k]:draft } })); setEditKey(null); };

  return (
    <div>
      <CHead n={3} title="Review structured note" sub="The 12-field medico-legal note extracted from the counselling. Verify each field; edit any if needed."/>
      <div style={{ marginTop:8, marginBottom:14, padding:'10px 14px', background:CT.c.successTint, borderRadius:9, fontSize:12.5, color:'#15803D', display:'flex', alignItems:'center', gap:9 }}>
        <RIcon name="check" size={15} color={CT.c.success}/><span><strong>12 fields extracted.</strong> Each maps to the procedure coverage and the derived patient-specific risks.</span>
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
        {NOTE_FIELDS.map(([key,label]) => {
          const highlight = key==='patientSpecificRisks';
          return (
            <div key={key} data-demo={highlight ? 'rec-note' : undefined} style={{ background:CT.c.surface, border:`1px solid ${highlight?CT.c.brand:CT.c.border}`, borderRadius:10, padding:'12px 14px' }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:6 }}>
                <span style={{ fontFamily:CT.f.mono, fontSize:9.5, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase', color: highlight?CT.c.brand:CT.c.textMuted }}>{label}</span>
                {editKey!==key && <button onClick={()=>{ setDraft(v(key)); setEditKey(key); }} style={{ border:'none', background:'transparent', cursor:'pointer', color:CT.c.accent, fontSize:11 }}><RIcon name="edit" size={12}/></button>}
              </div>
              {editKey===key
                ? <div><RTextarea value={draft} onChange={setDraft} rows={4}/><div style={{ display:'flex', justifyContent:'flex-end', gap:6, marginTop:6 }}><RBtn kind="ghost" size="sm" onClick={()=>setEditKey(null)}>Cancel</RBtn><RBtn kind="primary" size="sm" icon="check" onClick={()=>save(key)}>Save</RBtn></div></div>
                : <div style={{ fontSize:12.5, lineHeight:1.55, color:CT.c.text }}>{v(key)}</div>}
            </div>
          );
        })}
      </div>
      <CNav onBack={onBack} onNext={onNext} nextLabel="Proceed to signing"/>
    </div>
  );
}

// ── STEP 4: Multi-party signing ───────────────────────────
function CStepSign({ session, sessionId, onBack, onNext }) {
  const store = useRStore();
  const signers = [
    { role:'Doctor', name:session.doctorName, sub:session.doctorReg },
    { role:'Patient', name:session.profile.patientIdentifier, sub:session.profile.uhid },
    { role:'Witness', name:'K. Ramachandran (attendant)', sub:'Relationship: family' },
  ];
  const signed = session.signatures || [];
  const nextIdx = signed.length;
  const [sig, setSig] = React.useState(null);

  const doSign = () => {
    store.addSignature(sessionId, { role:signers[nextIdx].role, name:signers[nextIdx].name, dataUrl:sig, at:Date.now() });
    setSig(null);
    if (nextIdx+1 >= signers.length) store.updateSession(sessionId, { completed:true });
  };

  return (
    <div>
      <CHead n={4} title="Multi-party signing" sub="Sequential signing — doctor, then patient, then witness. Each signature is timestamped."/>
      <div style={{ display:'flex', gap:10, marginTop:16 }}>
        {signers.map((s,i)=>{
          const done = i < signed.length, cur = i === nextIdx;
          return (
            <div key={i} style={{ flex:1, padding:'14px 16px', borderRadius:10, border:`1px solid ${cur?CT.c.brand:CT.c.border}`, background: done?CT.c.successTint:cur?CT.c.brandSoft:CT.c.surface }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                <span style={{ fontSize:11, fontFamily:CT.f.mono, fontWeight:600, letterSpacing:'.06em', textTransform:'uppercase', color: done?CT.c.success:cur?CT.c.brand:CT.c.textMuted }}>{s.role}</span>
                {done && <RIcon name="check" size={15} color={CT.c.success}/>}
              </div>
              <div style={{ fontSize:13, fontWeight:600, marginTop:6 }}>{s.name}</div>
              <div style={{ fontSize:11, color:CT.c.textMuted, fontFamily:CT.f.mono }}>{s.sub}</div>
              {done && signed[i].dataUrl && <img src={signed[i].dataUrl} alt="" style={{ height:36, marginTop:8, background:'#fff', borderRadius:5, padding:3, border:`1px solid ${CT.c.border}` }}/>}
            </div>
          );
        })}
      </div>

      {nextIdx < signers.length ? (
        <RCard style={{ marginTop:16 }}>
          <RLabel>Signing now · {signers[nextIdx].role} — {signers[nextIdx].name}</RLabel>
          <div style={{ marginTop:12 }}><RSignaturePad onCapture={setSig}/></div>
          <div style={{ display:'flex', justifyContent:'flex-end', marginTop:12 }}>
            <RBtn kind="primary" icon="pen" disabled={!sig} onClick={doSign}>Capture {signers[nextIdx].role.toLowerCase()} signature</RBtn>
          </div>
        </RCard>
      ) : (
        <div style={{ marginTop:16, padding:'14px 16px', background:CT.c.successTint, borderRadius:9, fontSize:13, color:'#15803D', display:'flex', alignItems:'center', gap:9 }}>
          <RIcon name="check" size={16} color={CT.c.success}/><span>All three parties signed. Consent is complete.</span>
        </div>
      )}

      <CNav onBack={onBack} customNext={nextIdx>=signers.length && <RBtn kind="brand" icon="download" onClick={onNext}>Generate consent PDF</RBtn>}/>
    </div>
  );
}

// ── STEP 4: Consent PDF (consent is signed on paper — no digital signature) ──
function CStepConsent({ session, sessionId, onBack }) {
  const store = useRStore();
  const proc = window.PR.procedures[session.procedure];
  const risks = window.PR.deriveRisks(session.profile, session.specialty);
  const note = { ...(session.note||{}), ...(session.noteEdits||{}) };
  const K = window.PR.kannada;
  const sp = window.PR.specialties[session.specialty];

  React.useEffect(()=>{ if(!session.completed){ store.updateSession(sessionId, { completed:true }); } }, []);

  return (
    <div>
      <CHead n={4} title="Signed consent · PDF" sub="Bilingual English + Kannada informed-consent record with patient-specific risks emphasised. Signed on the printed copy by doctor, patient and witness."
        right={<div style={{ display:'flex', gap:8 }}>
          <RBtn kind="ghost" icon="left" onClick={onBack}>Back</RBtn>
          <RBtn kind="primary" icon="download" onClick={()=>store.toast({icon:'download', title:'Consent PDF downloaded', body:'Demo placeholder file'})}>Download PDF</RBtn>
        </div>}/>

      {!sp.validated && <div style={{ marginTop:14, padding:'10px 14px', background:'#FEF3C7', borderRadius:9, fontSize:12, color:'#92400E', display:'flex', alignItems:'center', gap:9 }}><RIcon name="alert" size={15} color="#B45309"/><span><strong>Unverified specialty.</strong> Orthopaedic risk content pending clinical validation.</span></div>}

      {/* Continue-to-discharge link */}
      <div style={{ marginTop:14, padding:'12px 16px', background:CT.c.brandSoft, borderRadius:10, display:'flex', alignItems:'center', gap:12 }}>
        <div style={{ width:34, height:34, borderRadius:8, background:'#fff', color:CT.c.brand, display:'grid', placeItems:'center', flexShrink:0 }}><RIcon name="link" size={17}/></div>
        <div style={{ flex:1, fontSize:12.5, color:'#4C1D95', lineHeight:1.5 }}>
          <strong>Continue to discharge later?</strong> Link this counselling to the patient's admission so the discharge summary references it.
        </div>
        {session.patientAdmissionId
          ? <span style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:CT.c.success, fontWeight:500 }}><RIcon name="check" size={15} color={CT.c.success}/>Linked · {session.patientAdmissionId}</span>
          : <RBtn kind="brand" size="sm" icon="link" onClick={()=>{ const pid=store.linkForDischarge(sessionId); store.toast({icon:'link', title:'Linked to admission', body:`Use "Import from counselling" in Discharge · ${pid}`}); }}>Link for discharge</RBtn>}
      </div>

      {/* Consent document */}
      <div style={{ marginTop:18, display:'flex', flexDirection:'column', gap:20, alignItems:'center' }}>
        <ConsentPage kannada={false} session={session} proc={proc} risks={risks} note={note} K={K}/>
        <ConsentPage kannada={true} session={session} proc={proc} risks={risks} note={note} K={K}/>
      </div>

      <div style={{ display:'flex', justifyContent:'center', gap:10, marginTop:24 }}>
        <a href="#/" style={{ textDecoration:'none' }}><RBtn kind="ghost" icon="home">Back to home</RBtn></a>
      </div>
    </div>
  );
}

function ConsentPage({ kannada, session, proc, risks, note, K }) {
  const t = window.PR.tenant;
  const kf = kannada ? "'Noto Sans Kannada', sans-serif" : CT.f.sans;
  const deKn = window.PR.deKn;
  // Kannada body comes from the pre-translated consent block; English from the note.
  const kn = kannada ? (window.PRC_NOTE_KN || {})[session.profileId] || {} : {};
  const F = (key) => kannada ? deKn(kn[key] || note[key]) : note[key];
  return (
    <div style={{ width:'100%', maxWidth:760, background:'#fff', border:`1px solid ${CT.c.border}`, borderRadius:8, boxShadow:'0 4px 16px -6px rgba(0,0,0,.1)', padding:'40px 48px' }}>
      <div style={{ borderBottom:`2px solid ${CT.c.text}`, paddingBottom:14, marginBottom:18, display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
        <div>
          <div style={{ fontSize:18, fontWeight:700 }}>{t.name}</div>
          <div style={{ fontSize:10.5, color:CT.c.textMuted, fontFamily:CT.f.mono, marginTop:3 }}>ROHINI {t.rohini} · {t.addressLine}</div>
        </div>
        <div style={{ fontSize:13, fontWeight:700, color:CT.c.brand, fontFamily:kf, textAlign:'right' }}>{kannada?K.consentTitle:'INFORMED CONSENT'}</div>
      </div>

      <div style={{ fontSize:11.5, lineHeight:1.7, color:'#1F1B16', fontFamily:kf }}>
        <p style={{ margin:'0 0 10px' }}>
          <strong>{kannada?K.patient:'Patient'}:</strong> {session.profile.patientIdentifier} ({session.profile.uhid}) · {session.profile.age}{session.profile.gender}<br/>
          <strong>{kannada?K.procedure:'Procedure'}:</strong> {proc.label}<br/>
          <strong>{kannada?K.doctor:'Doctor'}:</strong> {session.doctorName} ({session.doctorReg})
        </p>
        <p style={{ margin:'0 0 6px' }}><strong>{kannada?'ಸೂಚನೆ':'Indication'}:</strong> {F('indication')}</p>
        <p style={{ margin:'0 0 6px' }}><strong>{kannada?'ಶಸ್ತ್ರಚಿಕಿತ್ಸೆ ವಿವರ':'Procedure explained'}:</strong> {F('procedureExplained')}</p>

        <div style={{ marginTop:10, marginBottom:6, fontWeight:700, color:CT.c.brand }}>{kannada?K.risks:'Patient-specific risks counselled'}</div>
        <div data-demo="rec-consent" style={{ padding:'10px 12px', background:CT.c.brandSoft, borderRadius:7, fontWeight:600 }}>{F('patientSpecificRisks')}</div>
        {!kannada && (
          <ul style={{ margin:'10px 0', paddingLeft:18 }}>
            {risks.map(r => <li key={r.id} style={{ marginBottom:3 }}><strong>{r.description}</strong></li>)}
          </ul>
        )}
        <p style={{ margin:'10px 0 6px' }}><strong>{kannada?'ಸಾಮಾನ್ಯ ಅಪಾಯಗಳು':'General risks discussed'}:</strong> {F('risksDiscussed')}</p>
        <p style={{ margin:'0 0 6px' }}><strong>{kannada?'ಪರ್ಯಾಯಗಳು':'Alternatives'}:</strong> {F('alternativesDiscussed')}</p>
        <p style={{ margin:'0 0 6px' }}><strong>{kannada?'ಅರಿವಳಿಕೆ':'Anaesthesia'}:</strong> {F('anaesthesiaPlan')}</p>
        <p style={{ margin:'0 0 6px' }}><strong>{kannada?'ಸಮ್ಮತಿ':'Consent & voluntariness'}:</strong> {F('consentVoluntariness')}</p>
      </div>

      {/* Signature lines — signed on the printed copy (paper) */}
      <div style={{ marginTop:24, paddingTop:16, borderTop:`1px solid ${CT.c.border}`, display:'flex', justifyContent:'space-between', gap:16 }}>
        {[['Doctor',K.doctor],['Patient',K.patient],['Witness',K.witness]].map(([role,kl],i)=>(
          <div key={i} style={{ flex:1, textAlign:'center' }}>
            <div style={{ height:40 }}/>
            <div style={{ borderTop:`1px solid ${CT.c.text}`, paddingTop:4, fontSize:10.5, fontWeight:600, fontFamily:kf }}>{kannada?kl:role}</div>
            <div style={{ fontSize:8.5, color:CT.c.textDim, fontFamily:CT.f.mono, marginTop:2 }}>{kannada?'ಸಹಿ / ದಿನಾಂಕ':'Signature / Date'}</div>
          </div>
        ))}
      </div>
      <div style={{ marginTop:16, fontSize:9, color:CT.c.textDim, fontFamily:CT.f.mono, textAlign:'center' }}>{kannada?'ಪುಟ 2 (ಕನ್ನಡ)':'Page 1 (English)'} · PulseChart Record · demo document</div>
    </div>
  );
}

// ── helpers ───────────────────────────────────────────────
function CHead({ n, title, sub, right }) {
  return (
    <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:16 }}>
      <div>
        <div style={{ fontFamily:CT.f.mono, fontSize:10.5, color:CT.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:CT.c.textMuted, marginTop:6, lineHeight:1.55, maxWidth:640 }}>{sub}</p>}
      </div>
      {right}
    </div>
  );
}
function CNav({ 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 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, { CounselingPicker, CounselingWorkspace });
