// app.ts — universal client bundle injected on every page. Four jobs:
//   1. Wire the BottomNav (was previously written but never bundled — m
//      reproduced the broken [+] and Menü buttons in production).
//   2. Register the service worker so the site qualifies for PWA install.
//   3. Surface the install prompt (Chromium banner / iOS share-sheet hint).
//   4. Init the theme listener so the OS-level prefers-color-scheme change
//      flips the page when the user's pref is "auto" (m/paliad#2).
//
// Per-page bundles still register their own behaviour; this script is
// orthogonal and only touches DOM nodes it owns.

import { initBottomNav } from "./bottom-nav";
import { initInstallPrompt } from "./pwa-install";
import { initTheme } from "./theme";

function registerServiceWorker(): void {
  if (!("serviceWorker" in navigator)) return;
  // Don't bother in non-secure contexts (localhost is a secure context, so
  // local dev still registers).
  if (!window.isSecureContext) return;

  navigator.serviceWorker.register("/sw.js", { scope: "/" }).catch((err) => {
    // Surface registration failures in the console — do not throw, since the
    // site has to keep working without the SW.
    console.warn("paliad: service worker registration failed", err);
  });
}

function boot(): void {
  initBottomNav();
  initInstallPrompt();
  initTheme();
}

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

// Register the SW after the page has had a chance to paint so it never
// competes with critical resources on first paint.
if (document.readyState === "complete") {
  registerServiceWorker();
} else {
  window.addEventListener("load", registerServiceWorker);
}
