"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }




var _chunkIT5ICP43js = require('./chunk-IT5ICP43.js');



var _chunkEGTDJ4PLjs = require('./chunk-EGTDJ4PL.js');


var _chunkDGUM43GVjs = require('./chunk-DGUM43GV.js');

// src/rendering/components/Page.tsx
var _jsxruntime = require('react/jsx-runtime');
function Page({
  page,
  theme,
  themeTokens: providedTokens,
  siteId,
  resolvedData,
  routeMap,
  wrapBlock,
  registry,
  usePlaceholders = false,
  blockOverrides,
  sdkConfig,
  dataContext
}) {
  const baseTokens = _nullishCoalesce(providedTokens, () => ( _chunkIT5ICP43js.buildThemeRuntime.call(void 0, theme).tokens));
  const themeTokens = _optionalChain([sdkConfig, 'optionalAccess', _ => _.theme, 'optionalAccess', _2 => _2.palette]) ? { ...baseTokens, palette: { ...baseTokens.palette, ...sdkConfig.theme.palette } } : baseTokens;
  return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, 
    _chunkIT5ICP43js.PageRenderer,
    {
      theme,
      page,
      themeTokens,
      usePlaceholders,
      dataContext: {
        siteId,
        resolvedData,
        routes: routeMap,
        occurrenceContext: _nullishCoalesce(_optionalChain([dataContext, 'optionalAccess', _3 => _3.occurrenceContext]), () => ( null)),
        contentEntry: _nullishCoalesce(_optionalChain([dataContext, 'optionalAccess', _4 => _4.contentEntry]), () => ( null))
      },
      routeMap,
      wrapBlock,
      registry,
      blockOverrides,
      sdkConfig
    }
  );
}

// ../block-form/dist/server/index.mjs
var _zod = require('zod');

















