import { computed, h, ref } from 'vue'

export default function useRefocusTarget(props, rootRef) {
  const refocusRef = ref(null)

  const refocusTargetEl = computed(() => {
    if (props.disable) return null

    return h('span', {
      ref: refocusRef,
      class: 'no-outline',
      tabindex: -1
    })
  })

  function refocusTarget(e) {
    const root = rootRef.value

    if (e?.qAvoidFocus === true) return

    // never move focus into an aria-hidden control -- browsers
    // refuse to hide a focused element from AT and warn about it
    if (root?.getAttribute('aria-hidden') === 'true') return

    if (e?.type.indexOf('key') === 0) {
      if (
        document.activeElement !== root &&
        root?.contains(document.activeElement) === true
      ) {
        root.focus({ preventScroll: true })
      }
    } else if (
      refocusRef.value !== null &&
      (e === void 0 || root?.contains(e.target) === true)
    ) {
      refocusRef.value.focus({ preventScroll: true })
    }
  }

  return {
    refocusTargetEl,
    refocusTarget
  }
}
