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

import DashboardActivityFeed from './DashboardActivityFeed.svelte';
import type { components } from '$lib/generated/api';

type ActivityFeedItemDTO = components['schemas']['ActivityFeedItemDTO'];

afterEach(() => {
	cleanup();
});

const baseItem: ActivityFeedItemDTO = {
	kind: 'TEXT_SAVED',
	actor: { initials: 'MR', color: '#7a4f9a', name: 'Max Raddatz' },
	documentId: 'doc-1',
	documentTitle: 'Brief 1920',
	happenedAt: '2026-04-19T10:00:00Z',
	youMentioned: false,
	count: 1
};

describe('DashboardActivityFeed', () => {
	it('renders "für dich" badge when youMentioned is true', async () => {
		const item: ActivityFeedItemDTO = { ...baseItem, kind: 'MENTION_CREATED', youMentioned: true };
		render(DashboardActivityFeed, { feed: [item] });
		const badge = page.getByText('für dich');
		await expect.element(badge).toBeInTheDocument();
	});

	it('does not render "für dich" badge when youMentioned is false', async () => {
		render(DashboardActivityFeed, { feed: [baseItem] });
		const badge = page.getByText('für dich');
		await expect.element(badge).not.toBeInTheDocument();
	});

	it('renders empty state when feed is empty', async () => {
		render(DashboardActivityFeed, { feed: [] });
		const section = page.getByText('Kommentare & Aktivität');
		await expect.element(section).toBeInTheDocument();
	});

	it('renders count badge and en-dash time range for rollup rows (count > 1)', async () => {
		const rollup: ActivityFeedItemDTO = {
			...baseItem,
			count: 20,
			happenedAtUntil: '2026-04-19T10:32:00Z'
		};
		render(DashboardActivityFeed, { feed: [rollup] });
		const badge = page.getByTestId('feed-rollup-count');
		await expect.element(badge).toHaveTextContent('20');
		// "–" is U+2013 en-dash
		const stamp = page.getByText(/\u2013/);
		await expect.element(stamp).toBeInTheDocument();
	});

	it('does not render count badge for singleton rows (count === 1)', async () => {
		render(DashboardActivityFeed, { feed: [baseItem] });
		const badge = page.getByTestId('feed-rollup-count');
		await expect.element(badge).not.toBeInTheDocument();
	});

	it('links the "show all" footer to /aktivitaeten, not /documents', async () => {
		render(DashboardActivityFeed, { feed: [] });
		const link = page.getByRole('link', { name: /alle anzeigen/i });
		await expect.element(link).toHaveAttribute('href', '/aktivitaeten');
	});
});
