// ── Album Book v2 — Rare stickers · Evolution page · Modern areas ─
const { useState, useEffect, useRef, useCallback } = React;

const PW = 595;
const PH = 842;
const SMARG = 36;
const GMARG = 18;
const TMARG = 44;
const BMARG = 32;
const SC_W = 142;
const SC_H = 213; // proporção 1024×1536 (2:3)
const SC_G = 20;
const COLS = 3;

function chunkBy(arr, n) {
  const out = [];
  for (let i = 0; i < arr.length; i += n) out.push(arr.slice(i, i + n));
  return out;
}

// ── Inject shimmer + glow CSS once ───────────────────────────────
(function injectStyles() {
  if (document.getElementById('album-book-styles')) return;
  const s = document.createElement('style');
  s.id = 'album-book-styles';
  s.textContent = `
    @keyframes shimmer {
      0%   { background-position: -400px 0; }
      100% { background-position: 400px 0; }
    }
    @keyframes rareGlow {
      0%, 100% { box-shadow: 0 0 12px 3px rgba(254,206,2,0.5), 0 4px 8px rgba(0,0,0,0.3); }
      50%       { box-shadow: 0 0 24px 8px rgba(254,206,2,0.8), 0 4px 8px rgba(0,0,0,0.3); }
    }
    @keyframes rareBadge {
      0%, 100% { opacity: 1; }
      50%       { opacity: 0.7; }
    }
    .rare-sticker { animation: rareGlow 2.4s ease-in-out infinite; }
    .rare-shimmer {
      position: absolute; inset: 0; border-radius: 10px;
      background: linear-gradient(105deg, transparent 30%, rgba(255,255,220,0.45) 50%, transparent 70%);
      background-size: 800px 100%;
      animation: shimmer 2.2s linear infinite;
      pointer-events: none; z-index: 3;
    }
    .rare-badge { animation: rareBadge 2s ease-in-out infinite; }
  `;
  document.head.appendChild(s);
})();

