// Engine.js - 引擎核心

import EventBus from '../utils/EventBus.js';
import ResourceManager from '../managers/ResourceManager.js';
import AudioManager from '../managers/AudioManager.js';
import TransitionManager from '../managers/TransitionManager.js';
import Camera from '../managers/Camera.js';
import { UIManager } from '../ui/UI.js';
import AnimationSystem from '../animation/AnimationSystem.js';
import AnimationController from '../animation/AnimationController.js';

// 导入元素类
import BaseElement from '../elements/BaseElement.js';
import Sprite from '../elements/Sprite.js';
import Box from '../elements/Box.js';
import TextElement from '../elements/TextElement.js';
import HtmlElement from '../elements/HtmlElement.js';
import SvgElement from '../elements/SvgElement.js';

class Engine {
  constructor() {
    // 设置全局引擎实例
    if (typeof window !== 'undefined') {
      window.PE_ENGINE = this;
    }

    const defaultOptions = {
      width: 800,
      height: 600,
      background: '#f0f0f0',
      fps: 60
    };

    this.options = { ...defaultOptions };
    this.width = this.options.width;
    this.height = this.options.height;
    this.element = document.body;
    this.id = Date.now().toString(16);
    this.fps = this.options.fps;
    this.frameTime = 1000 / this.fps;
    this.lastFrameTime = 0;
    this.running = false;

    // 核心管理器
    this.eventBus = new EventBus();
    this.resourceManager = new ResourceManager();
    this.audioManager = new AudioManager();
    this.transitionManager = new TransitionManager(this);
    this.camera = new Camera(this);
    this.animationSystem = new AnimationSystem();
    this.animationController = new AnimationController(this);

    // 场景相关
    this.routes = [];
    this.scenes = new Map();
    this.currentScene = null;
    this.currentPath = null;

    // 生命周期回调
    this.onLoadCallbacks = [];
    this.onShowCallbacks = [];
    this.onHideCallbacks = [];
    this.onDestoryCallbacks = [];

    // 游戏循环相关
    this.gameObjects = [];
    this.timers = [];
    this.intervals = [];

    // 输入处理
    this.input = {
      mouse: { x: 0, y: 0, isDown: false },
      keyboard: {}
    };

    // 插件系统
    this.plugins = new Map();
    
    this.createStage();
    
    // 在stage创建之后初始化UIManager
    this.uiManager = new UIManager(this);
    
    this.setupInputHandlers();
    this.startGameLoop();
    
    // 加载路由
    this.loadRoutesFromConfig();
  }

  createStage() {
    // 清除body中的所有内容
    while (this.element.firstChild) {
      this.element.removeChild(this.element.firstChild);
    }
    
    this.stage = document.createElement('div');
    this.stage.setAttribute('data-engine-id', this.id);

    Object.assign(this.stage.style, {
      width: `${this.options.width}px`,
      height: `${this.options.height}px`,
      position: 'relative',
      userSelect: 'none',
      overflow: 'hidden',
      background: this.options.background,
      transform: 'translateZ(0)',
      border: '2px solid red', // 添加红色边框以便调试
      margin: '0 auto', // 居中显示
      zIndex: '1',
    });

    // 添加舞台操作方法
    this.stage.add = child => child && this.stage.appendChild(child.element || child);
    this.stage.remove = child => child && this.stage.removeChild(child.element || child);

    this.element.appendChild(this.stage);
    console.log('Stage created');
  }

  // 设置输入处理器
  setupInputHandlers() {
    // 鼠标事件
    this.stage.addEventListener('mousemove', (e) => {
      const rect = this.stage.getBoundingClientRect();
      this.input.mouse.x = e.clientX - rect.left;
      this.input.mouse.y = e.clientY - rect.top;
      this.eventBus.emit('mouseMove', { x: this.input.mouse.x, y: this.input.mouse.y });
    });

    this.stage.addEventListener('mousedown', (e) => {
      this.input.mouse.isDown = true;
      this.eventBus.emit('mouseDown', { x: this.input.mouse.x, y: this.input.mouse.y });
    });

    this.stage.addEventListener('mouseup', (e) => {
      this.input.mouse.isDown = false;
      this.eventBus.emit('mouseUp', { x: this.input.mouse.x, y: this.input.mouse.y });
    });

    // 键盘事件
    document.addEventListener('keydown', (e) => {
      this.input.keyboard[e.key] = true;
      this.eventBus.emit('keyDown', { key: e.key, code: e.code });
    });

    document.addEventListener('keyup', (e) => {
      this.input.keyboard[e.key] = false;
      this.eventBus.emit('keyUp', { key: e.key, code: e.code });
    });
  }

  // 从配置文件加载路由
  async loadRoutesFromConfig() {
    try {
      // 尝试加载路由配置
      const routesModule = await import('../../template-example/sences.json');
      this.routes = routesModule.default.sence || routesModule.sence || [];
      console.log('Routes loaded:', this.routes);
      
      // 如果有默认路径，自动切换到第一个场景
      if (this.routes && this.routes.length > 0) {
        const defaultRoute = this.routes[0];
        // 延迟一会儿再切换，确保初始化完成
        setTimeout(() => {
          console.log('Switching to default route:', defaultRoute.path);
          this.switchToPath(defaultRoute.path);
        }, 100);
      }
    } catch (error) {
      console.warn('Failed to load routes config:', error);
    }
  }

