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, asChild }: { children: React.ReactNode, asChild?: boolean }) => <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 any).mockReturnValue({
      activeClubId: null,
      clubs: [],
      setActiveClub: vi.fn(),
      userRole: null
    } as any);

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

  it('renders current club name and sport type badge', () => {
    (useTenant as any).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'
    } as any);

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

  it('calls setActiveClub when club is selected', () => {
    const mockSetActiveClub = vi.fn();
    (useTenant as any).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'
    } as any);

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