/**
 * 移动端窗口管理适配器
 * 不修改原 window-manager.js，通过覆盖方式适配
 * 让窗口在移动端全屏显示，禁用拖拽和缩放
 * 依赖: mobile-icons.js
 */

(function() {
  'use strict';

  // 检测是否为移动端
  const isMobile = window.innerWidth <= 768;

  /**
   * 移动端窗口适配器类
   */
  class MobileWindowAdapter {
    constructor() {
      this.isMobile = isMobile;
      this.originalOpenApp = null;
      this.originalCloseApp = null;
      this.originalActivateWindow = null;
      this.windowStack = [];
      this.maxZIndex = 1000;
      this.windowCounter = 0;
      this.isInitialized = false;
      this.pendingWindows = [];

      console.log('[MobileWindowAdapter] 已初始化，移动端模式:', this.isMobile);

      // 如果是移动端，等待 FluentOS 加载
      if (this.isMobile) {
        this.waitForFluentOS();
      }
    }

    /**
     * 等待 FluentOS 加载完成
     */
    waitForFluentOS() {
      // 如果 FluentOS 已经存在，直接初始化
      if (window.FluentOS) {
        this.init();
        return;
      }

      // 等待 FluentOS
      const checkInterval = setInterval(() => {
        if (window.FluentOS) {
          clearInterval(checkInterval);
          this.init();
        }
      }, 50);

      // 超时保护（5秒后强制初始化）
      setTimeout(() => {
        clearInterval(checkInterval);
        if (!this.isInitialized) {
          console.warn('[MobileWindowAdapter] FluentOS 加载超时，强制初始化');
          this.init();
        }
      }, 5000);
    }

    /**
     * 初始化
     */
    init() {
      if (this.isInitialized) return;
      this.isInitialized = true;

      const fluentOS = window.FluentOS;
      if (!fluentOS) {
        console.error('[MobileWindowAdapter] FluentOS 不存在');
        return;
      }

      // 保存原始方法
      this.originalOpenApp = fluentOS.openApp;
      this.originalCloseApp = fluentOS.closeApp;
      this.originalActivateWindow = fluentOS.activateWindow;

      // 覆盖 openApp
      this.overrideOpenApp(fluentOS);

      // 覆盖 closeApp
      this.overrideCloseApp(fluentOS);

      // 覆盖 activateWindow
      this.overrideActivateWindow(fluentOS);

      // 添加移动端专用方法
      this.addMobileMethods(fluentOS);

      // 监听窗口变化
      this.setupWindowObserver();

      // 适配已存在的窗口
      this.adaptExistingWindows();

      console.log('[MobileWindowAdapter] 移动端窗口适配已启用');
    }

    /**
     * 覆盖 openApp 方法
     */
    overrideOpenApp(fluentOS) {
      const self = this;

      fluentOS.openApp = function(appId, options = {}) {
        // 如果是移动端，强制全屏
        const mobileOptions = {
          ...options,
          fullscreen: true,
          resizable: false,
          draggable: false,
          width: window.innerWidth,
          height: window.innerHeight - 96, // 减去任务栏和导航栏
          x: 0,
          y: 0,
        };

        // 调用原始方法
        const result = self.originalOpenApp.call(this, appId, mobileOptions);

        // 延迟适配窗口
        setTimeout(() => {
          self.adaptWindow(appId);
        }, 50);

        return result;
      };

      // 保存引用
      fluentOS._originalOpenApp = this.originalOpenApp;
    }

    /**
     * 覆盖 closeApp 方法
     */
    overrideCloseApp(fluentOS) {
      const self = this;

      fluentOS.closeApp = function(appId) {
        // 从栈中移除
        self.removeFromStack(appId);

        // 调用原始方法
        const result = self.originalCloseApp.call(this, appId);

        // 更新任务切换器（如果存在）
        self.notifyTaskSwitcher();

        return result;
      };

      fluentOS._originalCloseApp = this.originalCloseApp;
    }

    /**
     * 覆盖 activateWindow 方法
     */
    overrideActivateWindow(fluentOS) {
      const self = this;

      fluentOS.activateWindow = function(windowId) {
        // 调用原始方法
        const result = self.originalActivateWindow.call(this, windowId);

        // 更新窗口栈
        const win = document.querySelector(`[data-window-id="${windowId}"]`);
        if (win) {
          const appId = win.dataset.appId;
          if (appId) {
            self.bringToTop(appId);
          }
        }

        return result;
      };

      fluentOS._originalActivateWindow = this.originalActivateWindow;
    }

    /**
     * 添加移动端专用方法
     */
    addMobileMethods(fluentOS) {
      const self = this;

      // 获取窗口栈
      fluentOS.getWindowStack = function() {
        return self.windowStack;
      };

      // 切换到指定窗口
      fluentOS.switchToWindow = function(appId) {
        return self.switchToWindow(appId);
      };

      // 获取当前活动窗口
      fluentOS.getActiveWindow = function() {
        return self.getActiveWindow();
      };

      // 关闭所有窗口（移动端专用）
      fluentOS.closeAllMobileWindows = function() {
        return self.closeAllWindows();
      };

      // 最小化所有窗口（移动端专用）
      fluentOS.minimizeAllWindows = function() {
        return self.minimizeAllWindows();
      };
    }

    /**
     * 适配单个窗口（移动端样式）
     */
    adaptWindow(appId) {
      // 查找最新打开的窗口
      const windows = document.querySelectorAll('.window-container');
      if (windows.length === 0) return;

      const targetWindow = windows[windows.length - 1];
      if (!targetWindow) return;

      // 如果已经适配过，跳过
      if (targetWindow.dataset.mobile === 'true') {
        return;
      }

      // 获取窗口标题
      const title = targetWindow.querySelector('.window-title')?.textContent || appId || '应用';

      // 设置移动端属性
      targetWindow.dataset.appId = appId || 'unknown';
      targetWindow.dataset.mobile = 'true';
      targetWindow.dataset.windowId = `win_${++this.windowCounter}`;

      // 添加移动端类
      targetWindow.classList.add('mobile-window');

      // ===== 强制全屏 =====
      const navHeight = 48; // 导航栏高度
      const taskbarHeight = 48; // 任务栏高度
      const totalBottom = navHeight + taskbarHeight;

      targetWindow.style.position = 'fixed';
      targetWindow.style.top = '0';
      targetWindow.style.left = '0';
      targetWindow.style.width = '100vw';
      targetWindow.style.height = `calc(100vh - ${totalBottom}px)`;
      targetWindow.style.borderRadius = '0';
      targetWindow.style.zIndex = ++this.maxZIndex;
      targetWindow.style.transform = 'none';
      targetWindow.style.transition = 'opacity 0.25s ease, transform 0.25s ease';
      targetWindow.style.opacity = '1';

      // ===== 适配标题栏 =====
      this.adaptTitleBar(targetWindow, appId, title);

      // ===== 隐藏不需要的元素 =====
      this.hideUnnecessaryElements(targetWindow);

      // ===== 适配窗口主体 =====
      this.adaptBody(targetWindow);

      // ===== 添加关闭事件 =====
      this.setupCloseHandler(targetWindow, appId);

      // ===== 添加到栈 =====
      this.addToStack(appId || 'unknown', targetWindow);

      // ===== 触发事件 =====
      const event = new CustomEvent('mobile-window-opened', {
        detail: { 
          appId: appId || 'unknown', 
          window: targetWindow,
          title: title
        }
      });
      document.dispatchEvent(event);

      // ===== 通知任务切换器 =====
      this.notifyTaskSwitcher();

      console.log('[MobileWindowAdapter] 窗口已适配:', appId || 'unknown');
    }

    /**
     * 适配标题栏
     */
    adaptTitleBar(windowEl, appId, title) {
      const titleBar = windowEl.querySelector('.window-title-bar');
      if (!titleBar) return;

      // 添加移动端类
      titleBar.classList.add('mobile-title-bar');

      // 确保标题内容正确
      const titleSpan = titleBar.querySelector('.window-title');
      if (titleSpan) {
        // 如果标题是空的，设置默认值
        if (!titleSpan.textContent || titleSpan.textContent.trim() === '') {
          titleSpan.textContent = title || appId || '应用';
        }

        // 添加图标（从 mobile-icons 获取）
        if (appId && window.MobileIconAdapter) {
          const iconHTML = window.MobileIconAdapter.getAppIcon(appId, 'small');
          // 插入到标题前面
          const iconWrapper = document.createElement('span');
          iconWrapper.className = 'title-icon';
          iconWrapper.innerHTML = iconHTML;
          titleSpan.prepend(iconWrapper);
        }
      }

      // 调整控制按钮
      const controls = titleBar.querySelector('.window-controls');
      if (controls) {
        const btns = controls.querySelectorAll('button');
        btns.forEach(btn => {
          // 隐藏最小化和最大化按钮
          if (btn.classList.contains('window-min-btn') || 
              btn.classList.contains('window-max-btn')) {
            btn.style.display = 'none';
          }
          // 关闭按钮保留，调整样式
          if (btn.classList.contains('window-close-btn')) {
            btn.style.background = 'rgba(255, 0, 0, 0.15)';
            btn.style.color = '#ff6b6b';
            btn.style.width = '32px';
            btn.style.height = '32px';
            btn.style.borderRadius = '50%';
            btn.style.border = 'none';
            btn.style.fontSize = '16px';
            btn.style.cursor = 'pointer';
            btn.style.display = 'flex';
            btn.style.alignItems = 'center';
            btn.style.justifyContent = 'center';
            btn.setAttribute('aria-label', '关闭');
          }
        });
      }
    }

    /**
     * 隐藏不需要的元素
     */
    hideUnnecessaryElements(windowEl) {
      // 隐藏窗口边框
      const borders = windowEl.querySelectorAll('.window-border, .window-resize-handle');
      borders.forEach(el => el.style.display = 'none');

      // 隐藏窗口阴影（通过移除类）
      windowEl.style.boxShadow = 'none';
      windowEl.style.border = 'none';
    }

    /**
     * 适配窗口主体
     */
    adaptBody(windowEl) {
      const body = windowEl.querySelector('.window-body');
      if (body) {
        body.style.height = 'calc(100% - 44px)';
        body.style.overflowY = 'auto';
        body.style.overflowX = 'hidden';
        body.style.webkitOverflowScrolling = 'touch';
        body.style.padding = '0';
        body.style.background = 'var(--bg-secondary, #1a1a2e)';
      }
    }

    /**
     * 设置关闭处理器
     */
    setupCloseHandler(windowEl, appId) {
      const closeBtn = windowEl.querySelector('.window-close-btn');
      if (closeBtn) {
        // 移除原有事件，添加新的
        const newCloseBtn = closeBtn.cloneNode(true);
        closeBtn.parentNode.replaceChild(newCloseBtn, closeBtn);

        newCloseBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          // 从栈中移除
          this.removeFromStack(appId || 'unknown');
          // 触发关闭动画
          windowEl.classList.add('slide-out');
          setTimeout(() => {
            // 调用原始关闭方法
            if (window.FluentOS && window.FluentOS.closeApp) {
              window.FluentOS.closeApp(appId);
            }
          }, 250);
        });
      }
    }

    /**
     * 窗口栈管理
     */
    addToStack(appId, windowElement) {
      // 移除已存在的相同 appId
      this.removeFromStack(appId);

      // 添加到栈顶
      this.windowStack.push({ 
        appId: appId, 
        element: windowElement,
        timestamp: Date.now()
      });

      // 限制栈大小（最多10个）
      if (this.windowStack.length > 10) {
        const oldest = this.windowStack.shift();
        this.closeWindow(oldest.element);
      }

      // 更新激活状态
      this.updateActiveStates(appId);
    }

    removeFromStack(appId) {
      const index = this.windowStack.findIndex(item => item.appId === appId);
      if (index !== -1) {
        this.windowStack.splice(index, 1);
        return true;
      }
      return false;
    }

    /**
     * 将窗口置顶
     */
    bringToTop(appId) {
      const item = this.windowStack.find(w => w.appId === appId);
      if (item) {
        // 移到栈顶
        this.removeFromStack(appId);
        this.windowStack.push(item);
        // 更新 z-index
        item.element.style.zIndex = ++this.maxZIndex;
        // 更新激活状态
        this.updateActiveStates(appId);
      }
    }

    /**
     * 更新激活状态
     */
    updateActiveStates(activeAppId) {
      this.windowStack.forEach(item => {
        const isActive = item.appId === activeAppId;
        item.element.classList.toggle('active', isActive);
        // 移除其他窗口的激活状态
        if (!isActive) {
          item.element.style.opacity = '0.95';
        } else {
          item.element.style.opacity = '1';
        }
      });
    }

    /**
     * 切换到指定窗口
     */
    switchToWindow(appId) {
      const item = this.windowStack.find(w => w.appId === appId);
      if (item) {
        this.bringToTop(appId);
        // 确保窗口显示
        item.element.style.display = 'block';
        item.element.classList.remove('minimized');
        return true;
      }
      return false;
    }

    /**
     * 获取当前活动窗口
     */
    getActiveWindow() {
      for (let i = this.windowStack.length - 1; i >= 0; i--) {
        const item = this.windowStack[i];
        if (item.element.style.display !== 'none' && 
            !item.element.classList.contains('minimized')) {
          return item;
        }
      }
      return null;
    }

    /**
     * 关闭窗口
     */
    closeWindow(windowElement) {
      const closeBtn = windowElement.querySelector('.window-close-btn');
      if (closeBtn) {
        closeBtn.click();
      }
    }

    /**
     * 关闭所有窗口
     */
    closeAllWindows() {
      const windows = [...this.windowStack];
      windows.forEach(item => {
        this.closeWindow(item.element);
      });
      this.windowStack = [];
      this.notifyTaskSwitcher();
    }

    /**
     * 最小化所有窗口
     */
    minimizeAllWindows() {
      this.windowStack.forEach(item => {
        item.element.classList.add('minimized');
        item.element.style.display = 'none';
      });
    }

    /**
     * 适配已存在的窗口
     */
    adaptExistingWindows() {
      const windows = document.querySelectorAll('.window-container:not([data-mobile="true"])');
      windows.forEach(win => {
        const appId = win.dataset.appId || 'unknown';
        this.adaptWindow(appId);
      });
    }

    /**
     * 监听窗口变化
     */
    setupWindowObserver() {
      const self = this;

      const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.type === 'childList') {
            mutation.addedNodes.forEach((node) => {
              if (node.nodeType === 1 && node.classList && 
                  node.classList.contains('window-container') &&
                  !node.dataset.mobile) {
                // 新窗口自动适配
                const appId = node.dataset.appId || 'unknown';
                self.adaptWindow(appId);
              }
            });

            // 检测窗口移除
            mutation.removedNodes.forEach((node) => {
              if (node.nodeType === 1 && node.classList && 
                  node.classList.contains('window-container')) {
                const appId = node.dataset.appId;
                if (appId) {
                  self.removeFromStack(appId);
                  self.notifyTaskSwitcher();
                }
              }
            });
          }
        });
      });

      // 监听窗口容器
      const container = document.getElementById('app-container') || document.body;
      observer.observe(container, {
        childList: true,
        subtree: true
      });

      this.windowObserver = observer;
    }

    /**
     * 通知任务切换器更新
     */
    notifyTaskSwitcher() {
      // 如果存在任务切换器，触发更新事件
      const event = new CustomEvent('window-stack-changed', {
        detail: {
          windows: this.windowStack,
          count: this.windowStack.length
        }
      });
      document.dispatchEvent(event);
    }

    /**
     * 获取窗口栈信息
     */
    getWindowStackInfo() {
      return this.windowStack.map(item => ({
        appId: item.appId,
        title: item.element.querySelector('.window-title')?.textContent || item.appId,
        isActive: item.element.classList.contains('active')
      }));
    }

    /**
     * 清理资源
     */
    destroy() {
      if (this.windowObserver) {
        this.windowObserver.disconnect();
      }
      this.windowStack = [];
      this.isInitialized = false;
    }
  }

  // ============================================
  // 创建全局实例（等待 MobileIconAdapter 加载）
  // ============================================

  // 等待 MobileIconAdapter 加载完成
  const checkIconAdapter = setInterval(() => {
    if (window.MobileIconAdapter) {
      clearInterval(checkIconAdapter);
      // 创建窗口适配器实例
      if (!window.MobileWindowAdapter) {
        window.MobileWindowAdapter = new MobileWindowAdapter();
        console.log('[MobileWindowAdapter] 已就绪');
      }
    }
  }, 50);

  // 超时保护
  setTimeout(() => {
    clearInterval(checkIconAdapter);
    if (!window.MobileWindowAdapter) {
      window.MobileWindowAdapter = new MobileWindowAdapter();
      console.log('[MobileWindowAdapter] 已就绪 (超时)');
    }
  }, 3000);

  // 导出到全局
  window.MobileWindowAdapter = window.MobileWindowAdapter || new MobileWindowAdapter();

})();