import { app, Menu, Tray, nativeImage } from 'electron';
import { join } from 'node:path';
import { isAutoStartEnabled, setAutoStart } from './autostart';

function iconPath(): string {
  return app.isPackaged
    ? join(process.resourcesPath, 'icon.png')
    : join(__dirname, '..', 'resources', 'icon.png');
}

/** Icône de barre système : ouvrir la fenêtre, basculer le lancement au login, quitter. */
export function createTray(opts: { show: () => void; quit: () => void }): Tray {
  const image = nativeImage.createFromPath(iconPath());
  const tray = new Tray(image.isEmpty() ? nativeImage.createEmpty() : image.resize({ width: 18, height: 18 }));
  tray.setToolTip('Arboretum');

  const buildMenu = (): void => {
    tray.setContextMenu(
      Menu.buildFromTemplate([
        { label: 'Open Arboretum', click: opts.show },
        { type: 'separator' },
        {
          label: 'Launch at login',
          type: 'checkbox',
          checked: isAutoStartEnabled(),
          click: (item) => {
            setAutoStart(item.checked);
            buildMenu();
          },
        },
        { type: 'separator' },
        { label: 'Quit', click: opts.quit },
      ]),
    );
  };

  buildMenu();
  tray.on('click', opts.show);
  return tray;
}
