// 하루결 — 검사 설명 화면

function LabsScreen({ navigate, termId }) {
  if (termId) {
    const term = LAB_TERMS.find(t => t.id === termId);
    if (!term) return <LabsListScreen navigate={navigate} />;
    return <LabTermDetailScreen navigate={navigate} term={term} />;
  }
  return <LabsListScreen navigate={navigate} />;
}

function LabsListScreen({ navigate }) {
  const s = useStore();
  const [query, setQuery] = React.useState('');
  const [cat, setCat] = React.useState('all');
  const [tab, setTab] = React.useState('browse'); // browse | mine

  let results = query ? searchLabs(query) : LAB_TERMS;
  if (cat !== 'all') results = results.filter(t => t.cat === cat);

  const myValues = s.labValues || [];

  return (
    <>
      <ScreenHeader
        title="검사지 설명"
        sub="병원 검사지의 영어 약자를 풀어드려요"
        back onBack={() => navigate('more')}
      />

      {/* 탭 */}
      <div style={{ padding: '6px 22px 0' }}>
        <div style={{
          display: 'flex', gap: 6, padding: 4,
          background: 'var(--hg-bg-deeper)',
          borderRadius: 14, border: '1px solid var(--hg-line-soft)',
        }}>
          <button onClick={() => setTab('browse')} style={{
            flex: 1, padding: '10px 0', borderRadius: 11,
            background: tab === 'browse' ? 'var(--hg-surface-2)' : 'transparent',
            color: tab === 'browse' ? 'var(--hg-clay-dark)' : 'var(--hg-muted)',
            fontSize: 13, fontWeight: tab === 'browse' ? 700 : 600,
            boxShadow: tab === 'browse' ? '0 1px 3px rgba(74,54,32,0.08)' : 'none',
          }}>용어 사전</button>
          <button onClick={() => setTab('mine')} style={{
            flex: 1, padding: '10px 0', borderRadius: 11,
            background: tab === 'mine' ? 'var(--hg-surface-2)' : 'transparent',
            color: tab === 'mine' ? 'var(--hg-clay-dark)' : 'var(--hg-muted)',
            fontSize: 13, fontWeight: tab === 'mine' ? 700 : 600,
            boxShadow: tab === 'mine' ? '0 1px 3px rgba(74,54,32,0.08)' : 'none',
          }}>내 수치 기록</button>
        </div>
      </div>

      {tab === 'browse' ? (
        <>
          {/* 검색 */}
          <div style={{ padding: '14px 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="예: WBC, 호중구, ER, Ki-67, 병기"
                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: '12px 22px 0' }}>
            <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4 }}>
              <CatChip label="전체" on={cat === 'all'} onClick={() => setCat('all')} c="var(--hg-clay)" bg="var(--hg-clay-tint)"/>
              {LAB_CATEGORIES.map(c => (
                <CatChip key={c.id} label={c.label} on={cat === c.id} onClick={() => setCat(c.id)} c={c.c} bg={c.bg}/>
              ))}
            </div>
          </div>

          {/* 결과 */}
          <div style={{ padding: '14px 22px 24px' }}>
            {results.length === 0 ? (
              <div style={{ padding: 30, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 13, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
                검색 결과가 없어요
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {results.map(t => {
                  const c = LAB_CATEGORIES.find(x => x.id === t.cat);
                  return (
                    <button key={t.id} onClick={() => navigate(`labs/${t.id}`)} 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={{
                        minWidth: 50, height: 50, borderRadius: 12, flexShrink: 0,
                        background: c.bg, color: c.c,
                        display: 'grid', placeItems: 'center', padding: 4,
                        fontSize: 11, fontWeight: 800, letterSpacing: '-0.02em', textAlign: 'center',
                      }}>{t.abbr}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap' }}>
                          <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{t.name}</span>
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 2, lineHeight: 1.5, overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                          {t.short}
                        </div>
                      </div>
                      <span style={{ color: 'var(--hg-muted)', fontSize: 16, flexShrink: 0 }}>›</span>
                    </button>
                  );
                })}
              </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>
        </>
      ) : (
        <MyLabsTab navigate={navigate} myValues={myValues} />
      )}
    </>
  );
}

function MyLabsTab({ navigate, myValues }) {
  const s = useStore();
  const [openAdd, setOpenAdd] = React.useState(false);

  // 항목별로 그룹화 → 추세 보기
  const grouped = {};
  myValues.forEach(v => { (grouped[v.termId] = grouped[v.termId] || []).push(v); });
  Object.values(grouped).forEach(list => list.sort((a, b) => b.date.localeCompare(a.date)));

  return (
    <>
      <div style={{ padding: '14px 22px 0' }}>
        <button onClick={() => setOpenAdd(true)} style={{
          width: '100%', minHeight: 60,
          background: 'linear-gradient(135deg, var(--hg-clay), var(--hg-clay-dark))',
          color: '#fff', borderRadius: 16,
          padding: '14px 18px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
          boxShadow: '0 8px 20px rgba(181,117,90,0.28)',
        }}>
          <div style={{ textAlign: 'left' }}>
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.05em', textTransform: 'uppercase', opacity: 0.85 }}>오늘 검사 결과</div>
            <div className="hg-serif" style={{ fontSize: 17, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 2 }}>검사 수치 기록하기</div>
          </div>
          <span style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'grid', placeItems: 'center', fontSize: 20, fontWeight: 300 }}>＋</span>
        </button>
      </div>

      <div style={{ padding: '18px 22px 24px' }}>
        {Object.keys(grouped).length === 0 ? (
          <div style={{ padding: 30, textAlign: 'center', color: 'var(--hg-muted)', fontSize: 13, background: 'var(--hg-surface)', borderRadius: 16, border: '1px dashed var(--hg-line)' }}>
            아직 기록한 수치가 없어요.<br/>병원에서 받은 검사지의 숫자를 입력해두면<br/>시간에 따른 변화를 볼 수 있어요.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {Object.entries(grouped).map(([termId, list]) => {
              const term = LAB_TERMS.find(t => t.id === termId);
              if (!term) return null;
              const c = LAB_CATEGORIES.find(x => x.id === term.cat);
              return (
                <button key={termId} onClick={() => navigate(`labs/${termId}`)} style={{
                  width: '100%', textAlign: 'left',
                  padding: 14, borderRadius: 16,
                  background: 'var(--hg-surface)',
                  border: '1px solid var(--hg-line-soft)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                    <div style={{
                      minWidth: 44, height: 44, borderRadius: 12,
                      background: c.bg, color: c.c,
                      display: 'grid', placeItems: 'center',
                      fontSize: 10, fontWeight: 800, letterSpacing: '-0.02em', textAlign: 'center', padding: 4,
                    }}>{term.abbr}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--hg-ink)' }}>{term.name}</div>
                      <div style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 600 }}>정상 {term.range}</div>
                    </div>
                    <span style={{ color: 'var(--hg-muted)', fontSize: 16 }}>›</span>
                  </div>
                  <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
                    {list.slice(0, 4).map((v, i) => (
                      <div key={v.id} style={{
                        minWidth: 70, padding: '8px 10px', borderRadius: 10,
                        background: i === 0 ? c.bg : 'var(--hg-bg-deeper)',
                        border: `1px solid ${i === 0 ? c.c + '33' : 'var(--hg-line-soft)'}`,
                        textAlign: 'center',
                      }}>
                        <div className="hg-serif" style={{ fontSize: 16, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em', lineHeight: 1 }}>{v.value}</div>
                        <div style={{ fontSize: 9, color: 'var(--hg-muted)', fontWeight: 600, marginTop: 4 }}>{v.date.slice(5).replace('-','/')}</div>
                      </div>
                    ))}
                  </div>
                </button>
              );
            })}
          </div>
        )}
      </div>

      {openAdd && <AddLabValueSheet onClose={() => setOpenAdd(false)} onAdd={(v) => {
        const list = [...(s.labValues || []), { ...v, id: 'lv' + Date.now() }];
        Store.save(K.labValues, list);
        showToast('수치 저장됨');
        setOpenAdd(false);
      }}/>}
    </>
  );
}

