/* screens-2.jsx — Vitals, AI Analysis, Doctor Selection, Ticket */

// ────────────────────────────────────────────────────────────
// 4. VITALS — connect to devices and read realtime
// ────────────────────────────────────────────────────────────
function ScreenVitals({ scenario, onNext }) {
  const [phase, setPhase] = useState('intro'); // intro → measuring → done
  const [progress, setProgress] = useState(0);
  const v = scenario.vitals;
  const flags = scenario.vitalsFlags || {};

  useEffect(() => {
    if (phase !== 'measuring') return;
    let p = 0;
    const t = setInterval(() => {
      p += 4;
      setProgress(p);
      if (p >= 100) { clearInterval(t); setTimeout(() => setPhase('done'), 400); }
    }, 80);
    return () => clearInterval(t);
  }, [phase]);

  return (
    <ScreenShell title="วัดสัญญาณชีพ" subtitle="เครื่องมือเชื่อมต่อกับ Bluetooth medical devices">
      {phase === 'intro' && (
        <div className="flex flex-col gap-5 sm:gap-7 mt-6 sm:mt-8">
          <KCard padding={36}>
            <div className="font-semibold text-lg sm:text-2xl lg:text-3xl leading-tight" style={{ color: K.ink, marginBottom: 24 }}>โปรดทำตามขั้นตอน</div>
            <DeviceStep n={1} icon="ph-thermometer-simple" title="วัดอุณหภูมิ" sub="วางหน้าผากใกล้เซนเซอร์ด้านบนของจอ"/>
            <DeviceStep n={2} icon="ph-cuff" title="วัดความดันโลหิต" sub="สวมปลอกแขนที่แขนขวา · เครื่องจะปั๊มอัตโนมัติ"/>
            <DeviceStep n={3} icon="ph-heartbeat" title="วัดอัตราการเต้นของหัวใจ + SpO₂" sub="หนีบนิ้วชี้ในเครื่อง pulse oximeter"/>
            <DeviceStep n={4} icon="ph-scales" title="ชั่งน้ำหนัก" sub="ยืนบนแผ่นชั่งด้านหน้าตู้ (ถ้าสะดวก)" last/>
          </KCard>
          <div className="flex justify-between gap-4">
            <KButton variant="secondary" size="lg" onClick={onNext}>ข้ามขั้นตอนนี้</KButton>
            <KButton size="lg" onClick={() => setPhase('measuring')} iconRight="ph-play">เริ่มวัด</KButton>
          </div>
        </div>
      )}

      {phase === 'measuring' && (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 40, paddingTop: 60 }}>
          <div style={{ position: 'relative', width: 320, height: 320 }}>
            <svg viewBox="0 0 100 100" style={{ width: '100%', height: '100%', transform: 'rotate(-90deg)' }}>
              <circle cx="50" cy="50" r="44" fill="none" stroke={K.line} strokeWidth="6"/>
              <circle cx="50" cy="50" r="44" fill="none" stroke={K.primary900} strokeWidth="6"
                strokeLinecap="round"
                strokeDasharray={`${276.5 * progress / 100} 276.5`}
                style={{ transition: 'stroke-dasharray .15s' }}/>
            </svg>
            <div style={{
              position: 'absolute', inset: 0, display: 'flex',
              flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            }}>
              <i className="ph-fill ph-heartbeat" style={{ fontSize: 64, color: K.coral, animation: 'kiosk-pulse 1s infinite' }}></i>
              <div className="font-bold text-3xl sm:text-5xl lg:text-6xl leading-none" style={{ color: K.ink, marginTop: 10 }}>{progress}%</div>
            </div>
          </div>
          <div className="font-medium text-xl sm:text-3xl lg:text-4xl leading-snug" style={{ color: K.ink2, textAlign: 'center' }}>
            {progress < 30 ? 'กำลังวัดอุณหภูมิ...' :
             progress < 60 ? 'กำลังวัดความดันโลหิต...' :
             progress < 90 ? 'กำลังวัด SpO₂...' : 'กำลังประมวลผล...'}
            <div className="font-normal text-base sm:text-lg lg:text-xl leading-snug" style={{ color: K.meta, marginTop: 8 }}>
              โปรดอยู่นิ่ง ๆ ระหว่างการวัด
            </div>
          </div>
        </div>
      )}

      {phase === 'done' && (
        <div style={{ marginTop: 24 }}>
          <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-none flex items-center gap-4 rounded-[20px] mb-5 sm:mb-7 px-5 py-4 sm:px-7 sm:py-5" style={{
            background: K.successBg, color: K.success,
          }}>
            <i className="ph-fill ph-check-circle" style={{ fontSize: 32 }}></i>
            วัดสัญญาณชีพเสร็จเรียบร้อย · ส่งข้อมูลให้ AI วิเคราะห์แล้ว
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 sm:gap-5">
            <VitalTile label="อุณหภูมิ" value={v.temp.toFixed(1)} unit="°C" icon="ph-thermometer-simple" status={flags.temp || 'normal'}/>
            <VitalTile label="ความดันโลหิต" value={`${v.sbp}/${v.dbp}`} unit="mmHg" icon="ph-cuff" status={flags.sbp || 'normal'}/>
            <VitalTile label="อัตราหัวใจ" value={v.hr} unit="bpm" icon="ph-heartbeat" status={flags.hr || 'normal'}/>
            <VitalTile label="SpO₂" value={v.spo2} unit="%" icon="ph-drop" status={flags.spo2 || 'normal'}/>
            <VitalTile label="น้ำหนัก" value={v.weight} unit="kg" icon="ph-scales" status="normal"/>
            <VitalTile label="BMI" value={(v.weight / 1.7 / 1.7).toFixed(1)} unit="kg/m²" icon="ph-person" status="normal" sub="ประมาณการจากส่วนสูงในประวัติ"/>
          </div>
          <div className="flex justify-end mt-6 sm:mt-8">
            <KButton size="lg" onClick={onNext} iconRight="ph-arrow-right">วิเคราะห์ด้วย AI</KButton>
          </div>
        </div>
      )}
    </ScreenShell>
  );
}

