import React from 'react';
import {render, screen, waitFor} from '@testing-library/react';
import ParticipationButton from '../ParticipationButton';
import {getParticipations} from '@/services/participationService';

const mockUseAuth = jest.fn();
jest.mock('@/services/participationService');
jest.mock('@/contexts/AuthContext', () => ({
  useAuth: () => mockUseAuth(),
}));
jest.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
}));
jest.mock('next/link', () => {
  return ({children, href, ...props}: {children: React.ReactNode; href: string; [key: string]: unknown}) => (
    <a href={href} {...props}>{children}</a>
  );
});

const mockedGetParticipations = getParticipations as jest.Mock;

describe('ParticipationButton', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    mockedGetParticipations.mockResolvedValue({count: 0, participants: []});
  });

  it('shouldInviteAnonymousVisitorsToLogInToManageTheirPresence', async () => {
    mockUseAuth.mockReturnValue({isAuthenticated: false, user: null});

    render(<ParticipationButton evenementId={10} eventDate="2099-10-03" />);

    await waitFor(() => expect(mockedGetParticipations).toHaveBeenCalled());
    expect(screen.getByText('login_to_participate').closest('a')).toHaveAttribute('href', '/connexion');
    expect(screen.queryByRole('button')).not.toBeInTheDocument();
  });

  it('shouldOfferToRegisterWhenLoggedIn', async () => {
    mockUseAuth.mockReturnValue({isAuthenticated: true, user: {id: '1', username: 'breizh56'}});

    render(<ParticipationButton evenementId={10} eventDate="2099-10-03" />);

    await waitFor(() => expect(mockedGetParticipations).toHaveBeenCalled());
    expect(screen.getByRole('button', {name: 'i_will_be_there'})).toBeInTheDocument();
  });
});
