import { describe, it, expect, vi, afterEach } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import CommentThread from './CommentThread.svelte';
import type { Comment } from '$lib/shared/types';

afterEach(() => {
	cleanup();
	vi.unstubAllGlobals();
});

function makeComment(id: string, content = 'Hello'): Comment {
	return {
		id,
		authorId: 'user-1',
		authorName: 'Alice',
		content,
		createdAt: new Date().toISOString(),
		updatedAt: new Date().toISOString(),
		replies: []
	};
}

const baseProps = {
	documentId: 'doc-1',
	canComment: true,
	currentUserId: 'user-1',
	canAdmin: false
};

describe('CommentThread – empty state', () => {
	it('shows empty state hint when there are no comments', async () => {
		render(CommentThread, { ...baseProps, initialComments: [] });
		await expect
			.element(page.getByText('Noch keine Kommentare – starte die Diskussion!'))
			.toBeInTheDocument();
	});

	it('does not show empty state hint when comments exist', async () => {
		render(CommentThread, { ...baseProps, initialComments: [makeComment('c-1')] });
		await expect
			.element(page.getByText('Noch keine Kommentare – starte die Diskussion!'))
			.not.toBeInTheDocument();
	});
});

describe('CommentThread – onCountChange', () => {
	it('calls onCountChange with initial SSR count on mount', async () => {
		const onCountChange = vi.fn();
		render(CommentThread, {
			...baseProps,
			initialComments: [makeComment('c-1'), makeComment('c-2')],
			onCountChange
		});
		expect(onCountChange).toHaveBeenCalledWith(2);
	});

	it('calls onCountChange with 0 when no initial comments', async () => {
		const onCountChange = vi.fn();
		render(CommentThread, { ...baseProps, initialComments: [], onCountChange });
		expect(onCountChange).toHaveBeenCalledWith(0);
	});

	it('counts replies in the total', async () => {
		const onCountChange = vi.fn();
		const comment = { ...makeComment('c-1'), replies: [makeComment('r-1') as never] };
		render(CommentThread, { ...baseProps, initialComments: [comment], onCountChange });
		expect(onCountChange).toHaveBeenCalledWith(2);
	});
});
