import { app, BrowserWindow, Menu, shell, dialog, nativeImage } from 'electron';
import * as path from 'path';
import * as fs from 'fs';

const isDev = process.env.VISITY_DEV === '1' || !app.isPackaged;
const DEV_URL = process.env.VISITY_DEV_URL || 'https://localhost:3000';

// In a packaged build electron-builder copies apps/web/dist into the .app's
// Resources/web/ via extraResources. In an unpackaged dev fallback (rare) we
// look next to the monorepo source.
const PROD_INDEX = app.isPackaged
  ? path.join(process.resourcesPath, 'web', 'index.html')
  : path.join(__dirname, '..', '..', 'web', 'dist', 'index.html');

let mainWindow: BrowserWindow | null = null;

const ICON_PATH = path.join(__dirname, '..', 'assets', 'icon.png');

function createWindow(): void {
  mainWindow = new BrowserWindow({
    width: 1440,
    height: 900,
    minWidth: 1100,
    minHeight: 700,
    show: false,
    backgroundColor: '#f8fafc',
    title: 'HoSt Visity',
    // BrowserWindow icon controls the title-bar icon on Windows/Linux. On
    // macOS the dock icon is set separately via app.dock.setIcon below.
    ...(process.platform !== 'darwin' && fs.existsSync(ICON_PATH)
      ? { icon: ICON_PATH }
      : {}),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
    },
  });

  mainWindow.once('ready-to-show', () => {
    mainWindow?.show();
    if (isDev) mainWindow?.webContents.openDevTools({ mode: 'detach' });
  });

  // External links open in the user's browser, not inside our app.
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      shell.openExternal(url);
      return { action: 'deny' };
    }
    return { action: 'allow' };
  });

  if (isDev) {
    void mainWindow.loadURL(DEV_URL).catch((err) => {
      console.error('Failed to load dev URL:', err);
      mainWindow?.webContents.loadURL(
        'data:text/html,' +
          encodeURIComponent(
            `<html><body style="font-family:system-ui;padding:40px;color:#334155">
              <h2>Can't reach ${DEV_URL}</h2>
              <p>Start the web dev server with <code>npm run dev</code> in <code>apps/web</code> and reload (Cmd/Ctrl+R).</p>
            </body></html>`,
          ),
      );
    });
  } else {
    if (fs.existsSync(PROD_INDEX)) {
      void mainWindow.loadFile(PROD_INDEX);
    } else {
      dialog.showErrorBox(
        'Web bundle not found',
        `Expected built web app at:\n${PROD_INDEX}\n\nRun "npm run build" in apps/web first.`,
      );
    }
  }

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

function buildMenu(): void {
  const isMac = process.platform === 'darwin';
  const template: Electron.MenuItemConstructorOptions[] = [
    ...(isMac
      ? [
          {
            label: app.name,
            submenu: [
              { role: 'about' as const },
              { type: 'separator' as const },
              { role: 'services' as const },
              { type: 'separator' as const },
              { role: 'hide' as const },
              { role: 'hideOthers' as const },
              { role: 'unhide' as const },
              { type: 'separator' as const },
              { role: 'quit' as const },
            ],
          },
        ]
      : []),
    {
      label: 'File',
      submenu: [isMac ? { role: 'close' } : { role: 'quit' }],
    },
    {
      label: 'Edit',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' },
        { role: 'selectAll' },
      ],
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload' },
        { role: 'forceReload' },
        { role: 'toggleDevTools' },
        { type: 'separator' },
        { role: 'resetZoom' },
        { role: 'zoomIn' },
        { role: 'zoomOut' },
        { type: 'separator' },
        { role: 'togglefullscreen' },
      ],
    },
    {
      label: 'Window',
      submenu: [
        { role: 'minimize' },
        { role: 'zoom' },
        ...(isMac
          ? ([
              { type: 'separator' },
              { role: 'front' },
              { type: 'separator' },
              { role: 'window' },
            ] as Electron.MenuItemConstructorOptions[])
          : ([{ role: 'close' }] as Electron.MenuItemConstructorOptions[])),
      ],
    },
    {
      role: 'help',
      submenu: [
        {
          label: 'Open issue tracker',
          click: () => shell.openExternal('https://gitlab.com/claude-code2704320/vcarrd-events/-/issues'),
        },
      ],
    },
  ];

  Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}

// Vite's basicSsl plugin serves the web app over HTTPS with a self-signed cert
// in dev. Accept it for localhost only — never relax this for any other host.
app.on('certificate-error', (event, _webContents, url, _error, _certificate, callback) => {
  try {
    if (isDev && new URL(url).hostname === 'localhost') {
      event.preventDefault();
      callback(true);
      return;
    }
  } catch {
    /* fall through */
  }
  callback(false);
});

app.whenReady().then(() => {
  // Set a dock icon on macOS when running unpacked (no .icns yet).
  if (process.platform === 'darwin' && fs.existsSync(ICON_PATH)) {
    app.dock.setIcon(nativeImage.createFromPath(ICON_PATH));
  }

  buildMenu();
  createWindow();

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

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