// ── Album Interativo — Componentes React ─────────────────────────
// Carregado via <script type="text/babel">

const { useState, useEffect, useCallback, useRef } = React;

// ── Paleta de áreas ───────────────────────────────────────────────
const AREA_COLORS = {
  hall:       { color: '#FECE02', text: '#1e1e1e', label: 'Hall da Fama' },
  b2c:        { color: '#1a5fb4', text: '#fff',    label: 'Inside Sales' },
  outbound:   { color: '#e65c00', text: '#fff',    label: 'CSP' },
  incompany:  { color: '#276221', text: '#fff',    label: 'Comercial In Company' },
  apoio:      { color: '#6d28d9', text: '#fff',    label: 'Revenue Operations (RevOps)' },
  academica:  { color: '#0e7490', text: '#fff',    label: 'Operação Acadêmica' },
  marketing:  { color: '#b91c1c', text: '#fff',    label: 'Marketing' },
};

// ── DB abstraction (Firebase ou localStorage demo) ────────────────
const DB = {
  async registerUser(data) {
    if (IS_DEMO_MODE) {
      const users = JSON.parse(localStorage.getItem('cbs_users') || '[]');
      const existing = users.find(u => u.email === data.email);
      if (existing) return existing;
      const user = { ...data, id: data.email, createdAt: Date.now(), unlockedCount: 0 };
      users.push(user);
      localStorage.setItem('cbs_users', JSON.stringify(users));
      return user;
    }
    const db = firebase.firestore();
    const existing = await db.collection('users').where('email', '==', data.email).get();
    if (!existing.empty) return { id: existing.docs[0].id, ...existing.docs[0].data() };
    const ref = await db.collection('users').add({ ...data, createdAt: Date.now(), unlockedCount: 0 });
    return { id: ref.id, ...data, unlockedCount: 0 };
  },

  async getProgress(userId) {
    if (IS_DEMO_MODE) {
      const p = localStorage.getItem(`cbs_progress_${userId}`);
      return p ? JSON.parse(p) : [];
    }
    const db = firebase.firestore();
    const doc = await db.collection('progress').doc(userId).get();
    return doc.exists ? (doc.data().unlocked || []) : [];
  },

  async unlockSticker(userId, stickerNum, count) {
    if (IS_DEMO_MODE) {
      const prev = JSON.parse(localStorage.getItem(`cbs_progress_${userId}`) || '[]');
      if (!prev.includes(stickerNum)) {
        prev.push(stickerNum);
        localStorage.setItem(`cbs_progress_${userId}`, JSON.stringify(prev));
        // update user count
        const users = JSON.parse(localStorage.getItem('cbs_users') || '[]');
        const u = users.find(x => x.id === userId || x.email === userId);
        if (u) { u.unlockedCount = prev.length; localStorage.setItem('cbs_users', JSON.stringify(users)); }
      }
      return prev;
    }
    const db = firebase.firestore();
    const batch = db.batch();
    const progRef = db.collection('progress').doc(userId);
    batch.set(progRef, { unlocked: firebase.firestore.FieldValue.arrayUnion(stickerNum) }, { merge: true });
    const userRef = db.collection('users').doc(userId);
    batch.update(userRef, { unlockedCount: count });
    await batch.commit();
    return null;
  },

  async getLeaderboard() {
    if (IS_DEMO_MODE) {
      const users = JSON.parse(localStorage.getItem('cbs_users') || '[]');
      return users.sort((a, b) => (b.unlockedCount || 0) - (a.unlockedCount || 0)).slice(0, 20);
    }
    const db = firebase.firestore();
    const snap = await db.collection('users').orderBy('unlockedCount', 'desc').limit(20).get();
    return snap.docs.map(d => ({ id: d.id, ...d.data() }));
  }
};

