import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import * as m from '$lib/paraglide/messages.js';

import DistributionBar from './DistributionBar.svelte';

afterEach(() => {
	cleanup();
});

describe('DistributionBar', () => {
	it('renders the Paraglide aria-label and visible segments', async () => {
		render(DistributionBar, {
			outCount: 3,
			inCount: 7,
			senderName: 'Hans Müller',
			receiverName: 'Anna Schmidt'
		});

		const container = document.querySelector('[role="img"]') as HTMLElement;
		expect(container).toBeTruthy();

		// The aria-label must come from Paraglide, not a hardcoded German string,
		// so the EN / ES users aren't served "Briefverteilung in diesem Zeitraum".
		const expectedAria = m.dist_bar_aria({
			outCount: 3,
			senderName: 'Hans Müller',
			inCount: 7,
			receiverName: 'Anna Schmidt'
		});
		expect(container.getAttribute('aria-label')).toBe(expectedAria);

		// The visible "{count} from/von {name}" spans must also come from Paraglide.
		const outText = m.dist_bar_segment({ count: 3, name: 'Hans' });
		const inText = m.dist_bar_segment({ count: 7, name: 'Anna' });
		expect(container.textContent).toContain(outText);
		expect(container.textContent).toContain(inText);

		// 3/10 → 30% / 70% split on the two segments
		const segments = container.querySelectorAll('[data-testid="dist-bar-segment"]');
		expect(segments).toHaveLength(2);
		expect((segments[0] as HTMLElement).style.width).toBe('30%');
		expect((segments[1] as HTMLElement).style.width).toBe('70%');
	});

	it('falls back to the full name when it has no space to split', async () => {
		render(DistributionBar, {
			outCount: 1,
			inCount: 0,
			senderName: 'SingleWord',
			receiverName: 'Another'
		});

		const container = document.querySelector('[role="img"]') as HTMLElement;
		const expected = m.dist_bar_segment({ count: 1, name: 'SingleWord' });
		expect(container.textContent).toContain(expected);
	});

	it('renders a zero-percent left segment when outCount is zero', async () => {
		render(DistributionBar, {
			outCount: 0,
			inCount: 4,
			senderName: 'Hans',
			receiverName: 'Anna'
		});

		const segments = document.querySelectorAll('[data-testid="dist-bar-segment"]');
		expect((segments[0] as HTMLElement).style.width).toBe('0%');
		expect((segments[1] as HTMLElement).style.width).toBe('100%');
	});
});
