---
// Menu tree from shared/data/docs.json.
import Subheader from '@ui/Subheader.astro'
import docs from '@data/docs.json'
import { pathSlug as slug } from '@shared/lib/string-format'

interface MenuLeaf {
  title: string
  url: string
}

interface MenuGroup extends MenuLeaf {
  children?: MenuLeaf[]
}

interface MenuSection {
  title: string
  children?: MenuGroup[]
}

interface Props {
  /** Page URL in the docs namespace (equivalent of page.url), e.g. "/ui/components/alert/". */
  url: string
}

const { url } = Astro.props
const menu = docs.menu as MenuSection[]
---

<!-- BEGIN DOCS MENU -->
<nav class="space-y space-y-5" id="menu">
  {
    menu.map((level1) => (
      <div>
        <Subheader class="mb-2">{level1.title}</Subheader>
        {level1.children && level1.children.length > 0 && (
          <nav class="nav nav-vertical">
            {level1.children.map((level2) => {
              const hasChildren = Boolean(level2.children && level2.children.length > 0)
              // Expanded only for the group's own page or one of its direct children —
              // a prefix check would also expand "Introduction" on /ui/getting-started/frameworks/* pages.
              const expanded = url === level2.url || Boolean(level2.children?.some((child) => child.url === url))
              return (
                <div>
                  {/* href/data-bs-* only when the element has children */}
                  {hasChildren ? (
                    <a class={`nav-link${expanded ? ' active' : ''}`} href={level2.url} data-bs-toggle="collapse" data-bs-target={`#collapse-${slug(level2.url)}`} aria-expanded={expanded ? 'true' : 'false'}>
                      {level2.title} <span class="nav-link-toggle" />
                    </a>
                  ) : (
                    <a class={`nav-link${expanded ? ' active' : ''}`}>{level2.title}</a>
                  )}

                  {hasChildren && (
                    <nav class={`nav nav-vertical collapse${expanded ? ' show' : ''}`} id={`collapse-${slug(level2.url)}`}>
                      {level2.children!.map((level3) => (
                        <div>
                          <a class={`nav-link${url === level3.url ? ' active' : ''}`} href={level3.url}>
                            {level3.title}
                          </a>
                        </div>
                      ))}
                    </nav>
                  )}
                </div>
              )
            })}
          </nav>
        )}
      </div>
    ))
  }
</nav>
<!-- END DOCS MENU -->