// ── Sticker Card ──────────────────────────────────────────────────
function BookSticker({ sticker, unlocked, onClick }) {
  // Pre-flip stickers that were already unlocked at mount — só anima se mudar agora.
  const [flipped, setFlipped] = useState(unlocked);
  // Estado local para a foto — começa com o que ALBUM_DATA tem; busca sob demanda quando desbloquear.
  const [photoUrl, setPhotoUrl] = useState(sticker.photoUrl || '');
  const [photoLoaded, setPhotoLoaded] = useState(!!sticker.photoUrl);
  const wasUnlockedRef = useRef(unlocked);
  const ac = AREA_COLORS[sticker.areaId] || { color: '#FECE02', text: '#1e1e1e' };
  const isRare = sticker.areaId === 'hall';

  // Pré-carrega a foto quando ela existir (garante que aparece sem flash).
  useEffect(() => {
    if (!photoUrl) { setPhotoLoaded(false); return; }
    const img = new Image();
    img.onload = () => setPhotoLoaded(true);
    img.onerror = () => setPhotoLoaded(false);
    img.src = photoUrl;
  }, [photoUrl]);

  useEffect(() => {
    if (unlocked && !wasUnlockedRef.current) {
      // Acabou de desbloquear — busca foto fresca do Firestore sob demanda.
      let cancelled = false;
      const fetchPhoto = async () => {
        try {
          const meta = await PACK_SYSTEM.getStickerMeta();
          const m = meta[sticker.number];
          if (m && m.photoUrl && !cancelled) {
            sticker.photoUrl = m.photoUrl; // hidrata in-place
            if (m.name) sticker.name = m.name;
            if (m.role) sticker.role = m.role;
            // Espera a imagem carregar antes de virar a carta.
            const img = new Image();
            img.onload = () => {
              if (cancelled) return;
              setPhotoUrl(m.photoUrl);
              setPhotoLoaded(true);
              setFlipped(true);
            };
            img.onerror = () => { if (!cancelled) setFlipped(true); };
            img.src = m.photoUrl;
          } else if (!cancelled) {
            setFlipped(true);
          }
        } catch {
          if (!cancelled) setFlipped(true);
        }
      };
      fetchPhoto();
      wasUnlockedRef.current = true;
      return () => { cancelled = true; };
    } else if (!unlocked) {
      setFlipped(false);
      wasUnlockedRef.current = false;
    }
  }, [unlocked]);

  return (
    <div onClick={onClick} style={{ width: SC_W, height: SC_H, perspective: 600, cursor: unlocked ? 'default' : 'pointer', flexShrink: 0 }}>
      <div style={{
        width: '100%', height: '100%', position: 'relative',
        transformStyle: 'preserve-3d',
        transition: wasUnlockedRef.current && unlocked ? 'transform 0.65s cubic-bezier(0.4,0,0.2,1)' : 'none',
        transform: unlocked && flipped ? 'rotateY(180deg)' : 'none'
      }}>

        {/* ── FRONT (locked) ── */}
        <div
          className={isRare && !unlocked ? 'rare-sticker' : ''}
          style={{
            position: 'absolute', inset: 0,
            backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden',
            borderRadius: 10,
            background: 'url(assets/sticker-card.png) center / cover no-repeat',
            boxShadow: isRare ? undefined : '0px 4px 4px rgba(0,0,0,0.25)',
            border: isRare ? '2px solid #FECE02' : 'none',
            filter: unlocked ? 'none' : isRare ? 'none' : 'grayscale(0.6)',
            transition: 'filter 0.3s'
          }}>
          
          {/* Shimmer overlay for rare */}
          {isRare && !unlocked && <div className="rare-shimmer" />}

          {/* Placeholder image for locked stickers (inclui Hall da Fama) */}
          {!unlocked &&
          <img src="assets/sticker-placeholder.png" alt="" style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', borderRadius: 10, zIndex: 1, pointerEvents: 'none'
          }} />
          }

          {/* Top accent */}
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: isRare ? 'linear-gradient(90deg,#FECE02,#fff8aa,#FECE02)' : ac.color, borderRadius: '10px 10px 0 0' }} />

          {/* Number badge */}
          <div style={{
            position: 'absolute', top: 7, left: 7,
            background: isRare ? '#FECE02' : ac.color,
            color: '#1e1e1e',
            fontFamily: "'Barlow Condensed', sans-serif",
            fontWeight: 800, fontSize: 11,
            padding: '3px 6px', borderRadius: 5, zIndex: 4,
            letterSpacing: '0.02em', lineHeight: 1,
            whiteSpace: 'nowrap'
          }} className={isRare ? 'rare-badge' : ''}>{sticker.number}</div>

          {/* RARA badge */}
          {isRare &&
          <div style={{
            position: 'absolute', top: 7, right: 7,
            background: '#1e1e1e', color: '#FECE02',
            fontFamily: "'Barlow Condensed', sans-serif",
            fontWeight: 800, fontSize: 9,
            padding: '2px 5px', borderRadius: 4, zIndex: 4,
            letterSpacing: '0.08em'
          }}>★ RARA</div>
          }

          {/* Locked label */}
          {!unlocked &&
          <div style={{
            position: 'absolute', bottom: 38, right: 7,
            background: 'rgba(0,0,0,0.6)', borderRadius: 4,
            padding: '2px 5px',
            fontFamily: "'Barlow Condensed', sans-serif",
            fontSize: 9, color: 'rgba(255,255,255,0.85)',
            letterSpacing: '0.06em', backdropFilter: 'blur(2px)',
            zIndex: 4
          }}>BLOQUEADA</div>
          }
        </div>

        {/* ── BACK (unlocked) — só a imagem, sem texto ── */}
        <div style={{
          position: 'absolute', inset: 0,
          backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden',
          transform: 'rotateY(180deg)',
          borderRadius: 10,
          overflow: 'hidden',
          background: photoUrl && photoLoaded ?
          `url(${photoUrl}) center/cover no-repeat` :
          isRare ?
          'linear-gradient(150deg,#3a2a00 0%,#1e1e1e 40%,#2a2000 100%)' :
          `linear-gradient(150deg, ${ac.color}55 0%, #1e1e1e 100%)`
        }}>
          {(!photoUrl || !photoLoaded) &&
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: "'Bebas Neue', sans-serif",
            fontSize: 44, color: isRare ? '#FECE02' : ac.color, opacity: 0.55
          }}>
              {sticker.name ? sticker.name.split(' ').map((w) => w[0]).slice(0, 2).join('') : '★'}
            </div>
          }
        </div>
      </div>
    </div>);

}

// ── Rotated section label ─────────────────────────────────────────
function RotatedSectionLabel({ text }) {
  return (
    <div style={{
      position: 'absolute', left: 0, top: 0,
      transform: 'matrix(-0.003,1,-1,-0.003,670,141)',
      transformOrigin: '0 0',
      width: 700, height: 124,
      border: '2px solid rgba(254,206,2,0.5)',
      fontFamily: "'Oswald', 'Barlow Condensed', sans-serif",
      fontSize: 80, lineHeight: '100%',
      color: 'transparent',
      display: 'flex', alignItems: 'center',
      pointerEvents: 'none', zIndex: 0, whiteSpace: 'nowrap'
    }}>{text}</div>);

}

