import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { ClubSwitcher } from '../club-switcher';
import { useTenant } from '../../contexts/tenant-context';

vi.mock('../../contexts/tenant-context', () => ({
  useTenant: vi.fn(),
}));

vi.mock('../ui/dropdown-menu', () => ({
  DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <div data-testid="trigger">{children}</div>,
  DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div data-testid="content">{children}</div>,
  DropdownMenuItem: ({ children, onClick }: { children: React.ReactNode, onClick: () => void }) => <div onClick={onClick} data-testid="menu-item">{children}</div>,
  DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  DropdownMenuSeparator: () => <div>---</div>,
}));

describe('ClubSwitcher', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders loading state when clubs is empty', () => {
    (useTenant as ReturnType<typeof vi.fn>).mockReturnValue({
      activeClubId: null,
      clubs: [],
      setActiveClub: vi.fn(),
      userRole: null
    });

    render(<ClubSwitcher />);
    expect(screen.getByRole('button')).toHaveTextContent('Select Club');
  });

  it('renders current club name and sport type badge', () => {
    (useTenant as ReturnType<typeof vi.fn>).mockReturnValue({
      activeClubId: 'club-1',
      clubs: [
        { id: 'club-1', name: 'Tennis Club', sportType: 'Tennis' },
        { id: 'club-2', name: 'Swim Club', sportType: 'Swimming' },
      ],
      setActiveClub: vi.fn(),
      userRole: 'admin'
    });

    render(<ClubSwitcher />);
    expect(screen.getAllByText('Tennis Club')[0]).toBeInTheDocument();
  });

  it('calls setActiveClub when club is selected', () => {
    const mockSetActiveClub = vi.fn();
    (useTenant as ReturnType<typeof vi.fn>).mockReturnValue({
      activeClubId: 'club-1',
      clubs: [
        { id: 'club-1', name: 'Tennis Club', sportType: 'Tennis' },
        { id: 'club-2', name: 'Swim Club', sportType: 'Swimming' },
      ],
      setActiveClub: mockSetActiveClub,
      userRole: 'admin'
    });

    render(<ClubSwitcher />);
    
    const swimClub = screen.getByText('Swim Club');
    fireEvent.click(swimClub);
    
    expect(mockSetActiveClub).toHaveBeenCalledWith('club-2');
  });
});
