import onFind from './dom/onFind'

onFind('.Page .Page-broadcastAlert', (container: HTMLElement) => {
  const pagination = container.querySelector<HTMLElement>('.pagination')

  if (!pagination) {
    return
  }

  const counter = pagination.querySelector<HTMLElement>('.pagination-count')

  if (!counter) {
    return
  }

  const items = container.querySelectorAll<HTMLElement>(
    '.Page-broadcastAlert-messages > *',
  )

  if (!items) {
    return
  }

  const previousButton = pagination.querySelector<HTMLElement>('.previous')

  if (!previousButton) {
    return
  }

  const previousButtonAnchor =
    previousButton.querySelector<HTMLElement>(':scope > a')

  if (!previousButtonAnchor) {
    return
  }

  const nextButton = pagination.querySelector<HTMLElement>('.next')

  if (!nextButton) {
    return
  }

  const nextButtonAnchor = nextButton.querySelector<HTMLElement>(':scope > a')

  if (!nextButtonAnchor) {
    return
  }

  const totalCount = items.length

  for (let i = 1; i < totalCount; i++) {
    items[i].hidden = true
  }

  let currentIndex = 0

  const updateCounter = () => {
    counter.textContent = `${currentIndex + 1} / ${totalCount}`
  }

  updateCounter()

  const update = (isNext: boolean) => {
    items[currentIndex].hidden = true
    currentIndex += isNext ? 1 : -1
    items[currentIndex].hidden = false
    updateCounter()

    const isPreviousDisabled = currentIndex === 0
    previousButton.classList.toggle('is-disabled', isPreviousDisabled)
    previousButtonAnchor.tabIndex = isPreviousDisabled ? -1 : 0

    const isNextDisabled = currentIndex === totalCount - 1
    nextButton.classList.toggle('is-disabled', isNextDisabled)
    nextButtonAnchor.tabIndex = isNextDisabled ? -1 : 0
  }

  previousButton.addEventListener('click', (event) => {
    event.preventDefault()

    if (currentIndex > 0) {
      update(false)
    }
  })

  nextButton.addEventListener('click', (event) => {
    event.preventDefault()

    if (currentIndex < totalCount - 1) {
      update(true)
    }
  })
})