// ── Cover ─────────────────────────────────────────────────────────
function CoverLeft() {
  return (
    <div style={{ width: PW, height: PH, background: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/cover-bg.png)', backgroundSize: 'cover', backgroundPosition: 'center' }} />
      <div style={{ position: 'absolute', bottom: 56, left: '50%', transform: 'translateX(-50%)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <img src="assets/conquer-logo.svg" style={{ width: 43, filter: 'brightness(0)' }} alt="" />
        <div>
          <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 18, color: '#1e1e1e', lineHeight: 1 }}>conquer</div>
          <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 13, color: '#1e1e1e' }}><b>Business</b> School</div>
        </div>
      </div>
      <div style={{ position: 'absolute', top: 0, right: 0, width: 20, height: '100%', background: 'linear-gradient(to right,transparent,rgba(0,0,0,0.2))' }} />
    </div>);

}

function CoverRight() {
  const totalStickers = ALBUM_DATA.areas.reduce((s, a) => s + a.times.reduce((ss, t) => ss + t.count, 0), 0);
  const totalTeams = ALBUM_DATA.areas.reduce((s, a) => s + a.times.length, 0);
  const totalAreas = ALBUM_DATA.areas.length;
  return (
    <div style={{ width: PW, height: PH, background: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', left: 0, top: 0, transform: 'matrix(-1,0,0,1,654,-84)', transformOrigin: '0 0', width: 713, height: 1070, backgroundImage: 'url(assets/back-bg.png)', backgroundSize: 'cover', backgroundPosition: 'center' }} />
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
        <div style={{ fontFamily: "'Oswald', 'Barlow Condensed', sans-serif", fontSize: 32, color: '#1e1e1e', lineHeight: 1, textAlign: 'center', letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>ÁLBUM DA COPA</div>
        <div style={{ width: 40, height: 3, background: '#FECE02', borderRadius: 2 }} />
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 500, fontSize: 12, color: '#888', letterSpacing: '0.08em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>CONQUER BUSINESS SCHOOL</div>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 11, color: '#aaa', letterSpacing: '0.04em', marginTop: 4, whiteSpace: 'nowrap' }}>{totalStickers} FIGURINHAS · {totalTeams} TIMES · {totalAreas} ÁREAS</div>
      </div>
      <div style={{ position: 'absolute', top: 0, left: 0, width: 20, height: '100%', background: 'linear-gradient(to left,transparent,rgba(0,0,0,0.15))' }} />
    </div>);
}

// ── Index ─────────────────────────────────────────────────────────
function IndexPage({ side, teams, showTitle = true }) {
  const isLeft = side === 'left';
  return (
    <div style={{ width: PW, height: PH, background: '#fff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: '#FECE02' }} />
      <div style={{ position: 'absolute', top: TMARG, bottom: BMARG, left: isLeft ? SMARG : GMARG, right: isLeft ? GMARG : SMARG }}>
        {showTitle &&
        <div style={{ marginBottom: 20 }}>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 500, fontSize: 11, letterSpacing: '0.22em', color: '#FECE02', textTransform: 'uppercase', marginBottom: 8 }}>CONQUER BUSINESS SCHOOL</div>
            <div style={{ fontSize: 34, color: '#1e1e1e', lineHeight: 0.95, marginBottom: 14, fontFamily: "\"Bebas Neue\"" }}>ÍNDICE DE TIMES</div>
            <div style={{ width: 32, height: 3, background: '#FECE02', borderRadius: 2 }} />
          </div>
        }
        {teams.map((t, i) => {
          const ac = AREA_COLORS[t.area.id] || { color: '#FECE02' };
          return (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, paddingBottom: 6, marginBottom: 6, borderBottom: '1px solid #f0f0f0' }}>
              <div style={{ width: 6, height: 6, borderRadius: '50%', background: ac.color, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 13, color: '#1e1e1e', textTransform: 'uppercase' }}>{t.name}</div>
                <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 10, color: '#bbb', letterSpacing: '0.04em' }}>{t.area.name}</div>
              </div>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 600, fontSize: 11, color: '#ccc' }}>
                {t.name}
              </div>
            </div>);

        })}
      </div>
      <PageFoot side={side} /><SpineShadow side={side} />
    </div>);

}

// ── Escala da Glória ──────────────────────────────────────────────
const MILESTONES = [
{ min: 20, title: 'ESCALADO', subtitle: 'Entrou em campo', icon: '🏃', color: '#2d6a2d', accent: '#5cb85c', num: '020' },
{ min: 80, title: 'TITULAR', subtitle: 'No onze inicial', icon: '⚽', color: '#1a3f7a', accent: '#4a90d9', num: '080' },
{ min: 120, title: 'CAPITÃO', subtitle: 'Lidera o time', icon: '🦾', color: '#3b1a6e', accent: '#9b59b6', num: '120' },
{ min: 140, title: 'LENDA DO HEXA', subtitle: 'Conquistou tudo', icon: '🏆', color: '#7a5a00', accent: '#FECE02', num: '140' }];


