import { isRichSchema, deriveCacheKey, resolveDefaultLocale, hasDarkScheme, createUniweb } from "@uniweb/core";
import React from "react";
import { renderToString } from "react-dom/server";
import { buildSectionOverrides } from "@uniweb/theming";
function guaranteeItemStructure(item) {
  return {
    title: item.title || "",
    pretitle: item.pretitle || "",
    subtitle: item.subtitle || "",
    paragraphs: item.paragraphs || [],
    links: item.links || [],
    images: item.images || [],
    lists: item.lists || [],
    icons: item.icons || [],
    videos: item.videos || [],
    snippets: item.snippets || [],
    buttons: item.buttons || [],
    data: item.data || {},
    cards: item.cards || [],
    documents: item.documents || [],
    forms: item.forms || [],
    quotes: item.quotes || [],
    headings: item.headings || [],
    ...item.math && item.math.length ? { math: item.math } : {}
  };
}
function guaranteeContentStructure(parsedContent) {
  const content = parsedContent || {};
  return {
    // Flat header fields
    title: content.title || "",
    pretitle: content.pretitle || "",
    subtitle: content.subtitle || "",
    alignment: content.alignment || null,
    // Flat body fields
    paragraphs: content.paragraphs || [],
    links: content.links || [],
    images: content.images || [],
    lists: content.lists || [],
    icons: content.icons || [],
    videos: content.videos || [],
    insets: content.insets || [],
    snippets: content.snippets || [],
    buttons: content.buttons || [],
    data: content.data || {},
    cards: content.cards || [],
    documents: content.documents || [],
    forms: content.forms || [],
    quotes: content.quotes || [],
    headings: content.headings || [],
    // Rare collections — surfaced only when present so pages that don't
    // use them don't pay the allocation cost. Foundations that need them
    // should check for presence (content.math?.length) or use
    // content.sequence for in-order rendering.
    ...content.math && content.math.length ? { math: content.math } : {},
    // Items with guaranteed structure
    items: (content.items || []).map(guaranteeItemStructure),
    // Sequence for ordered rendering
    sequence: content.sequence || [],
    // Preserve raw content if present
    raw: content.raw
  };
}
function applySchemaToObject(obj, schema) {
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
    return obj;
  }
  const result = { ...obj };
  for (const [field, fieldDef] of Object.entries(schema)) {
    const defaultValue = typeof fieldDef === "object" ? fieldDef.default : void 0;
    if (result[field] === void 0 && defaultValue !== void 0) {
      result[field] = defaultValue;
    }
    if (typeof fieldDef !== "object") continue;
    if (Array.isArray(fieldDef.enum)) {
      if (result[field] !== void 0 && !fieldDef.enum.includes(result[field]) && defaultValue !== void 0) {
        result[field] = defaultValue;
      }
    }
    if (fieldDef.type === "object" && fieldDef.fields && result[field]) {
      result[field] = applySchemaToObject(result[field], fieldDef.fields);
    }
    if (fieldDef.type === "array" && fieldDef.items && Array.isArray(result[field])) {
      const items = fieldDef.items;
      if (items && typeof items === "object" && items.type === "object" && items.fields) {
        result[field] = result[field].map((item) => applySchemaToObject(item, items.fields));
      }
    }
  }
  return result;
}
function applySchemaToValue(value, schema) {
  if (Array.isArray(value)) {
    return value.map((item) => applySchemaToObject(item, schema));
  }
  return applySchemaToObject(value, schema);
}
function applyRichFieldDefaults(obj, fields) {
  if (!obj || typeof obj !== "object" || Array.isArray(obj)) return obj;
  if (!Array.isArray(fields)) return obj;
  const result = { ...obj };
  for (const field of fields) {
    if (!field || typeof field !== "object" || !field.id) continue;
    const id = field.id;
    if (result[id] === void 0 && field.default !== void 0) {
      result[id] = field.default;
    }
    if (field.type === "form" && field.childSchema && Array.isArray(result[id])) {
      result[id] = result[id].map(
        (item) => applyRichFieldDefaults(item, field.childSchema.fields)
      );
    } else if ((field.type === "nestedObject" || field.type === "object") && Array.isArray(field.fields) && result[id] && typeof result[id] === "object") {
      result[id] = applyRichFieldDefaults(result[id], field.fields);
    }
  }
  return result;
}
function applyRichSchemaToValue(value, schema) {
  if (value == null) return value;
  if (schema.isComposite && schema.childSchema) {
    const childFields = schema.childSchema.fields;
    const collectionKey = schema.childCollection;
    if (collectionKey && value && typeof value === "object" && !Array.isArray(value)) {
      const arr = Array.isArray(value[collectionKey]) ? value[collectionKey] : [];
      return {
        ...value,
        [collectionKey]: arr.map((row) => applyRichFieldDefaults(row, childFields))
      };
    }
    if (Array.isArray(value)) {
      return value.map((row) => applyRichFieldDefaults(row, childFields));
    }
    return value;
  }
  if (Array.isArray(schema.fields)) {
    return applyRichFieldDefaults(value, schema.fields);
  }
  return value;
}
function applySchemas(data, schemas) {
  if (!schemas || !data || typeof data !== "object") {
    return data || {};
  }
  const result = { ...data };
  for (const [tag, rawValue] of Object.entries(data)) {
    const schema = schemas[tag];
    if (!schema) continue;
    result[tag] = isRichSchema(schema) ? applyRichSchemaToValue(rawValue, schema) : applySchemaToValue(rawValue, schema);
  }
  return result;
}
function applyDefaults(params, defaults) {
  if (!defaults || Object.keys(defaults).length === 0) {
    return params || {};
  }
  return {
    ...defaults,
    ...params || {}
  };
}
function mergeEntityData(block, entityData) {
  if (!entityData) return;
  const current = block.parsedContent.data || {};
  let changed = false;
  const merged = { ...current };
  for (const key of Object.keys(entityData)) {
    if (merged[key] === void 0) {
      merged[key] = entityData[key];
      changed = true;
    }
  }
  if (changed) {
    block.parsedContent.data = merged;
  }
}
function runDataHandler(block) {
  if (block.dataLoading) return;
  const handler = globalThis.uniweb?.foundationConfig?.handlers?.data;
  if (typeof handler !== "function") return;
  try {
    const result = handler(block.parsedContent.data, block);
    if (result != null && result !== block.parsedContent.data) {
      block.parsedContent.data = result;
    }
  } catch (err) {
    console.error("Foundation data handler failed:", err);
  }
}
function runContentHandler(block) {
  if (block.dataLoading) return;
  const handler = globalThis.uniweb?.foundationConfig?.handlers?.content;
  if (typeof handler !== "function") return;
  if (!block.rawContent || Object.keys(block.rawContent).length === 0) return;
  try {
    const transformed = handler(block.parsedContent.data, block);
    if (!transformed || transformed === block.rawContent) return;
    const reparsed = block.parseContent(transformed);
    reparsed.data = block.parsedContent.data;
    block.parsedContent = reparsed;
    block.items = reparsed.items || [];
  } catch (err) {
    console.error("Foundation content handler failed:", err);
  }
}
function runPropsHandler(content, params, block) {
  const handler = globalThis.uniweb?.foundationConfig?.handlers?.props;
  if (typeof handler !== "function") return null;
  try {
    const result = handler(content, params, block);
    if (result && typeof result === "object") return result;
  } catch (err) {
    console.error("Foundation props handler failed:", err);
  }
  return null;
}
function prepareProps(block, meta, entityData = null) {
  mergeEntityData(block, entityData);
  runDataHandler(block);
  runContentHandler(block);
  const defaults = meta?.defaults || {};
  const params = applyDefaults(block.properties, defaults);
  let content = guaranteeContentStructure(block.parsedContent);
  const schemas = meta?.schemas || null;
  if (schemas && content.data) {
    content.data = applySchemas(content.data, schemas);
  }
  const adjusted = runPropsHandler(content, params, block);
  if (adjusted) {
    return {
      content: adjusted.content || content,
      params: adjusted.params || params
    };
  }
  return { content, params };
}
function getComponentMeta(componentName) {
  return globalThis.uniweb?.getComponentMeta?.(componentName) || null;
}
function getComponentDefaults(componentName) {
  return globalThis.uniweb?.getComponentDefaults?.(componentName) || {};
}
function default404Html(basePath = "") {
  const homeHref = basePath ? `${basePath}/` : "/";
  return `<div class="page-not-found" style="min-height:80vh;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:2rem;text-align:center"><h1 style="font-size:3rem;font-weight:bold;color:#1f2937;margin-bottom:1rem">404</h1><p style="color:#64748b;margin-bottom:2rem">Page not found</p><a href="${homeHref}" style="color:#3b82f6;text-decoration:underline">Go to homepage</a></div>`;
}
function FallbackRef({ params }) {
  return React.createElement(
    "span",
    { className: "xref xref--unhandled" },
    `[${params?.key || "?"}]`
  );
}
function wireFoundationCapabilities(uniweb, foundation) {
  const caps = foundation?.default?.capabilities || {};
  uniweb.defaultInsets = { Ref: FallbackRef, ...caps.defaultInsets || {} };
  if (caps.xref?.build && uniweb.activeWebsite) {
    caps.xref.build(uniweb.activeWebsite, {
      foundationKinds: caps.xref.kinds || {}
    });
  }
}
function sliceContentForLocale(content, locale) {
  const defaultLang = resolveDefaultLocale(content?.config);
  const locData = content?.locales?.[locale];
  if (!locale || locale === defaultLang || !locData) return content;
  return {
    pages: locData.pages,
    layouts: locData.layouts || content.layouts,
    config: {
      ...locData.config,
      i18n: content.config?.i18n,
      activeLocale: locale
    }
  };
}
function hydrateDataStore(website, fetchedData) {
  if (!website?.dataStore || !fetchedData?.length) return;
  for (const entry of fetchedData) {
    website.dataStore.set(deriveCacheKey(entry.config), { data: entry.data });
  }
}
const NS = "uw-";
const toIdent = (name) => NS + String(name).replace(/[^a-zA-Z0-9_-]/g, "-");
function resolveLayoutTransitions(areaNames, explicit) {
  if (explicit === false) return null;
  const transitions = { body: toIdent("body") };
  for (const name of areaNames) transitions[name] = toIdent(name);
  return explicit ? { ...transitions, ...explicit } : transitions;
}
function applyBootScheme(respectSystem, fallback) {
  var stored = null;
  try {
    stored = localStorage.getItem("uniweb-appearance");
  } catch (e) {
  }
  var hasStored = stored === "light" || stored === "dark";
  var scheme = hasStored ? stored : fallback;
  if (!hasStored && respectSystem) {
    try {
      if (window.matchMedia("(prefers-color-scheme: dark)").matches) scheme = "dark";
    } catch (e) {
    }
  }
  try {
    var root = document.documentElement;
    if (scheme === "dark") {
      root.classList.add("scheme-dark");
      root.classList.remove("scheme-light");
    } else {
      root.classList.add("scheme-light");
      root.classList.remove("scheme-dark");
    }
  } catch (e) {
  }
  return scheme;
}
function resolveAppearanceBoot(appearance) {
  if (!appearance || !hasDarkScheme(appearance)) return null;
  return {
    respectSystem: appearance.respectSystemPreference !== false,
    fallback: appearance.default === "dark" ? "dark" : "light"
  };
}
function renderAppearanceBootScript(appearance) {
  const opts = resolveAppearanceBoot(appearance);
  if (!opts) return "";
  const call = `(${applyBootScheme.toString()})(${opts.respectSystem}, ${JSON.stringify(opts.fallback)})`;
  return `<script id="uniweb-appearance">${call}<\/script>`;
}
const VALID_CONTEXTS = ["light", "medium", "dark"];
function getWrapperProps(block) {
  const theme = block.themeName;
  const blockClassName = block.state?.className || "";
  let contextClass = "";
  if (theme && VALID_CONTEXTS.includes(theme)) {
    contextClass = `context-${theme}`;
  }
  let className = contextClass;
  if (blockClassName) {
    className = className ? `${className} ${blockClassName}` : blockClassName;
  }
  const { background = {} } = block.standardOptions;
  const style = {};
  if (background.mode) {
    style.position = "relative";
    style.isolation = "isolate";
  }
  if (block.contextOverrides) {
    for (const [key, value] of Object.entries(block.contextOverrides)) {
      style[`--${key}`] = value;
    }
  }
  const sectionId = block.stableId || block.id;
  return { id: `section-${sectionId}`, style, className, background };
}
function withOpacity(color, opacity) {
  if (color.startsWith("#")) {
    const r = parseInt(color.slice(1, 3), 16);
    const g = parseInt(color.slice(3, 5), 16);
    const b = parseInt(color.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${opacity})`;
  }
  if (color.startsWith("rgb")) {
    const match = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
    if (match) {
      return `rgba(${match[1]}, ${match[2]}, ${match[3]}, ${opacity})`;
    }
  }
  return color;
}
function resolveUrl(url) {
  if (!url || !url.startsWith("/")) return url;
  const basePath = globalThis.uniweb?.activeWebsite?.basePath || "";
  if (!basePath) return url;
  if (url.startsWith(basePath + "/") || url === basePath) return url;
  return basePath + url;
}
function renderBackground(background) {
  if (!background?.mode) return null;
  const containerStyle = {
    position: "absolute",
    inset: "0",
    overflow: "hidden",
    zIndex: 0
  };
  const children = [];
  if (background.mode === "color" && background.color) {
    children.push(
      React.createElement("div", {
        key: "bg-color",
        className: "background-color",
        style: { position: "absolute", inset: "0", backgroundColor: background.color },
        "aria-hidden": "true"
      })
    );
  }
  if (background.mode === "gradient" && background.gradient) {
    const g = background.gradient;
    let bgValue;
    if (typeof g === "string") {
      bgValue = g;
    } else {
      const {
        start = "transparent",
        end = "transparent",
        angle = 0,
        startPosition = 0,
        endPosition = 100,
        startOpacity = 1,
        endOpacity = 1
      } = g;
      const startColor = startOpacity < 1 ? withOpacity(start, startOpacity) : start;
      const endColor = endOpacity < 1 ? withOpacity(end, endOpacity) : end;
      bgValue = `linear-gradient(${angle}deg, ${startColor} ${startPosition}%, ${endColor} ${endPosition}%)`;
    }
    children.push(
      React.createElement("div", {
        key: "bg-gradient",
        className: "background-gradient",
        style: { position: "absolute", inset: "0", background: bgValue },
        "aria-hidden": "true"
      })
    );
  }
  if (background.mode === "image" && background.image?.src) {
    const img = background.image;
    children.push(
      React.createElement("div", {
        key: "bg-image",
        className: "background-image",
        style: {
          position: "absolute",
          inset: "0",
          backgroundImage: `url(${resolveUrl(img.src)})`,
          backgroundPosition: img.position || "center",
          backgroundSize: img.size || "cover",
          backgroundRepeat: "no-repeat"
        },
        "aria-hidden": "true"
      })
    );
  }
  if (background.overlay?.enabled) {
    const ov = background.overlay;
    let overlayStyle;
    if (ov.gradient) {
      const g = ov.gradient;
      overlayStyle = {
        position: "absolute",
        inset: "0",
        pointerEvents: "none",
        background: `linear-gradient(${g.angle || 180}deg, ${g.start || "rgba(0,0,0,0.7)"} ${g.startPosition || 0}%, ${g.end || "rgba(0,0,0,0)"} ${g.endPosition || 100}%)`,
        opacity: ov.opacity ?? 0.5
      };
    } else {
      const baseColor = ov.type === "light" ? "255, 255, 255" : "0, 0, 0";
      overlayStyle = {
        position: "absolute",
        inset: "0",
        pointerEvents: "none",
        backgroundColor: `rgba(${baseColor}, ${ov.opacity ?? 0.5})`
      };
    }
    children.push(
      React.createElement("div", {
        key: "bg-overlay",
        className: ov.gradient ? "background-overlay background-overlay--gradient" : "background-overlay background-overlay--solid",
        style: overlayStyle,
        "aria-hidden": "true"
      })
    );
  }
  if (children.length === 0) return null;
  return React.createElement("div", {
    className: `background background--${background.mode}`,
    style: containerStyle,
    "aria-hidden": "true"
  }, ...children);
}
function renderBlock(block, { as = "section" } = {}) {
  const Component = block.initComponent();
  if (!Component) {
    return React.createElement("div", {
      className: "block-error",
      style: { padding: "1rem", background: "#fef2f2", color: "#dc2626" }
    }, `Component not found: ${block.type}`);
  }
  const meta = getComponentMeta(block.type);
  const entityStore = block.website?.entityStore;
  let entityData = null;
  if (entityStore) {
    const resolved = entityStore.resolve(block, meta);
    if (resolved.status === "ready") entityData = resolved.data;
  }
  const prepared = prepareProps(block, meta, entityData);
  const params = prepared.params;
  const content = { ...prepared.content, ...block.properties };
  const componentProps = { content, params, block };
  if (!as) {
    return React.createElement(Component, componentProps);
  }
  const { background, ...wrapperProps } = getWrapperProps(block);
  const componentClassName = Component.className;
  if (componentClassName) {
    wrapperProps.className = wrapperProps.className ? `${wrapperProps.className} ${componentClassName}` : componentClassName;
  }
  const hasBackground = background?.mode && meta?.background !== "self";
  block.hasBackground = hasBackground;
  const wrapperTag = as !== "section" ? as : Component.as || "section";
  if (hasBackground) {
    return React.createElement(
      wrapperTag,
      wrapperProps,
      renderBackground(background),
      React.createElement(
        "div",
        { style: { position: "relative", zIndex: 10 } },
        React.createElement(Component, componentProps)
      )
    );
  }
  return React.createElement(
    wrapperTag,
    wrapperProps,
    React.createElement(Component, componentProps)
  );
}
function renderBlocks(blocks) {
  if (!blocks || blocks.length === 0) return null;
  return blocks.map(
    (block, index) => React.createElement(
      React.Fragment,
      { key: block.id || index },
      renderBlock(block)
    )
  );
}
function renderLayout(page, website) {
  const layoutName = page.getLayoutName();
  const RemoteLayout = website.getRemoteLayout(layoutName);
  const layoutMeta = website.getLayoutMeta(layoutName);
  const bodyBlocks = page.getBodyBlocks();
  const areas = page.getLayoutAreas();
  const transitions = website.viewTransitions ? resolveLayoutTransitions(Object.keys(areas), layoutMeta?.transitions) : null;
  const wrapTransition = (name, element) => {
    const vtName = transitions?.[name];
    return vtName ? React.createElement("div", { style: { viewTransitionName: vtName } }, element) : element;
  };
  const bodyElement = bodyBlocks ? wrapTransition("body", renderBlocks(bodyBlocks)) : null;
  const areaElements = {};
  for (const [name, blocks] of Object.entries(areas)) {
    areaElements[name] = wrapTransition(name, renderBlocks(blocks));
  }
  if (RemoteLayout) {
    const params = { ...layoutMeta?.defaults || {}, ...page.getLayoutParams() || {} };
    return React.createElement(RemoteLayout, {
      page,
      website,
      params,
      body: bodyElement,
      ...areaElements
    });
  }
  return React.createElement(
    React.Fragment,
    null,
    areaElements.header && React.createElement("header", { style: { position: "relative", zIndex: 40 } }, areaElements.header),
    bodyElement && React.createElement("main", null, bodyElement),
    areaElements.footer && React.createElement("footer", { style: { position: "relative", zIndex: 30 } }, areaElements.footer)
  );
}
function initPrerenderForLocale(content, foundation, locale, extensionsOrOptions, maybeOptions) {
  const localeContent = sliceContentForLocale(content, locale);
  const uniweb = initPrerender(localeContent, foundation, extensionsOrOptions, maybeOptions);
  const defaultLang = resolveDefaultLocale(content?.config);
  if (locale && locale !== defaultLang && uniweb.activeWebsite?.setActiveLocale) {
    uniweb.activeWebsite.setActiveLocale(locale);
  }
  return uniweb;
}
function initPrerender(content, foundation, extensionsOrOptions, maybeOptions) {
  let extensions = [];
  let options = {};
  if (Array.isArray(extensionsOrOptions)) {
    extensions = extensionsOrOptions;
    options = maybeOptions || {};
  } else {
    options = extensionsOrOptions || {};
  }
  const { onProgress = () => {
  } } = options;
  onProgress("Initializing runtime...");
  const uniweb = createUniweb(content, foundation, extensions);
  if (content.config?.base && uniweb.activeWebsite?.setBasePath) {
    uniweb.activeWebsite.setBasePath(content.config.base);
  }
  uniweb.childBlockRenderer = function InlineChildBlocks({ blocks, from, wrapAs }) {
    const blockList = blocks || from?.childBlocks || [];
    return blockList.map(
      (childBlock, index) => React.createElement(
        React.Fragment,
        { key: childBlock.id || index },
        renderBlock(childBlock, { as: wrapAs || null })
      )
    );
  };
  wireFoundationCapabilities(uniweb, foundation);
  const website = uniweb.activeWebsite;
  uniweb.routingComponents = {
    useLocation: () => {
      const route = website?.activePage?.route || "";
      return { pathname: "/" + route, search: "", hash: "", state: null, key: "default" };
    },
    useParams: () => ({}),
    useNavigate: () => () => {
    }
  };
  return uniweb;
}
async function prefetchIcons(siteContent, uniweb, onProgress = () => {
}) {
  const icons = siteContent.icons?.used || [];
  if (icons.length === 0) return;
  const cdnBase = siteContent.config?.icons?.cdnUrl || "https://uniweb.github.io/icons";
  onProgress(`Fetching ${icons.length} icons for SSR...`);
  const results = await Promise.allSettled(
    icons.map(async (iconRef) => {
      const [family, name] = iconRef.split(":");
      const url = `${cdnBase}/${family}/${family}-${name}.svg`;
      const response = await fetch(url);
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const svg = await response.text();
      uniweb.iconCache.set(`${family}:${name}`, svg);
    })
  );
  const succeeded = results.filter((r) => r.status === "fulfilled").length;
  const failed = results.filter((r) => r.status === "rejected").length;
  if (failed > 0) {
    const msg = `Fetched ${succeeded}/${icons.length} icons (${failed} failed)`;
    console.warn(`[prerender] ${msg}`);
    onProgress(`  ${msg}`);
  }
  if (uniweb.iconCache.size > 0) {
    siteContent._iconCache = Object.fromEntries(uniweb.iconCache);
  }
}
function classifyRenderError(err) {
  const msg = err.message || "";
  if (msg.includes("Invalid hook call") || msg.includes("useState") || msg.includes("useEffect")) {
    return {
      type: "hooks",
      message: "contains components with React hooks (renders client-side)"
    };
  }
  if (msg.includes("Element type is invalid") && msg.includes("null")) {
    return {
      type: "null-component",
      message: "a component resolved to null (often hook-related, renders client-side)"
    };
  }
  return {
    type: "unknown",
    message: msg
  };
}
function renderPage(page, website) {
  website.setActivePage(page.route);
  const element = renderLayout(page, website);
  let renderedContent;
  try {
    renderedContent = renderToString(element);
  } catch (err) {
    return { error: classifyRenderError(err) };
  }
  const appearance = website.themeData?.appearance;
  const sectionOverrideCSS = buildSectionOverrides(page.getPageBlocks(), appearance);
  return { renderedContent, sectionOverrideCSS };
}
function escapeHtml(str) {
  if (!str) return "";
  return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
}
function injectPageContent(html, renderedContent, page, options = {}) {
  let result = html;
  if (!result.includes('id="uniweb-appearance"')) {
    const bootScript = renderAppearanceBootScript(page?.website?.themeData?.appearance);
    if (bootScript) {
      result = result.replace("</head>", `  ${bootScript}
</head>`);
    }
  }
  if (options.sectionOverrideCSS) {
    const overrideStyle = `<style id="uniweb-page-overrides">
${options.sectionOverrideCSS}
</style>`;
    result = result.replace("</head>", `${overrideStyle}
</head>`);
  }
  result = result.replace(
    /<div id="root">[\s\S]*?<\/div>/,
    `<div id="root">${renderedContent}</div>`
  );
  const pageTitle = page.getTitle?.() || page.title;
  if (pageTitle) {
    result = result.replace(
      /<title>.*?<\/title>/,
      `<title>${escapeHtml(pageTitle)}</title>`
    );
  }
  if (page.description) {
    const metaDesc = `<meta name="description" content="${escapeHtml(page.description)}">`;
    if (result.includes('<meta name="description"')) {
      result = result.replace(/<meta name="description"[^>]*>/, metaDesc);
    } else {
      result = result.replace("</head>", `${metaDesc}
</head>`);
    }
  }
  const headMeta = page.getHeadMeta?.();
  if (headMeta) {
    const og = headMeta.og || {};
    const keywords = Array.isArray(headMeta.keywords) ? headMeta.keywords.join(", ") : headMeta.keywords;
    const tags = [];
    if (keywords) tags.push(`<meta name="keywords" content="${escapeHtml(keywords)}">`);
    if (headMeta.robots) tags.push(`<meta name="robots" content="${escapeHtml(headMeta.robots)}">`);
    if (og.title) tags.push(`<meta property="og:title" content="${escapeHtml(og.title)}">`);
    if (og.description) tags.push(`<meta property="og:description" content="${escapeHtml(og.description)}">`);
    if (og.image) tags.push(`<meta property="og:image" content="${escapeHtml(og.image)}">`);
    if (og.url) tags.push(`<meta property="og:url" content="${escapeHtml(og.url)}">`);
    tags.push('<meta property="og:type" content="website">');
    tags.push(`<meta name="twitter:card" content="${og.image ? "summary_large_image" : "summary"}">`);
    if (og.title) tags.push(`<meta name="twitter:title" content="${escapeHtml(og.title)}">`);
    if (og.description) tags.push(`<meta name="twitter:description" content="${escapeHtml(og.description)}">`);
    if (og.image) tags.push(`<meta name="twitter:image" content="${escapeHtml(og.image)}">`);
    if (headMeta.canonical) tags.push(`<link rel="canonical" href="${escapeHtml(headMeta.canonical)}">`);
    if (tags.length) result = result.replace("</head>", `${tags.join("\n")}
</head>`);
  }
  return result;
}
function generate404Html({ baseHtml, website, siteContent }) {
  const dynamicTemplates = siteContent.pages?.filter((p) => p.isDynamic) || [];
  const routePatterns = dynamicTemplates.map((p) => {
    const escaped = p.route.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/:[^/]+/g, "[^\\/]+");
    return `^${escaped}\\/?$`;
  });
  let html = baseHtml;
  const notFoundPage = website.getNotFoundPage();
  if (notFoundPage) {
    const notFoundResult = renderPage(notFoundPage, website);
    if (notFoundResult && !notFoundResult.error) {
      html = injectPageContent(html, notFoundResult.renderedContent, notFoundPage, {
        sectionOverrideCSS: notFoundResult.sectionOverrideCSS
      });
    }
  } else {
    const basePath = website.basePath || "";
    html = html.replace(
      /<div id="root">[\s\S]*?<\/div>/,
      `<div id="root">${default404Html(basePath)}</div>`
    );
  }
  if (routePatterns.length > 0) {
    const patternList = routePatterns.map((p) => `/${p}/`).join(",");
    const dynamicScript = `<script>(function(){var p=[${patternList}],r=window.location.pathname;if(p.some(function(x){return x.test(r)})){var el=document.getElementById('root');if(el)el.innerHTML='';}})()<\/script>`;
    html = html.replace("</body>", `${dynamicScript}
</body>`);
  }
  return { html, hasNotFoundPage: !!notFoundPage };
}
export {
  applyDefaults,
  applySchemas,
  classifyRenderError,
  escapeHtml,
  generate404Html,
  getComponentDefaults,
  getComponentMeta,
  getWrapperProps,
  guaranteeContentStructure,
  hydrateDataStore,
  initPrerender,
  initPrerenderForLocale,
  injectPageContent,
  prefetchIcons,
  prepareProps,
  renderAppearanceBootScript,
  renderBackground,
  renderBlock,
  renderBlocks,
  renderLayout,
  renderPage,
  sliceContentForLocale
};
//# sourceMappingURL=ssr.js.map
