---
// The base HTML shell. `Astro.locals.editMode` is set by the generated
// middleware.ts (from your auth seam); LouiseEdit boots the editor when it's on.
//
// SEO is settings-driven: the `site_settings` row supplies the site-wide title,
// description, and OG image, and a page overrides any of them via props.
// <StructuredData> emits the schema.org graph (business + WebSite), with the
// business `@type` chosen from your archetype.
import Credit from "astroidjs/components/Credit.astro";
import Seo from "astroidjs/components/Seo.astro";
import StructuredData from "astroidjs/components/StructuredData.astro";
import { astroidBusiness, astroidSeoLocale } from "astroidjs";
import { env } from "cloudflare:workers";
import { astroidIndexingDisabled } from "astroidjs/seo";
import astroidConfig from "../../astroid.config.js";
import LouiseEdit from "../components/LouiseEdit.astro";
import "../styles/site.css";

interface Props {
  title?: string;
  description?: string;
  /** Absolute or root-relative share image; falls back to the site default. */
  ogImage?: string;
  /** Keep this page out of search indexes (cart, checkout, account). */
  noindex?: boolean;
  /** A `pages` row id whose `<Editable>` fields stage drafts + publish. */
  versionedPageId?: number;
  /** The page's stored `sections` array, forwarded to the on-canvas section
   *  editor so it can seed its store with what's actually rendered. */
  sections?: unknown;
}

const { title, description, ogImage, noindex, versionedPageId, sections } = Astro.props;
const { editMode } = Astro.locals;

// The editable settings row drives the head. Missing (pre-provision, pre-seed)
// falls back to the brand name from your config, so a fresh clone still renders
// a sane <title> rather than an empty one.
type Settings = {
  site_name: string | null;
  tagline: string | null;
  meta_description: string | null;
  default_og_image_url: string | null;
  logo_url: string | null;
  contact_email: string | null;
  contact_phone: string | null;
  contact_address: string | null;
  social_links: string | null;
};
let row: Settings | null = null;
try {
  row = await env.DB.prepare(
    `SELECT site_name, tagline, meta_description, default_og_image_url, logo_url,
            contact_email, contact_phone, contact_address, social_links
     FROM site_settings WHERE id = 1`,
  ).first<Settings>();
} catch {
  // No DB binding yet—fall through to the config defaults below.
}

const settings = {
  siteName: row?.site_name ?? astroidConfig.theme.name,
  tagline: row?.tagline,
  metaDescription: row?.meta_description,
  defaultOgImageUrl: row?.default_og_image_url,
  logoUrl: row?.logo_url,
  contactEmail: row?.contact_email,
  contactPhone: row?.contact_phone,
  contactAddress: row?.contact_address,
  // Stored as a JSON string; a malformed value must not take down the page.
  socialLinks: (() => {
    try {
      return row?.social_links ? JSON.parse(row.social_links) : undefined;
    } catch {
      return undefined;
    }
  })(),
  // **Hide from search engines**: every page prints `noindex` while it's on,
  // the same switch that makes robots.txt serve `Disallow: /`.
  disableIndexing: await astroidIndexingDisabled(astroidConfig, env),
};

// The page language is `business.locale` from astroid.config.ts, and English,
// the language this template is written in, until the config states one.
const lang = astroidBusiness(astroidConfig).locale ?? "en";
---

<!doctype html>
<html lang={lang} data-theme="light">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <Seo
      settings={settings}
      title={title}
      description={description}
      ogImage={ogImage}
      noindex={noindex}
      titleTemplate={astroidConfig.seo?.titleTemplate}
      twitterHandle={astroidConfig.seo?.twitterHandle}
      locale={astroidSeoLocale(astroidConfig)}
    />
    <StructuredData config={astroidConfig} settings={settings} />
  </head>
  <body class="min-h-screen bg-base-100 text-base-content" data-edit-mode={editMode ? "" : undefined}>
    <slot />
    {
      /* The agency credit, when astroid.config.ts sets `credit`. A site with
         its own footer can move <Credit config={astroidConfig} /> into it. */
      astroidConfig.credit && (
        <footer class="mx-auto flex max-w-6xl justify-center px-6 py-8">
          <Credit config={astroidConfig} />
        </footer>
      )
    }
    <LouiseEdit versionedPageId={versionedPageId} sections={sections} />
    {
      /* Real-visitor Core Web Vitals. A static file from public/, so it is
         same-origin and already covered by `script-src 'self'`—an inline
         script with generated content couldn't be hashed into the CSP.
         `defer` keeps it off the critical path; it reports once per page on
         visibilitychange via sendBeacon. Skipped in edit mode: an editor's
         session is not representative field data. */
      !editMode && <script src="/vitals.js" defer />
    }
  </body>
</html>
