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';

async function boot() {
  setLang(store.get('language') || 'ar');
  await theme.load();
  audio.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('shop', 'shop-browse');
    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' : '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 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');
    }
  } else {
    hud.hide();
    scene.push('auth-splash');
  }

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

function onAuthSuccess() {
  hud.init();
  hud.show();
  scene.setRoot('play', 'play-table');
  scene.setRoot('rank', 'leaderboard');
  scene.setRoot('social', 'friends');
  scene.setRoot('shop', 'shop-browse');
  scene.setRoot('profile', 'profile-view');
  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/rank/mod.js');
  await import('./modules/social/mod.js');
  await import('./modules/shop/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();
