/* screens-3.jsx — enhanced AI-driven versions of Triage, Vitals, AI screens
 * with live Claude chat, body map, vision-based vitals, neural viz, reasoning chain
 */

// ──────────────────────────────────────────────────────────────
// 3'. TRIAGE WITH LIVE AI CHAT + BODY MAP
// ──────────────────────────────────────────────────────────────
const SYSTEM_PROMPT_TH = `คุณคือ "พี่หมอดี" พยาบาลผู้ช่วย AI ในตู้คัดกรอง OPD ของโรงพยาบาล
ตอบเป็นภาษาไทย กระชับ อบอุ่น เหมือนพยาบาลตัวจริงคุยกับคนไข้
ทำหน้าที่: ถามคำถามคัดกรองทีละข้อสั้นๆ (เช่น ระยะเวลา ระดับความรุนแรง อาการร่วม)
ห้ามวินิจฉัย ห้ามให้ยา — เพียงเก็บข้อมูลและให้กำลังใจ
จบข้อความด้วยคำถามเดียวให้ผู้ป่วยตอบ ใช้ <= 2 ประโยค`;
const SYSTEM_PROMPT_EN = `You are "MorDee", an AI nurse assistant in a hospital OPD triage kiosk.
Reply in English, concisely, warmly — like a real nurse talking to a patient.
Role: ask one short triage question at a time (e.g. duration, severity, associated symptoms).
Do NOT diagnose or prescribe — only collect information and offer reassurance.
End with a single question for the patient. Use <= 2 sentences.`;

