/**
 * Get the active top-level parent for the current route. Used to drive the vertical subsidebar:
 * subsidebar shows children of the active top-level item (e.g. Settings), never the root container.
 *
 * @param {Object} rootNode - The root menu node (first element of nav tree); has .items = top-level entries
 * @param {String} routePath - Current route path (e.g. route.path)
 * @returns {{ parent: Object, items: Array, parentPath: string }|null} parentPath is item.to or ''
 */
export function getActiveTopLevelParent(rootNode, routePath) {
  if (!routePath || !rootNode?.items?.length) return null;
  const normalizedPath = routePath.replace(/\/$/, "") || "/";
  for (const item of rootNode.items) {
    if (item.separator || item.header) continue;
    const itemPath = (item.to || "").replace(/\/$/, "") || "";
    if (
      itemPath &&
      (normalizedPath === itemPath || normalizedPath.startsWith(itemPath + "/"))
    ) {
      return {
        parent: item,
        items: item.items || [],
        parentPath: item.to || "",
      };
    }
    const children = item.items || [];
    for (const child of children) {
      const childPath = (child.to || "").replace(/\/$/, "") || "";
      if (
        childPath &&
        (normalizedPath === childPath ||
          normalizedPath.startsWith(childPath + "/"))
      ) {
        return { parent: item, items: children, parentPath: item.to || "" };
      }
    }
  }
  return null;
}

/**
 * Get submenu context for current route: { items, parentPath } when route is under a nested
 * parent with 2+ children (vertical submenu), else null. Single source for "are we in submenu?".
 * @param {Array} menuItems - Menu items array
 * @param {String} routePath - Current route path (e.g. route.path)
 * @param {String} parentPath - Parent path for nested items
 * @param {Number} depth - Current depth (0 = root)
 * @returns {{ items: Array, parentPath: string }|null}
 */
export function getSubmenuContextForRoute(
  menuItems,
  routePath,
  parentPath = "",
  depth = 0,
) {
  if (!routePath || !menuItems) return null;

  for (const item of menuItems) {
    if (item.separator || item.header) continue;

    const itemPath = item.path ? parentPath + item.path : item.to || "";
    if (!itemPath) continue;

    const hasSubmenu = item.items && item.items.length > 1 && depth > 0;
    if (hasSubmenu) {
      if (routePath === itemPath || routePath.startsWith(itemPath + "/")) {
        return { items: item.items, parentPath: itemPath };
      }
      for (const child of item.items) {
        const childPath = child.to || itemPath + (child.path || "");
        if (routePath === childPath || routePath.startsWith(childPath + "/")) {
          return { items: item.items, parentPath: itemPath };
        }
      }
    }

    if (item.items) {
      const found = getSubmenuContextForRoute(
        item.items,
        routePath,
        itemPath,
        depth + 1,
      );
      if (found) return found;
    }
  }
  return null;
}

/**
 * Get breadcrumb segments (label + optional path) for current route by walking the menu tree.
 * Last segment has no `to` so the current page is not clickable.
 * @param {Array} menuItems - Menu items array
 * @param {String} targetPath - Current route path (e.g. route.path)
 * @param {String} parentPath - Parent path for nested items
 * @param {{ label: string, to?: string }[]} breadcrumbPath - Accumulated segments
 * @returns {{ label: string, to?: string }[]|null} - Array of segments from root to current route, or null
 */
export function getBreadcrumbForRoute(
  menuItems,
  targetPath,
  parentPath = "",
  breadcrumbPath = [],
) {
  if (!targetPath || !menuItems) return null;

  const normalizedTarget = targetPath.replace(/\/$/, "") || "/";

  for (const item of menuItems) {
    if (item.separator || item.header) continue;

    const itemPath =
      (item.path ? parentPath + item.path : item.to || "").replace(/\/$/, "") ||
      "/";
    const currentBreadcrumb = [...breadcrumbPath];
    if (item.label) currentBreadcrumb.push({ label: item.label, to: itemPath });

    if (
      normalizedTarget === itemPath ||
      (item.to && normalizedTarget === (item.to.replace(/\/$/, "") || "/"))
    ) {
      if (currentBreadcrumb.length)
        currentBreadcrumb[currentBreadcrumb.length - 1] = {
          label: currentBreadcrumb[currentBreadcrumb.length - 1].label,
        };
      return currentBreadcrumb;
    }
    if (item.items) {
      const found = getBreadcrumbForRoute(
        item.items,
        targetPath,
        itemPath,
        currentBreadcrumb,
      );
      if (found) return found;
    }
  }
  return null;
}
