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

afterEach(cleanup);

describe('UserMenu', () => {
	it('renders the avatar button when userInitials is set', async () => {
		render(UserMenu, { props: { userInitials: 'AS' } });

		await expect.element(page.getByRole('button', { name: 'AS' })).toBeVisible();
	});

	it('renders the icon-only button when userInitials is null', async () => {
		render(UserMenu, { props: { userInitials: null } });

		await expect.element(page.getByRole('button', { name: /profil/i })).toBeVisible();
	});

	it('starts with the menu closed (aria-expanded=false)', async () => {
		render(UserMenu, { props: { userInitials: 'AS' } });

		await expect
			.element(page.getByRole('button', { name: 'AS' }))
			.toHaveAttribute('aria-expanded', 'false');
	});

	it('opens the menu when the trigger is clicked', async () => {
		render(UserMenu, { props: { userInitials: 'AS' } });

		await page.getByRole('button', { name: 'AS' }).click();

		await expect
			.element(page.getByRole('button', { name: 'AS' }))
			.toHaveAttribute('aria-expanded', 'true');
	});

	it('renders the profile link and logout button when the menu is open', async () => {
		render(UserMenu, { props: { userInitials: 'AS' } });

		await page.getByRole('button', { name: 'AS' }).click();

		await expect
			.element(page.getByRole('link', { name: /profil/i }))
			.toHaveAttribute('href', '/profile');
		await expect.element(page.getByRole('button', { name: /abmelden/i })).toBeVisible();
	});

	it('declares POST and /logout on the logout form', async () => {
		render(UserMenu, { props: { userInitials: 'AS' } });

		await page.getByRole('button', { name: 'AS' }).click();

		const form = document.querySelector('form[action="/logout"]') as HTMLFormElement;
		expect(form).not.toBeNull();
		expect(form.method.toLowerCase()).toBe('post');
	});
});
