import { createVNode, render, h, onMounted, onUnmounted } from 'vue';
import { Spin as ASpin } from 'ant-design-vue';

export function useGlobalLoading() {
  let loadingElement: HTMLElement | null = null;

  const showLoading = () => {
    if (!loadingElement) {
      loadingElement = document.createElement('div');
      loadingElement.id = 'global-loading';
      document.body.appendChild(loadingElement);

      const spinVNode = h(ASpin, { spinning: true });
      render(spinVNode, loadingElement);
    }
  };
  
  const hideLoading = () => {
    if (loadingElement) {
      document.body.removeChild(loadingElement);
      loadingElement = null;
    }
  };

  onUnmounted(hideLoading);

  return { showLoading, hideLoading };
}
