// site-jogador/js/recompensas.jsx
//
// Recompensas de Fundador (pré-registro): barra de progresso até a meta + 3 cards 3D
// (tilt + brilho seguindo o mouse) com a imagem PNG e os benefícios de cada item.
// Dados: data/rewards.json (copia publicada; fonte canonica em shared/rewards.json).

const RW_ACCENT = '#a8ff00';

// ── Barra de progresso de Fundadores ──────────────────────────────────
function FoundersBar({ current, goal, goalLabel }) {
  const c = current || 0;
  const g = goal || 0;
  const pct = g > 0 ? Math.min((c / g) * 100, 100) : 0;
  return (
    <div style={{
      background: 'rgba(28,28,28,0.7)',
      border: '1px solid rgba(255,255,255,0.08)',
      borderTop: `2px solid ${RW_ACCENT}`,
      padding: '22px 26px',
      marginBottom: 40,
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 10, marginBottom: 14 }}>
        <div>
          <div style={{ fontFamily: 'Share Tech Mono', fontSize: 10, color: RW_ACCENT, letterSpacing: '0.16em', marginBottom: 6 }}>
            FUNDADORES PRÉ-REGISTRADOS
          </div>
          <div style={{ fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 22, color: '#fff' }}>
            {c.toLocaleString('pt-BR')} <span style={{ color: 'rgba(255,255,255,0.4)', fontSize: 15, fontWeight: 500 }}>de {g.toLocaleString('pt-BR')}</span>
          </div>
        </div>
        <div style={{ fontFamily: 'Share Tech Mono', fontSize: 30, fontWeight: 700, color: RW_ACCENT }}>
          {pct.toFixed(0)}%
        </div>
      </div>

      <div style={{ height: 12, background: 'rgba(255,255,255,0.06)', position: 'relative', overflow: 'hidden', borderRadius: 2 }}>
        <div style={{
          position: 'absolute', top: 0, left: 0, bottom: 0, width: `${pct}%`,
          background: `linear-gradient(90deg, ${RW_ACCENT} 0%, #d4ff4d 100%)`,
          boxShadow: `0 0 14px ${RW_ACCENT}90`, transition: 'width 0.6s ease',
        }} />
      </div>

      <div style={{ fontFamily: 'Rajdhani', fontSize: 13, color: 'rgba(255,255,255,0.5)', lineHeight: 1.6, marginTop: 12 }}>
        Próxima recompensa: <span style={{ color: RW_ACCENT }}>{goalLabel}</span>. Cada novo Fundador chega mais perto.
      </div>
    </div>
  );
}

