import { h, Fragment } from "../jsx";

// FOUC-prevention bootstrap (m/paliad#2 + maria's instruction 2026-04-30).
//
// Runs synchronously in <head> BEFORE the stylesheet starts loading. Its
// only job is to set classes/attributes on <html> that change first-frame
// layout, so the page paints in the user's persisted state instead of
// flickering from default → JS-applied state.
//
// Three pieces of state are restored:
//   1. paliad-theme    — light / dark / auto-with-system-pref
//   2. paliad-sidebar-pinned — desktop-only padding-left swap
//   3. paliad-sidebar-width  — user-resized rail width
//
// Body class for `sidebar-pinned` is owned by client/sidebar.ts post-
// hydration (we can't touch document.body from <head>). The CSS uses two
// selectors — `.has-sidebar.sidebar-pinned` (body class, runtime) and
// `:root.sidebar-pinned .has-sidebar` (html class, this script) — so
// either source pre-paints the correct padding.
//
// Storage keys and decision logic mirror frontend/src/client/theme.ts and
// client/sidebar.ts. If you change one, change the others.
const FOUC_BOOTSTRAP = `(function(){try{var d=document.documentElement,ls=localStorage;var p=ls.getItem("paliad-theme");if(p==="dark"||((!p||p==="auto")&&window.matchMedia&&matchMedia("(prefers-color-scheme: dark)").matches))d.setAttribute("data-theme","dark");if(window.innerWidth>=1024&&ls.getItem("paliad-sidebar-pinned")==="true")d.classList.add("sidebar-pinned");var w=parseInt(ls.getItem("paliad-sidebar-width")||"",10);if(w>=180&&w<=480)d.style.setProperty("--sidebar-width",w+"px");}catch(e){}})();`;

// PWAHead emits the head fragment that turns Paliad into an installable PWA.
// Add it to every page's <head> alongside the existing viewport / theme-color
// metas. The <script src="/assets/app.js"> registers the service worker,
// initialises the BottomNav, and surfaces the install banner — included here
// (not in <body>) so it runs on every page regardless of which per-page
// bundle the page also loads.
export function PWAHead(): string {
  return (
    <Fragment>
      <script dangerouslySetInnerHTML={{ __html: FOUC_BOOTSTRAP }} />
      <link rel="manifest" href="/manifest.json" />
      <link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
      <link rel="icon" type="image/png" sizes="192x192" href="/icons/icon-192.png" />
      <link rel="icon" type="image/png" sizes="512x512" href="/icons/icon-512.png" />
      <link rel="shortcut icon" type="image/png" href="/icons/favicon-32.png" />
      <meta name="apple-mobile-web-app-title" content="Paliad" />
      <meta name="application-name" content="Paliad" />
      <meta name="mobile-web-app-capable" content="yes" />
      <script src="/assets/app.js" defer></script>
    </Fragment>
  );
}