function DeviceStep({ n, icon, title, sub, last }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 24,
      padding: '20px 0',
      borderBottom: last ? 'none' : `1px solid ${K.line}`,
    }}>
      <div className="font-bold text-lg sm:text-2xl lg:text-3xl leading-none" style={{
        width: 56, height: 56, borderRadius: '50%',
        background: K.primary050, color: K.primary900,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>{n}</div>
      <i className={`ph ${icon}`} style={{ fontSize: 36, color: K.primary900 }}></i>
      <div style={{ flex: 1 }}>
        <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-tight" style={{ color: K.ink }}>{title}</div>
        <div className="font-normal text-base sm:text-lg lg:text-xl leading-snug" style={{ color: K.meta, marginTop: 4 }}>{sub}</div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 5. AI ANALYSIS
// ────────────────────────────────────────────────────────────
function ScreenAI({ scenario, onNext }) {
  const [phase, setPhase] = useState('thinking');
  useEffect(() => {
    const t = setTimeout(() => setPhase('result'), 2400);
    return () => clearTimeout(t);
  }, []);
  const ai = scenario.ai;
  const urgencyTone = ai.urgencyLevel >= 4 ? 'danger' : ai.urgencyLevel >= 2 ? 'warning' : 'success';

  return (
    <ScreenShell title="ผลการวิเคราะห์ด้วย AI" subtitle="ประมวลผลด้วยโมเดล MorDee Triage v2.4 · อ้างอิงจากฐานข้อมูล 1.8M เคส">
      {phase === 'thinking' && (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 36, paddingTop: 80 }}>
          <div style={{ position: 'relative' }}>
            <NurseAvatar size={200} speaking/>
            <div style={{
              position: 'absolute', inset: -24, borderRadius: '50%',
              border: `3px dashed ${K.primary}`,
              animation: 'kiosk-spin 8s linear infinite',
            }}/>
          </div>
          <div style={{ textAlign: 'center' }}>
            <div className="font-semibold text-xl sm:text-3xl lg:text-4xl leading-snug" style={{ color: K.ink, marginBottom: 12 }}>กำลังวิเคราะห์ข้อมูลของคุณ...</div>
            <div className="font-normal text-lg sm:text-xl lg:text-2xl leading-snug" style={{ color: K.meta }}>เชื่อมโยงอาการ + สัญญาณชีพ + ประวัติการรักษา</div>
          </div>
          <div className="flex flex-col gap-3 w-full sm:w-[600px]">
            <ThinkingLine label="วิเคราะห์อาการที่ผู้ป่วยให้" delay={0}/>
            <ThinkingLine label="เปรียบเทียบกับฐานข้อมูล" delay={500}/>
            <ThinkingLine label="ประเมินความเร่งด่วน" delay={1000}/>
            <ThinkingLine label="จับคู่แผนกที่เหมาะสม" delay={1500}/>
          </div>
        </div>
      )}

      {phase === 'result' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, marginTop: 16 }}>
          {/* Hero result */}
          <div style={{
            background: ai.urgencyLevel >= 4
              ? `linear-gradient(135deg, ${K.danger} 0%, #B00808 100%)`
              : `linear-gradient(135deg, ${K.primary900} 0%, #1A3A3B 100%)`,
            color: '#fff', borderRadius: 24,
            position: 'relative', overflow: 'hidden',
          }} className="p-5 sm:p-8 md:p-10">
            <div style={{ position: 'absolute', top: -40, right: -40, opacity: 0.12 }}>
              <i className={`ph-fill ${ai.icon}`} style={{ fontSize: 280 }}></i>
            </div>
            <div style={{ position: 'relative' }}>
              <div className="font-medium text-base sm:text-lg lg:text-xl leading-none" style={{ letterSpacing: 2, opacity: 0.8, marginBottom: 12 }}>
                แผนกที่แนะนำ · RECOMMENDED DEPARTMENT
              </div>
              <div className="font-bold text-3xl sm:text-5xl lg:text-6xl leading-none" style={{ letterSpacing: -1, marginBottom: 8 }}>{ai.department}</div>
              <div className="font-normal text-lg sm:text-xl lg:text-2xl leading-none" style={{ opacity: 0.85, marginBottom: 24 }}>{ai.deptEn}</div>
              <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
                <ResultPill icon="ph-warning" label="ระดับความเร่งด่วน" value={ai.urgency}/>
                <ResultPill icon="ph-clock" label="คิวรอประมาณ" value={ai.wait}/>
                <ResultPill icon="ph-shield-check" label="ความมั่นใจ AI" value={`${ai.confidence}%`}/>
              </div>
            </div>
          </div>

          {/* Two-column body */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5">
            <KCard padding={28}>
              <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-none" style={{ color: K.ink, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 10 }}>
                <i className="ph-fill ph-list-magnifying-glass" style={{ color: K.primary900 }}></i>
                ภาวะที่เป็นไปได้
              </div>
              {ai.conditions.map((c, i) => (
                <div key={i} style={{
                  display: 'flex', flexDirection: 'column', gap: 8,
                  paddingBottom: 14, marginBottom: 14,
                  borderBottom: i < ai.conditions.length - 1 ? `1px solid ${K.line}` : 'none',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                      <div className="font-semibold text-base sm:text-lg lg:text-xl leading-tight" style={{ color: K.ink }}>{c.name}</div>
                      <div className="font-normal text-base leading-none" style={{ color: K.meta, marginTop: 4 }}>ICD-10: {c.icd}</div>
                    </div>
                    <div className="font-bold text-lg sm:text-xl lg:text-2xl leading-none" style={{ color: i === 0 ? K.primary900 : K.meta }}>{c.prob}%</div>
                  </div>
                  <div style={{ height: 6, background: K.line, borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{
                      height: '100%', width: `${c.prob}%`,
                      background: i === 0 ? K.primary900 : K.primary,
                      borderRadius: 999,
                    }}/>
                  </div>
                </div>
              ))}
            </KCard>

            <KCard padding={28}>
              <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-none" style={{ color: K.ink, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 10 }}>
                <i className="ph-fill ph-brain" style={{ color: K.coral }}></i>
                เหตุผลของ AI
              </div>
              {ai.reasoning.map((r, i) => (
                <div key={i} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 14,
                  padding: '12px 0',
                  borderBottom: i < ai.reasoning.length - 1 ? `1px dashed ${K.line}` : 'none',
                }}>
                  <i className="ph-fill ph-check-circle" style={{ fontSize: 22, color: K.primary900, marginTop: 2 }}></i>
                  <div className="font-normal text-base sm:text-lg leading-snug" style={{ color: K.ink2 }}>{r}</div>
                </div>
              ))}
            </KCard>
          </div>

          {/* Disclaimer + CTA */}
          <div className="font-normal text-base sm:text-lg leading-snug" style={{
            display: 'flex', gap: 14, alignItems: 'center',
            padding: '16px 22px', borderRadius: 16,
            background: K.warningBg, color: K.warning,
          }}>
            <i className="ph-fill ph-info" style={{ fontSize: 22 }}></i>
            ผลการวิเคราะห์เป็นเพียงคำแนะนำเบื้องต้น · การวินิจฉัยขั้นสุดท้ายอยู่ในดุลยพินิจของแพทย์
          </div>

          <div className="flex justify-between mt-2">
            <KButton variant="secondary" size="lg" icon="ph-chat-circle">ปรึกษาเจ้าหน้าที่</KButton>
            <KButton size="lg" onClick={onNext} iconRight="ph-arrow-right" variant={ai.urgencyLevel >= 4 ? 'danger' : 'primary'}>
              {ai.urgencyLevel >= 4 ? 'ไป ER ทันที' : 'เลือกแพทย์และนัดหมาย'}
            </KButton>
          </div>
        </div>
      )}
    </ScreenShell>
  );
}

