import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/svelte';
import ContinueReadingShelf from './ContinueReadingShelf.svelte';
import type { ReadProgressSummary } from '$lib/api/read_progress';

afterEach(() => cleanup());

type Entry = ReadProgressSummary & { new_chapters_count: number };

function entry(over: Partial<Entry> = {}): Entry {
    return {
        manga_id: 'm1',
        manga_title: 'Berserk',
        manga_cover_image_path: null,
        chapter_id: 'c1',
        chapter_number: 3,
        chapter_page_count: 20,
        page: 3,
        updated_at: '2026-01-01T00:00:00Z',
        new_chapters_count: 0,
        ...over
    };
}

describe('ContinueReadingShelf', () => {
    it('renders a card per entry linking to the continue position', () => {
        render(ContinueReadingShelf, {
            props: {
                entries: [
                    entry({ manga_id: 'm1', chapter_id: 'c1', page: 3 }),
                    entry({ manga_id: 'm2', chapter_id: 'c2', page: 1, manga_title: 'Vinland' })
                ]
            }
        });

        // Page > 1 deep-links to the exact page; page 1 omits the query.
        const first = screen.getByTestId('continue-card-m1');
        expect(first.getAttribute('href')).toBe('/manga/m1/chapter/c1?page=3');
        const second = screen.getByTestId('continue-card-m2');
        expect(second.getAttribute('href')).toBe('/manga/m2/chapter/c2');

        expect(screen.getByText('Berserk')).toBeTruthy();
        expect(screen.getByText('Vinland')).toBeTruthy();
    });

    it('shows the new-chapter badge only when there are new chapters', () => {
        render(ContinueReadingShelf, {
            props: {
                entries: [
                    entry({ manga_id: 'm1', new_chapters_count: 2 }),
                    entry({ manga_id: 'm2', new_chapters_count: 0 })
                ]
            }
        });

        const badge = screen.getByTestId('continue-new-badge-m1');
        expect(badge.textContent).toContain('2');
        expect(screen.queryByTestId('continue-new-badge-m2')).toBeNull();
    });

    it('links to the manga when the progress has no chapter', () => {
        render(ContinueReadingShelf, {
            props: {
                entries: [entry({ manga_id: 'm3', chapter_id: null, chapter_number: null })]
            }
        });
        expect(screen.getByTestId('continue-card-m3').getAttribute('href')).toBe('/manga/m3');
    });
});
