// site-jogador/js/contadores-vivos.jsx
//
// Sub-fase 2 da Homepage. 3 contadores vivos de transparência:
//  1. Horas trabalhadas no projeto (lê shared/work-log.json)
//  2. R$ investido até hoje (lê shared/expenses.json — soma history)
//  3. Custo mensal recorrente (lê shared/expenses.json — soma monthly_recurring)
//
// Substitui a STATS BAR antiga (15 jogadores / 99% / 2x XP / 12 eventos)
// que tinha números fictícios. Agora é transparência real do projeto.

const { useState, useEffect } = React;

function CountUp({ target, duration = 1500, suffix = '', prefix = '', decimals = 0 }) {
  const [val, setVal] = useState(0);
  useEffect(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      const p = Math.min((now - start) / duration, 1);
      const ease = 1 - Math.pow(1 - p, 3);
      setVal(ease * target);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration]);

  const formatted = decimals > 0
    ? val.toFixed(decimals).replace('.', ',')
    : Math.round(val).toLocaleString('pt-BR');

  return <span>{prefix}{formatted}{suffix}</span>;
}

function ContadoresVivos() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Tenta múltiplos paths pra cobrir 2 setups de servidor:
    //  - http server na raiz do projeto: /shared/...
    //  - http server dentro de site-jogador: ../shared/... ou data/... (futuro)
    const tryPaths = async (file) => {
      const candidates = [`/shared/${file}`, `../shared/${file}`, `shared/${file}`];
      for (const p of candidates) {
        try {
          const r = await fetch(p);
          if (r.ok) return await r.json();
        } catch {}
      }
      throw new Error(`não foi possível carregar ${file} de nenhum path`);
    };

    Promise.all([tryPaths('work-log.json'), tryPaths('expenses.json')])
      .then(([workLog, expenses]) => {
        const totalHours = workLog.sessions.reduce((s, x) => s + (x.hours || 0), 0);
        const totalInvested = expenses.history.reduce((s, x) => s + (x.total || 0), 0);
        const monthlyRecurring = expenses.monthly_recurring
          .filter(e => e.active)
          .reduce((s, x) => s + x.value, 0);
        setData({ totalHours, totalInvested, monthlyRecurring });
      })
      .catch((err) => {
        console.error('Falha ao carregar contadores:', err);
        setError(err.message);
      });
  }, []);

  if (error) {
    return null; // falha silenciosa — site não quebra
  }

  const counters = [
    {
      label: 'HORAS TRABALHADAS',
      sublabel: 'desde abril de 2026',
      value: data?.totalHours ?? 0,
      suffix: 'h',
      color: '#a8ff00',
    },
    {
      label: 'INVESTIDO ATÉ HOJE',
      sublabel: 'infra + ferramentas + claude',
      value: data?.totalInvested ?? 0,
      prefix: 'R$ ',
      color: '#a8ff00',
    },
    {
      label: 'CUSTO MENSAL',
      sublabel: 'burn rate atual',
      value: data?.monthlyRecurring ?? 0,
      prefix: 'R$ ',
      color: '#f59e0b',
    },
  ];

  return (
    <div style={{
      background: 'rgba(20,20,20,0.82)',
      backdropFilter: 'blur(28px) saturate(1.3)',
      WebkitBackdropFilter: 'blur(28px) saturate(1.3)',
      borderTop: '1px solid rgba(168,255,0,0.15)',
      borderBottom: '1px solid rgba(168,255,0,0.15)',
      padding: '32px 5vw',
    }}>
      <div style={{ maxWidth: 1100, margin: '0 auto' }}>

        {/* Header pequeno */}
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%',
              background: '#a8ff00', boxShadow: '0 0 8px #a8ff00',
              animation: 'pulse 2.4s infinite',
            }} />
            <span style={{ fontFamily: 'Share Tech Mono', fontSize: 10, color: '#a8ff00', letterSpacing: '0.18em' }}>
              TRANSPARÊNCIA EM TEMPO REAL
            </span>
          </div>
          <p style={{ fontFamily: 'Share Tech Mono', fontSize: 10, color: 'rgba(255,255,255,0.35)', letterSpacing: '0.1em' }}>
            Atualizado automaticamente a cada sessão de trabalho
          </p>
        </div>

        {/* 3 contadores */}
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))',
          gap: 16,
          textAlign: 'center',
        }}>
          {counters.map((c, i) => (
            <div key={c.label} style={{
              padding: '16px 12px',
              borderRight: i < counters.length - 1 ? '1px solid rgba(255,255,255,0.06)' : 'none',
            }}>
              <div style={{
                fontFamily: 'Share Tech Mono',
                fontSize: 'clamp(28px, 4.2vw, 44px)',
                color: c.color,
                fontWeight: 400,
                lineHeight: 1.1,
                filter: `drop-shadow(0 0 12px ${c.color}40)`,
              }}>
                {data ? <CountUp target={c.value} prefix={c.prefix} suffix={c.suffix} /> : '—'}
              </div>
              <div style={{
                fontFamily: 'Rajdhani', fontWeight: 600,
                fontSize: 11, letterSpacing: '0.15em',
                color: 'rgba(255,255,255,0.5)',
                marginTop: 6,
              }}>
                {c.label}
              </div>
              <div style={{
                fontFamily: 'Share Tech Mono', fontSize: 9,
                color: 'rgba(255,255,255,0.3)', letterSpacing: '0.08em',
                marginTop: 3,
              }}>
                {c.sublabel}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ContadoresVivos });