// ── RegisterPage ──────────────────────────────────────────────────
function RegisterPage({ onRegister }) {
  const [form, setForm] = useState({ name: '', email: '', phone: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.phone) { setError('Preencha todos os campos.'); return; }
    if (!/\S+@\S+\.\S+/.test(form.email)) { setError('E-mail inválido.'); return; }
    setLoading(true); setError('');
    try {
      const user = await DB.registerUser(form);
      onRegister(user);
    } catch(err) { setError('Erro ao cadastrar. Tente novamente.'); }
    setLoading(false);
  };

  return (
    <div style={regStyles.page}>
      <div style={regStyles.bg} />
      <div style={regStyles.card}>
        {/* Logo / header */}
        <div style={regStyles.header}>
          <img src="assets/conquer-logo.svg" style={regStyles.logo} alt="Conquer" />
          <div style={regStyles.title}>ÁLBUM DA COPA</div>
          <div style={regStyles.subtitle}>CONQUER BUSINESS SCHOOL</div>
          <div style={regStyles.divider} />
          <div style={regStyles.desc}>
            Cadastre-se para receber seu álbum e começar a colecionar as 149 figurinhas!
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} style={regStyles.form}>
          <Field label="Nome completo" value={form.name}
            onChange={v => setForm(f => ({...f, name: v}))} placeholder="Seu nome" />
          <Field label="E-mail" value={form.email} type="email"
            onChange={v => setForm(f => ({...f, email: v}))} placeholder="seu@email.com" />
          <Field label="Telefone / WhatsApp" value={form.phone} type="tel"
            onChange={v => setForm(f => ({...f, phone: v}))} placeholder="(11) 99999-9999" />
          {error && <div style={regStyles.error}>{error}</div>}
          <button type="submit" style={regStyles.btn} disabled={loading}>
            {loading ? 'Cadastrando...' : 'ENTRAR NO ÁLBUM →'}
          </button>
        </form>

        <div style={regStyles.hint}>
          {IS_DEMO_MODE && <span style={{color:'#FECE02'}}>⚠ Modo demo — configure o Firebase para persistência real.</span>}
        </div>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, type = 'text', placeholder }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={regStyles.label}>{label}</label>
      <input
        type={type} value={value} placeholder={placeholder}
        onChange={e => onChange(e.target.value)}
        style={regStyles.input}
        onFocus={e => e.target.style.borderColor = '#FECE02'}
        onBlur={e => e.target.style.borderColor = '#333'}
      />
    </div>
  );
}

const regStyles = {
  page: { minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#0f0f0f', padding: 24, position: 'relative', overflow: 'hidden' },
  bg: { position: 'absolute', inset: 0, backgroundImage: 'url(assets/cover-bg.png)', backgroundSize: 'cover', backgroundPosition: 'center', opacity: 0.06, pointerEvents: 'none' },
  card: { background: '#1a1a1a', borderRadius: 20, padding: '48px 40px', width: '100%', maxWidth: 440, position: 'relative', zIndex: 1, border: '1px solid #2a2a2a' },
  header: { textAlign: 'center', marginBottom: 36 },
  logo: { width: 80, filter: 'brightness(0) invert(1)', marginBottom: 20 },
  title: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 36, color: '#fff', letterSpacing: '-0.01em', lineHeight: 1 },
  subtitle: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 500, fontSize: 13, color: '#FECE02', letterSpacing: '0.2em', marginTop: 4 },
  divider: { width: 40, height: 3, background: '#FECE02', borderRadius: 2, margin: '16px auto' },
  desc: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 15, color: '#888', lineHeight: 1.5 },
  form: { display: 'flex', flexDirection: 'column' },
  label: { display: 'block', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 600, fontSize: 12, color: '#888', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 6 },
  input: { width: '100%', background: '#111', border: '1.5px solid #333', borderRadius: 10, padding: '12px 16px', fontFamily: "'Barlow Condensed', sans-serif", fontSize: 16, color: '#fff', outline: 'none', transition: 'border-color 0.15s', boxSizing: 'border-box' },
  error: { background: '#2a1111', border: '1px solid #b91c1c', color: '#f87171', borderRadius: 8, padding: '10px 14px', fontFamily: "'Barlow Condensed', sans-serif", fontSize: 14, marginBottom: 12 },
  btn: { background: '#FECE02', color: '#1e1e1e', border: 'none', borderRadius: 10, padding: '14px 0', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 800, fontSize: 16, letterSpacing: '0.08em', cursor: 'pointer', marginTop: 8, transition: 'opacity 0.15s' },
  hint: { textAlign: 'center', marginTop: 20, fontFamily: "'Barlow Condensed', sans-serif", fontSize: 12, color: '#555' },
};