function MilestoneCard({ milestone, achieved, isNext, unlockedCount }) {
  const pct = Math.min(100, Math.round(unlockedCount / milestone.min * 100));
  return (
    <div style={{
      width: SC_W, height: SC_H,
      borderRadius: 10,
      position: 'relative',
      overflow: 'hidden',
      flexShrink: 0,
      boxShadow: achieved ?
      `0 0 20px ${milestone.accent}88, 0 4px 8px rgba(0,0,0,0.4)` :
      '0 3px 8px rgba(0,0,0,0.5)',
      border: achieved ? `2px solid ${milestone.accent}` : '2px solid #2a2a2a',
      transition: 'all 0.4s'
    }}>
      {/* Background sticker image with tint */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'url(assets/sticker-card.png)',
        backgroundSize: 'cover',
        filter: achieved ? `sepia(1) hue-rotate(${milestone.num === '140' ? '0' : '200'}deg) saturate(${achieved ? 1.4 : 0.3}) brightness(${achieved ? 0.85 : 0.4})` : 'grayscale(1) brightness(0.3)'
      }} />

      {/* Dark overlay */}
      <div style={{ position: 'absolute', inset: 0, background: achieved ? `linear-gradient(160deg,${milestone.color}cc,${milestone.color}88)` : 'rgba(10,10,10,0.75)' }} />

      {/* Shimmer on achieved */}
      {achieved && <div className="rare-shimmer" style={{ zIndex: 4 }} />}

      {/* Top accent bar */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: achieved ? milestone.accent : '#2a2a2a', borderRadius: '10px 10px 0 0', zIndex: 3 }} />

      {/* Number badge */}
      <div style={{
        position: 'absolute', top: 7, left: 7, zIndex: 5,
        background: achieved ? milestone.accent : '#1a1a1a',
        color: achieved ? milestone.num === '140' ? '#1e1e1e' : '#fff' : '#555',
        fontFamily: "'Barlow Condensed',sans-serif",
        fontWeight: 800, fontSize: 10,
        padding: '2px 5px', borderRadius: 4, letterSpacing: '0.04em',
        whiteSpace: 'nowrap'
      }}>{milestone.min} fig.</div>

      {/* Icon / content area */}
      <div style={{
        position: 'absolute', top: 30, left: 0, right: 0, bottom: 44,
        display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center', gap: 4, zIndex: 3
      }}>
        <div style={{ fontSize: achieved ? 42 : 32, filter: achieved ? 'none' : 'grayscale(1)', opacity: achieved ? 1 : 0.3 }}>{achieved ? milestone.icon : '🔒'}</div>
        {!achieved &&
        <div style={{ width: 80, marginTop: 4 }}>
            <div style={{ height: 4, background: '#1a1a1a', borderRadius: 10, overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${pct}%`, background: '#333', borderRadius: 10, transition: 'width 0.5s' }} />
            </div>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 9, color: '#444', textAlign: 'center', marginTop: 3, letterSpacing: '0.06em' }}>{pct}%</div>
          </div>
        }
      </div>

      {/* Footer */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        background: achieved ? milestone.color : '#0f0f0f',
        borderTop: `1px solid ${achieved ? milestone.accent + '44' : '#1a1a1a'}`,
        padding: '5px 8px', zIndex: 3
      }}>
        <div style={{ fontFamily: "'Bebas Neue', sans-serif", fontSize: 11, color: achieved ? milestone.accent : '#333', lineHeight: 1.1, letterSpacing: '0.01em', textTransform: 'uppercase' }}>{milestone.title}</div>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 8.5, color: achieved ? 'rgba(255,255,255,0.6)' : '#2a2a2a', letterSpacing: '0.04em', marginTop: 1 }}>
          {achieved ? '★ ★ ★ ★ ★' : milestone.subtitle}
        </div>
      </div>

      {/* Achieved glow ring */}
      {achieved &&
      <div style={{ position: 'absolute', inset: -1, borderRadius: 11, border: `1px solid ${milestone.accent}66`, pointerEvents: 'none', zIndex: 6 }} />
      }
    </div>);

}

function EvolutionLeft({ unlockedCount }) {
  const current = [...MILESTONES].reverse().find((m) => unlockedCount >= m.min) || null;
  const next = MILESTONES.find((m) => unlockedCount < m.min);
  const pct = Math.min(100, Math.round(unlockedCount / 149 * 100));

  return (
    <div style={{ width: PW, height: PH, background: '#0f0f0f', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/cover-bg.png)', backgroundSize: 'cover', opacity: 0.04 }} />
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: `0 ${SMARG}px`, textAlign: "left", opacity: "1" }}>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 500, fontSize: 11, letterSpacing: '0.25em', color: '#FECE02', textTransform: 'uppercase', marginBottom: 14 }}>CONQUISTAS</div>
        <div style={{ fontSize: 40, lineHeight: 0.9, color: '#fff', marginBottom: 6, fontFamily: "\"Bebas Neue\"" }}>ESCALA<br />DA GLÓRIA</div>
        <div style={{ width: 52, height: 4, background: '#FECE02', borderRadius: 3, marginBottom: 28 }} />

        {/* Progress */}
        <div style={{ marginBottom: 32 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 15, color: '#fff' }}>{unlockedCount} de {ALBUM_DATA.areas.reduce((s, a) => s + a.times.reduce((ss, t) => ss + t.count, 0), 0)} figurinhas</div>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 15, color: '#FECE02' }}>{pct}%</div>
          </div>
          <div style={{ height: 8, background: '#1a1a1a', borderRadius: 10, overflow: 'hidden', border: '1px solid #2a2a2a' }}>
            <div style={{ height: '100%', width: `${pct}%`, background: 'linear-gradient(90deg,#FECE02,#fff8aa)', borderRadius: 10, transition: 'width 0.6s ease' }} />
          </div>
        </div>

        {/* Status */}
        <div style={{ padding: '18px 20px', background: 'rgba(254,206,2,0.06)', border: '1px solid rgba(254,206,2,0.15)', borderRadius: 12 }}>
          {current ?
          <>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 11, color: '#666', letterSpacing: '0.12em', marginBottom: 6 }}>SEU STATUS ATUAL</div>
              <div style={{ fontFamily: "'Bebas Neue', sans-serif", fontSize: 24, color: current.accent, lineHeight: 1 }}>{current.icon} {current.title}</div>
            </> :

          <>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 12, color: '#555', letterSpacing: '0.1em', marginBottom: 4 }}>AINDA NÃO INICIADO</div>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 14, color: '#FECE02' }}>Desbloqueie 20 figurinhas!</div>
            </>
          }
          {next &&
          <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 12, color: '#555', marginTop: 10 }}>
              Próximo: <span style={{ color: '#888' }}>{next.title}</span> — faltam <span style={{ color: '#FECE02' }}>{next.min - unlockedCount}</span> fig.
            </div>
          }
        </div>
      </div>
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 4, background: '#FECE02' }} />
      <SpineShadow side="left" dark />
    </div>);

}

function EvolutionRight({ unlockedCount }) {
  return (
    <div style={{ width: PW, height: PH, background: '#141414', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/sticker-template.png)', backgroundSize: 'cover', opacity: 0.04 }} />
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: '#FECE02' }} />

      <div style={{ position: 'absolute', top: TMARG, bottom: BMARG, left: GMARG, right: SMARG, display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 600, fontSize: 11, color: '#555', letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 16 }}>DESBLOQUEIO AUTOMÁTICO AO COLETAR</div>

        {/* 2×2 grid of milestone sticker cards */}
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(2, ${SC_W}px)`, gap: 12, justifyContent: 'center' }}>
          {MILESTONES.map((m, i) =>
          <MilestoneCard
            key={i}
            milestone={m}
            achieved={unlockedCount >= m.min}
            isNext={!unlockedCount >= m.min && (i === 0 || unlockedCount >= MILESTONES[i - 1]?.min)}
            unlockedCount={unlockedCount} />

          )}
        </div>
      </div>
      <SpineShadow side="right" dark />
    </div>);

}

