---
import type { Menu, VersionPrefix } from '@/config/types';
import type { VersionConfig } from '@/components/patterns/VersionSwitcher/types';
import { Body } from '@/components/primitives';
import { Icon } from 'astro-icon/components';
import { VersionSwitcher } from '@/components/patterns';
import SidebarItemsList from './SidebarItemsList.astro';
import {
  shouldOmitSection,
  collectAllSubmenus,
  submenuContainsCurrentPath,
  calculateInitialActiveLevel,
  groupSubmenusByLevel,
  type SubmenuData,
} from './utils';

interface Props {
  menu: Menu;
  level: number;
  title?: string;
  lang: string;
  currentPath: string;
  basePath?: string;
  versioned?: VersionPrefix[];
  version?: string;
  versions?: VersionConfig[];
  defaultVersion?: string;
  parentId?: string;
}

const {
  menu,
  level,
  lang,
  currentPath,
  basePath = '',
  versioned = [],
  version = '5x',
  versions = [],
  defaultVersion = '5x',
  parentId = 'root',
} = Astro.props;

const submenus: SubmenuData[] = [];
if (level === 0) {
  collectAllSubmenus(menu, level, parentId, basePath, versioned, version, submenus);
}

const submenusByLevel = groupSubmenusByLevel(submenus);
const sortedLevels = Array.from(submenusByLevel.keys()).sort((a, b) => a - b);
const initialActiveLevel =
  level === 0 ? calculateInitialActiveLevel(submenus, currentPath, lang, version) : 0;
---

{
  level === 0 && (
    <div
      class="sidebar-column sidebar-root-column"
      data-nav-level={level}
      data-parent-id={parentId}
      data-initial-active-level={initialActiveLevel}
      aria-hidden="false"
    >
      <nav class="sidebar-nav" aria-label="Main navigation">
        <ul class="sidebar-nav-list">
          {menu.sections
            ?.filter((section) => !shouldOmitSection(section, version))
            .map((section, sectionIndex) => (
              <li class="sidebar-section">
                {section.title && <Body as="h3">{section.title}</Body>}
                <ul class="sidebar-section-list">
                  <SidebarItemsList
                    items={section.items}
                    parentId={parentId}
                    sectionIndex={sectionIndex}
                    currentPath={currentPath}
                    lang={lang}
                    basePath={basePath}
                    versioned={versioned}
                    version={version}
                    variant="root"
                    showIcon={true}
                    targetLevel={level + 1}
                  />
                </ul>
              </li>
            ))}
          <SidebarItemsList
            items={menu.items ?? []}
            parentId={parentId}
            sectionIndex={null}
            currentPath={currentPath}
            lang={lang}
            basePath={basePath}
            versioned={versioned}
            version={version}
            variant="root"
            showIcon={true}
            targetLevel={level + 1}
          />
        </ul>
      </nav>
    </div>
  )
}

{
  level === 0 && sortedLevels.length > 0 && (
    <div class="sidebar-nested">
      {sortedLevels.map((navLevel) => (
        <div
          class="sidebar-column sidebar-nested-column"
          data-nav-level={navLevel}
          aria-hidden="true"
        >
          {submenusByLevel.get(navLevel)?.map((submenu) => {
            const panelHasActiveItem = submenuContainsCurrentPath(
              submenu.menu,
              submenu.basePath,
              submenu.versioned,
              currentPath,
              lang,
              version
            );
            const availableVersions =
              submenu.versioned.length > 0
                ? versions.filter((v) => submenu.versioned.includes(v.id as VersionPrefix))
                : [];
            return (
              <div
                class:list={[
                  'sidebar-nav-panel',
                  panelHasActiveItem && 'sidebar-nav-panel--active',
                ]}
                data-parent-id={submenu.id}
                aria-hidden="true"
              >
                {availableVersions.length > 0 && (
                  <VersionSwitcher
                    class="sidebar-version-switcher"
                    versions={availableVersions}
                    defaultVersion={defaultVersion}
                    currentPath={currentPath}
                    aria-label="Select documentation version"
                    data-version-switcher
                  />
                )}
                <nav class="sidebar-nav" aria-label={`${submenu.title} navigation`}>
                  <button
                    class="sidebar-nav-back"
                    type="button"
                    aria-label={`Go back from ${submenu.title}`}
                    data-back-button
                    data-target-level={navLevel - 1}
                  >
                    <Icon
                      name="fluent:arrow-export-rtl-20-regular"
                      size="16"
                      color="var(--color-icon-primary)"
                      aria-hidden="true"
                    />
                    <Body as="span" weight="bold" vMargin={false}>
                      {submenu.title}
                    </Body>
                  </button>
                  <div class="sidebar-nav-content">
                    {submenu.menu.sections
                      ?.filter((section) => !shouldOmitSection(section, version))
                      .map((section, sectionIndex) => (
                        <div class="sidebar-section">
                          {section.title && (
                            <Body as="h3" weight="bold" aria-label={`Section: ${section.title}`}>
                              {section.title}
                            </Body>
                          )}
                          <ul class="sidebar-section-list">
                            <SidebarItemsList
                              items={section.items}
                              parentId={submenu.id}
                              sectionIndex={sectionIndex}
                              currentPath={currentPath}
                              lang={lang}
                              basePath={submenu.basePath}
                              versioned={submenu.versioned}
                              version={version}
                              variant="nested"
                              showIcon={false}
                              targetLevel={navLevel + 1}
                            />
                          </ul>
                        </div>
                      ))}
                    {submenu.menu.items && submenu.menu.items.length > 0 && (
                      <ul class="sidebar-section-list">
                        <SidebarItemsList
                          items={submenu.menu.items}
                          parentId={submenu.id}
                          sectionIndex={null}
                          currentPath={currentPath}
                          lang={lang}
                          basePath={submenu.basePath}
                          versioned={submenu.versioned}
                          version={version}
                          variant="nested"
                          showIcon={false}
                          targetLevel={navLevel + 1}
                        />
                      </ul>
                    )}
                  </div>
                </nav>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  )
}
