/* SINAIS FIFA — data layer (API-backed) */

// Affiliate config (estático — não vem da API)
const AFFIL = {
  brand: 'GoldeBet',
  signupUrl: 'https://goldebet.bet.br/?c=FIFAEDGE',
  loginUrl:  'https://goldebet.bet.br/login',
  iframeUrl: '/api/partner',                          // proxy via FlareSolverr (bypass X-Frame-Options)
  iframeFallbackUrl: 'https://goldebet.bet.br/',
  gameUrlBase: 'https://goldebet.bet.br/sports/efutebol-fifa/match/',
};

// Estado global mutável — Dashboard lê via window.MATCHES_FIFA etc.
window.MATCHES_FIFA = [];
window.QUEUE_FIFA   = [];
window.HISTORY_FIFA = [];
window.PERF_FIFA    = [];
window.LEAGUES_FIFA = [];
window.TILES_FIFA   = [
  { k: 'Sinais Hoje', v: '–', d: '', cls: 'gold' },
  { k: 'Win Rate 7d', v: '–', d: '', cls: 'win'  },
  { k: 'ROI 7d',      v: '–', d: '', cls: 'gold' },
];
window.AFFIL = AFFIL;
window.SF_DATA_LOADING = false;
window.SF_DATA_ERROR = null;
window.SF_LEAGUE_ID = 22614;        // padrão: Battle 8min (mais ativa)

const API_BASE = (() => {
  // Em dev, o front pode estar em outra origem — permite override
  const meta = document.querySelector('meta[name="sf-api-base"]');
  return (meta && meta.content) || '';
})();

async function _fetchJSON(path) {
  const res = await fetch(API_BASE + path, { credentials: 'omit' });
  if (!res.ok) throw new Error(`${path} → ${res.status}`);
  return res.json();
}

async function loadAllData() {
  window.SF_DATA_LOADING = true;
  window.SF_DATA_ERROR = null;
  try {
    const leagueParam = window.SF_LEAGUE_ID ? `?league_id=${window.SF_LEAGUE_ID}` : '';
    const [tiles, matches, queue, history, perf, leagues] = await Promise.all([
      _fetchJSON('/api/tiles'),
      _fetchJSON('/api/matches'),
      _fetchJSON('/api/queue'),
      _fetchJSON('/api/history'),
      _fetchJSON('/api/performance' + leagueParam),
      _fetchJSON('/api/leagues'),
    ]);
    window.TILES_FIFA   = tiles;
    window.MATCHES_FIFA = matches;
    window.QUEUE_FIFA   = queue;
    window.HISTORY_FIFA = history;
    window.PERF_FIFA    = perf;
    window.LEAGUES_FIFA = leagues;
  } catch (err) {
    window.SF_DATA_ERROR = err.message || String(err);
    console.error('[sf] load failed:', err);
  } finally {
    window.SF_DATA_LOADING = false;
    window.dispatchEvent(new CustomEvent('sf:data', { detail: { ts: Date.now() } }));
  }
}

async function loginRequest(email, password, accept) {
  const res = await fetch(API_BASE + '/api/auth/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password, accept }),
  });
  if (!res.ok) {
    const detail = await res.json().catch(() => ({}));
    throw new Error(detail.detail || 'login failed');
  }
  return res.json();
}

window.loadAllData    = loadAllData;
window.loginRequest   = loginRequest;
