import onFind from './dom/onFind'
import { contentSummaryEvent } from './ContentSummary'

const tooltips = window.BRIGHTSPOT?.ui.tooltips
const drawerKey = `BSP.ContentEdit.contentEditDrawerOpen`

// Initializes multi select event on drawer checkboxes
onFind(
  '.ContentEditDrawer.is-open .ContentEditDrawer-widget-carousel-list-item',
  (drawerItem) => {
    drawerItemSelectEvent(drawerItem)
  },
)

onFind('.ContentEditDrawer-widget.frame.loaded', (drawerWidget) => {
  const page = drawerWidget.closest<HTMLElement>('.content-edit')
  if (!page) return

  const drawerButton = page.querySelector<HTMLButtonElement>(
    ':scope button[data-icon-button-name="manage_search"]',
  )
  const drawerContainer = drawerWidget.parentElement
  const contentFormMain = page.querySelector<HTMLElement>('.contentForm-main')
  const closeButton =
    drawerContainer?.querySelector<HTMLButtonElement>('button.Popup-close')

  if (closeButton) {
    closeButton.title = tooltips.collapse
  }

  // Move the drawer button to the end of the toolbar to match visual order
  if (drawerButton) {
    const listItem = drawerButton.closest('li')
    const toolbar = drawerButton.closest('.ContentEdit-toolbar')
    if (listItem && toolbar) {
      toolbar.appendChild(listItem)
    }
  }

  const openDrawer = (shouldFocus = true) => {
    drawerContainer?.classList.add('is-open')
    contentFormMain?.classList.add('is-openDrawer')
    localStorage.setItem(drawerKey, 'true')

    // Handle shelf right rail button state
    if (drawerButton) {
      const labelOpen = `${tooltips.close} ${drawerButton.dataset.label}`

      drawerButton.classList.add('is-active')
      drawerButton.ariaLabel = labelOpen
      drawerButton.title = labelOpen
      drawerButton.ariaExpanded = 'true'
    }

    // Move focus to the close button when drawer is opened by user interaction
    if (shouldFocus) {
      closeButton?.focus()
    }
  }

  const closeDrawer = () => {
    drawerContainer?.classList.remove('is-open')
    contentFormMain?.classList.remove('is-openDrawer')
    localStorage.removeItem(drawerKey)

    // Handle shelf right rail button state
    if (drawerButton) {
      const labelClose = `${tooltips.open} ${drawerButton.dataset.label}`

      drawerButton.classList.remove('is-active')
      drawerButton.ariaLabel = labelClose
      drawerButton.title = labelClose
      drawerButton.ariaExpanded = 'false'
    }

    // Return focus to the drawer button when drawer is closed
    drawerButton?.focus()
  }

  closeButton?.addEventListener('click', (evt) => {
    evt.preventDefault()
    evt.stopPropagation()

    closeDrawer()
  })

  if (localStorage.getItem(drawerKey)) {
    openDrawer(false)
  }

  // Shelf frame refreshes on filters but right rail shelf button doesn't, so we shouldn't reinitialize its click event
  if (!drawerButton?.dataset.clickInitialized) {
    drawerButton?.addEventListener('click', () => {
      drawerButton.dataset.clickInitialized = 'true'

      const isActive = drawerContainer?.classList.contains('is-open')
      if (isActive) {
        closeDrawer()
      } else {
        openDrawer()
      }
    })
  }
})

onFind('.ContentEditDrawer-widget-carousel-list', (drawerList) => {
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      // Allows to place back item back into drawer
      if (mutation.addedNodes.length) {
        const addedNode = mutation.addedNodes[0]

        if (addedNode instanceof HTMLLIElement) {
          addedNode.classList.remove('is-hidden')
          addedNode.classList.remove('RCS-item')

          const drawerSelectButton = addedNode.querySelector<HTMLInputElement>(
            'input.ContentEditDrawer-widget-carousel-list-item-selectButton',
          )
          const drawerInfoButton = addedNode.querySelector<HTMLButtonElement>(
            'button.ContentEditDrawer-widget-carousel-list-item-moreInfoButton',
          )

          // Reinitialize multi select and content summary event since Sortable cloning removes it

          if (
            !addedNode.classList.contains('Sortable-selected') ||
            !addedNode.classList.contains('is-moving')
          ) {
            deselectDrawerItem(addedNode)
          } else if (drawerSelectButton) {
            drawerSelectButton.checked = true
          }

          // Re-add checkbox event listeners after cloning
          drawerItemSelectEvent(addedNode)

          if (drawerInfoButton) {
            drawerInfoButton.classList.remove('is-active')
            contentSummaryEvent(drawerInfoButton)
          }
        }
      }

      if (mutation.removedNodes.length) {
        const removedNode = mutation.removedNodes[0]

        if (removedNode instanceof HTMLLIElement) {
          removedNode.classList.add('RCS-item')
        }
      }
    })
  })

  observer.observe(drawerList, {
    childList: true,
  })
})

if (CSS.supports('content-visibility', 'hidden')) {
  onFind(
    '.ContentEditDrawer.is-open .ContentEditDrawer-widget-carousel-list-item',
    (drawerItem) => {
      const options = {}

      const observer = new IntersectionObserver(
        (entries: IntersectionObserverEntry[]) => {
          entries.forEach((entry: IntersectionObserverEntry) => {
            if (entry.isIntersecting) {
              entry.target.classList.remove('is-hidden')
            } else {
              entry.target.classList.add('is-hidden')
            }
          })
        },
        options,
      )

      observer.observe(drawerItem)
    },
  )
}

export const drawerItemSelectEvent = (drawerItem: Element) => {
  const checkbox = drawerItem.querySelector<HTMLInputElement>(
    'input.ContentEditDrawer-widget-carousel-list-item-selectButton',
  )
  if (!checkbox) return

  // Add is-moving on mousedown BEFORE Sortable's onSelect fires
  checkbox.addEventListener('mousedown', () => {
    if (!checkbox.checked) {
      drawerItem.classList.add('is-moving')
    }
  })

  // Handle the actual selection state on change
  checkbox.addEventListener('change', () => {
    if (!checkbox.checked) {
      drawerItem.classList.remove('Sortable-selected')
      drawerItem.classList.remove('is-moving')
    }
  })
}

export const deselectDrawerItem = (drawerItem: Element) => {
  const drawerSelectButton = drawerItem.querySelector<HTMLInputElement>(
    'input.ContentEditDrawer-widget-carousel-list-item-selectButton',
  )

  if (drawerSelectButton) {
    drawerSelectButton.checked = false
  }

  drawerItem.classList.remove('Sortable-selected')
  drawerItem.classList.remove('is-moving')
}