function ScreenTriageAI({ scenario, onNext, aiMode }) {
  const T = useT();
  const { lang } = useLang();
  const [mode, setMode] = React.useState('chat'); // chat | bodymap
  const [bodyParts, setBodyParts] = React.useState(scenario.id === 'knee' ? ['kneeR']
    : scenario.id === 'chest' ? ['chest', 'armL']
    : scenario.id === 'fever' ? ['throat', 'head'] : []);
  const greet = lang === 'en'
    ? `Hi, I'm "MorDee" your AI nurse assistant.\n${scenario.patient.name.en}, what brings you in today?`
    : `สวัสดีค่ะ ดิฉันชื่อ "พี่หมอดี" จะช่วยประเมินอาการเบื้องต้นนะคะ\nวันนี้${scenario.patient.name.th.replace('คุณ', 'คุณ')}มาด้วยอาการอะไรคะ?`;
  const [messages, setMessages] = React.useState([
    { role: 'nurse', text: greet },
  ]);
  const [input, setInput] = React.useState(T(scenario.chief));
  const [thinking, setThinking] = React.useState(false);
  const [turn, setTurn] = React.useState(0);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, thinking]);

  // 4 user messages: chief (turn 0) + 3 scripted questions (turns 1..3)
  const TOTAL_TURNS = 4;
  const SCRIPTED = scenario.triage;

  const askNext = async (userMsg) => {
    setMessages(m => [...m, { role: 'user', text: userMsg }]);
    setInput('');
    setThinking(true);

    let reply = '';
    if (aiMode === 'live' && window.claude && window.claude.complete) {
      try {
        const nurseLabel = lang === 'en' ? 'MorDee' : 'พี่หมอดี';
        const patientLabel = lang === 'en' ? 'Patient' : 'ผู้ป่วย';
        const history = [...messages, { role: 'user', text: userMsg }]
          .map(m => `${m.role === 'nurse' ? nurseLabel : patientLabel}: ${m.text}`).join('\n');
        const sysPrompt = lang === 'en' ? SYSTEM_PROMPT_EN : SYSTEM_PROMPT_TH;
        const ctxLine = lang === 'en'
          ? `Patient context: ${T(scenario.patient.name)}, age ${scenario.patient.age}, chief complaint: ${T(scenario.chief)}`
          : `บริบทผู้ป่วย: ${T(scenario.patient.name)}, อายุ ${scenario.patient.age}, อาการหลัก: ${T(scenario.chief)}`;
        const tail = lang === 'en'
          ? `\n\n${nurseLabel} (reply in 1-2 short sentences + one question):`
          : `\n\nพี่หมอดี (ตอบให้สั้น 1-2 ประโยค + คำถามเดียว):`;
        const fullPrompt = `${sysPrompt}\n\n${ctxLine}\n\n${lang === 'en' ? 'Conversation' : 'บทสนทนา'}:\n${history}${tail}`;
        reply = await window.claude.complete(fullPrompt);
      } catch (e) { console.warn('claude error', e); }
    }
    if (!reply) {
      // scripted fallback: turn 0 = user just gave chief → ask SCRIPTED[0] (duration);
      // turn 1..2 → next scripted q; turn === SCRIPTED.length → closing thanks.
      const q = turn < SCRIPTED.length ? SCRIPTED[turn] : null;
      reply = q ? T(q.q)
        : T({ th: 'รับทราบค่ะ ขอบคุณที่ตอบนะคะ ดิฉันจะส่งข้อมูลให้แพทย์เลยค่ะ',
              en: 'Got it, thank you. Sending your info to the doctor now.' });
    }

    setTimeout(() => {
      setMessages(m => [...m, { role: 'nurse', text: reply.trim() }]);
      setThinking(false);
      setTurn(t => t + 1);
    }, aiMode === 'live' ? 200 : 700);
  };

  const handleQuickReply = (txt) => askNext(txt);

  const toggleBodyPart = (id) => {
    setBodyParts(b => b.includes(id) ? b.filter(x => x !== id) : [...b, id]);
  };

  const finished = turn >= TOTAL_TURNS;

  return (
    <ScreenShell title={T({ th: 'คัดกรองอาการ', en: 'Symptom triage' })} subtitle={
      mode === 'chat'
        ? T({
            th: `สนทนากับพยาบาล AI · ${aiMode === 'live' ? '🟢 Live Claude AI' : 'Scripted demo'} · รอบที่ ${turn}/${TOTAL_TURNS}`,
            en: `Chat with AI nurse · ${aiMode === 'live' ? '🟢 Live Claude AI' : 'Scripted demo'} · Turn ${turn}/${TOTAL_TURNS}`,
          })
        : T({ th: 'ระบุตำแหน่งอาการ · เลือกได้หลายจุด', en: 'Mark symptom location · multiple allowed' })
    }>
      {/* Mode tabs */}
      <div className="flex flex-wrap gap-3 sm:gap-4 mb-5 sm:mb-6">
        <ModeChip active={mode === 'chat'}    onClick={() => setMode('chat')}    icon="ph-chat-circle-dots" label={T({ th: 'คุยกับพยาบาล AI', en: 'Chat with AI nurse' })}/>
        <ModeChip active={mode === 'bodymap'} onClick={() => setMode('bodymap')} icon="ph-person" label={T({ th: `ระบุจุดที่ปวด${bodyParts.length ? ` (${bodyParts.length})` : ''}`, en: `Mark pain points${bodyParts.length ? ` (${bodyParts.length})` : ''}` })}/>
      </div>

      {mode === 'chat' && (
        <div className="flex flex-col gap-4 sm:gap-5" style={{ height: '100%' }}>
          {/* Chat scrollable */}
          <div ref={scrollRef} className="flex-1 min-h-0" style={{
            flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 16,
            padding: 24, background: 'linear-gradient(180deg, #fff 0%, #F1F9F9 100%)',
            borderRadius: 20, border: `1px solid ${K.line}`,
          }}>
            {messages.map((m, i) => m.role === 'nurse'
              ? <NurseMessage key={i} text={m.text}/>
              : <UserMessage key={i} text={m.text}/>)}
            {thinking && <NurseTyping aiMode={aiMode}/>}
          </div>

          {/* Input area */}
          {!finished ? (
            <ChatInput value={input} onChange={setInput}
              onSend={() => input.trim() && askNext(input.trim())}
              sttPhrase={getSTTPhrase(scenario, turn, lang)}
              quickReplies={getQuickReplies(scenario, turn, lang)}
              onQuick={handleQuickReply}
              disabled={thinking}/>
          ) : (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: 20, background: K.successBg, borderRadius: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <i className="ph-fill ph-check-circle" style={{ fontSize: 32, color: K.success }}></i>
                <div>
                  <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-none" style={{ color: K.success }}>{T({ th: 'คัดกรองเสร็จสิ้น', en: 'Triage complete' })}</div>
                  <div className="font-normal text-base leading-tight" style={{ color: K.ink2, marginTop: 4 }}>{T({ th: 'ส่งข้อมูลให้ AI วิเคราะห์ต่อ', en: 'Sending data for AI analysis' })}</div>
                </div>
              </div>
              <KButton size="lg" onClick={onNext} iconRight="ph-arrow-right">{T({ th: 'วิเคราะห์ด้วย AI', en: 'Analyze with AI' })}</KButton>
            </div>
          )}
        </div>
      )}

      {mode === 'bodymap' && (
        <div className="flex flex-col gap-5 sm:gap-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 sm:gap-8 items-start">
            <div className="p-4 sm:p-6" style={{
              background: 'linear-gradient(180deg, #F1F9F9 0%, #fff 100%)',
              borderRadius: 24, border: `1px solid ${K.line}`,
            }}>
              <BodyMap selected={bodyParts} onToggle={toggleBodyPart} lang={lang}/>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-snug" style={{ color: K.ink, marginBottom: 4 }}>
                {lang === 'en' ? <>Tap where it <b style={{ color: K.coral }}>feels abnormal</b></> : <>แตะตำแหน่งที่ <b style={{ color: K.coral }}>รู้สึกผิดปกติ</b></>}
              </div>
              <div className="font-normal text-base leading-snug" style={{ color: K.meta, marginBottom: 12 }}>
                {T({ th: 'AI จะนำตำแหน่งและความรุนแรงไปประกอบการวินิจฉัย', en: 'AI uses location and severity in its diagnosis.' })}
              </div>
              <div style={{
                background: '#fff', border: `1px solid ${K.line}`,
                borderRadius: 16, padding: 18, minHeight: 200,
              }}>
                <div className="font-semibold text-base leading-none" style={{ color: K.meta, marginBottom: 12, letterSpacing: 1 }}>
                  {T({ th: 'จุดที่เลือก', en: 'Selected' })} ({bodyParts.length})
                </div>
                {bodyParts.length === 0 ? (
                  <div className="font-normal text-base leading-snug" style={{ color: K.meta, fontStyle: 'italic' }}>
                    {T({ th: 'ยังไม่ได้เลือก', en: 'None selected' })}
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {bodyParts.map(id => {
                      const r = BODY_REGIONS.find(x => x.id === id);
                      return r ? (
                        <div key={id} style={{
                          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                          padding: '10px 14px', background: K.bg, borderRadius: 10,
                        }}>
                          <span className="font-medium text-base leading-none" style={{ display: 'flex', alignItems: 'center', gap: 10, color: K.ink }}>
                            <span style={{ width: 10, height: 10, borderRadius: '50%', background: K.coral }}/>
                            {window.getBodyLabel ? window.getBodyLabel(r, lang) : (typeof r.label === 'string' ? r.label : r.label[lang])}
                          </span>
                          <button onClick={() => toggleBodyPart(id)} style={{
                            border: 'none', background: 'transparent', cursor: 'pointer',
                            color: K.meta, fontSize: 18,
                          }}>
                            <i className="ph ph-x"></i>
                          </button>
                        </div>
                      ) : null;
                    })}
                  </div>
                )}
              </div>
              <div className="font-normal text-base leading-snug" style={{
                background: K.bg, border: `1px dashed ${K.primary}`,
                borderRadius: 12, padding: '14px 16px',
                color: K.ink2,
                display: 'flex', gap: 10,
              }}>
                <i className="ph-fill ph-lightbulb" style={{ fontSize: 18, color: K.primary900, flexShrink: 0 }}></i>
                <span>{lang === 'en' ? <><b>Tip:</b> Mark multiple points — AI looks for patterns, e.g. chest pain radiating to left arm</> : <><b>เคล็ดลับ:</b> ระบุได้หลายจุด AI จะหา pattern ที่เกี่ยวข้องกัน เช่น ปวดอกร้าวแขนซ้าย</>}</span>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <KButton variant="secondary" size="lg" onClick={() => setMode('chat')}>{T({ th: 'กลับไปคุย', en: 'Back to chat' })}</KButton>
            <KButton size="lg" onClick={() => setMode('chat')} iconRight="ph-arrow-right">{T({ th: 'ยืนยันตำแหน่ง', en: 'Confirm location' })}</KButton>
          </div>
        </div>
      )}
    </ScreenShell>
  );
}

function ModeChip({ active, onClick, icon, label }) {
  return (
    <button onClick={onClick} className="font-semibold text-base sm:text-lg leading-none" style={{
      display: 'inline-flex', alignItems: 'center', gap: 10,
      padding: '14px 22px', borderRadius: 999,
      background: active ? K.primary900 : '#fff',
      color: active ? '#fff' : K.ink2,
      border: `2px solid ${active ? K.primary900 : K.line}`,
      cursor: 'pointer',
    }}>
      <i className={`ph ${icon}`} style={{ fontSize: 22 }}></i>
      {label}
    </button>
  );
}

