import { describe, it, expect } from 'vitest';
import { computeGraphBounds, getMinimapTransform, minimapToWorld } from '../components/minimap-utils';
import type { NodeLike } from '../components/minimap-utils';

describe('minimap-utils', () => {
	const makeNode = (x: number, y: number, w = 200, h = 100): NodeLike => ({
		position: { x, y },
		width: w,
		height: h,
	});

	describe('computeGraphBounds', () => {
		it('returns null for empty array', () => {
			expect(computeGraphBounds([])).toBeNull();
		});

		it('returns correct bounds for single node', () => {
			const bounds = computeGraphBounds([makeNode(50, 100, 200, 100)]);
			expect(bounds).toEqual({ minX: 50, minY: 100, maxX: 250, maxY: 200 });
		});

		it('returns correct bounds for multiple nodes', () => {
			const bounds = computeGraphBounds([
				makeNode(0, 0, 100, 100),
				makeNode(500, 300, 200, 150),
			]);
			expect(bounds!.minX).toBe(0);
			expect(bounds!.minY).toBe(0);
			expect(bounds!.maxX).toBe(700);
			expect(bounds!.maxY).toBe(450);
		});

		it('uses default dimensions when width/height missing', () => {
			const bounds = computeGraphBounds([{ position: { x: 0, y: 0 } }]);
			expect(bounds!.maxX).toBe(200); // default width
			expect(bounds!.maxY).toBe(100); // default height
		});
	});

	describe('getMinimapTransform', () => {
		it('returns null for zero-size bounds', () => {
			const t = getMinimapTransform({ minX: 0, minY: 0, maxX: 0, maxY: 0 }, 200, 150);
			expect(t).toBeNull();
		});

		it('returns valid transform with scale', () => {
			const t = getMinimapTransform({ minX: 0, minY: 0, maxX: 800, maxY: 600 }, 200, 150);
			expect(t).not.toBeNull();
			expect(t!.scale).toBeGreaterThan(0);
		});

		it('scale fits within minimap dimensions', () => {
			const t = getMinimapTransform({ minX: 0, minY: 0, maxX: 800, maxY: 600 }, 200, 150);
			// Scaled graph should fit within 200x150 minus padding
			const scaledW = 800 * t!.scale;
			const scaledH = 600 * t!.scale;
			expect(scaledW).toBeLessThanOrEqual(200);
			expect(scaledH).toBeLessThanOrEqual(150);
		});
	});

	describe('minimapToWorld', () => {
		it('round-trips through transform', () => {
			const bounds = { minX: 0, minY: 0, maxX: 800, maxY: 600 };
			const t = getMinimapTransform(bounds, 200, 150)!;

			// Center of graph in minimap coords
			const centerMinimapX = t.offsetX + 400 * t.scale;
			const centerMinimapY = t.offsetY + 300 * t.scale;

			const world = minimapToWorld(centerMinimapX, centerMinimapY, t);
			expect(world.x).toBeCloseTo(400, 1);
			expect(world.y).toBeCloseTo(300, 1);
		});
	});
});