var __require2 = /* @__PURE__ */ ((x) => typeof _chunkDGUM43GVjs.__require !== "undefined" ? _chunkDGUM43GVjs.__require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof _chunkDGUM43GVjs.__require !== "undefined" ? _chunkDGUM43GVjs.__require : a)[b]
}) : x)(function(x) {
  if (typeof _chunkDGUM43GVjs.__require !== "undefined") return _chunkDGUM43GVjs.__require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
function buildTextFieldSchema(field) {
  const ui = _nullishCoalesce(_optionalChain([field, 'optionalAccess', _5 => _5.ui]), () => ( {}));
  const inputType = _optionalChain([ui, 'optionalAccess', _6 => _6.inputType]);
  if (inputType === "email") {
    let s2 = _zod.z.string().email("Enter a valid email");
    if (typeof field.maxLength === "number") {
      s2 = s2.max(field.maxLength);
    }
    if (field.required) {
      return s2.min(1, "This field is required");
    }
    return s2.optional().nullable().or(_zod.z.literal(""));
  }
  if (inputType === "tel") {
    let s2 = _zod.z.string().regex(/^[+()0-9\s\-]{3,}$/, "Enter a valid phone number");
    if (typeof field.maxLength === "number") {
      s2 = s2.max(field.maxLength);
    }
    if (field.required) {
      return s2.min(1, "This field is required");
    }
    return s2.optional().nullable().or(_zod.z.literal(""));
  }
  let s = _zod.z.string();
  if (typeof field.maxLength === "number") {
    s = s.max(field.maxLength);
  }
  if (_optionalChain([ui, 'optionalAccess', _7 => _7.pattern])) {
    try {
      const re = new RegExp(ui.pattern);
      s = s.regex(re);
    } catch (e) {
    }
  }
  if (field.required) {
    return s.min(1, "This field is required");
  }
  return s.optional().nullable().or(_zod.z.literal(""));
}
function getTextFieldDefault(field) {
  if (field.defaultValue !== void 0 && field.defaultValue !== null) {
    return String(field.defaultValue);
  }
  if (field.required) {
    return field.label;
  }
  return "";
}
function buildNumberFieldSchema(field) {
  const ui = _nullishCoalesce(_optionalChain([field, 'optionalAccess', _8 => _8.ui]), () => ( {}));
  let s = _zod.z.coerce.number();
  if (typeof _optionalChain([ui, 'optionalAccess', _9 => _9.min]) === "number") {
    s = s.min(ui.min);
  }
  if (typeof _optionalChain([ui, 'optionalAccess', _10 => _10.max]) === "number") {
    s = s.max(ui.max);
  }
  if (!field.required) {
    s = s.optional().nullable();
  }
  return s;
}
function getNumberFieldDefault(field) {
  if (field.defaultValue !== void 0) {
    return typeof field.defaultValue === "number" ? field.defaultValue : null;
  }
  return null;
}
function buildSelectFieldSchema(field) {
  const validValues = _nullishCoalesce(_optionalChain([field, 'access', _11 => _11.options, 'optionalAccess', _12 => _12.map, 'call', _13 => _13((opt) => opt.value)]), () => ( []));
  if (validValues.length === 0) {
    return field.required ? _zod.z.string().min(1) : _zod.z.string().optional();
  }
  let schema = _zod.z.enum(validValues);
  if (!field.required) {
    schema = schema.optional();
  }
  return schema;
}
function getSelectFieldDefault(field) {
  if (field.defaultValue !== void 0 && field.defaultValue !== null) {
    return String(field.defaultValue);
  }
  return _nullishCoalesce(_optionalChain([field, 'access', _14 => _14.options, 'optionalAccess', _15 => _15[0], 'optionalAccess', _16 => _16.value]), () => ( ""));
}
function buildBooleanFieldSchema(field) {
  return _zod.z.boolean();
}
function getBooleanFieldDefault(field) {
  if (field.defaultValue !== void 0) {
    return Boolean(field.defaultValue);
  }
  return false;
}
function buildGroupFieldSchema(field, ctx) {
  const shape = {};
  for (const child of field.fields) {
    shape[child.id] = ctx.getFieldSchema(child);
  }
  return _zod.z.object(shape).catchall(_zod.z.unknown()).passthrough();
}
function getGroupFieldDefault(field, ctx) {
  const obj = {};
  for (const child of field.fields) {
    obj[child.id] = ctx.resolve(child);
  }
  return obj;
}
function buildModalFieldSchema(field, ctx) {
  const shape = {};
  const fields = _nullishCoalesce(_nullishCoalesce(_optionalChain([field, 'access', _17 => _17.schema, 'optionalAccess', _18 => _18.fields]), () => ( field.fields)), () => ( []));
  for (const child of fields) {
    shape[child.id] = ctx.getFieldSchema(child);
  }
  return _zod.z.object(shape).catchall(_zod.z.unknown()).passthrough();
}
function getModalFieldDefault(field, ctx) {
  const obj = {};
  const fields = _nullishCoalesce(_nullishCoalesce(_optionalChain([field, 'access', _19 => _19.schema, 'optionalAccess', _20 => _20.fields]), () => ( field.fields)), () => ( []));
  for (const child of fields) {
    obj[child.id] = ctx.resolve(child);
  }
  return obj;
}
function buildRepeaterFieldSchema(field, ctx) {
  let itemSchema;
  if (field.polymorphic && field.itemTypes) {
    const itemTypeSchemas = [];
    for (const [typeKey, itemType] of Object.entries(field.itemTypes)) {
      const childShape = {
        _type: _zod.z.literal(typeKey)
      };
      for (const childField of itemType.fields) {
        childShape[childField.id] = ctx.getFieldSchema(childField);
      }
      itemTypeSchemas.push(_zod.z.object(childShape).catchall(_zod.z.unknown()).passthrough());
    }
    itemSchema = itemTypeSchemas.length > 1 ? _zod.z.discriminatedUnion("_type", itemTypeSchemas) : _nullishCoalesce(itemTypeSchemas[0], () => ( _zod.z.object({ _type: _zod.z.string() }).passthrough()));
  } else if (!field.polymorphic && field.fields) {
    const childShape = {};
    for (const childField of field.fields) {
      childShape[childField.id] = ctx.getFieldSchema(childField);
    }
    itemSchema = _zod.z.object(childShape).catchall(_zod.z.unknown()).passthrough();
  } else {
    itemSchema = _zod.z.any();
  }
  if (field.validation) {
    const customValidation = field.validation;
    if (field.required) {
      return customValidation;
    }
    return customValidation.optional();
  }
  let schema = _zod.z.array(itemSchema);
  const minItems = _nullishCoalesce(field.minItems, () => ( 0));
  if (minItems > 0) {
    schema = schema.min(minItems, `Must have at least ${minItems} item(s)`);
  }
  if (field.maxItems !== void 0) {
    schema = schema.max(field.maxItems, `Must have at most ${field.maxItems} item(s)`);
  }
  if (field.required) {
    return schema;
  }
  return schema.optional();
}
function getRepeaterFieldDefault(field, ctx) {
  if (field.defaultValue !== void 0) {
    return Array.isArray(field.defaultValue) ? field.defaultValue : [];
  }
  const minItems = _nullishCoalesce(field.minItems, () => ( 0));
  if (minItems > 0) {
    const items = [];
    for (let i = 0; i < minItems; i++) {
      const item = {};
      if (field.polymorphic && field.itemTypes) {
        const firstType = Object.keys(field.itemTypes)[0];
        if (firstType) {
          item._type = firstType;
          const typeSchema = field.itemTypes[firstType];
          if (typeSchema) {
            for (const childField of typeSchema.fields) {
              item[childField.id] = ctx.resolve(childField);
            }
          }
        }
      } else if (field.fields) {
        for (const childField of field.fields) {
          item[childField.id] = ctx.resolve(childField);
        }
      }
      items.push(item);
    }
    return items;
  }
  return [];
}
var ALLOWED_PROTOCOLS = ["http:", "https:"];
function buildUrlFieldSchema(field) {
  const message = `${field.label} must be a valid URL`;
  const validator = (value) => {
    if (!value) {
      return !field.required;
    }
    if (field.allowRelative && value.startsWith("/")) {
      return true;
    }
    try {
      const parsed = new URL(value);
      return ALLOWED_PROTOCOLS.includes(parsed.protocol);
    } catch (e2) {
      return false;
    }
  };
  const base = _zod.z.string().trim().refine(validator, message);
  if (field.required) {
    return base.min(1, { message: `${field.label} is required` });
  }
  return _zod.z.union([base, _zod.z.literal("")]).optional().nullable();
}
function getUrlFieldDefault(field) {
  return _nullishCoalesce(field.defaultValue, () => ( ""));
}
function buildTimeFieldSchema(field) {
  const base = _zod.z.string();
  if (field.required) {
    return base.min(1, { message: `${field.label} is required` });
  }
  return _zod.z.union([base, _zod.z.literal(""), _zod.z.null()]).optional().nullable();
}
function getTimeFieldDefault(field) {
  return _nullishCoalesce(field.defaultValue, () => ( null));
}
function buildDateFieldSchema(field) {
  const base = _zod.z.string();
  if (field.required) {
    return base.min(1, { message: `${field.label} is required` });
  }
  return _zod.z.union([base, _zod.z.literal(""), _zod.z.null()]).optional().nullable();
}
function getDateFieldDefault(field) {
  return _nullishCoalesce(field.defaultValue, () => ( null));
}
function buildDateTimeFieldSchema(field) {
  const base = _zod.z.string().refine(
    (val) => {
      if (!val) return true;
      const date = new Date(val);
      return !isNaN(date.getTime());
    },
    { message: `${field.label} must be a valid date-time` }
  );
  if (field.required) {
    return base.min(1, { message: `${field.label} is required` });
  }
  return _zod.z.union([base, _zod.z.literal(""), _zod.z.null()]).optional().nullable();
}
function getDateTimeFieldDefault(field) {
  return _nullishCoalesce(field.defaultValue, () => ( null));
}
var SLUG_PATTERN = /^(?:[a-z0-9]+(?:-[a-z0-9]+)*)(?:\/(?:[a-z0-9]+(?:-[a-z0-9]+)*))*$/;
function buildSlugFieldSchema(field) {
  const base = _zod.z.string().regex(SLUG_PATTERN, `${field.label} must use lowercase letters, numbers, and dashes`);
  const withLength = field.maxLength ? base.max(field.maxLength, { message: `${field.label} must be at most ${field.maxLength} characters` }) : base;
  if (field.required) {
    return withLength.min(1, { message: `${field.label} is required` });
  }
  return _zod.z.union([withLength, _zod.z.literal("")]).optional().nullable();
}
function getSlugFieldDefault(field) {
  return _nullishCoalesce(field.defaultValue, () => ( ""));
}
function buildLinkFieldSchema(field) {
  const nullableString = _zod.z.union([_zod.z.string().min(1), _zod.z.null()]);
  const internal = _zod.z.object({
    kind: _zod.z.literal("internal"),
    routeId: _zod.z.string().min(1),
    entityId: _zod.z.string().min(1).optional(),
    entityType: _zod.z.enum(["page", "content"]).optional(),
    href: nullableString.optional(),
    title: nullableString.optional(),
    typeLabel: nullableString.optional(),
    contentTypeKey: nullableString.optional(),
    contentTypeName: nullableString.optional(),
    updatedAt: nullableString.optional()
  }).passthrough();
  const external = _zod.z.object({
    kind: _zod.z.literal("external"),
    href: _zod.z.string().min(1)
  }).passthrough();
  const custom = _zod.z.object({
    kind: _zod.z.literal("url"),
    href: _zod.z.string().min(1)
  }).passthrough();
  const linkSchema = _zod.z.union([internal, external, custom]);
  if (field.required) {
    return linkSchema;
  }
  return _zod.z.union([linkSchema, _zod.z.null()]).optional();
}
function getLinkFieldDefault(_field) {
  return null;
}
function buildRichTextFieldSchema(config) {
  return _chunkIT5ICP43js.buildRichTextSchema.call(void 0, {
    required: config.required,
    label: config.label
  });
}
var EMPTY_RICH_TEXT_DOC = {
  type: "doc",
  content: [
    {
      type: "paragraph"
    }
  ]
};
function getRichTextFieldDefaultValue(_config) {
  return EMPTY_RICH_TEXT_DOC;
}
var MediaValueSchema = _zod.z.object({
  kind: _zod.z.enum(["image", "video"]),
  url: _zod.z.string().url(),
  alt: _zod.z.string().optional(),
  caption: _zod.z.string().optional(),
  credit: _zod.z.string().optional(),
  width: _zod.z.number().optional(),
  height: _zod.z.number().optional(),
  size: _zod.z.number().optional(),
  mimeType: _zod.z.string().optional()
});
function buildMediaFieldSchema(config) {
  let schema = MediaValueSchema.nullable();
  if (config.required) {
    schema = schema.refine((val) => val !== null, {
      message: `${config.label} is required`
    });
  }
  return schema;
}
function getMediaFieldDefaultValue(_config) {
  return null;
}
function buildTabGroupFieldSchema(field, ctx) {
  const shape = {};
  for (const tab of field.tabs) {
    for (const child of tab.fields) {
      shape[child.id] = ctx.getFieldSchema(child);
    }
  }
  if (field.activeTabField) {
    const tabIds = field.tabs.map((t) => t.id);
    if (tabIds.length > 0) {
      shape[field.activeTabField] = _zod.z.enum(tabIds);
    }
  }
  return _zod.z.object(shape).catchall(_zod.z.unknown()).passthrough();
}
function getTabGroupFieldDefault(field, ctx) {
  const defaults = {};
  for (const tab of field.tabs) {
    for (const child of tab.fields) {
      defaults[child.id] = ctx.resolve(child);
    }
  }
  if (field.activeTabField && field.tabs.length > 0) {
    defaults[field.activeTabField] = field.tabs[0].id;
  }
  return defaults;
}
function buildPresetOrCustomFieldSchema(field, _ctx) {
  const presetValues = field.presets.map((p) => p.value);
  return _zod.z.string();
}
function getPresetOrCustomFieldDefault(field, _ctx) {
  if (field.defaultValue !== void 0 && field.defaultValue !== null) {
    return String(field.defaultValue);
  }
  return _nullishCoalesce(_optionalChain([field, 'access', _21 => _21.presets, 'access', _22 => _22[0], 'optionalAccess', _23 => _23.value]), () => ( ""));
}
function buildReferenceFieldSchema(field, _ctx) {
  return _zod.z.string();
}
function getReferenceFieldDefault(field, _ctx) {
  if (field.defaultValue !== void 0 && field.defaultValue !== null) {
    return String(field.defaultValue);
  }
  if (field.required) {
    return `placeholder-${field.id}`;
  }
  return "";
}
var SCHEMA_BUILDERS = {
  text: buildTextFieldSchema,
  number: buildNumberFieldSchema,
  select: buildSelectFieldSchema,
  boolean: buildBooleanFieldSchema,
  group: buildGroupFieldSchema,
  modal: buildModalFieldSchema,
  repeater: buildRepeaterFieldSchema,
  url: buildUrlFieldSchema,
  time: buildTimeFieldSchema,
  date: buildDateFieldSchema,
  datetime: buildDateTimeFieldSchema,
  slug: buildSlugFieldSchema,
  link: buildLinkFieldSchema,
  richText: buildRichTextFieldSchema,
  media: buildMediaFieldSchema,
  tabGroup: buildTabGroupFieldSchema,
  presetOrCustom: buildPresetOrCustomFieldSchema,
  reference: buildReferenceFieldSchema
};
var DEFAULT_VALUE_BUILDERS = {
  text: getTextFieldDefault,
  number: getNumberFieldDefault,
  select: getSelectFieldDefault,
  boolean: getBooleanFieldDefault,
  group: getGroupFieldDefault,
  modal: getModalFieldDefault,
  repeater: getRepeaterFieldDefault,
  url: getUrlFieldDefault,
  time: getTimeFieldDefault,
  date: getDateFieldDefault,
  datetime: getDateTimeFieldDefault,
  slug: getSlugFieldDefault,
  link: getLinkFieldDefault,
  richText: getRichTextFieldDefaultValue,
  media: getMediaFieldDefaultValue,
  tabGroup: getTabGroupFieldDefault,
  presetOrCustom: getPresetOrCustomFieldDefault,
  reference: getReferenceFieldDefault
};
function buildFieldSchema(field, ctx) {
  const builder = SCHEMA_BUILDERS[field.type];
  if (!builder) {
    console.warn(`No schema builder registered for field type: ${field.type}`);
    return __require2("zod").z.any();
  }
  return builder(field, ctx);
}
function getFieldDefault(field, ctx) {
  const getDefault = DEFAULT_VALUE_BUILDERS[field.type];
  if (!getDefault) {
    console.warn(`No default value builder registered for field type: ${field.type}`);
    return field.defaultValue;
  }
  return getDefault(field, ctx);
}
var DEFAULT_ROLE = "author";
var rolePriority = {
  author: 0,
  designer: 1,
  admin: 2
};
function createManifestFormAdapter(manifest, options) {
  const role = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _24 => _24.role]), () => ( DEFAULT_ROLE));
  const fields = (_nullishCoalesce(manifest.fields, () => ( []))).map((field) => transformField(field, role)).filter(Boolean);
  const schema = buildValidationSchema(fields);
  return { fields, schema };
}
function transformField(field, role) {
  if (!isFieldVisible(field, role)) {
    return void 0;
  }
  if (field.type !== "group" && field.type !== "repeater") {
    return field;
  }
  if (field.type === "group") {
    const children = (_nullishCoalesce(_optionalChain([field, 'access', _25 => _25.schema, 'optionalAccess', _26 => _26.fields]), () => ( []))).map((child) => transformField(child, role)).filter(Boolean);
    if (!children.length) {
      return void 0;
    }
    const { schema: _schema, ...rest } = field;
    return { ...rest, fields: children };
  }
  if (field.type === "repeater") {
    if (field.polymorphic && field.itemTypes) {
      const itemTypes = {};
      for (const [typeKey, itemType] of Object.entries(field.itemTypes)) {
        const children2 = (_nullishCoalesce(itemType.fields, () => ( []))).map((child) => transformField(child, role)).filter(Boolean);
        if (children2.length > 0) {
          itemTypes[typeKey] = {
            label: itemType.label,
            icon: itemType.icon,
            fields: children2
          };
        }
      }
      if (Object.keys(itemTypes).length === 0) {
        return void 0;
      }
      const { schema: _schema2, ...rest2 } = field;
      return { ...rest2, itemTypes };
    }
    const children = (_nullishCoalesce(_optionalChain([field, 'access', _27 => _27.schema, 'optionalAccess', _28 => _28.fields]), () => ( []))).map((child) => transformField(child, role)).filter(Boolean);
    if (!children.length) {
      return void 0;
    }
    const { schema: _schema3, polymorphic: _polymorphic, itemTypes: _itemTypes, ...rest } = field;
    return { ...rest, fields: children };
  }
  return void 0;
}
function isFieldVisible(field, role) {
  if (role === "admin") {
    return true;
  }
  const allowed = field.visibleRoles;
  if (!allowed || allowed.length === 0) {
    return true;
  }
  return allowed.some((visibility) => rolePriority[role] >= rolePriority[visibility]);
}
function buildValidationSchema(fields) {
  const shape = {};
  const ctx = {
    getFieldSchema: (field) => buildFieldSchema(field, ctx)
  };
  for (const field of fields) {
    shape[field.id] = buildFieldSchema(field, ctx);
  }
  return _zod.z.object(shape).catchall(_zod.z.unknown()).passthrough();
}
function createManifestDefaultValues(manifest, data = {}, options = {}) {
  const { fields } = createManifestFormAdapter(manifest, {
    role: options.role,
    ...options.adapterOptions
  });
  const ctx = {
    resolve: (field) => getFieldDefault(field, ctx)
  };
  const result = {};
  for (const field of fields) {
    const rawValue = data[field.id];
    result[field.id] = ensureFieldValue(field, rawValue, ctx);
  }
  return result;
}
function ensureFieldValue(field, rawValue, ctx) {
  if (field.type === "repeater") {
    if (rawValue === void 0) {
      rawValue = getFieldDefault(field, ctx);
    }
    const items = Array.isArray(rawValue) ? rawValue : [];
    return items.map((item) => ensureRepeaterItem(field, item, ctx));
  }
  if (rawValue === void 0) {
    return getFieldDefault(field, ctx);
  }
  return rawValue;
}
function ensureRepeaterItem(field, value, ctx) {
  const itemData = typeof value === "object" && value !== null ? { ...value } : {};
  if (field.polymorphic && field.itemTypes) {
    const itemType = typeof itemData._type === "string" ? itemData._type : Object.keys(field.itemTypes)[0];
    const typeSchema = field.itemTypes[itemType];
    if (!typeSchema) return itemData;
    for (const child of typeSchema.fields) {
      if (child.type === "group" && _optionalChain([child, 'optionalAccess', _29 => _29.ui, 'optionalAccess', _30 => _30.flattenInRepeater])) {
        const group = child;
        for (const gc of group.fields) {
          itemData[gc.id] = ensureFieldValue(gc, itemData[gc.id], ctx);
        }
      } else {
        itemData[child.id] = ensureFieldValue(child, itemData[child.id], ctx);
      }
    }
    return itemData;
  }
  if (!field.polymorphic && field.fields) {
    for (const child of field.fields) {
      if (child.type === "group" && _optionalChain([child, 'optionalAccess', _31 => _31.ui, 'optionalAccess', _32 => _32.flattenInRepeater])) {
        const group = child;
        for (const gc of group.fields) {
          itemData[gc.id] = ensureFieldValue(gc, itemData[gc.id], ctx);
        }
      } else {
        itemData[child.id] = ensureFieldValue(child, itemData[child.id], ctx);
      }
    }
  }
  return itemData;
}