function AddLabValueSheet({ onClose, onAdd }) {
  const [form, setForm] = React.useState({
    date: todayISO(),
    termId: 'wbc',
    value: '',
    unit: '',
  });
  const term = LAB_TERMS.find(t => t.id === form.termId);
  const cat = LAB_CATEGORIES.find(c => c.id === term.cat);
  const [catFilter, setCatFilter] = React.useState(term.cat);

  const termsInCat = LAB_TERMS.filter(t => t.cat === catFilter);

  return (
    <Sheet title="검사 수치 기록" onClose={onClose}>
      <label className="hg-label">검사 분야</label>
      <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4, marginBottom: 4 }}>
        {LAB_CATEGORIES.map(c => (
          <button key={c.id} onClick={() => setCatFilter(c.id)} style={{
            padding: '8px 14px', borderRadius: 999, whiteSpace: 'nowrap', flexShrink: 0,
            background: catFilter === c.id ? c.c : c.bg,
            color: catFilter === c.id ? '#fff' : c.c,
            fontSize: 12, fontWeight: 700,
            border: '1px solid ' + (catFilter === c.id ? 'transparent' : `${c.c}22`),
          }}>{c.label}</button>
        ))}
      </div>

      <label className="hg-label" style={{ marginTop: 14 }}>항목</label>
      <select className="hg-select" value={form.termId} onChange={(e) => setForm({ ...form, termId: e.target.value })}>
        {termsInCat.map(t => (
          <option key={t.id} value={t.id}>{t.name} ({t.abbr})</option>
        ))}
      </select>

      <div style={{
        marginTop: 8, padding: 10, borderRadius: 10,
        background: cat.bg, fontSize: 11, color: 'var(--hg-ink-2)', lineHeight: 1.6, fontWeight: 500,
      }}>
        정상 범위: <strong style={{ color: cat.c }}>{term.range}</strong>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 10, marginTop: 14 }}>
        <div>
          <label className="hg-label">수치</label>
          <input className="hg-input" placeholder="예: 3500" value={form.value} onChange={(e) => setForm({ ...form, value: e.target.value })}/>
        </div>
        <div>
          <label className="hg-label">검사일</label>
          <input type="date" className="hg-input" value={form.date} onChange={(e) => setForm({ ...form, date: e.target.value })}/>
        </div>
      </div>

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

