import { test, expect, type Page } from './fixtures';

// The bookmarks page streams its list (the single fetch is also the auth
// gate), so a row skeleton shows while it loads, then resolves to the list.

async function mockCommon(page: Page) {
    await page.route('**/api/v1/auth/config', (r) =>
        r.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ self_register_enabled: true, private_mode: false })
        })
    );
    await page.route('**/api/v1/auth/me', (r) =>
        r.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({ user: { id: 'u1', username: 'reader', created_at: '2026-01-01T00:00:00Z', is_admin: false } })
        })
    );
    await page.route('**/api/v1/auth/me/preferences', (r) =>
        r.fulfill({ status: 200, contentType: 'application/json', body: '{}' })
    );
    await page.route('**/api/v1/files/**', (r) => r.fulfill({ status: 200, body: '' }));
}

test('shows a row skeleton while bookmarks stream, then the list', async ({ page }) => {
    await mockCommon(page);

    let release: () => void = () => {};
    const gate = new Promise<void>((resolve) => {
        release = resolve;
    });
    await page.route('**/api/v1/me/bookmarks*', async (route) => {
        await gate;
        await route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({
                items: [
                    {
                        id: 'bk1', user_id: 'u1', manga_id: 'm1', chapter_id: null, page: null,
                        created_at: '2026-01-01T00:00:00Z', manga_title: 'Berserk', manga_cover_image_path: null
                    }
                ],
                page: { limit: 50, offset: 0, total: 1 }
            })
        });
    });

    await page.goto('/bookmarks');
    await expect(page.getByTestId('list-row-skeleton')).toBeVisible();

    release();
    await expect(page.getByText('Berserk')).toBeVisible();
    await expect(page.getByTestId('list-row-skeleton')).toHaveCount(0);
});
