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

vi.mock('$app/navigation', () => ({
	beforeNavigate: () => {},
	afterNavigate: () => {},
	goto: vi.fn(),
	invalidate: vi.fn(),
	invalidateAll: vi.fn(),
	preloadCode: vi.fn(),
	preloadData: vi.fn(),
	pushState: vi.fn(),
	replaceState: vi.fn(),
	disableScrollHandling: vi.fn(),
	onNavigate: () => () => {}
}));

const { default: AdminEntryPage } = await import('./+page.svelte');

afterEach(cleanup);

const baseData = (overrides: Record<string, unknown> = {}) => ({
	userCount: 5,
	groupCount: 3,
	tagCount: 12,
	inviteCount: 1,
	canManageUsers: true,
	canManageTags: true,
	canManagePermissions: true,
	canRunMaintenance: true,
	...overrides
});

describe('admin/ entry page (mobile picker)', () => {
	it('renders the heading', async () => {
		render(AdminEntryPage, { props: { data: baseData() } });

		await expect.element(page.getByRole('heading', { name: /admin dashboard/i })).toBeVisible();
	});

	it('renders all five entity links when all permissions are granted', async () => {
		render(AdminEntryPage, { props: { data: baseData() } });

		const links = document.querySelectorAll('nav a[href^="/admin/"]');
		expect(links.length).toBe(5);
	});

	it('hides users + invites links when canManageUsers is false', async () => {
		render(AdminEntryPage, { props: { data: baseData({ canManageUsers: false }) } });

		expect(document.querySelector('a[href="/admin/users"]')).toBeNull();
		expect(document.querySelector('a[href="/admin/invites"]')).toBeNull();
	});

	it('hides the groups link when canManagePermissions is false', async () => {
		render(AdminEntryPage, { props: { data: baseData({ canManagePermissions: false }) } });

		expect(document.querySelector('a[href="/admin/groups"]')).toBeNull();
	});

	it('hides the tags link when canManageTags is false', async () => {
		render(AdminEntryPage, { props: { data: baseData({ canManageTags: false }) } });

		expect(document.querySelector('a[href="/admin/tags"]')).toBeNull();
	});

	it('hides the system link when canRunMaintenance is false', async () => {
		render(AdminEntryPage, { props: { data: baseData({ canRunMaintenance: false }) } });

		expect(document.querySelector('a[href="/admin/system"]')).toBeNull();
	});

	it('renders entity counts in each row', async () => {
		render(AdminEntryPage, {
			props: {
				data: baseData({ userCount: 42, groupCount: 7, tagCount: 99, inviteCount: 3 })
			}
		});

		await expect.element(page.getByText('42')).toBeVisible();
		await expect.element(page.getByText('7')).toBeVisible();
		await expect.element(page.getByText('99')).toBeVisible();
		await expect.element(page.getByText('3')).toBeVisible();
	});
});