  // 游戏循环
  startGameLoop() {
    this.running = true;
    const loop = (timestamp) => {
      if (!this.running) return;
      
      // 计算时间差
      if (!this.lastFrameTime) this.lastFrameTime = timestamp;
      const deltaTime = timestamp - this.lastFrameTime;
      this.lastFrameTime = timestamp;
      
      // 控制帧率
      if (deltaTime >= this.frameTime) {
        this.update(deltaTime);
        this.render();
      }
      
      requestAnimationFrame(loop);
    };
    
    requestAnimationFrame(loop);
  }

  // 停止游戏循环
  stopGameLoop() {
    this.running = false;
  }

  // 更新逻辑
  update(deltaTime) {
    // 更新摄像机
    this.camera.update(deltaTime);
    
    // 更新UI管理器
    this.uiManager.update(deltaTime);
    
    // 更新动画系统
    this.animationSystem.update();
    
    // 更新所有游戏对象
    this.gameObjects.forEach(obj => {
      if (obj.update) obj.update(deltaTime);
    });
    
    // 更新计时器
    this.timers = this.timers.filter(timer => {
      timer.remaining -= deltaTime;
      if (timer.remaining <= 0) {
        timer.callback();
        return false;
      }
      return true;
    });
  }

  // 渲染
  render() {
    // 应用摄像机变换
    this.camera.apply();
    
    // 渲染所有游戏对象
    this.gameObjects.forEach(obj => {
      if (obj.render) obj.render();
    });
    
    // 渲染UI
    this.uiManager.render();
  }

  // 添加游戏对象
  addGameObject(obj) {
    this.gameObjects.push(obj);
    if (obj.element) {
      this.stage.add(obj);
    }
    return this;
  }

  // 移除游戏对象
  removeGameObject(obj) {
    const index = this.gameObjects.indexOf(obj);
    if (index !== -1) {
      this.gameObjects.splice(index, 1);
      if (obj.element && obj.element.parentNode) {
        this.stage.remove(obj);
      }
    }
    return this;
  }

  // 定时器
  setTimeout(callback, delay) {
    const timer = {
      callback,
      remaining: delay
    };
    this.timers.push(timer);
    return timer;
  }

  // 清除定时器
  clearTimeout(timer) {
    const index = this.timers.indexOf(timer);
    if (index !== -1) {
      this.timers.splice(index, 1);
    }
    return this;
  }

  // 间隔执行
  setInterval(callback, interval) {
    const intervalId = setInterval(callback, interval);
    this.intervals.push(intervalId);
    return intervalId;
  }

  // 清除间隔
  clearInterval(intervalId) {
    const index = this.intervals.indexOf(intervalId);
    if (index !== -1) {
      clearInterval(intervalId);
      this.intervals.splice(index, 1);
    }
    return this;
  }

  // 碰撞检测
  checkCollision(obj1, obj2) {
    // 简单的矩形碰撞检测
    return obj1.x < obj2.x + obj2.width &&
           obj1.x + obj1.width > obj2.x &&
           obj1.y < obj2.y + obj2.height &&
           obj1.y + obj1.height > obj2.y;
  }

  // 插件系统
  use(plugin, options = {}) {
    if (this.plugins.has(plugin.name)) {
      console.warn(`Plugin ${plugin.name} is already installed.`);
      return this;
    }

    if (typeof plugin.install === 'function') {
      plugin.install(this, options);
      this.plugins.set(plugin.name, plugin);
    }

    return this;
  }

  // 资源加载
  load(src) {
    return this.resourceManager.load(src);
  }

  // 音频管理
  loadSound(name, src, options) {
    return this.audioManager.loadSound(name, src, options);
  }

  loadMusic(name, src, options) {
    return this.audioManager.loadMusic(name, src, options);
  }

  playSound(name, options) {
    return this.audioManager.playSound(name, options);
  }

  playMusic(name, options) {
    return this.audioManager.playMusic(name, options);
  }

  stopMusic(name) {
    return this.audioManager.stopMusic(name);
  }

  pauseMusic(name) {
    return this.audioManager.pauseMusic(name);
  }

  resumeMusic(name) {
    return this.audioManager.resumeMusic(name);
  }

  setMasterVolume(volume) {
    return this.audioManager.setMasterVolume(volume);
  }

  setSoundVolume(volume) {
    return this.audioManager.setSoundVolume(volume);
  }

  setMusicVolume(volume) {
    return this.audioManager.setMusicVolume(volume);
  }

  // UI系统
  addUIElement(element) {
    return this.uiManager.addElement(element);
  }

  removeUIElement(element) {
    return this.uiManager.removeElement(element);
  }

  // 根据路径查找路由配置
  findRouteByPath(path) {
    const findRoute = (routes) => {
      for (const route of routes) {
        if (route.path === path) {
          return route;
        }
        if (route.extend) {
          const found = findRoute(route.extend);
          if (found) {
            return found;
          }
        }
      }
      return null;
    };
    
    return findRoute(this.routes);
  }

