import { reactive, nextTick, watch, computed } from "vue";

export const state = reactive({
  _activeIndex: undefined,
  get activeIndex(){
    return state._activeIndex;
  },
  set activeIndex(val){
    // if (val === state._activeIndex) return;
    state._activeIndex = val;
    if (val === undefined) return;
    state._activeElement = document.querySelector(`[tabindex="${val}"]`);
    nextTick(() => {
      nextTick(() => {
        state._activeElement?.focus();
      })
    })
  },
  _activeElement: undefined,
  get activeElement(){
    return state._activeElement;
  },
  set activeElement(val){
    // if (val === state._activeElement) return;
    state._activeElement = val;
    if (val === undefined) return;
    state.activeIndex = val.tabIndex;
  },
  elements: {},
  sortedElements: computed(() => Object.keys(state.elements)),
  init: true,
  back: [],
  backActive: []
});

watch(() => state.sortedElements, () => {
  if (state._activeIndex !== undefined && state.sortedElements.length > 0){
    state.activeIndex = state._activeIndex;
  }
})

watch(() => state.activeIndex, () => {
  if (state.activeIndex === undefined && state.sortedElements.length > 0){
    state.activeIndex = state.sortedElements[0];
  }
})
