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

afterEach(cleanup);

describe('reset-password page', () => {
	it('renders the password and confirmation inputs by default', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'abc' }, form: undefined }
		});

		await expect
			.element(page.getByRole('heading', { name: /neues passwort festlegen/i }))
			.toBeVisible();
		await expect.element(page.getByLabelText('Neues Passwort')).toBeVisible();
		await expect.element(page.getByLabelText('Passwort bestätigen')).toBeVisible();
	});

	it('renders the token in a hidden input', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'tok-123' }, form: undefined }
		});

		const tokenInput = document.querySelector('input[name="token"]') as HTMLInputElement;
		expect(tokenInput.type).toBe('hidden');
		expect(tokenInput.value).toBe('tok-123');
	});

	it('falls back to an empty token when data.token is null', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: null }, form: undefined }
		});

		const tokenInput = document.querySelector('input[name="token"]') as HTMLInputElement;
		expect(tokenInput.value).toBe('');
	});

	it('shows the success banner and hides the form when form.success is true', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'abc' }, form: { success: true } }
		});

		await expect
			.element(
				page.getByText('Ihr Passwort wurde erfolgreich geändert. Sie können sich jetzt anmelden.')
			)
			.toBeVisible();
		await expect.element(page.getByLabelText('Neues Passwort')).not.toBeInTheDocument();
	});

	it('renders the localised mismatch message for the MISMATCH error code', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'abc' }, form: { error: 'MISMATCH' } }
		});

		await expect.element(page.getByText('Die Passwörter stimmen nicht überein.')).toBeVisible();
	});

	it('falls back to the generic error message for any other error code', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'abc' }, form: { error: 'TOKEN_EXPIRED' } }
		});

		await expect
			.element(page.getByText(/(fehler|expired|abgelaufen|ungültig|generic)/i))
			.toBeVisible();
	});

	it('always offers a back-to-login link', async () => {
		render(ResetPasswordPage, {
			props: { data: { token: 'abc' }, form: undefined }
		});

		await expect
			.element(page.getByRole('link', { name: /zurück zum login/i }))
			.toHaveAttribute('href', '/login');
	});
});
