import { Tray, Menu, nativeImage, BrowserWindow, app, NativeImage } from 'electron'
import * as path from 'path'
import type { StoreType } from './storeTypes'

let tray: Tray | null = null

export function setupTray(
  mainWindow: BrowserWindow | null,
  store: StoreType
) {
  const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged

  // In dev: __dirname is dist/main/main/, in prod: same
  const iconPath = isDev
    ? path.join(__dirname, '../../../resources/icon.ico')
    : path.join(__dirname, '../../../resources/icon.ico')

  // Create tray icon
  let trayIcon: NativeImage
  try {
    trayIcon = nativeImage.createFromPath(iconPath)
    if (trayIcon.isEmpty()) {
      trayIcon = nativeImage.createEmpty()
    }
  } catch {
    trayIcon = nativeImage.createEmpty()
  }

  // Resize for tray (16x16 on Windows)
  if (!trayIcon.isEmpty()) {
    trayIcon = trayIcon.resize({ width: 16, height: 16 })
  }

  tray = new Tray(trayIcon)
  tray.setToolTip('Game Marathon Tracker')

  const contextMenu = Menu.buildFromTemplate([
    {
      label: 'Открыть',
      click: () => {
        mainWindow?.show()
        mainWindow?.focus()
      },
    },
    { type: 'separator' },
    {
      label: 'Статус: Отслеживание',
      enabled: false,
    },
    { type: 'separator' },
    {
      label: 'Выход',
      click: () => {
        app.isQuitting = true
        app.quit()
      },
    },
  ])

  tray.setContextMenu(contextMenu)

  // Double-click to show window
  tray.on('double-click', () => {
    mainWindow?.show()
    mainWindow?.focus()
  })

  return tray
}

export function updateTrayMenu(
  mainWindow: BrowserWindow | null,
  isTracking: boolean,
  currentGame?: string
) {
  if (!tray) return

  const statusLabel = isTracking
    ? `Отслеживание: ${currentGame || 'Активно'}`
    : 'Отслеживание: Неактивно'

  const contextMenu = Menu.buildFromTemplate([
    {
      label: 'Открыть',
      click: () => {
        mainWindow?.show()
        mainWindow?.focus()
      },
    },
    { type: 'separator' },
    {
      label: statusLabel,
      enabled: false,
    },
    { type: 'separator' },
    {
      label: 'Выход',
      click: () => {
        app.isQuitting = true
        app.quit()
      },
    },
  ])

  tray.setContextMenu(contextMenu)
}

export function destroyTray() {
  if (tray) {
    tray.destroy()
    tray = null
  }
}

export { tray }
