import './SkipLinks.css'
import onFind from './dom/onFind'
import { focusRegionManager } from './FocusRegions'
import create from './dom/create'
import { localizeShortcut } from './platform'

onFind('.aria--skiptoContent', (originalButton: HTMLElement) => {
  let nav: HTMLElement | null = null
  let list: HTMLElement | null = null
  let note: HTMLElement | null = null
  let lastRegionKey = ''

  const skipToPrefix = window.BRIGHTSPOT?.ui.tooltips.skipLinks.heading

  originalButton.addEventListener('focus', () => {
    const layer = focusRegionManager.getTopLayer()
    const regions = focusRegionManager.getVisibleRegions(layer)

    // Grab the visible regions and filter for those with labels
    const labeledRegions = regions
      .map((config) => ({
        config,
        label: focusRegionManager.getRegionLabel(config),
      }))
      .filter(
        (entry): entry is { config: typeof entry.config; label: string } =>
          entry.label !== null,
      )

    // No labeled regions — leave the original button as-is
    if (labeledRegions.length === 0) return

    // Skip rebuild if the set of visible labeled regions hasn't changed
    const regionKey = labeledRegions
      .map((r) => `${r.config.id}:${r.label}`)
      .join('|')
    const needsRebuild = regionKey !== lastRegionKey

    // Build the panel shell once
    if (!nav) {
      nav = create('nav', {
        className: 'SkipLinks',
        'aria-label': skipToPrefix,
      })

      const heading = create('h2', {
        className: 'SkipLinks-heading',
        textContent: skipToPrefix,
      })

      const rawSkipNote = window.BRIGHTSPOT?.ui.tooltips.skipLinks.note
      const skipNote = rawSkipNote ?? ''
      note = create('p', {
        className: 'SkipLinks-note',
        textContent: localizeShortcut(skipNote),
      })

      list = create('ul', {
        className: 'SkipLinks-list',
      })

      nav.append(heading, note, list)
      originalButton.insertAdjacentElement('beforebegin', nav)
    }

    // Rebuild links only when regions have changed
    if (needsRebuild && list) {
      lastRegionKey = regionKey
      list.innerHTML = ''

      for (const { config, label } of labeledRegions) {
        const li = create('li')
        const link = create('button', {
          className: 'SkipLinks-link',
          type: 'button',
          textContent: label,
          'aria-label': `${skipToPrefix} ${label}`,
        })
        link.addEventListener('click', () => {
          if (!config.element.isConnected) return
          focusRegionManager.focusRegion(config, document.body)
        })
        li.append(link)
        list.append(li)
      }
    }

    // Hide the original button and move focus to the first link
    originalButton.hidden = true
    nav.removeAttribute('aria-hidden')
    const firstLink = nav.querySelector<HTMLElement>('.SkipLinks-link')
    firstLink?.focus()
  })

  // Dismiss with Escape key
  document.addEventListener('keydown', (e) => {
    if (!nav || e.key !== 'Escape') return
    if (nav.contains(document.activeElement)) {
      originalButton.hidden = false
      originalButton.focus()
    }
  })

  // When focus leaves the panel, re-show the original button for next time
  document.addEventListener('focusin', (e) => {
    if (!nav) return
    if (!nav.contains(e.target as Node)) {
      originalButton.hidden = false
      nav.setAttribute('aria-hidden', 'true')
    }
  })
})
