// 그란데 독서타임 — 공용 책 상세 모달
// 아카이브 그리드 / 메인 홈 책탑 양쪽에서 동일하게 사용

const BookModal = ({ book, isMobile = false, onClose }) => {
  const t = window.tokens;

  React.useEffect(() => {
    if (!book) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose && onClose(); };
    window.addEventListener('keydown', onKey);
    // 모달 열려있는 동안 body 스크롤 잠금 — 뒷배경이 같이 스크롤되는 "두 겹 스크롤" 방지
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      window.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [book, onClose]);

  if (!book) return null;

  // 표지 fallback 팔레트 (썸네일 없을 때)
  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 },
  ];
  const sp = palette[book.id % palette.length];
  const hasCover = !!book.thumbnail;

  // 부모(#scaler)에 transform: scale이 걸려있으면 position: fixed 기준점이 viewport가
  // 아닌 transformed ancestor가 됨 → Portal로 body 직접 자식으로 빼서 viewport 중앙 보장
  return ReactDOM.createPortal(
    <div
      onClick={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        background: 'rgba(20, 20, 22, 0.55)',
        zIndex: 100,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: isMobile ? 12 : 24,
        overflowY: 'auto',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          width: isMobile ? '100%' : 880,
          maxWidth: isMobile ? '100%' : 880,
          maxHeight: isMobile ? '92vh' : 'auto',
          minHeight: isMobile ? 'auto' : 480,
          background: '#fff', borderRadius: 12,
          boxShadow: '0 30px 80px -20px rgba(0,0,0,0.45), 0 0 0 1px rgba(0,0,0,0.04)',
          display: 'flex',
          flexDirection: isMobile ? 'column' : 'row',
          overflow: isMobile ? 'auto' : 'hidden',
          position: 'relative',
        }}
      >
        {/* 닫기 버튼 */}
        <div
          onClick={onClose}
          style={{
            position: 'absolute', top: 16, right: 16, zIndex: 2,
            width: 32, height: 32, borderRadius: '50%',
            background: 'rgba(255,255,255,0.92)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', fontSize: 22, color: t.color.muted,
            lineHeight: 1, fontWeight: 300,
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
            transition: 'color 0.15s',
          }}
          onMouseEnter={e => { e.currentTarget.style.color = t.color.ink; }}
          onMouseLeave={e => { e.currentTarget.style.color = t.color.muted; }}
        >×</div>

        {/* 좌측(데스크탑) / 상단(모바일) 표지 */}
        {hasCover ? (
          isMobile ? (
            <div style={{
              width: '100%',
              padding: '28px 20px',
              background: t.color.cream || '#F4F0E6',
              display: 'flex', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <div style={{
                width: 160,
                aspectRatio: '2 / 3',
                backgroundImage: `url("${book.thumbnail}")`,
                backgroundSize: 'contain',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
                backgroundColor: '#F4F4F2',
                boxShadow: '0 14px 32px -10px rgba(0,0,0,0.28), inset 0 0 0 1px rgba(0,0,0,0.04)',
              }} />
            </div>
          ) : (
            <div style={{
              width: 320, flexShrink: 0,
              background: t.color.cream || '#F4F0E6',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: '32px 28px',
            }}>
              <div style={{
                width: '100%',
                aspectRatio: '2 / 3',
                backgroundImage: `url("${book.thumbnail}")`,
                backgroundSize: 'cover',
                backgroundPosition: 'center',
                backgroundColor: '#F4F4F2',
                boxShadow: '0 18px 40px -12px rgba(0,0,0,0.28), inset 0 0 0 1px rgba(0,0,0,0.04)',
              }} />
            </div>
          )
        ) : (
          isMobile ? (
            <div style={{
              width: '100%',
              padding: '28px 20px',
              background: t.color.cream || '#F4F0E6',
              display: 'flex', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <div style={{
                width: 160,
                aspectRatio: '2 / 3',
                background: sp.bg, color: sp.fg,
                padding: 18,
                display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                boxShadow: '0 14px 32px -10px rgba(0,0,0,0.28), inset 0 0 0 1px rgba(0,0,0,0.04)',
              }}>
                <div style={{ height: 2, width: 24, background: sp.accent }} />
                <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
                  {book.title || '(제목 미입력)'}
                </div>
                <div style={{ fontSize: 9, opacity: 0.7, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                  {book.genre || '미분류'}
                </div>
              </div>
            </div>
          ) : (
            <div style={{
              width: 320, flexShrink: 0,
              background: sp.bg, color: sp.fg,
              padding: 28,
              display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
            }}>
              <div style={{ height: 2, width: 32, background: sp.accent }} />
              <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1.2 }}>
                {book.title || '(제목 미입력)'}
              </div>
              <div style={{ fontSize: 11, opacity: 0.7, letterSpacing: '0.14em', textTransform: 'uppercase' }}>
                {book.genre || '미분류'}
              </div>
            </div>
          )
        )}

        {/* 우측(데스크탑) / 하단(모바일) 정보 */}
        <div style={{
          flex: 1, padding: isMobile ? '24px 20px' : '48px 44px',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* 장르 */}
          <div style={{
            fontSize: 17, fontWeight: 700,
            color: t.color.blue,
            letterSpacing: '-0.005em',
            marginBottom: 8,
          }}>
            {book.genre || '미분류'}
          </div>

          {/* 제목 */}
          <div style={{
            fontSize: 36, fontWeight: 700,
            letterSpacing: '-0.03em', lineHeight: 1.18,
            color: t.color.ink,
            marginBottom: 32,
          }}>
            {book.title || '(제목 미입력)'}
          </div>

          {/* 인용문 — 있을 때만 표시. 메타 위 배치 */}
          {book.quote && (
            <div style={{ marginBottom: 32 }}>
              <div style={{
                fontSize: 15, fontWeight: 700,
                letterSpacing: '0.1em',
                color: t.color.blue,
                textTransform: 'uppercase',
                marginBottom: 12,
              }}>
                구성원이 주목한 문장
              </div>
              <div style={{
                background: t.color.blueSoft,
                padding: '40px 52px 36px',
                borderRadius: 6,
                position: 'relative',
                overflow: 'hidden',
              }}>
                {/* 장식용 따옴표 — 좌상단 / 우하단 대각선, 두꺼운 흰색 */}
                <div aria-hidden="true" style={{
                  position: 'absolute',
                  top: 4, left: 12,
                  fontSize: 64, fontWeight: 900,
                  color: '#FFFFFF',
                  lineHeight: 1,
                  pointerEvents: 'none',
                  userSelect: 'none',
                  fontFamily: 'Georgia, "Times New Roman", serif',
                }}>“</div>
                <div aria-hidden="true" style={{
                  position: 'absolute',
                  bottom: -28, right: 16,
                  fontSize: 64, fontWeight: 900,
                  color: '#FFFFFF',
                  lineHeight: 1,
                  pointerEvents: 'none',
                  userSelect: 'none',
                  fontFamily: 'Georgia, "Times New Roman", serif',
                }}>”</div>
                <div style={{
                  position: 'relative',
                  fontSize: 16, fontWeight: 500,
                  lineHeight: 1.75, letterSpacing: '-0.015em',
                  color: t.color.ink,
                  whiteSpace: 'pre-wrap',
                }}>
                  {book.quote}
                </div>
                {(() => {
                  const by = book.quoteBy
                    || (book.readers && book.readers[0])
                    || book.reader
                    || '';
                  return by ? (
                    <div style={{
                      position: 'relative',
                      fontSize: 13, fontWeight: 600,
                      color: t.color.muted,
                      letterSpacing: '-0.01em',
                      marginTop: 16,
                      textAlign: 'right',
                    }}>
                      — {by}
                    </div>
                  ) : null;
                })()}
              </div>
            </div>
          )}

          {/* 메타 — 등록일 / 읽은 사람 / 진행률(진행중일 때만) */}
          {(() => {
            const total = book.pages || 0;
            const read = (book.pagesRead != null && book.pagesRead !== '') ? Number(book.pagesRead) : total;
            const isInProgress = total > 0 && read < total;
            const pct = total > 0 ? Math.round((read / total) * 100) : 0;
            const showDone = book.done === true;
            const showProgress = !showDone && isInProgress;
            const memberCount = book.memberCount || 0;
            const doneCount = book.doneCount || 0;
            const isGroup = memberCount >= 2;
            const groupValue = (doneCount > 0 && doneCount === memberCount)
              ? `${memberCount}명 전원 완독`
              : (doneCount > 0 ? `${memberCount}명 · 완독 ${doneCount}` : `${memberCount}명`);
            return (
              <div style={{
                display: 'flex', gap: 40, flexWrap: 'wrap',
                paddingTop: 22,
                borderTop: `1px solid ${t.color.ruleSoft}`,
              }}>
                <div>
                  <div style={{ fontSize: 12, letterSpacing: '0.04em', color: t.color.muted, marginBottom: 8, fontWeight: 600 }}>등록일</div>
                  <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.02em', color: t.color.ink, fontVariantNumeric: 'tabular-nums' }}>
                    {book.date || '—'}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 12, letterSpacing: '0.04em', color: t.color.muted, marginBottom: 8, fontWeight: 600 }}>읽은 사람</div>
                  <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.02em', color: t.color.ink }}>
                    {(() => {
                      const rs = (book.readers && book.readers.length > 0)
                        ? book.readers
                        : (book.reader ? [book.reader] : []);
                      return rs.length > 0 ? rs.join(' · ') : '—';
                    })()}
                  </div>
                </div>
                {isGroup ? (
                  <div>
                    <div style={{ fontSize: 12, letterSpacing: '0.04em', color: t.color.muted, marginBottom: 8, fontWeight: 600 }}>
                      함께 읽기
                    </div>
                    <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.02em', color: t.color.ink, fontVariantNumeric: 'tabular-nums' }}>
                      {groupValue}
                    </div>
                  </div>
                ) : (showDone || showProgress) && (
                  <div>
                    <div style={{ fontSize: 12, letterSpacing: '0.04em', color: t.color.muted, marginBottom: 8, fontWeight: 600 }}>
                      {showProgress ? '읽은 분량' : '완독'}
                    </div>
                    <div style={{ fontSize: 17, fontWeight: 600, letterSpacing: '-0.02em', color: showProgress ? t.color.blue : t.color.ink, fontVariantNumeric: 'tabular-nums' }}>
                      {showProgress
                        ? <>{read}<span style={{ color: t.color.mutedLight, fontWeight: 500 }}> / {total}쪽 · {pct}%</span></>
                        : (total > 0 ? <>{total}쪽</> : <>완독</>)}
                    </div>
                  </div>
                )}
              </div>
            );
          })()}
        </div>
      </div>
    </div>,
    document.body
  );
};

window.BookModal = BookModal;
