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

afterEach(() => cleanup());

function fixture(overrides: Record<string, unknown> = {}) {
    return {
        tag: 'funny',
        page_id: 'p1',
        chapter_id: 'ch1',
        manga_id: 'm1',
        page_number: 5,
        chapter_number: 3,
        chapter_title: null,
        manga_title: 'Berserk',
        storage_key: 'mangas/m1/chapters/ch1/pages/0005.png',
        tagged_at: '2026-01-01T00:00:00Z',
        ...overrides
    };
}

describe('TaggedPageRow', () => {
    it('links the breadcrumb to the reader at ?page=N', () => {
        const { container } = render(TaggedPageRow, { props: { item: fixture() } });
        const anchors = Array.from(
            container.querySelectorAll('a[href*="?page="]')
        ) as HTMLAnchorElement[];
        // Both the (aria-hidden) cover link and the visible breadcrumb
        // point to the reader at the same page.
        expect(anchors.length).toBeGreaterThanOrEqual(2);
        expect(anchors[0].href).toContain('/manga/m1/chapter/ch1?page=5');
    });

    it('shows the tag pill by default', () => {
        render(TaggedPageRow, { props: { item: fixture({ tag: 'fight' }) } });
        expect(screen.getByText('#fight')).toBeTruthy();
    });

    it('omits the tag pill when showTagPill=false', () => {
        render(TaggedPageRow, {
            props: { item: fixture(), showTagPill: false }
        });
        expect(screen.queryByText('#funny')).toBeNull();
    });

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

    it('falls back to "Chapter N" when title is null', () => {
        render(TaggedPageRow, { props: { item: fixture({ chapter_title: null }) } });
        expect(screen.getByText(/Chapter 3/)).toBeTruthy();
    });
});
