import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { AppShell } from '@/components/layout/AppShell';
import { useAuthStore } from '@/store/authStore';

vi.mock('@/api/hooks', () => ({
  useLogout: () => ({ mutateAsync: vi.fn(), isPending: false }),
  useSwitchTenant: () => ({ mutateAsync: vi.fn(), isPending: false }),
  useGlobalSearch: () => ({ data: [], isLoading: false }),
}));

function renderWithRouter(initialPath = '/dashboard') {
  return render(
    <MemoryRouter initialEntries={[initialPath]}>
      <Routes>
        <Route path="*" element={<AppShell />} />
      </Routes>
    </MemoryRouter>
  );
}

describe('AppShell', () => {
  beforeEach(() => {
    useAuthStore.setState({
      isAuthenticated: true,
      user: {
        id: '1',
        email: 'max@test.de',
        first_name: 'Max',
        last_name: 'Mustermann',
        role: 'admin',
        avatar_url: null,
        tenants: [
          { id: 't1', name: 'Firma Alpha', slug: 'alpha' },
          { id: 't2', name: 'Firma Beta', slug: 'beta' },
        ],
      },
      currentTenant: { id: 't1', name: 'Firma Alpha', slug: 'alpha' },
    });
  });
  it('renders sidebar, topbar, and content area', () => {
    renderWithRouter();
    expect(screen.getByTestId('app-shell')).toBeInTheDocument();
    expect(screen.getByTestId('sidebar')).toBeInTheDocument();
    expect(screen.getByTestId('topbar')).toBeInTheDocument();
    expect(screen.getByTestId('content-area')).toBeInTheDocument();
  });

  it('sidebar contains navigation items', () => {
    renderWithRouter();
    const sidebar = screen.getByTestId('sidebar');
    expect(within(sidebar).getByText('Dashboard')).toBeInTheDocument();
    expect(within(sidebar).getByText('Kontakte')).toBeInTheDocument();
  });

  it('topbar contains tenant switcher, search, and user menu', () => {
    renderWithRouter();
    const topbar = screen.getByTestId('topbar');
    expect(within(topbar).getByLabelText('Mandant wechseln')).toBeInTheDocument();
    expect(within(topbar).getByLabelText('Suchen...')).toBeInTheDocument();
    expect(within(topbar).getByLabelText('Benutzermenü')).toBeInTheDocument();
  });

  it('content area has main role for screen readers', () => {
    renderWithRouter();
    expect(screen.getByRole('main')).toBeInTheDocument();
  });
});
