/* SINAIS FIFA — Dashboard (GoldeBet iframe placeholder + tools) */

const { useState: useS_D, useEffect: useE_D } = React;

const HouseFrame = () => (
  <div className="house-frame">
    <iframe
      className="house-iframe"
      src={AFFIL.iframeUrl}
      title="GoldeBet"
      sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
      allow="autoplay; fullscreen"
    />
  </div>
);

const TilesRow = () => (
  <div className="tiles">
    {TILES_FIFA.map((t, i) => (
      <div className="tile" key={i}>
        <div className="tile-k">{t.k}</div>
        <div className={`tile-v ${t.cls || ''}`}>{t.v}</div>
        {t.d && <div className="tile-d">{t.d}</div>}
      </div>
    ))}
  </div>
);

const NextMatches = ({ onPick }) => (
  <div className="card">
    <div className="card-h">
      <div className="card-t">
        <div className="ico gold">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>
        </div>
        Próximas Partidas
      </div>
      <span className="card-sub">{MATCHES_FIFA.length} hoje</span>
    </div>
    <div>
      {MATCHES_FIFA.map(m => (
        <div className="match-row" key={m.id} onClick={() => onPick(m)}>
          <div className="match-time">{m.t}<small>BRT</small></div>
          <div className="match-info">
            <div className="match-players">
              <span>{m.home.handle}</span>
              <span className="vs">vs</span>
              <span>{m.away.handle}</span>
            </div>
            <div className="match-meta">
              <span>{m.league}</span>
              <span>EV <b>+{m.ev.toFixed(1)}%</b></span>
              <span>Conf {m.conf}%</span>
            </div>
          </div>
          <div className="match-cta">
            <button className="btn-mini gold">Gerar análise</button>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const HISTORY_PAGE_SIZE = 10;

const SignalQueue = () => {
  const [tab, setTab] = useS_D('queue'); // queue | history
  const [page, setPage] = useS_D(1);

  const greens = HISTORY_FIFA.filter(h => h.result === 'green').length;
  const reds   = HISTORY_FIFA.filter(h => h.result === 'red').length;

  const items = tab === 'queue' ? QUEUE_FIFA : HISTORY_FIFA;
  const totalPages = Math.max(1, Math.ceil(HISTORY_FIFA.length / HISTORY_PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const paged = tab === 'history'
    ? items.slice((safePage - 1) * HISTORY_PAGE_SIZE, safePage * HISTORY_PAGE_SIZE)
    : items;

  const switchTab = (t) => { setTab(t); setPage(1); };

  return (
    <div className="card">
      <div className="card-h">
        <div className="card-t">
          <div className="ico green">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M13 2 3 14h7l-1 8 10-12h-7l1-8z"/></svg>
          </div>
          Sinais
          <span className="chip ev">
            {tab === 'queue' ? `${QUEUE_FIFA.length} prontos` : `${greens}V · ${reds}D · ${HISTORY_FIFA.length} total`}
          </span>
        </div>
        <div className="seg">
          <button className={`seg-b ${tab === 'queue' ? 'on' : ''}`} onClick={() => switchTab('queue')}>Fila</button>
          <button className={`seg-b ${tab === 'history' ? 'on' : ''}`} onClick={() => switchTab('history')}>Histórico</button>
        </div>
      </div>
      <div>
        {paged.length === 0 && (
          <div style={{padding:'18px 14px', color:'var(--text-3)', fontSize:12}}>
            {tab === 'queue' ? 'sem sinais aguardando dispatch' : 'sem histórico no período'}
          </div>
        )}
        {paged.map(q => {
          const gameUrl = q.url || `${AFFIL.gameUrlBase}${q.matchId}`;
          return (
            <div className={`sq-row ${tab === 'history' ? 'sq-row-2' : ''}`} key={q.id}>
              <div className="sq-time">
                {q.kickoff}<small>BRT</small>
              </div>
              <div className="sq-info">
                <div className="sq-match">
                  {q.match}
                  {tab === 'history' && (
                    <span className={`sq-res sq-res-${q.result}`}>
                      {q.result === 'green' ? '✓' : q.result === 'red' ? '✗' : '∅'} {q.score}
                    </span>
                  )}
                </div>
                <div className="sq-pick">
                  {q.pick} @ <b>{q.odd}</b> · EV +{q.ev}%
                </div>
              </div>
              {tab === 'queue' && (
                <a className="sq-cta" href={gameUrl} target="_blank" rel="noreferrer" title="Ir para o jogo">
                  Ir →
                </a>
              )}
            </div>
          );
        })}
      </div>

      {tab === 'history' && totalPages > 1 && (
        <div className="sq-pager" style={{
          display:'flex', alignItems:'center', justifyContent:'space-between',
          padding:'10px 14px', borderTop:'1px solid var(--line, #1f1f28)',
          gap:8, flexWrap:'wrap'
        }}>
          <button className="seg-b" disabled={safePage <= 1} onClick={() => setPage(p => Math.max(1, p - 1))}>
            ← Anterior
          </button>
          <span style={{fontSize:11, color:'var(--text-3)', fontFamily:'var(--f-mono)'}}>
            página <b>{safePage}</b> / {totalPages} · {HISTORY_FIFA.length} sinais
          </span>
          <button className="seg-b" disabled={safePage >= totalPages} onClick={() => setPage(p => Math.min(totalPages, p + 1))}>
            Próximo →
          </button>
        </div>
      )}
    </div>
  );
};

const DEFAULT_LEAGUE_ID = 22614; // Battle 8min

const Performance = ({ onPickPlayer }) => {
  const [leagueId, setLeagueId] = useS_D(window.SF_LEAGUE_ID || DEFAULT_LEAGUE_ID);

  // garante que SF_LEAGUE_ID e dataset estão sincronizados na primeira render
  useE_D(() => {
    if (!window.SF_LEAGUE_ID) {
      window.SF_LEAGUE_ID = DEFAULT_LEAGUE_ID;
      if (window.loadAllData) window.loadAllData();
    }
  }, []);

  const switchLeague = (id) => {
    setLeagueId(id);
    window.SF_LEAGUE_ID = id;
    if (window.loadAllData) window.loadAllData();
  };

  const list = PERF_FIFA;

  return (
    <div className="card">
      <div className="card-h">
        <div className="card-t">
          <div className="ico">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-5"/></svg>
          </div>
          Performance dos Jogadores
        </div>
        <span className="card-sub">{list.length} jogadores</span>
      </div>

      {LEAGUES_FIFA.length > 0 && (
        <div className="seg" style={{margin:'8px 14px 4px', flexWrap:'wrap', gap:4}}>
          {LEAGUES_FIFA.map(l => (
            <button key={l.id}
                    className={`seg-b ${leagueId === l.id ? 'on' : ''}`}
                    onClick={() => switchLeague(l.id)}>
              {l.name} <small style={{opacity:.6, marginLeft:4}}>{l.matchCount}</small>
            </button>
          ))}
        </div>
      )}

      <div className="card-body">
        {list.length === 0 && (
          <div style={{padding:'16px 14px', color:'var(--text-3)', fontSize:12}}>
            sem jogadores com partidas registradas{leagueId ? ' nessa liga' : ''}
          </div>
        )}
        {list.map((p, i) => (
          <div className="perf-row perf-row-clickable" key={p.id || p.handle} onClick={() => onPickPlayer(p)}>
            <div className={`perf-rank ${i < 3 ? 'top' : ''}`}>{String(i+1).padStart(2,'0')}</div>
            <div>
              <div className="perf-name">
                {p.handle}
                <span style={{color:'var(--text-3)', fontWeight:500, fontSize:11, marginLeft:6, fontFamily:'var(--f-mono)'}}>{p.team}</span>
              </div>
              <div className="perf-bar"><i style={{width: `${p.bar || 0}%`}}/></div>
              <div className="perf-meta">
                {p.matches || p.games} jogos · ELO {p.elo || '—'}
                {p.roi ? <> · ROI {p.roi >= 0 ? '+' : ''}{p.roi}%</> : null}
              </div>
            </div>
            <div className="perf-wr">{p.wr}%</div>
          </div>
        ))}
      </div>
    </div>
  );
};

const Topbar = ({ email }) => {
  const [hidden, setHidden] = useS_D(false);

  useE_D(() => {
    let lastY = window.scrollY;
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const y = window.scrollY;
        const diff = y - lastY;
        if (y < 24) {
          setHidden(false);                 // sempre visível no topo
        } else if (diff > 8) {
          setHidden(true);                  // rolando pra baixo → esconde
        } else if (diff < -8) {
          setHidden(false);                 // rolando pra cima → mostra
        }
        lastY = y;
        ticking = false;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <div className={`topbar topbar-sticky${hidden ? ' topbar-hidden' : ''}`}>
      <div className="brand">
        <div className="brand-mark">FE</div>
        <div>
          <div className="brand-name">FIFA <span>EDGE</span></div>
          <div className="brand-sub">powered by {AFFIL.brand}</div>
        </div>
      </div>
    </div>
  );
};

const Dashboard = ({ user, onLogout }) => {
  const [picked, setPicked] = useS_D(null);
  const [pickedPlayer, setPickedPlayer] = useS_D(null);

  return (
    <div className="shell">
      {/* Premia Bet rewards banner */}
      <div className="afh-banner premia">
        <span className="pulse"/>
        <strong>Suas apostas valem prêmios.</strong>&nbsp;Acumule pontos a cada depósito e troque por PIX, eletrônicos e sorteios exclusivos →
        <a href="https://clube.premiabet.site/" target="_blank" rel="noreferrer">GANHAR PRÊMIOS</a>
      </div>

      {/* Topbar — ocultada ao rolar pra baixo */}
      <Topbar email={user.email} />


      {/* Main grid */}
      <div className="dash-main">
        {/* Left: GoldeBet iframe */}
        <div style={{display:'flex', flexDirection:'column', gap:14}}>
          <HouseFrame />
        </div>

        {/* Right: tools */}
        <div className="tools">
          <div className="card">
            <div className="card-h">
              <div className="card-t">
                <div className="ico gold">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M3 3h18v18H3z"/><path d="M3 9h18M9 21V9"/></svg>
                </div>
                Resumo do Dia
              </div>
              <span className="card-sub">19 ABR · ao vivo</span>
            </div>
            <TilesRow />
          </div>

          <NextMatches onPick={setPicked} />
          <SignalQueue />
          <Performance onPickPlayer={setPickedPlayer} />
        </div>
      </div>

      {/* Footer */}
      <div className="foot">
        <div className="age">JOGUE COM RESPONSABILIDADE</div>
        <div>
          FIFA EDGE é um sistema de sinais e ferramentas estatísticas para e-Soccer.
          Apostas envolvem risco · não há garantia de retorno.
        </div>
        <div>
          Conta vinculada a <a href={AFFIL.loginUrl} target="_blank" rel="noreferrer">{AFFIL.brand}</a> ·
          {' '}<a onClick={onLogout} style={{cursor:'pointer'}}>sair da sessão</a>
        </div>
      </div>

      {picked && <SignalModal match={picked} onClose={() => setPicked(null)} />}
      {pickedPlayer && <PlayerModal player={pickedPlayer} onClose={() => setPickedPlayer(null)} />}
    </div>
  );
};

window.Dashboard = Dashboard;