function ThinkingLine({ label, delay }) {
  const [done, setDone] = useState(false);
  useEffect(() => { const t = setTimeout(() => setDone(true), delay + 300); return () => clearTimeout(t); }, [delay]);
  return (
    <div className="font-medium text-base sm:text-lg lg:text-xl leading-none" style={{
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '14px 22px', borderRadius: 14,
      background: '#fff', border: `1px solid ${K.line}`,
      color: K.ink2,
      opacity: done ? 1 : 0.5, transition: 'all .3s',
    }}>
      <i className={done ? 'ph-fill ph-check-circle' : 'ph ph-circle-notch'}
         style={{ fontSize: 22, color: done ? K.success : K.meta, animation: done ? 'none' : 'kiosk-spin 1s linear infinite' }}></i>
      {label}
    </div>
  );
}

function ResultPill({ icon, label, value }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 12,
      background: 'rgba(255,255,255,.18)', backdropFilter: 'blur(4px)',
      padding: '14px 20px', borderRadius: 14,
    }}>
      <i className={`ph-fill ${icon}`} style={{ fontSize: 24 }}></i>
      <div>
        <div className="font-normal text-base leading-none" style={{ opacity: 0.75, marginBottom: 4 }}>{label}</div>
        <div className="font-bold text-lg sm:text-xl lg:text-2xl leading-none">{value}</div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 6. DOCTOR SELECTION
