// src/components/FlyerCountDisplay.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { FlyerCountDisplay } from './FlyerCountDisplay';
import { useFlyers } from '../hooks/useFlyers';
import type { Flyer } from '../types';

// Mock the dependencies
vi.mock('../hooks/useFlyers');

// Create typed mocks
const mockedUseFlyers = vi.mocked(useFlyers);

describe('FlyerCountDisplay', () => {
  beforeEach(() => {
    // Reset mocks before each test to ensure they are isolated.
    vi.clearAllMocks();
  });

  it('should render a loading state when isLoading is true', () => {
    // Arrange: For this specific test, override the mock to return a loading state.
    mockedUseFlyers.mockReturnValue({
      flyers: [],
      isLoadingFlyers: true,
      flyersError: null,
      fetchNextFlyersPage: vi.fn(),
      hasNextFlyersPage: false,
      isRefetchingFlyers: false,
      refetchFlyers: vi.fn(),
    });

    // Act: Render the component.
    render(<FlyerCountDisplay />);

    // Assert: Check that the loading spinner is visible.
    expect(screen.getByTestId('loading-spinner')).toBeInTheDocument();
    expect(screen.getByText('Loading...')).toBeInTheDocument();
  });

  it('should render an error message when an error is present', () => {
    // Arrange: Override the mock to return an error state.
    const errorMessage = 'Failed to fetch data';
    mockedUseFlyers.mockReturnValue({
      flyers: [],
      isLoadingFlyers: false,
      flyersError: new Error(errorMessage),
      fetchNextFlyersPage: vi.fn(),
      hasNextFlyersPage: false,
      isRefetchingFlyers: false,
      refetchFlyers: vi.fn(),
    });

    // Act
    render(<FlyerCountDisplay />);

    // Assert: Check that the error message is displayed.
    expect(screen.getByRole('alert')).toHaveTextContent(errorMessage);
  });

  it('should render the flyer count when data is successfully loaded', () => {
    // Arrange: Override the mock to return a successful state with some data.
    const mockFlyers: Flyer[] = [
      { flyer_id: 1, file_name: 'flyer1.pdf', image_url: '', item_count: 10, created_at: '' },
      { flyer_id: 2, file_name: 'flyer2.pdf', image_url: '', item_count: 20, created_at: '' },
    ];
    mockedUseFlyers.mockReturnValue({
      flyers: mockFlyers,
      isLoadingFlyers: false,
      flyersError: null,
      fetchNextFlyersPage: vi.fn(),
      hasNextFlyersPage: false,
      isRefetchingFlyers: false,
      refetchFlyers: vi.fn(),
    });

    // Act
    render(<FlyerCountDisplay />);

    // Assert: Check that the correct count is displayed.
    const countDisplay = screen.getByTestId('flyer-count');
    expect(countDisplay).toBeInTheDocument();
    expect(countDisplay).toHaveTextContent('Number of flyers: 2');
  });
});