import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ThemeProvider } from '../../theme';

// next-intl mocked to echo keys (+ params) and locale = en so the money util groups with ASCII digits.
jest.mock('next-intl', () => ({
  useTranslations: () => (key: string, params?: Record<string, unknown>) =>
    params ? `${key}:${JSON.stringify(params)}` : key,
  useLocale: () => 'en',
}));

import BnplPlanCard from './BnplPlanCard';
import type { BnplPlanOption } from '@/services/bnpl/types';

const FEE_PLAN: BnplPlanOption = {
  planId: 'digipay_6m',
  termMonths: 6,
  installmentCount: 6,
  feePercent: 0.04,
  downPaymentPercent: 0.2,
  monthlyAmountIrr: '4040000', // 404,000 Toman
  downPaymentIrr: '4660000',
  totalIrr: '23300000',
};

const INTEREST_FREE_PLAN: BnplPlanOption = {
  planId: 'snapppay_4',
  termMonths: null,
  installmentCount: 4,
  feePercent: 0,
  downPaymentPercent: 0,
  monthlyAmountIrr: '5825000',
  downPaymentIrr: '0',
  totalIrr: '23300000',
};

function renderCard(props: Partial<React.ComponentProps<typeof BnplPlanCard>> = {}) {
  const onSelect = props.onSelect ?? jest.fn();
  render(
    <ThemeProvider>
      <BnplPlanCard plan={FEE_PLAN} selected={false} onSelect={onSelect} {...props} />
    </ThemeProvider>,
  );
  return { onSelect };
}

describe('<BnplPlanCard/> component', () => {
  it('renders the served monthly amount as grouped Toman (never derived)', () => {
    renderCard();
    expect(screen.getByText(/404,000/)).toBeInTheDocument();
    expect(screen.getByText('monthly')).toBeInTheDocument();
  });

  it('shows the fee sub-label for a fee-bearing plan and the down-payment indicator', () => {
    renderCard();
    // t('plan_fee', { percent: 4 }) — feePercent 0.04 → 4%
    expect(screen.getByText('plan_fee:{"percent":4}')).toBeInTheDocument();
    expect(screen.getByText('down_payment_percent:{"percent":20}')).toBeInTheDocument();
    expect(screen.getByRole('progressbar')).toBeInTheDocument();
  });

  it('shows "interest-free" and no down-payment bar for a 0-fee, 0-down plan', () => {
    renderCard({ plan: INTEREST_FREE_PLAN });
    expect(screen.getByText('plan_interest_free')).toBeInTheDocument();
    expect(screen.queryByRole('progressbar')).not.toBeInTheDocument();
  });

  it('marks the selected card via aria-pressed + data-selected', () => {
    renderCard({ selected: true });
    const card = screen.getByRole('button');
    expect(card).toHaveAttribute('aria-pressed', 'true');
    expect(card).toHaveAttribute('data-selected', 'true');
  });

  it('calls onSelect with the planId when clicked', async () => {
    const user = userEvent.setup();
    const { onSelect } = renderCard();
    await user.click(screen.getByRole('button'));
    expect(onSelect).toHaveBeenCalledWith('digipay_6m');
  });
});