// ────────────────────────────────────────────────────────────
function ScreenDoctor({ scenario, onNext, selectedDoctor, setSelectedDoctor }) {
  return (
    <ScreenShell title={`เลือกแพทย์ · ${scenario.ai.department}`} subtitle="แพทย์ที่พร้อมให้บริการในขณะนี้">
      <div className="flex flex-col gap-3 sm:gap-5 mt-3 sm:mt-4">
        {scenario.doctors.map((d, i) => {
          const sel = selectedDoctor === i;
          return (
            <KCard key={i} padding={28} onClick={() => setSelectedDoctor(i)} style={{
              border: `2px solid ${sel ? K.primary900 : K.line}`,
              background: sel ? K.primary050 : '#fff',
              display: 'flex', alignItems: 'center', gap: 24,
            }}>
              <div style={{
                width: 100, height: 100, borderRadius: '50%',
                background: d.emergency ? K.dangerBg : K.primary100,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                <i className={`ph-fill ${d.emergency ? 'ph-ambulance' : 'ph-user'}`}
                   style={{ fontSize: 52, color: d.emergency ? K.danger : K.primary900 }}></i>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 6 }}>
                  <div className="font-bold text-lg sm:text-2xl lg:text-3xl leading-tight" style={{ color: K.ink }}>{d.name}</div>
                  {d.soonest && <KTag tone={d.emergency ? 'danger' : 'success'} icon="ph-lightning" size="sm">
                    {d.emergency ? 'ฉุกเฉิน' : 'พร้อมที่สุด'}
                  </KTag>}
                </div>
                <div className="font-normal text-base sm:text-lg lg:text-xl leading-snug" style={{ color: K.ink3, marginBottom: 12 }}>{d.spec}</div>
                <div className="font-normal text-base sm:text-lg leading-none" style={{ display: 'flex', gap: 24, color: K.meta }}>
                  {!d.emergency && <span><i className="ph-fill ph-star" style={{ color: K.warning, marginRight: 6 }}></i>{d.rating} ({d.exp} ปี)</span>}
                  <span><i className="ph ph-map-pin" style={{ marginRight: 6 }}></i>{d.slot}</span>
                </div>
              </div>
              <div style={{
                width: 36, height: 36, borderRadius: '50%',
                border: `2px solid ${sel ? K.primary900 : K.line}`,
                background: sel ? K.primary900 : 'transparent',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: '#fff', flexShrink: 0,
              }}>
                {sel && <i className="ph-bold ph-check" style={{ fontSize: 20 }}></i>}
              </div>
            </KCard>
          );
        })}
      </div>
      <div className="flex justify-between mt-6 sm:mt-8">
        <KButton variant="ghost" size="lg" icon="ph-calendar">นัดวันอื่น</KButton>
        <KButton size="lg" onClick={onNext} disabled={selectedDoctor == null} iconRight="ph-arrow-right">
          ยืนยันการนัดหมาย
        </KButton>
      </div>
    </ScreenShell>
  );
}

