/* SINAIS FIFA — root */

const { useState: useS_A, useEffect: useE_A } = React;

const REFRESH_INTERVAL_MS = 30_000;

function Root() {
  const [user, setUser] = useS_A(() => {
    try { return JSON.parse(localStorage.getItem('sf.user')) || null; } catch { return null; }
  });
  const [dataTick, setDataTick] = useS_A(0);

  useE_A(() => {
    if (user) localStorage.setItem('sf.user', JSON.stringify(user));
    else localStorage.removeItem('sf.user');
  }, [user]);

  // Carrega dados da API ao logar e a cada 30s. Re-renderiza via dataTick.
  useE_A(() => {
    if (!user) return;
    let cancelled = false;
    const onData = () => { if (!cancelled) setDataTick(t => t + 1); };
    window.addEventListener('sf:data', onData);
    window.loadAllData();
    const id = setInterval(() => window.loadAllData(), REFRESH_INTERVAL_MS);
    return () => {
      cancelled = true;
      window.removeEventListener('sf:data', onData);
      clearInterval(id);
    };
  }, [user]);

  if (!user) return <LoginScreen onLogin={setUser} />;
  return <Dashboard user={user} onLogout={() => setUser(null)} dataTick={dataTick} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
