import "./style.css";
import backgroundMusicUrl from "../background_music.mp3";
import { createGame } from "./phaser/createGame";
import { createHud } from "./ui/hud";

interface NavigatorWithUAData extends Navigator {
  userAgentData?: {
    mobile?: boolean;
  };
}

function isPhoneDevice(): boolean {
  const nav = navigator as NavigatorWithUAData;
  if (nav.userAgentData?.mobile) {
    return true;
  }

  const ua = navigator.userAgent.toLowerCase();
  const phoneByUa = /(iphone|ipod|android.*mobile|windows phone|blackberry|opera mini|iemobile)/.test(ua);
  if (phoneByUa) {
    return true;
  }

  const coarsePointer = window.matchMedia("(pointer: coarse)").matches;
  const smallScreen = Math.min(window.innerWidth, window.innerHeight) <= 900;
  return coarsePointer && smallScreen;
}

function renderDesktopOnlyMessage(host: HTMLElement): void {
  host.replaceChildren();
  host.classList.add("desktop-only-mode");

  const shell = document.createElement("section");
  shell.className = "desktop-only-shell";

  const card = document.createElement("article");
  card.className = "desktop-only-card";

  const title = document.createElement("h1");
  title.textContent = "Deltanism";

  const text = document.createElement("p");
  text.textContent = "Эта игра работает только на компьютере.";

  const hint = document.createElement("p");
  hint.className = "desktop-only-hint";
  hint.textContent = "Откройте игру на ПК или ноутбуке.";

  card.append(title, text, hint);
  shell.append(card);
  host.append(shell);
}

function startDesktopOnlyMusic(): void {
  const music = new Audio(backgroundMusicUrl);
  music.loop = true;
  music.volume = 0.34;
  music.preload = "auto";

  const tryPlay = () => {
    void music.play()
      .then(detachUnlockHandlers)
      .catch(() => {
        /* Autoplay may be blocked on mobile; wait for interaction handlers. */
      });
  };

  const unlockAndPlay = () => {
    tryPlay();
  };

  const detachUnlockHandlers = () => {
    window.removeEventListener("pointerdown", unlockAndPlay);
    window.removeEventListener("touchstart", unlockAndPlay);
    window.removeEventListener("keydown", unlockAndPlay);
  };

  window.addEventListener("pointerdown", unlockAndPlay, { once: true });
  window.addEventListener("touchstart", unlockAndPlay, { once: true });
  window.addEventListener("keydown", unlockAndPlay, { once: true });
  tryPlay();
}

const app = document.querySelector<HTMLDivElement>("#app");
if (!app) {
  throw new Error("Missing #app root.");
}

if (isPhoneDevice()) {
  renderDesktopOnlyMessage(app);
  startDesktopOnlyMusic();
} else {
  app.classList.remove("desktop-only-mode");
  const shell = document.createElement("main");
  shell.className = "game-shell";

  const gameRoot = document.createElement("section");
  gameRoot.className = "game-root";

  const hudRoot = document.createElement("aside");
  hudRoot.className = "hud-root";

  shell.append(gameRoot, hudRoot);
  app.append(shell);

  const hud = createHud(hudRoot);
  hud.setVisible(false);
  const game = createGame(gameRoot, hud);

  window.addEventListener("beforeunload", () => {
    game.destroy(true);
    hud.destroy();
  });
}
