// 하루결 — 응급 / 위험신호 + 진료 질문 + 약 + 처음 진단 가이드 + 설정

// ────────────────────────────────────────────────────────────
// 응급 화면 (전체 페이지)
// ────────────────────────────────────────────────────────────
function EmergencyScreen({ navigate }) {
  const s = useStore();
  const signs = [
    { sign: '38.0°C 이상 발열 또는 오한',         advice: '즉시 병원 연락',    level: 'red' },
    { sign: '숨이 차거나 흉통, 심한 어지러움',     advice: '응급실 권장',       level: 'red' },
    { sign: '멈추지 않는 구토·설사·출혈',          advice: '즉시 병원 연락',    level: 'red' },
    { sign: '주사 부위가 부어오르고 통증',         advice: '진료시간 내 연락',  level: 'amber' },
    { sign: '심한 두통이 진통제로 안 가라앉을 때', advice: '진료시간 내 연락',  level: 'amber' },
  ];

  const callPhone = (phone) => { window.location.href = `tel:${phone}`; };

  return (
    <div style={{
      minHeight: '100%',
      backgroundImage: `linear-gradient(180deg, rgba(42,36,29,0.55), rgba(42,36,29,0.55)), url("${IMG.morning}")`,
      backgroundSize: 'cover', backgroundPosition: 'center',
      backgroundAttachment: 'local',
      paddingTop: 0,
      display: 'flex', flexDirection: 'column',
    }}>
      <div style={{ padding: '54px 22px 12px' }}>
        <button onClick={() => navigate('home')} aria-label="뒤로" style={{
          width: 38, height: 38, borderRadius: '50%',
          background: 'rgba(255,253,247,0.18)', color: '#fff',
          backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)',
          display: 'grid', placeItems: 'center', fontSize: 18,
        }}>‹</button>
      </div>

      <div style={{
        marginTop: 'auto',
        background: 'var(--hg-surface-2)',
        borderTopLeftRadius: 36, borderTopRightRadius: 36,
        padding: '14px 24px 32px',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.3)',
      }}>
        <div style={{ width: 44, height: 5, borderRadius: 4, background: 'var(--hg-line)', margin: '0 auto 18px' }} />

        <div style={{ textAlign: 'center', marginBottom: 22 }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: 'var(--hg-rose-soft)', margin: '0 auto 12px',
            display: 'grid', placeItems: 'center',
          }}>
            <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
              <path d="M14 4v12M14 22v.5" stroke="var(--hg-rose)" strokeWidth="2.5" strokeLinecap="round"/>
              <circle cx="14" cy="14" r="11" stroke="var(--hg-rose)" strokeWidth="2"/>
            </svg>
          </div>
          <div className="hg-serif" style={{ fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--hg-ink)' }}>
            위험 신호가 있나요?
          </div>
          <div style={{ fontSize: 13, color: 'var(--hg-muted)', marginTop: 4 }}>
            아래 신호가 있으면 망설이지 마세요
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 20 }}>
          {signs.map((sg, i) => {
            const isRed = sg.level === 'red';
            return (
              <div key={i} style={{
                padding: 14, borderRadius: 16,
                background: isRed ? '#FCEEEC' : 'var(--hg-honey-tint)',
                border: '1px solid ' + (isRed ? 'rgba(194,85,74,0.32)' : 'var(--hg-honey-soft)'),
                display: 'flex', alignItems: 'center', gap: 12,
              }}>
                <div style={{
                  width: 8, height: 8, borderRadius: '50%',
                  background: isRed ? 'var(--hg-rose)' : 'var(--hg-honey)',
                  boxShadow: isRed ? '0 0 0 4px rgba(194,85,74,0.18)' : '0 0 0 4px rgba(217,166,108,0.18)',
                  flexShrink: 0,
                }} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)', lineHeight: 1.4 }}>{sg.sign}</div>
                  <div style={{ fontSize: 11, color: isRed ? 'var(--hg-rose)' : 'var(--hg-honey)', fontWeight: 700, marginTop: 3 }}>{sg.advice}</div>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{
          padding: 16, borderRadius: 20,
          background: 'var(--hg-bg-deeper)',
          marginBottom: 14,
        }}>
          <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', marginBottom: 8 }}>
            등록된 병원 연락처
          </div>
          <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--hg-ink)' }}>{s.profile.hospital}</div>
          <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>응급실 24시 · {s.profile.hospitalPhone}</div>
        </div>

        <button onClick={() => callPhone(s.profile.hospitalPhone)} style={{
          width: '100%', minHeight: 64, marginBottom: 8,
          background: 'var(--hg-rose)', color: '#fff',
          fontSize: 17, fontWeight: 800, letterSpacing: '-0.02em',
          borderRadius: 18,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          boxShadow: '0 10px 24px rgba(194,85,74,0.32)',
        }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="#fff">
            <path d="M5.5 3l3-1 2 3.8-2 2c1 3 3 5 6 6l2-2 3.8 2-1 3c-5 0-13.8-8.8-13.8-13.8z"/>
          </svg>
          병원에 바로 전화하기
        </button>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={() => callPhone(s.profile.caregiverPhone)} style={{
            flex: 1, height: 50, borderRadius: 14,
            background: 'var(--hg-surface)', color: 'var(--hg-ink)',
            border: '1px solid var(--hg-line)',
            fontSize: 13, fontWeight: 700,
          }}>보호자 호출</button>
          <button onClick={() => callPhone('119')} style={{
            flex: 1, height: 50, borderRadius: 14,
            background: 'var(--hg-surface)', color: 'var(--hg-ink)',
            border: '1px solid var(--hg-line)',
            fontSize: 13, fontWeight: 700,
          }}>119 호출</button>
        </div>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// 진료 질문 노트
// ────────────────────────────────────────────────────────────
function QuestionsScreen({ navigate, initialOpen }) {
  const s = useStore();
  const today = todayISO();
  const [openAdd, setOpenAdd] = React.useState(initialOpen || false);

  const next = [...s.schedules]
    .filter(x => x.date >= today)
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time))[0];
  const daysLeft = next ? daysBetween(today, next.date) : null;

  const open = s.questions.filter(q => !q.done);
  const done = s.questions.filter(q => q.done);

  const suggested = [
    '제가 받는 약의 정확한 이름과 목적은?',
    '이 약에서 바로 병원에 연락해야 하는 부작용은?',
    '영양제·한약·진통제와 항암제 같이 괜찮은가요?',
  ];

  return (
    <>
      <ScreenHeader title="진료 질문 노트" sub="다음 진료 전에 정리해두세요"
        back onBack={() => navigate('more')}
        action={<FAB onClick={() => setOpenAdd(true)} />}
      />

      {/* 다음 진료 */}
      {next && (
        <div style={{ padding: '6px 22px 0' }}>
          <div style={{
            padding: '14px 18px',
            background: 'linear-gradient(120deg, var(--hg-clay-tint), var(--hg-surface) 100%)',
            border: '1px solid var(--hg-line)',
            borderRadius: 18,
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: 'var(--hg-clay)', color: '#fff',
              display: 'grid', placeItems: 'center',
              fontFamily: '"Noto Serif KR", serif', fontSize: 18, fontWeight: 600,
            }}>{daysLeft}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: 'var(--hg-clay-dark)', fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase' }}>
                {daysLeft === 0 ? '오늘' : daysLeft === 1 ? '내일' : `${daysLeft}일 뒤`}
              </div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)', marginTop: 2 }}>{fmtMonth(next.date)} · {next.title}</div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>이번에 물어볼 것 <strong style={{ color: 'var(--hg-clay)' }}>{open.length}개</strong></div>
            </div>
          </div>
        </div>
      )}

      {/* 열린 질문 */}
      <div style={{ padding: '16px 22px 0' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>물어볼 것</div>
          <span style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600 }}>{open.length} / {s.questions.length}</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {open.map((q) => <QuestionRow key={q.id} q={q} onToggle={() => s.toggleQuestion(q.id)} onRemove={() => s.removeQuestion(q.id)} />)}
        </div>
      </div>

      {/* 자주 묻는 질문 */}
      <div style={{ padding: '20px 22px 0' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)', marginBottom: 10 }}>이런 것도 물어보세요</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {suggested.map((q) => (
            <button key={q} onClick={() => { s.addQuestion({ topic: q, ctx: '', cat: '기본' }); showToast('질문 추가됨'); }} style={{
              padding: '12px 14px', borderRadius: 14, textAlign: 'left',
              background: 'var(--hg-surface-2)',
              border: '1px dashed var(--hg-line)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
              fontSize: 13, color: 'var(--hg-ink-2)', fontWeight: 600,
            }}>
              <span style={{ flex: 1 }}>{q}</span>
              <span style={{
                width: 24, height: 24, borderRadius: '50%',
                background: 'var(--hg-clay-tint)', color: 'var(--hg-clay)',
                display: 'grid', placeItems: 'center', fontSize: 14, flexShrink: 0,
              }}>＋</span>
            </button>
          ))}
        </div>
      </div>

      {/* 완료된 질문 */}
      {done.length > 0 && (
        <div style={{ padding: '20px 22px 24px' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-muted)', marginBottom: 10 }}>완료 {done.length}</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {done.map((q) => <QuestionRow key={q.id} q={q} onToggle={() => s.toggleQuestion(q.id)} onRemove={() => s.removeQuestion(q.id)} />)}
          </div>
        </div>
      )}

      <div style={{ height: 24 }} />

      {openAdd && <AddQuestionSheet onClose={() => setOpenAdd(false)} onAdd={(x) => { s.addQuestion(x); showToast('질문 추가됨'); setOpenAdd(false); }} />}
    </>
  );
}

