import { BrowserWindow, app } from 'electron';
import { join } from 'path';
import log from 'electron-log';

let actionsWindow: BrowserWindow | null = null;

export function showActionsWindow(): void {
  if (actionsWindow) {
    actionsWindow.focus();

    // Ensure dock icon is visible
    if (process.platform === 'darwin') {
      app.dock.show();
    }

    return;
  }

  // Show dock icon on macOS when actions window opens
  if (process.platform === 'darwin') {
    app.dock.show();
    log.info('Dock icon shown for actions');
  }

  actionsWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    resizable: true,
    minimizable: true,
    maximizable: true,
    title: 'Actions',
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/actions-preload.js')
    }
  });

  // Load the actions HTML
  // Check if Vite dev server is available (development mode with npm run dev)
  const isViteDevMode = !app.isPackaged && process.env.VITE_DEV_SERVER_URL;

  if (isViteDevMode) {
    // Development mode with npm run dev - load from Vite dev server
    const devServerURL = 'http://localhost:5173/actions/index.html';
    log.info(`Loading actions from Vite dev server: ${devServerURL}`);
    actionsWindow.loadURL(devServerURL);
  } else {
    // Production mode OR npm start - load from built files
    const rendererPath = join(__dirname, '../renderer/actions/index.html');
    log.info(`Loading actions from built files: ${rendererPath}`);
    actionsWindow.loadFile(rendererPath);
  }

  actionsWindow.on('closed', () => {
    actionsWindow = null;
    log.info('Actions window closed');

    // Hide dock icon on macOS if no other windows are open
    if (process.platform === 'darwin') {
      // Import window getters to check if any windows are still open
      const { getSetupWizardWindow } = require('./setup-wizard-window');

      const setupWizardWindow = getSetupWizardWindow();

      // Only hide dock icon if all windows are closed
      if (!setupWizardWindow) {
        app.dock.hide();
        log.info('Dock icon hidden - all windows closed');
      }
    }
  });

  log.info('Actions window opened');
}

export function getActionsWindow(): BrowserWindow | null {
  return actionsWindow;
}
