---
import { getCollection } from 'astro:content'

import { Navigation as ReactNav } from './Navigation.tsx'
import { TextContentEntry } from './NavEntry.tsx'

import { content } from '../content'

import { config } from '../../pf-docs.config.mjs'

const collections = await Promise.all(
  content.map(
    async (entry) => await getCollection(entry.name as 'textContent'),
  ),
)

const navDataRaw = collections.flat();
const uniqueSections = new Set(navDataRaw.map((entry) => entry.data.section as string));

const [orderedSections, unorderedSections] = Array.from(uniqueSections).reduce(
    (acc, section) => {
      if (!config.navSectionOrder) {
        acc[1].push(section)
        return acc
      }

      const index = config.navSectionOrder.indexOf(section)
      if (index > -1) {
        acc[0][index] = section
      } else {
        acc[1].push(section)
      }
      return acc
    },
    [[], []] as [string[], string[]],
  )

const sortedSections = [...orderedSections, ...unorderedSections.sort()]
const navData = sortedSections.map((section) => {
  const entries = navDataRaw
    .filter((entry) => entry.data.section === section)
    .map(entry => ({ id: entry.id, data: { id: entry.data.id, section, sortValue: entry.data.sortValue, subsection: entry.data.subsection }} as TextContentEntry))

  const uniqueEntries = [
    ...entries
      .reduce((map, entry) => {
        if (!map.has(entry.data.id)) {
          map.set(entry.data.id, entry)
        }
        return map
      }, new Map())
      .values(),
  ]
  

    // Sort alphabetically, unless a sort value is specified in the frontmatter
  const sortedUniqueEntries = uniqueEntries.sort((a, b) => {
    if (a.data.sortValue || b.data.sortValue) {
      const aSortOrder = a.data.sortValue || 50
      const bSortOrder = b.data.sortValue || 50

      return aSortOrder - bSortOrder
    }
    return a.data.id.localeCompare(b.data.id)
  })

  return sortedUniqueEntries
})

---

<ReactNav client:only="react" navData={navData} transition:animate="fade" />
