'use client';

import { NavItem } from '@/config/navigation';
import { usePathname } from 'next/navigation';
import { useLocale } from 'next-intl';

export const useActiveNavItem = (item: NavItem) => {
  const path = usePathname();
  const locale = useLocale();
  const prefixedHref = `/${locale}${item.href}`;

  const normalize = (url: string) => url.replace(/\/$/, '');
  const currentPath = normalize(path);
  const target = normalize(prefixedHref);

  const hasActiveChild = item.children
    ? item.children.some((child) => currentPath.startsWith(normalize(`/${locale}${child.href}`)))
    : false;

  const isActive =
    target === `/${locale}` ? currentPath === `/${locale}` : currentPath.startsWith(target) || hasActiveChild;

  const isChildActive = (href: string) => currentPath === `/${locale}${href}`;

  return { isActive, isChildActive };
};
