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

afterEach(cleanup);

const bucket = (month: string, count = 1) => ({ month, count });

describe('TimelineXAxis', () => {
	it('renders no ticks when filled is empty', async () => {
		render(TimelineXAxis, { props: { filled: [] } });

		const ticks = document.querySelectorAll('[data-testid="timeline-x-tick"]');
		expect(ticks.length).toBe(0);
	});

	it('renders tick marks when filled buckets are present', async () => {
		const filled = Array.from({ length: 12 }, (_, i) =>
			bucket(`1923-${String(i + 1).padStart(2, '0')}`)
		);
		render(TimelineXAxis, { props: { filled } });

		const ticks = document.querySelectorAll('[data-testid="timeline-x-tick"]');
		expect(ticks.length).toBeGreaterThan(0);
	});

	it('omits the year when all visible buckets share the same year', async () => {
		const filled = Array.from({ length: 12 }, (_, i) =>
			bucket(`1923-${String(i + 1).padStart(2, '0')}`)
		);
		render(TimelineXAxis, { props: { filled } });

		const ticks = Array.from(document.querySelectorAll('[data-testid="timeline-x-tick"]'));
		const allText = ticks.map((t) => t.textContent ?? '').join(' ');
		expect(allText).not.toContain('1923');
	});

	it('shows the year when buckets span multiple years', async () => {
		const filled = [bucket('1923-01'), bucket('1924-06'), bucket('1925-12')];
		render(TimelineXAxis, { props: { filled } });

		const ticks = Array.from(document.querySelectorAll('[data-testid="timeline-x-tick"]'));
		const allText = ticks.map((t) => t.textContent ?? '').join(' ');
		expect(allText).toMatch(/19\d{2}/);
	});

	it('handles single-year (length-4) bucket month strings without omitting the year', async () => {
		const filled = [bucket('1923'), bucket('1924')];
		render(TimelineXAxis, { props: { filled } });

		const ticks = document.querySelectorAll('[data-testid="timeline-x-tick"]');
		expect(ticks.length).toBeGreaterThan(0);
	});
});
