import { test, expect } from '@playwright/test';

test.describe('DocumentTopBar — back navigation', () => {
	test('BackButton returns to /documents after navigating from the documents list', async ({
		page
	}) => {
		// Navigate to home page first (mirrors the real user flow)
		await page.goto('/');
		await page.waitForSelector('[data-hydrated]');

		// Click the Dokumente nav link (SPA navigation — pushes to history)
		await page.click('a[href="/documents"]');
		await page.waitForURL('/documents');
		await page.waitForSelector('[data-hydrated]');

		// Click first real document link (skip /documents/new and edit links)
		const docLink = page.locator('a[href^="/documents/"]:not([href="/documents/new"])').first();
		const count = await docLink.count();

		if (count === 0) {
			test.skip(true, 'No documents in test database');
		}

		const docHref = await docLink.getAttribute('href');
		await docLink.click();
		await page.waitForURL(new RegExp(docHref!.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
		await page.waitForSelector('[data-hydrated]');

		// Find and click the BackButton in the DocumentTopBar
		const backBtn = page.locator('[data-topbar]').getByRole('button', { name: /zurück/i });
		await expect(backBtn).toBeVisible();
		await backBtn.click();

		// Should be back at the documents list, not at /
		await page.waitForURL(/\/documents($|\?)/);
		expect(page.url()).toMatch(/\/documents($|\?)/);
	});
});
