import { describe, it, expect, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import UserGroupsSection from './UserGroupsSection.svelte';

afterEach(cleanup);

const groups = [
	{ id: 'g1', name: 'Familie' },
	{ id: 'g2', name: 'Admins' },
	{ id: 'g3', name: 'Lesetransport' }
];

describe('UserGroupsSection', () => {
	it('renders one checkbox per group', async () => {
		render(UserGroupsSection, { props: { groups } });

		const checkboxes = document.querySelectorAll('input[name="groupIds"]');
		expect(checkboxes.length).toBe(3);
	});

	it('renders each group label', async () => {
		render(UserGroupsSection, { props: { groups } });

		expect(document.body.textContent).toContain('Familie');
		expect(document.body.textContent).toContain('Admins');
		expect(document.body.textContent).toContain('Lesetransport');
	});

	it('preselects checkboxes for ids in selectedGroupIds', async () => {
		render(UserGroupsSection, { props: { groups, selectedGroupIds: ['g1', 'g3'] } });

		const checkboxes = Array.from(
			document.querySelectorAll('input[name="groupIds"]')
		) as HTMLInputElement[];
		const checkedValues = checkboxes.filter((c) => c.checked).map((c) => c.value);
		expect(checkedValues.sort()).toEqual(['g1', 'g3']);
	});

	it('renders nothing when groups is empty', async () => {
		render(UserGroupsSection, { props: { groups: [] } });

		const checkboxes = document.querySelectorAll('input[name="groupIds"]');
		expect(checkboxes.length).toBe(0);
	});

	it('handles a missing selectedGroupIds prop by defaulting to none selected', async () => {
		render(UserGroupsSection, { props: { groups } });

		const checkboxes = Array.from(
			document.querySelectorAll('input[name="groupIds"]')
		) as HTMLInputElement[];
		expect(checkboxes.every((c) => !c.checked)).toBe(true);
	});
});
