import { app, BrowserWindow, dialog, session } from 'electron'
import { join } from 'path'
import { installCloseGuard, registerIpc } from './ipc'
import { closeAllScreens, setBroadcast, setMainWindow } from './screens'
import { loadSettings } from './settings'
import { readProjectFile } from './project'
import type { ProjectJson } from './project'
import { parseArgv } from './shortcuts'
import { pushLoad, setPendingLoad } from './loader'
import type { LoadPayload } from './loader'

let mainWindow: BrowserWindow | null = null

function sendScreensChanged(list: unknown): void {
  mainWindow?.webContents.send('screens:changed', list)
}

function createWindow(): void {
  mainWindow = new BrowserWindow({
    width: 1420,
    height: 900,
    minWidth: 1120,
    minHeight: 700,
    show: false,
    frame: false,
    backgroundColor: '#eef3fa',
    icon: join(app.getAppPath(), 'build/icon.ico'),
    title: `智慧农业大数据可视化控制中心 v${app.getVersion()}`,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
      webviewTag: true,
      spellcheck: false
    }
  })

  mainWindow.on('ready-to-show', () => mainWindow?.show())

  // 页面 <title> 会覆盖构造标题，加载完成后统一为带版本号标题（任务栏/Alt+Tab 显示）
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow?.setTitle(`智慧农业大数据可视化控制中心 v${app.getVersion()}`)
  })
  mainWindow.on('closed', () => {
    setMainWindow(null)
    mainWindow = null
  })

  setMainWindow(mainWindow)

  mainWindow.on('maximize', () => mainWindow?.webContents.send('win:maximized', true))
  mainWindow.on('unmaximize', () => mainWindow?.webContents.send('win:maximized', false))

  installCloseGuard(mainWindow)

  const devUrl = process.env['ELECTRON_RENDERER_URL']
  if (devUrl) {
    void mainWindow.loadURL(devUrl)
  } else {
    void mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

/** 快捷方式启动参数：打开指定工程并进入编辑/发布状态 */
async function handleLaunch(parsed: { project?: string; mode?: 'edit' | 'publish' }): Promise<void> {
  if (!parsed.project) return
  const settings = await loadSettings()
  const res = await readProjectFile(parsed.project, settings.jsonPassword)
  if (!res.json) {
    void dialog.showMessageBox({
      type: 'error',
      title: '打开项目失败',
      message:
        res.error === '密码错误'
          ? '密码错误，无法解密该工程文件。\n请先在工具「配置 → 项目信息」中设置正确的 JSON 读写密码后重试。'
          : res.error ?? '无法读取文件'
    })
    return
  }
  const payload: LoadPayload = { path: res.path, json: res.json as ProjectJson, mode: parsed.mode ?? 'edit' }
  setPendingLoad(payload)
  if (mainWindow && !mainWindow.isDestroyed()) {
    // second-instance / 已运行场景：实时推送（渲染层就绪时可直接收到）
    pushLoad(mainWindow, payload)
  }
}

const gotLock = app.requestSingleInstanceLock()

if (!gotLock) {
  app.quit()
} else {
  app.on('second-instance', (_e, argv) => {
    const parsed = parseArgv(argv)
    if (parsed.project) void handleLaunch(parsed)
    else if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })

  app.whenReady().then(async () => {
    // 麦克风测试权限
    session.defaultSession.setPermissionRequestHandler((_wc, permission, callback) => {
      callback(permission === 'media')
    })

    setBroadcast(sendScreensChanged)
    registerIpc()
    createWindow()

    // 快捷方式启动：打开指定工程
    const parsed = parseArgv(process.argv)
    if (parsed.project) await handleLaunch(parsed)

    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })

  app.on('before-quit', () => {
    closeAllScreens()
  })
}
