// 하루결 — 정보 도서관 화면

function LibraryScreen({ navigate, articleId }) {
  // 단건 보기
  if (articleId) {
    const article = LIBRARY.find(a => a.id === articleId);
    if (!article) return <LibraryListScreen navigate={navigate} />;
    return <LibraryArticleScreen navigate={navigate} article={article} />;
  }
  return <LibraryListScreen navigate={navigate} />;
}

function LibraryListScreen({ navigate }) {
  const [query, setQuery] = React.useState('');
  const [cat, setCat] = React.useState('all');

  let results = query ? searchLibrary(query) : LIBRARY;
  if (cat !== 'all') results = results.filter(a => a.cat === cat);

  return (
    <>
      <ScreenHeader
        title="정보 도서관"
        sub="공식 자료를 모아두었어요"
        back onBack={() => navigate('more')}
      />

      {/* 검색 */}
      <div style={{ padding: '6px 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="예: 메스꺼움, 발열, 손발 저림, 식사"
            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: '14px 22px 0' }}>
        <div style={{ display: 'flex', gap: 6, overflowX: 'auto', paddingBottom: 4, scrollbarWidth: 'none' }}>
          <CatChip label="전체" on={cat === 'all'} onClick={() => setCat('all')} c="var(--hg-clay)" bg="var(--hg-clay-tint)"/>
          {LIBRARY_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' }}>
        {query && (
          <div style={{ fontSize: 12, color: 'var(--hg-muted)', fontWeight: 600, marginBottom: 10 }}>
            "{query}" 검색 결과 {results.length}건
          </div>
        )}

        {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)' }}>
            검색 결과가 없어요.<br/>다른 키워드로 다시 찾아보세요.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {results.map(a => {
              const c = LIBRARY_CATEGORIES.find(x => x.id === a.cat);
              return (
                <button key={a.id} onClick={() => navigate(`library/${a.id}`)} style={{
                  width: '100%', textAlign: 'left',
                  padding: 16, borderRadius: 18,
                  background: 'var(--hg-surface)',
                  border: '1px solid var(--hg-line-soft)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <Chip bg={c.bg} color={c.c}>{c.label}</Chip>
                    <span style={{ fontSize: 10, color: 'var(--hg-muted)', fontWeight: 600 }}>
                      출처 {a.sources.length}
                    </span>
                  </div>
                  <div className="hg-serif" style={{ fontSize: 18, fontWeight: 600, color: 'var(--hg-ink)', letterSpacing: '-0.02em', lineHeight: 1.3, marginBottom: 6 }}>
                    {a.title}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--hg-muted)', fontWeight: 500, lineHeight: 1.6 }}>
                    {a.intro}
                  </div>
                </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/>
          서울대학교병원·삼성서울병원·세브란스병원 공식 자료를<br/>
          참고하여 정리한 것입니다. 치료 결정은 담당 의료진과 상의하세요.
        </div>
      </div>
    </>
  );
}

function CatChip({ label, on, onClick, c, bg }) {
  return (
    <button onClick={onClick} style={{
      padding: '8px 14px', borderRadius: 999,
      background: on ? c : bg,
      color: on ? '#fff' : c,
      fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap', flexShrink: 0,
      border: '1px solid ' + (on ? 'transparent' : `${c}22`),
    }}>{label}</button>
  );
}

function LibraryArticleScreen({ navigate, article }) {
  const s = useStore();
  const c = LIBRARY_CATEGORIES.find(x => x.id === article.cat);

  const trustBadge = (trust) => {
    const map = {
      official: { l: '공식', bg: 'var(--hg-sage-tint)',  c: 'var(--hg-sage)' },
      hospital: { l: '병원', bg: 'var(--hg-clay-tint)',  c: 'var(--hg-clay)' },
      society:  { l: '학회', bg: 'var(--hg-mist-tint)',  c: 'var(--hg-mist)' },
    };
    return map[trust] || map.official;
  };

  // 진료 질문 노트에 추가
  const askDoctor = () => {
    s.addQuestion({
      topic: `'${article.title}'에 대해 더 자세히 알고 싶어요`,
      ctx: '하루결 정보 도서관에서 본 내용',
      cat: c.label,
    });
    showToast('진료 질문에 추가됨');
  };

  return (
    <>
      <ScreenHeader
        title={article.title}
        sub={c.label}
        back onBack={() => navigate('library')}
      />

      {/* 한 줄 요약 */}
      <div style={{ padding: '6px 22px 0' }}>
        <Panel style={{
          padding: 16,
          background: c.bg,
          borderColor: `${c.c}33`,
        }}>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--hg-ink)', lineHeight: 1.6 }}>
            {article.intro}
          </div>
        </Panel>
      </div>

      {/* 핵심 포인트 */}
      <div style={{ padding: '16px 22px 0' }}>
        <Eyebrow>알아두면 좋은 것</Eyebrow>
        <Panel style={{ padding: 4 }}>
          {article.points.map((p, i) => (
            <div key={i} style={{
              display: 'flex', gap: 12,
              padding: '14px 14px',
              borderBottom: i < article.points.length - 1 ? '1px solid var(--hg-line-soft)' : 'none',
            }}>
              <div style={{
                minWidth: 22, height: 22, borderRadius: '50%', flexShrink: 0,
                background: c.bg, color: c.c,
                display: 'grid', placeItems: 'center',
                fontFamily: '"Noto Serif KR", serif', fontSize: 11, fontWeight: 700,
                marginTop: 1,
              }}>{i + 1}</div>
              <div style={{ fontSize: 13, color: 'var(--hg-ink-2)', lineHeight: 1.7, textWrap: 'pretty' }}>
                {p}
              </div>
            </div>
          ))}
        </Panel>
      </div>

      {/* 진료 질문에 추가 / 응급 안내 */}
      <div style={{ padding: '16px 22px 0' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          <button onClick={askDoctor} style={{
            flex: 1, padding: '14px', 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>
          {article.cat === 'emergency' && (
            <button onClick={() => navigate('emergency')} style={{
              flex: 1, padding: '14px', borderRadius: 14,
              background: 'var(--hg-rose)', color: '#fff',
              fontSize: 13, fontWeight: 700,
            }}>병원 콜 →</button>
          )}
        </div>
      </div>

      {/* 출처 */}
      <div style={{ padding: '20px 22px 0' }}>
        <Eyebrow>출처 · 원문 보기</Eyebrow>
        <Panel style={{ padding: 4 }}>
          {article.sources.map((src, i) => {
            const t = trustBadge(src.trust);
            return (
              <a key={i} href={src.url} target="_blank" rel="noopener noreferrer" style={{
                display: 'flex', alignItems: 'center', gap: 12,
                padding: '14px 14px',
                borderBottom: i < article.sources.length - 1 ? '1px solid var(--hg-line-soft)' : 'none',
                color: 'inherit', textDecoration: 'none',
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10, flexShrink: 0,
                  background: t.bg, color: t.c,
                  display: 'grid', placeItems: 'center',
                  fontSize: 10, fontWeight: 700,
                }}>{t.l}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--hg-ink)' }}>{src.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--hg-muted)', fontWeight: 500, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {src.title}
                  </div>
                </div>
                <svg width="16" height="16" viewBox="0 0 22 22" fill="none" style={{ flexShrink: 0 }}>
                  <path d="M7 5h10v10M7 17L17 5" stroke="var(--hg-muted)" strokeWidth="1.6" strokeLinecap="round"/>
                </svg>
              </a>
            );
          })}
        </Panel>
      </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>
    </>
  );
}

Object.assign(window, { LibraryScreen, LibraryListScreen, LibraryArticleScreen });
