import { app, BrowserWindow, ipcMain } from 'electron'
import * as path from 'path'
import Store from 'electron-store'
import { setupTray, destroyTray } from './tray'
import { setupAutoLaunch } from './autolaunch'
import { setupIpcHandlers } from './ipc'
import { ProcessTracker } from './tracking/processTracker'
import { createSplashWindow, setupAutoUpdater, setupUpdateIpcHandlers } from './updater'
import type { StoreType } from './storeTypes'
import './storeTypes' // Import for global type declarations

// Initialize electron store
const store = new Store({
  defaults: {
    settings: {
      autoLaunch: false,
      minimizeToTray: true,
      trackingInterval: 5000,
      apiUrl: 'https://marathon.animeenigma.ru/api/v1',
      theme: 'dark',
    },
    token: null,
    trackedGames: {},
    trackingData: {},
  },
}) as StoreType

let mainWindow: BrowserWindow | null = null
let processTracker: ProcessTracker | null = null
let isMonitoringEnabled = false

const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged

// Prevent multiple instances
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
}

function createWindow() {
  // __dirname is dist/main/main/ in both dev and prod
  const iconPath = path.join(__dirname, '../../../resources/icon.ico')

  mainWindow = new BrowserWindow({
    width: 450,
    height: 750,
    resizable: false,
    frame: false,
    titleBarStyle: 'hidden',
    backgroundColor: '#0d0e14',
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      nodeIntegration: false,
      contextIsolation: true,
    },
    icon: iconPath,
  })

  // Load the app
  if (isDev) {
    mainWindow.loadURL('http://localhost:5173')
    mainWindow.webContents.openDevTools({ mode: 'detach' })
  } else {
    // In production: __dirname is dist/main/main/, so go up twice to dist/renderer/
    mainWindow.loadFile(path.join(__dirname, '../../renderer/index.html'))
  }

  // Handle close to tray
  mainWindow.on('close', (event) => {
    const settings = store.get('settings')
    if (settings.minimizeToTray && !app.isQuitting) {
      event.preventDefault()
      mainWindow?.hide()
    }
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  // Setup tray icon
  setupTray(mainWindow, store)

  return mainWindow
}


app.whenReady().then(async () => {
  // Setup IPC handlers
  setupIpcHandlers(store, () => mainWindow)
  setupUpdateIpcHandlers()

  // Show splash screen and check for updates
  createSplashWindow()

  setupAutoUpdater(async () => {
    // This runs after update check is complete (or skipped)

    // Create the main window
    createWindow()

    // Setup auto-launch
    const settings = store.get('settings')
    await setupAutoLaunch(settings.autoLaunch)

    // Initialize process tracker (but don't start automatically)
    processTracker = new ProcessTracker(
      store,
      (stats) => {
        mainWindow?.webContents.send('tracking-update', stats)
      },
      (event) => {
        // Game started
        mainWindow?.webContents.send('game-started', event.gameName, event.gameId)
      },
      (event) => {
        // Game stopped
        mainWindow?.webContents.send('game-stopped', event.gameName, event.duration || 0)
      }
    )
    // Don't start automatically - user will start via button
  })

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

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    // Don't quit on Windows if minimize to tray is enabled
    const settings = store.get('settings')
    if (!settings.minimizeToTray) {
      app.quit()
    }
  }
})

app.on('before-quit', () => {
  app.isQuitting = true
  processTracker?.stop()
  destroyTray()
})

// Handle IPC for window controls
ipcMain.on('minimize-to-tray', () => {
  mainWindow?.hide()
})

ipcMain.on('quit-app', () => {
  app.isQuitting = true
  app.quit()
})

// Monitoring control
ipcMain.handle('start-monitoring', () => {
  if (!isMonitoringEnabled && processTracker) {
    processTracker.start()
    isMonitoringEnabled = true
    console.log('Monitoring started')
  }
  return isMonitoringEnabled
})

ipcMain.handle('stop-monitoring', () => {
  if (isMonitoringEnabled && processTracker) {
    processTracker.stop()
    isMonitoringEnabled = false
    console.log('Monitoring stopped')
  }
  return isMonitoringEnabled
})

ipcMain.handle('get-monitoring-status', () => {
  return isMonitoringEnabled
})

// Export for use in other modules
export { store, mainWindow }
