import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';

vi.mock('$app/state', () => ({
  page: { url: new URL('http://localhost/') }
}));

vi.mock('$app/navigation', () => ({
  goto: vi.fn()
}));

vi.mock('$lib/auth/store.svelte', () => ({
  user: { value: { id: '1', username: 'alice', is_admin: false } },
  logout: vi.fn().mockResolvedValue(undefined)
}));

import Shell from './Shell.svelte';
import { logout } from '$lib/auth/store.svelte';
import { goto } from '$app/navigation';

afterEach(() => {
  vi.clearAllMocks();
});

describe('Shell', () => {
  test('renders the username in the header', () => {
    render(Shell);
    expect(screen.getByText('alice')).toBeInTheDocument();
  });

  test('renders three nav items: Library, Search, Playlists', () => {
    render(Shell);
    expect(screen.getByRole('link', { name: 'Library' })).toHaveAttribute('href', '/');
    expect(screen.getByRole('link', { name: 'Search' })).toHaveAttribute('href', '/search');
    expect(screen.getByRole('link', { name: 'Playlists' })).toHaveAttribute('href', '/playlists');
  });

  test('user-menu "Log out" calls logout() and navigates to /login', async () => {
    render(Shell);
    await fireEvent.click(screen.getByRole('button', { name: /alice/i }));
    await fireEvent.click(screen.getByRole('button', { name: /log out/i }));
    expect(logout).toHaveBeenCalledTimes(1);
    expect(goto).toHaveBeenCalledWith('/login', { replaceState: true });
  });
});
