// Application entry point / 应用入口
import { MSG_TYPE } from './utils/constants.js'
import { GameEngine } from './game/engine.js'
import { LobbyUI } from './ui/lobby.js'
import './style.css'

// WebSocket server URL / WebSocket 服务器地址
const WS_URL = `ws://${window.location.hostname}:8080/ws`

/**
 * Main application class that manages lobby and game transitions / 主应用类，管理大厅和游戏之间的切换
 */
class App {
  constructor() {
    // Root DOM element / 根 DOM 元素
    this.appEl = document.getElementById('app')

    // Lobby container element / 大厅容器元素
    this.lobbyEl = document.createElement('div')
    // Game canvas element / 游戏画布元素
    this.gameCanvasEl = document.createElement('canvas')

    this.appEl.appendChild(this.lobbyEl)
    this.appEl.appendChild(this.gameCanvasEl)

    // Hide game canvas initially / 初始时隐藏游戏画布
    this.gameCanvasEl.style.display = 'none'

    // Game engine instance / 游戏引擎实例
    this.engine = null
    // Lobby UI instance / 大厅 UI 实例
    this.lobby = new LobbyUI(this.lobbyEl)

    // Player session info / 玩家会话信息
    this.playerId = null
    this.roomId = null
    this.isHost = false
    this.playerName = ''

    this._setupLobby()
  }

  // Set up lobby event callbacks / 设置大厅事件回调
  _setupLobby() {
    this.lobby.onCreateRoom = (name) => {
      this.playerName = name
      this._ensureConnection().then(() => {
        this.engine.network.createRoom(name)
      })
    }

    this.lobby.onJoinRoom = (roomId, name) => {
      this.playerName = name
      this._ensureConnection().then(() => {
        this.engine.network.joinRoom(roomId, name)
      })
    }

    this.lobby.onRefreshRooms = () => {
      this._ensureConnection().then(() => {
        this.engine.network.requestRoomList()
      })
    }

    this.lobby.onReady = () => {
      if (this.engine) this.engine.network.ready()
    }

    this.lobby.onStartGame = () => {
      if (this.engine) this.engine.network.startGame()
    }

    this.lobby.onLeaveRoom = () => {
      if (this.engine) {
        this.engine.network.leaveRoom()
        this.roomId = null
        this.isHost = false
        this.lobby.render()
      }
    }
  }

  // Ensure WebSocket connection is established / 确保 WebSocket 连接已建立
  async _ensureConnection() {
    if (!this.engine) {
      this.engine = new GameEngine(this.gameCanvasEl)
      try {
        await this.engine.connect(WS_URL)
        this._setupNetworkHandlers()
      } catch (e) {
        console.error('Failed to connect:', e)
        alert('Failed to connect to server. Make sure the server is running on port 8080.')
      }
    } else if (!this.engine.network.connected) {
      try {
        await this.engine.connect(WS_URL)
        this._setupNetworkHandlers()
      } catch (e) {
        console.error('Failed to reconnect:', e)
      }
    }
  }

  // Register network message handlers / 注册网络消息处理器
  _setupNetworkHandlers() {
    const net = this.engine.network

    // Handle room list updates / 处理房间列表更新
    net.on(MSG_TYPE.ROOM_LIST, (data) => {
      this.lobby.updateRoomList(data.rooms)
    })

    // Handle room state updates / 处理房间状态更新
    net.on(MSG_TYPE.ROOM_STATE, (data) => {
      if (data.playerId) {
        this.playerId = data.playerId
      } else if (!this.playerId) {
        console.warn('ROOM_STATE missing playerId / ROOM_STATE 缺少 playerId')
      }
      this.roomId = data.roomId
      this.isHost = data.isHost || false
      this.lobby.showRoom(data, this.isHost, this.playerId)
    })

    // Handle game start event / 处理游戏开始事件
    net.on(MSG_TYPE.GAME_STARTED, (data) => {
      this.playerId = data.playerId
      this.lobbyEl.style.display = 'none'
      this.gameCanvasEl.style.display = 'block'
    })

    // Handle error messages / 处理错误消息
    net.on(MSG_TYPE.ERROR, (data) => {
      console.error('Error:', data.message)
      alert(data.message)
    })
  }
}

// Initialize the application / 初始化应用
const app = new App()