function NurseMessage({ text }) {
  const T = useT();
  return (
    <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: `radial-gradient(circle at 30% 25%, ${K.primary100}, ${K.primary} 90%)`,
        flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 4px 10px rgba(47,82,82,.15)',
      }}>
        <i className="ph-fill ph-first-aid-kit" style={{ color: '#fff', fontSize: 24 }}></i>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="font-medium text-base leading-none" style={{ color: K.primary900, marginBottom: 6 }}>
          {T({ th: 'พี่หมอดี', en: 'MorDee' })} <span style={{ color: K.meta, fontWeight: 400, marginLeft: 6 }}>· {T({ th: 'พยาบาล AI', en: 'AI nurse' })}</span>
        </div>
        <div className="font-normal text-lg sm:text-xl lg:text-2xl leading-normal" style={{
          background: '#fff', border: `1px solid ${K.line}`,
          borderRadius: '4px 22px 22px 22px', padding: '18px 22px',
          color: K.ink,
          whiteSpace: 'pre-wrap', boxShadow: '0 2px 6px rgba(47,82,82,.06)',
        }}>{text}</div>
      </div>
    </div>
  );
}

function UserMessage({ text }) {
  const T = useT();
  return (
    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
      <div style={{ maxWidth: '78%' }}>
        <div className="font-medium text-base leading-none" style={{ color: K.meta, marginBottom: 6, textAlign: 'right' }}>
          {T({ th: 'คุณ', en: 'You' })}
        </div>
        <div className="font-medium text-lg sm:text-xl lg:text-2xl leading-snug" style={{
          background: K.primary900, color: '#fff',
          borderRadius: '22px 4px 22px 22px', padding: '18px 22px',
        }}>{text}</div>
      </div>
    </div>
  );
}

