const { app, BrowserWindow, globalShortcut } = require('electron')
const path = require('path')
const { startServer } = require('./server')

let server = null
let PORT = null

app.whenReady().then(async () => {
  try {
    // 启动本地服务器
    const serverInfo = await startServer()
    server = serverInfo.server
    PORT = serverInfo.PORT

    const sceneArg = process.argv.find(a => a.startsWith('--scene='))
    const query = sceneArg ? { scene: sceneArg.split('=')[1] } : {}

    const win = new BrowserWindow({
      width: 1280,
      height: 720,
      minWidth: 800,
      minHeight: 600,
      resizable: true,
      maximizable: true,
      minimizable: true,
      closable: true,
      autoHideMenuBar: false,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js')
      },
      icon: path.join(__dirname, '..', 'public', 'icon.png') // 应用图标
    })

    // 注册全屏切换快捷键 (F11 或 Command+F)
    globalShortcut.register('F11', () => {
      win.setFullScreen(!win.isFullScreen())
    })

    // 注册退出快捷键 (Alt+F4 或 Command+Q)
    globalShortcut.register('Alt+F4', () => {
      app.quit()
    })

    // 构建查询参数字符串
    const queryString = new URLSearchParams(query).toString()
    const url = queryString ? `http://127.0.0.1:${PORT}/index.html?${queryString}` : `http://127.0.0.1:${PORT}/index.html`

    console.log('🚀 Loading app from:', url)
    win.loadURL(url)

    // 打开开发者工具，方便调试（生产环境可以注释掉）
    // win.webContents.openDevTools()
  } catch (error) {
    console.error('❌ Failed to start app:', error)
    app.quit()
  }
})

app.on('window-all-closed', () => {
  // 取消注册所有快捷键
  globalShortcut.unregisterAll()
  if (server) {
    server.close() // 关闭服务器
  }
  app.quit()
})

app.on('before-quit', () => {
  // 取消注册所有快捷键
  globalShortcut.unregisterAll()
  if (server) {
    server.close() // 确保服务器被关闭
  }
})

// 防止应用在 Mac 上关闭窗口后退出
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    app.whenReady().then(() => {
      // 重新创建窗口的逻辑
    })
  }
})
