---
import GlossaryLayout from "../../layouts/GlossaryLayout.astro";
import GlossaryAside from "../../components/GlossaryAside.astro";
import GlossaryRelationCards from "../../components/GlossaryRelationCards.astro";
import GlossaryEntryLegacyNote from "../../components/GlossaryEntryLegacyNote.astro";
import GlossaryEntryHero from "../../components/GlossaryEntryHero.astro";
import GlossaryEntryBody from "../../components/GlossaryEntryBody.astro";
import GlossaryEntryStickySync from "../../components/GlossaryEntryStickySync.astro";
import { getCollection, render } from "astro:content";
import {
  getDisplayDomain,
  getDisplayFamily,
  getDisplayLevel,
  getRelationBlocks,
  normalizeGlossarySlug,
} from "../../lib/glossary";

export async function getStaticPaths() {
  const entries = await getCollection("glossaire");
  const paths = [];
  const seen = new Set();

  for (const entry of entries) {
    const canonicalSlug = normalizeGlossarySlug(entry.id);

    if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(canonicalSlug)) continue;

    const addPath = (rawSlug) => {
      const requestedSlug = normalizeGlossarySlug(rawSlug);

      if (!requestedSlug) return;
      if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(requestedSlug)) return;
      if (seen.has(requestedSlug)) return;

      seen.add(requestedSlug);
      paths.push({
        params: { slug: requestedSlug },
        props: {
          entry,
          requestedSlug,
          canonicalSlug,
        },
      });
    };

    addPath(canonicalSlug);

    for (const alias of entry.data.urlAliases ?? []) {
      addPath(alias);
    }
  }

  return paths;
}

const { entry, requestedSlug, canonicalSlug } = Astro.props;
const allEntries = await getCollection("glossaire");
const { Content } = await render(entry);

const isAliasRoute = requestedSlug !== canonicalSlug;
const canonicalHref = `/glossaire/${canonicalSlug}/`;

const relationBlocks = getRelationBlocks(entry, allEntries);

const displayFamily = getDisplayFamily(entry);
const displayDomain = getDisplayDomain(entry);
const displayLevel = getDisplayLevel(entry);
---

<GlossaryLayout
  title={entry.data.title}
  version={entry.data.version}
  stickyMode="glossary-entry"
>
  <Fragment slot="aside">
    <GlossaryAside currentEntry={entry} allEntries={allEntries} />
  </Fragment>

  {isAliasRoute && (
    <GlossaryEntryLegacyNote
      canonicalHref={canonicalHref}
      term={entry.data.term}
    />
  )}

  <GlossaryEntryHero
    term={entry.data.term}
    definitionShort={entry.data.definitionShort}
    displayFamily={displayFamily}
    displayDomain={displayDomain}
    displayLevel={displayLevel}
    mobilizedAuthors={entry.data.mobilizedAuthors ?? []}
    comparisonTraditions={entry.data.comparisonTraditions ?? []}
  />

  <GlossaryEntryBody>
    <Content />
  </GlossaryEntryBody>

  <GlossaryRelationCards relationBlocks={relationBlocks} />

  <GlossaryEntryStickySync />
</GlossaryLayout>