// UI.js
// UI系统

class UIElement {
  constructor(x = 0, y = 0, width = 0, height = 0) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.visible = true;
    this.enabled = true;
    this.alpha = 1;
    this.children = [];
    this.parent = null;
    this.eventListeners = new Map();
  }

  // 设置位置
  setPosition(x, y) {
    this.x = x;
    this.y = y;
    return this;
  }

  // 设置尺寸
  setSize(width, height) {
    this.width = width;
    this.height = height;
    return this;
  }

  // 显示/隐藏
  setVisible(visible) {
    this.visible = visible;
    return this;
  }

  // 启用/禁用
  setEnabled(enabled) {
    this.enabled = enabled;
    return this;
  }

  // 设置透明度
  setAlpha(alpha) {
    this.alpha = alpha;
    return this;
  }

  // 添加子元素
  addChild(child) {
    if (child.parent) {
      child.parent.removeChild(child);
    }
    child.parent = this;
    this.children.push(child);
    return this;
  }

  // 移除子元素
  removeChild(child) {
    const index = this.children.indexOf(child);
    if (index !== -1) {
      child.parent = null;
      this.children.splice(index, 1);
    }
    return this;
  }

  // 事件处理
  on(event, callback) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event).push(callback);
    return this;
  }

  // 触发事件
  emit(event, data) {
    const listeners = this.eventListeners.get(event);
    if (listeners) {
      listeners.forEach(callback => callback(data));
    }
    return this;
  }

  // 检查点是否在元素内
  containsPoint(x, y) {
    return x >= this.x && x <= this.x + this.width &&
           y >= this.y && y <= this.y + this.height;
  }

  // 更新方法
  update(deltaTime) {
    this.children.forEach(child => {
      if (child.update) {
        child.update(deltaTime);
      }
    });
  }

  // 渲染方法
  render(context) {
    this.children.forEach(child => {
      if (child.visible && child.render) {
        child.render(context);
      }
    });
  }

  // 销毁方法
  destroy() {
    this.children.forEach(child => {
      if (child.destroy) {
        child.destroy();
      }
    });
    this.children = [];
    
    if (this.parent) {
      this.parent.removeChild(this);
    }
  }
}

class UIButton extends UIElement {
  constructor(x, y, width, height, text = '') {
    super(x, y, width, height);
    this.text = text;
    this.backgroundColor = '#ffffff';
    this.borderColor = '#000000';
    this.textColor = '#000000';
    this.hoverColor = '#f0f0f0';
    this.pressedColor = '#d0d0d0';
    this.borderWidth = 1;
    this.cornerRadius = 0;
    this.isHovered = false;
    this.isPressed = false;
    this.font = '16px Arial';
  }

  // 设置文本
  setText(text) {
    this.text = text;
    return this;
  }

  // 设置背景颜色
  setBackgroundColor(color) {
    this.backgroundColor = color;
    return this;
  }

  // 设置边框颜色
  setBorderColor(color) {
    this.borderColor = color;
    return this;
  }

  // 设置文本颜色
  setTextColor(color) {
    this.textColor = color;
    return this;
  }

  // 设置悬停颜色
  setHoverColor(color) {
    this.hoverColor = color;
    return this;
  }

  // 设置按下颜色
  setPressedColor(color) {
    this.pressedColor = color;
    return this;
  }

  // 设置边框宽度
  setBorderWidth(width) {
    this.borderWidth = width;
    return this;
  }

  // 设置圆角
  setCornerRadius(radius) {
    this.cornerRadius = radius;
    return this;
  }

  // 设置字体
  setFont(font) {
    this.font = font;
    return this;
  }

  // 处理鼠标进入
  onMouseEnter() {
    this.isHovered = true;
    this.emit('mouseenter');
  }

  // 处理鼠标离开
  onMouseLeave() {
    this.isHovered = false;
    this.isPressed = false;
    this.emit('mouseleave');
  }

  // 处理鼠标按下
  onMouseDown() {
    if (this.enabled) {
      this.isPressed = true;
      this.emit('mousedown');
    }
  }

  // 处理鼠标抬起
  onMouseUp() {
    if (this.enabled && this.isPressed) {
      this.isPressed = false;
      this.emit('mouseup');
      this.emit('click');
    }
  }

