---
import MobileMenuFooter from 'virtual:starlight/components/MobileMenuFooter';
import SidebarPersister from '@astrojs/starlight/components/SidebarPersister.astro';
import SidebarSublist from '@astrojs/starlight/components/SidebarSublist.astro';
import versions from '../data/docs-versions.json';
import { docsRoute, docsTargetHref } from '../docs-path';

const { sidebar } = Astro.locals.starlightRoute;
const pathname = Astro.url.pathname;
const route = docsRoute(pathname);
const scopedSidebar = route.target === 'stable' ? sidebar : rewriteSidebar(sidebar);

function rewriteSidebar(entries) {
  return entries.flatMap((entry) => {
    if (entry.type === 'link') {
      const linkRoute = docsRoute(entry.href);
      if (!linkRoute.isDocs) return [entry];
      if (linkRoute.target !== 'stable') {
        return linkRoute.target === route.target
          ? [{ ...entry, isCurrent: samePath(entry.href, pathname) }]
          : [];
      }

      const localeKey = route.locale ?? 'root';
      const availablePages = versions.scopes[route.target]?.locales[localeKey] ?? [];
      if (!availablePages.includes(linkRoute.page)) return [];

      const href = docsTargetHref({ ...linkRoute, locale: route.locale }, route.target, versions.scopes);
      return [{ ...entry, href, isCurrent: samePath(href, pathname) }];
    }

    const rewrittenEntries = rewriteSidebar(entry.entries);
    if (rewrittenEntries.length === 0) return [];
    return [{ ...entry, entries: rewrittenEntries }];
  });
}

function samePath(left, right) {
  return stripTrailingSlash(left) === stripTrailingSlash(right);
}

function stripTrailingSlash(path) {
  return path.length > 1 ? path.replace(/\/$/, '') : path;
}
---

<SidebarPersister>
  <SidebarSublist sublist={scopedSidebar} />
</SidebarPersister>

<div class="md:sl-hidden">
  <MobileMenuFooter />
</div>
