import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import { Tray, Menu, nativeImage, app } from 'electron';
import Logger from 'electron-log/main';

import { resolveAppIconPath } from '~main/modules/appIcon';
import { mainWindow } from '~main/index';

let tray: Tray | null = null;
let isMinimizedToTray = false;

const restoreWindow = () => {
	if (!mainWindow) return;
	mainWindow.show();
	if (mainWindow.isMinimized()) mainWindow.restore();
	mainWindow.focus();
	isMinimizedToTray = false;
};

/**
 * Linux StatusNotifierItem often fails with asar paths / tiny 16px icons
 * (blank/black slot). Copy the PNG to a real filesystem path at 32px.
 */
const loadTrayIcon = () => {
	const size = process.platform === 'linux' ? 32 : 16;
	const src = resolveAppIconPath();
	if (!src) {
		Logger.warn('App icon not found for tray');
		return nativeImage.createEmpty();
	}

	const tmpSrc = path.join(os.tmpdir(), 'octolauncher-icon-src.png');
	const tmpTray = path.join(os.tmpdir(), 'octolauncher-tray.png');

	try {
		fs.copyFileSync(src, tmpSrc);
	} catch (e) {
		Logger.warn('Failed to copy tray icon', e);
		return nativeImage.createFromPath(src).resize({
			width: size,
			height: size,
			quality: 'best'
		});
	}

	let img = nativeImage.createFromPath(tmpSrc);
	img = img.resize({ width: size, height: size, quality: 'best' });

	if (process.platform === 'linux' && !img.isEmpty()) {
		try {
			fs.writeFileSync(tmpTray, Uint8Array.from(img.toPNG()));
			const fromDisk = nativeImage.createFromPath(tmpTray);
			if (!fromDisk.isEmpty()) return fromDisk;
		} catch (e) {
			Logger.warn('Failed to materialize tray icon on disk', e);
		}
	}
	return img;
};

const ensureTray = () => {
	if (tray) return tray;
	const trayIcon = loadTrayIcon();
	if (trayIcon.isEmpty())
		Logger.warn('Tray icon is empty — panel may show a blank slot');
	tray = new Tray(trayIcon);
	tray.setToolTip('OctoLauncher');
	tray.setContextMenu(
		Menu.buildFromTemplate([
			{ label: 'Show launcher', click: restoreWindow },
			{ type: 'separator' },
			{ label: 'Quit', click: () => app.quit() }
		])
	);
	tray.on('click', restoreWindow);
	return tray;
};

export const minimizeToTray = () => {
	if (!mainWindow) return;
	ensureTray();
	mainWindow.hide();
	isMinimizedToTray = true;
	Logger.info('Minimized to tray');
};

export const restoreFromTray = () => {
	if (!isMinimizedToTray) return;
	restoreWindow();
};

export const isInTray = () => isMinimizedToTray;

export const destroyTray = () => {
	tray?.destroy();
	tray = null;
};
