---
import type { MenuItem, VersionPrefix } from '@/config/types';
import SidebarNavItem from './SidebarNavItem.astro';
import {
  isLink,
  hasSubmenu,
  filterItems,
  getItemId,
  resolveHref,
  normalizePath,
  submenuContainsCurrentPath,
} from './utils';

interface Props {
  items: MenuItem[];
  parentId: string;
  sectionIndex: number | null;
  currentPath: string;
  lang: string;
  basePath: string;
  versioned: VersionPrefix[];
  version: string;
  variant: 'root' | 'nested';
  showIcon?: boolean;
  targetLevel: number;
}

const {
  items,
  parentId,
  sectionIndex,
  currentPath,
  lang,
  basePath,
  versioned,
  version,
  variant,
  showIcon = false,
  targetLevel,
} = Astro.props;

const filteredItems = filterItems(items, version);
---

{
  filteredItems
    .filter((item) => isLink(item) || hasSubmenu(item))
    .map((item, itemIndex) => {
      const itemId = getItemId(parentId, sectionIndex, itemIndex);
      const itemHref = item.href;

      const itemVersioned = item.submenu?.versioned ?? versioned;
      const itemBasePath = item.submenu?.basePath ?? basePath;

      const href = itemHref
        ? resolveHref(itemHref, lang, itemBasePath, itemVersioned, version)
        : '';

      const isActive =
        hasSubmenu(item) && variant === 'root'
          ? submenuContainsCurrentPath(
              item.submenu,
              itemBasePath,
              itemVersioned,
              currentPath,
              lang,
              version
            )
          : href
            ? normalizePath(currentPath) === normalizePath(href)
            : false;

      if (hasSubmenu(item)) {
        return (
          <SidebarNavItem
            item={item}
            href={href}
            isActive={isActive}
            variant={variant}
            type="submenu"
            submenuId={`submenu-${itemId}`}
            targetLevel={targetLevel}
            showIcon={showIcon}
          />
        );
      }

      return (
        <SidebarNavItem
          item={item}
          href={href}
          isActive={isActive}
          variant={variant}
          type="link"
          showIcon={showIcon}
        />
      );
    })
}