function QuestionRow({ q, onToggle, onRemove }) {
  return (
    <div style={{
      padding: 14, borderRadius: 16,
      background: q.done ? 'var(--hg-bg-deeper)' : 'var(--hg-surface)',
      border: '1px solid ' + (q.urgent && !q.done ? 'rgba(194,85,74,0.32)' : 'var(--hg-line-soft)'),
      display: 'flex', gap: 12,
      opacity: q.done ? 0.65 : 1,
    }}>
      <Checkbox checked={q.done} onClick={onToggle} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, flexWrap: 'wrap' }}>
          {q.cat && <Chip style={{ background: q.urgent ? 'var(--hg-rose-soft)' : 'var(--hg-mist-tint)', color: q.urgent ? 'var(--hg-rose)' : 'var(--hg-mist)' }}>{q.cat}</Chip>}
          {q.urgent && !q.done && <Chip style={{ background: 'var(--hg-rose)', color: '#fff' }}>꼭 묻기</Chip>}
        </div>
        <div style={{
          fontSize: 14, fontWeight: 600, color: q.done ? 'var(--hg-muted)' : 'var(--hg-ink)',
          lineHeight: 1.5, textDecoration: q.done ? 'line-through' : 'none',
        }}>{q.topic}</div>
        {q.ctx && <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 6, paddingLeft: 10, borderLeft: '2px solid var(--hg-line)' }}>{q.ctx}</div>}
      </div>
      <button onClick={onRemove} style={{ width: 22, height: 22, color: 'var(--hg-muted)', fontSize: 11, alignSelf: 'flex-start' }}>✕</button>
    </div>
  );
}

