import { useLocation } from 'react-router-dom';
import { navTree, MainNode, NAV_TREE_VERSION } from '../nav/tree';

export function useActiveSection(): { main: MainNode; all: MainNode[] } {
  const { pathname } = useLocation();

  function pick(): MainNode {
    // Special case: /settings should match settings section
    if (pathname === '/settings' || pathname.startsWith('/settings/')) {
      const settingsNode = navTree.find(n => n.key === 'settings');
      if (settingsNode) return settingsNode;
    }
    
    // Try to find section by matching path prefix
    for (const node of navTree) {
      if (node.path === '/') continue; // Skip dashboard for now
      if (pathname.startsWith(node.path)) {
        return node;
      }
    }
    
    // Fallback to dashboard
    return navTree.find(n => n.key === 'dashboard') || navTree[0];
  }

  const main = pick();
  const children = Array.isArray(main.children) ? main.children : [];

  // Debug: ensure we are using the latest tree module (driven by PHP-localized window.wnw.isDev)
  const isDev = Boolean((window as any).wnw?.isDev);

  return { main: { ...main, children }, all: navTree } as const;
}