// ── Card 3D de recompensa (tilt + glare seguindo o mouse) ─────────────
function RewardCard({ reward }) {
  const ref = React.useRef(null);
  const achieved = reward.status === 'achieved';
  const accent = achieved ? RW_ACCENT : 'rgba(180,180,180,0.55)';

  const onMove = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width;
    const py = (e.clientY - r.top) / r.height;
    const MAX = 10; // graus de inclinacao
    el.style.transform =
      `rotateX(${((0.5 - py) * 2 * MAX).toFixed(2)}deg) rotateY(${((px - 0.5) * 2 * MAX).toFixed(2)}deg) scale(1.03)`;
    el.style.setProperty('--gx', (px * 100).toFixed(1) + '%');
    el.style.setProperty('--gy', (py * 100).toFixed(1) + '%');
  };
  const reset = () => { if (ref.current) ref.current.style.transform = 'rotateX(0deg) rotateY(0deg) scale(1)'; };

  return (
    <div style={{ perspective: 1000 }}>
      <div
        ref={ref}
        onMouseMove={onMove}
        onMouseLeave={reset}
        style={{
          position: 'relative',
          transformStyle: 'preserve-3d', willChange: 'transform',
          transition: 'transform 0.25s ease',
          background: achieved
            ? 'linear-gradient(160deg, rgba(30,40,12,0.9) 0%, rgba(20,20,20,0.94) 60%)'
            : 'rgba(22,22,22,0.85)',
          border: `1px solid ${achieved ? 'rgba(168,255,0,0.35)' : 'rgba(255,255,255,0.08)'}`,
          borderTop: `3px solid ${accent}`,
          paddingBottom: 22,
          height: '100%',
          opacity: achieved ? 1 : 0.94,
          boxShadow: achieved ? '0 18px 40px rgba(0,0,0,0.4)' : 'none',
        }}
      >
        {/* brilho que segue o mouse */}
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 5,
          background: `radial-gradient(circle at var(--gx,50%) var(--gy,50%), ${achieved ? 'rgba(168,255,0,0.16)' : 'rgba(255,255,255,0.06)'} 0%, transparent 45%)`,
        }} />

        {/* badge de status */}
        <div style={{
          position: 'absolute', top: 14, right: 14, zIndex: 6,
          fontFamily: 'Share Tech Mono', fontSize: 9, fontWeight: 700, letterSpacing: '0.14em',
          color: achieved ? '#0b0b0b' : '#fff',
          background: achieved ? accent : 'rgba(255,255,255,0.12)',
          border: achieved ? 'none' : '1px solid rgba(255,255,255,0.2)',
          padding: '4px 9px', transform: 'translateZ(40px)',
        }}>
          {achieved ? '✓ CONQUISTADA' : '🔒 BLOQUEADA'}
        </div>

        {/* imagem do item (pop pra frente no 3D) */}
        <div style={{
          position: 'relative', height: 230,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          background: achieved ? 'radial-gradient(circle at 50% 42%, rgba(168,255,0,0.10) 0%, transparent 68%)' : 'transparent',
          transform: 'translateZ(46px)',
        }}>
          {reward.image
            ? <img src={reward.image} alt={reward.name} style={{
                maxWidth: '78%', maxHeight: '90%', objectFit: 'contain',
                filter: achieved ? 'drop-shadow(0 10px 22px rgba(0,0,0,0.55))' : 'grayscale(1)', opacity: achieved ? 1 : 0.45,
              }} />
            : <div style={{ fontSize: 86, opacity: 0.3, transform: 'translateZ(0)' }}>🔒</div>}
        </div>

        {/* corpo */}
        <div style={{ padding: '0 22px', transform: 'translateZ(22px)' }}>
          <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: accent, letterSpacing: '0.16em', marginBottom: 4 }}>
            {reward.milestone}{reward.rarity ? `  ·  ${reward.rarity}` : ''}
          </div>
          <div style={{ fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 22, color: '#fff', lineHeight: 1.1, marginBottom: 6 }}>
            {reward.name}
          </div>
          {reward.tagline && (
            <div style={{ fontFamily: 'Rajdhani', fontWeight: 500, fontSize: 13, color: 'rgba(255,255,255,0.5)', lineHeight: 1.5, fontStyle: 'italic' }}>
              {reward.tagline}
            </div>
          )}

          <div style={{ height: 1, background: 'rgba(255,255,255,0.08)', margin: '14px 0' }} />

          <div style={{ fontFamily: 'Share Tech Mono', fontSize: 9, color: 'rgba(168,255,0,0.6)', letterSpacing: '0.16em', marginBottom: 10 }}>
            O QUE DÁ
          </div>
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {(reward.benefits || []).map((b, i) => (
              <li key={i} style={{
                fontFamily: 'Rajdhani', fontWeight: 500, fontSize: 13.5, lineHeight: 1.45,
                color: achieved ? 'rgba(255,255,255,0.75)' : 'rgba(255,255,255,0.5)',
                paddingLeft: 18, position: 'relative',
              }}>
                <span style={{ position: 'absolute', left: 0, color: accent, fontWeight: 700 }}>+</span>{b}
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
}

// ── MAIN ──────────────────────────────────────────────────────────────
function RecompensasFundador() {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [live, setLive] = React.useState(null); // contagem real de Fundadores (Supabase)

  React.useEffect(() => {
    const paths = ['data/rewards.json', '/data/rewards.json', '/shared/rewards.json', '../shared/rewards.json', 'shared/rewards.json'];
    (async () => {
      for (const p of paths) {
        try {
          const r = await fetch(p);
          if (r.ok) { const j = await r.json(); setData(j); return; }
        } catch (e) { /* try next */ }
      }
      setError('Falha ao carregar recompensas.');
    })();
  }, []);

  // contagem REAL de Fundadores via Supabase (RPC public_founder_count) -> barra "ao vivo".
  // re-busca a cada 60s e ao voltar pra aba. Se falhar, cai no numero do rewards.json.
  React.useEffect(() => {
    if (!window.sb) return;
    let alive = true;
    const pull = async () => {
      try {
        const { data: n, error: e } = await window.sb.rpc('public_founder_count');
        if (alive && !e && typeof n === 'number') setLive(n);
      } catch (err) { /* mantem o fallback */ }
    };
    pull();
    const id = setInterval(pull, 60000);
    const onVis = () => { if (document.visibilityState === 'visible') pull(); };
    document.addEventListener('visibilitychange', onVis);
    return () => { alive = false; clearInterval(id); document.removeEventListener('visibilitychange', onVis); };
  }, []);

  if (error || !data) return null; // silencioso: se nao carregar, a secao some

  const s = data.signups || {};
  const rewards = data.rewards || [];
  const current = (live != null) ? live : s.current; // ao vivo quando disponivel

  return (
    <section style={{
      background: 'rgba(20,20,20,0.85)',
      backdropFilter: 'blur(24px) saturate(1.2)',
      WebkitBackdropFilter: 'blur(24px) saturate(1.2)',
      padding: '80px 5vw',
      borderTop: '1px solid rgba(255,255,255,0.05)',
    }}>
      <div style={{ maxWidth: 1100, margin: '0 auto' }}>
        {/* header */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <div style={{ width: 24, height: 2, background: RW_ACCENT }} />
          <span style={{ fontFamily: 'Share Tech Mono', fontSize: 11, color: RW_ACCENT, letterSpacing: '0.18em' }}>
            RECOMPENSAS DE FUNDADOR
          </span>
        </div>
        <h2 style={{
          fontFamily: 'Rajdhani', fontWeight: 700, fontSize: 'clamp(28px,4vw,48px)',
          lineHeight: 1.1, textTransform: 'uppercase', marginBottom: 12,
        }}>
          QUEM CHEGA CEDO<br /><span style={{ color: RW_ACCENT }}>ENTRA EQUIPADO</span>
        </h2>
        <p style={{ color: 'rgba(255,255,255,0.6)', fontSize: 14, lineHeight: 1.7, maxWidth: 720, marginBottom: 32 }}>
          Cada marco de pré-registro desbloqueia uma recompensa pra todo mundo que se cadastrou.
          São itens que ajudam de verdade no começo, resgatados pelo Painel do Jogador quando a beta abrir.
        </p>

        {/* barra de progresso */}
        <FoundersBar current={current} goal={s.next_goal} goalLabel={s.goal_label} />

        {/* cards 3D */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 20 }}>
          {rewards.map((rw, i) => <RewardCard key={rw.id || i} reward={rw} />)}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { RecompensasFundador });