// ────────────────────────────────────────────────────────────
// 7. TICKET — printable A5 OPD card
// ────────────────────────────────────────────────────────────
function ScreenTicket({ scenario, onRestart }) {
  const T = useT();
  const ticketNo = React.useMemo(() => 'A' + String(Math.floor(1000 + Math.random() * 9000)), [scenario.id]);
  const now = React.useMemo(() => new Date(), []);
  const ai = scenario.ai;
  const isER = ai.urgencyLevel >= 4;
  const directions = getDirections(scenario);

  return (
    <div className="ticket-screen flex flex-col px-4 py-6 sm:px-10 sm:py-9 md:px-14" style={{
      flex: 1,
      background: `linear-gradient(180deg, ${K.bg} 0%, ${K.bgDeep} 100%)`,
      position: 'relative', overflow: 'hidden',
      minHeight: 0,
    }}>
      <div className="no-print" style={{ textAlign: 'center', marginBottom: 18 }}>
        <div style={{
          width: 86, height: 86, borderRadius: '50%',
          background: isER ? K.danger : K.success, margin: '0 auto 12px',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: isER ? '0 8px 22px rgba(214,49,49,.32)' : '0 8px 22px rgba(40,163,56,.3)',
          animation: 'kiosk-pop .5s ease-out',
        }}>
          <i className={`ph-bold ${isER ? 'ph-warning' : 'ph-check'}`} style={{ fontSize: 50, color: '#fff' }}></i>
        </div>
        <h1 className="font-bold text-2xl sm:text-4xl lg:text-5xl leading-none" style={{ color: K.ink, margin: 0, marginBottom: 6 }}>
          {isER ? T({ th: 'นำท่านไปยัง ER ด่วน', en: 'Proceed to ER immediately' }) : T({ th: 'เสร็จเรียบร้อย!', en: 'All set!' })}
        </h1>
        <p className="font-normal text-lg sm:text-xl lg:text-2xl leading-snug" style={{ color: K.ink2, margin: 0 }}>
          {isER ? T({ th: 'แสดงบัตรนี้ที่จุดคัดกรอง ER เจ้าหน้าที่จะดูแลทันที', en: 'Show this card at the ER triage point. Staff will assist immediately.' }) : T({ th: 'พิมพ์บัตรและทำตามวิธีไปแผนกด้านล่าง', en: 'Print your card and follow the directions below.' })}
        </p>
      </div>

      {/* The A5 OPD card — only this prints */}
      <div className="opd-card" style={{
        background: '#fff', borderRadius: 18,
        boxShadow: '0 12px 36px rgba(47,82,82,.16)',
        position: 'relative', overflow: 'hidden',
        flex: 1, minHeight: 0,
        display: 'flex', flexDirection: 'column',
      }}>
        <OPDCardHeader isER={isER} now={now} ticketNo={ticketNo}/>

        {/* Body grid */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5 px-4 py-4 sm:px-7 sm:py-5" style={{
          flex: 1, minHeight: 0,
        }}>
          {/* LEFT — patient + queue + dept */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minHeight: 0 }}>
            <PatientBlock patient={scenario.patient}/>
            <QueueBlock ticketNo={ticketNo} dept={ai.department} deptEn={ai.deptEn} wait={ai.wait} isER={isER}/>
            <SymptomBlock chief={scenario.chief} ai={ai}/>
          </div>

          {/* RIGHT — directions + QR */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minHeight: 0 }}>
            <DirectionsBlock directions={directions} dept={ai.department}/>
            <QRBlock ticketNo={ticketNo} hn={scenario.patient.hn}/>
          </div>
        </div>

        <OPDCardFooter now={now}/>
      </div>

      {/* Actions — hidden on print */}
      <div className="no-print flex gap-3 sm:gap-4 mt-4 sm:mt-5 justify-center flex-wrap">
        <KButton variant="secondary" size="lg" onClick={onRestart} icon="ph-arrow-counter-clockwise">{T({ th: 'เริ่มใหม่', en: 'Start over' })}</KButton>
        <KButton size="lg" onClick={() => window.print()} icon="ph-printer">
          {T({ th: 'พิมพ์บัตร', en: 'Print card' })}
        </KButton>
        <KButton variant="ghost" size="lg" icon="ph-paper-plane-tilt">{T({ th: 'ส่งเข้า LINE', en: 'Send to LINE' })}</KButton>
      </div>
    </div>
  );
}

