import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { createStore, Provider } from 'jotai';
import React from 'react';
import { Viewport } from '../../components/Viewport';
import { panAtom, zoomAtom } from '../../core/viewport-store';
import { GestureProvider } from '../../gestures/GestureProvider';

function setupStore() {
	const store = createStore();
	return store;
}

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

describe('Viewport', () => {
	it('renders with data-viewport attribute', () => {
		const store = setupStore();
		const { container } = renderWithStore(
			store,
			<Viewport>
				<div>child</div>
			</Viewport>,
		);

		const viewport = container.querySelector('[data-viewport="true"]');
		expect(viewport).toBeInTheDocument();
	});

	it('renders children inside transform container', () => {
		const store = setupStore();
		const { getByText } = renderWithStore(
			store,
			<Viewport>
				<span>Hello Canvas</span>
			</Viewport>,
		);

		expect(getByText('Hello Canvas')).toBeInTheDocument();
	});

	it('applies custom className', () => {
		const store = setupStore();
		const { container } = renderWithStore(
			store,
			<Viewport className="my-viewport">
				<div />
			</Viewport>,
		);

		const viewport = container.querySelector('.my-viewport');
		expect(viewport).toBeInTheDocument();
	});

	it('applies custom style', () => {
		const store = setupStore();
		const { container } = renderWithStore(
			store,
			<Viewport style={{ background: 'red' }}>
				<div />
			</Viewport>,
		);

		const viewport = container.querySelector('[data-viewport="true"]') as HTMLElement;
		expect(viewport.style.background).toBe('red');
	});

	it('has viewport id for CSS targeting', () => {
		const store = setupStore();
		const { container } = renderWithStore(
			store,
			<Viewport>
				<div />
			</Viewport>,
		);

		expect(container.querySelector('#viewport-canvas')).toBeInTheDocument();
	});

	it('applies touch-action none for gesture handling', () => {
		const store = setupStore();
		const { container } = renderWithStore(
			store,
			<Viewport>
				<div />
			</Viewport>,
		);

		const viewport = container.querySelector('[data-viewport="true"]') as HTMLElement;
		expect(viewport.style.touchAction).toBe('none');
	});

	it('applies transform based on pan and zoom atoms', () => {
		const store = setupStore();
		store.set(panAtom, { x: 100, y: 50 });
		store.set(zoomAtom, 2);

		const { container } = renderWithStore(
			store,
			<Viewport>
				<div />
			</Viewport>,
		);

		const viewport = container.querySelector('[data-viewport="true"]') as HTMLElement;
		const transformDiv = viewport.firstChild as HTMLElement;
		expect(transformDiv.style.transform).toBe('translate(100px, 50px) scale(2)');
	});
});
