class Loading {
  private static instance: HTMLElement | null = null;

  private static createLoadingElement(text: string): HTMLElement {
    const wrapper = document.createElement("div");
    wrapper.className = "global-loading";

    const content = document.createElement("div");
    content.className = "loading-content";

    // 创建加载动画容器
    const loadingContainer = document.createElement("div");
    loadingContainer.className = "loading-container";

    // 创建三个圆点
    for (let i = 0; i < 3; i++) {
      const dot = document.createElement("div");
      dot.className = "loading-dot";
      loadingContainer.appendChild(dot);
    }

    // 文字
    const textDiv = document.createElement("div");
    textDiv.className = "loading-text";
    textDiv.textContent = text;

    content.appendChild(loadingContainer);
    content.appendChild(textDiv);
    wrapper.appendChild(content);

    // 添加样式
    const style = document.createElement("style");
    style.textContent = `
      .global-loading {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(255, 255, 255, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      }
      
      .loading-content {
        text-align: center;
      }
      
      .loading-container {
        display: flex;
        justify-content: center;
        gap: 8px;
        margin-bottom: 15px;
      }
      
      .loading-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: #529ff4;
        opacity: 0;
      }
      
      .loading-dot:nth-child(1) {
        animation: dotAnimation 1.8s infinite;
      }
      
      .loading-dot:nth-child(2) {
        animation: dotAnimation 1.8s infinite;
        animation-delay: 0.2s;
      }
      
      .loading-dot:nth-child(3) {
        animation: dotAnimation 1.8s infinite;
        animation-delay: 0.4s;
      }
      
      @keyframes dotAnimation {
        0% { 
          opacity: 0;
          transform: scale(0.5);
        }
        20% { 
          opacity: 1;
          transform: scale(1);
        }
        60% { 
          opacity: 1;
          transform: scale(1);
        }
        80% { 
          opacity: 0;
          transform: scale(0.5);
        }
        100% { 
          opacity: 0;
          transform: scale(0.5);
        }
      }
      
      .loading-text {
        color: #333;
        font-size: 14px;
      }
    `;
    document.head.appendChild(style);

    return wrapper;
  }

  public static show(text: string = "加载中，请稍后...") {
    if (this.instance) {
      this.close();
    }

    this.instance = this.createLoadingElement(text);
    document.body.appendChild(this.instance);
  }

  public static close() {
    if (this.instance && document.body.contains(this.instance)) {
      document.body.removeChild(this.instance);
      this.instance = null;
    }
  }
}

export default Loading;