  // 根据路径加载场景
  async loadSceneByPath(path) {
    // 如果场景已加载，直接返回
    if (this.scenes.has(path)) {
      const scene = this.scenes.get(path);
      // 确保场景可见
      if (scene && scene.container) {
        scene.container.style.display = 'block';
        scene.container.style.visibility = 'visible';
      }
      return scene;
    }

    // 查找路由配置
    const route = this.findRouteByPath(path);
    if (!route) {
      throw new Error(`Route not found for path: ${path}`);
    }

    try {
      // 处理路径，根路径使用'index'目录
      const scenePath = path === '/' ? '/index' : path;
      
      // 加载场景模块
      const sceneModulePath = `/sence${scenePath}/index.pe`;
      console.log('Loading scene from:', sceneModulePath);
      const sceneText = await fetch(sceneModulePath).then(res => {
        if (!res.ok) {
          throw new Error(`Failed to load scene: ${res.status} ${res.statusText}`);
        }
        return res.text();
      });
      
      // 加载场景样式
      const sceneStylePath = `/sence${scenePath}/index.less`;
      console.log('Loading scene style from:', sceneStylePath);
      let sceneStyle = '';
      try {
        // 首先尝试加载预编译的样式模块
        try {
          const compiledStyleModule = await import(`../../template-example/compiled-styles${scenePath}/index.js`);
          sceneStyle = compiledStyleModule.default || compiledStyleModule.style || '';
          console.log('Loaded compiled scene style');
        } catch (importError) {
          // 如果预编译样式不存在，则回退到动态加载
          console.log('Compiled style not found, falling back to dynamic loading');
          sceneStyle = await fetch(sceneStylePath).then(res => {
            if (!res.ok) {
              console.warn(`Failed to load scene style: ${res.status} ${res.statusText}`);
              return '';
            }
            return res.text();
          });
          
          // 如果是.less文件，需要进行编译处理
          if (sceneStylePath.endsWith('.less') && sceneStyle.includes('{')) {
            // 简单的.less到CSS编译处理（移除注释和简单的变量替换）
            // 在实际项目中，这里应该使用完整的Less编译器
            sceneStyle = this.compileLessToCss(sceneStyle);
          }
        }
      } catch (styleError) {
        console.warn(`Failed to load scene style for path: ${path}`, styleError);
      }
      
      // 解析场景文件
      const scene = this.parseSceneFile(sceneText, sceneStyle, path);
      
      // 存储场景
      this.scenes.set(path, scene);
      
      return scene;
    } catch (error) {
      console.error(`Failed to load scene for path: ${path}`, error);
      throw error;
    }
  }

  // 解析场景文件
  parseSceneFile(content, style, path) {
    console.log('Parsing scene file for path:', path);
    
    // 提取模板部分
    const templateMatch = content.match(/<sence>([\s\S]*?)<\/sence>/i);
    const template = templateMatch ? templateMatch[1].trim() : '';
    
    // 提取脚本部分
    const scriptMatch = content.match(/<script>([\s\S]*?)<\/script>/i);
    const script = scriptMatch ? scriptMatch[1].trim() : '';
    
    // 创建场景对象
    const scene = {
      path,
      template,
      script,
      style,
      data: {},
      elements: new Map(),
      container: null,
      callbacks: {
        onLoad: [],
        onShow: [],
        onHide: [],
        onDestory: []
      }
    };
    
    // 创建场景容器
    scene.container = document.createElement('div');
    scene.container.classList.add('pe-scene-container');
    scene.container.setAttribute('data-scene-path', path);
    
    this.stage.appendChild(scene.container);
    console.log('Scene container created for path:', path);
    
    // 应用样式
    if (style) {
      this.applySceneStyle(scene, style);
    }
    
    // 解析脚本
    if (script) {
      this.parseSceneScript(scene, script);
    }
    
    // 解析模板
    if (template) {
      this.parseSceneTemplate(scene, template);
    }
    
    console.log('Scene parsed, container children:', scene.container.children.length);
    
    return scene;
  }

