import { vi, describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import {
	createConfirmService,
	CONFIRM_KEY,
	type ConfirmOptions,
	type ConfirmService
} from '$lib/shared/services/confirm.svelte.js';
import EditPage from './+page.svelte';

afterEach(cleanup);

function makeDocument(overrides: Record<string, unknown> = {}) {
	return {
		id: 'doc-1',
		title: 'Test Document',
		originalFilename: 'test.pdf',
		status: 'UPLOADED' as const,
		createdAt: '2024-01-01T00:00:00Z',
		updatedAt: '2024-01-01T00:00:00Z',
		metadataComplete: false,
		scriptType: 'UNKNOWN' as const,
		// No filePath — avoids triggering the file loader fetch in tests
		...overrides
	};
}

describe('Edit page — delete button', () => {
	it('renders the delete button', async () => {
		const service = createConfirmService();
		render(EditPage, {
			props: { data: { document: makeDocument() }, form: null },
			context: new Map([[CONFIRM_KEY, service]])
		});
		await expect.element(page.getByRole('button', { name: /löschen/i })).toBeInTheDocument();
	});

	it('opens a confirm dialog when the delete button is clicked', async () => {
		// vi.spyOn on a Svelte 5 compiled service object does not reliably track calls in
		// vitest-browser mode (signal scoping), so we use a plain mock object instead.
		let capturedOptions: ConfirmOptions | null = null;
		let settleRef: ((value: boolean) => void) | null = null;
		const mockService: ConfirmService = {
			confirm(opts) {
				capturedOptions = opts;
				return new Promise<boolean>((resolve) => {
					settleRef = resolve;
				});
			},
			get options(): ConfirmOptions | null {
				return null;
			},
			settle(value) {
				settleRef?.(value);
			}
		};

		render(EditPage, {
			props: { data: { document: makeDocument() }, form: null },
			context: new Map([[CONFIRM_KEY, mockService]])
		});

		// Playwright CDP click has latency that can exceed vi.waitFor's 1000ms deadline.
		// Dispatching the MouseEvent directly from browser-JS context is synchronous and
		// reliably triggers Svelte 5 onclick — same pattern as GeschichteEditor.svelte.spec.ts.
		const btn = (await page
			.getByRole('button', { name: /löschen/i })
			.element()) as HTMLButtonElement;
		btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
		expect(capturedOptions).not.toBeNull();
		expect(capturedOptions).toMatchObject({ destructive: true });
		settleRef?.(false);
	});

	it('submits the delete form when the user confirms', async () => {
		const service = createConfirmService();
		render(EditPage, {
			props: { data: { document: makeDocument() }, form: null },
			context: new Map([[CONFIRM_KEY, service]])
		});

		const deleteForm = document.getElementById('delete-form') as HTMLFormElement;
		const submitSpy = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});

		await page.getByRole('button', { name: /löschen/i }).click();
		// confirm() has been called synchronously — settle and flush the microtask queue
		service.settle(true);
		await Promise.resolve();

		expect(submitSpy).toHaveBeenCalledOnce();
	});

	it('does NOT submit the delete form when the user cancels', async () => {
		const service = createConfirmService();
		render(EditPage, {
			props: { data: { document: makeDocument() }, form: null },
			context: new Map([[CONFIRM_KEY, service]])
		});

		const deleteForm = document.getElementById('delete-form') as HTMLFormElement;
		const submitSpy = vi.spyOn(deleteForm, 'requestSubmit').mockImplementation(() => {});

		await page.getByRole('button', { name: /löschen/i }).click();
		service.settle(false);
		await Promise.resolve();

		expect(submitSpy).not.toHaveBeenCalled();
	});
});
