---
import { env } from 'cloudflare:workers';
import '../styles/theme.css';
import { ConsentBanner } from '@platform-modules/content-react';
import { getMenuTree } from '@platform-modules/menus';
import { getFullDb } from '../lib/db';
import { getAllSettings } from '../lib/settings';
import { getMenusDb, resolveMenuHref } from '../lib/menus';
import { MOD_CMS_PALETTE_SET, themeCss, DEFAULT_SELECTION } from '../lib/theme';
import { assembleBaseChrome } from './base-chrome';
import { resolveModTheme } from '../themes/registry';
import { resolveShell } from '../lib/theme-contract';
import type { ActiveSelection } from '@platform-modules/ui-tokens/theme-engine';

interface Props {
  title: string;
  description?: string;
  noindex?: boolean;
  /** Install wizard shell — no site chrome, no internal product copy in header/footer. */
  minimal?: boolean;
  /** Pre-resolved appearance selection (passed by a page that already read it, to avoid a double settings read / torn chrome-vs-body). When omitted, Base reads it from settings itself. */
  selection?: ActiveSelection;
}

const {
  title,
  description = 'mod-cms — a content distribution built on the platform',
  noindex = false,
  minimal = false,
  selection: selectionProp,
} = Astro.props;

let settings: Awaited<ReturnType<typeof getAllSettings>> | null = null;
try {
  settings = await getAllSettings(getFullDb(env).db);
} catch {
  settings = null;
}

let resolvedNav: { label: string; href: string }[] | null = null;
try {
  const { db: contentDb } = getFullDb(env);
  const menusDb = getMenusDb(env);
  const tree = await getMenuTree(menusDb, 'primary');
  if (tree && tree.items.length > 0) {
    const resolved = await Promise.all(
      tree.items.map(async (item) => {
        const href = await resolveMenuHref(item, { db: contentDb });
        return href ? { label: item.label, href } : null;
      }),
    );
    const links = resolved.filter((link): link is { label: string; href: string } => link != null);
    if (links.length > 0) resolvedNav = links;
  }
} catch {
  resolvedNav = null;
}

const { selection, identity, consent, navLinks, hideModeToggle } = assembleBaseChrome({
  settings,
  resolvedNav,
  selectionProp,
});
const Shell = resolveShell(resolveModTheme(selection.themeId));
const htmlThemeAttrs = {
  'data-theme': MOD_CMS_PALETTE_SET.id,
  'data-palette': selection.paletteId,
  // Omit data-mode for 'system' so the engine's media-query path (anti-FOUC, no JS) drives it.
  ...(selection.mode === 'system' ? {} : { 'data-mode': selection.mode }),
};

---

<!doctype html>
<html lang="en" {...htmlThemeAttrs}>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content={description} />
    {noindex ? <meta name="robots" content="noindex" /> : null}
    <title>{title}</title>
    {minimal ? (
      <link
        rel="stylesheet"
        href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght@0,9..144,300..700;1,9..144,300..700&family=Schibsted+Grotesk:wght@400;500&display=swap"
      />
    ) : null}
    <style set:html={themeCss}></style>
  </head>
  <body class={minimal ? 'install-body' : undefined}>
    {minimal ? (
      <main class="install-main"><slot /></main>
    ) : (
      <Shell
        siteName={identity.name}
        logoUrl={identity.logoUrl}
        hideModeToggle={hideModeToggle}
        navLinks={navLinks}
      >
        <main><slot /></main>
      </Shell>
    )}
    {!minimal && !hideModeToggle ? (
      <script is:inline>
      (function () {
        var root = document.documentElement;
        var key = 'mod-cms-theme';
        var stored = localStorage.getItem(key);
        if (stored === 'light' || stored === 'dark') root.dataset.mode = stored;
        var btn = document.getElementById('theme-toggle');
        if (!btn) return;
        btn.addEventListener('click', function () {
          // Resolve current effective mode: explicit data-mode, else the OS preference.
          var current = root.dataset.mode
            || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
          var next = current === 'dark' ? 'light' : 'dark';
          root.dataset.mode = next;
          localStorage.setItem(key, next);
        });
      })();
    </script>
    ) : null}
    {!minimal && consent.enabled ? (
      <ConsentBanner
        client:idle
        version={consent.version}
        categories={consent.categories}
        policyHref={consent.policyHref}
      />
    ) : null}
  </body>
</html>
