import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/svelte';
import TaggedChapterRow from './TaggedChapterRow.svelte';

afterEach(() => cleanup());

function fixture(overrides: Record<string, unknown> = {}) {
    return {
        chapter_id: 'ch1',
        manga_id: 'm1',
        manga_title: 'Berserk',
        chapter_number: 3,
        chapter_title: null as string | null,
        match_count: 12,
        sample_storage_keys: [
            'mangas/m1/chapters/ch1/pages/0001.png',
            'mangas/m1/chapters/ch1/pages/0002.png',
            'mangas/m1/chapters/ch1/pages/0003.png'
        ],
        ...overrides
    };
}

describe('TaggedChapterRow', () => {
    it('links the row to the reader at the chapter root (no ?page=)', () => {
        const { container } = render(TaggedChapterRow, {
            props: { item: fixture() }
        });
        const link = container.querySelector('a.title') as HTMLAnchorElement;
        expect(link.href).toContain('/manga/m1/chapter/ch1');
        expect(link.href).not.toContain('?page=');
    });

    it('shows pluralized match-count when > 1', () => {
        render(TaggedChapterRow, { props: { item: fixture({ match_count: 12 }) } });
        expect(screen.getByText('12 pages')).toBeTruthy();
    });

    it('shows singular match-count when exactly 1', () => {
        render(TaggedChapterRow, { props: { item: fixture({ match_count: 1 }) } });
        expect(screen.getByText('1 page')).toBeTruthy();
    });

    it('renders breadcrumb with chapter title when present', () => {
        render(TaggedChapterRow, {
            props: { item: fixture({ chapter_title: 'The Brand' }) }
        });
        expect(screen.getByText(/Berserk · The Brand/)).toBeTruthy();
    });

    it('renders thumbnail strip for samples beyond the primary cover', () => {
        const { container } = render(TaggedChapterRow, {
            props: { item: fixture() }
        });
        // 3 samples: index 0 is the primary cover (rendered separately
        // in the .cover slot). Indices 1-2 land in .samples.
        const samples = container.querySelectorAll('.sample');
        expect(samples.length).toBe(2);
    });

    it('falls back to a placeholder when no sample keys', () => {
        const { container } = render(TaggedChapterRow, {
            props: { item: fixture({ sample_storage_keys: [] }) }
        });
        expect(container.querySelector('.cover-placeholder')).toBeTruthy();
    });
});
