import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '../../theme';
import TicketListCard from './TicketListCard';
import type { TicketSummary } from '@/services/tickets/types';

const base: TicketSummary = {
  id: 12,
  referenceCode: 'TKT-9F3K2A7Q',
  subject: 'هماهنگی ویزیت',
  status: 'open',
  category: 'coordination',
  bookingId: 5001,
  refundId: null,
  createdAt: '2026-07-01T10:00:00Z',
  lastMessageAt: '2026-07-01T12:00:00Z',
  unreadCount: 2,
};

function renderCard(overrides: Partial<TicketSummary>, extra: Partial<React.ComponentProps<typeof TicketListCard>> = {}) {
  const onOpen = jest.fn();
  render(
    <ThemeProvider>
      <TicketListCard
        ticket={{ ...base, ...overrides }}
        categoryLabel="هماهنگی"
        statusLabel="باز"
        timeLabel="۱۲:۰۰"
        linkedBookingLabel={overrides.bookingId === null ? null : 'رزرو #۵۰۰۱'}
        linkedRefundLabel={null}
        onOpen={onOpen}
        {...extra}
      />
    </ThemeProvider>,
  );
  return onOpen;
}

describe('<TicketListCard/> component', () => {
  it('shows the reference code prominently', () => {
    renderCard({});
    expect(screen.getByText('TKT-9F3K2A7Q')).toBeInTheDocument();
  });

  it('shows the unread indicator with the count when there is unread activity', () => {
    renderCard({ unreadCount: 2 });
    expect(screen.getByTestId('ticket-unread')).toHaveTextContent('2');
  });

  it('hides the unread indicator when nothing is unread', () => {
    renderCard({ unreadCount: 0 });
    expect(screen.queryByTestId('ticket-unread')).not.toBeInTheDocument();
  });

  it('renders the linked-booking hint only when the ticket is booking-linked', () => {
    renderCard({});
    expect(screen.getByText('رزرو #۵۰۰۱')).toBeInTheDocument();
  });

  it('renders no linked hint for a pure support ticket', () => {
    renderCard({ bookingId: null, refundId: null });
    expect(screen.queryByText('رزرو #۵۰۰۱')).not.toBeInTheDocument();
  });

  it('calls onOpen when clicked', () => {
    const onOpen = renderCard({});
    fireEvent.click(screen.getByTestId('ticket-card'));
    expect(onOpen).toHaveBeenCalledTimes(1);
  });
});
