import { ref, onMounted, onBeforeUnmount } from 'vue'

export function useDeferredTabFocus() {
  const focusableElements = ref<HTMLElement[]>([])

  function register(el: HTMLElement | null) {
    if (el) {
      el.setAttribute('tabindex', '-1')
      focusableElements.value.push(el)
    }
  }

  function activateFocus() {
    focusableElements.value.forEach(el => el.removeAttribute('tabindex'))
    document.body.classList.add('user-is-tabbing') // <– das hier neu
    window.removeEventListener('keydown', onKeyDown)
  }
 

  function onKeyDown(e: KeyboardEvent) {
    if (e.key === 'Tab') {
      activateFocus()
    }
  }

  function onMouseDown() {
    document.body.classList.remove('user-is-tabbing')
    window.addEventListener('keydown', onKeyDown) // optional: erlaubt Wiederaktivierung nach Maus
  }
  

  onMounted(() => {
    window.addEventListener('keydown', onKeyDown)
    window.addEventListener('mousedown', onMouseDown)
  })
  
  onBeforeUnmount(() => {
    window.removeEventListener('keydown', onKeyDown)
    window.removeEventListener('mousedown', onMouseDown)
  })

  return {
    register
  }
}