  // 渲染按钮
  render(context) {
    if (!this.visible) return;
    
    // 保存上下文
    context.save();
    
    // 设置透明度
    context.globalAlpha = this.alpha;
    
    // 确定背景颜色
    let bgColor = this.backgroundColor;
    if (this.isPressed && this.enabled) {
      bgColor = this.pressedColor;
    } else if (this.isHovered && this.enabled) {
      bgColor = this.hoverColor;
    }
    
    // 绘制背景
    context.fillStyle = bgColor;
    if (this.cornerRadius > 0) {
      this.drawRoundedRect(context, this.x, this.y, this.width, this.height, this.cornerRadius);
      context.fill();
    } else {
      context.fillRect(this.x, this.y, this.width, this.height);
    }
    
    // 绘制边框
    if (this.borderWidth > 0) {
      context.strokeStyle = this.borderColor;
      context.lineWidth = this.borderWidth;
      if (this.cornerRadius > 0) {
        this.drawRoundedRect(context, this.x, this.y, this.width, this.height, this.cornerRadius);
        context.stroke();
      } else {
        context.strokeRect(this.x, this.y, this.width, this.height);
      }
    }
    
    // 绘制文本
    if (this.text) {
      context.fillStyle = this.enabled ? this.textColor : '#888888';
      context.font = this.font;
      context.textAlign = 'center';
      context.textBaseline = 'middle';
      
      const textX = this.x + this.width / 2;
      const textY = this.y + this.height / 2;
      context.fillText(this.text, textX, textY);
    }
    
    // 恢复上下文
    context.restore();
    
    // 渲染子元素
    super.render(context);
  }

  // 绘制圆角矩形
  drawRoundedRect(context, x, y, width, height, radius) {
    context.beginPath();
    context.moveTo(x + radius, y);
    context.lineTo(x + width - radius, y);
    context.quadraticCurveTo(x + width, y, x + width, y + radius);
    context.lineTo(x + width, y + height - radius);
    context.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
    context.lineTo(x + radius, y + height);
    context.quadraticCurveTo(x, y + height, x, y + height - radius);
    context.lineTo(x, y + radius);
    context.quadraticCurveTo(x, y, x + radius, y);
    context.closePath();
  }
}

class UILabel extends UIElement {
  constructor(x, y, text = '') {
    super(x, y, 0, 0);
    this.text = text;
    this.color = '#000000';
    this.font = '16px Arial';
    this.align = 'left';
    this.baseline = 'top';
  }

  // 设置文本
  setText(text) {
    this.text = text;
    return this;
  }

  // 设置颜色
  setColor(color) {
    this.color = color;
    return this;
  }

  // 设置字体
  setFont(font) {
    this.font = font;
    return this;
  }

  // 设置对齐方式
  setAlign(align) {
    this.align = align;
    return this;
  }

  // 设置基线
  setBaseline(baseline) {
    this.baseline = baseline;
    return this;
  }

  // 渲染标签
  render(context) {
    if (!this.visible || !this.text) return;
    
    // 保存上下文
    context.save();
    
    // 设置透明度
    context.globalAlpha = this.alpha;
    
    // 绘制文本
    context.fillStyle = this.color;
    context.font = this.font;
    context.textAlign = this.align;
    context.textBaseline = this.baseline;
    context.fillText(this.text, this.x, this.y);
    
    // 恢复上下文
    context.restore();
    
    // 渲染子元素
    super.render(context);
  }
}

class UIImage extends UIElement {
  constructor(x, y, width, height, image = null) {
    super(x, y, width, height);
    this.image = image;
    this.sourceX = 0;
    this.sourceY = 0;
    this.sourceWidth = 0;
    this.sourceHeight = 0;
  }

  // 设置图像
  setImage(image) {
    this.image = image;
    if (image && !this.sourceWidth) {
      this.sourceWidth = image.width;
      this.sourceHeight = image.height;
    }
    return this;
  }

  // 设置源矩形
  setSourceRect(x, y, width, height) {
    this.sourceX = x;
    this.sourceY = y;
    this.sourceWidth = width;
    this.sourceHeight = height;
    return this;
  }

