// src/components/WhatsNewModal.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { WhatsNewModal } from './WhatsNewModal';

describe('WhatsNewModal', () => {
  const mockOnClose = vi.fn();
  const defaultProps = {
    isOpen: true,
    onClose: mockOnClose,
    version: '20240101-abcd',
    commitMessage: 'feat: Add exciting new feature',
  };

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('should not render when isOpen is false', () => {
    const { container } = render(<WhatsNewModal {...defaultProps} isOpen={false} />);
    // The component returns null, so the container should be empty.
    expect(container.firstChild).toBeNull();
  });

  it('should render correctly when isOpen is true', () => {
    render(<WhatsNewModal {...defaultProps} />);

    expect(screen.getByRole('heading', { name: /what's new/i })).toBeInTheDocument();
    expect(screen.getByText(`Version: ${defaultProps.version}`)).toBeInTheDocument();
    expect(screen.getByText(defaultProps.commitMessage)).toBeInTheDocument();
    expect(screen.getByRole('button', { name: /got it/i })).toBeInTheDocument();
  });

  it('should call onClose when the "Got it!" button is clicked', () => {
    render(<WhatsNewModal {...defaultProps} />);
    fireEvent.click(screen.getByRole('button', { name: /got it/i }));
    expect(mockOnClose).toHaveBeenCalledTimes(1);
  });

  it('should call onClose when the close icon button is clicked', () => {
    render(<WhatsNewModal {...defaultProps} />);
    // The close button is an SVG icon inside a button, best queried by its aria-label.
    const closeButton = screen.getByRole('button', { name: /close/i });
    fireEvent.click(closeButton);
    expect(mockOnClose).toHaveBeenCalledTimes(1);
  });

  it('should call onClose when clicking on the overlay', () => {
    render(<WhatsNewModal {...defaultProps} />);
    // The overlay is the root div with the background color.
    const overlay = screen.getByRole('dialog').parentElement;
    fireEvent.click(overlay!);
    expect(mockOnClose).toHaveBeenCalledTimes(1);
  });

  it('should not call onClose when clicking inside the modal content', () => {
    render(<WhatsNewModal {...defaultProps} />);
    fireEvent.click(screen.getByText(defaultProps.commitMessage));
    expect(mockOnClose).not.toHaveBeenCalled();
  });
});