/* Theme boot — include in <head> AFTER the page's stylesheets so the theme
   override loads last. Applies the stored choice (or the OS preference)
   before first paint; renders always pin the default theme so user theming
   can never change export pixels. */
(() => {
  const DEFAULT = 'liquid-dark';
  const render = new URLSearchParams(location.search).has('render');
  let id = DEFAULT;
  if (!render) {
    try { id = localStorage.getItem('app-theme') || ''; } catch (e) { id = ''; }
    if (!id) id = matchMedia('(prefers-color-scheme: light)').matches ? 'paper-light' : DEFAULT;
  }
  document.documentElement.dataset.theme = id;
  document.write(`<link rel="stylesheet" id="theme-css" href="/theme-css/${encodeURIComponent(id)}.css">`);

  const syncMeta = () => {
    const m = document.querySelector('meta[name="theme-color"]');
    if (!m) return;
    const bg = getComputedStyle(document.documentElement).getPropertyValue('--bg').trim();
    if (bg) m.content = bg;
  };
  addEventListener('DOMContentLoaded', () => setTimeout(syncMeta, 60));

  window.APPTHEME = {
    get: () => document.documentElement.dataset.theme,
    set(next) {
      try { localStorage.setItem('app-theme', next); } catch (e) {}
      document.documentElement.dataset.theme = next;
      const link = document.getElementById('theme-css');
      link.href = `/theme-css/${encodeURIComponent(next)}.css`;
      link.addEventListener('load', syncMeta, { once: true });
    },
  };
})();