function LabTermDetailScreen({ navigate, term }) {
  const s = useStore();
  const c = LAB_CATEGORIES.find(x => x.id === term.cat);
  const myValues = (s.labValues || []).filter(v => v.termId === term.id).sort((a, b) => a.date.localeCompare(b.date));

  const askDoctor = () => {
    s.addQuestion({
      topic: `'${term.name} (${term.abbr})' 수치에 대해 설명 부탁드려요`,
      ctx: '하루결 검사지 사전에서',
      cat: '검사 결과',
    });
    showToast('진료 질문에 추가됨');
  };

  return (
    <>
      <ScreenHeader title={term.name} sub={term.english}
        back onBack={() => navigate('labs')} />

      {/* 약자 + 한 줄 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{
          padding: 18,
          background: `linear-gradient(135deg, ${c.bg}, var(--hg-surface) 120%)`,
          borderColor: `${c.c}33`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 16, flexShrink: 0,
              background: c.c, color: '#fff',
              display: 'grid', placeItems: 'center',
              fontSize: 14, fontWeight: 800, letterSpacing: '-0.02em', textAlign: 'center', padding: 4,
            }}>{term.abbr}</div>
            <div style={{ flex: 1 }}>
              <Eyebrow color={c.c}>{c.label}</Eyebrow>
              <div className="hg-serif" style={{ fontSize: 20, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em' }}>{term.name}</div>
              <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 2 }}>{term.english}</div>
            </div>
          </div>
          <div style={{ marginTop: 14, padding: 12, borderRadius: 12, background: 'var(--hg-surface-2)' }}>
            <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, fontWeight: 500 }}>{term.short}</div>
          </div>
        </Panel>
      </div>

      {/* 정상 범위 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow>정상 범위</Eyebrow>
        <Panel>
          <div className="hg-serif" style={{ fontSize: 18, fontWeight: 600, color: c.c, letterSpacing: '-0.02em' }}>{term.range}</div>
          <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 6 }}>※ 검사실마다 약간 다를 수 있어요</div>
        </Panel>
      </div>

      {/* 높을 때 / 낮을 때 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow>수치 해석</Eyebrow>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Panel style={{ padding: 14, background: 'var(--hg-rose-soft)', borderColor: 'rgba(194,85,74,0.3)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{
                padding: '3px 9px', borderRadius: 999,
                background: 'var(--hg-rose)', color: '#fff',
                fontSize: 10, fontWeight: 700,
              }}>높을 때 ↑</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, fontWeight: 500 }}>{term.high}</div>
          </Panel>
          <Panel style={{ padding: 14, background: 'var(--hg-honey-tint)', borderColor: 'var(--hg-honey-soft)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <span style={{
                padding: '3px 9px', borderRadius: 999,
                background: 'var(--hg-honey)', color: '#fff',
                fontSize: 10, fontWeight: 700,
              }}>낮을 때 ↓</span>
            </div>
            <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, fontWeight: 500 }}>{term.low}</div>
          </Panel>
        </div>
      </div>

      {/* 왜 중요한가 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Panel style={{ padding: 16, background: 'var(--hg-bg-deeper)', borderColor: 'var(--hg-line-soft)' }}>
          <Eyebrow color="var(--hg-muted)">유방암 환자에게는</Eyebrow>
          <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, fontWeight: 500, marginTop: 4 }}>{term.why}</div>
        </Panel>
      </div>

      {/* 내 수치 추세 */}
      {myValues.length > 0 && (
        <div style={{ padding: '16px 22px 0' }}>
          <Eyebrow>내 수치 추세</Eyebrow>
          <Panel style={{ padding: 16 }}>
            <LabTrendChart values={myValues} color={c.c}/>
            <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid var(--hg-line-soft)', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {[...myValues].reverse().slice(0, 5).map((v) => (
                <div key={v.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontSize: 12 }}>
                  <span style={{ color: 'var(--hg-muted)', fontWeight: 600 }}>{v.date}</span>
                  <span className="hg-serif" style={{ fontSize: 14, fontWeight: 600, color: c.c, letterSpacing: '-0.02em' }}>{v.value}</span>
                </div>
              ))}
            </div>
          </Panel>
        </div>
      )}

      {/* 진료 질문 추가 */}
      <div style={{ padding: '16px 22px 0' }}>
        <button onClick={askDoctor} style={{
          width: '100%', padding: 14, borderRadius: 14,
          background: 'var(--hg-surface)',
          border: '1px solid var(--hg-line)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)',
        }}>
          <svg width="16" height="16" viewBox="0 0 22 22" fill="none">
            <path d="M14 4l4 4-9 9-4 1 1-4 8-10z" stroke="var(--hg-clay)" strokeWidth="1.8" strokeLinejoin="round"/>
          </svg>
          이 수치에 대해 의사에게 물어보기
        </button>
      </div>

      <div style={{ padding: '16px 22px 24px' }}>
        <div style={{
          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 LabTrendChart({ values, color }) {
  if (values.length === 0) return null;
  const nums = values.map(v => parseFloat(v.value)).filter(n => !isNaN(n));
  if (nums.length === 0) return <div style={{ fontSize: 12, color: 'var(--hg-muted)' }}>숫자가 아닌 값이라 그래프 생략</div>;
  const min = Math.min(...nums) * 0.9;
  const max = Math.max(...nums) * 1.1;
  const W = 280, H = 90;
  const pts = nums.map((n, i) => {
    const x = nums.length === 1 ? W / 2 : (i / (nums.length - 1)) * W;
    const y = H - ((n - min) / (max - min || 1)) * H;
    return { x, y, n };
  });
  const d = pts.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(' ');

  return (
    <svg width="100%" height={H + 20} viewBox={`0 -10 ${W} ${H + 20}`}>
      <path d={d} fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"/>
      {pts.map((p, i) => (
        <g key={i}>
          <circle cx={p.x} cy={p.y} r={i === pts.length - 1 ? 5 : 3} fill={i === pts.length - 1 ? color : '#fff'} stroke={color} strokeWidth="2"/>
        </g>
      ))}
    </svg>
  );
}

Object.assign(window, { LabsScreen, LabsListScreen, LabTermDetailScreen });