  // 渲染图像
  render(context) {
    if (!this.visible || !this.image) return;
    
    // 保存上下文
    context.save();
    
    // 设置透明度
    context.globalAlpha = this.alpha;
    
    // 绘制图像
    if (this.sourceWidth > 0 && this.sourceHeight > 0) {
      context.drawImage(
        this.image,
        this.sourceX, this.sourceY, this.sourceWidth, this.sourceHeight,
        this.x, this.y, this.width, this.height
      );
    } else {
      context.drawImage(this.image, this.x, this.y, this.width, this.height);
    }
    
    // 恢复上下文
    context.restore();
    
    // 渲染子元素
    super.render(context);
  }
}

class UISlider extends UIElement {
  constructor(x, y, width, height, min = 0, max = 100, value = 50) {
    super(x, y, width, height);
    this.min = min;
    this.max = max;
    this.value = value;
    this.backgroundColor = '#cccccc';
    this.fillColor = '#007acc';
    this.handleColor = '#ffffff';
    this.borderColor = '#000000';
    this.borderWidth = 1;
    this.handleRadius = 8;
    this.isDragging = false;
  }

  // 设置最小值
  setMin(min) {
    this.min = min;
    this.value = Math.max(this.min, Math.min(this.max, this.value));
    return this;
  }

  // 设置最大值
  setMax(max) {
    this.max = max;
    this.value = Math.max(this.min, Math.min(this.max, this.value));
    return this;
  }

  // 设置值
  setValue(value) {
    this.value = Math.max(this.min, Math.min(this.max, value));
    this.emit('change', this.value);
    return this;
  }

  // 设置背景颜色
  setBackgroundColor(color) {
    this.backgroundColor = color;
    return this;
  }

  // 设置填充颜色
  setFillColor(color) {
    this.fillColor = color;
    return this;
  }

  // 设置手柄颜色
  setHandleColor(color) {
    this.handleColor = color;
    return this;
  }

  // 设置边框颜色
  setBorderColor(color) {
    this.borderColor = color;
    return this;
  }

  // 设置边框宽度
  setBorderWidth(width) {
    this.borderWidth = width;
    return this;
  }

  // 设置手柄半径
  setHandleRadius(radius) {
    this.handleRadius = radius;
    return this;
  }

  // 处理鼠标按下
  onMouseDown(x, y) {
    if (!this.enabled) return;
    
    this.isDragging = true;
    this.updateValueFromPosition(x);
    this.emit('mousedown');
  }

  // 处理鼠标移动
  onMouseMove(x, y) {
    if (!this.enabled || !this.isDragging) return;
    
    this.updateValueFromPosition(x);
  }

  // 处理鼠标抬起
  onMouseUp(x, y) {
    if (!this.enabled || !this.isDragging) return;
    
    this.isDragging = false;
    this.emit('mouseup');
    this.emit('change', this.value);
  }

  // 根据位置更新值
  updateValueFromPosition(x) {
    const handleX = Math.max(this.x, Math.min(this.x + this.width, x));
    const ratio = (handleX - this.x) / this.width;
    this.value = this.min + ratio * (this.max - this.min);
    this.emit('drag', this.value);
  }

  // 获取手柄位置
  getHandlePosition() {
    const ratio = (this.value - this.min) / (this.max - this.min);
    return this.x + ratio * this.width;
  }

  // 渲染滑块
  render(context) {
    if (!this.visible) return;
    
    // 保存上下文
    context.save();
    
    // 设置透明度
    context.globalAlpha = this.alpha;
    
    // 绘制背景
    context.fillStyle = this.backgroundColor;
    context.fillRect(this.x, this.y, this.width, this.height);
    
    // 绘制填充
    const fillWidth = ((this.value - this.min) / (this.max - this.min)) * this.width;
    context.fillStyle = this.fillColor;
    context.fillRect(this.x, this.y, fillWidth, this.height);
    
    // 绘制边框
    if (this.borderWidth > 0) {
      context.strokeStyle = this.borderColor;
      context.lineWidth = this.borderWidth;
      context.strokeRect(this.x, this.y, this.width, this.height);
    }
    
    // 绘制手柄
    const handleX = this.getHandlePosition();
    const handleY = this.y + this.height / 2;
    
    context.fillStyle = this.handleColor;
    context.beginPath();
    context.arc(handleX, handleY, this.handleRadius, 0, Math.PI * 2);
    context.fill();
    
    context.strokeStyle = this.borderColor;
    context.lineWidth = this.borderWidth;
    context.stroke();
    
    // 恢复上下文
    context.restore();
    
    // 渲染子元素
    super.render(context);
  }
}

