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

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