import onFind from '../dom/onFind'

onFind('div.GraphQL-previewControls', (div) => {
  const previewForm = div.querySelector<HTMLFormElement>('form[id]')
  if (!previewForm) return
  const deviceSelect =
    previewForm.querySelector<HTMLSelectElement>('.deviceWidthSelect')
  if (!deviceSelect) return

  deviceSelect.addEventListener('change', (event) => {
    const targetFrame = document.querySelector<HTMLElement>(
      "iframe[name='" + previewForm.target + "']",
    )

    if (targetFrame && event?.currentTarget instanceof HTMLSelectElement) {
      targetFrame.style.width =
        event?.currentTarget?.selectedOptions[0].value + 'px'
    }

    window.dispatchEvent(new Event('resize'))
    previewForm.submit()
  })
})
