class GamepadController {
  constructor(options = {}) {
    this.options  = {
      ...{
        debug: false,
        deadZone: 0.1,
        updateInterval: 50,
        buttonsConfig: [
          { name: "Left2", index: 6 },
          { name: "Back", index: 8 },
          { name: "Right Joystick Press", index: 11 }
        ]
      },
      ...options 
    };
 
    this.gamepadIndex  = null;
    this.gamepad  = null;
    this.interval  = null;
    this.buttons  = [];
    this.directionAxis0_1  = "";
    this.directionAxis9  = "";
    this.angle = 0;
    this.rightJoystickPressed = false;
    this.speed = 0; // 添加速度属性
    // 初始化按钮状态 
    this.buttons  = this.options.buttonsConfig.map(button  => ({
      ...button,
      pressed: false 
    }));
 
    // 注册事件监听器 
    window.addEventListener("gamepadconnected",  this.onGamepadConnected.bind(this)); 
    window.addEventListener("gamepaddisconnected",  this.onGamepadDisconnected.bind(this)); 
 
    if (this.options.debug)  {
      console.log("GamepadController  initialized with options:", this.options); 
    }
  }
 
  onGamepadConnected(e) {
    console.log("Gamepad  connected:", e.gamepad); 
    this.gamepadIndex  = e.gamepad.index; 
    this.gamepad  = navigator.getGamepads()[this.gamepadIndex]; 
    this.startGamepad(); 
  }
 
  onGamepadDisconnected() {
    clearInterval(this.interval); 
    this.gamepad  = null;
    if (this.options.debug)  {
      console.log("Gamepad  disconnected");
    }
  }
 
  startGamepad() {
    this.interval  = setInterval(() => {
      const gamepads = navigator.getGamepads(); 
      const gamepad = gamepads[this.gamepadIndex];
      
      if (gamepad) {
        // 注释掉调试打印
        // if (this.options.debug)  {
        //   console.log('Axes  data:', {
        //     axis0: gamepad.axes[0], 
        //     axis1: gamepad.axes[1], 
        //     gamepadIndex: this.gamepadIndex  
        //   });
        // }
        
        this.updateDirection(gamepad.axes); 
        this.updateDirectionAxis9(gamepad.axes); 
        this.pressKey(gamepad.buttons); 
      }
    }, this.options.updateInterval); 
  }
 
  updateDirection(axes) {
    const axis0 = axes[0];
    const axis1 = axes[1];
 
    // 检查是否在死区 
    if (Math.abs(axis0) < this.options.deadZone && Math.abs(axis1) < this.options.deadZone) {
      this.directionAxis0_1 = "未定义";
      this.angle = 0;
      this.speed = 0; // 在死区时速度为0
      return;
    }
 
    // 计算速度（到原点的距离）
    // 使用勾股定理计算距离，并将结果限制在0-100之间
    const distance = Math.sqrt(axis0 * axis0 + axis1 * axis1);
    this.speed = Math.round(Math.min(distance * 100, 100));

    // 计算方向角度（0-360度）
    let angle = Math.atan2(axis1, axis0) * (180 / Math.PI);
    angle = (angle + 360) % 360;
    angle = Math.round(angle);
    this.angle = angle;
    
    // 更新方向数据 
    if (Math.abs(axis0) > this.options.deadZone || Math.abs(axis1) > this.options.deadZone) {
      this.directionAxis0_1 = `${angle}°`;
      // 注释掉调试打印
      // if (this.options.debug) {
      //   console.log(` 摇杆方向: ${angle}°, X轴: ${axis0.toFixed(2)}, Y轴: ${axis1.toFixed(2)}`);
      // }
    }
  }
 
  updateDirectionAxis9(axes) {
    const axis9 = axes[9];
    const roundedAxis9 = Math.round(axis9  * 100) / 100;
    if (roundedAxis9 <= -0.9) {
      this.directionAxis9  = 0;
    } else if (roundedAxis9 >= 0.0 && roundedAxis9 <= 0.2) {
      this.directionAxis9  = 1;
    // } else if (roundedAxis9 >= 0.6 && roundedAxis9 <= 0.8) {
    //   this.directionAxis9  = "左";
    // } else if (roundedAxis9 >= -0.5 && roundedAxis9 <= -0.4) {
    //   this.directionAxis9  = "右";
    } 
    else {
      this.directionAxis9  = 0;
    }
  }
 
  pressKey(buttons) {
    this.buttons.forEach(button => {
      const buttonData = buttons[button.index];
      button.pressed = buttonData ? buttonData.value === 1 : false;
      
      // 特别检查 Right Joystick Press 按钮
      if (button.name === "Right Joystick Press") {
        this.rightJoystickPressed = button.pressed;
      }
    });
  }
 
  destroy() {
    clearInterval(this.interval); 
    window.removeEventListener("gamepadconnected",  this.onGamepadConnected); 
    window.removeEventListener("gamepaddisconnected",  this.onGamepadDisconnected); 
    if (this.options.debug)  {
      console.log("GamepadController  destroyed");
    }
  }
}
 
// 导出类以便外部使用 
export default GamepadController;