import React from 'react';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TopBar } from '@/components/layout/TopBar';
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 renderTopBar() {
  return render(
    <MemoryRouter initialEntries={['/dashboard']}>
      <TopBar />
    </MemoryRouter>
  );
}

describe('TopBar', () => {
  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 tenant switcher with current tenant name', () => {
    renderTopBar();
    expect(screen.getByText('Firma Alpha')).toBeInTheDocument();
  });

  it('renders search input with aria-label', () => {
    renderTopBar();
    expect(screen.getByLabelText('Suchen...')).toBeInTheDocument();
  });

  it('renders user menu button with aria-label', () => {
    renderTopBar();
    expect(screen.getByLabelText('Benutzermenü')).toBeInTheDocument();
  });

  it('all interactive elements have min-h-touch for 44px targets', () => {
    renderTopBar();
    const buttons = screen.getAllByRole('button');
    buttons.forEach((btn) => {
      expect(btn.className).toContain('min-h-touch');
    });
  });
});
