import { NavigationItem } from "@/src/entities/models/navigation-item.model"; import { NavigationItemRepositoryImpl } from "@/src/infrastructure/repositories/navigation-item.repository.impl"; import { useEffect, useState } from "react"; export function useNavigationItem() { const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchNavigation = async () => { try { const repository = new NavigationItemRepositoryImpl(); const navItems = await repository.findAll(); // Convert flat structure to tree const buildNavigationTree = ( items: NavigationItem[], parentPath: string = "" ): any[] => { return items .filter((item) => { const itemPath = item.path.split("/").filter(Boolean); const parentPathParts = parentPath.split("/").filter(Boolean); return ( itemPath.length === parentPathParts.length + 1 && itemPath.slice(0, parentPathParts.length).join("/") === parentPathParts.join("/") ); }) .map((item) => ({ ...item, subItems: buildNavigationTree(items, item.path), })) .sort((a, b) => a.orderSeq - b.orderSeq); }; const navigationTree = buildNavigationTree(navItems); setItems(navigationTree); } catch (err) { setError( err instanceof Error ? err.message : "Failed to fetch navigation" ); } finally { setLoading(false); } }; fetchNavigation(); }, []); return { items, loading, error }; }