/* global location */
function deselectAndAddLength (l) {
  return Object.assign(l, { selected: false, length: l.value?.replace?.(/\.html.*/, '')?.length ?? 0 })
}

export default function markSelection (links) {
  const payload = [...links]
  for (const link of payload) {
    link.selected = false // Reset selection.
    payload.push(...(link.children ?? [])) // Go deeper.
    const url = new URL(link.value, location)
    // Select all links on the current path except for hash links.
    link.selected = !url.href.includes('#') && location.href.startsWith(url.href.replace(/\.html.*/, ''))
  }

  // Make sure only one first level link is selected (the longest = most specific).
  const longestSelectedLink = links.filter(l => l.selected).map(deselectAndAddLength).sort((a, b) => a.length - b.length).pop() ?? {}
  longestSelectedLink.selected = true
}