// ── A5 card sub-blocks ─────────────────────────────────────
function OPDCardHeader({ isER, now, ticketNo }) {
  return (
    <div style={{
      padding: '18px 28px', display: 'flex', justifyContent: 'space-between',
      alignItems: 'center',
      background: isER
        ? `linear-gradient(135deg, ${K.danger} 0%, #B00808 100%)`
        : `linear-gradient(135deg, ${K.primary900} 0%, #1A3A3B 100%)`,
      color: '#fff',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ background: '#fff', borderRadius: 10, padding: '6px 12px' }}>
          <img src="assets/mordee-logo.png" style={{ height: 28, display: 'block' }} alt="MorDee"/>
        </div>
        <div>
          <div className="font-bold text-base sm:text-lg lg:text-xl leading-none">OPD Smart Triage Card</div>
          <div className="font-normal text-base leading-none" style={{ opacity: 0.8, marginTop: 4 }}>
            Center of Excellence · MorDee × Hospital Group
          </div>
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="font-normal text-base leading-none" style={{ opacity: 0.85, letterSpacing: 1 }}>QUEUE NO.</div>
        <div className="font-bold text-xl sm:text-3xl lg:text-4xl leading-none" style={{ letterSpacing: -1, marginTop: 4 }}>{ticketNo}</div>
        <div className="font-normal text-base leading-none" style={{ opacity: 0.8, marginTop: 4 }}>
          {now.toLocaleDateString('th-TH', { day: '2-digit', month: 'short', year: 'numeric' })} · {now.toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit' })}
        </div>
      </div>
    </div>
  );
}

function OPDCardFooter({ now }) {
  return (
    <div className="font-normal text-base leading-snug" style={{
      padding: '12px 28px', display: 'flex', justifyContent: 'space-between',
      borderTop: `1px dashed ${K.line}`, background: K.bg,
      color: K.meta,
    }}>
      <span>* บัตรนี้ออกโดย Smart Triage Kiosk · ผลคัดกรองจาก AI ใช้ประกอบการตัดสินใจของแพทย์เท่านั้น<br/>* Issued by Smart Triage Kiosk · AI screening output is for physician reference only</span>
      <span>Station 04 · {now.toLocaleTimeString('th-TH', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</span>
    </div>
  );
}

function PatientBlock({ patient }) {
  return (
    <div style={{
      border: `1px solid ${K.line}`, borderRadius: 12, padding: '14px 18px',
      display: 'grid', gridTemplateColumns: '1fr auto', alignItems: 'center', gap: 12,
    }}>
      <div>
        <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>PATIENT · ข้อมูลผู้ป่วย</div>
        <div className="font-bold text-lg sm:text-xl lg:text-2xl leading-tight" style={{ color: K.ink, marginTop: 6 }}>{patient.name.th} · {patient.name.en}</div>
        <div className="font-medium text-base leading-none" style={{ display: 'flex', gap: 16, marginTop: 8, color: K.ink2 }}>
          <span><b style={{ color: K.meta, fontWeight: 500 }}>HN:</b> {patient.hn.replace('HN ', '')}</span>
          <span><b style={{ color: K.meta, fontWeight: 500 }}>Age/อายุ:</b> {patient.age}</span>
          <span><b style={{ color: K.meta, fontWeight: 500 }}>Sex/เพศ:</b> {patient.gender.en} ({patient.gender.th})</span>
        </div>
        {patient.allergy !== '–' && (
          <div className="font-semibold text-base leading-none" style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            marginTop: 8, padding: '4px 10px', borderRadius: 999,
            background: K.dangerBg, color: K.danger,
          }}>
            <i className="ph-fill ph-warning"></i>
            Allergy / แพ้ยา: {patient.allergy}
          </div>
        )}
      </div>
      <i className="ph-fill ph-user-circle" style={{ fontSize: 56, color: K.primary }}></i>
    </div>
  );
}

function QueueBlock({ ticketNo, dept, deptEn, wait, isER }) {
  return (
    <div style={{
      border: `2px solid ${isER ? K.danger : K.primary900}`, borderRadius: 12,
      padding: '14px 18px', position: 'relative', overflow: 'hidden',
      background: isER ? '#FFF5F5' : K.primary050,
    }}>
      <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>
        DEPARTMENT · แผนก
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginTop: 6, flexWrap: 'wrap' }}>
        <div className="font-bold text-lg sm:text-2xl lg:text-3xl leading-none" style={{ color: isER ? K.danger : K.primary900 }}>{dept.th}</div>
        <div className="font-normal text-base leading-none" style={{ color: K.meta }}>{deptEn}</div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 10, gap: 14 }}>
        <div>
          <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>QUEUE</div>
          <div className="font-bold text-2xl sm:text-4xl lg:text-5xl leading-none" style={{ color: isER ? K.danger : K.primary900, letterSpacing: -1 }}>{ticketNo}</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>EST. WAIT · รอประมาณ</div>
          <div className="font-bold text-base sm:text-lg leading-tight" style={{ color: K.ink, marginTop: 4 }}>{wait.en} · {wait.th}</div>
        </div>
      </div>
    </div>
  );
}

