// 그란데 독서타임 — 통계
// 레이아웃: 추이 강조 2단
//   1단(상): 월별 추이 막대그래프 (1fr) + KPI 사이드(300px)
//   2단(하): 장르 도넛 + 그란데 리더 TOP 5 (이달/누적 토글)
// 운영 통합: window.bookStore에서 derive된 라이브 데이터 props로 받음

const Stats = ({ books, members, stats, genres, isMobile = false }) => {
  const t = window.tokens;

  // ───────────── 장르 도넛 ─────────────
  const total = genres.reduce((s, g) => s + g.count, 0);
  const shades = [t.color.blue, '#0A0A0A', t.color.blueMid, '#5A5A5A', '#9E9E9E', '#C8C8C8'];

  const cx = 140, cy = 140, r = 96, sw = 40;
  const C = 2 * Math.PI * r;
  let acc = 0;
  const segments = genres.map((g, i) => {
    const frac = total > 0 ? g.count / total : 0;
    const dash = frac * C;
    const offset = -acc * C;
    acc += frac;
    return { ...g, dash, offset, color: shades[i % shades.length], pct: Math.round(frac * 100) };
  });

  const [activeGenre, setActiveGenre] = React.useState(null);
  const focused = activeGenre ? segments.find(s => s.genre === activeGenre) : null;

  // ───────────── 월별 집계 ─────────────
  // date 'YYYY.MM.DD' → 'YYYY.MM' 키로 그룹핑. 회차 발표 월 기준
  const now = new Date();
  const thisYM = `${now.getFullYear()}.${String(now.getMonth() + 1).padStart(2, '0')}`;
  const thisMonthLabel = `${parseInt(thisYM.split('.')[1], 10)}월`;

  const monthly = React.useMemo(() => {
    const map = {};
    books.forEach(b => {
      const ym = (b.date || '').slice(0, 7);
      if (!ym || ym.length < 7) return;
      if (!map[ym]) map[ym] = { ym, count: 0, pages: 0 };
      map[ym].count += 1;
      map[ym].pages += (b.pages || 0);
    });
    return Object.values(map)
      .map(m => ({ ...m, cm: +(m.pages * 0.008).toFixed(1) }))
      .sort((a, b) => a.ym.localeCompare(b.ym));
  }, [books]);

  const thisMonthData = monthly.find(m => m.ym === thisYM);
  const thisMonthBooks = thisMonthData?.count || 0;
  const maxMonthly = monthly.length > 0 ? Math.max(...monthly.map(m => m.count)) : 1;

  // ───────────── 이달의 리더 / 누적 토글 ─────────────
  const [leaderMode, setLeaderMode] = React.useState('thisMonth'); // 'thisMonth' | 'allTime'

  const monthlyMembers = React.useMemo(() => {
    const memberMap = {};
    books
      .filter(b => (b.date || '').startsWith(thisYM))
      .forEach(b => {
        const rs = window.bookStore.readersOf(b);
        rs.forEach(name => {
          if (!memberMap[name]) memberMap[name] = { name, role: b.role || '', books: 0, pages: 0 };
          memberMap[name].books += 1;
          memberMap[name].pages += (b.pages || 0);
          if (b.role && !memberMap[name].role) memberMap[name].role = b.role;
        });
      });
    return Object.values(memberMap).sort((a, b) =>
      b.books - a.books || b.pages - a.pages || a.name.localeCompare(b.name, 'ko')
    );
  }, [books, thisYM]);

  const displayMembers = leaderMode === 'thisMonth' ? monthlyMembers : members;
  const maxBooks = displayMembers.length > 0 ? Math.max(...displayMembers.map(m => m.books)) : 1;

  // ───────────── 렌더 ─────────────
  return (
    <div style={{
      padding: isMobile ? '24px 20px 56px' : '40px 64px 56px',
      minHeight: isMobile ? 'auto' : 816,
      display: 'flex', flexDirection: 'column',
    }}>
      {/* Header */}
      <div style={{ marginBottom: isMobile ? 20 : 28 }}>
        <div style={{
          fontFamily: t.font.sans,
          fontSize: isMobile ? 14 : 20, fontWeight: 700,
          color: t.color.mutedLight, letterSpacing: '0',
          marginBottom: isMobile ? 8 : 10,
        }}>
          그란데 독서타임
        </div>
        <div style={{ fontSize: isMobile ? 32 : 56, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1.05 }}>
          <span style={{ color: t.color.blue }}>숫자</span>로 보는 <span style={{ color: t.color.mutedLight }}>우리의 독서</span>
        </div>
      </div>

      {/* === SECTION 1: 월별 추이 + KPI === */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 300px',
        gap: isMobile ? 16 : 28,
        marginBottom: isMobile ? 16 : 28,
      }}>
        {/* Monthly trend */}
        <div style={{
          background: '#FAFAF8',
          padding: '24px 28px',
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18 }}>
            <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>월별 추이</div>
            <div style={{ fontSize: 12, color: t.color.muted }}>회차 발표 월 기준</div>
          </div>
          {monthly.length === 0 ? (
            <div style={{ padding: '20px 0', color: t.color.muted, fontSize: 14 }}>아직 기록된 회차가 없어요.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16, flex: 1, justifyContent: 'center' }}>
              {monthly.map(m => {
                const monthLabel = `${parseInt(m.ym.split('.')[1], 10)}월`;
                const yearLabel = m.ym.split('.')[0];
                const isThis = m.ym === thisYM;
                const barPct = (m.count / maxMonthly) * 100;
                return (
                  <div key={m.ym} style={{
                    display: 'grid',
                    gridTemplateColumns: isMobile ? '48px 1fr 76px' : '60px 1fr 96px',
                    gap: isMobile ? 12 : 16, alignItems: 'center',
                  }}>
                    <div>
                      <div style={{
                        fontSize: 20, fontWeight: 700, letterSpacing: '-0.025em',
                        color: isThis ? t.color.blue : t.color.ink,
                        fontVariantNumeric: 'tabular-nums', lineHeight: 1,
                      }}>{monthLabel}</div>
                      <div style={{ fontSize: 11, color: t.color.muted, marginTop: 4, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
                        {yearLabel}
                      </div>
                    </div>
                    <div style={{ height: 28, background: '#EFEFEC', position: 'relative' }}>
                      <div style={{
                        position: 'absolute', left: 0, top: 0, bottom: 0,
                        width: `${Math.max(barPct, 4)}%`,
                        background: isThis ? t.color.blue : t.color.ink,
                        transition: 'width 0.5s cubic-bezier(0.2, 0.8, 0.2, 1)',
                      }} />
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
                        {m.count}<span style={{ fontSize: 12, color: t.color.muted, fontWeight: 500, marginLeft: 3 }}>권</span>
                      </div>
                      <div style={{ fontSize: 11, color: t.color.muted, marginTop: 5, fontVariantNumeric: 'tabular-nums' }}>
                        {m.cm}cm
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* KPI side */}
        <div style={{
          background: '#FAFAF8',
          padding: 24,
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: t.color.muted, letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 16 }}>
            한눈에 보기
          </div>

          {/* Hero: 이달의 권수 */}
          <div style={{ paddingBottom: 18, borderBottom: `1px solid ${t.color.ruleSoft}` }}>
            <div style={{ fontSize: 12, color: t.color.muted, marginBottom: 6, letterSpacing: '-0.01em' }}>
              {thisMonthLabel}에 읽은 책
            </div>
            <div style={{
              fontSize: isMobile ? 44 : 56, fontWeight: 800, letterSpacing: '-0.05em', lineHeight: 0.92,
              color: t.color.blue, fontVariantNumeric: 'tabular-nums',
            }}>
              {thisMonthBooks}
              <span style={{ fontSize: isMobile ? 16 : 18, fontWeight: 600, color: t.color.muted, marginLeft: 4 }}>권</span>
            </div>
          </div>

          {/* List */}
          <KpiRow label="누적 권수" value={stats.totalBooks} unit="권" />
          <KpiRow label="누적 책탑" value={stats.totalHeightCm.toFixed(1)} unit="cm" />
          <KpiRow label="참여 구성원" value={stats.members} unit="명" last />
        </div>
      </div>

      {/* === SECTION 2: 장르 도넛 + 리더 TOP 5 (토글) === */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1.05fr 1fr',
        gap: isMobile ? 16 : 28,
        flex: 1, minHeight: 0,
      }}>
        {/* LEFT — Donut */}
        <div style={{
          display: 'flex', flexDirection: 'column', minHeight: 0,
          background: '#FAFAF8',
          padding: 24,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
            <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>장르 분포</div>
            <div style={{ fontSize: 12, color: t.color.muted }}>전체 {total}권</div>
          </div>
          {total === 0 ? (
            <div style={{ padding: '20px 0', color: t.color.muted, fontSize: 14 }}>장르 데이터가 아직 없어요.</div>
          ) : (
            <div style={{
              display: 'grid',
              gridTemplateColumns: isMobile ? '1fr' : '260px 1fr',
              gap: isMobile ? 20 : 24,
              alignItems: 'center',
              justifyItems: isMobile ? 'center' : 'stretch',
              flex: 1,
            }}>
              <div style={{ position: 'relative', width: isMobile ? 220 : 260, height: isMobile ? 220 : 260 }}>
                <svg width={isMobile ? 220 : 260} height={isMobile ? 220 : 260} viewBox="0 0 280 280">
                  <circle cx={cx} cy={cy} r={r} fill="none" stroke="#EFEFEC" strokeWidth={sw} />
                  {segments.map((s) => (
                    <circle
                      key={s.genre}
                      cx={cx} cy={cy} r={r}
                      fill="none"
                      stroke={s.color}
                      strokeWidth={focused && focused.genre === s.genre ? sw + 6 : sw}
                      strokeDasharray={`${s.dash} ${C}`}
                      strokeDashoffset={s.offset}
                      transform={`rotate(-90 ${cx} ${cy})`}
                      style={{ transition: 'stroke-width 0.2s', cursor: 'pointer' }}
                      onMouseEnter={() => setActiveGenre(s.genre)}
                      onMouseLeave={() => setActiveGenre(null)}
                    />
                  ))}
                </svg>
                <div style={{
                  position: 'absolute', inset: 0, display: 'flex',
                  flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                  pointerEvents: 'none', textAlign: 'center',
                }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: t.color.muted, letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 4 }}>
                    {focused ? focused.genre : '전체'}
                  </div>
                  <div style={{ fontSize: isMobile ? 44 : 56, fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, color: focused ? focused.color : t.color.ink }}>
                    {focused ? focused.count : total}
                  </div>
                  <div style={{ fontSize: 12, color: t.color.muted, marginTop: 6, fontWeight: 500 }}>
                    {focused ? `${focused.pct}%` : '권'}
                  </div>
                </div>
              </div>

              {/* Legend */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                {segments.map(s => (
                  <div key={s.genre}
                    onMouseEnter={() => setActiveGenre(s.genre)}
                    onMouseLeave={() => setActiveGenre(null)}
                    style={{
                      display: 'grid', gridTemplateColumns: '12px minmax(0, 1fr) auto',
                      gap: 10, alignItems: 'center', padding: '9px 0',
                      borderBottom: `1px solid ${t.color.ruleSoft}`,
                      cursor: 'pointer',
                      opacity: focused && focused.genre !== s.genre ? 0.35 : 1,
                      transition: 'opacity 0.15s',
                    }}>
                    <div style={{ width: 12, height: 12, background: s.color }} />
                    <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-0.015em', whiteSpace: 'nowrap' }}>{s.genre}</div>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                      <div style={{ fontSize: 11, color: t.color.muted, fontVariantNumeric: 'tabular-nums' }}>{s.count}권</div>
                      <div style={{ fontSize: 14, fontWeight: 700, letterSpacing: '-0.02em', textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{s.pct}%</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* RIGHT — Leaderboard with toggle */}
        <div style={{
          display: 'flex', flexDirection: 'column', minHeight: 0,
          background: '#FAFAF8',
          padding: 24,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
            <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>그란데 리더 TOP 5</div>
            <div style={{ display: 'flex', padding: 3, background: '#EFEFEC' }}>
              {[
                { id: 'thisMonth', label: thisMonthLabel },
                { id: 'allTime', label: '누적' },
              ].map(opt => (
                <div
                  key={opt.id}
                  onClick={() => setLeaderMode(opt.id)}
                  style={{
                    padding: '5px 14px',
                    fontSize: 12, fontWeight: 600,
                    cursor: 'pointer',
                    background: leaderMode === opt.id ? t.color.ink : 'transparent',
                    color: leaderMode === opt.id ? '#fff' : t.color.muted,
                    transition: 'all 0.15s',
                    letterSpacing: '-0.01em',
                  }}
                >
                  {opt.label}
                </div>
              ))}
            </div>
          </div>

          {displayMembers.length === 0 ? (
            <div style={{ padding: '20px 0', color: t.color.muted, fontSize: 14 }}>
              {leaderMode === 'thisMonth' ? `아직 ${thisMonthLabel} 기록이 없어요.` : '아직 등록된 구성원이 없어요.'}
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0, flex: 1 }}>
              {displayMembers.slice(0, 5).map((m, i) => {
                const barPct = (m.books / maxBooks) * 100;
                const isTop = i === 0;
                const isLast = i === Math.min(displayMembers.length, 5) - 1;
                return (
                  <div key={m.name} style={{
                    padding: '14px 0',
                    borderBottom: isLast ? 'none' : `1px solid ${t.color.ruleSoft}`,
                    flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center',
                  }}>
                    <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr auto', gap: 14, alignItems: 'center', marginBottom: 8 }}>
                      <div style={{ fontSize: 28, fontWeight: 300, letterSpacing: '-0.03em', color: isTop ? t.color.blue : t.color.mutedLight, fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
                        {String(i + 1).padStart(2, '0')}
                      </div>
                      <div>
                        <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: '-0.025em', lineHeight: 1.1 }}>{m.name}</div>
                        <div style={{ fontSize: 11, fontWeight: 500, color: t.color.muted, marginTop: 3 }}>{m.role || '—'}</div>
                      </div>
                      <div style={{ textAlign: 'right' }}>
                        <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums', lineHeight: 1 }}>
                          {m.books}<span style={{ fontSize: 12, color: t.color.muted, marginLeft: 3, fontWeight: 400 }}>권</span>
                        </div>
                      </div>
                    </div>
                    <div style={{ height: 5, background: '#EFEFEC', position: 'relative', marginLeft: 54 }}>
                      <div style={{
                        position: 'absolute', left: 0, top: 0, bottom: 0,
                        width: `${barPct}%`,
                        background: isTop ? t.color.blue : t.color.muted,
                        transition: 'width 0.3s',
                      }} />
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const KpiRow = ({ label, value, unit, last }) => {
  const t = window.tokens;
  return (
    <div style={{
      paddingTop: 14, paddingBottom: 14,
      borderBottom: last ? 'none' : `1px solid ${t.color.ruleSoft}`,
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
    }}>
      <div style={{ fontSize: 13, color: t.color.muted, letterSpacing: '-0.01em' }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums' }}>
        {value}<span style={{ fontSize: 12, color: t.color.muted, fontWeight: 500, marginLeft: 3 }}>{unit}</span>
      </div>
    </div>
  );
};

window.Stats = Stats;
