import onFind from '../dom/onFind'
import Tether from '../dom/Tether'

onFind('.GraphQL', (container: HTMLDivElement) => {
  container.addEventListener('onegraph-click', () => {
    // the mousedown is necessary to satisfy the ifClick plugin's check
    container.dispatchEvent(new Event('mousedown', { bubbles: true }))
    container.dispatchEvent(new Event('click', { bubbles: true }))
  })
})

onFind('.GraphQL-controls-toggle', (toggle: HTMLDivElement) => {
  const controls = toggle.closest('.GraphQL-controls-menu')
  const list = controls?.querySelector<HTMLElement>('.GraphQL-controls-list')

  if (list && controls) {
    toggle.addEventListener('click', (e: MouseEvent | KeyboardEvent) => {
      Tether.toggle(toggle, list, () => controls.classList.toggle('is-open'))
    })
  }
})

onFind('.GraphQL-copy', (link) => {
  link.addEventListener('click', (event) => {
    event.stopPropagation()
    event.preventDefault()

    const code = link.getAttribute('data-code')

    // copy to clipboard
    if (code) {
      window.navigator.clipboard.writeText(code)
    }

    link.setAttribute('data-copied', '')

    // confirmation
    const confirmation = link.nextElementSibling

    if (confirmation) {
      confirmation.removeAttribute('hidden')

      setTimeout(() => {
        confirmation.setAttribute('hidden', '')
        link.removeAttribute('data-copied')
      }, 1500)
    }
  })
})
