/**
 * Android 三大金刚键 - 完整实现
 * 支持：返回、主页、多任务（含任务切换器）
 * 依赖: mobile-window.js
 */

(function() {
  'use strict';

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

  /**
   * Android 导航类
   */
  class AndroidNavigation {
    constructor() {
      this.isMobile = isMobile;
      this.isTaskSwitcherOpen = false;
      this.backPressCount = 0;
      this.backPressTimer = null;
      this.windowStack = [];
      this.isInitialized = false;

      // DOM 元素
      this.navBar = null;
      this.backBtn = null;
      this.homeBtn = null;
      this.tasksBtn = null;
      this.taskSwitcher = null;
      this.taskList = null;
      this.clearAllBtn = null;

      // 绑定方法
      this.handleBack = this.handleBack.bind(this);
      this.handleHome = this.handleHome.bind(this);
      this.handleTasks = this.handleTasks.bind(this);
      this.handleLongPressBack = this.handleLongPressBack.bind(this);
      this.handleLongPressHome = this.handleLongPressHome.bind(this);
      this.updateTaskList = this.updateTaskList.bind(this);
      this.closeTaskSwitcher = this.closeTaskSwitcher.bind(this);

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

      if (this.isMobile) {
        this.waitForDependencies();
      }
    }

    /**
     * 等待依赖加载完成
     */
    waitForDependencies() {
      const checkDeps = setInterval(() => {
        if (window.MobileWindowAdapter && window.MobileIconAdapter) {
          clearInterval(checkDeps);
          this.init();
        }
      }, 50);

      setTimeout(() => {
        clearInterval(checkDeps);
        if (!this.isInitialized) {
          console.warn('[AndroidNav] 依赖加载超时，强制初始化');
          this.init();
        }
      }, 5000);
    }

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

      this.createNavBar();
      this.createTaskSwitcher();
      this.bindEvents();
      this.setupWindowListener();
      this.updateTaskList();

      console.log('[AndroidNav] 三大金刚键已初始化');
    }

    /**
     * 创建导航栏 DOM
     */
    createNavBar() {
      if (document.getElementById('android-nav-bar')) {
        this.navBar = document.getElementById('android-nav-bar');
        this.backBtn = document.getElementById('navBack');
        this.homeBtn = document.getElementById('navHome');
        this.tasksBtn = document.getElementById('navTasks');
        return;
      }

      const navBar = document.createElement('div');
      navBar.id = 'android-nav-bar';
      navBar.className = 'android-nav-bar';
      navBar.innerHTML = `
        <div class="nav-bar-container">
          <button class="nav-btn nav-back" id="navBack" aria-label="返回">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
            </svg>
            <span class="tooltip">返回</span>
            <span class="double-tap-hint">再按一次返回桌面</span>
          </button>

          <button class="nav-btn nav-home" id="navHome" aria-label="主页">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
            </svg>
            <span class="tooltip">主页</span>
          </button>

          <button class="nav-btn nav-tasks" id="navTasks" aria-label="多任务">
            <svg viewBox="0 0 24 24" width="24" height="24">
              <path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z"/>
            </svg>
            <span class="tooltip">多任务</span>
          </button>
        </div>
      `;

      document.body.appendChild(navBar);

      this.navBar = navBar;
      this.backBtn = document.getElementById('navBack');
      this.homeBtn = document.getElementById('navHome');
      this.tasksBtn = document.getElementById('navTasks');
    }

    /**
     * 创建任务切换器 DOM
     */
    createTaskSwitcher() {
      if (document.getElementById('task-switcher')) {
        this.taskSwitcher = document.getElementById('task-switcher');
        this.taskList = document.getElementById('taskList');
        this.clearAllBtn = document.getElementById('clearAllTasks');
        return;
      }

      const switcher = document.createElement('div');
      switcher.id = 'task-switcher';
      switcher.className = 'task-switcher';
      switcher.innerHTML = `
        <div class="task-switcher-header">
          <span>最近任务</span>
          <button id="clearAllTasks">清除全部</button>
        </div>
        <div class="task-switcher-list" id="taskList">
          <div class="task-empty">暂无最近任务</div>
        </div>
      `;

      document.body.appendChild(switcher);

      this.taskSwitcher = switcher;
      this.taskList = document.getElementById('taskList');
      this.clearAllBtn = document.getElementById('clearAllTasks');
    }

    /**
     * 绑定事件
     */
    bindEvents() {
      // 返回键
      if (this.backBtn) {
        this.backBtn.addEventListener('click', this.handleBack);

        let longPressTimer = null;
        this.backBtn.addEventListener('touchstart', () => {
          longPressTimer = setTimeout(this.handleLongPressBack, 800);
        });
        this.backBtn.addEventListener('touchend', () => {
          clearTimeout(longPressTimer);
        });
        this.backBtn.addEventListener('touchmove', () => {
          clearTimeout(longPressTimer);
        });

        this.backBtn.addEventListener('mousedown', () => {
          longPressTimer = setTimeout(this.handleLongPressBack, 800);
        });
        this.backBtn.addEventListener('mouseup', () => {
          clearTimeout(longPressTimer);
        });
        this.backBtn.addEventListener('mouseleave', () => {
          clearTimeout(longPressTimer);
        });
      }

      // 主页键
      if (this.homeBtn) {
        this.homeBtn.addEventListener('click', this.handleHome);

        let longPressTimer = null;
        this.homeBtn.addEventListener('touchstart', () => {
          longPressTimer = setTimeout(this.handleLongPressHome, 800);
        });
        this.homeBtn.addEventListener('touchend', () => {
          clearTimeout(longPressTimer);
        });
        this.homeBtn.addEventListener('touchmove', () => {
          clearTimeout(longPressTimer);
        });

        this.homeBtn.addEventListener('mousedown', () => {
          longPressTimer = setTimeout(this.handleLongPressHome, 800);
        });
        this.homeBtn.addEventListener('mouseup', () => {
          clearTimeout(longPressTimer);
        });
        this.homeBtn.addEventListener('mouseleave', () => {
          clearTimeout(longPressTimer);
        });
      }

      // 多任务键
      if (this.tasksBtn) {
        this.tasksBtn.addEventListener('click', this.handleTasks);
      }

      // 清除所有任务
      if (this.clearAllBtn) {
        this.clearAllBtn.addEventListener('click', () => {
          this.clearAllTasks();
        });
      }

      // 点击任务切换器外部关闭
      if (this.taskSwitcher) {
        this.taskSwitcher.addEventListener('click', (e) => {
          if (e.target === this.taskSwitcher) {
            this.closeTaskSwitcher();
          }
        });
      }

      // ESC 键关闭任务切换器（PC 调试用）
      document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && this.isTaskSwitcherOpen) {
          this.closeTaskSwitcher();
        }
      });

      // 监听窗口栈变化
      document.addEventListener('window-stack-changed', () => {
        if (this.isTaskSwitcherOpen) {
          this.updateTaskList();
        }
      });
    }

    /**
     * 监听窗口变化
     */
    setupWindowListener() {
      const observer = new MutationObserver(() => {
        if (this.isTaskSwitcherOpen) {
          this.updateTaskList();
        }
      });

      const container = document.getElementById('app-container') || document.body;
      observer.observe(container, {
        childList: true,
        subtree: true
      });
    }

    // ============================================
    // 返回逻辑
    // ============================================

    handleBack() {
      if (this.isTaskSwitcherOpen) {
        this.closeTaskSwitcher();
        return;
      }

      const panels = document.querySelectorAll(
        '.start-menu.active, .notification-center.active, ' +
        '.control-center.active, .context-menu.active, ' +
        '.modal-overlay.active, .dropdown.active'
      );
      if (panels.length > 0) {
        panels.forEach(p => p.classList.remove('active'));
        panels.forEach(p => {
          const event = new CustomEvent('panel-closed', { detail: { panel: p } });
          document.dispatchEvent(event);
        });
        return;
      }

      const windowStack = window.MobileWindowAdapter?.getWindowStack?.() || [];
      if (windowStack.length > 0) {
        const topWindow = windowStack[windowStack.length - 1];
        if (topWindow && topWindow.element) {
          const closeBtn = topWindow.element.querySelector('.window-close-btn');
          if (closeBtn) {
            closeBtn.click();
            this.showToast('已关闭');
            return;
          }
        }
      }

      this.showBackToast();
    }

    /**
     * 长按返回 → 强制关闭当前应用
     */
    handleLongPressBack() {
      const windowStack = window.MobileWindowAdapter?.getWindowStack?.() || [];
      if (windowStack.length > 0) {
        const topWindow = windowStack[windowStack.length - 1];
        if (topWindow && topWindow.element) {
          const appId = topWindow.appId;
          if (appId && window.FluentOS) {
            window.FluentOS.closeApp(appId);
            this.showToast('已强制关闭应用');
          }
        }
      }
    }

    /**
     * 双击返回提示
     */
    showBackToast() {
      this.backPressCount++;
      if (this.backPressCount === 1) {
        const hint = this.backBtn?.querySelector('.double-tap-hint');
        if (hint) {
          hint.classList.add('show');
          setTimeout(() => hint.classList.remove('show'), 2000);
        }
        this.showToast('再按一次返回桌面');

        this.backPressTimer = setTimeout(() => {
          this.backPressCount = 0;
        }, 2000);
      } else if (this.backPressCount >= 2) {
        clearTimeout(this.backPressTimer);
        this.backPressCount = 0;
        this.handleHome();
      }
    }

    // ============================================
    // 主页逻辑
    // ============================================

    handleHome() {
      this.closeTaskSwitcher();

      if (window.MobileWindowAdapter) {
        window.MobileWindowAdapter.closeAllWindows();
      } else if (window.FluentOS) {
        window.FluentOS.closeAllWindows?.();
      }

      document.querySelectorAll('.active').forEach(el => {
        if (el.classList.contains('window-container')) return;
        el.classList.remove('active');
      });

      const desktop = document.getElementById('desktop');
      if (desktop) {
        desktop.style.display = 'block';
      }

      document.querySelectorAll('.window-container').forEach(win => {
        win.style.display = 'none';
      });

      this.showToast('回到桌面');
    }

    /**
     * 长按主页 → 打开助手
     */
    handleLongPressHome() {
      this.showToast('正在打开助手...');
      if (window.FluentOS && window.FluentOS.openApp) {
        window.FluentOS.openApp('fingo');
      } else {
        this.showToast('助手功能暂不可用');
      }
    }

    // ============================================
    // 多任务逻辑
    // ============================================

    handleTasks() {
      if (this.isTaskSwitcherOpen) {
        this.closeTaskSwitcher();
        return;
      }
      this.openTaskSwitcher();
    }

    openTaskSwitcher() {
      this.updateTaskList();
      if (this.taskSwitcher) {
        this.taskSwitcher.classList.add('active');
        this.isTaskSwitcherOpen = true;
        document.body.style.overflow = 'hidden';
      }
    }

    closeTaskSwitcher() {
      if (this.taskSwitcher) {
        this.taskSwitcher.classList.remove('active');
        this.isTaskSwitcherOpen = false;
        document.body.style.overflow = '';
      }
    }

    /**
     * 更新任务列表
     */
    updateTaskList() {
      if (!this.taskList) return;

      const tasks = this.getRunningApps();
      this.taskList.innerHTML = '';

      if (tasks.length === 0) {
        this.taskList.innerHTML = `
          <div class="task-empty">暂无最近任务</div>
        `;
        return;
      }

      tasks.forEach((task, index) => {
        const item = document.createElement('div');
        item.className = 'task-item';

        let iconHTML = '';
        if (window.MobileIconAdapter && task.appId) {
          iconHTML = window.MobileIconAdapter.getAppIcon(task.appId, 'medium');
        } else {
          iconHTML = `<span style="font-size:24px;">[?]</span>`;
        }

        item.innerHTML = `
          <div class="task-icon">${iconHTML}</div>
          <div class="task-info">
            <div class="task-name">${task.title || task.appId || '未命名应用'}</div>
            <div class="task-preview">${task.isActive ? '[当前运行]' : '点击切换'}</div>
          </div>
          <button class="task-close" data-index="${index}" aria-label="关闭任务">X</button>
        `;

        item.addEventListener('click', () => {
          this.switchToTask(index);
        });

        const closeBtn = item.querySelector('.task-close');
        if (closeBtn) {
          closeBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.closeTask(index);
          });
        }

        if (task.isActive) {
          item.style.borderColor = 'rgba(74, 158, 255, 0.3)';
          item.style.background = 'rgba(74, 158, 255, 0.08)';
        }

        this.taskList.appendChild(item);
      });
    }

    /**
     * 获取正在运行的应用
     */
    getRunningApps() {
      const apps = [];
      const windowStack = window.MobileWindowAdapter?.getWindowStack?.() || [];

      windowStack.forEach(item => {
        const title = item.element?.querySelector('.window-title')?.textContent ||
                      item.appId || '应用';
        const isActive = item.element?.classList?.contains('active') || false;
        const isVisible = item.element?.style?.display !== 'none';

        if (isVisible) {
          apps.push({
            appId: item.appId,
            title: title.trim(),
            element: item.element,
            isActive: isActive
          });
        }
      });

      return apps;
    }

    /**
     * 切换到指定任务
     */
    switchToTask(index) {
      const tasks = this.getRunningApps();
      if (tasks[index]) {
        const appId = tasks[index].appId;
        if (appId && window.MobileWindowAdapter) {
          window.MobileWindowAdapter.switchToWindow(appId);
        }
        this.closeTaskSwitcher();
      }
    }

    /**
     * 关闭单个任务
     */
    closeTask(index) {
      const tasks = this.getRunningApps();
      if (tasks[index]) {
        const appId = tasks[index].appId;
        if (appId && window.FluentOS) {
          window.FluentOS.closeApp(appId);
          setTimeout(() => {
            this.updateTaskList();
            if (this.getRunningApps().length === 0) {
              this.closeTaskSwitcher();
            }
          }, 300);
        }
      }
    }

    /**
     * 清除所有任务
     */
    clearAllTasks() {
      if (window.MobileWindowAdapter) {
        window.MobileWindowAdapter.closeAllWindows();
      }
      this.updateTaskList();
      this.showToast('已清除所有任务');
      setTimeout(() => {
        if (this.getRunningApps().length === 0) {
          this.closeTaskSwitcher();
        }
      }, 500);
    }

    // ============================================
    // Toast 提示
    // ============================================

    showToast(message, duration = 1500) {
      const existing = document.querySelector('.android-toast');
      if (existing) existing.remove();

      const toast = document.createElement('div');
      toast.className = 'android-toast';
      toast.textContent = message;
      document.body.appendChild(toast);

      setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(-50%) translateY(20px)';
        toast.style.transition = 'all 0.3s ease';
        setTimeout(() => toast.remove(), 300);
      }, duration);
    }

    // ============================================
    // 公共方法
    // ============================================

    getState() {
      return {
        isMobile: this.isMobile,
        isTaskSwitcherOpen: this.isTaskSwitcherOpen,
        windowCount: this.getRunningApps().length,
        isInitialized: this.isInitialized
      };
    }

    show() {
      if (this.navBar) {
        this.navBar.classList.remove('hidden');
        this.navBar.classList.add('visible');
      }
    }

    hide() {
      if (this.navBar) {
        this.navBar.classList.add('hidden');
        this.navBar.classList.remove('visible');
      }
    }

    toggle() {
      if (this.navBar) {
        this.navBar.classList.toggle('hidden');
      }
    }

    destroy() {
      if (this.navBar) {
        this.navBar.remove();
      }
      if (this.taskSwitcher) {
        this.taskSwitcher.remove();
      }
      this.isInitialized = false;
    }
  }

  // ============================================
  // 创建全局实例
  // ============================================

  const checkAdapter = setInterval(() => {
    if (window.MobileWindowAdapter) {
      clearInterval(checkAdapter);
      if (!window.AndroidNavigation) {
        window.AndroidNavigation = new AndroidNavigation();
        console.log('[AndroidNav] 已就绪');
      }
    }
  }, 50);

  setTimeout(() => {
    clearInterval(checkAdapter);
    if (!window.AndroidNavigation) {
      window.AndroidNavigation = new AndroidNavigation();
      console.log('[AndroidNav] 已就绪 (超时)');
    }
  }, 3000);

  window.AndroidNavigation = window.AndroidNavigation || new AndroidNavigation();

})();