import { describe, it, expect, vi } from 'vitest';
import { render } from 'vitest-browser-svelte';
import StammbaumConnectors from './StammbaumConnectors.svelte';
import { NODE_H } from './layout/buildLayout';
import type { components } from '$lib/generated/api';

type RelationshipDTO = components['schemas']['RelationshipDTO'];

const P = '00000000-0000-0000-0000-0000000000c1';
const C = '00000000-0000-0000-0000-0000000000c2';
const H = '00000000-0000-0000-0000-0000000000c3';
const W = '00000000-0000-0000-0000-0000000000c4';

function parentEdge(parentId: string, childId: string): RelationshipDTO {
	return {
		id: `${parentId}>${childId}`,
		personId: parentId,
		relatedPersonId: childId,
		personDisplayName: '',
		relatedPersonDisplayName: '',
		relationType: 'PARENT_OF',
		fromDatePrecision: 'UNKNOWN',
		toDatePrecision: 'UNKNOWN'
	};
}

function endedSpouseEdge(a: string, b: string): RelationshipDTO {
	return {
		id: `${a}~${b}`,
		personId: a,
		relatedPersonId: b,
		personDisplayName: '',
		relatedPersonDisplayName: '',
		relationType: 'SPOUSE_OF',
		fromDatePrecision: 'UNKNOWN',
		toDate: '1950-01-01',
		toDatePrecision: 'YEAR'
	};
}

const positions = new Map([
	[P, { x: 0, y: 0 }],
	[C, { x: 400, y: NODE_H + 80 }],
	[H, { x: 0, y: 400 }],
	[W, { x: 300, y: 400 }]
]);

const dashesOf = (selector: string) =>
	Array.from(document.querySelectorAll(selector))
		.map((el) => el.getAttribute('stroke-dasharray'))
		.filter((d): d is string => d !== null);

describe('StammbaumConnectors — cross-link cadence (#724)', () => {
	it('renders a cross-level link with the distinct 2 6 dash, never the 4 4 ended-marriage dash', async () => {
		render(StammbaumConnectors, {
			edges: [parentEdge(P, C), endedSpouseEdge(H, W)],
			positions,
			crossLinks: [{ parentId: P, childId: C }]
		});

		await vi.waitFor(() => {
			const dashes = dashesOf('line');
			// The cross-link cadence is present …
			expect(dashes).toContain('2 6');
			// … the ended-marriage cadence is present …
			expect(dashes).toContain('4 4');
			// … and the two are genuinely different cadences (WCAG 1.4.1: not by
			// stroke alone, but they must not collapse into the same pattern).
			expect('2 6').not.toBe('4 4');
		});
	});

	it('draws a normal parent→child connector solid when it is NOT a cross-link', async () => {
		render(StammbaumConnectors, {
			edges: [parentEdge(P, C)],
			positions,
			crossLinks: []
		});

		await vi.waitFor(() => {
			// No dashed parent lines at all when nothing is a cross-link.
			expect(dashesOf('line')).not.toContain('2 6');
			expect(document.querySelectorAll('line').length).toBeGreaterThan(0);
		});
	});
});
