// Loading state management utilities

export function createLoadingSpinner(container = null) {
  const spinner = document.createElement("div");
  spinner.className = "loading-spinner";
  
  // Add spinner styles if not already present
  if (!document.getElementById("spinner-styles")) {
    const style = document.createElement("style");
    style.id = "spinner-styles";
    style.textContent = `
      .loading-spinner {
        width: 24px;
        height: 24px;
        border: 3px solid rgba(34, 211, 238, 0.2);
        border-top-color: #22d3ee;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
      }
      .loading-spinner-large {
        width: 40px;
        height: 40px;
        border-width: 4px;
      }
      @keyframes spin {
        to { transform: rotate(360deg); }
      }
      .loading-overlay {
        position: fixed;
        inset: 0;
        background: rgba(4, 7, 13, 0.8);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        backdrop-filter: blur(4px);
      }
      .loading-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;
        color: #ffffff;
      }
      .loading-text {
        font-size: 14px;
        color: #a0a7b5;
      }
    `;
    document.head.appendChild(style);
  }
  
  if (container) {
    container.appendChild(spinner);
  }
  
  return spinner;
}

export function showLoadingOverlay(message = "Loading...") {
  const overlay = document.createElement("div");
  overlay.className = "loading-overlay";
  overlay.innerHTML = `
    <div class="loading-content">
      <div class="loading-spinner loading-spinner-large"></div>
      <div class="loading-text">${message}</div>
    </div>
  `;
  document.body.appendChild(overlay);
  return overlay;
}

export function hideLoadingOverlay(overlay) {
  if (overlay && overlay.parentNode) {
    overlay.parentNode.removeChild(overlay);
  }
}

export function setButtonLoading(button, isLoading, originalText = null) {
  if (!button) return;
  
  if (isLoading) {
    button.dataset.originalText = originalText || button.textContent;
    button.disabled = true;
    button.style.opacity = "0.6";
    button.style.cursor = "not-allowed";
    
    const spinner = createLoadingSpinner();
    spinner.style.width = "16px";
    spinner.style.height = "16px";
    spinner.style.borderWidth = "2px";
    button.innerHTML = "";
    button.appendChild(spinner);
  } else {
    button.disabled = false;
    button.style.opacity = "1";
    button.style.cursor = "pointer";
    if (button.dataset.originalText) {
      button.textContent = button.dataset.originalText;
      delete button.dataset.originalText;
    }
  }
}

