// src/lib/nav/nav-types.ts

export interface NavTab {
  path: string;
  titleHe: string;
  titleEn: string;
}

export interface NavPage<G extends string = string> {
  path: string;
  titleHe: string;
  titleEn: string;
  group: G;
  /** Empty array = no tab strip rendered for this page. */
  tabs: NavTab[];
}

export interface NavGroup<G extends string = string> {
  id: G;
  labelHe: string;
  labelEn: string;
  pages: NavPage<G>[];
}

export interface NavContext<G extends string = string> {
  group: NavGroup<G>;
  page: NavPage<G>;
  /** Undefined when URL matches the page itself (not a tab path). */
  activeTab: NavTab | undefined;
}

/**
 * Find the nav context for a given pathname.
 *
 * Algorithm:
 * 1. Exact match on a page path → that page.
 * 2. Exact match on a tab path → that tab's parent page.
 * 3. Longest prefix match (excluding '/', '/admin', '/vendor' roots) → detail pages like /admin/vendors/123.
 * 4. Fallback → first page of first group (dashboard).
 */
export function findNavContext<G extends string>(
  pathname: string,
  nav: readonly NavGroup<G>[],
): NavContext<G> | undefined {
  if (!nav.length) return undefined;

  // 1. Exact match on page path
  for (const group of nav) {
    for (const page of group.pages) {
      if (pathname === page.path) {
        return { group, page, activeTab: undefined };
      }
    }
  }

  // 2. Exact match on tab path
  for (const group of nav) {
    for (const page of group.pages) {
      const tab = page.tabs.find((t) => t.path === pathname);
      if (tab) {
        return { group, page, activeTab: tab };
      }
    }
  }

  // 3. Longest prefix match for detail pages (e.g. /admin/vendors/123)
  //    A root path (depth <= 1 after stripping leading slash) is excluded from prefix matching
  //    to prevent '/' or '/admin' from matching everything.
  let best: NavContext<G> | undefined;
  for (const group of nav) {
    for (const page of group.pages) {
      const depth = page.path.replace(/^\//, '').split('/').length;
      if (depth >= 2 && pathname.startsWith(page.path + '/')) {
        if (!best || page.path.length > best.page.path.length) {
          best = { group, page, activeTab: undefined };
        }
      }
    }
  }
  if (best) return best;

  // 4. Fallback to first page (dashboard)
  const fallbackGroup = nav[0]!;
  const fallbackPage = fallbackGroup.pages[0]!;
  return { group: fallbackGroup, page: fallbackPage, activeTab: undefined };
}
