/* eslint-disable */
// upload-status-helper.js
// 文件上传状态监控工具

if (window.__UPLOAD_STATUS_HELPER_INITIALIZED__) {
  // Already initialized, skip
} else {
  window.__UPLOAD_STATUS_HELPER_INITIALIZED__ = true;

  /**
   * 上传状态监控工具类
   */
  class UploadStatusHelper {
    /**
     * 监控文件输入框状态变化
     * @param {string} inputSelector - 文件输入框选择器
     * @param {Object} options - 监控选项
     * @returns {Promise<Object>} 监控结果
     */
    static async monitorInputStatus(inputSelector = 'input[type="file"]', options = {}) {
      const {
        timeout = 30000,
        checkInterval = 500,
        onProgress = null, // 进度回调函数
        onStatusChange = null, // 状态变化回调函数
      } = options;

      try {
        const fileInput = await window.DOMUtils.waitForElement(inputSelector, timeout);

        return new Promise((resolve) => {
          const startTime = Date.now();
          let lastFileCount = fileInput.files.length;
          let uploadStarted = false;

          const checkStatus = () => {
            const currentFileCount = fileInput.files.length;
            const elapsed = Date.now() - startTime;

            // 检测文件是否开始上传
            if (currentFileCount > lastFileCount && !uploadStarted) {
              uploadStarted = true;
              if (onStatusChange) {
                onStatusChange('started', { fileCount: currentFileCount });
              }
            }

            // 检测是否有进度指示器
            const progressElements = document.querySelectorAll(
              ['.upload-progress', '.progress', '[class*="progress"]', '[class*="upload"]'].join(
                ',',
              ),
            );

            if (progressElements.length > 0) {
              const progressInfo = Array.from(progressElements).map((el) => ({
                element: el,
                text: el.textContent,
                value: el.value || el.getAttribute('aria-valuenow'),
                style: window.getComputedStyle(el),
              }));

              if (onProgress) {
                onProgress(progressInfo);
              }
            }

            // 检查是否超时
            if (elapsed > timeout) {
              resolve({
                success: false,
                error: 'Upload monitoring timeout',
                duration: elapsed,
              });
              return;
            }

            // 继续监控
            setTimeout(checkStatus, checkInterval);
          };

          // 监听文件输入变化
          fileInput.addEventListener('change', () => {
            if (onStatusChange) {
              onStatusChange('fileSelected', { fileCount: fileInput.files.length });
            }
          });

          checkStatus();
        });
      } catch (error) {
        return {
          success: false,
          error: `Error monitoring input status: ${error.message}`,
        };
      }
    }

    /**
     * 等待上传完成（通过页面元素变化）
     * @param {Object} options - 选项
     * @returns {Promise<Object>} 等待结果
     */
    static async waitForUploadComplete(options = {}) {
      const {
        successSelectors = [
          '.upload-success',
          '.success',
          '[class*="success"]',
          '[data-status="success"]',
        ],
        errorSelectors = ['.upload-error', '.error', '[class*="error"]', '[data-status="error"]'],
        progressSelectors = ['.upload-progress', '.progress', '[class*="progress"]'],
        timeout = 30000,
        checkInterval = 500,
      } = options;

      try {
        return new Promise((resolve) => {
          const startTime = Date.now();

          const checkUploadStatus = () => {
            // 检查成功状态
            for (const selector of successSelectors) {
              const successElement = document.querySelector(selector);
              if (successElement && window.getComputedStyle(successElement).display !== 'none') {
                resolve({
                  success: true,
                  status: 'completed',
                  message: successElement.textContent || 'Upload completed successfully',
                  element: successElement,
                  duration: Date.now() - startTime,
                });
                return;
              }
            }

            // 检查错误状态
            for (const selector of errorSelectors) {
              const errorElement = document.querySelector(selector);
              if (errorElement && window.getComputedStyle(errorElement).display !== 'none') {
                resolve({
                  success: false,
                  status: 'failed',
                  error: errorElement.textContent || 'Upload failed',
                  element: errorElement,
                  duration: Date.now() - startTime,
                });
                return;
              }
            }

            // 检查是否还在上传中
            const progressElement = progressSelectors
              .map((selector) => document.querySelector(selector))
              .find((el) => el && window.getComputedStyle(el).display !== 'none');

            if (progressElement) {
              const progressValue =
                progressElement.value ||
                progressElement.getAttribute('aria-valuenow') ||
                progressElement.getAttribute('data-progress');

              if (progressValue && parseFloat(progressValue) >= 100) {
                resolve({
                  success: true,
                  status: 'completed',
                  message: 'Upload progress reached 100%',
                  element: progressElement,
                  duration: Date.now() - startTime,
                });
                return;
              }
            }

            // 检查超时
            if (Date.now() - startTime > timeout) {
              resolve({
                success: false,
                status: 'timeout',
                error: `Upload timeout after ${timeout}ms`,
                duration: Date.now() - startTime,
              });
              return;
            }

            // 继续检查
            setTimeout(checkUploadStatus, checkInterval);
          };

          checkUploadStatus();
        });
      } catch (error) {
        return {
          success: false,
          error: `Error waiting for upload complete: ${error.message}`,
        };
      }
    }

    /**
     * 获取当前上传进度
     * @param {Object} options - 选项
     * @returns {Object} 进度信息
     */
    static getUploadProgress(options = {}) {
      const {
        progressSelectors = ['.upload-progress', '.progress', '[class*="progress"]', 'progress'],
      } = options;

      const progressInfo = [];

      for (const selector of progressSelectors) {
        const elements = document.querySelectorAll(selector);

        elements.forEach((element) => {
          if (window.getComputedStyle(element).display !== 'none') {
            const value =
              element.value ||
              element.getAttribute('aria-valuenow') ||
              element.getAttribute('data-progress') ||
              element.textContent.match(/(\d+)%/)?.[1];

            progressInfo.push({
              element: element,
              selector: selector,
              value: value ? parseFloat(value) : null,
              text: element.textContent,
              max: element.max || element.getAttribute('aria-valuemax') || 100,
              isVisible: true,
            });
          }
        });
      }

      return {
        progressElements: progressInfo,
        averageProgress:
          progressInfo.length > 0
            ? progressInfo.reduce((sum, info) => sum + (info.value || 0), 0) / progressInfo.length
            : null,
        isUploading: progressInfo.some((info) => info.value !== null && info.value < 100),
      };
    }

    /**
     * 监控多个文件的上传状态
     * @param {Array} fileSelectors - 文件相关选择器数组
     * @param {Object} options - 选项
     * @returns {Promise<Object>} 监控结果
     */
    static async monitorMultipleUploads(fileSelectors = [], options = {}) {
      const {
        timeout = 60000,
        checkInterval = 1000,
        onProgress = null,
        onFileComplete = null,
      } = options;

      try {
        const results = [];
        const startTime = Date.now();

        return new Promise((resolve) => {
          const checkAllUploads = () => {
            let allCompleted = true;
            let anyFailed = false;

            fileSelectors.forEach((selector, index) => {
              const elements = document.querySelectorAll(selector);

              elements.forEach((element) => {
                const status = this._getElementUploadStatus(element);

                if (status.isCompleted && !results[index]) {
                  results[index] = status;
                  if (onFileComplete) {
                    onFileComplete(status, index);
                  }
                } else if (!status.isCompleted) {
                  allCompleted = false;
                }

                if (status.hasFailed) {
                  anyFailed = true;
                }
              });
            });

            if (onProgress) {
              onProgress({
                completed: results.filter((r) => r).length,
                total: fileSelectors.length,
                results: results,
              });
            }

            if (allCompleted || anyFailed || Date.now() - startTime > timeout) {
              resolve({
                success: allCompleted && !anyFailed,
                completed: allCompleted,
                failed: anyFailed,
                timeout: Date.now() - startTime > timeout,
                results: results,
                duration: Date.now() - startTime,
              });
              return;
            }

            setTimeout(checkAllUploads, checkInterval);
          };

          checkAllUploads();
        });
      } catch (error) {
        return {
          success: false,
          error: `Error monitoring multiple uploads: ${error.message}`,
        };
      }
    }

    // 私有方法：获取元素的上传状态
    static _getElementUploadStatus(element) {
      const classList = element.className;
      const textContent = element.textContent;

      return {
        isCompleted:
          classList.includes('success') ||
          classList.includes('complete') ||
          textContent.includes('完成') ||
          textContent.includes('success'),
        hasFailed:
          classList.includes('error') ||
          classList.includes('failed') ||
          textContent.includes('失败') ||
          textContent.includes('error'),
        isUploading:
          classList.includes('uploading') ||
          classList.includes('progress') ||
          textContent.includes('上传中') ||
          textContent.includes('uploading'),
        element: element,
        text: textContent,
      };
    }
  }

  // 监听来自扩展的消息
  chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
    if (request.action === 'monitorInputStatus') {
      UploadStatusHelper.monitorInputStatus(request.inputSelector, request.options)
        .then(sendResponse)
        .catch((error) => {
          sendResponse({
            success: false,
            error: error.message,
          });
        });
      return true; // 异步响应
    }

    if (request.action === 'waitForUploadComplete') {
      UploadStatusHelper.waitForUploadComplete(request.options)
        .then(sendResponse)
        .catch((error) => {
          sendResponse({
            success: false,
            error: error.message,
          });
        });
      return true; // 异步响应
    }

    if (request.action === 'getUploadProgress') {
      const progress = UploadStatusHelper.getUploadProgress(request.options);
      sendResponse(progress);
      return false;
    }

    if (request.action === 'chrome_upload_status_ping') {
      sendResponse({ status: 'pong' });
      return false;
    }
  });

  // 将工具类暴露到全局
  window.UploadStatusHelper = UploadStatusHelper;
}
