/* ============================================================
   FIFA EDGE — views per section
   ============================================================ */

const { useState: useStateV, useMemo: useMemoV } = React;

/* ---------- TODAY view ---------- */
const TodayView = ({ showEv }) => {
  const [leagueFilter, setLeagueFilter] = useStateV('all');
  const [onlyEv, setOnlyEv] = useStateV(false);
  const filtered = MATCHES.filter(m => (onlyEv ? m.ev.pick !== null : true));
  const evSignals = MATCHES.filter(m => m.ev.pick);

  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">Painel de operação · Hoje</h1>
          <div className="page-sub">{new Date().toLocaleDateString('pt-BR', {day:'2-digit', month:'short', year:'numeric', timeZone:'America/Sao_Paulo'}).toUpperCase()} · e-Soccer Battle 8 · {MATCHES.length} partidas monitoradas</div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="filter" size={12} />Filtros</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi label="Bankroll" value={OVERVIEW.bankroll != null ? OVERVIEW.bankroll.toFixed(2) : '—'} unit="u" delta={OVERVIEW.roi_delta ?? 0} spark={ROI_14D} />
        <Kpi label="ROI 14d" value={OVERVIEW.roi_14d != null ? OVERVIEW.roi_14d.toFixed(1) : '—'} unit="%" delta={OVERVIEW.roi_delta ?? 0} spark={ROI_14D} />
        <Kpi label="Win rate" value={OVERVIEW.winrate != null ? OVERVIEW.winrate.toFixed(1) : '—'} unit="%" delta={0} spark={ROI_14D.map(v=>v*0.9)} />
        <Kpi label="EV+ médio" value={OVERVIEW.ev_plus_avg != null ? OVERVIEW.ev_plus_avg.toFixed(2) : '—'} unit={OVERVIEW.ev_plus_avg != null ? '%' : ''} delta={0} spark={ROI_14D.map(v=>v*0.7)} />
      </div>

      <div className="two-col">
        <div className="card">
          <div className="card-head">
            <div className="card-title">
              <span className="bar"></span>
              Próximas partidas
              <span className="badge">{filtered.length}</span>
            </div>
            <div className="card-tools">
              <button className={`tool-btn ${leagueFilter==='all'?'active':''}`} onClick={()=>setLeagueFilter('all')}>All</button>
              <button className={`tool-btn ${leagueFilter==='battle'?'active':''}`} onClick={()=>setLeagueFilter('battle')}>Battle 8</button>
              <button className={`tool-btn ${onlyEv?'active':''}`} onClick={()=>setOnlyEv(v=>!v)}>EV+ only</button>
            </div>
          </div>
          <div className="card-body flush">
            {filtered.map(m => <MatchRow key={m.id} m={m} showEv={showEv} />)}
          </div>
        </div>

        <div className="stack">
          <div className="card">
            <div className="card-head">
              <div className="card-title"><span className="bar"></span>Fila de sinais<span className="badge">{evSignals.length}</span></div>
              <div className="card-tools">
                <button className="tool-btn active">Queue</button>
                <button className="tool-btn">Sent</button>
              </div>
            </div>
            <div className="card-body flush">
              {evSignals.slice(0,4).map(m => <SignalQueueItem key={m.id} m={m} />)}
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title"><span className="bar"></span>Consistência · 70 últimos</div>
            </div>
            <div className="card-body">
              <Heat data={HEATMAP} />
              <div style={{display:'flex', justifyContent:'space-between', marginTop:10, fontFamily:'var(--f-mono)', fontSize:10, color:'var(--text-3)', letterSpacing:'0.08em', textTransform:'uppercase'}}>
                <span>há 14 dias</span>
                <span>hoje</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

/* ---------- LIVE view ---------- */
const LiveView = () => (
  <>
    <div className="page-head">
      <div>
        <h1 className="page-title">Partidas ao vivo</h1>
        <div className="page-sub">Tempo real · {LIVE.length} partidas em andamento</div>
      </div>
      <div className="page-actions">
        <button className="btn"><Icon name="refresh" size={12} />Auto-refresh: 3s</button>
      </div>
    </div>

    <div className="kpis">
      <Kpi label="Gols já marcados" value="7" />
      <Kpi label="Média min/gol" value="3.8" />
      <Kpi label="Over 2.5 batidos" value="2/3" />
      <Kpi label="Cobertura BTTS" value="2/3" />
    </div>

    <div className="card">
      <div className="card-head">
        <div className="card-title"><span className="bar"></span>Em andamento<span className="badge">Battle 8</span></div>
        <div className="card-tools">
          <button className="tool-btn active">Todas</button>
          <button className="tool-btn">C/ sinal</button>
          <button className="tool-btn">High EV</button>
        </div>
      </div>
      <div className="card-body flush">
        {LIVE.map(l => <LiveRow key={l.id} m={l} />)}
      </div>
    </div>

    <div style={{height: 14}} />

    <div className="grid-2">
      <div className="card">
        <div className="card-head"><div className="card-title"><span className="bar"></span>Feed de eventos</div></div>
        <div className="card-body" style={{fontFamily:'var(--f-mono)', fontSize:11.5, lineHeight:1.8, color:'var(--text-2)'}}>
          <div><span style={{color:'var(--loss)'}}>4'12" </span>GOAL · Leto09 {'>'} Drako · 2-1 · xG 0.41</div>
          <div><span style={{color:'var(--loss)'}}>4'03" </span>SHOT · Drako missed · target 0.6m wide</div>
          <div><span style={{color:'var(--loss)'}}>3'47" </span>CORNER · Leto09 · 5th of match</div>
          <div><span style={{color:'var(--loss)'}}>3'21" </span>GOAL · Drako {'>'} Leto09 · 1-1 · xG 0.28</div>
          <div><span style={{color:'var(--loss)'}}>2'54" </span>YELLOW · Drako</div>
          <div><span style={{color:'var(--loss)'}}>2'10" </span>GOAL · Leto09 · 1-0 · xG 0.52</div>
          <div><span style={{color:'var(--text-3)'}}>1'00" </span>KICKOFF</div>
        </div>
      </div>

      <div className="card">
        <div className="card-head"><div className="card-title"><span className="bar"></span>Mercado inplay · Leto09 vs Drako</div></div>
        <div className="card-body">
          <div style={{display:'grid', gridTemplateColumns:'1fr auto auto auto', gap:8, fontSize:12}}>
            {[
              ['Next goal · Leto09', 1.78, 1.65, '-8%'],
              ['Next goal · Drako',  2.90, 3.10, '+7%'],
              ['Over 3.5 FT',        1.52, 1.42, '-7%'],
              ['BTTS FT',            1.35, 1.30, '-4%'],
              ['Leto09 -1.5 AH',     2.15, 2.05, '-5%'],
            ].map((r,i)=>(
              <React.Fragment key={i}>
                <span style={{color:'var(--text-1)'}}>{r[0]}</span>
                <span className="mono" style={{color:'var(--text-3)'}}>{r[1].toFixed(2)}</span>
                <span className="mono" style={{color:'var(--text-0)'}}>{r[2].toFixed(2)}</span>
                <span className="mono" style={{color: r[3].startsWith('+') ? 'var(--win)' : 'var(--loss)'}}>{r[3]}</span>
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>
    </div>
  </>
);

/* ---------- SIGNALS view ---------- */
const SignalsView = () => {
  const [filter, setFilter] = useStateV('all');
  const rows = SIGNALS.filter(s => filter==='all' ? true : s.result===filter);
  const totals = SIGNALS.reduce((a, s) => {
    a.pnl += s.pnl; a[s.result] = (a[s.result]||0)+1; return a;
  }, { pnl: 0 });

  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">Sinais enviados</h1>
          <div className="page-sub">Auditoria completa · {SIGNALS.length} sinais nas últimas 24h</div>
        </div>
        <div className="page-actions">
          <button className="btn">Exportar CSV</button>
          <button className="btn primary"><Icon name="telegram" size={12} />Abrir canal</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi label="PnL 24h" value={`${totals.pnl >= 0 ? '+':''}${totals.pnl.toFixed(2)}`} unit="u" delta={+12.3} spark={ROI_14D} />
        <Kpi label="Win"  value={totals.win || 0} />
        <Kpi label="Loss" value={totals.loss || 0} />
        <Kpi label="Void" value={totals.void || 0} />
      </div>

      <div className="card">
        <div className="filters">
          <span className="lbl">Resultado</span>
          <button className={`chip ${filter==='all'?'active':''}`} onClick={()=>setFilter('all')}>Todos</button>
          <button className={`chip ${filter==='win'?'active':''}`} onClick={()=>setFilter('win')}><span className="dot" style={{background:'var(--win)'}}/>Win</button>
          <button className={`chip ${filter==='loss'?'active':''}`} onClick={()=>setFilter('loss')}><span className="dot" style={{background:'var(--loss)'}}/>Loss</button>
          <button className={`chip ${filter==='void'?'active':''}`} onClick={()=>setFilter('void')}><span className="dot" style={{background:'var(--text-3)'}}/>Void</button>
          <span className="sep"></span>
          <span className="lbl">Período</span>
          <select className="select"><option>Últimas 24h</option><option>Última semana</option><option>Mês</option></select>
          <span className="sep"></span>
          <span className="lbl">Mercado</span>
          <select className="select"><option>Todos</option><option>1X2</option><option>O/U 2.5</option><option>BTTS</option></select>
        </div>
        <table className="table">
          <thead>
            <tr>
              <th>#</th><th>Hora</th><th>Partida</th><th>Pick</th>
              <th className="num">Odd</th><th className="num">Stake</th>
              <th className="num">EV</th><th className="num">Conf</th>
              <th>Resultado</th><th className="num">PnL</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(s => (
              <tr key={s.id}>
                <td className="mono" style={{color:'var(--text-3)'}}>{s.id.slice(1)}</td>
                <td className="mono">{window.fmtHM(s.ts)}</td>
                <td>{s.match}</td>
                <td><span className="mono" style={{color:'var(--accent)', background:'var(--accent-bg)', padding:'2px 6px', borderRadius:3, border:'1px solid var(--accent-bd)'}}>{s.pick}</span></td>
                <td className="num">{s.odd.toFixed(2)}</td>
                <td className="num">{s.stake.toFixed(1)}u</td>
                <td className="num" style={{color:'var(--win)'}}>+{s.ev.toFixed(1)}%</td>
                <td className="num">{s.conf}%</td>
                <td>
                  {s.result==='win'  && <span className="mono" style={{color:'var(--win)', fontWeight:600}}>● WIN</span>}
                  {s.result==='loss' && <span className="mono" style={{color:'var(--loss)', fontWeight:600}}>● LOSS</span>}
                  {s.result==='void' && <span className="mono" style={{color:'var(--text-3)', fontWeight:600}}>● VOID</span>}
                </td>
                <td className="num mono" style={{color: s.pnl > 0 ? 'var(--win)' : s.pnl < 0 ? 'var(--loss)' : 'var(--text-3)', fontWeight: 600}}>
                  {s.pnl > 0 ? '+':''}{s.pnl.toFixed(2)}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
};

/* ---------- LEADERBOARD view ---------- */
const EloView = () => (
  <>
    <div className="page-head">
      <div>
        <h1 className="page-title">Leaderboard ELO</h1>
        <div className="page-sub">Rating temporal · {PLAYERS.length} pro-players · atualizado após cada match</div>
      </div>
      <div className="page-actions">
        <button className="btn"><Icon name="filter" size={12} />Liga: Battle 8</button>
      </div>
    </div>

    <div className="kpis">
      <Kpi label="Top ELO" value={PLAYERS[0].elo} delta={+1.0} />
      <Kpi label="ELO médio" value={Math.round(PLAYERS.reduce((a,p)=>a+p.elo,0)/PLAYERS.length)} />
      <Kpi label="Sessões hoje" value="187" delta={+8.4} />
      <Kpi label="K-factor" value="32" />
    </div>

    <div className="card">
      <table className="table">
        <thead>
          <tr>
            <th>#</th><th>Player</th><th>Time base</th>
            <th className="num">ELO</th><th className="num">Δ 24h</th>
            <th className="num">Jogos</th><th className="num">WR</th>
            <th>Forma (últ. 10)</th>
          </tr>
        </thead>
        <tbody>
          {PLAYERS.map((p, i) => (
            <tr key={p.id}>
              <td><span className={`rank ${i<3?'top':''}`}>{String(i+1).padStart(2,'0')}</span></td>
              <td>
                <div style={{display:'flex', alignItems:'center', gap:10}}>
                  <div style={{width:28, height:28, borderRadius:4, background:'var(--bg-3)', display:'grid', placeItems:'center', fontFamily:'var(--f-mono)', fontSize:11, color:'var(--text-0)', fontWeight:600, border:'1px solid var(--line-1)'}}>{p.handle.slice(0,2).toUpperCase()}</div>
                  <span style={{color:'var(--text-0)', fontWeight:500}}>{p.handle}</span>
                </div>
              </td>
              <td style={{color:'var(--text-2)'}}>{p.team}</td>
              <td className="num elo">{p.elo}</td>
              <td className="num"><span className={`elo ${p.delta<0?'d neg':'d'}`} style={{color: p.delta>=0?'var(--win)':'var(--loss)'}}>{p.delta>=0?'+':''}{p.delta}</span></td>
              <td className="num mono" style={{color:'var(--text-2)'}}>{p.games}</td>
              <td className="num mono">{(p.wr*100).toFixed(1)}%</td>
              <td><FormDots form={p.form} /></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </>
);

/* ---------- STATS view (full table with many filters) ---------- */
const ALL_LEAGUES = ['Todas as ligas','Battle 8','H2H GG','Volta','GT League'];
const TEAMS = ['Todos os times','Real Madrid','Man City','Bayern','PSG','Barcelona','Liverpool','Atlético MG','Inter','Dortmund','Chelsea','Juventus','Arsenal'];

const StatsView = () => {
  const [tipo, setTipo] = useStateV('jogadores'); // jogadores | partidas | times
  const [tempo, setTempo] = useStateV('ambos');   // 1t | 2t | ambos
  const [cantos, setCantos] = useStateV('com');   // com | sem
  const [periodo, setPeriodo] = useStateV('hoje');
  const [historico, setHistorico] = useStateV('completo');
  const [league, setLeague] = useStateV('Todas as ligas');
  const [team, setTeam]   = useStateV('Todos os times');
  const [minJogos, setMinJogos] = useStateV(5);
  const [overs, setOvers] = useStateV(70);
  const [exibicao, setExibicao] = useStateV(20);
  const [search, setSearch] = useStateV('');
  const [sort, setSort] = useStateV({ col:'elo', dir:'desc' });

  const rows = useMemoV(() => {
    let data = PLAYERS.map(p => {
      const w = Math.round(p.games*p.wr);
      const l = Math.round(p.games*(1-p.wr)*0.7);
      const d = p.games - w - l;
      const gf = Math.round(p.games * (1.6 + (p.elo-1700)/250));
      const ga = Math.round(p.games * (1.3 - (p.elo-1700)/400));
      const saldo = gf - ga;
      const wr = Math.round(p.wr*1000)/10;
      const o25 = Math.round(60 + (p.elo-1700)/5);
      const o35 = Math.round(40 + (p.elo-1700)/6);
      const btts = Math.round(55 + (p.elo-1700)/8);
      const cs = Math.round(18 + (p.elo-1700)/12);
      const avgGF = (gf / p.games).toFixed(2);
      const avgGA = (ga / p.games).toFixed(2);
      const noGoal = Math.round(8 + (1800-p.elo)/20);
      const comeback = Math.round(5 + (p.elo-1700)/30);
      return { ...p, w, l, d, gf, ga, saldo, wr, o25, o35, btts, cs, avgGF, avgGA, noGoal, comeback };
    });
    if (search) data = data.filter(r => r.handle.toLowerCase().includes(search.toLowerCase()) || r.team.toLowerCase().includes(search.toLowerCase()));
    if (team !== 'Todos os times') data = data.filter(r => r.team === team);
    data = data.filter(r => r.games >= minJogos);
    data = data.filter(r => r.o25 >= overs - 30);
    data.sort((a,b) => {
      const av = a[sort.col], bv = b[sort.col];
      const n = typeof av === 'number' ? av - bv : String(av).localeCompare(String(bv));
      return sort.dir === 'asc' ? n : -n;
    });
    return data.slice(0, exibicao);
  }, [search, team, minJogos, overs, exibicao, sort, tipo, tempo, cantos, periodo, historico, league]);

  const toggleSort = (c) => setSort(s => ({ col: c, dir: s.col===c && s.dir==='desc' ? 'asc' : 'desc' }));
  const th = (id, label, num) => (
    <th className={num?'num':''} onClick={()=>toggleSort(id)}>
      <span style={{display:'inline-flex', alignItems:'center', gap:4}}>
        {label}
        {sort.col===id && <span style={{color:'var(--accent)', fontSize:9}}>{sort.dir==='desc'?'▼':'▲'}</span>}
      </span>
    </th>
  );

  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">e-Soccer · Tabela de estatísticas</h1>
          <div className="page-sub">Estatísticas de jogadores · filtros avançados · Battle 8 + outras ligas</div>
        </div>
        <div className="page-actions">
          <button className="btn">Exportar CSV</button>
          <button className="btn primary">Salvar visão</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi label="Jogadores" value={PLAYERS.length} />
        <Kpi label="Visíveis após filtros" value={rows.length} />
        <Kpi label="Partidas analisadas" value={PLAYERS.reduce((a,p)=>a+p.games,0).toLocaleString()} delta={+5.2} />
        <Kpi label="Cobertura temporal" value="90d" />
      </div>

      {/* --- Filter block (mirrors the reference structure with original styling) --- */}
      <div className="card" style={{marginBottom: 14}}>
        <div className="card-head">
          <div className="card-title"><span className="bar"></span>Filtros</div>
          <div className="card-tools">
            <button className="tool-btn" onClick={()=>{ setTeam('Todos os times'); setLeague('Todas as ligas'); setMinJogos(5); setOvers(70); setExibicao(20); setSearch(''); }}>Reset</button>
          </div>
        </div>
        <div className="card-body" style={{padding:16}}>
          {/* Row 1 — big segmented groups */}
          <div className="stats-filter-row">
            <div className="field">
              <label>Tipo de dados</label>
              <div className="seg4">
                {['jogadores','partidas','times'].map(t => (
                  <button key={t} className={tipo===t?'active':''} onClick={()=>setTipo(t)}>{t==='jogadores'?'Jogadores':t==='partidas'?'Partidas':'Times'}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Modo de tempo</label>
              <div className="seg4">
                {[['1t','1º tempo'],['2t','2º tempo'],['ambos','Ambos os tempos']].map(([v,l]) => (
                  <button key={v} className={tempo===v?'active':''} onClick={()=>setTempo(v)}>{l}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Escanteios</label>
              <div className="seg4">
                {[['com','Com cantos'],['sem','Sem cantos']].map(([v,l]) => (
                  <button key={v} className={cantos===v?'active':''} onClick={()=>setCantos(v)}>{l}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Período</label>
              <div className="seg4">
                {[['hoje','Hoje'],['7d','7 dias'],['30d','30 dias']].map(([v,l]) => (
                  <button key={v} className={periodo===v?'active':''} onClick={()=>setPeriodo(v)}>{l}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>Histórico</label>
              <select className="select" value={historico} onChange={e=>setHistorico(e.target.value)}>
                <option value="completo">Histórico completo</option>
                <option value="semana">Última semana</option>
                <option value="mes">Último mês</option>
              </select>
            </div>
          </div>

          {/* Row 2 — inputs */}
          <div className="stats-filter-row" style={{marginTop: 14}}>
            <div className="field">
              <label>Buscar jogador</label>
              <div className="search-inline">
                <Icon name="search" size={13} />
                <input placeholder="Nome do player…" value={search} onChange={e=>setSearch(e.target.value)} />
              </div>
            </div>
            <div className="field">
              <label>Time da FIFA</label>
              <select className="select" value={team} onChange={e=>setTeam(e.target.value)}>
                {TEAMS.map(t => <option key={t}>{t}</option>)}
              </select>
            </div>
            <div className="field">
              <label>Liga</label>
              <select className="select" value={league} onChange={e=>setLeague(e.target.value)}>
                {ALL_LEAGUES.map(l => <option key={l}>{l}</option>)}
              </select>
            </div>
            <div className="field">
              <label>Mín. jogos <span className="mono v">{minJogos}</span></label>
              <input type="range" min="1" max="50" value={minJogos} onChange={e=>setMinJogos(+e.target.value)} />
            </div>
            <div className="field">
              <label>Overs % (mín) <span className="mono v">{overs}%</span></label>
              <input type="range" min="30" max="95" value={overs} onChange={e=>setOvers(+e.target.value)} />
            </div>
            <div className="field">
              <label>Exibição máxima</label>
              <select className="select" value={exibicao} onChange={e=>setExibicao(+e.target.value)}>
                <option value="10">10 jogadores</option>
                <option value="20">20 jogadores</option>
                <option value="50">50 jogadores</option>
                <option value="100">100 jogadores</option>
              </select>
            </div>
          </div>

          <div style={{marginTop:14, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div className="chips-row">
              <span className="chip active"><span className="dot"/>Filtros aplicados</span>
              {team !== 'Todos os times' && <span className="chip">Time: {team} ×</span>}
              {league !== 'Todas as ligas' && <span className="chip">Liga: {league} ×</span>}
              <span className="chip">Mín. jogos ≥ {minJogos}</span>
              <span className="chip">Overs ≥ {overs}%</span>
              <span className="chip">{tempo === '1t' ? '1º T' : tempo === '2t' ? '2º T' : 'Ambos T'}</span>
            </div>
            <button className="btn primary">Aplicar filtros</button>
          </div>
        </div>
      </div>

      {/* --- Data table with sticky cols --- */}
      <div className="card">
        <div className="card-head">
          <div className="card-title"><span className="bar"></span>Estatísticas · {rows.length} resultados</div>
          <div className="card-tools">
            <button className="tool-btn active">Densa</button>
            <button className="tool-btn">Padrão</button>
          </div>
        </div>
        <div className="scrollx">
          <table className="table stats-table">
            <thead>
              <tr>
                {th('handle','Player')}
                {th('team','Time')}
                {th('elo','ELO', true)}
                {th('games','Jogos', true)}
                <th className="num">W-D-L</th>
                {th('gf','Gols +', true)}
                {th('ga','Gols -', true)}
                {th('saldo','Saldo', true)}
                {th('wr','WR %', true)}
                {th('o25','Over 2.5 %', true)}
                {th('o35','Over 3.5 %', true)}
                {th('btts','BTTS %', true)}
                {th('avgGF','Avg GF', true)}
                {th('avgGA','Avg GA', true)}
                {th('cs','Clean sheet %', true)}
                {th('noGoal','Sem gols %', true)}
                {th('comeback','Comeback', true)}
              </tr>
            </thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.id}>
                  <td className="sticky-col">
                    <div style={{display:'flex', alignItems:'center', gap:10}}>
                      <div className="avatar-sq">{r.handle.slice(0,2).toUpperCase()}</div>
                      <span style={{color:'var(--text-0)', fontWeight:500}}>{r.handle}</span>
                    </div>
                  </td>
                  <td style={{color:'var(--text-2)'}}>{r.team}</td>
                  <td className="num elo">{r.elo}</td>
                  <td className="num">{r.games}</td>
                  <td className="num mono">
                    <span style={{color:'var(--win)'}}>{r.w}</span>
                    <span style={{color:'var(--text-3)', margin:'0 3px'}}>-</span>
                    <span style={{color:'var(--text-2)'}}>{r.d}</span>
                    <span style={{color:'var(--text-3)', margin:'0 3px'}}>-</span>
                    <span style={{color:'var(--loss)'}}>{r.l}</span>
                  </td>
                  <td className="num mono">{r.gf}</td>
                  <td className="num mono" style={{color:'var(--text-3)'}}>{r.ga}</td>
                  <td className="num mono" style={{color: r.saldo>=0?'var(--win)':'var(--loss)', fontWeight:600}}>{r.saldo>=0?'+':''}{r.saldo}</td>
                  <td className="num mono"><HeatCell v={r.wr/100} label={`${r.wr}%`} /></td>
                  <td className="num mono"><HeatCell v={r.o25/100} label={`${r.o25}%`} /></td>
                  <td className="num mono"><HeatCell v={r.o35/100} label={`${r.o35}%`} /></td>
                  <td className="num mono"><HeatCell v={r.btts/100} label={`${r.btts}%`} /></td>
                  <td className="num mono">{r.avgGF}</td>
                  <td className="num mono" style={{color:'var(--text-3)'}}>{r.avgGA}</td>
                  <td className="num mono">{r.cs}%</td>
                  <td className="num mono" style={{color:'var(--text-3)'}}>{r.noGoal}%</td>
                  <td className="num mono" style={{color:'var(--warn)'}}>{r.comeback}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="table-foot">
          <span className="mono" style={{color:'var(--text-3)', fontSize:11}}>Exibindo 1–{rows.length} de {PLAYERS.length}</span>
          <div style={{display:'flex', gap:4}}>
            <button className="btn" disabled>‹ Anterior</button>
            <button className="btn">Próxima ›</button>
          </div>
        </div>
      </div>
    </>
  );
};

/* heat cell for numeric % values in the stats table */
const HeatCell = ({ v, label }) => {
  const lvl = v >= 0.70 ? 4 : v >= 0.60 ? 3 : v >= 0.50 ? 2 : v >= 0.40 ? 1 : 0;
  const colors = ['transparent', 'oklch(0.78 0.16 155 / 0.10)', 'oklch(0.78 0.16 155 / 0.20)', 'oklch(0.78 0.16 155 / 0.35)', 'oklch(0.78 0.16 155 / 0.55)'];
  const fg = lvl >= 3 ? 'var(--accent)' : 'var(--text-1)';
  return (
    <span style={{
      display:'inline-block', minWidth: 48, padding:'2px 6px', borderRadius:3,
      background: colors[lvl], color: fg, fontWeight: lvl >= 3 ? 600 : 400, textAlign:'right'
    }}>{label}</span>
  );
};

/* ---------- PERFORMANCE view ---------- */
const PerfView = () => {
  const months = ['J','F','M','A','M','J','J','A','S','O','N','D'];
  const monthly = [2.1, 4.8, 6.2, 8.9, 11.4, 9.8, 13.2, 14.6, 12.1, 15.8, 17.9, 17.4];
  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">Performance do bot</h1>
          <div className="page-sub">ROI acumulado · drawdown · distribuição por mercado</div>
        </div>
        <div className="page-actions">
          <button className="btn">Ano</button>
          <button className="btn primary">YTD</button>
        </div>
      </div>

      <div className="kpis">
        <Kpi label="ROI YTD"        value="+124.6" unit="%" delta={+17.4} spark={monthly} />
        <Kpi label="Sinais enviados" value="2,847" delta={+5.2} spark={ROI_14D} />
        <Kpi label="Max drawdown"    value="-8.4"  unit="%" delta={-1.2} sparkColor="var(--loss)" spark={ROI_14D.map(v=>-v*0.3)} />
        <Kpi label="Sharpe (sim.)"   value="2.14"           delta={+0.14} spark={ROI_14D} />
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>ROI mensal · 12 meses</div></div>
          <div className="card-body">
            <div style={{display:'grid', gridTemplateColumns:'repeat(12,1fr)', gap:6, alignItems:'end', height:180}}>
              {monthly.map((v,i) => (
                <div key={i} style={{display:'flex', flexDirection:'column', alignItems:'center', gap:6, height:'100%'}}>
                  <div style={{flex:1, width:'100%', display:'flex', alignItems:'flex-end'}}>
                    <div style={{width:'100%', height:`${(v/20)*100}%`, background:'var(--accent)', opacity: i===11 ? 1 : 0.5, borderRadius:'2px 2px 0 0'}}></div>
                  </div>
                  <span className="mono" style={{fontSize:10, color:'var(--text-3)'}}>{months[i]}</span>
                </div>
              ))}
            </div>
            <div style={{display:'flex', gap:14, marginTop:16, fontFamily:'var(--f-mono)', fontSize:11, color:'var(--text-3)'}}>
              <span>● <span style={{color:'var(--text-1)'}}>Melhor mês: Nov +17.9%</span></span>
              <span>● <span style={{color:'var(--text-1)'}}>Pior mês: Jan +2.1%</span></span>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>Distribuição por mercado</div></div>
          <div className="card-body">
            {[
              ['1X2 · Home',    42, '+14.2%'],
              ['1X2 · Away',    18, '+8.6%'],
              ['Draw',           4, '-2.1%'],
              ['Over 2.5',      21, '+18.4%'],
              ['Under 2.5',      5, '+3.2%'],
              ['BTTS',          10, '+11.8%'],
            ].map((r,i) => (
              <div key={i} style={{display:'grid', gridTemplateColumns:'120px 1fr 60px 60px', gap:10, alignItems:'center', padding:'8px 0', borderBottom:'1px solid var(--line-1)'}}>
                <span style={{fontSize:12, color:'var(--text-1)'}}>{r[0]}</span>
                <div style={{height:6, background:'var(--bg-3)', borderRadius:3, overflow:'hidden'}}>
                  <div style={{width:`${r[1]*2}%`, height:'100%', background:'var(--accent)', opacity:0.6}}></div>
                </div>
                <span className="mono" style={{fontSize:11, color:'var(--text-3)', textAlign:'right'}}>{r[1]}%</span>
                <span className="mono" style={{fontSize:11, color: r[2].startsWith('+')?'var(--win)':'var(--loss)', textAlign:'right'}}>{r[2]}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

/* ---------- SETTINGS view ---------- */
const SettingsView = () => {
  const [cfg, setCfg] = useStateV({
    botToken: '',
    chatId: '-100',
    affiliateBase: 'https://stake.com/?c=',
    channelName: 'FIFA EDGE · VIP',
    msgTemplate: '🎯 {pick} @ {odd}\n\n{home} vs {away}\n{league} · {kickoff}\n\nEV {ev}% · Conf {conf}%\nStake: {stake}u\n\n🔗 Stake: {aff}',
    testResult: null,
  });

  const set = (k, v) => setCfg(c => ({...c, [k]: v}));

  const validateToken = (t) => /^\d{8,10}:[A-Za-z0-9_-]{30,}$/.test(t);
  const validateChat  = (c) => /^-?\d{5,}$/.test(c);
  const validateUrl   = (u) => /^https?:\/\/.+/.test(u);

  const ready = validateToken(cfg.botToken) && validateChat(cfg.chatId) && validateUrl(cfg.affiliateBase);

  const runTest = () => {
    if (!ready) { set('testResult', {ok:false, msg:'Preencha token, chat_id e URL válidos antes de testar.'}); return; }
    set('testResult', {ok:true, msg:`Mensagem de teste enviada para ${cfg.chatId} via bot ****${cfg.botToken.slice(-6)}.`});
  };

  return (
    <>
      <div className="page-head">
        <div>
          <h1 className="page-title">Configurações</h1>
          <div className="page-sub">Engine · fontes · disparo Telegram · multi-tenant</div>
        </div>
        <div className="page-actions">
          <button className="btn">Cancelar</button>
          <button className="btn primary" disabled={!ready}>Salvar alterações</button>
        </div>
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>Engine</div></div>
          <div className="card-body">
            {[
              ['K-factor ELO', '32'],
              ['Momentum lookback', '10 jogos'],
              ['EV mínimo', '+5.0%'],
              ['Confiança mínima', '70%'],
              ['Stake base', '2.0u (Kelly ¼)'],
              ['Dispatch offset', 'T-15min'],
            ].map((r,i) => (
              <div key={i} style={{display:'grid', gridTemplateColumns:'1fr auto', padding:'10px 0', borderBottom:'1px solid var(--line-1)', alignItems:'center'}}>
                <span style={{fontSize:12, color:'var(--text-1)'}}>{r[0]}</span>
                <span className="mono" style={{fontSize:12, color:'var(--text-0)', background:'var(--bg-2)', border:'1px solid var(--line-1)', padding:'4px 10px', borderRadius:4}}>{r[1]}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>Fontes</div></div>
          <div className="card-body">
            {[
              ['BetsAPI · schedule', 'OK · 03:00 UTC diário'],
              ['BetsAPI · results', 'OK · a cada 30min'],
              ['Odds · RapidAPI', 'DEGRADED · sem campo markets'],
              ['Scheduler', 'OK · last tick 12s'],
              ['SQLite WAL', 'OK · 14.2 MB'],
            ].map((r,i) => {
              const warn = r[1].includes('DEGRADED');
              return (
                <div key={i} style={{display:'grid', gridTemplateColumns:'1fr auto', padding:'10px 0', borderBottom:'1px solid var(--line-1)', alignItems:'center'}}>
                  <span style={{fontSize:12, color:'var(--text-1)'}}>{r[0]}</span>
                  <span className="mono" style={{fontSize:11, color: warn?'var(--warn)':'var(--win)'}}>● {r[1]}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{height:14}}/>

      {/* ===== Disparo — multi-tenant Telegram ===== */}
      <div className="card">
        <div className="card-head">
          <div className="card-title"><span className="bar"></span>Disparo · Telegram<span className="badge">multi-tenant</span></div>
          <div className="card-tools">
            <span className="mono" style={{fontSize:10, color:'var(--text-3)', letterSpacing:'0.1em', textTransform:'uppercase'}}>
              {ready ? <span style={{color:'var(--win)'}}>● PRONTO</span> : <span style={{color:'var(--warn)'}}>● INCOMPLETO</span>}
            </span>
          </div>
        </div>
        <div className="card-body">
          <div style={{color:'var(--text-2)', fontSize:12, marginBottom:16, lineHeight:1.6}}>
            Configure as credenciais do seu bot do Telegram e o link de afiliado Stake. Cada operador pode ter seu próprio canal e link — o sistema envia os sinais usando essas credenciais isoladas.
          </div>

          <div className="stats-filter-row">
            <div className="field">
              <label>Bot token <span className="mono v" style={{color: validateToken(cfg.botToken)?'var(--win)':'var(--text-3)'}}>{validateToken(cfg.botToken)?'● válido':'● token'}</span></label>
              <div className="search-inline" style={{borderColor: cfg.botToken && !validateToken(cfg.botToken) ? 'var(--loss)' : 'var(--line-1)'}}>
                <Icon name="telegram" size={13}/>
                <input
                  placeholder="123456789:ABCdefGhIjKlMnOpQrStUvWxYz_1234567"
                  value={cfg.botToken}
                  onChange={e=>set('botToken', e.target.value)}
                  style={{fontFamily:'var(--f-mono)', fontSize:11.5}}
                />
              </div>
              <span style={{fontSize:10.5, color:'var(--text-3)', fontFamily:'var(--f-mono)', marginTop:2}}>Gere com @BotFather no Telegram</span>
            </div>

            <div className="field">
              <label>Chat ID / Grupo <span className="mono v" style={{color: validateChat(cfg.chatId)?'var(--win)':'var(--text-3)'}}>{validateChat(cfg.chatId)?'● válido':'● id'}</span></label>
              <div className="search-inline" style={{borderColor: cfg.chatId && !validateChat(cfg.chatId) ? 'var(--loss)' : 'var(--line-1)'}}>
                <Icon name="signals" size={13}/>
                <input
                  placeholder="-1001234567890"
                  value={cfg.chatId}
                  onChange={e=>set('chatId', e.target.value)}
                  style={{fontFamily:'var(--f-mono)', fontSize:11.5}}
                />
              </div>
              <span style={{fontSize:10.5, color:'var(--text-3)', fontFamily:'var(--f-mono)', marginTop:2}}>Grupos começam com -100. Use @getidsbot</span>
            </div>

            <div className="field">
              <label>Base URL afiliado Stake <span className="mono v" style={{color: validateUrl(cfg.affiliateBase)?'var(--win)':'var(--text-3)'}}>{validateUrl(cfg.affiliateBase)?'● válido':'● url'}</span></label>
              <div className="search-inline" style={{borderColor: cfg.affiliateBase && !validateUrl(cfg.affiliateBase) ? 'var(--loss)' : 'var(--line-1)'}}>
                <Icon name="perf" size={13}/>
                <input
                  placeholder="https://stake.com/?c=SEUCODIGO"
                  value={cfg.affiliateBase}
                  onChange={e=>set('affiliateBase', e.target.value)}
                  style={{fontFamily:'var(--f-mono)', fontSize:11.5}}
                />
              </div>
              <span style={{fontSize:10.5, color:'var(--text-3)', fontFamily:'var(--f-mono)', marginTop:2}}>Usado no placeholder {'{aff}'} do template</span>
            </div>
          </div>

          <div className="stats-filter-row" style={{marginTop:14}}>
            <div className="field">
              <label>Nome do canal (display)</label>
              <div className="search-inline">
                <Icon name="trophy" size={13}/>
                <input value={cfg.channelName} onChange={e=>set('channelName', e.target.value)} />
              </div>
            </div>
            <div className="field" style={{gridColumn:'span 2'}}>
              <label>Template da mensagem <span className="mono v">placeholders: {'{pick} {odd} {home} {away} {league} {kickoff} {ev} {conf} {stake} {aff}'}</span></label>
              <textarea
                value={cfg.msgTemplate}
                onChange={e=>set('msgTemplate', e.target.value)}
                rows={7}
                style={{
                  background:'var(--bg-2)',
                  border:'1px solid var(--line-1)',
                  borderRadius:'var(--r-sm)',
                  color:'var(--text-1)',
                  padding:'10px 12px',
                  fontFamily:'var(--f-mono)',
                  fontSize:11.5,
                  resize:'vertical',
                  outline:'none',
                  lineHeight:1.55,
                }}
              />
            </div>
          </div>

          {cfg.testResult && (
            <div className="alert" style={{marginTop:16, borderColor: cfg.testResult.ok ? 'oklch(0.78 0.16 155 / 0.35)' : 'oklch(0.66 0.19 25 / 0.35)', background: cfg.testResult.ok ? 'oklch(0.78 0.16 155 / 0.08)' : 'oklch(0.66 0.19 25 / 0.08)'}}>
              <div className="i" style={{background: cfg.testResult.ok ? 'oklch(0.78 0.16 155 / 0.18)' : 'oklch(0.66 0.19 25 / 0.18)', color: cfg.testResult.ok ? 'var(--win)' : 'var(--loss)'}}>
                <Icon name={cfg.testResult.ok?'signals':'bell'} size={14}/>
              </div>
              <div>
                <div className="t">{cfg.testResult.ok?'Teste enviado':'Falha no teste'}</div>
                <div className="d">{cfg.testResult.msg}</div>
              </div>
              <button className="btn ghost" onClick={()=>set('testResult', null)}>×</button>
            </div>
          )}

          <div style={{display:'flex', gap:8, marginTop:16, justifyContent:'flex-end'}}>
            <button className="btn" onClick={runTest}>Enviar teste</button>
            <button className="btn" onClick={()=>setCfg({botToken:'', chatId:'-100', affiliateBase:'https://stake.com/?c=', channelName:'FIFA EDGE · VIP', msgTemplate: cfg.msgTemplate, testResult: null})}>Limpar</button>
            <button className="btn primary" disabled={!ready}><Icon name="telegram" size={12}/>Salvar disparo</button>
          </div>
        </div>
      </div>

      <div style={{height:14}}/>

      {/* Preview do Telegram */}
      <div className="grid-2">
        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>Pré-visualização</div></div>
          <div className="card-body">
            <div style={{background:'#17212b', borderRadius:8, padding:16, maxWidth:420, margin:'0 auto', boxShadow:'0 4px 14px rgba(0,0,0,0.3)'}}>
              <div style={{display:'flex', alignItems:'center', gap:10, paddingBottom:10, borderBottom:'1px solid rgba(255,255,255,0.08)'}}>
                <div style={{width:36, height:36, borderRadius:'50%', background:'var(--accent)', display:'grid', placeItems:'center', fontFamily:'var(--f-mono)', color:'var(--bg-0)', fontWeight:700, fontSize:13}}>FE</div>
                <div>
                  <div style={{color:'#fff', fontSize:13, fontWeight:600}}>{cfg.channelName || 'Canal sem nome'}</div>
                  <div style={{color:'#8996a5', fontSize:11, fontFamily:'var(--f-mono)'}}>{cfg.chatId || '—'}</div>
                </div>
              </div>
              <div style={{
                marginTop:12, padding:'12px 14px', background:'#2b5278', borderRadius:8, color:'#fff',
                fontSize:12.5, lineHeight:1.55, whiteSpace:'pre-wrap', fontFamily:'var(--f-ui)'
              }}>
                {cfg.msgTemplate
                  .replace('{pick}', '1')
                  .replace('{odd}', '1.72')
                  .replace('{home}', 'Hawk_13')
                  .replace('{away}', 'Orbit')
                  .replace('{league}', 'Battle 8')
                  .replace('{kickoff}', '18:06 UTC')
                  .replace('{ev}', '+8.4')
                  .replace('{conf}', '74')
                  .replace('{stake}', '2.0')
                  .replace('{aff}', (cfg.affiliateBase || 'https://stake.com/?c=XXX') + 'FIFAEDGE')}
              </div>
              <div style={{textAlign:'right', marginTop:6, color:'#8996a5', fontSize:10, fontFamily:'var(--f-mono)'}}>18:06 ✓✓</div>
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><div className="card-title"><span className="bar"></span>Operadores cadastrados<span className="badge">multi-tenant</span></div></div>
          <div className="card-body flush">
            {[
              { op:'admin@fifaedge',    channel:'FIFA EDGE · VIP',  subs:847, status:'active' },
              { op:'tipster.br',        channel:'TipsterBR Pro',    subs:412, status:'active' },
              { op:'carlos.operador',   channel:'Carlos VIP',        subs:168, status:'paused' },
              { op:'novo.operador',     channel:'(setup pendente)',  subs:0,   status:'setup' },
            ].map((r,i)=>(
              <div key={i} style={{display:'grid', gridTemplateColumns:'1fr 1fr auto auto', gap:12, padding:'12px 16px', borderBottom:'1px solid var(--line-1)', alignItems:'center'}}>
                <div>
                  <div style={{color:'var(--text-0)', fontSize:12.5, fontWeight:500}}>{r.op}</div>
                  <div style={{color:'var(--text-3)', fontSize:10.5, fontFamily:'var(--f-mono)', marginTop:2}}>{r.channel}</div>
                </div>
                <span className="mono" style={{fontSize:11, color:'var(--text-2)'}}>{r.subs} subs</span>
                <span className="mono" style={{fontSize:10, color: r.status==='active'?'var(--win)':r.status==='paused'?'var(--warn)':'var(--text-3)', letterSpacing:'0.08em', textTransform:'uppercase'}}>● {r.status}</span>
                <button className="tool-btn">Gerenciar</button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { TodayView, LiveView, SignalsView, EloView, StatsView, PerfView, SettingsView });