class UIManager {
  constructor(engine) {
    this.engine = engine;
    this.elements = [];
    this.canvas = null;
    this.context = null;
    this.setupCanvas();
    this.setupEventListeners();
  }

  // 设置画布
  setupCanvas() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.engine.width;
    this.canvas.height = this.engine.height;
    this.canvas.style.position = 'absolute';
    this.canvas.style.top = '0';
    this.canvas.style.left = '0';
    this.canvas.style.pointerEvents = 'none'; // 允许事件穿透到舞台
    
    this.context = this.canvas.getContext('2d');
    
    // 将UI画布添加到舞台
    this.engine.stage.appendChild(this.canvas);
  }

  // 设置事件监听器
  setupEventListeners() {
    // 鼠标事件
    this.engine.stage.addEventListener('mousemove', (e) => {
      const rect = this.engine.stage.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      this.handleMouseMove(x, y);
    });
    
    this.engine.stage.addEventListener('mousedown', (e) => {
      const rect = this.engine.stage.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      this.handleMouseDown(x, y);
    });
    
    this.engine.stage.addEventListener('mouseup', (e) => {
      const rect = this.engine.stage.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      
      this.handleMouseUp(x, y);
    });
  }

  // 处理鼠标移动
  handleMouseMove(x, y) {
    this.elements.forEach(element => {
      if (element.enabled && element.visible) {
        const wasHovered = element.isHovered;
        const isHovered = element.containsPoint(x, y);
        
        if (isHovered && !wasHovered && element.onMouseEnter) {
          element.onMouseEnter();
        } else if (!isHovered && wasHovered && element.onMouseLeave) {
          element.onMouseLeave();
        }
        
        if (element.isDragging && element.onMouseMove) {
          element.onMouseMove(x, y);
        }
      }
    });
  }

  // 处理鼠标按下
  handleMouseDown(x, y) {
    // 从后向前遍历，确保上层元素优先处理事件
    for (let i = this.elements.length - 1; i >= 0; i--) {
      const element = this.elements[i];
      if (element.enabled && element.visible && element.containsPoint(x, y)) {
        if (element.onMouseDown) {
          element.onMouseDown(x, y);
        }
        // 找到第一个匹配的元素就停止
        break;
      }
    }
  }

  // 处理鼠标抬起
  handleMouseUp(x, y) {
    this.elements.forEach(element => {
      if (element.enabled && element.visible) {
        if (element.onMouseUp) {
          element.onMouseUp(x, y);
        }
      }
    });
  }

  // 添加UI元素
  addElement(element) {
    this.elements.push(element);
    return this;
  }

  // 移除UI元素
  removeElement(element) {
    const index = this.elements.indexOf(element);
    if (index !== -1) {
      this.elements.splice(index, 1);
    }
    return this;
  }

  // 更新UI
  update(deltaTime) {
    this.elements.forEach(element => {
      if (element.update) {
        element.update(deltaTime);
      }
    });
  }

  // 渲染UI
  render() {
    if (!this.context) return;
    
    // 清空画布
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 渲染所有UI元素
    this.elements.forEach(element => {
      if (element.visible && element.render) {
        element.render(this.context);
      }
    });
  }

  // 调整大小
  resize(width, height) {
    if (this.canvas) {
      this.canvas.width = width;
      this.canvas.height = height;
    }
  }

  // 销毁UI管理器
  destroy() {
    this.elements.forEach(element => {
      if (element.destroy) {
        element.destroy();
      }
    });
    this.elements = [];
    
    if (this.canvas && this.canvas.parentNode) {
      this.canvas.parentNode.removeChild(this.canvas);
    }
    
    this.canvas = null;
    this.context = null;
  }
}

export {
  UIElement,
  UIButton,
  UILabel,
  UIImage,
  UISlider,
  UIManager
};