import { Menu } from 'components/Header/header.types';

export const getPathFromUrl = (input?: string) => {
  if (!input) return;
  try {
    const url = new URL(input);
    return url.pathname;
  } catch (error) {
    return input;
  }
};

export const isActivePath = (url?: string) => {
  if (typeof window === 'undefined') return false;
  const path = getPathFromUrl(url);
  if (!path) return false;
  return window.location.pathname.includes(path);
};

export const isActiveParent = (menu?: Menu) => {
  if (!menu || !menu.menuItems) return false;
  for (const menuItem of menu.menuItems) {
    if (!menuItem.subMenus) return false;
    for (const sub of menuItem.subMenus) {
      if (isActivePath(sub.url)) {
        return true;
      }
    }
  }
  return false;
};