// ── Modern Area Intro ─────────────────────────────────────────────
function AreaIntroBookPage({ area }) {
  const ac = AREA_COLORS[area.id] || { color: '#FECE02', text: '#1e1e1e' };
  const totalStickers = area.times.reduce((s, t) => s + t.count, 0);

  return (
    <div style={{ width: PW, height: PH, background: '#0f0f0f', position: 'relative', overflow: 'hidden' }}>
      {/* Bold color block — top half diagonal */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: PH * 0.52, background: ac.color, clipPath: 'polygon(0 0,100% 0,100% 78%,0 100%)' }} />

      {/* Big watermark number */}
      <div style={{ position: 'absolute', top: -20, right: -20, fontFamily: "'Holtwood One SC',serif", fontSize: 280, color: 'rgba(0,0,0,0.12)', lineHeight: 1, userSelect: 'none' }}>{totalStickers}</div>

      {/* Area label in color block — text must contrast against ac.color */}
      <div style={{ position: 'absolute', top: TMARG, left: SMARG, right: SMARG }}>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 600, fontSize: 11, letterSpacing: '0.28em', color: ac.textColor === '#ffffff' ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.5)', textTransform: 'uppercase', marginBottom: 10 }}>ÁREA DE ATUAÇÃO</div>
        <div style={{ fontSize: 44, lineHeight: 0.9, color: ac.textColor === '#ffffff' ? '#fff' : '#1e1e1e', marginBottom: 8, fontFamily: "\"Bebas Neue\"" }}>{area.name}</div>
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 14, color: ac.textColor === '#ffffff' ? 'rgba(255,255,255,0.55)' : 'rgba(0,0,0,0.45)', letterSpacing: '0.06em' }}>{totalStickers} FIGURINHAS · {area.times.length} TIMES</div>
      </div>

      {/* Bottom dark section — team list */}
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, top: PH * 0.48, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: `0 ${SMARG}px 40px` }}>
        <div style={{ width: 40, height: 3, background: ac.color, borderRadius: 2, marginBottom: 20 }} />
        {area.times.map((t, i) => <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: ac.color, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, border: '1px solid rgba(255,255,255,0.15)' }}>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 800, fontSize: 9, color: ac.textColor, letterSpacing: '0.01em', textAlign: 'center', lineHeight: 1.1 }}>{t.abbrev}</div>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 15, color: '#fff', textTransform: 'uppercase', lineHeight: 1 }}>{t.name}</div>
            </div>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 600, fontSize: 13, color: '#555' }}>{t.count} fig.</div>
          </div>
        )}
      </div>
      <SpineShadow side="left" dark />
    </div>);

}

