import * as bus from './core/bus.js';
import * as store from './core/store.js';
import * as scene from './core/scene.js';
import * as audio from './core/audio.js';
import * as input from './core/input.js';
import * as hud from './core/hud.js';
import * as theme from './core/theme.js';
import { setLang } from './core/i18n.js';
import { getRecoverableMatch } from './core/match-session.js';
import * as tournamentSession from './core/tournament-session.js';
import * as nativeBridge from './core/native-bridge.js';

async function boot() {
  // Handle OAuth callback — extract tokens from URL hash before anything else
  const hash = window.location.hash;
  if (hash.includes('access_token')) {
    const params = new URLSearchParams(hash.substring(1));
    const accessToken = params.get('access_token');
    const refreshToken = params.get('refresh_token');
    if (accessToken) {
      store.set('auth.token', accessToken);
      store.set('auth.refreshToken', refreshToken);
      store.set('auth.isGuest', false);
      store.set('auth.guestId', null);
      // Ensure profile exists with Google data (name, avatar)
      fetch('/api/profile.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${accessToken}` },
        body: JSON.stringify({ action: 'ensure' })
      }).then(r => r.json()).then(p => {
        if (p && !p.error) store.set('player', { ...store.get('player'), ...p });
      }).catch(() => {});
    }
    history.replaceState(null, '', '/');
  }

  setLang(store.get('language') || 'ar');
  await theme.load();
  audio.init();
  if (window.flutter_bridge || window.IS_NATIVE_APP) nativeBridge.init();
  input.init();
  scene.init();

  await loadModules();

  const token = store.get('auth.token');
  if (token) {
    hud.init();
    scene.setRoot('play', 'play-table');
    scene.setRoot('rank', 'leaderboard');
    scene.setRoot('social', 'friends');
    scene.setRoot('tournaments', 'tournaments-hub');
    scene.setRoot('profile', 'profile-view');

    // Check for active match to resume (tab refresh / re-entry recovery)
    const recoverable = getRecoverableMatch();
    if (recoverable) {
      // Verify match is still running on server before reconnecting
      try {
        const endpoint = recoverable.gameType === 'ludo' ? 'ludo-match.php' : recoverable.gameType === 'domino' ? 'domino-match.php' : recoverable.gameType === 'backgammon' ? 'backgammon-match.php' : 'game.php';
        const res = await fetch(`/api/${endpoint}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
          body: JSON.stringify({ action: 'get', match_id: recoverable.matchId })
        });
        const matchData = await res.json();
        if (matchData && !matchData.error && matchData.status === 'in_progress') {
          // Match still running — rejoin
          const gameScene = recoverable.gameType === 'chess' ? 'chess-game' : recoverable.gameType + '-game';
          scene.push(gameScene, { mode: 'live', matchId: recoverable.matchId, recovered: true });
        } else {
          // Match ended, abandoned, or not found — clear recovery and go home
          localStorage.removeItem('el3ab_active_match');
          scene.switchWorld(store.get('activeWorld') || 'play');
        }
      } catch (e) {
        // Network error — try to rejoin anyway
        const gameScene = recoverable.gameType === 'chess' ? 'chess-game' : recoverable.gameType + '-game';
        scene.push(gameScene, { mode: 'live', matchId: recoverable.matchId, recovered: true });
      }
    } else {
      scene.switchWorld(store.get('activeWorld') || 'play');
    }
    tournamentSession.init();
  } else {
    hud.hide();
    scene.push('auth-splash');
  }

  bus.on('auth:success', onAuthSuccess);
  bus.on('auth:guestSuccess', onGuestSuccess);
  bus.on('auth:expired', onAuthExpired);
  bus.on('auth:logout', onLogout);
}

function onAuthSuccess() {
  store.set('auth.isGuest', false);
  store.set('auth.guestId', null);
  hud.init();
  hud.show();
  scene.setRoot('play', 'play-table');
  scene.setRoot('rank', 'leaderboard');
  scene.setRoot('social', 'friends');
  scene.setRoot('tournaments', 'tournaments-hub');
  scene.setRoot('profile', 'profile-view');
  scene.switchWorld('play');
  tournamentSession.init();
}

function onGuestSuccess() {
  hud.init(true);
  hud.show();
  scene.setRoot('play', 'play-table');
  scene.switchWorld('play');
}

function onAuthExpired() {
  store.set('auth.token', null);
  store.set('auth.refreshToken', null);
  store.set('auth.userId', null);
  hud.hide();
  scene.push('auth-login');
}

function onLogout() {
  store.reset();
  hud.hide();
  scene.push('auth-splash');
}

async function loadModules() {
  await import('./modules/auth/mod.js');
  await import('./modules/play/mod.js');
  await import('./modules/chess/mod.js');
  await import('./modules/domino/mod.js');
  await import('./modules/ludo/mod.js');
  await import('./modules/backgammon/mod.js');
  await import('./modules/rank/mod.js');
  await import('./modules/social/mod.js');
  await import('./modules/tournaments/mod.js');
  await import('./modules/profile/mod.js');
  await import('./modules/rewards/mod.js');
  await import('./modules/puzzles/mod.js');
  await import('./modules/org/mod.js');
}

boot();
