import { CONFIG } from './config.js';
import { state } from './core/state.js';
import { Game } from './core/game.js';
import { bindInput } from './core/input.js';
import { loadSave } from './systems/storage.js';
import { createHud } from './ui/hud.js';
import { showScreen, createGameOver } from './ui/screens.js';
import { initLanguage, setLanguage, onLanguageChange } from './lang/language.js';
import { createInfoModal } from './ui/info-modal.js';

const hud = createHud();
const gameOverUi = createGameOver();
const game = new Game(document.querySelector('#gameCanvas'), hud, gameOverUi);
const playButton = document.querySelector('#playButton');
const menuButton = document.querySelector('#menuButton');
const retryButton = document.querySelector('#retryButton');
const gameOverMenuButton = document.querySelector('#gameOverMenuButton');
const canvas = document.querySelector('#gameCanvas');
const infoModal = createInfoModal({ onOpen: () => game.audio.click() });

function goToMenu() {
  game.stop();
  gameOverUi.hide();
  showScreen('menu');
  hud.update(state);
}

function startGame() {
  showScreen('game');
  game.start();
}

function init() {
  const save = loadSave();
  state.highscore = Number(save.highscore) || 0;
  initLanguage();
  hud.update(state);
  game.init();

  playButton.addEventListener('click', () => { game.audio.click(); startGame(); });
  retryButton.addEventListener('click', () => { game.audio.click(); startGame(); });
  menuButton.addEventListener('click', () => { game.audio.click(); goToMenu(); });
  gameOverMenuButton.addEventListener('click', () => { game.audio.click(); goToMenu(); });
  document.querySelectorAll('[data-language]').forEach(button => {
    button.addEventListener('click', () => { game.audio.click(); setLanguage(button.dataset.language); });
  });
  onLanguageChange(() => {
    hud.update(state);
    gameOverUi.refresh();
  });
  bindInput({ canvas, onEscape: () => { if (infoModal.isOpen()) infoModal.close(); else goToMenu(); }, onAction: point => game.actionAt(point.x, point.y) });

  setTimeout(() => showScreen('menu'), CONFIG.splashDuration);

  const isLocal = ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname);
  if (!isLocal && 'serviceWorker' in navigator && location.protocol.startsWith('http')) {
    navigator.serviceWorker.register('./service-worker.js?v=0007', { updateViaCache: 'none' }).catch(console.warn);
  }
}

init();
