// what the window chrome needs from the docs: the address bar's crumbs and menus, and the
// list of every page in nav order.

import { SECTIONS, INDEX_ICON, type NavSection } from "./nav";
import { urlFor, type Doc } from "./docs";

/** the site's one line about itself, for the home page and its link preview */
export const HOME_DESCRIPTION = "docs for hydrant, an AT Protocol indexer and relay built on fjall";

export interface MenuItem {
  label: string;
  href: string;
  icon: string;
  current?: boolean;
  /** the current page's own sections, listed under it */
  children?: { label: string; href: string }[];
}

export interface Crumb {
  label: string;
  href?: string;
  icon?: string;
  current?: boolean;
  /** what the ▸ after this crumb opens: the level below it */
  menu?: MenuItem[];
}

export interface MenuGroup {
  title: string;
  items: MenuItem[];
}

/** a section with a README goes to it, the others to their box on the home grid */
export function sectionHref(s: NavSection): string {
  return s.index ? urlFor(s.index) : `/#${s.id}`;
}

function sectionPages(s: NavSection, currentId?: string): MenuItem[] {
  const pages = s.pages.map((p) => ({ label: p.label, href: urlFor(p.doc), icon: p.icon, current: p.doc === currentId }));
  return s.index ? [{ label: "overview", href: urlFor(s.index), icon: INDEX_ICON, current: s.index === currentId }, ...pages] : pages;
}

/** every page in nav order; the current one carries its own sections */
export function allPages(doc?: Doc): MenuGroup[] {
  const children = doc?.settings
    ? doc.settings.map((s) => ({ label: s.title, href: `#${s.id}` }))
    : doc?.headings.filter((h) => h.depth === 2).map((h) => ({ label: h.text, href: `#${h.id}` }));
  return SECTIONS.map((s) => ({
    title: s.title,
    items: sectionPages(s, doc?.id).map((it) => (it.current ? { ...it, children } : it)),
  }));
}

export function crumbsFor(doc?: Doc): Crumb[] {
  const current = doc?.place.section;
  const sections = SECTIONS.map((s) => ({ label: s.title, href: sectionHref(s), icon: s.index ? INDEX_ICON : s.pages[0].icon, current: s === current }));
  const home: Crumb = { label: "all pages", href: "/", icon: "hydrant", current: !doc, menu: sections };
  if (!doc) return [home];
  const section: Crumb = { label: current!.title, href: sectionHref(current!), menu: sectionPages(current!, doc.id) };
  if (doc.place.isIndex) return [home, { ...section, href: undefined, current: true }];
  return [home, section, { label: doc.place.label, current: true }];
}
