/*
  main.js — Save Pet
  Boot sequence. Every other module is self-contained (SP.Storage,
  SP.Audio, SP.Game, SP.UI, SP.Ads, SP.Analytics, SP.PWA); this file
  just brings them up in the right order and reveals the app once
  everything is wired.
*/
(function () {
  "use strict";

  function boot() {
    SP.Storage.load();
    SP.Audio.init();
    if (SP.Analytics) SP.Analytics.init();

    const canvas = document.getElementById("game-canvas");
    if (canvas) SP.Game.init(canvas);

    SP.UI.init();
    if (SP.Ads) SP.Ads.initAll();
    if (SP.PWA) SP.PWA.init();

    const splash = document.getElementById("splash-screen");
    const app = document.getElementById("app");
    if (app) app.classList.remove("hidden");
    if (splash) {
      splash.classList.add("splash--done");
      setTimeout(function () { splash.style.display = "none"; }, 500);
    }

    SP.Audio.playMusic("menu");
    handleShortcut();
  }

  function handleShortcut() {
    try {
      const params = new URLSearchParams(window.location.search);
      const mode = params.get("mode");
      if (!mode) return;
      if (mode === "daily") { SP.UI.showScreen("game"); SP.Game.startLevel(SP.Levels.getDailyLevel(), "daily"); }
      else if (mode === "endless") { SP.UI.showScreen("game"); SP.Game.startLevel(SP.Levels.getEndlessConfig(), "endless"); }
      else if (mode === "continue") {
        const next = SP.Storage.data.unlockedLevel || 1;
        SP.UI.showScreen("game"); SP.Game.startLevel(SP.Levels.getLevel(next), "level");
      }
      if (window.history && window.history.replaceState) {
        window.history.replaceState({}, document.title, window.location.pathname);
      }
    } catch (e) { /* malformed URL params should never break boot */ }
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", boot);
  } else {
    boot();
  }
})();