function SymptomBlock({ chief, ai }) {
  return (
    <div style={{ border: `1px solid ${K.line}`, borderRadius: 12, padding: '14px 18px' }}>
      <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>
        CHIEF COMPLAINT · อาการสำคัญ
      </div>
      <div className="font-semibold text-base sm:text-lg leading-snug" style={{ color: K.ink, marginTop: 6 }}>”{chief.th}”</div>
      <div className="font-normal text-base leading-snug" style={{ color: K.meta, marginTop: 4 }}>”{chief.en}”</div>

      <div style={{ marginTop: 12, paddingTop: 10, borderTop: `1px dashed ${K.line}` }}>
        <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>
          AI TRIAGE · {ai.confidence}% confidence
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
          <span className="font-semibold text-base leading-none" style={{
            padding: '4px 10px', borderRadius: 999,
            background: ai.urgencyLevel >= 4 ? K.dangerBg : ai.urgencyLevel >= 3 ? K.warningBg : K.successBg,
            color: ai.urgencyLevel >= 4 ? K.danger : ai.urgencyLevel >= 3 ? K.warning : K.success,
          }}>● {ai.urgency.en} · {ai.urgency.th}</span>
          {ai.conditions.slice(0, 2).map((c, i) => (
            <span key={i} className="font-medium text-base leading-none" style={{
              padding: '4px 10px', borderRadius: 999,
              background: K.bg, color: K.ink2,
            }}>
              {c.name.en} · {c.prob}%
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

function DirectionsBlock({ directions, dept }) {
  return (
    <div style={{
      border: `1px solid ${K.line}`, borderRadius: 12, padding: '14px 18px',
      flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>
          HOW TO GET THERE · วิธีไปแผนก
        </div>
        <div className="font-semibold text-base leading-none" style={{ color: K.primary900 }}>
          From Kiosk Station 04
        </div>
      </div>
      <div style={{ marginTop: 10, display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
        {directions.steps.map((s, i) => (
          <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <div className="font-bold text-base leading-none" style={{
              width: 22, height: 22, borderRadius: '50%', background: K.primary900,
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0, marginTop: 1,
            }}>{i + 1}</div>
            <div>
              <div className="font-semibold text-base leading-snug" style={{ color: K.ink }}>{s.title.en}</div>
              <div className="font-medium text-base leading-snug" style={{ color: K.ink2 }}>{s.title.th}</div>
              {s.sub && <div className="font-normal text-base leading-snug" style={{ color: K.meta, marginTop: 2 }}>{s.sub.en} · {s.sub.th}</div>}
            </div>
          </div>
        ))}
      </div>
      <MiniMap directions={directions}/>
    </div>
  );
}

function MiniMap({ directions }) {
  // Simple schematic floor map showing kiosk → destination
  return (
    <div style={{
      marginTop: 10, height: 90, border: `1px solid ${K.line}`,
      borderRadius: 8, position: 'relative', overflow: 'hidden',
      background: '#FAFCFC',
    }}>
      <svg viewBox="0 0 320 90" style={{ width: '100%', height: '100%' }}>
        {/* corridors */}
        <rect x="0" y="38" width="320" height="14" fill="#EAF2F2"/>
        <rect x="148" y="0" width="14" height="90" fill="#EAF2F2"/>
        {/* rooms */}
        <rect x="8"  y="8"  width="48" height="22" fill="#fff" stroke={K.line}/>
        <rect x="8"  y="60" width="48" height="22" fill="#fff" stroke={K.line}/>
        <rect x="200" y="8"  width="60" height="22" fill="#fff" stroke={K.line}/>
        <rect x="264" y="8" width="48" height="22" fill="#fff" stroke={K.line}/>
        <rect x="200" y="60" width="60" height="22" fill="#fff" stroke={K.line}/>
        <rect x="264" y="60" width="48" height="22" fill="#fff" stroke={K.line}/>
        {/* path */}
        <path d={directions.path} stroke={K.coral} strokeWidth="2.4" fill="none"
          strokeDasharray="4 3" strokeLinecap="round"/>
        {/* kiosk marker */}
        <circle cx="32" cy="45" r="5" fill={K.primary900}/>
        <text x="42" y="48" fill={K.ink2} className="font-bold text-base">KIOSK 04</text>
        {/* destination marker */}
        <circle cx={directions.endX} cy={directions.endY} r="6" fill={K.coral}/>
        <text x={directions.endX - 18} y={directions.endY + 18} fill={K.coral} className="font-bold text-base">{directions.label}</text>
      </svg>
    </div>
  );
}

function QRBlock({ ticketNo, hn }) {
  return (
    <div style={{
      border: `1px solid ${K.line}`, borderRadius: 12, padding: '12px 16px',
      display: 'flex', gap: 14, alignItems: 'center',
    }}>
      <div style={{
        width: 96, height: 96, padding: 6, background: '#fff',
        border: `1px solid ${K.line}`, borderRadius: 8, flexShrink: 0,
      }}>
        <FakeQR/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="font-medium text-base leading-none" style={{ color: K.meta, letterSpacing: 1 }}>
          QUEUE QR · ติดตามคิวบนแอป · TRACK ON APP
        </div>
        <div className="font-semibold text-base leading-snug" style={{ color: K.ink, marginTop: 4 }}>
          สแกนด้วยกล้องมือถือ หรือเปิดแอป MorDee · Scan with phone camera or open MorDee app
        </div>
        <div className="font-semibold text-base leading-none" style={{ marginTop: 8, padding: '6px 10px', background: K.bg, borderRadius: 6,
          color: K.ink2, letterSpacing: 1, display: 'inline-block',
        }}>
          {ticketNo} · {hn.replace('HN ', '')}
        </div>
        {/* barcode strip */}
        <div style={{ display: 'flex', gap: 1, marginTop: 8, height: 18 }}>
          {Array.from({ length: 56 }).map((_, i) => (
            <div key={i} style={{
              width: ((i * 7919) % 5) + 1, height: '100%',
              background: i % 3 === 0 ? K.ink : (i % 5 === 0 ? K.line : K.ink),
            }}/>
          ))}
        </div>
      </div>
    </div>
  );
}

function getDirections(scenario) {
  const deptKey = scenario.ai.deptKey;
  if (deptKey === 'er') return {
    label: 'ER', endX: 290, endY: 75,
    path: 'M 32 45 L 155 45 L 155 71 L 264 71',
    steps: [
      { title: { en: 'Notify staff at the triage point immediately', th: 'แจ้งเจ้าหน้าที่จุด Triage ทันที' },
        sub:   { en: 'Show this card — staff will escort you to the ER', th: 'ยกบัตรนี้ขึ้นให้เห็น · เจ้าหน้าที่จะนำตัวเข้า ER' } },
      { title: { en: 'Take the elevator down to floor 1', th: 'ลงลิฟต์ไปชั้น 1' },
        sub:   { en: 'Use the nearest lift; a nurse will guide you', th: 'ใช้ลิฟต์ใกล้สุด · มีพยาบาลพาทาง' } },
      { title: { en: 'Enter the ER through the back door', th: 'เข้า ER ทางประตูด้านหลัง' },
        sub:   { en: 'Bay 2 · Emergency team will be ready', th: 'Bay 2 · มีทีมแพทย์ฉุกเฉินรออยู่' } },
    ],
  };
  if (deptKey === 'ortho') return {
    label: 'ORTHO', endX: 230, endY: 21,
    path: 'M 32 45 L 155 45 L 155 19 L 200 19',
    steps: [
      { title: { en: 'Walk straight along the main corridor', th: 'เดินตรงไปตามทางเดินหลัก' },
        sub:   { en: 'Blue corridor · pass the Lab on your right', th: 'ทางเดินสีฟ้า · ผ่านห้อง Lab ทางขวา' } },
      { title: { en: 'Turn right at the main junction', th: 'เลี้ยวขวาที่ทางแยกใหญ่' },
        sub:   { en: 'Sign reads “Orthopedics · Floor 2”', th: 'มีป้ายชี้ “Orthopedics ชั้น 2”' } },
      { title: { en: 'Take the escalator to floor 2', th: 'ขึ้นบันไดเลื่อนชั้น 2' },
        sub:   { en: 'Orthopedics dept · examination room 7', th: 'แผนกกระดูกและข้อ · ห้องตรวจที่ 7' } },
      { title: { en: 'Show this card at the service desk', th: 'แสดงบัตรนี้ที่จุดบริการ' },
        sub:   { en: `Wait for your name · ${scenario.ai.wait.en}`, th: `รอเรียกชื่อ · ${scenario.ai.wait.th}` } },
    ],
  };
  // default → Internal Medicine
  return {
    label: 'IPD/MED', endX: 290, endY: 21,
    path: 'M 32 45 L 155 45 L 155 19 L 264 19',
    steps: [
      { title: { en: 'Walk straight along the main corridor', th: 'เดินตรงไปตามทางเดินหลัก' },
        sub:   { en: 'About 30 m, past the pharmacy', th: 'ประมาณ 30 เมตร · ผ่านห้องเภสัช' } },
      { title: { en: 'Turn right at the junction', th: 'เลี้ยวขวาที่ทางแยก' },
        sub:   { en: 'Toward the “Internal Medicine” sign', th: 'ตรงป้าย “อายุรกรรม Internal Medicine”' } },
      { title: { en: 'Go up to floor 2 (stairs or lift)', th: 'ขึ้นชั้น 2 (บันไดหรือลิฟต์)' },
        sub:   { en: 'Nearest lift is left of the restrooms', th: 'ลิฟต์ใกล้สุดอยู่ทางซ้ายหลังห้องน้ำ' } },
      { title: { en: 'Show this card at the counter', th: 'แสดงบัตรที่เคาน์เตอร์' },
        sub:   { en: `Wait for your name · ${scenario.ai.wait.en}`, th: `รอเรียกชื่อ · ${scenario.ai.wait.th}` } },
    ],
  };
}

function FakeQR() {
  // simple fake QR pattern
  const cells = [];
  const seed = 'MorDee-Triage-2026';
  let h = 0; for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0;
  for (let i = 0; i < 21 * 21; i++) {
    h = (h * 1103515245 + 12345) >>> 0;
    cells.push(h % 2);
  }
  // force position markers
  const isCorner = (r, c) => (r < 7 && c < 7) || (r < 7 && c > 13) || (r > 13 && c < 7);
  const cornerOn = (r, c) => {
    const inBox = (r === 0 || r === 6 || c === 0 || c === 6 || (r >= 2 && r <= 4 && c >= 2 && c <= 4));
    return inBox ? 1 : 0;
  };
  return (
    <svg viewBox="0 0 21 21" style={{ width: '100%', height: '100%' }}>
      {cells.map((v, i) => {
        const r = Math.floor(i / 21), c = i % 21;
        let on = v;
        if (isCorner(r, c)) {
          const lr = r > 13 ? r - 14 : r;
          const lc = c > 13 ? c - 14 : c;
          on = cornerOn(lr, lc);
        }
        return on ? <rect key={i} x={c} y={r} width="1" height="1" fill={K.ink}/> : null;
      })}
    </svg>
  );
}

window.ScreenVitals = ScreenVitals;
window.ScreenAI = ScreenAI;
window.ScreenDoctor = ScreenDoctor;
window.ScreenTicket = ScreenTicket;
