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

afterEach(cleanup);

const baseActor = { id: 'a1', name: 'Anna Schmidt', initials: 'AS', color: '#012851' };

const makeItem = (overrides: Record<string, unknown> = {}) => ({
	id: 'i1',
	kind: 'TEXT_SAVED' as string,
	actor: baseActor,
	documentId: 'd1',
	documentTitle: 'Brief 1923',
	count: 1,
	happenedAt: new Date().toISOString(),
	youMentioned: false,
	...overrides
});

describe('ChronikTimeline', () => {
	it('renders nothing when items is empty', async () => {
		render(ChronikTimeline, { props: { items: [] } });

		const buckets = document.querySelectorAll('[data-testid^="chronik-bucket-"]');
		expect(buckets.length).toBe(0);
	});

	it('renders the today bucket for today items', async () => {
		const today = new Date();
		render(ChronikTimeline, {
			props: { items: [makeItem({ id: 'i1', happenedAt: today.toISOString() })] }
		});

		const today_bucket = document.querySelector('[data-testid="chronik-bucket-today"]');
		expect(today_bucket).not.toBeNull();
	});

	it('renders the older bucket for old items', async () => {
		render(ChronikTimeline, {
			props: { items: [makeItem({ id: 'i1', happenedAt: '2020-01-01T10:00:00Z' })] }
		});

		const olderBucket = document.querySelector('[data-testid="chronik-bucket-older"]');
		expect(olderBucket).not.toBeNull();
	});

	it('renders multiple buckets when items span time ranges', async () => {
		const today = new Date();
		render(ChronikTimeline, {
			props: {
				items: [
					makeItem({ id: 'i1', kind: 'TEXT_SAVED', happenedAt: today.toISOString() }),
					makeItem({
						id: 'i2',
						kind: 'FILE_UPLOADED',
						documentId: 'd2',
						happenedAt: '2020-01-01T10:00:00Z'
					})
				]
			}
		});

		const buckets = document.querySelectorAll('[data-testid^="chronik-bucket-"]');
		expect(buckets.length).toBeGreaterThanOrEqual(2);
	});
});
