const Loading = (function() {
  let loadingCount = 0;
  let loadingInstance = null;
  let styleInstance = null;

  function createLoading(options = {}) {
    const {
      text = 'Loading...',
      background = 'rgba(0, 0, 0, 0.57)',
      color = '#fff',
      zIndex = 9999,
      spinnerColor = color,
      spinnerSize = '40px'
    } = options;

    if (loadingCount === 0) {
      // Create loading element if it doesn't exist
      loadingInstance = document.createElement('div');
      loadingInstance.className = 'custom-loading';
      loadingInstance.style.position = 'fixed';
      loadingInstance.style.top = '0';
      loadingInstance.style.left = '0';
      loadingInstance.style.width = '100%';
      loadingInstance.style.height = '100%';
      loadingInstance.style.backgroundColor = background;
      loadingInstance.style.display = 'flex';
      loadingInstance.style.justifyContent = 'center';
      loadingInstance.style.alignItems = 'center';
      loadingInstance.style.zIndex = zIndex;
      loadingInstance.style.flexDirection = 'column';

      // Create spinner element
      const spinnerEl = document.createElement('div');
      spinnerEl.className = 'custom-loading-spinner';
      spinnerEl.style.border = `4px solid rgba(0, 0, 0, 0.3)`;
      spinnerEl.style.borderRadius = '50%';
      spinnerEl.style.borderTop = `4px solid ${spinnerColor}`;
      spinnerEl.style.width = spinnerSize;
      spinnerEl.style.height = spinnerSize;
      spinnerEl.style.animation = 'spin 1s linear infinite';

      // Create text element
      const textEl = document.createElement('p');
      textEl.className = 'custom-loading-text';
      textEl.textContent = text;
      textEl.style.color = color;
      textEl.style.marginTop = '20px';
      textEl.style.fontFamily = 'Arial, sans-serif';

      // Add animation styles
      styleInstance = document.createElement('style');
      styleInstance.textContent = `
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
      `;

      // Assemble elements
      loadingInstance.appendChild(spinnerEl);
      loadingInstance.appendChild(textEl);
      document.head.appendChild(styleInstance);
      document.body.appendChild(loadingInstance);
    }
    loadingCount++;
  }

  function destroyLoading() {
    if (loadingCount <= 0) return;
    
    loadingCount--;
    
    if (loadingCount === 0 && loadingInstance) {
      document.body.removeChild(loadingInstance);
      document.head.removeChild(styleInstance);
      loadingInstance = null;
      styleInstance = null;
    }
  }

  return {
    show: createLoading,
    hide: destroyLoading,
    getCount: () => loadingCount // Optional: add method to get current loading count
  };
})();

export default Loading;