import { Tray, Menu, nativeImage, BrowserWindow, app } from "electron";
import { join } from "path";
import { existsSync } from "fs";

let tray: Tray | null = null;

export function setupTray(mainWindow: BrowserWindow, appName: string): void {
  const iconPath = getTrayIcon();
  if (!iconPath) {
    console.warn("[tray] No icon found, skipping tray setup");
    return;
  }

  const icon = nativeImage.createFromPath(iconPath);
  tray = new Tray(icon.resize({ width: 16, height: 16 }));
  tray.setToolTip(appName);

  const contextMenu = Menu.buildFromTemplate([
    {
      label: "Show " + appName,
      click: () => {
        mainWindow.show();
        mainWindow.focus();
      },
    },
    { type: "separator" },
    {
      label: "Quit",
      click: () => {
        app.quit();
      },
    },
  ]);

  tray.setContextMenu(contextMenu);

  tray.on("click", () => {
    if (mainWindow.isVisible()) {
      mainWindow.focus();
    } else {
      mainWindow.show();
    }
  });

  tray.on("double-click", () => {
    mainWindow.show();
    mainWindow.focus();
  });
}

function getTrayIcon(): string | null {
  const candidates = [
    join(__dirname, "..", "assets", "tray-icon.png"),
    join(__dirname, "..", "assets", "icon.png"),
    join(__dirname, "..", "assets", "icon.ico"),
  ];
  for (const p of candidates) {
    if (existsSync(p)) return p;
  }
  return null;
}
