import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/react';
import { createStore, Provider } from 'jotai';
import React from 'react';
import { SelectionOverlay } from '../../components/SelectionOverlay';
import { selectionPathAtom } from '../../core/selection-path-store';
import { panAtom, zoomAtom } from '../../core/viewport-store';

function renderWithStore(store: ReturnType<typeof createStore>, ui: React.ReactElement) {
	return render(<Provider store={store}>{ui}</Provider>);
}

describe('SelectionOverlay', () => {
	it('renders nothing when no selection path', () => {
		const store = createStore();
		const { container } = renderWithStore(store, <SelectionOverlay />);
		expect(container.querySelector('svg')).toBeNull();
	});

	it('renders rect when selection type is rect', () => {
		const store = createStore();
		store.set(selectionPathAtom, {
			type: 'rect',
			points: [
				{ x: 10, y: 10 },
				{ x: 100, y: 100 },
			],
		});
		store.set(panAtom, { x: 0, y: 0 });
		store.set(zoomAtom, 1);

		const { container } = renderWithStore(store, <SelectionOverlay />);
		const svg = container.querySelector('svg');
		expect(svg).not.toBeNull();
		const rect = svg!.querySelector('rect');
		expect(rect).not.toBeNull();
	});

	it('renders polygon when selection type is lasso', () => {
		const store = createStore();
		store.set(selectionPathAtom, {
			type: 'lasso',
			points: [
				{ x: 0, y: 0 },
				{ x: 100, y: 0 },
				{ x: 50, y: 100 },
			],
		});

		const { container } = renderWithStore(store, <SelectionOverlay />);
		const polygon = container.querySelector('polygon');
		expect(polygon).not.toBeNull();
		expect(polygon!.getAttribute('points')).toBe('0,0 100,0 50,100');
	});

	it('applies custom colors', () => {
		const store = createStore();
		store.set(selectionPathAtom, {
			type: 'rect',
			points: [
				{ x: 0, y: 0 },
				{ x: 50, y: 50 },
			],
		});

		const { container } = renderWithStore(
			store,
			<SelectionOverlay fillColor="red" strokeColor="blue" />,
		);

		const rect = container.querySelector('rect');
		expect(rect!.getAttribute('fill')).toBe('red');
		expect(rect!.getAttribute('stroke')).toBe('blue');
	});

	it('scales stroke width by zoom', () => {
		const store = createStore();
		store.set(selectionPathAtom, {
			type: 'rect',
			points: [
				{ x: 0, y: 0 },
				{ x: 50, y: 50 },
			],
		});
		store.set(zoomAtom, 2);

		const { container } = renderWithStore(
			store,
			<SelectionOverlay strokeWidth={4} />,
		);

		const rect = container.querySelector('rect');
		// strokeWidth should be 4 / 2 = 2
		expect(rect!.getAttribute('stroke-width')).toBe('2');
	});
});
