import onFind from './dom/onFind'

onFind('.PrePublish', (popup: HTMLElement) => {
  const close = popup.querySelector<HTMLElement>('.PrePublish-cancel')
  const id = popup.dataset.prepublish
  const form = document.querySelector<HTMLFormElement>(
    `form[data-content-id="${id}"]`,
  )
  const submitButton = popup.querySelector<HTMLButtonElement>(
    'button[type="submit"]',
  )

  // Trigger legacy jQuery event for hooks like navigate away.
  if (submitButton) {
    submitButton.addEventListener('click', () => {
      $(form as any).trigger('submit')
    })
  }

  close?.addEventListener('click', () => {
    // User closed the popup and chose to continue then submit without interferrence.
    if (form) {
      const input = form.querySelector<HTMLInputElement>(
        'input[name="prePublish"]',
      )
      const button = form.querySelector<HTMLButtonElement>(
        'button[name="prePublishDisplay"]',
      )

      input?.remove()

      if (button) {
        button.addEventListener(
          'click',
          () => {
            if (input) {
              form.appendChild(input)
            }
          },
          { once: true },
        )
      }
    }

    popup.classList.remove('is-visible')

    if (window.BRIGHTSPOT?.ui.cms.enableV5UI) {
      popup.dispatchEvent(
        new CustomEvent('legacy.popup.close', {
          bubbles: true,
        }),
      )
    }
  })

  const hiddenChildren = popup.querySelectorAll(
    '.CIG:not(.TC) > [data-tab].TC-unselected',
  )

  Array.from(hiddenChildren).forEach((child) => {
    child.classList.remove('TC-unselected')
  })
})