function NurseTyping({ aiMode }) {
  const T = useT();
  return (
    <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
      <div style={{
        width: 56, height: 56, borderRadius: '50%',
        background: `radial-gradient(circle at 30% 25%, ${K.primary100}, ${K.primary} 90%)`,
        flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <i className="ph-fill ph-first-aid-kit" style={{ color: '#fff', fontSize: 24 }}></i>
      </div>
      <div style={{
        background: '#fff', border: `1px solid ${K.line}`,
        borderRadius: '4px 22px 22px 22px', padding: '18px 22px',
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        {[0, 1, 2].map(i => (
          <span key={i} style={{
            width: 10, height: 10, borderRadius: '50%', background: K.primary900,
            animation: `kiosk-bounce 1.2s ${i * 0.15}s infinite`,
          }}/>
        ))}
        <span className="font-normal text-base leading-none" style={{ color: K.meta, marginLeft: 8 }}>
          {aiMode === 'live' ? T({ th: 'Claude AI กำลังคิด...', en: 'Claude AI thinking...' }) : T({ th: 'กำลังพิมพ์...', en: 'Typing...' })}
        </span>
      </div>
    </div>
  );
}

// VOICE-FIRST INPUT (Google Assistant style)
//   idle       → big mic CTA + scrim of quick chips + "type instead" link
//   listening  → fullscreen-ish gradient panel, 4-bar bouncing waveform, "Listening…"
//   transcribing → text streams in big, waveform calms
//   done       → preview transcript + Send / Retry / Edit
//   type       → keyboard fallback (text input + send)
function ChatInput({ value, onChange, onSend, quickReplies = [], onQuick, disabled, sttPhrase }) {
  const { lang } = useLang();
  const T = useT();
  const [stt, setStt] = React.useState('idle');         // idle | listening | transcribing | done
  const [typeMode, setTypeMode] = React.useState(false);
  const charTimer = React.useRef(null);
  const listenTimer = React.useRef(null);

  const startSTT = () => {
    if (stt !== 'idle' || disabled) return;
    setTypeMode(false);
    setStt('listening');
    onChange('');
    listenTimer.current = setTimeout(() => {
      setStt('transcribing');
      streamPhrase(sttPhrase || (lang === 'en'
        ? 'I have stomach pain for 2 days, low fever, loose stools about 3 times.'
        : 'มีอาการ ปวดท้อง 2 วัน มีไข้ต่ำๆ ถ่ายเหลวประมาณ 3 ครั้ง'));
    }, 1100);
  };

  const streamPhrase = (phrase) => {
    let i = 0;
    const tick = () => {
      i = Math.min(i + Math.ceil(Math.random() * 2), phrase.length);
      onChange(phrase.slice(0, i));
      if (i < phrase.length) {
        charTimer.current = setTimeout(tick, 38 + Math.random() * 60);
      } else {
        setStt('done');
      }
    };
    tick();
  };

  const cancelSTT = () => {
    clearTimeout(listenTimer.current);
    clearTimeout(charTimer.current);
    setStt('idle');
    onChange('');
  };
  const stopSTT = () => {
    clearTimeout(listenTimer.current);
    clearTimeout(charTimer.current);
    setStt('done');
  };
  const sendIt = () => { onSend(); setStt('idle'); setTypeMode(false); };

  React.useEffect(() => () => {
    clearTimeout(listenTimer.current);
    clearTimeout(charTimer.current);
  }, []);

  // ── LISTENING / TRANSCRIBING — big animated panel ─────────────
  if (stt === 'listening' || stt === 'transcribing') {
    const isListening = stt === 'listening';
    return (
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24,
        padding: '32px 24px',
        background: `radial-gradient(ellipse at 50% 0%, rgba(251,115,92,.18) 0%, ${K.bg} 70%)`,
        border: `2px solid ${K.coral}`,
        borderRadius: 28,
        boxShadow: '0 12px 32px rgba(251,115,92,.18)',
      }}>
        {/* Big pulsing mic */}
        <div style={{ position: 'relative', width: 120, height: 120, flexShrink: 0 }}>
          <div style={{
            position: 'absolute', inset: -16, borderRadius: '50%',
            background: K.coral, opacity: .25,
            animation: 'kiosk-pulse 1.4s infinite',
          }}/>
          <div style={{
            position: 'absolute', inset: -32, borderRadius: '50%',
            background: K.coral, opacity: .12,
            animation: 'kiosk-pulse 1.6s .2s infinite',
          }}/>
          <div style={{
            position: 'relative', width: '100%', height: '100%', borderRadius: '50%',
            background: `linear-gradient(135deg, ${K.coral}, #C84122)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 12px 28px rgba(251,115,92,.35)',
          }}>
            <i className="ph-fill ph-microphone" style={{ fontSize: 56, color: '#fff' }}/>
          </div>
        </div>

        <div className="font-bold text-xl sm:text-3xl lg:text-4xl leading-none" style={{ color: K.coral, textAlign: 'center' }}>
          {isListening
            ? T({ th: 'กำลังฟัง...', en: 'Listening…' })
            : T({ th: 'กำลังถอดเสียง...', en: 'Transcribing…' })}
        </div>
        <div className="font-medium text-base sm:text-lg leading-snug" style={{ color: K.meta, textAlign: 'center', maxWidth: 480 }}>
          {isListening
            ? T({ th: 'พูดให้ชัดเจน — ระบบจะแปลงเสียงเป็นข้อความให้อัตโนมัติ', en: 'Speak clearly — your voice will turn into text automatically.' })
            : T({ th: 'จับใจความจากเสียงของคุณ', en: 'Capturing what you said.' })}
        </div>

        <div style={{ width: '100%', maxWidth: 520 }}>
          <VoiceWaveform active bars={48} color={K.coral}/>
        </div>

        {/* Live transcript preview */}
        {!isListening && value && (
          <div className="font-medium text-lg sm:text-xl lg:text-2xl leading-snug" style={{
            background: '#fff', border: `1px solid ${K.line}`,
            borderRadius: 18, padding: '16px 20px',
            color: K.coral, width: '100%', maxWidth: 560, textAlign: 'center',
            minHeight: 56,
          }}>
            "{value}"
          </div>
        )}

        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
          <KButton size="md" variant="secondary" onClick={stopSTT} icon="ph-stop">
            {T({ th: 'หยุด', en: 'Stop' })}
          </KButton>
          <KButton size="md" variant="ghost" onClick={cancelSTT} icon="ph-x">
            {T({ th: 'ยกเลิก', en: 'Cancel' })}
          </KButton>
        </div>
      </div>
    );
  }

  // ── DONE — preview transcript with Send / Retry / Edit ───────
  if (stt === 'done') {
    return (
      <div style={{
        display: 'flex', flexDirection: 'column', gap: 20,
        padding: '28px 24px',
        background: '#fff', border: `2px solid ${K.success}`,
        borderRadius: 28, boxShadow: '0 12px 28px rgba(40,163,56,.12)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'center' }}>
          <i className="ph-fill ph-check-circle" style={{ fontSize: 28, color: K.success }}/>
          <span className="font-semibold text-base sm:text-lg leading-none" style={{ color: K.success, letterSpacing: 1 }}>
            {T({ th: 'ถอดเสียงสำเร็จ', en: 'Transcribed' })}
          </span>
        </div>
        <div className="font-medium text-xl sm:text-2xl lg:text-3xl leading-snug" style={{
          color: K.ink, textAlign: 'center', padding: '8px 12px',
        }}>"{value}"</div>
        <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center' }}>
          <KButton size="lg" onClick={sendIt} icon="ph-paper-plane-right">
            {T({ th: 'ส่งเลย', en: 'Send' })}
          </KButton>
          <KButton size="md" variant="secondary" onClick={() => { cancelSTT(); startSTT(); }} icon="ph-arrow-counter-clockwise">
            {T({ th: 'พูดอีกครั้ง', en: 'Speak again' })}
          </KButton>
          <KButton size="md" variant="ghost" onClick={() => { setStt('idle'); setTypeMode(true); }} icon="ph-pencil-simple">
            {T({ th: 'แก้ไขข้อความ', en: 'Edit text' })}
          </KButton>
        </div>
      </div>
    );
  }

  // ── TYPE FALLBACK — keyboard input ───────────────────────────
  if (typeMode) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          background: '#fff', border: `2px solid ${K.primary900}`,
          borderRadius: 18, padding: 14,
        }}>
          <input
            type="text"
            autoFocus
            value={value}
            onChange={e => onChange(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && value.trim() && sendIt()}
            placeholder={T({ th: 'พิมพ์คำตอบ...', en: 'Type your answer…' })}
            disabled={disabled}
            className="font-medium text-lg sm:text-2xl lg:text-3xl leading-none"
            style={{
              flex: 1, border: 'none', outline: 'none',
              color: K.ink, background: 'transparent', padding: '12px 0',
              caretColor: K.primary900, minWidth: 0,
            }}/>
          <KButton size="md" onClick={sendIt}
            disabled={disabled || !value.trim()}
            icon="ph-paper-plane-right">
            {T({ th: 'ส่ง', en: 'Send' })}
          </KButton>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <button onClick={() => { setTypeMode(false); onChange(''); }} className="font-medium text-base leading-none" style={{
            border: 'none', background: 'transparent', color: K.primary900, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 8, padding: '8px 4px',
          }}>
            <i className="ph-fill ph-microphone"/> {T({ th: 'กลับไปใช้เสียง', en: 'Use voice instead' })}
          </button>
        </div>
      </div>
    );
  }

  // ── IDLE — voice-first hero ──────────────────────────────────
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
      {/* Big mic CTA */}
      <button
        onClick={startSTT}
        disabled={disabled}
        title={T({ th: 'แตะแล้วพูด', en: 'Tap and speak' })}
        style={{
          position: 'relative',
          width: 128, height: 128, borderRadius: '50%', border: 'none',
          background: `linear-gradient(135deg, ${K.primary900}, ${K.primary})`,
          color: '#fff',
          cursor: disabled ? 'not-allowed' : 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 16px 36px rgba(47,82,82,.32), 0 0 0 8px rgba(111,195,196,.18)',
          opacity: disabled ? 0.4 : 1,
          transition: 'transform .15s',
        }}
        onMouseDown={e => !disabled && (e.currentTarget.style.transform = 'scale(.96)')}
        onMouseUp={e => (e.currentTarget.style.transform = 'scale(1)')}
        onMouseLeave={e => (e.currentTarget.style.transform = 'scale(1)')}
      >
        <i className="ph-fill ph-microphone" style={{ fontSize: 64 }}/>
      </button>
      <div className="font-semibold text-lg sm:text-2xl lg:text-3xl leading-snug" style={{ color: K.ink, textAlign: 'center' }}>
        {T({ th: 'แตะที่ไมค์แล้วพูดได้เลย', en: 'Tap the mic and speak' })}
      </div>
      <div className="font-normal text-base sm:text-lg leading-snug" style={{ color: K.meta, textAlign: 'center', maxWidth: 520 }}>
        {T({ th: 'พยาบาล AI ฟังภาษาไทยและอังกฤษ', en: 'AI nurse listens in both Thai and English' })}
      </div>

      {/* Quick reply chips — small + secondary */}
      {quickReplies.length > 0 && (
        <details style={{ width: '100%' }}>
          <summary className="font-medium text-base leading-none" style={{
            cursor: 'pointer', color: K.primary900, textAlign: 'center',
            padding: '10px', listStyle: 'none', display: 'flex',
            alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            <i className="ph-fill ph-list-dashes"/> {T({ th: 'หรือเลือกคำตอบ', en: 'Or pick a quick reply' })}
          </summary>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'center', marginTop: 8 }}>
            {quickReplies.map((q, i) => (
              <button key={i} onClick={() => onQuick(q)} disabled={disabled} className="font-medium text-base sm:text-lg leading-none" style={{
                padding: '12px 18px', borderRadius: 999,
                background: '#fff', border: `1px solid ${K.line}`,
                color: K.ink2, cursor: disabled ? 'wait' : 'pointer',
                transition: 'all .15s',
              }}>{q}</button>
            ))}
          </div>
        </details>
      )}

      <button onClick={() => setTypeMode(true)} className="font-medium text-base leading-none" style={{
        border: 'none', background: 'transparent', color: K.meta, cursor: 'pointer',
        display: 'flex', alignItems: 'center', gap: 8, padding: '8px 4px',
        textDecoration: 'underline', textDecorationColor: K.line,
      }}>
        <i className="ph ph-keyboard"/> {T({ th: 'พิมพ์แทน', en: 'Type instead' })}
      </button>
    </div>
  );
}

// Phrase + quick-reply sets are aligned to the conversation turn:
// turn 0 = chief complaint (response to "what brings you in?")
// turn 1 = duration / onset
// turn 2 = severity / quality / when worst
// turn 3 = associated symptoms / radiation / swelling

function getSTTPhrase(scenario, turn, lang) {
  const phrases = lang === 'en' ? {
    fever: [
      'I have a cough, fever, and sore throat.',
      'About two days now.',
      'Moderate — bearable but it disrupts my sleep.',
      'Some clear runny nose and a mild headache too.',
    ],
    knee: [
      'My right knee hurts and walking is hard.',
      'Gradual — about two to three months, no fall.',
      'It hurts most going up and down stairs.',
      'A little swelling, no redness or warmth.',
    ],
    chest: [
      'I have tight chest pain and shortness of breath.',
      'About half an hour.',
      'It feels tight, like being squeezed.',
      'It radiates to my left arm and jaw.',
    ],
  } : {
    fever: [
      'มีไข้ ไอ และเจ็บคอ',
      'เป็นมาประมาณ 2 วันแล้ว',
      'รุนแรงปานกลาง พอทนได้ แต่นอนไม่ค่อยหลับ',
      'มีน้ำมูกใส ๆ กับปวดหัวนิดหน่อย',
    ],
    knee: [
      'ปวดเข่าขวา เดินไม่ค่อยสะดวก',
      'ค่อย ๆ ปวดมา 2-3 เดือน ไม่ได้ล้ม',
      'ปวดมากตอนขึ้น-ลงบันได',
      'บวมเล็กน้อย ไม่แดง ไม่ร้อน',
    ],
    chest: [
      'เจ็บแน่นหน้าอก หายใจหอบ',
      'เป็นมาประมาณครึ่งชั่วโมง',
      'เจ็บแบบโดนบีบ แน่น ๆ',
      'ร้าวลงแขนซ้ายและกราม',
    ],
  };
  const arr = phrases[scenario.id] || phrases.fever;
  return arr[Math.min(turn, arr.length - 1)];
}

function getQuickReplies(scenario, turn, lang) {
  const all = lang === 'en' ? {
    fever: [
      ['Cough + fever + sore throat', 'Mainly sore throat', 'Dry cough'],     // 0 chief
      ['Less than 1 day', '1–3 days', 'More than 1 week'],                    // 1 duration
      ['Mild', 'Moderate', 'Severe'],                                          // 2 severity
      ['Runny nose', 'Headache', 'Trouble breathing', 'None'],                // 3 associated
    ],
    knee: [
      ['Right knee', 'Left knee', 'Both knees'],                              // 0 chief
      ['Gradual, 2–3 months', 'Recent fall/impact', 'Not sure'],              // 1 onset
      ['Going up/down stairs', 'On waking', 'Prolonged sitting', 'All the time'], // 2 worst
      ['Mild swelling', 'Red, warm, swollen', 'No swelling'],                 // 3 swelling
    ],
    chest: [
      ['Tight chest pain', 'Short of breath', 'Tight + cannot breathe'],      // 0 chief
      ['Less than 1 hr', '1–6 hrs', 'More than 6 hrs'],                       // 1 duration
      ['Tight / squeezing', 'Burning', 'Sharp / stabbing'],                   // 2 quality
      ['Radiates to arm', 'Radiates to jaw', 'Radiates to back', 'Does not radiate'], // 3 radiation
    ],
  } : {
    fever: [
      ['ไอ มีไข้ เจ็บคอ', 'เจ็บคอเป็นหลัก', 'ไอแห้ง ๆ'],
      ['น้อยกว่า 1 วัน', '1–3 วัน', 'มากกว่า 1 สัปดาห์'],
      ['เล็กน้อย', 'ปานกลาง', 'รุนแรง'],
      ['น้ำมูก', 'ปวดศีรษะ', 'หายใจลำบาก', 'ไม่มี'],
    ],
    knee: [
      ['ปวดเข่าขวา', 'ปวดเข่าซ้าย', 'ปวด 2 ข้าง'],
      ['ค่อย ๆ เป็น 2-3 เดือน', 'มีล้ม/กระแทก', 'ไม่แน่ใจ'],
      ['ขึ้น-ลงบันได', 'ตื่นนอน', 'นั่งนาน ๆ', 'ตลอดเวลา'],
      ['บวมเล็กน้อย', 'บวมแดงร้อน', 'ไม่มี'],
    ],
    chest: [
      ['เจ็บแน่นหน้าอก', 'หายใจหอบ', 'แน่นอก หายใจไม่ออก'],
      ['ไม่ถึง 1 ชม.', '1–6 ชม.', 'มากกว่า 6 ชม.'],
      ['แน่น/บีบ', 'แสบ/ร้อน', 'จี๊ด/แปลบ'],
      ['ร้าวแขน', 'ร้าวกราม', 'ร้าวหลัง', 'ไม่ร้าว'],
    ],
  };
  const sets = all[scenario.id] || all.fever;
  return sets[Math.min(turn, sets.length - 1)] || [];
}

// ──────────────────────────────────────────────────────────────
// 4'. VITALS WITH VISION MODE
// ──────────────────────────────────────────────────────────────
function ScreenVitalsAI({ scenario, onNext }) {
  const T = useT();
  const { lang } = useLang();
  const [mode, setMode] = React.useState('vision'); // vision | device
  const [phase, setPhase] = React.useState('intro'); // intro | scan | done
  const [progress, setProgress] = React.useState(0);
  const v = scenario.vitals;
  const flags = scenario.vitalsFlags || {};

  React.useEffect(() => {
    if (phase !== 'scan') return;
    let p = 0;
    const t = setInterval(() => { p += 2.5; setProgress(p); if (p >= 100) { clearInterval(t); setTimeout(() => setPhase('done'), 500); } }, 80);
    return () => clearInterval(t);
  }, [phase]);

  return (
    <ScreenShell title={T({ th: 'วัดสัญญาณชีพ', en: 'Vital signs' })} subtitle={mode === 'vision' ? T({ th: 'Contactless Vision-Based · ไม่ต้องสัมผัสอุปกรณ์', en: 'Contactless vision-based · no device contact' }) : T({ th: 'เชื่อมต่อ Bluetooth medical devices', en: 'Connect Bluetooth medical devices' })}>
      {/* Mode switcher */}
      {phase === 'intro' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-5">
            <ModeCard active={mode === 'vision'} onClick={() => setMode('vision')}
              icon="ph-camera" badge={T({ th: 'NEW · AI', en: 'NEW · AI' })}
              title="Vision-based"
              sub={T({ th: 'กล้องหน้าจออ่านชีพจร, อัตราการหายใจ และระดับความเครียดจากใบหน้า · 30 วินาที', en: 'Front camera reads pulse, respiratory rate, and stress from your face · 30 sec' })}/>
            <ModeCard active={mode === 'device'} onClick={() => setMode('device')}
              icon="ph-cuff"
              title="Medical Devices"
              sub={T({ th: 'ใช้เครื่องวัดมาตรฐาน — ปลอกแขน, pulse oximeter, เทอร์โมมิเตอร์', en: 'Use standard devices — cuff, pulse oximeter, thermometer' })}/>
          </div>
          {mode === 'vision' && (
            <KCard padding={32}>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6 sm:gap-8 items-center">
                <div>
                  <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-snug" style={{ color: K.ink, marginBottom: 12 }}>{T({ th: 'เทคโนโลยี rPPG', en: 'rPPG technology' })}</div>
                  <div className="font-normal text-base sm:text-lg leading-normal" style={{ color: K.ink2, marginBottom: 16 }}>
                    {lang === 'en'
                      ? <>Remote Photoplethysmography — the camera detects skin-color changes from blood flow to extract vital signs <b>without touching any device.</b></>
                      : <>Remote Photoplethysmography — กล้องตรวจจับการเปลี่ยนแปลงสีผิวจากการไหลเวียนเลือดเพื่อสกัดสัญญาณชีพ <b>โดยไม่ต้องสัมผัสอุปกรณ์</b></>}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    <Bullet icon="ph-heartbeat" label={T({ th: 'อัตราการเต้นของหัวใจ', en: 'Heart rate' })}/>
                    <Bullet icon="ph-wind" label={T({ th: 'อัตราการหายใจ', en: 'Respiratory rate' })}/>
                    <Bullet icon="ph-drop" label={T({ th: 'ระดับ SpO₂ (โดยประมาณ)', en: 'SpO₂ level (estimated)' })}/>
                    <Bullet icon="ph-thermometer-simple" label={T({ th: 'อุณหภูมิผิวหน้า (IR sensor)', en: 'Skin temperature (IR sensor)' })}/>
                    <Bullet icon="ph-brain" label={T({ th: 'ระดับความเครียด (HRV)', en: 'Stress level (HRV)' })}/>
                  </div>
                </div>
                <div style={{
                  background: '#0F2A2C', borderRadius: 24, padding: 24,
                  position: 'relative', overflow: 'hidden',
                }}>
                  <VisionFeed active={false} hr={v.hr}/>
                </div>
              </div>
            </KCard>
          )}
          {mode === 'device' && (
            <KCard padding={28}>
              <DeviceStep n={1} icon="ph-thermometer-simple" title={T({ th: 'วัดอุณหภูมิ', en: 'Take temperature' })} sub={T({ th: 'วางหน้าผากใกล้เซนเซอร์ด้านบนของจอ', en: 'Hold forehead near sensor at top of screen' })}/>
              <DeviceStep n={2} icon="ph-cuff" title={T({ th: 'วัดความดันโลหิต', en: 'Take blood pressure' })} sub={T({ th: 'สวมปลอกแขนที่แขนขวา · เครื่องจะปั๊มอัตโนมัติ', en: 'Wear cuff on right arm · auto-inflates' })}/>
              <DeviceStep n={3} icon="ph-heartbeat" title={T({ th: 'วัดอัตราการเต้นของหัวใจ + SpO₂', en: 'Measure heart rate + SpO₂' })} sub={T({ th: 'หนีบนิ้วชี้ในเครื่อง pulse oximeter', en: 'Clip index finger in pulse oximeter' })}/>
              <DeviceStep n={4} icon="ph-scales" title={T({ th: 'ชั่งน้ำหนัก', en: 'Weigh' })} sub={T({ th: 'ยืนบนแผ่นชั่งด้านหน้าตู้', en: 'Stand on scale in front of kiosk' })} last/>
            </KCard>
          )}
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <KButton variant="secondary" size="lg" onClick={onNext}>{T({ th: 'ข้ามขั้นตอนนี้', en: 'Skip this step' })}</KButton>
            <KButton size="lg" onClick={() => setPhase('scan')} iconRight="ph-play">{T({ th: `เริ่มวัด ${mode === 'vision' ? '(ไม่ต้องสัมผัส)' : ''}`, en: `Start scan ${mode === 'vision' ? '(contactless)' : ''}` })}</KButton>
          </div>
        </div>
      )}

      {phase === 'scan' && mode === 'vision' && (
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5 sm:gap-7 items-start">
          <div style={{ background: '#0F2A2C', borderRadius: 24, padding: 18 }}>
            <VisionFeed active={true} hr={v.hr}/>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <KCard padding={24}>
              <div className="font-semibold text-base sm:text-lg leading-none" style={{ color: K.meta, marginBottom: 8, letterSpacing: 1 }}>
                LIVE rPPG SIGNAL
              </div>
              <RPPGGraph width={420} height={120} hr={v.hr}/>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12 }}>
                <span className="font-medium text-base leading-none" style={{ color: K.meta }}>SNR: 24.5 dB</span>
                <span className="font-medium text-base leading-none" style={{ color: K.success }}>● Locked</span>
              </div>
            </KCard>
            <KCard padding={24}>
              <div className="font-semibold text-base leading-none" style={{ color: K.meta, marginBottom: 12, letterSpacing: 1 }}>
                EXTRACTING VITALS · {progress}%
              </div>
              <div style={{ height: 8, background: K.line, borderRadius: 999, overflow: 'hidden', marginBottom: 18 }}>
                <div style={{ width: `${progress}%`, height: '100%', background: `linear-gradient(90deg, ${K.primary} 0%, ${K.primary900} 100%)`, transition: 'width .15s' }}/>
              </div>
              <ScanLine done={progress >= 18} label={T({ th: 'กำลังจับใบหน้า...', en: 'Locking face...' })}/>
              <ScanLine done={progress >= 35} label={T({ th: 'วัดอัตราการเต้นของหัวใจ', en: 'Measuring heart rate' })}/>
              <ScanLine done={progress >= 55} label={T({ th: 'ประมาณ SpO₂ จากความเข้มสีผิว', en: 'Estimating SpO₂ from skin color' })}/>
              <ScanLine done={progress >= 75} label={T({ th: 'วัดอัตราการหายใจ', en: 'Measuring respiratory rate' })}/>
              <ScanLine done={progress >= 92} label={T({ th: 'ประเมิน HRV และระดับความเครียด', en: 'Computing HRV and stress level' })}/>
            </KCard>
            <div className="font-normal text-base leading-snug" style={{
              background: K.bg, border: `1px dashed ${K.primary}`,
              borderRadius: 12, padding: 16, color: K.ink2,
            }}>
              <i className="ph-fill ph-info" style={{ color: K.primary900, marginRight: 8 }}></i>
              {T({ th: 'โปรดมองตรงไปที่กล้อง · นั่งนิ่ง ๆ · แสงสว่างเพียงพอ', en: 'Look straight at the camera · sit still · ensure good lighting' })}
            </div>
          </div>
        </div>
      )}

      {phase === 'scan' && mode === 'device' && (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 36, 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-2xl sm:text-4xl lg:text-5xl 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 ? T({ th: 'กำลังวัดอุณหภูมิ...', en: 'Measuring temperature...' }) : progress < 60 ? T({ th: 'กำลังวัดความดันโลหิต...', en: 'Measuring blood pressure...' }) : progress < 90 ? T({ th: 'กำลังวัด SpO₂...', en: 'Measuring SpO₂...' }) : T({ th: 'กำลังประมวลผล...', en: 'Processing...' })}
          </div>
        </div>
      )}

      {phase === 'done' && (
        <div style={{ marginTop: 8 }}>
          <div className="font-semibold text-lg sm:text-xl lg:text-2xl leading-none" style={{
            display: 'flex', alignItems: 'center', gap: 16,
            background: K.successBg, color: K.success,
            padding: '20px 28px', borderRadius: 20, marginBottom: 24,
          }}>
            <i className="ph-fill ph-check-circle" style={{ fontSize: 32 }}></i>
            {T({ th: `วัดเสร็จเรียบร้อย ${mode === 'vision' ? '· แบบ contactless' : ''} · ส่งข้อมูลให้ AI`, en: `Scan complete ${mode === 'vision' ? '· contactless' : ''} · sending to AI` })}
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
            <VitalTile label={T({ th: 'อุณหภูมิ', en: 'Temp' })} value={v.temp.toFixed(1)} unit="°C" icon="ph-thermometer-simple" status={flags.temp || 'normal'}/>
            <VitalTile label={T({ th: 'ความดันโลหิต', en: 'BP' })} value={`${v.sbp}/${v.dbp}`} unit="mmHg" icon="ph-cuff" status={flags.sbp || 'normal'}/>
            <VitalTile label={T({ th: 'อัตราหัวใจ', en: 'HR' })} 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={T({ th: 'อัตราหายใจ', en: 'RR' })} value={mode === 'vision' ? '16' : v.weight} unit={mode === 'vision' ? '/min' : 'kg'} icon={mode === 'vision' ? 'ph-wind' : 'ph-scales'} status="normal"/>
            <VitalTile label={mode === 'vision' ? T({ th: 'ความเครียด (HRV)', en: 'Stress (HRV)' }) : 'BMI'} value={mode === 'vision' ? T({ th: 'ปกติ', en: 'Normal' }) : (v.weight / 1.7 / 1.7).toFixed(1)} unit={mode === 'vision' ? '' : 'kg/m²'} icon="ph-brain" status="normal"/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 28 }}>
            <KButton size="lg" onClick={onNext} iconRight="ph-arrow-right">{T({ th: 'วิเคราะห์ด้วย AI', en: 'Analyze with AI' })}</KButton>
          </div>
        </div>
      )}
    </ScreenShell>
  );
}

function ModeCard({ active, onClick, icon, title, sub, badge }) {
  return (
    <button onClick={onClick} style={{
      background: active ? K.primary900 : '#fff',
      color: active ? '#fff' : K.ink,
      border: `2px solid ${active ? K.primary900 : K.line}`,
      borderRadius: 24, padding: 28, cursor: 'pointer', textAlign: 'left',
      display: 'flex', flexDirection: 'column', gap: 14,
      position: 'relative',
    }}>
      {badge && (
        <span className="font-bold text-base leading-none" style={{
          position: 'absolute', top: 14, right: 14,
          background: K.coral, color: '#fff',
          padding: '4px 10px', borderRadius: 999,
          letterSpacing: 1,
        }}>{badge}</span>
      )}
      <div style={{
        width: 64, height: 64, borderRadius: 16,
        background: active ? 'rgba(255,255,255,.18)' : K.primary050,
        color: active ? '#fff' : K.primary900,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        <i className={`ph ${icon}`} style={{ fontSize: 36 }}></i>
      </div>
      <div className="font-bold text-xl sm:text-3xl lg:text-4xl leading-tight">{title}</div>
      <div className="font-normal text-base leading-snug" style={{ opacity: active ? 0.85 : 0.7 }}>{sub}</div>
    </button>
  );
}

function Bullet({ icon, label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <i className={`ph-fill ${icon}`} style={{ fontSize: 18, color: K.primary900 }}></i>
      <span className="font-medium text-base leading-snug" style={{ color: K.ink2 }}>{label}</span>
    </div>
  );
}

function ScanLine({ done, label }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0',
      opacity: done ? 1 : 0.5, transition: 'opacity .3s',
    }}>
      <i className={`ph-fill ${done ? 'ph-check-circle' : 'ph-circle-notch'}`}
         style={{ fontSize: 20, color: done ? K.success : K.meta, animation: done ? 'none' : 'kiosk-spin 1s linear infinite' }}/>
      <span className="font-medium text-base leading-none" style={{ color: K.ink2 }}>{label}</span>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// 5'. AI ANALYSIS WITH NEURAL NET + REASONING + COHORT
// ──────────────────────────────────────────────────────────────
function ScreenAIAdvanced({ scenario, onNext, onRestart }) {
  const T = useT();
  const ai = scenario.ai;
  const isER = ai.urgencyLevel >= 4;
  const [shown, setShown] = React.useState(false);
  React.useEffect(() => {
    const t = setTimeout(() => setShown(true), 30);
    return () => clearTimeout(t);
  }, []);

  const urgencyTone = isER
    ? { bg: K.dangerBg, fg: K.danger }
    : ai.urgencyLevel >= 3
      ? { bg: K.warningBg, fg: K.warning }
      : { bg: K.successBg, fg: K.success };

  const conditions = (ai.conditions || []).slice(0, 3);

  const handleShare = () => {
    if (typeof onNext === 'function') onNext();
  };
  const handleRestart = () => {
    if (typeof onRestart === 'function') onRestart();
  };

  return (
    <div className="flex flex-col w-full min-h-screen pb-[max(1.5rem,env(safe-area-inset-bottom))]" style={{ background: K.bg, color: K.ink }}>
      {/* Top bar — dark band with logo, lang toggle, close X */}
      <div className="flex items-center justify-between px-4 py-3 sm:px-6 sm:py-4 shrink-0" style={{ background: K.primary900, color: '#fff' }}>
        <img
          src="assets/mordee-logo.png"
          alt="MorDee"
          className="block h-7 sm:h-8"
          style={{ filter: 'brightness(0) invert(1)' }}
        />
        <div className="flex items-center gap-2 sm:gap-3">
          <LangToggle size="sm" tone="dark"/>
          <button
            onClick={handleRestart}
            aria-label={T({ th: 'ปิดและเริ่มใหม่', en: 'Close and restart' })}
            className="flex items-center justify-center rounded-full text-lg leading-none"
            style={{
              width: 36, height: 36,
              background: 'rgba(255,255,255,.12)',
              color: '#fff', border: 'none', cursor: 'pointer',
            }}>
            <i className="ph ph-x"></i>
          </button>
        </div>
      </div>

      {/* Body */}
      <div
        className="flex-1 flex flex-col px-4 sm:px-6 pt-5 sm:pt-6 gap-4 sm:gap-5"
        style={{ opacity: shown ? 1 : 0, transition: 'opacity 800ms ease' }}>

        {/* Header */}
        <div className="shrink-0">
          <h1 className="font-bold text-2xl sm:text-3xl leading-tight tracking-tight" style={{ color: K.ink }}>
            {T({ th: 'สรุปผลตรวจอาการ', en: 'Symptom Check Summary' })}
          </h1>
          <p className="font-normal text-sm sm:text-base leading-snug mt-1" style={{ color: K.meta }}>
            {T({ th: 'AI วิเคราะห์เบื้องต้นจากอาการที่คุณแจ้ง', en: 'AI preliminary analysis from your reported symptoms' })}
          </p>
        </div>

        {/* Unified summary card */}
        <div
          className="rounded-2xl p-4 sm:p-5 flex flex-col gap-4"
          style={{
            background: '#fff',
            border: `1px solid ${K.line}`,
            boxShadow: '0 4px 16px rgba(47,82,82,.06)',
          }}>

          {/* 3-stat row: department, urgency, wait */}
          <div className="grid grid-cols-3 gap-2 sm:gap-3">
            <div className="flex flex-col gap-1">
              <div className="font-medium text-xs leading-none uppercase tracking-wide" style={{ color: K.meta }}>
                {T({ th: 'แผนก', en: 'Department' })}
              </div>
              <div className="font-bold text-base sm:text-lg leading-tight" style={{ color: K.primary900 }}>
                {T(ai.department)}
              </div>
            </div>
            <div className="flex flex-col gap-1">
              <div className="font-medium text-xs leading-none uppercase tracking-wide" style={{ color: K.meta }}>
                {T({ th: 'ความเร่งด่วน', en: 'Urgency' })}
              </div>
              <span
                className="inline-flex items-center self-start rounded-full font-semibold text-xs sm:text-sm leading-none px-2.5 py-1"
                style={{ background: urgencyTone.bg, color: urgencyTone.fg }}>
                {T(ai.urgency)}
              </span>
            </div>
            <div className="flex flex-col gap-1">
              <div className="font-medium text-xs leading-none uppercase tracking-wide" style={{ color: K.meta }}>
                {T({ th: 'คิวรอ', en: 'Wait' })}
              </div>
              <div className="font-bold text-base sm:text-lg leading-tight" style={{ color: K.ink }}>
                {T(ai.wait)}
              </div>
            </div>
          </div>

          <div className="h-px w-full" style={{ background: K.line }}/>

          {/* Top 3 conditions with probability bars */}
          <div className="flex flex-col gap-3">
            <div className="font-semibold text-sm leading-none" style={{ color: K.ink2 }}>
              {T({ th: 'ภาวะที่เป็นไปได้สูงสุด', en: 'Top possible conditions' })}
            </div>
            {conditions.map((c, i) => (
              <div key={i} className="flex flex-col gap-1.5">
                <div className="flex items-center justify-between gap-2">
                  <div className="font-medium text-sm sm:text-base leading-tight truncate" style={{ color: K.ink }}>
                    {T(c.name)}
                  </div>
                  <div
                    className="font-bold text-sm sm:text-base leading-none shrink-0"
                    style={{ color: i === 0 ? K.primary900 : K.meta }}>
                    {c.prob}%
                  </div>
                </div>
                <div className="h-1.5 rounded-full overflow-hidden" style={{ background: K.line }}>
                  <div
                    className="h-full rounded-full"
                    style={{
                      width: `${c.prob}%`,
                      background: i === 0 ? K.primary900 : K.primary,
                    }}/>
                </div>
              </div>
            ))}
          </div>

          {/* Disclaimer microcopy */}
          <div
            className="flex items-start gap-2 rounded-lg p-2.5 font-normal text-xs leading-snug"
            style={{ background: K.warningBg, color: K.warning }}>
            <i className="ph-fill ph-info text-base leading-none mt-px"></i>
            <span>
              {T({ th: 'คำแนะนำเบื้องต้น · ควรพบแพทย์เพื่อยืนยันการวินิจฉัย', en: 'Preliminary guidance only - see a doctor for diagnosis' })}
            </span>
          </div>
        </div>

        {/* CTAs */}
        <div className="flex flex-col gap-2 mt-auto pb-2">
          <button
            onClick={handleRestart}
            className="w-full rounded-full font-semibold text-base sm:text-lg leading-none flex items-center justify-center gap-2 py-3.5"
            style={{ background: K.primary900, color: '#fff', border: 'none', cursor: 'pointer' }}>
            <i className="ph ph-arrow-counter-clockwise"></i>
            {T({ th: 'เริ่มตรวจใหม่', en: 'Start over' })}
          </button>
          <button
            onClick={handleShare}
            className="w-full rounded-full font-medium text-base sm:text-lg leading-none flex items-center justify-center gap-2 py-3.5"
            style={{ background: '#fff', color: K.primary900, border: `1.5px solid ${K.primary900}`, cursor: 'pointer' }}>
            <i className="ph ph-share-network"></i>
            {T({ th: 'บันทึก / แชร์', en: 'Save / Share' })}
          </button>
        </div>
      </div>
    </div>
  );
}

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 leading-snug" style={{ color: K.meta, marginTop: 4 }}>{sub}</div>
      </div>
    </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>
  );
}

window.ScreenTriageAI = ScreenTriageAI;
window.ScreenVitalsAI = ScreenVitalsAI;
window.ScreenAIAdvanced = ScreenAIAdvanced;
