// Dynamic SPA menu tree (reads from backend via window.WNW_NAV_TREE)
export const NAV_TREE_VERSION = 'navTree-2025-10-28-dynamic';

export type NodeMode = 'spa' | 'bridge';
export type SubItem = {
  label: string;
  mode: NodeMode;
  path?: string;   // for SPA routes
  href?: string;   // for classic admin URLs
  exact?: boolean;
};
export type MainKey = string; // Changed from union to string to support dynamic keys
export type MainNode = {
  key: MainKey;
  label: string;
  path: string; // main path
  icon?: string; // lucide icon name
  children: SubItem[]; // will be frozen at runtime
};

/**
 * Get navigation tree from backend (SINGLE SOURCE OF TRUTH)
 * Backend (PHP) is more flexible - can check WooCommerce settings, be extended by addons, etc.
 */
function getNavTreeFromBackend(): MainNode[] {
  const backendTree = (window as any).WNW_NAV_TREE;
  
  if (!Array.isArray(backendTree) || backendTree.length === 0) {
    console.error('WNW_NAV_TREE not found! Navigation will be empty.');
    return [];
  }
  
  return backendTree;
}

/**
 * Deep freeze tree for immutability
 */
function deepFreezeTree(src: MainNode[]): MainNode[] {
  return src.map((n) =>
    Object.freeze({
      ...n,
      children: Object.freeze([...(n.children ?? [])]),
    }) as MainNode
  ) as unknown as MainNode[];
}

/**
 * Export the navigation tree (reads from backend, falls back to static)
 */
export const navTree: MainNode[] = Object.freeze(
  deepFreezeTree(getNavTreeFromBackend())
) as unknown as MainNode[];