/**
 * TrendApp — Shell (Router hash + Viewport + BottomNav)
 *
 * Router: hash-based, com stack de navegação para "voltar".
 *   #/inicio              (tab)
 *   #/extrato             (dentro de Início)
 *   #/lancamento/:id
 *   #/vendas              (tab)
 *   #/pedidos             (dentro de Vendas)
 *   #/pedido/:id
 *   #/clientes            (tab)
 *   #/cliente/:id
 *   #/recuperar
 *   #/perfil              (tab)
 *   #/login
 *   #/recuperar-senha
 */

// (React hooks declarados uma vez em logo.jsx)

// ─── Router ────────────────────────────────────────────────────────────────
const RouterCtx = createContext(null);

function parseRoute(hash) {
  const clean = (hash || '#/welcome').replace(/^#\/?/, '');
  const [path, ...rest] = clean.split('?');
  const parts = path.split('/').filter(Boolean);
  return { name: parts[0] || 'welcome', params: parts.slice(1), raw: path };
}

// Estas rotas são as ABAS principais — apenas 4 conforme §5 do doc
const MAIN_TABS = ['inicio', 'vendas', 'clientes', 'perfil'];

function RouterProvider({ children }) {
  const [route, setRoute] = useState(() => parseRoute(location.hash));
  const stackRef = useRef([]);   // pilha de rotas para voltar
  const tabRef = useRef({ inicio: 'inicio', vendas: 'vendas', clientes: 'clientes', perfil: 'perfil' });

  useEffect(() => {
    // Redireciona rota vazia → welcome
    if (!location.hash || location.hash === '#') location.hash = '#/welcome';

    const handler = () => {
      const r = parseRoute(location.hash);
      setRoute(r);
    };
    window.addEventListener('hashchange', handler);
    handler();
    return () => window.removeEventListener('hashchange', handler);
  }, []);

  const go = useCallback((path, { replace = false, push = true } = {}) => {
    const target = path.startsWith('#') ? path : `#${path.startsWith('/') ? '' : '/'}${path}`;
    if (push && !replace) stackRef.current.push(location.hash);
    if (replace) location.replace(target); else location.hash = target;
  }, []);

  const back = useCallback((fallback = '/inicio') => {
    if (stackRef.current.length > 0) {
      const prev = stackRef.current.pop();
      if (prev) location.hash = prev;
      else location.hash = `#${fallback}`;
    } else {
      location.hash = `#${fallback}`;
    }
  }, []);

  const gotoTab = useCallback((tab) => {
    stackRef.current = [];
    location.hash = `#/${tab}`;
  }, []);

  const activeTab = useMemo(() => {
    if (MAIN_TABS.includes(route.name)) return route.name;
    // Sub-rotas mapeadas para a aba pai
    if (['extrato', 'lancamento'].includes(route.name)) return 'inicio';
    if (['pedidos', 'pedido'].includes(route.name)) return 'vendas';
    if (['cliente', 'recuperar'].includes(route.name)) return 'clientes';
    return route.name;
  }, [route.name]);

  const value = useMemo(() => ({ route, go, back, gotoTab, activeTab }), [route, go, back, gotoTab, activeTab]);
  return <RouterCtx.Provider value={value}>{children}</RouterCtx.Provider>;
}

function useRouter() {
  return useContext(RouterCtx);
}

// ─── BottomNav ─────────────────────────────────────────────────────────────
function BottomNav() {
  const { activeTab, gotoTab } = useRouter();
  useLucide([activeTab]);

  const ITEMS = [
    { id: 'inicio',   label: 'Início',   icon: 'home' },
    { id: 'vendas',   label: 'Vendas',   icon: 'trending-up' },
    { id: 'clientes', label: 'Clientes', icon: 'users' },
    { id: 'perfil',   label: 'Perfil',   icon: 'user-round' },
  ];

  return (
    <nav className="bottom-nav" role="navigation" aria-label="Navegação principal">
      {ITEMS.map(item => (
        <button
          key={item.id}
          className="bottom-nav-item"
          data-active={activeTab === item.id ? 'true' : 'false'}
          onClick={() => gotoTab(item.id)}
          aria-label={item.label}
          aria-current={activeTab === item.id ? 'page' : undefined}
        >
          <span className="indicator" />
          <Icon name={item.icon} size={22} />
          <span>{item.label}</span>
        </button>
      ))}
    </nav>
  );
}

// ─── Assign ────────────────────────────────────────────────────────────────
Object.assign(window, {
  RouterProvider, useRouter, BottomNav, parseRoute, MAIN_TABS,
});