  // 应用场景样式
  applySceneStyle(scene, style) {
    // 生成场景特定的ID，用于样式隔离
    const sceneId = `pe-scene-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    scene.sceneId = sceneId;
    
    // 创建包含基础样式和用户样式的完整CSS内容
    // 使用属性选择器来确保样式只应用到当前场景的元素
    const fullStyleContent = `
      [data-scene-id="${sceneId}"] {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: block;
        border: 2px dashed green;
        z-index: 10;
        background-color: rgba(255, 255, 255, 0.9);
        visibility: visible;
        overflow: hidden;
      }
      
      [data-scene-id="${sceneId}"].pe-scene-inactive {
        display: none;
        visibility: hidden;
      }
      
      [data-scene-id="${sceneId}"].pe-scene-active {
        display: block;
        visibility: visible;
        z-index: 20;
        background-color: white;
      }
      
      [data-scene-id="${sceneId}"] .pe-element {
        position: absolute;
      }
      
      ${style}
    `;
    
    // 创建style元素而不是link元素，确保样式能立即应用
    const styleElement = document.createElement('style');
    styleElement.textContent = fullStyleContent;
    
    // 将样式元素添加到场景容器中
    scene.container.appendChild(styleElement);
    
    // 为场景容器添加特定的ID和类名，以便样式能正确应用
    scene.container.setAttribute('data-scene-id', sceneId);
    scene.container.classList.add('pe-scene-container');
  }
  
  

  // 解析场景模板
  parseSceneTemplate(scene, template) {
    console.log('Parsing scene template');
    
    // 创建临时容器来解析模板
    const tempContainer = document.createElement('div');
    tempContainer.innerHTML = template.trim();
    
    // 遍历所有元素
    const elements = Array.from(tempContainer.children);
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];
      this.parseElement(scene, element, i);
    }
    
    console.log('Scene template parsed, container children:', scene.container.children.length);
  }

  // 递归解析元素
  parseElement(scene, element, index, parentData = null) {
    const tagName = element.tagName.toLowerCase();
    const className = element.className;
    const clickHandler = element.getAttribute('@click');
    const forAttr = element.getAttribute('for');
    
    console.log(`Parsing element: ${tagName}, class: ${className}, for: ${forAttr}`);
    
    // 处理for循环
    if (forAttr) {
      this.parseForLoop(scene, element, forAttr, index, parentData);
      return;
    }
    
    let peElement;
    
    // 根据标签名创建对应的PE元素
    switch (tagName) {
      case 'sprite':
        // 从元素属性中获取位置和尺寸信息
        const spriteX = parseInt(element.getAttribute('x')) || 100;
        const spriteY = parseInt(element.getAttribute('y')) || 100;
        const spriteWidth = parseInt(element.getAttribute('width')) || 100;
        const spriteHeight = parseInt(element.getAttribute('height')) || 100;
        peElement = this.create('sprite', { x: spriteX, y: spriteY, width: spriteWidth, height: spriteHeight });
        break;
      case 'box':
        // 从元素属性中获取位置和尺寸信息
        const boxX = parseInt(element.getAttribute('x')) || 100;
        const boxY = parseInt(element.getAttribute('y')) || 250;
        const boxWidth = parseInt(element.getAttribute('width')) || 200;
        const boxHeight = parseInt(element.getAttribute('height')) || 100;
        peElement = this.create('box', { x: boxX, y: boxY, width: boxWidth, height: boxHeight });
        break;
      case 'text':
        // 从元素属性中获取位置信息
        const textX = parseInt(element.getAttribute('x')) || 100;
        const textY = parseInt(element.getAttribute('y')) || 400;
        peElement = this.create('text', { text: element.textContent.trim() || 'Text Element', x: textX, y: textY });
        break;
      default:
        // 默认创建div元素
        const defaultElement = document.createElement('div');
        defaultElement.style.position = 'absolute';
        // 从元素属性中获取位置信息
        const defaultX = parseInt(element.getAttribute('x')) || 100;
        const defaultY = parseInt(element.getAttribute('y')) || 500;
        const defaultWidth = parseInt(element.getAttribute('width')) || 150;
        const defaultHeight = parseInt(element.getAttribute('height')) || 100;
        defaultElement.style.left = defaultX + 'px';
        defaultElement.style.top = defaultY + 'px';
        defaultElement.style.width = defaultWidth + 'px';
        defaultElement.style.height = defaultHeight + 'px';
        defaultElement.style.zIndex = '100';
        defaultElement.style.display = 'flex';
        defaultElement.style.alignItems = 'center';
        defaultElement.style.justifyContent = 'center';
        defaultElement.textContent = `Default ${tagName}`;
        peElement = defaultElement;
    }
    
    // 添加CSS类
    if (className) {
      const domElement = peElement.element || peElement;
      if (domElement instanceof HTMLElement) {
        domElement.classList.add(className);
      }
    }
    
    // 处理文本内容和插值
    if (element.textContent && tagName !== 'text') {
      const textContent = element.textContent.trim();
      if (textContent) {
        const domElement = peElement.element || peElement;
        if (domElement instanceof HTMLElement) {
          domElement.textContent = textContent;
        }
      }
    }
    
    // 添加点击事件处理
    if (clickHandler) {
      const domElement = peElement.element || peElement;
      if (domElement instanceof HTMLElement) {
        // 直接绑定事件处理函数
        try {
          domElement.addEventListener('click', (event) => {
            try {
              // 获取当前场景
              const scene = window.PE_ENGINE.currentScene;
              
              // 创建一个安全的执行环境
              const scope = {
                event: event  // 将事件对象添加到作用域中
              };
              if (scene && scene.data) {
                // 将场景中的所有数据和函数复制到作用域中
                Object.assign(scope, scene.data);
              }
              
              // 如果是for循环创建的元素，还需要将循环变量添加到作用域中
              if (parentData) {
                Object.assign(scope, parentData);
              }
              
              // 使用with语句创建正确的执行上下文
              // 这样可以确保在执行clickHandler时能够访问到scope中的所有变量和函数
              const handlerFunction = new Function('scope', 'event', `
                with (scope) {
                  ${clickHandler}
                }
              `);
              
              handlerFunction(scope, event);
            } catch (error) {
              console.error('Error in click handler:', error);
            }
          });
        } catch (error) {
          console.error('Error binding click handler:', error);
        }
      }
    }
    
    // 添加到场景
    const domElement = peElement.element || peElement;
    if (domElement instanceof HTMLElement) {
      // 添加通用的CSS类
      domElement.classList.add('pe-element');
      
      // 如果元素有类名，确保这些类名能正确应用样式
      if (className) {
        // 为元素添加场景ID作为前缀的类名，以确保样式隔离
        const classList = className.split(' ');
        classList.forEach(cls => {
          if (cls.trim()) {
            domElement.classList.add(cls.trim());
          }
        });
      }
      
      scene.elements.set(className || `element_${index}`, { element: domElement, peElement, type: tagName });
      scene.container.appendChild(domElement);
      
      // 确保元素可见，但不使用行内样式
      domElement.style.zIndex = '100';
      
      console.log(`Added element: ${tagName} with class: ${className}`);
    }
    
    // 递归处理子元素
    if (!forAttr) {
      const children = Array.from(element.children);
      for (let i = 0; i < children.length; i++) {
        this.parseElement(scene, children[i], `${index}_${i}`, parentData);
      }
    }
  }

  // 解析for循环
  parseForLoop(scene, element, forAttr, index, parentData) {
    console.log('Parsing for loop:', forAttr);
    
    // 解析for表达式，例如 "{label,action} in boxList"
    const match = forAttr.match(/\{([^}]+)\}\s+in\s+(\w+)/);
    if (!match) {
      console.warn('Invalid for loop syntax:', forAttr);
      // 如果不是有效的for循环语法，按普通元素处理
      this.parseElement(scene, element, index, parentData);
      return;
    }
    
    const vars = match[1].split(',').map(v => v.trim()); // [label, action]
    const arrayName = match[2]; // boxList
    
    // 立即处理循环
    this.processSingleLoop(scene, element, vars, arrayName, index);
  }
  
  // 处理单个循环
  processSingleLoop(scene, originalElement, vars, arrayName, index) {
    console.log('Processing loop for array:', arrayName);
    
    // 获取数组数据
    let arrayData = scene.data[arrayName];
    
    // 如果在场景数据中找不到，尝试在全局作用域中查找
    if (!arrayData && typeof window !== 'undefined') {
      arrayData = window[arrayName];
    }
    
    if (Array.isArray(arrayData)) {
      console.log(`Found array with ${arrayData.length} items`);
      
      // 为数组中的每个项目创建元素
      arrayData.forEach((item, i) => {
        console.log('Processing item:', item);
        
        // 克隆原始元素
        const elementClone = originalElement.cloneNode(true);
        
        // 设置数据上下文
        const itemData = typeof item === 'object' ? item : { item: item };
        
        // 替换插值表达式
        this.replaceInterpolations(elementClone, itemData);
        
        // 解析克隆的元素（注意：这里不递归处理for循环以防止无限递归）
        this.parseElementWithoutForLoop(scene, elementClone, `${index}_${i}`, itemData);
      });
    } else {
      console.warn(`Loop array ${arrayName} is not an array or not found`);
      // 如果数组不存在，仍然创建一个元素
      this.parseElementWithoutForLoop(scene, originalElement, index, null);
    }
  }
  
  // 解析元素但不处理for循环（防止无限递归）
  parseElementWithoutForLoop(scene, element, index, parentData = null) {
    const tagName = element.tagName.toLowerCase();
    const className = element.className;
    const clickHandler = element.getAttribute('@click');
    // 注意：这里不检查forAttr以防止无限递归
    
    console.log(`Parsing element without for loop: ${tagName}, class: ${className}`);
    
    let peElement;
    
    // 根据标签名创建对应的PE元素
    switch (tagName) {
      case 'sprite':
        // 从元素属性中获取位置和尺寸信息
        const spriteX = parseInt(element.getAttribute('x')) || 100;
        const spriteY = parseInt(element.getAttribute('y')) || 100;
        const spriteWidth = parseInt(element.getAttribute('width')) || 100;
        const spriteHeight = parseInt(element.getAttribute('height')) || 100;
        peElement = this.create('sprite', { x: spriteX, y: spriteY, width: spriteWidth, height: spriteHeight });
        break;
      case 'box':
        // 从元素属性中获取位置和尺寸信息
        const boxX = parseInt(element.getAttribute('x')) || 100;
        const boxY = parseInt(element.getAttribute('y')) || 250;
        const boxWidth = parseInt(element.getAttribute('width')) || 200;
        const boxHeight = parseInt(element.getAttribute('height')) || 100;
        peElement = this.create('box', { x: boxX, y: boxY, width: boxWidth, height: boxHeight });
        break;
      case 'text':
        // 从元素属性中获取位置信息
        const textX = parseInt(element.getAttribute('x')) || 100;
        const textY = parseInt(element.getAttribute('y')) || 400;
        peElement = this.create('text', { text: element.textContent.trim() || 'Text Element', x: textX, y: textY });
        break;
      default:
        // 默认创建div元素
        const defaultElement = document.createElement('div');
        defaultElement.style.position = 'absolute';
        // 从元素属性中获取位置信息
        const defaultX = parseInt(element.getAttribute('x')) || 100;
        const defaultY = parseInt(element.getAttribute('y')) || 500;
        const defaultWidth = parseInt(element.getAttribute('width')) || 150;
        const defaultHeight = parseInt(element.getAttribute('height')) || 100;
        defaultElement.style.left = defaultX + 'px';
        defaultElement.style.top = defaultY + 'px';
        defaultElement.style.width = defaultWidth + 'px';
        defaultElement.style.height = defaultHeight + 'px';
        defaultElement.style.zIndex = '100';
        defaultElement.style.display = 'flex';
        defaultElement.style.alignItems = 'center';
        defaultElement.style.justifyContent = 'center';
        defaultElement.textContent = `Default ${tagName}`;
        peElement = defaultElement;
    }
    
    // 添加CSS类
    if (className) {
      const domElement = peElement.element || peElement;
      if (domElement instanceof HTMLElement) {
        domElement.classList.add(className);
      }
    }
    
    // 处理文本内容和插值
    if (element.textContent && tagName !== 'text') {
      const textContent = element.textContent.trim();
      if (textContent) {
        const domElement = peElement.element || peElement;
        if (domElement instanceof HTMLElement) {
          domElement.textContent = textContent;
        }
      }
    }
    
    // 添加点击事件处理
    if (clickHandler) {
      const domElement = peElement.element || peElement;
      if (domElement instanceof HTMLElement) {
        // 直接绑定事件处理函数
        try {
          domElement.addEventListener('click', (event) => {
            try {
              // 获取当前场景
              const scene = window.PE_ENGINE.currentScene;
              
              // 创建一个安全的执行环境
              const scope = {
                event: event  // 将事件对象添加到作用域中
              };
              if (scene && scene.data) {
                // 将场景中的所有数据和函数复制到作用域中
                Object.assign(scope, scene.data);
              }
              
              // 如果是for循环创建的元素，还需要将循环变量添加到作用域中
              if (parentData) {
                Object.assign(scope, parentData);
              }
              
              // 使用with语句创建正确的执行上下文
              // 这样可以确保在执行clickHandler时能够访问到scope中的所有变量和函数
              const handlerFunction = new Function('scope', 'event', `
                with (scope) {
                  ${clickHandler}
                }
              `);
              
              handlerFunction(scope, event);
            } catch (error) {
              console.error('Error in click handler:', error);
            }
          });
        } catch (error) {
          console.error('Error binding click handler:', error);
        }
      }
    }
    
    // 添加到场景
    const domElement = peElement.element || peElement;
    if (domElement instanceof HTMLElement) {
      // 添加通用的CSS类
      domElement.classList.add('pe-element');
      
      // 如果元素有类名，确保这些类名能正确应用样式
      if (className) {
        // 为元素添加场景ID作为前缀的类名，以确保样式隔离
        const classList = className.split(' ');
        classList.forEach(cls => {
          if (cls.trim()) {
            domElement.classList.add(cls.trim());
          }
        });
      }
      
      scene.elements.set(className || `element_${index}`, { element: domElement, peElement, type: tagName });
      scene.container.appendChild(domElement);
      
      // 确保元素可见，但不使用行内样式
      domElement.style.zIndex = '100';
      
      console.log(`Added element: ${tagName} with class: ${className}`);
    }
    
    // 递归处理子元素（但不处理for循环）
    const children = Array.from(element.children);
    for (let i = 0; i < children.length; i++) {
      // 确保子元素也不处理for循环
      const childForAttr = children[i].getAttribute('for');
      if (!childForAttr) {
        this.parseElementWithoutForLoop(scene, children[i], `${index}_${i}`, parentData);
      }
    }
  }

  // 替换插值表达式
  replaceInterpolations(element, data) {
    // 处理元素的文本内容
    if (element.textContent) {
      let textContent = element.textContent;
      // 简单的插值替换
      Object.keys(data).forEach(key => {
        const regex = new RegExp(`{{\\s*${key}\\s*}}`, 'g');
        textContent = textContent.replace(regex, data[key]);
      });
      element.textContent = textContent;
    }
    
    // 递归处理子元素（添加深度限制防止栈溢出）
    const children = Array.from(element.children);
    for (let i = 0; i < children.length; i++) {
      this.replaceInterpolations(children[i], data);
    }
  }

  // 解析场景脚本
  parseSceneScript(scene, script) {
    console.log('Parsing scene script');
    
    try {
      // 创建一个函数来执行脚本
      const scriptFunction = new Function(`
        // 提供PE全局对象
        const PE = window.PE;
        
        // 定义生命周期函数
        const onLoad = (callback) => {
          if (typeof window !== 'undefined' && window.PE_ENGINE) {
            // 将回调函数存储在全局变量中，稍后在场景创建完成后移动到场景对象中
            if (!window.PE_ENGINE.pendingCallbacks) {
              window.PE_ENGINE.pendingCallbacks = { onLoad: [], onShow: [], onHide: [], onDestory: [] };
            }
            window.PE_ENGINE.pendingCallbacks.onLoad.push(callback);
          }
        };
        
        const onShow = (callback) => {
          if (typeof window !== 'undefined' && window.PE_ENGINE) {
            if (!window.PE_ENGINE.pendingCallbacks) {
              window.PE_ENGINE.pendingCallbacks = { onLoad: [], onShow: [], onHide: [], onDestory: [] };
            }
            window.PE_ENGINE.pendingCallbacks.onShow.push(callback);
          }
        };
        
        const onHide = (callback) => {
          if (typeof window !== 'undefined' && window.PE_ENGINE) {
            if (!window.PE_ENGINE.pendingCallbacks) {
              window.PE_ENGINE.pendingCallbacks = { onLoad: [], onShow: [], onHide: [], onDestory: [] };
            }
            window.PE_ENGINE.pendingCallbacks.onHide.push(callback);
          }
        };
        
        const onDestory = (callback) => {
          if (typeof window !== 'undefined' && window.PE_ENGINE) {
            if (!window.PE_ENGINE.pendingCallbacks) {
              window.PE_ENGINE.pendingCallbacks = { onLoad: [], onShow: [], onHide: [], onDestory: [] };
            }
            window.PE_ENGINE.pendingCallbacks.onDestory.push(callback);
          }
        };
        
        // 执行脚本
        ${script}
        
        // 返回脚本中定义的变量和函数
        return {
          boxList: typeof boxList !== 'undefined' ? boxList : undefined,
          onMenuClick: typeof onMenuClick !== 'undefined' ? onMenuClick : undefined
        };
      `);
      
      // 执行脚本
      const scriptResult = scriptFunction();
      
      // 将脚本中定义的数据存储到场景中
      if (scriptResult.boxList) {
        scene.data.boxList = scriptResult.boxList;
        console.log('BoxList loaded:', scene.data.boxList);
      }
      
      // 存储脚本中定义的函数
      if (scriptResult.onMenuClick) {
        scene.data.onMenuClick = scriptResult.onMenuClick;
      }
      
      // 将挂起的回调函数移动到场景对象中
      if (typeof window !== 'undefined' && window.PE_ENGINE && window.PE_ENGINE.pendingCallbacks) {
        const pending = window.PE_ENGINE.pendingCallbacks;
        scene.callbacks.onLoad.push(...pending.onLoad);
        scene.callbacks.onShow.push(...pending.onShow);
        scene.callbacks.onHide.push(...pending.onHide);
        scene.callbacks.onDestory.push(...pending.onDestory);
        
        // 清除挂起的回调函数
        window.PE_ENGINE.pendingCallbacks = null;
      }
      
    } catch (error) {
      console.error('Error executing scene script:', error);
    }
  }

  // 切换到指定路径的场景
  async switchToPath(path) {
    try {
      console.log('Switching to path:', path);
      
      // 隐藏当前场景
      if (this.currentScene) {
        this.currentScene.container.classList.remove('pe-scene-active');
        this.currentScene.container.classList.add('pe-scene-inactive');
        console.log('Hid current scene');
      }
      
      // 加载新场景
      const scene = await this.loadSceneByPath(path);
      
      // 显示新场景
      scene.container.classList.remove('pe-scene-inactive');
      scene.container.classList.add('pe-scene-active');
      
      console.log('Showing new scene, children:', scene.container.children.length);
      
      // 调用场景的onShow回调
      scene.callbacks.onShow.forEach(callback => {
        try {
          callback();
        } catch (error) {
          console.error('Error in onShow callback:', error);
        }
      });
      
      // 如果是首次加载，调用onLoad回调
      if (!scene.loaded) {
        scene.callbacks.onLoad.forEach(callback => {
          try {
            callback();
          } catch (error) {
            console.error('Error in onLoad callback:', error);
          }
        });
        scene.loaded = true;
      }
      
      // 设置为当前场景
      this.currentScene = scene;
      this.currentPath = path;
      
      // 触发场景切换事件
      this.eventBus.emit('sceneChanged', { path, scene });
      
      return scene;
    } catch (error) {
      console.error(`Failed to switch to scene: ${path}`, error);
      throw error;
    }
  }

  // 预加载场景
  async preloadScenes(paths) {
    const pathArray = Array.isArray(paths) ? paths : [paths];
    const promises = pathArray.map(path => this.loadSceneByPath(path));
    return Promise.all(promises);
  }

  // 获取当前路径
  getCurrentPath() {
    return this.currentPath;
  }

  // 获取当前场景
  getCurrentScene() {
    return this.currentScene;
  }

  // 获取场景元素
  getSceneElement(name) {
    if (this.currentScene && this.currentScene.elements.has(name)) {
      const elementObj = this.currentScene.elements.get(name);
      return elementObj.peElement || elementObj.element;
    }
    return null;
  }

  // 在场景上下文中获取元素的辅助方法
  getElement(name) {
    return this.getSceneElement(name);
  }

  // 摄像机控制
  setCameraPosition(x, y) {
    return this.camera.setPosition(x, y);
  }

  moveCamera(x, y) {
    return this.camera.move(x, y);
  }

  setCameraZoom(zoom) {
    return this.camera.setZoom(zoom);
  }

  setCameraRotation(rotation) {
    return this.camera.setRotation(rotation);
  }

  follow(target, offset) {
    return this.camera.follow(target, offset);
  }

  unfollow() {
    return this.camera.unfollow();
  }

  setCameraBounds(bounds) {
    return this.camera.setBounds(bounds);
  }

  shakeCamera(intensity, duration) {
    return this.camera.shake(intensity, duration);
  }

  getCamera() {
    return this.camera;
  }

  // 动画系统
  tween(target, duration, easing) {
    return this.animationSystem.tween(target, duration, easing);
  }

  // 高级动画控制器
  createFrameAnimation(name, frames, frameRate) {
    return this.animationController.createFrameAnimation(name, frames, frameRate);
  }

  playFrameAnimation(sprite, animationName, loop) {
    return this.animationController.playFrameAnimation(sprite, animationName, loop);
  }

  stopFrameAnimation(animationName) {
    return this.animationController.stopFrameAnimation(animationName);
  }

  createSequence(name, animations) {
    return this.animationController.createSequence(name, animations);
  }

  playSequence(sequenceName, loop) {
    return this.animationController.playSequence(sequenceName, loop);
  }

  stopSequence() {
    return this.animationController.stopSequence();
  }

  // 元素创建方法
  create(type, options = {}) {
    switch (type.toLowerCase()) {
      case 'sprite':
        return this.createSprite(options.image, options.x || 0, options.y || 0, options.width || 100, options.height || 100);
      case 'box':
        return this.createBox(options.x || 0, options.y || 0, options.width || 100, options.height || 100);
      case 'text':
        const textElement = this.createText(options.text || '', options.x || 0, options.y || 0);
        if (options.style) {
          textElement.setStyle(options.style);
        }
        return textElement;
      case 'html':
        return this.createHtml(options.html || '', options.x || 0, options.y || 0);
      case 'svg':
        return this.createSvg(options.x || 0, options.y || 0, options.width || 100, options.height || 100, options.content || '');
      default:
        throw new Error(`Unsupported element type: ${type}`);
    }
  }

  createSprite(img, x = 0, y = 0, width = 100, height = 100) {
    // 如果没有提供图片，创建一个默认的sprite
    if (!img) {
      // 创建一个简单的div元素作为sprite
      const spriteElement = document.createElement('div');
      spriteElement.style.position = 'absolute';
      spriteElement.style.left = x + 'px';
      spriteElement.style.top = y + 'px';
      spriteElement.style.width = width + 'px';
      spriteElement.style.height = height + 'px';
      
      // 添加setPosition和setSize方法
      spriteElement.setPosition = function(x, y) {
        this.style.left = x + 'px';
        this.style.top = y + 'px';
      };
      
      spriteElement.setSize = function(width, height) {
        this.style.width = width + 'px';
        this.style.height = height + 'px';
      };
      
      // 返回一个类似PE元素的对象
      return {
        element: spriteElement,
        setPosition: function(x, y) {
          spriteElement.setPosition(x, y);
        },
        setSize: function(width, height) {
          spriteElement.setSize(width, height);
        }
      };
    }
    
    const sprite = new Sprite(img, x, y, width, height, this.id);
    return sprite;
  }

  createBox(x = 0, y = 0, width = 100, height = 100) {
    const box = new Box(x, y, width, height, this.id);
    // 确保box可见
    box.element.style.zIndex = '100';
    box.element.style.position = 'absolute';
    return box;
  }

  createText(text = '', x = 0, y = 0) {
    const textElement = new TextElement(text, x, y, this.id);
    // 确保文本元素可见
    textElement.element.style.zIndex = '100';
    textElement.element.style.position = 'absolute';
    return textElement;
  }

  createHtml(html = '', x = 0, y = 0) {
    return new HtmlElement(html, x, y, this.id);
  }

  createSvg(x = 0, y = 0, width = 100, height = 100, content = '') {
    return new SvgElement(x, y, width, height, content, this.id);
  }

  destroy() {
    this.stopGameLoop();
    
    // 调用所有场景的onDestory回调
    this.scenes.forEach(scene => {
      if (scene.callbacks && scene.callbacks.onDestory) {
        scene.callbacks.onDestory.forEach(callback => {
          try {
            callback();
          } catch (error) {
            console.error('Error in onDestory callback:', error);
          }
        });
      }
    });
    
    if (this.stage && this.stage.parentNode) {
      this.stage.parentNode.removeChild(this.stage);
    }

    // 清理所有图像引用
    this.resourceManager.clear();

    // 停止所有动画
    this.animationSystem.stopAll();

    // 销毁UI管理器
    this.uiManager.destroy();

    // 清除所有间隔
    this.intervals.forEach(intervalId => clearInterval(intervalId));
    this.intervals = [];

    // 清除所有引用
    this.stage = null;
    this.element = null;
    this.options = null;
    this.gameObjects = [];
    this.timers = [];
    
    // 清除全局引用
    if (typeof window !== 'undefined' && window.PE_ENGINE === this) {
      window.PE_ENGINE = null;
    }
  }
}

export default Engine;