// ../site-renderer/dist/index.mjs
function selectPrimaryMenu(menus) {
  if (!menus.length) {
    return null;
  }
  const primary = menus.find((menu) => menu.isPrimary);
  return _nullishCoalesce(_nullishCoalesce(primary, () => ( menus[0])), () => ( null));
}
function buildMenuViewModel(menu) {
  if (!menu) {
    return { items: [], ctaItem: null };
  }
  const flatItems = menu.items.filter((item) => item.parentId === null && item.urlType !== "dropdown").sort((a, b) => a.orderIndex - b.orderIndex);
  const items = [];
  let ctaItem = null;
  for (const item of flatItems) {
    const viewItem = {
      id: item.id,
      label: item.label,
      link: convertNavigationLink(item),
      target: null,
      rel: null,
      active: false
      // TODO: Compute active state based on current route
    };
    if (!ctaItem && Boolean(item.isCta)) {
      ctaItem = { ...viewItem, variant: "primary" };
      continue;
    }
    items.push(viewItem);
  }
  return { items, ctaItem };
}
function buildLogoViewModel(logo, fallbackTitle) {
  if (!logo) {
    return null;
  }
  if (!logo.url && !logo.assetId) {
    return null;
  }
  const alt = logo.alt && logo.alt.trim().length > 0 ? logo.alt : _nullishCoalesce(fallbackTitle, () => ( "Site logo"));
  const viewModel = {
    type: "image",
    src: _nullishCoalesce(logo.url, () => ( "")),
    // Empty string when url is null - media node uses assetId instead
    alt,
    assetId: _nullishCoalesce(logo.assetId, () => ( void 0)),
    width: _nullishCoalesce(logo.width, () => ( void 0)),
    height: _nullishCoalesce(logo.height, () => ( void 0))
  };
  return viewModel;
}
function convertNavigationLink(item) {
  const payload = _nullishCoalesce(item.url, () => ( null));
  if (!payload) return null;
  const kind = typeof payload.kind === "string" ? payload.kind : null;
  if (kind === "external" || kind === "url") {
    const href = typeof payload.href === "string" ? payload.href : null;
    return href ? { kind, href } : null;
  }
  if (kind === "internal") {
    const routeId = typeof payload.routeId === "string" ? payload.routeId : null;
    const entityId = typeof payload.entityId === "string" ? payload.entityId : null;
    const entityType = typeof payload.entityType === "string" && (payload.entityType === "page" || payload.entityType === "content") ? payload.entityType : null;
    const href = typeof payload.href === "string" ? payload.href : null;
    const title = typeof payload.title === "string" ? payload.title : null;
    const typeLabel = typeof payload.typeLabel === "string" ? payload.typeLabel : null;
    if (!routeId || !entityId || !entityType || !href || !title || !typeLabel) {
      return null;
    }
    return {
      kind: "internal",
      routeId,
      entityId,
      entityType,
      href,
      title,
      typeLabel,
      contentTypeKey: typeof payload.contentTypeKey === "string" ? payload.contentTypeKey : null,
      contentTypeName: typeof payload.contentTypeName === "string" ? payload.contentTypeName : null,
      updatedAt: typeof payload.updatedAt === "string" ? payload.updatedAt : null
    };
  }
  return null;
}
var HEADER_DEFAULTS = createManifestDefaultValues(_chunkEGTDJ4PLjs.siteHeaderManifest);
var FOOTER_DEFAULTS = createManifestDefaultValues(_chunkEGTDJ4PLjs.siteFooterManifest);