function AddQuestionSheet({ onClose, onAdd }) {
  const [form, setForm] = React.useState({ topic: '', ctx: '', cat: '부작용', urgent: false });
  const cats = ['부작용', '식사·체중', '약·상호작용', '생활', '감염예방', '기타'];

  return (
    <Sheet title="질문 추가" onClose={onClose}>
      <label className="hg-label">무엇이 궁금해요?</label>
      <textarea className="hg-textarea" placeholder="예: 손발저림이 점점 심해져요, 약 용량 조정 가능한가요?" value={form.topic} onChange={(e) => setForm({ ...form, topic: e.target.value })}/>

      <label className="hg-label" style={{ marginTop: 14 }}>관련 상황 (선택)</label>
      <input className="hg-input" placeholder="예: 항암 3일째부터" value={form.ctx} onChange={(e) => setForm({ ...form, ctx: e.target.value })}/>

      <label className="hg-label" style={{ marginTop: 14 }}>분류</label>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {cats.map(c => (
          <button key={c} onClick={() => setForm({ ...form, cat: c })} style={{
            padding: '8px 14px', borderRadius: 999,
            background: form.cat === c ? 'var(--hg-mist)' : 'var(--hg-bg-deeper)',
            color: form.cat === c ? '#fff' : 'var(--hg-ink-2)',
            fontSize: 12, fontWeight: 700,
          }}>{c}</button>
        ))}
      </div>

      <button onClick={() => setForm({ ...form, urgent: !form.urgent })} style={{
        marginTop: 18, padding: 14, borderRadius: 14, width: '100%',
        background: form.urgent ? 'var(--hg-rose-soft)' : 'var(--hg-bg-deeper)',
        border: '1px solid ' + (form.urgent ? 'var(--hg-rose)' : 'var(--hg-line-soft)'),
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <Checkbox checked={form.urgent} />
        <div style={{ flex: 1, textAlign: 'left' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: form.urgent ? 'var(--hg-rose)' : 'var(--hg-ink)' }}>꼭 묻기로 표시</div>
          <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 2 }}>중요한 질문일 때</div>
        </div>
      </button>

      <div style={{ marginTop: 18 }}>
        <PrimaryButton disabled={!form.topic} onClick={() => onAdd(form)}>저장</PrimaryButton>
      </div>
    </Sheet>
  );
}

Object.assign(window, { EmergencyScreen, QuestionsScreen });
