import React from "react";
import { hasAllFeatures as checkFeatures } from "@open-mercato/shared/security/features";
async function fetchFeatureGrants(requestFeatures) {
  const granted = /* @__PURE__ */ new Set();
  if (!requestFeatures.length) return granted;
  let url = "/api/auth/feature-check";
  let headersInit;
  if (typeof window === "undefined") {
    try {
      const { headers: getHeaders } = await import("next/headers");
      const h = await getHeaders();
      const host = h.get("x-forwarded-host") || h.get("host") || "";
      const proto = h.get("x-forwarded-proto") || "http";
      const cookie = h.get("cookie") || "";
      if (host) url = `${proto}://${host}/api/auth/feature-check`;
      headersInit = { cookie };
    } catch {
    }
  }
  try {
    const res = await fetch(url, {
      method: "POST",
      credentials: "include",
      headers: { "content-type": "application/json", ...headersInit || {} },
      body: JSON.stringify({ features: requestFeatures })
    });
    if (res.ok) {
      const data = await res.json().catch(() => ({ granted: [] }));
      if (Array.isArray(data?.granted)) {
        data.granted.forEach((f) => granted.add(f));
      }
    }
  } catch {
  }
  return granted;
}
function buildSettingsSections(entries, sectionOrder) {
  const settingsItems = entries.filter((e) => e.pageContext === "settings");
  const sectionMap = /* @__PURE__ */ new Map();
  const mapSectionItem = (item) => {
    const itemId = item.href.replace(/\//g, "-").slice(1);
    return {
      id: itemId,
      label: item.title,
      labelKey: item.titleKey,
      href: item.href,
      icon: item.icon,
      requireFeatures: void 0,
      order: item.order ?? item.priority ?? 100,
      children: item.children?.map(mapSectionItem)
    };
  };
  for (const item of settingsItems) {
    const sectionId = item.group.toLowerCase().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
    const order = sectionOrder[sectionId] ?? 999;
    if (!sectionMap.has(sectionId)) {
      sectionMap.set(sectionId, {
        id: sectionId,
        label: item.group,
        labelKey: item.groupKey,
        order,
        items: []
      });
    }
    const section = sectionMap.get(sectionId);
    section.items.push(mapSectionItem(item));
  }
  const sections = Array.from(sectionMap.values());
  const sortItems = (items) => {
    items.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
    for (const item of items) {
      if (item.children?.length) sortItems(item.children);
    }
  };
  sections.sort((a, b) => a.order - b.order);
  for (const section of sections) {
    sortItems(section.items);
  }
  return sections;
}
function computeSettingsPathPrefixes(sections) {
  const prefixes = /* @__PURE__ */ new Set();
  const visitItem = (item) => {
    const parts = item.href.split("/");
    const lastSegment = parts[parts.length - 1];
    if (parts.length > 3 && lastSegment !== "settings") {
      prefixes.add(parts.slice(0, -1).join("/"));
    }
    prefixes.add(item.href);
    if (item.children?.length) {
      for (const child of item.children) visitItem(child);
    }
  };
  for (const section of sections) {
    for (const item of section.items) {
      visitItem(item);
    }
  }
  return Array.from(prefixes);
}
function convertToSectionNavGroups(sections, translate) {
  const t = translate || ((key, fallback) => fallback);
  const mapSectionItem = (item) => ({
    id: item.id,
    label: t(item.labelKey, item.label),
    labelKey: item.labelKey,
    href: item.href,
    icon: item.icon,
    order: item.order,
    children: item.children?.map(mapSectionItem)
  });
  return sections.map((section) => ({
    id: section.id,
    label: t(section.labelKey, section.label),
    labelKey: section.labelKey,
    order: section.order,
    items: section.items.map(mapSectionItem)
  }));
}
async function buildAdminNav(modules, ctx, userEntities, translate, options) {
  function capitalize(s) {
    return s.charAt(0).toUpperCase() + s.slice(1);
  }
  function deriveTitleFromPath(p) {
    const seg = p.split("/").filter(Boolean).pop() || "";
    return seg ? seg.split("-").map(capitalize).join(" ") : "Home";
  }
  const entries = [];
  const allRequiredFeatures = /* @__PURE__ */ new Set();
  for (const m of modules) {
    for (const r of m.backendRoutes ?? []) {
      const features = r.requireFeatures;
      if (features && features.length) {
        features.forEach((f) => allRequiredFeatures.add(f));
      }
    }
  }
  let userFeatures = [];
  if (allRequiredFeatures.size > 0) {
    const requestFeatures = Array.from(allRequiredFeatures);
    if (options?.checkFeatures) {
      try {
        const resolved = await options.checkFeatures(requestFeatures);
        if (resolved) {
          userFeatures = Array.from(resolved).filter((feature) => typeof feature === "string" && feature.length > 0);
        }
      } catch {
      }
    } else {
      userFeatures = Array.from(await fetchFeatureGrants(requestFeatures));
    }
  }
  function hasAllFeatures(required) {
    if (!required || required.length === 0) return true;
    return checkFeatures(userFeatures, required);
  }
  for (const m of modules) {
    const groupDefault = capitalize(m.id);
    for (const r of m.backendRoutes ?? []) {
      const href = r.pattern ?? r.path ?? "";
      if (!href || href.includes("[")) continue;
      if (r.navHidden) continue;
      const title = r.title || deriveTitleFromPath(href);
      const titleKey = r.pageTitleKey ?? r.titleKey;
      const group = r.group || groupDefault;
      const groupKey = r.pageGroupKey ?? r.groupKey;
      const groupId = groupKey ?? group;
      const displayGroup = translate ? translate(groupKey, group) : group;
      const displayTitle = translate ? translate(titleKey, title) : title;
      const visible = r.visible ? await Promise.resolve(r.visible(ctx)) : true;
      if (!visible) continue;
      const enabled = r.enabled ? await Promise.resolve(r.enabled(ctx)) : true;
      const required = r.requireRoles || [];
      if (required.length) {
        const roles = ctx.auth?.roles || [];
        const ok = required.some((role) => roles.includes(role));
        if (!ok) continue;
      }
      const features = r.requireFeatures;
      if (features && features.length) {
        const ok = hasAllFeatures(features);
        if (!ok) continue;
      }
      const order = r.order;
      const priority = r.priority ?? order;
      const icon = r.icon;
      const pageContext = r.pageContext;
      entries.push({
        group: displayGroup,
        groupId,
        groupKey,
        groupDefaultName: displayGroup,
        title: displayTitle,
        defaultTitle: displayTitle,
        titleKey,
        href,
        enabled,
        order,
        priority,
        icon,
        pageContext
      });
    }
  }
  const sorted = [...entries].sort((a, b) => a.href.length - b.href.length);
  const byHref = /* @__PURE__ */ new Map();
  const roots = [];
  for (const e of sorted) {
    let parent;
    const segments = e.href.split("/");
    for (let i = segments.length - 1; i >= 2; i--) {
      const candidate = byHref.get(segments.slice(0, i).join("/"));
      if (candidate && candidate !== e && candidate.groupId === e.groupId) {
        parent = candidate;
        break;
      }
    }
    byHref.set(e.href, e);
    if (parent) {
      parent.children = parent.children || [];
      parent.children.push(e);
    } else {
      roots.push(e);
    }
  }
  if (userEntities && userEntities.length > 0) {
    const tableIcon = React.createElement(
      "svg",
      { width: 16, height: 16, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2 },
      React.createElement("rect", { x: 3, y: 4, width: 18, height: 16, rx: 2 }),
      React.createElement("path", { d: "M3 10h18M9 4v16M15 4v16" })
    );
    const userEntitiesLegacyGroupKeys = /* @__PURE__ */ new Set(["settings.sections.dataDesigner", "entities.nav.group"]);
    const userEntitiesItem = entries.find((entry) => entry.href === "/backend/entities/user") ?? entries.find(
      (entry) => entry.titleKey === "entities.nav.userEntities" && typeof entry.groupKey === "string" && userEntitiesLegacyGroupKeys.has(entry.groupKey)
    );
    if (userEntitiesItem) {
      const existingChildren = userEntitiesItem.children || [];
      const dynamicUserEntities = userEntities.map((entity) => ({
        group: userEntitiesItem.group,
        groupId: userEntitiesItem.groupId,
        groupKey: userEntitiesItem.groupKey,
        groupDefaultName: userEntitiesItem.groupDefaultName,
        title: entity.label,
        defaultTitle: entity.label,
        href: entity.href,
        enabled: true,
        order: 1e3,
        // High order to appear at the end
        priority: 1e3,
        icon: tableIcon
      }));
      const merged = [...existingChildren, ...dynamicUserEntities];
      const byHref2 = /* @__PURE__ */ new Map();
      for (const it of merged) {
        if (!byHref2.has(it.href)) byHref2.set(it.href, it);
      }
      userEntitiesItem.children = Array.from(byHref2.values());
    }
  }
  const sortItems = (arr) => {
    arr.sort((a, b) => {
      if (a.groupId !== b.groupId) return a.groupId.localeCompare(b.groupId);
      const ap = a.priority ?? a.order ?? 1e4;
      const bp = b.priority ?? b.order ?? 1e4;
      if (ap !== bp) return ap - bp;
      return a.title.localeCompare(b.title);
    });
    for (const it of arr) if (it.children?.length) sortItems(it.children);
  };
  sortItems(roots);
  return roots;
}
export {
  buildAdminNav,
  buildSettingsSections,
  computeSettingsPathPrefixes,
  convertToSectionNavGroups
};
//# sourceMappingURL=nav.js.map
