// 그란데 독서타임 — 아카이브 (책장 그리드 + 책 상세 모달)
// 책 클릭 시 공용 BookModal 컴포넌트로 표시 (홈에서도 동일하게 사용)

const Archive = ({ books, stats, quotes, goBook, isMobile = false }) => {
  const t = window.tokens;
  const [sort, setSort] = React.useState('newest'); // newest | oldest | title
  const [query, setQuery] = React.useState('');
  const [selectedId, setSelectedId] = React.useState(null);

  // 그란데 말입니다 — 인용문 회전. 인용문 길이에 비례해서 머무는 시간 결정.
  // 글자당 250ms + base 5초 / 최소 9초 / 최대 28초 (= 한국어 음미 읽기 ~4음절/초 가정)
  // 짧은 인용문은 충분히 다 읽을 시간 + 너무 길면 다음 인용문 노출을 위해 cap
  const [quoteIdx, setQuoteIdx] = React.useState(() =>
    quotes.length > 0 ? Math.floor(Math.random() * quotes.length) : 0
  );
  const [fade, setFade] = React.useState(true);
  React.useEffect(() => {
    if (quotes.length <= 1) return;
    const current = quotes[quoteIdx];
    const len = (current && current.text ? current.text : '').length;
    const duration = Math.max(9000, Math.min(28000, 5000 + len * 250));
    const id = setTimeout(() => {
      setFade(false);
      setTimeout(() => {
        setQuoteIdx(i => (i + 1) % quotes.length);
        setFade(true);
      }, 280);
    }, duration);
    return () => clearTimeout(id);
  }, [quotes.length, quoteIdx]);
  const currentQuote = quotes[quoteIdx] || null;

  const sorted = React.useMemo(() => {
    const q = query.trim().toLowerCase();
    let arr = [...books];
    if (q) {
      arr = arr.filter(b => {
        const haystack = [
          b.title, b.author, b.publisher, b.genre, b.reader,
          ...(Array.isArray(b.readers) ? b.readers : []),
        ].filter(Boolean).join(' ').toLowerCase();
        return haystack.includes(q);
      });
    }
    if (sort === 'newest') arr.sort((a, b) => (b.date || '').localeCompare(a.date || '') || b.id - a.id);
    if (sort === 'oldest') arr.sort((a, b) => (a.date || '').localeCompare(b.date || '') || a.id - b.id);
    if (sort === 'title') arr.sort((a, b) => (a.title || '').localeCompare(b.title || '', 'ko'));
    return arr;
  }, [books, sort, query]);

  // 같은 책(제목+저자) 묶기 — 서재 표시 전용. 개인 기록·통계·홈 책탑은 원본(books) 그대로.
  // 도끼책 원정대처럼 여러 명이 같은 책을 읽으면 표지 1개 + '함께 N명'으로 노출.
  const groups = React.useMemo(() => {
    const norm = (s) => (s || '').trim().toLowerCase();
    const readersArr = (b) => (b.readers && b.readers.length > 0) ? b.readers : (b.reader ? [b.reader] : []);
    const map = new Map();
    for (const b of sorted) {
      const key = norm(b.title) + '|' + norm(b.author);
      let g = map.get(key);
      if (!g) {
        g = { ...b, _readerSet: [], _doneCount: 0, _quote: b.quote || '', _quoteBy: b.quote ? (b.quoteBy || '') : '' };
        map.set(key, g);
      }
      if (!g.thumbnail && b.thumbnail) g.thumbnail = b.thumbnail;      // 대표 표지: 썸네일 우선
      readersArr(b).forEach((name) => {
        const nm = (name || '').trim();
        if (nm && !g._readerSet.includes(nm)) g._readerSet.push(nm);
      });
      if (b.done) g._doneCount += 1;
      if (!g._quote && b.quote) { g._quote = b.quote; g._quoteBy = b.quoteBy || readersArr(b)[0] || ''; }
      if ((b.date || '') > (g.date || '')) g.date = b.date;           // 최신 등록일 대표
    }
    return [...map.values()].map((g) => ({
      ...g,
      readers: g._readerSet,
      reader: g._readerSet[0] || '',
      memberCount: g._readerSet.length,
      doneCount: g._doneCount,
      quote: g._quote,
      quoteBy: g._quoteBy,
    }));
  }, [sorted]);

  // 표지 fallback 팔레트 (썸네일 URL이 없을 때만 사용)
  const spineFor = (b) => {
    const palette = [
      { bg: '#1A1A1A', fg: '#F4F0E6', accent: '#9E9E9E' },
      { bg: t.color.blue, fg: '#fff', accent: '#FFFFFF' },
      { bg: '#F4F0E6', fg: '#1A1A1A', accent: t.color.blue },
      { bg: '#454545', fg: '#F4F0E6', accent: '#C8C8C8' },
      { bg: t.color.blueMid, fg: '#fff', accent: '#FFFFFF' },
      { bg: '#0A0A0A', fg: '#F4F0E6', accent: t.color.blue },
    ];
    return palette[b.id % palette.length];
  };

  const sortOptions = [
    { id: 'newest', label: '최신순' },
    { id: 'oldest', label: '등록순' },
    { id: 'title', label: '가나다순' },
  ];

  const selectedBook = selectedId != null ? groups.find(g => g.id === selectedId) || null : null;

  return (
    <div style={{ padding: isMobile ? '24px 20px 80px' : '56px 64px 56px', position: 'relative' }}>
      {/* Header — 좌: 타이틀, 우: 누적 페이지 + 참여 구성원. 모바일은 세로 스택 */}
      <div style={{
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        justifyContent: 'space-between',
        alignItems: isMobile ? 'flex-start' : 'flex-end',
        marginBottom: isMobile ? 24 : 32,
        gap: isMobile ? 20 : 32,
      }}>
        <div>
          <div style={{
            fontFamily: t.font.sans,
            fontSize: isMobile ? 13 : 22, fontWeight: 700,
            color: t.color.mutedLight, letterSpacing: '0',
            marginBottom: isMobile ? 8 : 12,
          }}>
            그란데 독서타임
          </div>
          <div style={{ fontSize: isMobile ? 36 : 72, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1 }}>
            우리<span style={{ color: t.color.mutedLight }}>가 읽은 </span><span style={{ color: t.color.blue }}>{books.length}권</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: isMobile ? 24 : 40, alignItems: 'flex-end' }}>
          {[
            { l: '누적 페이지', v: stats.totalPages.toLocaleString('ko-KR'), u: '쪽' },
            { l: '참여 구성원', v: String(stats.members),                    u: '명' },
          ].map((m, i) => (
            <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
              <div style={{ fontFamily: t.font.sans, fontSize: isMobile ? 12 : 15, fontWeight: 500, color: t.color.muted, marginBottom: isMobile ? 4 : 8, letterSpacing: '-0.01em' }}>{m.l}</div>
              <div style={{
                fontFamily: t.font.sans, fontSize: isMobile ? 28 : 54, fontWeight: 700, letterSpacing: '-0.03em', lineHeight: 1,
                color: t.color.blueMid, fontVariantNumeric: 'tabular-nums',
              }}>
                {m.v}<span style={{ fontSize: isMobile ? 14 : 26, color: t.color.blueMid, opacity: 0.65, marginLeft: isMobile ? 4 : 8, fontWeight: 500, letterSpacing: '0.02em' }}>{m.u}</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 그란데 말입니다 — Pick 라벨 + 페이드 회전 인용문 */}
      {currentQuote && (
        <div style={{
          padding: isMobile ? '20px 20px' : '24px 28px',
          background: t.color.blueSoft,
          borderRadius: 8,
          marginBottom: 32,
          display: 'flex', flexDirection: 'column', gap: 14,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 14, flexWrap: 'wrap' }}>
            <div style={{
              padding: isMobile ? '6px 12px' : '8px 16px',
              fontSize: isMobile ? 14 : 20, fontWeight: 700,
              letterSpacing: '-0.005em',
              color: '#fff', background: t.color.blue,
              borderRadius: 6,
            }}>
              그란데 말입니다
            </div>
            {currentQuote.reader && (
              <div style={{
                fontSize: isMobile ? 15 : 19, fontWeight: 600,
                color: t.color.inkSoft, letterSpacing: '-0.015em',
                opacity: fade ? 1 : 0, transition: 'opacity 0.28s',
              }}>
                {currentQuote.reader} Pick
              </div>
            )}
          </div>
          <div style={{ opacity: fade ? 1 : 0, transition: 'opacity 0.28s' }}>
            <div style={{ fontSize: isMobile ? 16 : 22, fontWeight: 500, lineHeight: 1.5, letterSpacing: '-0.02em', color: t.color.ink, maxWidth: 1080 }}>
              “{currentQuote.text}”
            </div>
            {(currentQuote.book || currentQuote.author) && (
              <div style={{
                fontSize: isMobile ? 13 : 18, fontWeight: 500,
                color: t.color.muted, letterSpacing: '-0.015em',
                marginTop: isMobile ? 16 : 22,
              }}>
                {currentQuote.book && <span>— 〈{currentQuote.book}〉</span>}
                {currentQuote.author && <span>{currentQuote.book ? ', ' : '— '}{currentQuote.author}</span>}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Sort + Search — 데스크탑: 좌측 정렬 / 우측 검색, 모바일: 세로 스택 */}
      <div style={{
        display: 'flex',
        flexDirection: isMobile ? 'column' : 'row',
        gap: isMobile ? 12 : 16,
        marginBottom: isMobile ? 20 : 32,
        alignItems: isMobile ? 'stretch' : 'center',
        justifyContent: 'space-between',
      }}>
        {/* Sort */}
        <div style={{
          display: 'flex',
          gap: 8,
          alignItems: 'center',
          justifyContent: 'flex-start',
          flexWrap: 'wrap',
        }}>
          {sortOptions.map(s => (
            <div key={s.id} onClick={() => setSort(s.id)} style={{
              fontSize: isMobile ? 13 : 17, fontWeight: 600, padding: isMobile ? '8px 16px' : '11px 22px',
              borderRadius: 999, cursor: 'pointer',
              border: `1px solid ${sort === s.id ? t.color.blue : t.color.ruleSoft}`,
              background: sort === s.id ? t.color.blue : '#fff',
              color: sort === s.id ? '#fff' : t.color.inkSoft,
              letterSpacing: '-0.015em',
              transition: 'all 0.15s',
            }}>{s.label}</div>
          ))}
        </div>

        {/* Search */}
        <div style={{
          position: 'relative',
          flex: isMobile ? '0 0 auto' : '0 1 320px',
          maxWidth: isMobile ? '100%' : 360,
        }}>
          <input
            type="text"
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="책 제목·저자·읽은 사람 검색"
            style={{
              width: '100%', boxSizing: 'border-box',
              padding: isMobile ? '9px 38px 9px 16px' : '11px 42px 11px 18px',
              fontSize: isMobile ? 13 : 15, fontWeight: 500,
              fontFamily: t.font.sans,
              color: t.color.ink,
              border: `1px solid ${query ? t.color.blue : t.color.ruleSoft}`,
              borderRadius: 999, background: '#fff',
              letterSpacing: '-0.015em',
              outline: 'none',
              transition: 'border-color 0.15s',
            }}
            onFocus={e => e.currentTarget.style.borderColor = t.color.blue}
            onBlur={e => e.currentTarget.style.borderColor = query ? t.color.blue : t.color.ruleSoft}
          />
          {query ? (
            <div
              onClick={() => setQuery('')}
              title="검색 지우기"
              style={{
                position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                width: 22, height: 22, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                cursor: 'pointer', fontSize: 16, color: t.color.muted,
                lineHeight: 1, fontWeight: 400,
              }}
            >×</div>
          ) : (
            <div aria-hidden="true" style={{
              position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)',
              fontSize: 14, color: t.color.muted, pointerEvents: 'none', lineHeight: 1,
            }}>⌕</div>
          )}
        </div>
      </div>

      {/* Shelf grid — 표지 이미지 있으면 표시, 없으면 모노톤 fallback */}
      <div>
        {sorted.length === 0 ? (
          <div style={{ padding: '40px 0', color: t.color.muted, fontSize: 15 }}>
            {query
              ? <>‘{query}’에 해당하는 책이 없어요.</>
              : <>아직 등록된 책이 없어요. 우측 하단 <b>©</b>를 눌러 관리자에서 책을 추가해 보세요.</>
            }
          </div>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(6, 1fr)', gap: isMobile ? 16 : 28, rowGap: isMobile ? 32 : 56 }}>
            {groups.map(b => {
              const sp = spineFor(b);
              const hasCover = !!b.thumbnail;
              // 상태 배지 — 여러 명이면 '👥 N'(함께 읽기) 우선. 아니면 완독 체크 시 '완독',
              // 페이지+진행중일 때만 %, 그 외 미표시.
              const total = b.pages || 0;
              const read = (b.pagesRead != null && b.pagesRead !== '') ? Number(b.pagesRead) : total;
              const isInProgress = total > 0 && read < total;
              const pct = total > 0 ? Math.round((read / total) * 100) : 0;
              const isGroup = b.memberCount >= 2;
              const badgeText = isGroup ? `👥 ${b.memberCount}` : (b.done ? '완독' : (isInProgress ? `${pct}%` : null));
              const progressBadge = badgeText ? (
                <div style={{
                  position: 'absolute',
                  top: isMobile ? 6 : 8, right: isMobile ? 6 : 8,
                  padding: isMobile ? '3px 7px' : '4px 9px',
                  background: 'rgba(0,0,0,0.78)',
                  color: '#fff',
                  fontSize: isMobile ? 10 : 11, fontWeight: 600,
                  letterSpacing: '-0.01em',
                  fontVariantNumeric: 'tabular-nums',
                  pointerEvents: 'none',
                  zIndex: 2,
                  borderRadius: 3,
                  boxShadow: '0 1px 3px rgba(0,0,0,0.18)',
                  backdropFilter: 'blur(2px)',
                }}>
                  {badgeText}
                </div>
              ) : null;
              return (
                <div key={b.id} onClick={() => setSelectedId(b.id)} style={{ cursor: 'pointer' }}>
                  {hasCover ? (
                    <div
                      style={{
                        aspectRatio: '2 / 3',
                        backgroundImage: `url("${b.thumbnail}")`,
                        backgroundSize: 'cover',
                        backgroundPosition: 'center',
                        backgroundColor: '#F4F4F2',
                        boxShadow: '0 8px 20px -8px rgba(0,0,0,0.18), inset 0 0 0 1px rgba(0,0,0,0.04)',
                        position: 'relative', transition: 'transform 0.2s',
                      }}
                      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-4px)'}
                      onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
                    >
                      {progressBadge}
                    </div>
                  ) : (
                    <div
                      style={{
                        aspectRatio: '2 / 3', background: sp.bg, color: sp.fg,
                        padding: 18, display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                        boxShadow: '0 8px 20px -8px rgba(0,0,0,0.18), inset 0 0 0 1px rgba(0,0,0,0.04)',
                        position: 'relative', transition: 'transform 0.2s',
                      }}
                      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-4px)'}
                      onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
                    >
                      {progressBadge}
                      <div style={{ height: 2, width: 28, background: sp.accent }} />
                      <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
                        {b.title || '(제목 미입력)'}
                      </div>
                      <div>
                        <div style={{ fontSize: 12, opacity: 0.75, marginBottom: 4, letterSpacing: '-0.01em' }}>
                          {b.author || '저자 미상'}
                        </div>
                        <div style={{ fontSize: 10, opacity: 0.6, letterSpacing: '0.12em', textTransform: 'uppercase' }}>
                          {b.genre || '미분류'}
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* === 책 상세 모달 (공용 컴포넌트) === */}
      <window.BookModal book={selectedBook} isMobile={isMobile} onClose={() => setSelectedId(null)} />
    </div>
  );
};

window.Archive = Archive;