// src/rendering/components/Layout.tsx

async function Layout({
  siteData: providedSiteData,
  client,
  siteId,
  slug,
  domain,
  children,
  header = true,
  footer = true,
  headerVariant
}) {
  let siteData = providedSiteData;
  if (!siteData) {
    if (!client) {
      throw new Error("Layout: must provide either siteData or client");
    }
    if (!siteId && !slug && !domain) {
      throw new Error("Layout: must provide siteId, slug, or domain when using client");
    }
    siteData = await client.getSite({ id: siteId, slug, domain });
  }
  const { site, theme, navigation, layout, routes } = siteData;
  const themeRuntime = _chunkIT5ICP43js.buildThemeRuntime.call(void 0, theme);
  const menu = selectPrimaryMenu(navigation);
  const menuViewModel = buildMenuViewModel(menu);
  const logoViewModel = buildLogoViewModel(_nullishCoalesce(layout.logo, () => ( null)), site.title);
  const headerData = {
    menu: menuViewModel,
    logo: logoViewModel,
    site,
    theme,
    routes
  };
  const headerContent = headerVariant ? { ...layout.header, variant: headerVariant } : layout.header;
  const themeWithVariant = headerVariant ? {
    ...theme,
    header: { ...theme.header, variant: headerVariant }
  } : theme;
  const viewModelOverrides = {
    $root: {
      siteId: site.id,
      routes,
      theme: themeWithVariant
    },
    site,
    menu: menuViewModel,
    content: {
      logo: logoViewModel
    }
  };
  let headerElement = null;
  if (header === true) {
    headerElement = _chunkIT5ICP43js.renderBlock.call(void 0, _chunkEGTDJ4PLjs.siteHeaderManifest, headerContent, {
      theme: themeRuntime.tokens,
      themeConfig: themeWithVariant,
      viewModelOverrides
    });
  } else if (typeof header === "function") {
    headerElement = header(headerData);
  }
  return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment, { children: [
    headerElement,
    children,
    footer && _chunkIT5ICP43js.renderBlock.call(void 0, _chunkEGTDJ4PLjs.siteFooterManifest, layout.footer, {
      theme: themeRuntime.tokens,
      themeConfig: theme,
      viewModelOverrides
    })
  ] });
}




exports.Page = Page; exports.Layout = Layout;
//# sourceMappingURL=chunk-P6CDRJN3.js.map