const { app, BrowserWindow, ipcMain, shell } = require('electron')
const path = require('path')

let win

function createWindow() {
  win = new BrowserWindow({
    width: 1200,
    height: 800,
    frame: false,
    backgroundColor: '#141414',
    icon: path.join(__dirname, './logo512.png'),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  })

  // For development, load from localhost; for production, load the built index.html
  if (process.env.ELECTRON_START_URL) {
    win.loadURL(process.env.ELECTRON_START_URL)
  } else {
    win.loadFile(path.join(__dirname, '../build/index.html'))
  }

  setupWindowEvents()
}

app.whenReady().then(createWindow)

// IPC handler to get OS
ipcMain.handle('os-info', () => {
  return {
    platform: process.platform
  }
})

// IPC handler to get window state
ipcMain.handle('window-state', () => {
  return {
    isMaximized: win ? win.isMaximized() : false
  }
})

// Emit events to renderer when window is maximized/unmaximized
function setupWindowEvents() {
  if (!win) return
  win.on('maximize', () => {
    win.webContents.send('window-state', {
      isMaximized: true
    })
  })
  win.on('unmaximize', () => {
    win.webContents.send('window-state', {
      isMaximized: false
    })
  })
}

// IPC handlers for window controls
ipcMain.on('window-control', (event, action) => {
  if (!win) return
  switch (action) {
    case 'minimize':
      win.minimize()
      break
    case 'maximize':
      if (win.isMaximized()) {
        win.unmaximize()
      } else {
        win.maximize()
      }
      break
    case 'close':
      win.close()
      break
    default:
      break
  }
})

// Add this after other ipcMain handlers
ipcMain.handle('open-external-url', (event, url) => {
  console.log('Opening external url...')

  shell.openExternal(url)
})

app.on('open-url', (event, url) => {
  event.preventDefault()
  console.log('App opened with URL:', url)
  if (url.startsWith('farmcontrol://app')) {
    // Extract the path/query after 'farmcontrol://app'
    const redirectPath = url.replace('farmcontrol://app', '') || '/'
    if (win && win.webContents) {
      win.webContents.send('navigate', redirectPath)
    }
  }
})

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

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