// Cliente que consume el backend proxy. La API key jamas vive en el cliente.
// El proxy /api/bootstrap devuelve TEAMS, NEXT_MATCH, FIXTURE, RESULTS, STANDINGS
// en el mismo shape que usa data.jsx. Reemplazamos los globals window.* en mount.

// API base:
//   - dev con python http.server:5174 + node:3001 separados -> apuntamos a :3001
//   - prod (node server sirve frontend + /api en mismo origen) -> relativo ''
//   - override manual: window.REALE_API_BASE = 'https://mi-api.com'
const API_BASE = window.REALE_API_BASE
  ?? ((location.hostname === 'localhost' && location.port === '5174')
        ? 'http://localhost:3001'
        : '');

async function bootstrapFromApi() {
  const r = await fetch(`${API_BASE}/api/bootstrap`);
  if (!r.ok) throw new Error(`API bootstrap ${r.status}`);
  const d = await r.json();

  // Reemplazar los globals que usan los componentes
  window.TEAMS = d.teams;
  window.NEXT_MATCH = d.nextMatch;
  window.FIXTURE = d.fixture;
  window.RESULTS = d.results;
  window.STANDINGS = d.standings;
  window.STATS = d.stats || { goles: [], asistencias: [], amarillas: [] };
  // NEWS se mantiene como mock (la API de futbol no trae noticias)

  return d;
}

function useApiBootstrap() {
  const [state, setState] = React.useState({ status: 'loading', meta: null, error: null });

  React.useEffect(() => {
    let cancelled = false;
    bootstrapFromApi()
      .then((d) => { if (!cancelled) setState({ status: 'ready', meta: d.meta, error: null }); })
      .catch((err) => {
        console.error('[api] bootstrap failed, usando mock data:', err);
        if (!cancelled) setState({ status: 'fallback', meta: null, error: String(err.message) });
      });
    return () => { cancelled = true; };
  }, []);

  return state;
}

function ApiBadge({ state }) {
  if (state.status === 'loading') {
    return (
      <div style={apiBadgeStyle('#0A2B63')}>
        <span style={{ opacity: 0.9 }}>Cargando API...</span>
      </div>
    );
  }
  if (state.status === 'fallback') {
    return (
      <div style={apiBadgeStyle('#8B0A1A')} title={state.error || ''}>
        API off - datos demo
      </div>
    );
  }
  if (state.status === 'ready') {
    return (
      <div style={apiBadgeStyle('#1E7F3E')} title={state.meta?.note || ''}>
        API live · season {state.meta?.season}
      </div>
    );
  }
  return null;
}

function apiBadgeStyle(bg) {
  return {
    position: 'absolute',
    top: 8,
    left: '50%',
    transform: 'translateX(-50%)',
    zIndex: 50,
    background: bg,
    color: '#fff',
    fontSize: 10,
    fontWeight: 700,
    letterSpacing: 0.4,
    padding: '4px 10px',
    borderRadius: 999,
    boxShadow: '0 2px 8px rgba(0,0,0,0.25)',
    pointerEvents: 'none',
  };
}

window.useApiBootstrap = useApiBootstrap;
window.ApiBadge = ApiBadge;