// ── StickerCard (locked / unlocked) ──────────────────────────────
function StickerCard({ sticker, unlocked, onClickLocked }) {
  const [flipped, setFlipped] = useState(false);
  const [justUnlocked, setJustUnlocked] = useState(false);

  // Trigger flip animation when sticker becomes unlocked for the first time
  useEffect(() => {
    if (unlocked && !flipped) {
      const t = setTimeout(() => setFlipped(true), 50);
      return () => clearTimeout(t);
    }
  }, [unlocked]);

  const handleClick = () => {
    if (!unlocked) onClickLocked(sticker);
  };

  const areaC = AREA_COLORS[sticker.areaId] || { color: '#FECE02', text: '#1e1e1e' };

  return (
    <div
      onClick={handleClick}
      title={unlocked ? sticker.name : `Figurinha ${sticker.number} — clique para desbloquear`}
      style={{
        width: 120, height: 168,
        perspective: 600,
        cursor: unlocked ? 'default' : 'pointer',
        flexShrink: 0,
      }}
    >
      <div style={{
        width: '100%', height: '100%',
        position: 'relative',
        transformStyle: 'preserve-3d',
        transition: 'transform 0.6s cubic-bezier(0.4,0,0.2,1)',
        transform: (unlocked && flipped) ? 'rotateY(180deg)' : 'none',
      }}>
        {/* FRONT — locked */}
        <div style={{
          position: 'absolute', inset: 0,
          backfaceVisibility: 'hidden',
          WebkitBackfaceVisibility: 'hidden',
          borderRadius: 9,
          backgroundImage: 'url(assets/sticker-placeholder.png)',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          boxShadow: unlocked ? 'none' : '0 3px 10px rgba(0,0,0,0.35)',
          overflow: 'hidden',
        }}>
          {/* Number badge */}
          <div style={{
            position: 'absolute', top: 5, left: 5,
            background: areaC.color, color: areaC.text,
            fontFamily: "'Barlow Condensed', sans-serif",
            fontWeight: 700, fontSize: 10,
            padding: '2px 5px', borderRadius: 4,
            zIndex: 2,
          }}>{sticker.number}</div>
          {/* Top accent */}
          <div style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: areaC.color, borderRadius: '9px 9px 0 0', zIndex: 2 }} />
        </div>

        {/* BACK — unlocked */}
        <div style={{
          position: 'absolute', inset: 0,
          backfaceVisibility: 'hidden',
          WebkitBackfaceVisibility: 'hidden',
          transform: 'rotateY(180deg)',
          borderRadius: 9,
          background: `linear-gradient(160deg, ${areaC.color}22 0%, #fff 50%)`,
          border: `2.5px solid ${areaC.color}`,
          boxShadow: `0 4px 16px ${areaC.color}44`,
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
        }}>
          <div style={{ height: 3, background: areaC.color, flexShrink: 0 }} />
          {/* Photo area */}
          <div style={{
            flex: 1,
            background: sticker.photoUrl
              ? `url(${sticker.photoUrl}) center/cover no-repeat`
              : `linear-gradient(135deg, ${areaC.color}33 0%, ${areaC.color}11 100%)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {!sticker.photoUrl && (
              <div style={{
                fontFamily: "'Barlow Condensed', sans-serif",
                fontWeight: 900, fontSize: 32,
                color: areaC.color, opacity: 0.6,
              }}>
                {sticker.name ? sticker.name.split(' ').map(w => w[0]).slice(0,2).join('') : '?'}
              </div>
            )}
          </div>
          {/* Footer */}
          <div style={{
            background: '#1e1e1e', padding: '6px 8px',
            display: 'flex', flexDirection: 'column', gap: 2,
          }}>
            <div style={{
              fontFamily: "'Barlow Condensed', sans-serif",
              fontWeight: 700, fontSize: 11,
              color: '#fff', textTransform: 'uppercase',
              letterSpacing: '0.03em',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{sticker.name || 'CONQUER'}</div>
            <div style={{
              fontFamily: "'Barlow Condensed', sans-serif",
              fontSize: 9, color: areaC.color, letterSpacing: '0.05em',
              textTransform: 'uppercase',
            }}>{sticker.teamName}</div>
          </div>
          {/* Number */}
          <div style={{
            position: 'absolute', top: 5, right: 5,
            background: areaC.color, color: areaC.text,
            fontFamily: "'Barlow Condensed', sans-serif",
            fontWeight: 700, fontSize: 9,
            padding: '2px 4px', borderRadius: 3,
          }}>{sticker.number}</div>
        </div>
      </div>
    </div>
  );
}

// ── UnlockModal ───────────────────────────────────────────────────
function UnlockModal({ sticker, onClose, onUnlock, userId }) {
  const [code, setCode] = useState('');
  const [status, setStatus] = useState('idle'); // idle | loading | success | error
  const inputRef = useRef(null);

  useEffect(() => { setTimeout(() => inputRef.current?.focus(), 100); }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setStatus('loading');
    await new Promise(r => setTimeout(r, 400));

    // Check pack access first
    const hasAccess = await PACK_SYSTEM.canUnlock(userId, sticker.number);
    if (!hasAccess) {
      setStatus('noaccess');
      setTimeout(() => setStatus('idle'), 3000);
      return;
    }

    const expected = STICKER_CODES[sticker.number];
    if (code.trim().toUpperCase() === expected) {
      setStatus('success');
      setTimeout(() => { onUnlock(sticker); onClose(); }, 1200);
    } else {
      setStatus('error');
      setTimeout(() => setStatus('idle'), 1800);
    }
  };

  const areaC = AREA_COLORS[sticker.areaId] || { color: '#FECE02', text: '#1e1e1e' };

  return (
    <div style={modalStyles.overlay} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={modalStyles.box}>
        {/* Close */}
        <button onClick={onClose} style={modalStyles.close}>✕</button>

        {/* Sticker preview */}
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 20 }}>
          <div style={{
            width: 100, height: 140, borderRadius: 9,
            backgroundImage: 'url(assets/sticker-card.png)', backgroundSize: 'cover',
            filter: 'grayscale(1) brightness(0.55)',
            border: `2px solid ${areaC.color}`,
            position: 'relative',
            boxShadow: `0 0 20px ${areaC.color}44`,
          }}>
            <div style={{
              position: 'absolute', inset: 0, display: 'flex',
              alignItems: 'center', justifyContent: 'center',
            }}>
              <div style={{ fontSize: 28 }}>🔒</div>
            </div>
            <div style={{
              position: 'absolute', top: 4, left: 4,
              background: areaC.color, color: areaC.text,
              fontFamily: "'Barlow Condensed', sans-serif",
              fontWeight: 700, fontSize: 10, padding: '2px 5px', borderRadius: 4,
            }}>{sticker.number}</div>
          </div>
        </div>

        <div style={modalStyles.title}>DESBLOQUEAR FIGURINHA</div>
        <div style={modalStyles.teamLabel} >{sticker.teamName} · {areaC.label}</div>

        {status === 'success' ? (
          <div style={modalStyles.successMsg}>
            <div style={{ fontSize: 36, marginBottom: 8 }}>🎉</div>
            <div>Figurinha desbloqueada!</div>
          </div>
        ) : (
          <form onSubmit={handleSubmit}>
            <div style={modalStyles.codeLabel}>Digite o código da figurinha</div>
            <input
              ref={inputRef}
              value={code}
              onChange={e => setCode(e.target.value.toUpperCase())}
              placeholder={`EX: ${sticker.number}-XXXX`}
              maxLength={12}
              style={{
                ...modalStyles.codeInput,
                borderColor: status === 'error' ? '#b91c1c' : status === 'success' ? '#22c55e' : '#333',
              }}
            />
            {status === 'noaccess' && (
              <div style={{...modalStyles.errorMsg, color:'#f59e0b', background:'rgba(245,158,11,0.1)', border:'1px solid rgba(245,158,11,0.3)', padding:'12px 14px', borderRadius:8}}>
                🔒 Você ainda não recebeu este pack.<br/>
                <span style={{fontSize:11, color:'#888'}}>Aguarde a distribuição do seu pack pelo administrador.</span>
              </div>
            )}
            {status === 'error' && (
              <div style={modalStyles.errorMsg}>Código inválido. Verifique e tente novamente.</div>
            )}
            <button
              type="submit"
              disabled={status === 'loading' || code.length < 6}
              style={{...modalStyles.unlockBtn, background: areaC.color, color: areaC.text}}
            >
              {status === 'loading' ? '...' : 'DESBLOQUEAR'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}

const modalStyles = {
  overlay: { position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 1000, padding: 20, backdropFilter: 'blur(4px)' },
  box: { background: '#1a1a1a', borderRadius: 20, padding: '40px 36px', width: '100%', maxWidth: 360, position: 'relative', border: '1px solid #2a2a2a', textAlign: 'center' },
  close: { position: 'absolute', top: 14, right: 16, background: 'none', border: 'none', color: '#666', fontSize: 18, cursor: 'pointer', padding: 4 },
  title: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 22, color: '#fff', letterSpacing: '0.04em', marginBottom: 4 },
  teamLabel: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 13, color: '#888', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 24 },
  codeLabel: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 12, color: '#888', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 8 },
  codeInput: { width: '100%', background: '#111', border: '2px solid #333', borderRadius: 10, padding: '14px 0', textAlign: 'center', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 800, fontSize: 24, color: '#fff', letterSpacing: '0.2em', outline: 'none', boxSizing: 'border-box', marginBottom: 8, transition: 'border-color 0.2s' },
  errorMsg: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 13, color: '#f87171', marginBottom: 12 },
  successMsg: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 700, fontSize: 20, color: '#22c55e', padding: '20px 0' },
  unlockBtn: { width: '100%', border: 'none', borderRadius: 10, padding: '14px 0', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 800, fontSize: 16, letterSpacing: '0.08em', cursor: 'pointer', marginTop: 4, transition: 'opacity 0.15s' },
};

// ── ProgressBar ───────────────────────────────────────────────────
function ProgressBar({ unlocked, total }) {
  const pct = Math.round((unlocked / total) * 100);
  return (
    <div style={pbStyles.wrap}>
      <div style={pbStyles.track}>
        <div style={{ ...pbStyles.fill, width: `${pct}%` }} />
      </div>
      <div style={pbStyles.label}>{unlocked} / {total} figurinhas — {pct}%</div>
    </div>
  );
}
const pbStyles = {
  wrap: { padding: '0 0 16px' },
  track: { height: 6, background: '#2a2a2a', borderRadius: 10, overflow: 'hidden', marginBottom: 6 },
  fill: { height: '100%', background: '#FECE02', borderRadius: 10, transition: 'width 0.5s ease' },
  label: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 13, color: '#888', letterSpacing: '0.06em' },
};

// ── LeaderboardPage ───────────────────────────────────────────────
function LeaderboardPage({ currentUser }) {
  const [board, setBoard] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    DB.getLeaderboard().then(data => { setBoard(data); setLoading(false); });
  }, []);

  const medals = ['🥇', '🥈', '🥉'];

  return (
    <div style={lbStyles.page}>
      <div style={lbStyles.header}>
        <div style={lbStyles.title}>PLACAR GERAL</div>
        <div style={lbStyles.sub}>Quem está completando mais rápido?</div>
      </div>
      {loading ? (
        <div style={lbStyles.loading}>Carregando...</div>
      ) : (
        <div style={lbStyles.list}>
          {board.map((u, i) => (
            <div key={u.id} style={{
              ...lbStyles.row,
              background: u.email === currentUser?.email ? '#2a2a00' : '#1a1a1a',
              border: u.email === currentUser?.email ? '1.5px solid #FECE02' : '1.5px solid #222',
            }}>
              <div style={lbStyles.rank}>{medals[i] || `${i+1}°`}</div>
              <div style={lbStyles.name}>
                <div style={lbStyles.nameText}>{u.name}</div>
                {u.email === currentUser?.email && <div style={lbStyles.youBadge}>VOCÊ</div>}
              </div>
              <div style={lbStyles.count}>{u.unlockedCount || 0}</div>
              <div style={lbStyles.bar}>
                <div style={{ ...lbStyles.barFill, width: `${Math.round(((u.unlockedCount||0)/149)*100)}%` }} />
              </div>
            </div>
          ))}
          {board.length === 0 && <div style={lbStyles.empty}>Nenhum cadastro ainda.</div>}
        </div>
      )}
    </div>
  );
}

const lbStyles = {
  page: { padding: '0 0 48px' },
  header: { marginBottom: 28 },
  title: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 32, color: '#fff', letterSpacing: '-0.01em' },
  sub: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 14, color: '#888', letterSpacing: '0.04em' },
  loading: { fontFamily: "'Barlow Condensed', sans-serif", color: '#666', fontSize: 16, textAlign: 'center', padding: 40 },
  list: { display: 'flex', flexDirection: 'column', gap: 8 },
  row: { borderRadius: 12, padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12 },
  rank: { fontSize: 20, width: 32, flexShrink: 0, textAlign: 'center' },
  name: { flex: 1, display: 'flex', alignItems: 'center', gap: 8 },
  nameText: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 700, fontSize: 16, color: '#fff', textTransform: 'uppercase', letterSpacing: '0.03em' },
  youBadge: { background: '#FECE02', color: '#1e1e1e', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 700, fontSize: 10, padding: '2px 6px', borderRadius: 4, letterSpacing: '0.08em' },
  count: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 22, color: '#FECE02', width: 40, textAlign: 'right', flexShrink: 0 },
  bar: { width: 80, height: 5, background: '#333', borderRadius: 10, overflow: 'hidden', flexShrink: 0 },
  barFill: { height: '100%', background: '#FECE02', borderRadius: 10, transition: 'width 0.4s' },
  empty: { fontFamily: "'Barlow Condensed', sans-serif", color: '#555', fontSize: 15, textAlign: 'center', padding: 32 },
};

// ── AdminPage ─────────────────────────────────────────────────────
function AdminPage() {
  const areas = ALBUM_DATA.areas;
  const allStickers = areas.flatMap(a => a.times.flatMap(t => t.stickers));

  const downloadCSV = () => {
    const rows = [['Número','Time','Área','Código']];
    allStickers.forEach(s => rows.push([s.number, s.team, s.areaColor ? s.areaColor : '—', STICKER_CODES[s.number]]));
    const csv = rows.map(r => r.join(',')).join('\n');
    const a = document.createElement('a');
    a.href = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    a.download = 'codigos-figurinhas.csv';
    a.click();
  };

  return (
    <div style={{ padding: '0 0 48px' }}>
      <div style={{ fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 28, color: '#FECE02', marginBottom: 8 }}>PAINEL ADMIN</div>
      <div style={{ fontFamily: "'Barlow Condensed', sans-serif", fontSize: 14, color: '#888', marginBottom: 24 }}>Acesse via ?admin=true</div>
      <button onClick={downloadCSV} style={{ background: '#FECE02', color: '#1e1e1e', border: 'none', borderRadius: 10, padding: '12px 24px', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 800, fontSize: 15, cursor: 'pointer', marginBottom: 32 }}>
        ⬇ EXPORTAR TODOS OS CÓDIGOS (.CSV)
      </button>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 8 }}>
        {allStickers.slice(0, 30).map(s => (
          <div key={s.number} style={{ background: '#1a1a1a', borderRadius: 8, padding: '10px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontFamily: "'Barlow Condensed', sans-serif", color: '#888', fontSize: 14 }}>{s.number} · {s.team}</span>
            <span style={{ fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 700, color: '#FECE02', fontSize: 15, letterSpacing: '0.1em' }}>{STICKER_CODES[s.number]}</span>
          </div>
        ))}
        {allStickers.length > 30 && <div style={{ fontFamily: "'Barlow Condensed', sans-serif", color: '#555', fontSize: 13, padding: 10 }}>...e mais {allStickers.length - 30} figurinhas no CSV.</div>}
      </div>
    </div>
  );
}

// ── AlbumView ─────────────────────────────────────────────────────
function AlbumView({ user, unlocked, onUnlock }) {
  const [modal, setModal] = useState(null);
  const [activeTab, setActiveTab] = useState('album');
  const [filterArea, setFilterArea] = useState('all');

  const isAdmin = new URLSearchParams(window.location.search).get('admin') === 'true';
  const areas = ALBUM_DATA.areas;
  const allStickers = areas.flatMap(a => a.times.flatMap(t => t.stickers));
  const total = allStickers.length;

  const handleUnlock = async (sticker) => {
    if (unlocked.includes(sticker.number)) return;
    const newCount = unlocked.length + 1;
    await DB.unlockSticker(user.id || user.email, sticker.number, newCount);
    onUnlock(sticker.number);
  };

  const tabs = [
    { id: 'album', label: '⊞ ÁLBUM' },
    { id: 'leaderboard', label: '🏆 PLACAR' },
    ...(isAdmin ? [{ id: 'admin', label: '⚙ ADMIN' }] : []),
  ];

  return (
    <div style={avStyles.page}>
      {/* Header */}
      <div style={avStyles.header}>
        <div style={avStyles.headerInner}>
          <div style={avStyles.headerLeft}>
            <img src="assets/conquer-logo.svg" style={avStyles.headerLogo} alt="Conquer" />
            <div>
              <div style={avStyles.headerTitle}>ÁLBUM DA COPA</div>
              <div style={avStyles.headerUser}>Olá, {user.name.split(' ')[0]}!</div>
            </div>
          </div>
          <ProgressBar unlocked={unlocked.length} total={total} />
        </div>

        {/* Tabs */}
        <div style={avStyles.tabs}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setActiveTab(t.id)} style={{
              ...avStyles.tab,
              borderBottom: activeTab === t.id ? '2.5px solid #FECE02' : '2.5px solid transparent',
              color: activeTab === t.id ? '#FECE02' : '#888',
            }}>{t.label}</button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={avStyles.content}>
        {activeTab === 'album' && (
          <div style={{ display:'flex', justifyContent:'center', padding:'8px 0 48px' }}>
            <BookAlbum
              areas={areas}
              unlocked={unlocked}
              onClickSticker={setModal}
            />
          </div>
        )}

        {activeTab === 'leaderboard' && <LeaderboardPage currentUser={user} />}
        {activeTab === 'admin' && <AdminPage />}
      </div>

      {/* Unlock modal */}
      {modal && (
        <UnlockModal
          sticker={modal}
          onClose={() => setModal(null)}
          onUnlock={handleUnlock}
          userId={user.id || user.email}
        />
      )}
    </div>
  );
}

const avStyles = {
  page: { minHeight: '100vh', background: '#0f0f0f', color: '#fff' },
  header: { position: 'sticky', top: 0, background: '#0f0f0f', borderBottom: '1px solid #1e1e1e', zIndex: 100, padding: '0 80px' },
  headerInner: { maxWidth: 1320, margin: '0 auto', padding: '16px 0 8px', display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap' },
  headerLeft: { display: 'flex', alignItems: 'center', gap: 14, flex: '0 0 auto' },
  headerLogo: { width: 36, filter: 'brightness(0) invert(1)' },
  headerTitle: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 900, fontSize: 20, color: '#fff', letterSpacing: '0.02em', lineHeight: 1 },
  headerUser: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 13, color: '#FECE02', letterSpacing: '0.05em' },
  tabs: { maxWidth: 1320, margin: '0 auto', display: 'flex', gap: 4, paddingTop: 4 },
  tab: { background: 'none', border: 'none', padding: '10px 16px', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 700, fontSize: 13, letterSpacing: '0.1em', cursor: 'pointer', transition: 'color 0.15s, border-color 0.15s' },
  content: { maxWidth: 1320, margin: '0 auto', padding: '32px 80px' },
  filterRow: { display: 'flex', flexWrap: 'wrap', gap: 8, marginBottom: 28 },
  filterBtn: { border: 'none', borderRadius: 20, padding: '6px 14px', fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 600, fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase', cursor: 'pointer', transition: 'all 0.15s' },
  section: { marginBottom: 40 },
  areaHeader: { display: 'flex', alignItems: 'center', gap: 10, paddingBottom: 12, marginBottom: 16, borderBottom: '2px solid' },
  areaDot: { width: 10, height: 10, borderRadius: '50%', flexShrink: 0 },
  areaName: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 800, fontSize: 18, color: '#fff', letterSpacing: '0.04em', flex: 1 },
  areaCount: { fontFamily: "'Barlow Condensed', sans-serif", fontSize: 13, color: '#888', letterSpacing: '0.06em' },
  teamBlock: { marginBottom: 24 },
  teamName: { fontFamily: "'Barlow Condensed', sans-serif", fontWeight: 600, fontSize: 13, color: '#888', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 10 },
  stickerRow: { display: 'flex', flexWrap: 'wrap', gap: 10 },
};

// Export
Object.assign(window, { RegisterPage, AlbumView, ProgressBar, LeaderboardPage, AdminPage });
