// 하루결 — 검사 가이드 화면

function ExamsScreen({ navigate, examId }) {
  if (examId) {
    const ex = EXAMS.find(e => e.id === examId);
    if (!ex) return <ExamsListScreen navigate={navigate} />;
    return <ExamDetailScreen navigate={navigate} exam={ex} />;
  }
  return <ExamsListScreen navigate={navigate} />;
}

function ExamsListScreen({ navigate }) {
  const s = useStore();
  const today = todayISO();
  const [query, setQuery] = React.useState('');

  // 다가오는 일정 중 검사가 있는 것
  const upcomingExams = s.schedules
    .filter(sc => sc.date >= today && examTypeFor(sc.title))
    .sort((a, b) => (a.date + a.time).localeCompare(b.date + b.time))
    .slice(0, 3);

  const filtered = query
    ? EXAMS.filter(e => (e.name + e.en).toLowerCase().includes(query.toLowerCase()))
    : EXAMS;

  return (
    <>
      <ScreenHeader
        title="검사 가이드"
        sub="금식·준비물·주의사항"
        back onBack={() => navigate('more')}
      />

      {/* 다가오는 검사 */}
      {upcomingExams.length > 0 && (
        <div style={{ padding: '6px 22px 0' }}>
          <Eyebrow color="var(--hg-clay)">곧 받는 검사</Eyebrow>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {upcomingExams.map((sc) => {
              const exam = examTypeFor(sc.title);
              const daysLeft = daysBetween(today, sc.date);
              return (
                <button key={sc.id} onClick={() => navigate(`exams/${exam.id}`)} style={{
                  width: '100%', textAlign: 'left',
                  padding: 14, borderRadius: 16,
                  background: 'linear-gradient(120deg, var(--hg-clay-tint), var(--hg-surface))',
                  border: '1px solid rgba(181,117,90,0.24)',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 12,
                    background: 'var(--hg-clay)', color: '#fff',
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                    fontFamily: '"Noto Serif KR", serif', fontSize: 16, fontWeight: 600,
                  }}>{daysLeft === 0 ? '오늘' : `D-${daysLeft}`}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>{sc.title}</div>
                    <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 2 }}>
                      {fmtMonth(sc.date)} {sc.time}
                      {exam.fasting.required && <span style={{ color: 'var(--hg-rose)', fontWeight: 700 }}> · 금식 {exam.fasting.hours}시간</span>}
                    </div>
                  </div>
                  <span style={{ color: 'var(--hg-clay)', fontSize: 16, flexShrink: 0 }}>›</span>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* 검색 */}
      <div style={{ padding: '16px 22px 0' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10,
          padding: '12px 14px', borderRadius: 14,
          background: 'var(--hg-surface)',
          border: '1px solid var(--hg-line)',
        }}>
          <svg width="18" height="18" viewBox="0 0 22 22" fill="none">
            <circle cx="10" cy="10" r="6" stroke="var(--hg-muted)" strokeWidth="1.8"/>
            <path d="M15 15l4 4" stroke="var(--hg-muted)" strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="예: CT, MRI, 피검사, 조직검사"
            style={{
              flex: 1, border: 'none', outline: 'none', background: 'transparent',
              fontSize: 14, color: 'var(--hg-ink)',
            }}
          />
          {query && <button onClick={() => setQuery('')} style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--hg-bg-deeper)', color: 'var(--hg-muted)', fontSize: 11 }}>✕</button>}
        </div>
      </div>

      {/* 전체 검사 */}
      <div style={{ padding: '16px 22px 24px' }}>
        <Eyebrow>모든 검사 둘러보기</Eyebrow>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {filtered.map(ex => <ExamCard key={ex.id} exam={ex} onClick={() => navigate(`exams/${ex.id}`)}/>)}
        </div>

        <div style={{
          marginTop: 22,
          padding: 14, borderRadius: 14,
          background: 'var(--hg-bg-deeper)',
          fontSize: 11, color: 'var(--hg-muted)', fontWeight: 600,
          lineHeight: 1.6, textAlign: 'center',
        }}>
          병원·검사실마다 안내가 조금 다를 수 있어요.<br/>
          정확한 지침은 받으신 안내문을 따르세요.
        </div>
      </div>
    </>
  );
}

function ExamCard({ exam, onClick }) {
  const toneC = { rose: 'var(--hg-rose)', mist: 'var(--hg-mist)', clay: 'var(--hg-clay)', sage: 'var(--hg-sage)' }[exam.tone];
  const toneBg = { rose: 'var(--hg-rose-soft)', mist: 'var(--hg-mist-tint)', clay: 'var(--hg-clay-tint)', sage: 'var(--hg-sage-tint)' }[exam.tone];
  return (
    <button onClick={onClick} style={{
      width: '100%', textAlign: 'left',
      padding: 14, borderRadius: 16,
      background: 'var(--hg-surface)',
      border: '1px solid var(--hg-line-soft)',
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 44, height: 44, borderRadius: 12,
        background: toneBg, color: toneC,
        display: 'grid', placeItems: 'center', flexShrink: 0,
      }}>
        <ExamIcon name={exam.icon} color={toneC}/>
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{exam.name}</span>
          {exam.fasting.required && <Chip bg="var(--hg-rose)" color="#fff">금식 {exam.fasting.hours}h</Chip>}
        </div>
        <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, lineHeight: 1.5, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
          {exam.duration} · {exam.purpose}
        </div>
      </div>
      <span style={{ color: 'var(--hg-muted)', fontSize: 16, flexShrink: 0 }}>›</span>
    </button>
  );
}

function ExamDetailScreen({ navigate, exam }) {
  const s = useStore();
  const today = todayISO();
  const toneC = { rose: 'var(--hg-rose)', mist: 'var(--hg-mist)', clay: 'var(--hg-clay)', sage: 'var(--hg-sage)' }[exam.tone];
  const toneBg = { rose: 'var(--hg-rose-soft)', mist: 'var(--hg-mist-tint)', clay: 'var(--hg-clay-tint)', sage: 'var(--hg-sage-tint)' }[exam.tone];

  // 일정에 추가
  const addToSchedule = () => {
    const date = prompt('검사 날짜를 입력하세요 (YYYY-MM-DD)', today);
    if (!date) return;
    const time = prompt('시간을 입력하세요 (HH:MM)', '10:00') || '10:00';
    s.addSchedule({ title: exam.name, date, time, dept: '', memo: exam.fasting.required ? `금식 ${exam.fasting.hours}시간` : '', tag: '검사', tone: exam.tone });
    showToast('일정에 추가됨');
    navigate('schedule');
  };

  return (
    <>
      <ScreenHeader title={exam.name} sub={exam.en}
        back onBack={() => navigate('exams')} />

      {/* 히어로 */}
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{
          padding: 18, borderRadius: 22,
          background: `linear-gradient(135deg, ${toneBg}, var(--hg-surface) 130%)`,
          border: `1px solid ${toneC}33`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14 }}>
            <div style={{
              width: 56, height: 56, borderRadius: 16, flexShrink: 0,
              background: toneC, color: '#fff',
              display: 'grid', placeItems: 'center',
            }}>
              <ExamIcon name={exam.icon} color="#fff" size={28}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 11, color: toneC, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase' }}>소요 시간</div>
              <div className="hg-serif" style={{ fontSize: 20, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em' }}>{exam.duration}</div>
            </div>
          </div>
          <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.7 }}>{exam.purpose}</div>
        </div>
      </div>

      {/* 금식 안내 — 가장 중요 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Panel style={{
          padding: 16,
          background: exam.fasting.required ? 'linear-gradient(135deg, #FCEEEC, var(--hg-surface))' : 'var(--hg-sage-tint)',
          borderColor: exam.fasting.required ? 'rgba(194,85,74,0.32)' : 'var(--hg-sage-soft)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 12,
              background: exam.fasting.required ? 'var(--hg-rose)' : 'var(--hg-sage)',
              color: '#fff',
              display: 'grid', placeItems: 'center', flexShrink: 0,
              fontFamily: '"Noto Serif KR", serif', fontSize: 16, fontWeight: 600,
            }}>
              {exam.fasting.required ? `${exam.fasting.hours}h` : '✓'}
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: exam.fasting.required ? 'var(--hg-rose)' : 'var(--hg-sage)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                {exam.fasting.required ? `금식 ${exam.fasting.hours}시간` : '금식 불필요'}
              </div>
              <div style={{ fontSize: 12, color: 'var(--hg-ink-2)', fontWeight: 500, lineHeight: 1.6, marginTop: 4 }}>
                {exam.fasting.note}
              </div>
            </div>
          </div>
        </Panel>
      </div>

      {/* 준비물 */}
      <Section title="준비할 것" color={toneC}>
        {exam.prepare.map((p, i) => <BulletItem key={i} num={i + 1} text={p} color={toneC} bg={toneBg}/>)}
      </Section>

      {/* 과정 */}
      <Section title="검사 과정">
        {exam.process.map((p, i) => <BulletItem key={i} num={i + 1} text={p} color="var(--hg-mist)" bg="var(--hg-mist-tint)"/>)}
      </Section>

      {/* 검사 후 */}
      <Section title="검사 후">
        {exam.after.map((p, i) => <BulletItem key={i} num={i + 1} text={p} color="var(--hg-sage)" bg="var(--hg-sage-tint)"/>)}
      </Section>

      {/* 주의 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Panel style={{ padding: 14, background: 'var(--hg-honey-tint)', borderColor: 'var(--hg-honey-soft)' }}>
          <div style={{ display: 'flex', gap: 10 }}>
            <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--hg-honey)', color: '#fff', display: 'grid', placeItems: 'center', fontWeight: 700, fontSize: 12, flexShrink: 0 }}>!</span>
            <div style={{ fontSize: 12, color: 'var(--hg-ink-2)', fontWeight: 600, lineHeight: 1.6 }}>
              {exam.caution}
            </div>
          </div>
        </Panel>
      </div>

      {/* 액션 */}
      <div style={{ padding: '20px 22px 24px' }}>
        <PrimaryButton onClick={addToSchedule} color={toneC} shadow={`0 8px 20px ${toneC}40`}>
          <span style={{ marginRight: 6, fontSize: 18, fontWeight: 300 }}>＋</span>
          일정에 추가하기
        </PrimaryButton>
      </div>
    </>
  );
}

function Section({ title, color = 'var(--hg-clay)', children }) {
  return (
    <div style={{ padding: '16px 22px 0' }}>
      <Eyebrow color={color}>{title}</Eyebrow>
      <Panel style={{ padding: 4 }}>{children}</Panel>
    </div>
  );
}

function BulletItem({ num, text, color, bg }) {
  return (
    <div style={{
      display: 'flex', gap: 12,
      padding: '12px 14px',
      borderBottom: '1px solid var(--hg-line-soft)',
    }}>
      <div style={{
        minWidth: 22, height: 22, borderRadius: '50%', flexShrink: 0,
        background: bg, color: color,
        display: 'grid', placeItems: 'center',
        fontFamily: '"Noto Serif KR", serif', fontSize: 11, fontWeight: 700,
        marginTop: 1,
      }}>{num}</div>
      <div style={{ flex: 1, fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7 }}>{text}</div>
    </div>
  );
}

function ExamIcon({ name, color, size = 22 }) {
  const sw = 1.6, c = color, s = size;
  if (name === 'blood')   return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M11 3c-3 4-5 7-5 10a5 5 0 0010 0c0-3-2-6-5-10z" stroke={c} strokeWidth={sw} fill="none" strokeLinejoin="round"/></svg>;
  if (name === 'ct')      return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="11" cy="11" r="7" stroke={c} strokeWidth={sw}/><path d="M11 4v14M4 11h14" stroke={c} strokeWidth={sw} strokeLinecap="round"/></svg>;
  if (name === 'mri')     return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><rect x="3" y="5" width="16" height="12" rx="3" stroke={c} strokeWidth={sw}/><path d="M7 11l2-3 2 4 2-2 2 1" stroke={c} strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" fill="none"/></svg>;
  if (name === 'pet')     return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><circle cx="11" cy="11" r="4" fill={c}/><circle cx="11" cy="11" r="8" stroke={c} strokeWidth={sw} strokeDasharray="2 2"/></svg>;
  if (name === 'mammo')   return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M6 11c0-4 2-7 5-7s5 3 5 7-2 7-5 7-5-3-5-7z" stroke={c} strokeWidth={sw}/><circle cx="11" cy="11" r="2" fill={c}/></svg>;
  if (name === 'us')      return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M4 8c2 2 4 3 7 3s5-1 7-3M4 12c2 2 4 3 7 3s5-1 7-3M4 16c2 2 4 3 7 3" stroke={c} strokeWidth={sw} strokeLinecap="round" fill="none"/></svg>;
  if (name === 'biopsy')  return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M4 18l8-8 4 4-8 8H4v-4zM12 10l4-4 2 2-4 4" stroke={c} strokeWidth={sw} strokeLinejoin="round" fill="none"/></svg>;
  if (name === 'bone')    return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M6 5c-1 0-2 1-2 2 0 1 .5 1.5 1 2-.5.5-1 1-1 2s1 2 2 2c0-1 1-1 2-1l6-6c0-1 0-2 1-2s2 1 2 2c1 0 2 1 2 2 0 1-.5 1.5-1 2 .5.5 1 1 1 2s-1 2-2 2c0-1-1-1-2-1l-6 6c0 1 0 2-1 2s-2-1-2-2c-1 0-2-1-2-2 0-1 .5-1.5 1-2-.5-.5-1-1-1-2" stroke={c} strokeWidth="1.4" fill="none" strokeLinejoin="round"/></svg>;
  if (name === 'heart')   return <svg width={s} height={s} viewBox="0 0 22 22" fill="none"><path d="M11 18s-7-4.2-7-9.5C4 5.5 6.5 4 8.5 4c1.4 0 2.3.6 2.5 1 .2-.4 1.1-1 2.5-1C15.5 4 18 5.5 18 8.5 18 13.8 11 18 11 18z" stroke={c} strokeWidth={sw} strokeLinejoin="round" fill="none"/></svg>;
  return null;
}

Object.assign(window, { ExamsScreen, ExamsListScreen, ExamDetailScreen, ExamIcon });
