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

// next-intl echoes keys so we can assert on them; locale = en so numbers format with ASCII digits.
jest.mock('next-intl', () => ({
  useTranslations: () => {
    const t = (key: string, values?: Record<string, unknown>) =>
      values ? `${key}:${Object.values(values).join(',')}` : key;
    t.has = () => true;
    return t;
  },
  useLocale: () => 'en',
}));

// NurseResultCard renders <TrustBadge nurseId=…>, which calls useNurseTrustBadge — mock it so the
// card doesn't need a real QueryClientProvider in this test.
jest.mock('@/services/verification', () => ({
  useNurseTrustBadge: () => ({ data: undefined, isLoading: false, isError: false }),
}));

import NurseResultCard from './NurseResultCard';

const NURSE: NurseSearchResult = {
  nurseId: 1,
  variantId: 11,
  serviceCategoryId: 1,
  nurseName: 'Maryam Rezaei',
  avatarUrl: null,
  isVerified: true,
  averageRating: 4.9,
  totalReviews: 37,
  totalCompletedBookings: 52,
  distanceKm: 2.4,
  priceFromIrr: '2800000',
  priceUnit: 'per_hour',
  nurseGender: 'female',
  cityId: 101,
  districtId: 1003,
  topReviewTag: null,
};

function renderCard(nurse: NurseSearchResult, onSelect = jest.fn(), serviceLabel = 'Elderly Care') {
  render(
    <ThemeProvider>
      <NurseResultCard nurse={nurse} serviceLabel={serviceLabel} onSelect={onSelect} />
    </ThemeProvider>,
  );
  return onSelect;
}

describe('<NurseResultCard/> component', () => {
  it('renders the name, service label, the reused verified badge, and the rating', () => {
    renderCard(NURSE);
    expect(screen.getByText('Maryam Rezaei')).toBeInTheDocument();
    expect(screen.getByText('Elderly Care')).toBeInTheDocument();
    expect(screen.getByText('badge_verified')).toBeInTheDocument();
    expect(screen.getByText('4.9')).toBeInTheDocument();
    expect(screen.getByText(/reviews_count/)).toBeInTheDocument();
  });

  it('renders the nurse gender chip and the completed-visits count', () => {
    const { container } = render(
      <ThemeProvider>
        <NurseResultCard nurse={NURSE} serviceLabel="Elderly Care" onSelect={jest.fn()} />
      </ThemeProvider>,
    );
    expect(container.querySelector('[data-nurse-gender="female"]')).toBeInTheDocument();
    expect(screen.getByText(/completed_visits/)).toBeInTheDocument();
  });

  it('renders the "from" price line as grouped Toman via the money util', () => {
    renderCard(NURSE);
    expect(screen.getByText('price_from')).toBeInTheDocument();
    // 2,800,000 IRR = 280,000 Toman.
    expect(screen.getByText(/280,000/)).toBeInTheDocument();
  });

  it('shows the distance chip only when distanceKm is present', () => {
    const { rerender } = render(
      <ThemeProvider>
        <NurseResultCard nurse={NURSE} serviceLabel="Elderly Care" onSelect={jest.fn()} />
      </ThemeProvider>,
    );
    expect(screen.getByText(/distance_km/)).toBeInTheDocument();

    rerender(
      <ThemeProvider>
        <NurseResultCard nurse={{ ...NURSE, distanceKm: null }} serviceLabel="Elderly Care" onSelect={jest.fn()} />
      </ThemeProvider>,
    );
    expect(screen.queryByText(/distance_km/)).not.toBeInTheDocument();
  });

  it('renders the optional top-review tag only when served', () => {
    const { rerender } = render(
      <ThemeProvider>
        <NurseResultCard nurse={NURSE} serviceLabel="Elderly Care" onSelect={jest.fn()} />
      </ThemeProvider>,
    );
    expect(screen.queryByText(/منظم و دقیق/)).not.toBeInTheDocument();

    rerender(
      <ThemeProvider>
        <NurseResultCard
          nurse={{ ...NURSE, topReviewTag: 'منظم و دقیق' }}
          serviceLabel="Elderly Care"
          onSelect={jest.fn()}
        />
      </ThemeProvider>,
    );
    expect(screen.getByText(/منظم و دقیق/)).toBeInTheDocument();
  });

  it('falls back to a label when the name is missing (b7 join gap)', () => {
    renderCard({ ...NURSE, nurseName: '' });
    expect(screen.getByText('unnamed_nurse')).toBeInTheDocument();
  });

  it('calls onSelect with the nurse row when clicked', () => {
    const onSelect = jest.fn();
    const { container } = render(
      <ThemeProvider>
        <NurseResultCard nurse={NURSE} serviceLabel="Elderly Care" onSelect={onSelect} />
      </ThemeProvider>,
    );
    fireEvent.click(container.querySelector('[data-nurse-result-card]') as HTMLElement);
    expect(onSelect).toHaveBeenCalledWith(NURSE);
  });

  it('exposes a co-located Skeleton twin matching the card shell', () => {
    const { container } = render(
      <ThemeProvider>
        <NurseResultCard.Skeleton />
      </ThemeProvider>,
    );
    expect(container.querySelectorAll('.MuiSkeleton-root').length).toBeGreaterThan(0);
  });
});
