import { ref, provide, inject, onMounted, onBeforeUnmount, nextTick, type Ref, type InjectionKey } from 'vue';

export const AdminTableRowActionsMenuKey: InjectionKey<Ref<boolean>> = Symbol('adminTableRowActionsMenu');

const MOBILE_MAX = 768;

export function useAdminTableRowActionsProvider(tableWrapRef: Ref<HTMLElement | null>) {
  const useMenu = ref(false);

  function update() {
    const wrap = tableWrapRef.value;
    if (!wrap) return;

    if (window.innerWidth <= MOBILE_MAX) {
      useMenu.value = true;
      return;
    }

    const table = wrap.querySelector('.el-table') as HTMLElement | null;
    if (!table) {
      useMenu.value = false;
      return;
    }

    useMenu.value = table.scrollWidth > wrap.clientWidth + 2;
  }

  let observer: ResizeObserver | null = null;

  onMounted(async () => {
    await nextTick();
    update();
    if (tableWrapRef.value) {
      observer = new ResizeObserver(() => update());
      observer.observe(tableWrapRef.value);
      const table = tableWrapRef.value.querySelector('.el-table');
      if (table) observer.observe(table);
    }
    window.addEventListener('resize', update);
  });

  onBeforeUnmount(() => {
    observer?.disconnect();
    window.removeEventListener('resize', update);
  });

  provide(AdminTableRowActionsMenuKey, useMenu);
  return useMenu;
}

export function useAdminTableRowActionsMenu() {
  return inject(AdminTableRowActionsMenuKey, null);
}
