/**
 * AtRiskCard tests — the lightweight Admin Tools card that surfaces the
 * at-risk count and opens the full panel in a modal when clicked.
 *
 * AtRiskCard owns its own count fetch (/api/admin/at-risk). Loading / error
 * states must not block the click — admins should still be able to open the
 * modal even when the badge is unknown.
 */

import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { AtRiskCard } from '../AtRiskCard';

global.fetch = jest.fn();
const mockFetch = global.fetch as jest.Mock;

function resolveWith(body: unknown, ok = true) {
  mockFetch.mockResolvedValue({ ok, json: () => Promise.resolve(body) });
}

describe('AtRiskCard', () => {
  beforeEach(() => {
    jest.clearAllMocks();
  });

  it('renders title + description even while the count is loading', () => {
    mockFetch.mockImplementation(() => new Promise(() => {}));
    render(<AtRiskCard onClick={jest.fn()} />);
    expect(screen.getByRole('button', { name: /at-risk dealers/i })).toBeInTheDocument();
  });

  it('shows the total count badge once the fetch resolves with non-zero counts', async () => {
    resolveWith({
      success: true,
      counts: { missingZo: 5, missingSubdomain: 2, total: 6 },
      dealers: [],
    });
    render(<AtRiskCard onClick={jest.fn()} />);
    await waitFor(() => expect(screen.getByTestId('at-risk-badge')).toHaveTextContent('6'));
  });

  it('omits the badge when the total is zero', async () => {
    resolveWith({
      success: true,
      counts: { missingZo: 0, missingSubdomain: 0, total: 0 },
      dealers: [],
    });
    render(<AtRiskCard onClick={jest.fn()} />);
    await screen.findByRole('button', { name: /at-risk dealers/i });
    await waitFor(() => expect(screen.queryByTestId('at-risk-badge')).not.toBeInTheDocument());
  });

  it('omits the badge on fetch error but stays clickable', async () => {
    resolveWith({ success: false, error: 'boom' }, false);
    const onClick = jest.fn();
    render(<AtRiskCard onClick={onClick} />);
    await screen.findByRole('button', { name: /at-risk dealers/i });
    await waitFor(() => expect(screen.queryByTestId('at-risk-badge')).not.toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: /at-risk dealers/i }));
    expect(onClick).toHaveBeenCalledTimes(1);
  });

  it('fires onClick when the card is clicked', async () => {
    resolveWith({
      success: true,
      counts: { missingZo: 1, missingSubdomain: 0, total: 1 },
      dealers: [],
    });
    const onClick = jest.fn();
    render(<AtRiskCard onClick={onClick} />);
    await waitFor(() => expect(screen.getByTestId('at-risk-badge')).toBeInTheDocument());
    fireEvent.click(screen.getByRole('button', { name: /at-risk dealers/i }));
    expect(onClick).toHaveBeenCalledTimes(1);
  });
});