// ── Team sticker page ─────────────────────────────────────────────
function TeamBookPage({ side, page, unlocked, onClickSticker }) {
  const { time, stickers, cont } = page;
  const ac = AREA_COLORS[time.area?.id] || { color: '#FECE02', text: '#1e1e1e' };
  const isLeft = side === 'left';
  const pl = isLeft ? SMARG : GMARG;
  const pr = isLeft ? GMARG : SMARG;
  const isRareArea = time.area?.id === 'hall';

  return (
    <div style={{ width: PW, height: PH, background: isRareArea ? '#0f0f0f' : '#ffffff', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/sticker-template.png)', backgroundSize: 'cover', backgroundPosition: 'center', opacity: isRareArea ? 0.05 : 0.07 }} />
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: isRareArea ? 'linear-gradient(90deg,#FECE02,#fff8aa,#FECE02)' : ac.color }} />
      {isRareArea && <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(135deg,rgba(254,206,2,0.04) 0%,transparent 60%)', pointerEvents: 'none' }} />}
      <RotatedSectionLabel text={time.name} />

      <div style={{ position: 'absolute', top: TMARG, bottom: BMARG, left: pl, right: pr, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, paddingBottom: 12, borderBottom: `2px solid ${isRareArea ? '#FECE02' : ac.color}` }}>
          <div style={{ width: 30, height: 36, background: isRareArea ? '#FECE02' : ac.color, clipPath: 'polygon(0 0,100% 0,100% 72%,50% 100%,0 72%)', flexShrink: 0 }} />
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.1, color: isRareArea ? '#FECE02' : '#1e1e1e', wordBreak: 'break-word', fontFamily: "\"Bebas Neue\"" }}>{time.name}</div>
            <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 400, fontSize: 11, color: isRareArea ? '#666' : '#aaa', letterSpacing: '0.06em', textTransform: 'uppercase', marginTop: 2 }}>
              {stickers.length} figurinhas{cont ? ' (cont.)' : ''}{isRareArea ? ' · ★ RARAS' : ''}
            </div>
          </div>
          {isRareArea && <div style={{ marginLeft: 'auto', fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 800, fontSize: 11, color: '#FECE02', background: 'rgba(254,206,2,0.12)', border: '1px solid rgba(254,206,2,0.3)', padding: '4px 10px', borderRadius: 20, letterSpacing: '0.08em' }}>EDIÇÃO ESPECIAL</div>}
        </div>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${COLS}, ${SC_W}px)`, gap: SC_G }}>
            {stickers.map((s) =>
            <BookSticker key={s.number} sticker={s} unlocked={unlocked.includes(s.number)} onClick={() => !unlocked.includes(s.number) && onClickSticker(s)} />
            )}
          </div>
        </div>
      </div>
      <PageFoot side={side} dark={isRareArea} /><SpineShadow side={side} dark={isRareArea} />
    </div>);

}

function EmptyPage({ side, areaId }) {
  const ac = AREA_COLORS[areaId] || { color: '#FECE02' };
  return (
    <div style={{ width: PW, height: PH, background: '#f8f8f6', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/sticker-template.png)', backgroundSize: 'cover', opacity: 0.04 }} />
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: ac.color }} />
      <SpineShadow side={side} />
    </div>);

}

function BackLeft() {
  return (
    <div style={{ width: PW, height: PH, background: '#f5f5f2', position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, textAlign: 'center', padding: 60, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 4, background: '#FECE02' }} />
      <div style={{ fontSize: 46, color: '#1e1e1e', lineHeight: 0.95, fontFamily: "\"Bebas Neue\"" }}>ALBUM<br />COMPLETO</div>
      <div style={{ width: 40, height: 4, background: '#FECE02', borderRadius: 2 }} />
      <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 13, color: '#888', lineHeight: 1.6 }}>{ALBUM_DATA.areas.reduce((s, a) => s + a.times.reduce((ss, t) => ss + t.count, 0), 0)} FIGURINHAS · {ALBUM_DATA.areas.reduce((s, a) => s + a.times.length, 0)} TIMES<br />Cole e complete sua coleção!</div>
      <SpineShadow side="left" />
    </div>);

}

function BackRight() {
  return (
    <div style={{ width: PW, height: PH, background: '#1e1e1e', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, backgroundImage: 'url(assets/back-bg.png)', backgroundSize: 'cover', transform: 'matrix(-1,0,0,1,654,-84)', transformOrigin: '0 0', opacity: 0.15 }} />
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14 }}>
        <img src="assets/conquer-logo.svg" style={{ width: 150, filter: 'brightness(0) invert(1)', opacity: 0.85 }} alt="Conquer" />
        <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 300, fontSize: 13, color: 'rgba(255,255,255,0.45)', letterSpacing: '0.22em', textTransform: 'uppercase' }}>BUSINESS SCHOOL</div>
      </div>
      <SpineShadow side="right" dark />
    </div>);

}

function PageFoot({ side, dark = false }) {
  const isLeft = side === 'left';
  return <div style={{ position: 'absolute', bottom: 10, [isLeft ? 'left' : 'right']: SMARG, fontFamily: "'Barlow Condensed',sans-serif", fontSize: 9, color: dark ? '#333' : '#ccc', letterSpacing: '0.12em', textTransform: 'uppercase' }}>Conquer Business School</div>;
}

function SpineShadow({ side, dark = false }) {
  const isLeft = side === 'left';
  const c = dark ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0.10)';
  return <div style={{ position: 'absolute', top: 0, [isLeft ? 'right' : 'left']: 0, width: 20, height: '100%', background: `linear-gradient(${isLeft ? 'to right' : 'to left'},transparent,${c})`, pointerEvents: 'none' }} />;
}

// ── Build spreads ─────────────────────────────────────────────────
function buildBookSpreads(areas, unlocked, onClickSticker) {
  const spreads = [];
  const unlockedCount = unlocked.length;

  spreads.push({ id: 'cover', label: 'Capa', left: <CoverLeft />, right: <CoverRight /> });

  const allTeams = areas.flatMap((a) => a.times.map((t) => ({ ...t, area: a })));
  const half = Math.ceil(allTeams.length / 2);
  spreads.push({
    id: 'index', label: 'Índice',
    left: <IndexPage side="left" teams={allTeams.slice(0, half)} />,
    right: <IndexPage side="right" teams={allTeams.slice(half)} showTitle={false} />
  });

  spreads.push({
    id: 'evolution', label: 'Escala da Glória',
    left: <EvolutionLeft unlockedCount={unlockedCount} />,
    right: <EvolutionRight unlockedCount={unlockedCount} />
  });

  areas.forEach((area) => {
    const pages = [];
    area.times.forEach((time) => {
      chunkBy(time.stickers, 9).forEach((chunk, ci) => {
        pages.push({ type: 'team', time, stickers: chunk, cont: ci > 0 });
      });
    });

    const first = pages.shift();
    spreads.push({
      id: `${area.id}-0`, label: area.name,
      left: <AreaIntroBookPage area={area} />,
      right: <TeamBookPage side="right" page={first} unlocked={unlocked} onClickSticker={onClickSticker} />
    });

    while (pages.length > 0) {
      const lp = pages.shift();
      const rp = pages.shift() || null;
      spreads.push({
        id: `${area.id}-${spreads.length}`, label: `${area.name} (cont.)`,
        left: <TeamBookPage side="left" page={lp} unlocked={unlocked} onClickSticker={onClickSticker} />,
        right: rp ?
        <TeamBookPage side="right" page={rp} unlocked={unlocked} onClickSticker={onClickSticker} /> :
        <EmptyPage side="right" areaId={area.id} />
      });
    }
  });

  spreads.push({ id: 'backcover', label: 'Contracapa', left: <BackLeft />, right: <BackRight /> });
  return spreads;
}

// ── BookAlbum — flip engine ───────────────────────────────────────
function BookAlbum({ areas, unlocked, onClickSticker }) {
  const [current, setCurrent] = useState(0);
  const [anim, setAnim] = useState(null);
  const [flipping, setFlipping] = useState(false);
  const timerRef = useRef(null);

  const spreads = buildBookSpreads(areas, unlocked, onClickSticker);
  const total = spreads.length;

  const goTo = useCallback((next, dir) => {
    if (flipping) return;
    if (next < 0 || next >= total) return;
    setAnim({ dir, next });
    requestAnimationFrame(() => requestAnimationFrame(() => setFlipping(true)));
    timerRef.current = setTimeout(() => {setCurrent(next);setAnim(null);setFlipping(false);}, 680);
  }, [flipping, total]);

  useEffect(() => () => clearTimeout(timerRef.current), []);
  useEffect(() => {
    const h = (e) => {
      if (e.key === 'ArrowRight') goTo(current + 1, 'fwd');
      if (e.key === 'ArrowLeft') goTo(current - 1, 'bwd');
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [current, goTo]);

  const sp = spreads[current];
  const nextSp = anim ? spreads[anim.next] : null;

  const flipStyle = anim ? {
    position: 'absolute', top: 0,
    left: anim.dir === 'fwd' ? PW : 0,
    width: PW, height: PH,
    transformStyle: 'preserve-3d',
    transformOrigin: anim.dir === 'fwd' ? 'left center' : 'right center',
    transition: flipping ? 'transform 0.65s cubic-bezier(0.4,0,0.2,1)' : 'none',
    transform: flipping ? anim.dir === 'fwd' ? 'rotateY(-180deg)' : 'rotateY(180deg)' : 'none',
    zIndex: 10, willChange: 'transform'
  } : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 20 }}>
      <div style={{ position: 'relative', width: PW * 2, height: PH, perspective: 2400, boxShadow: '0 32px 90px rgba(0,0,0,0.65), 0 0 0 1px rgba(0,0,0,0.2)', borderRadius: 2 }}>
        <div style={{ position: 'absolute', top: 0, left: 0, width: PW, height: PH, zIndex: 1 }}>{anim?.dir === 'bwd' ? nextSp?.left : sp.left}</div>
        <div style={{ position: 'absolute', top: 0, left: PW, width: PW, height: PH, zIndex: 1 }}>{anim?.dir === 'fwd' ? nextSp?.right : sp.right}</div>
        {anim &&
        <div style={flipStyle}>
            <div style={{ position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden' }}>
              {anim.dir === 'fwd' ? sp.right : sp.left}
              <div style={{ position: 'absolute', top: 0, [anim.dir === 'fwd' ? 'left' : 'right']: 0, width: 60, height: '100%', background: anim.dir === 'fwd' ? 'linear-gradient(to right,rgba(0,0,0,0.15),transparent)' : 'linear-gradient(to left,rgba(0,0,0,0.15),transparent)', pointerEvents: 'none', zIndex: 4 }} />
            </div>
            <div style={{ position: 'absolute', inset: 0, backfaceVisibility: 'hidden', WebkitBackfaceVisibility: 'hidden', transform: 'rotateY(180deg)' }}>
              {anim.dir === 'fwd' ? nextSp?.left : nextSp?.right}
            </div>
          </div>
        }
        <div style={{ position: 'absolute', top: 0, left: PW - 1, width: 2, height: PH, background: 'rgba(0,0,0,0.15)', zIndex: 20, pointerEvents: 'none' }} />
        <div style={{ position: 'absolute', bottom: -14, left: 30, right: 30, height: 26, background: 'rgba(0,0,0,0.45)', filter: 'blur(18px)', zIndex: 0, borderRadius: '50%' }} />
        {current > 0 && <button onClick={() => goTo(current - 1, 'bwd')} disabled={flipping} style={arrowBtnStyle('left')}>‹</button>}
        {current < total - 1 && <button onClick={() => goTo(current + 1, 'fwd')} disabled={flipping} style={arrowBtnStyle('right')}>›</button>}
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 24 }}>
        <button onClick={() => goTo(current - 1, 'bwd')} disabled={current === 0 || flipping} style={navBtn}>← ANTERIOR</button>
        <div style={{ textAlign: 'center', minWidth: 180 }}>
          <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 14, color: '#fff', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{sp.label}</div>
          <div style={{ fontFamily: "'Barlow Condensed',sans-serif", fontSize: 11, color: '#555', letterSpacing: '0.1em' }}>{current + 1} DE {total}</div>
        </div>
        <button onClick={() => goTo(current + 1, 'fwd')} disabled={current === total - 1 || flipping} style={navBtn}>PRÓXIMO →</button>
      </div>
    </div>);

}

function arrowBtnStyle(side) {
  return { position: 'absolute', top: '50%', [side]: -54, transform: 'translateY(-50%)', background: '#FECE02', border: 'none', borderRadius: '50%', width: 46, height: 46, fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 900, fontSize: 30, color: '#1e1e1e', cursor: 'pointer', zIndex: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 4px 16px rgba(0,0,0,0.45)', lineHeight: 1 };
}
const navBtn = { background: 'none', border: '1.5px solid #2a2a2a', color: '#666', fontFamily: "'Barlow Condensed',sans-serif", fontWeight: 700, fontSize: 11, letterSpacing: '0.12em', padding: '8px 22px', borderRadius: 20, cursor: 'pointer' };

Object.assign(window, { BookAlbum });