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

afterEach(() => cleanup());

function fixture(overrides: Record<string, unknown> = {}) {
    return {
        manga_id: 'm1',
        manga_title: 'Berserk',
        manga_cover_image_path: 'mangas/m1/cover.png' as string | null,
        match_count: 28,
        sample_storage_keys: [
            'mangas/m1/chapters/ch1/pages/0005.png',
            'mangas/m1/chapters/ch2/pages/0010.png',
            'mangas/m1/chapters/ch3/pages/0015.png'
        ],
        ...overrides
    };
}

describe('TaggedMangaRow', () => {
    it('links to the manga detail page', () => {
        const { container } = render(TaggedMangaRow, {
            props: { item: fixture() }
        });
        const link = container.querySelector('a.title') as HTMLAnchorElement;
        expect(link.href).toMatch(/\/manga\/m1$/);
    });

    it('prefers manga_cover_image_path as the primary cover', () => {
        const { container } = render(TaggedMangaRow, {
            props: { item: fixture() }
        });
        const cover = container.querySelector('img.cover') as HTMLImageElement;
        expect(cover.src).toContain('mangas/m1/cover.png');
        // All 3 samples land in the strip because the manga cover
        // already filled the primary slot.
        expect(container.querySelectorAll('.sample').length).toBe(3);
    });

    it('falls back to the first sample when no manga cover', () => {
        const { container } = render(TaggedMangaRow, {
            props: { item: fixture({ manga_cover_image_path: null }) }
        });
        const cover = container.querySelector('img.cover') as HTMLImageElement;
        expect(cover.src).toContain('chapters/ch1/pages/0005.png');
        // Strip shows the remaining 2 samples.
        expect(container.querySelectorAll('.sample').length).toBe(2);
    });

    it('shows singular / plural match-count', () => {
        const { rerender } = render(TaggedMangaRow, {
            props: { item: fixture({ match_count: 1 }) }
        });
        expect(screen.getByText('1 page')).toBeTruthy();
        rerender({ item: fixture({ match_count: 28 }) });
        expect(screen.getByText('28 pages')).toBeTruthy();
    });

    it('renders placeholder when neither cover nor samples exist', () => {
        const { container } = render(TaggedMangaRow, {
            props: {
                item: fixture({
                    manga_cover_image_path: null,
                    sample_storage_keys: []
                })
            }
        });
        expect(container.querySelector('.cover-placeholder')).toBeTruthy();
    });
});
