import { useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { navTree as initialNavTree, MainNode } from '../nav/tree';

function getCurrentNavTree(): MainNode[] {
  const tree = window.WNW_NAV_TREE;
  return Array.isArray(tree) && tree.length > 0
    ? (tree as MainNode[])
    : initialNavTree;
}

export function useActiveSection(): { main: MainNode; all: MainNode[] } {
  const { pathname } = useLocation();
  const [navTree, setNavTree] = useState<MainNode[]>(getCurrentNavTree);

  useEffect(() => {
    const handleNavUpdate = () => setNavTree(getCurrentNavTree());
    window.addEventListener('woonoow:navigation-updated', handleNavUpdate);
    return () => window.removeEventListener('woonoow:navigation-updated', handleNavUpdate);
  }, []);

  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;
    }
    
    // Special case: /coupons should match marketing section
    if (pathname === '/coupons' || pathname.startsWith('/coupons/')) {
      const marketingNode = navTree.find(n => n.key === 'marketing');
      if (marketingNode) return marketingNode;
    }
    
    // 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 : [];

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