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

afterEach(() => cleanup());

describe('AppBar', () => {
    it('renders the title as the h1', () => {
        render(AppBar, { props: { title: 'Mangalord' } });
        expect(screen.getByRole('heading', { level: 1, name: 'Mangalord' })).toBeTruthy();
    });

    it('omits the back control when neither backHref nor onBack is provided', () => {
        render(AppBar, { props: { title: 'Home' } });
        expect(screen.queryByRole('link', { name: 'Back' })).toBeNull();
        expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
    });

    it('renders a back link when backHref is provided', () => {
        render(AppBar, { props: { title: 'Detail', backHref: '/library' } });
        const back = screen.getByRole('link', { name: 'Back' });
        expect((back as HTMLAnchorElement).getAttribute('href')).toBe('/library');
    });

    it('renders a back button calling onBack when onBack is provided (and no href)', () => {
        const onBack = vi.fn();
        render(AppBar, { props: { title: 'Detail', onBack } });
        screen.getByRole('button', { name: 'Back' }).click();
        expect(onBack).toHaveBeenCalledOnce();
    });

    it('renders the trailing snippet when provided', () => {
        const trailing = createRawSnippet(() => ({
            render: () => `<button type="button" aria-label="More">…</button>`
        }));
        render(AppBar, { props: { title: 'Detail', trailing } });
        expect(screen.getByRole('button', { name: 'More' })).toBeTruthy();
    });
});
