import { OPEN_COMPOSE_EVENT_TYPE } from '@/email/EmailFormOverlay'
import { useEffect, useRef } from 'react'

const setMailTo = (root: HTMLDivElement) => {
  root.querySelectorAll('a[href^=mailto]').forEach(element => {
    ;(element as HTMLLinkElement).onclick = event => {
      event.preventDefault()
      window.dispatchEvent(
        new CustomEvent(OPEN_COMPOSE_EVENT_TYPE, {
          detail: {
            // remove "mailto:"
            email: (element as HTMLLinkElement).href.slice(7),
          },
        })
      )
    }
  })
}

const useMailToRef = () => {
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const root = ref.current
    if (!root) return

    // initial call to set mailto links
    setMailTo(root)

    const observer = new MutationObserver(() => setMailTo(root))
    observer.observe(root, { childList: true, subtree: true })

    return () => {
      observer.disconnect()
    }
  }, [])

  return ref
}

export default useMailToRef
