import { FunctionComponent } from 'react';
import { render, screen } from '@testing-library/react';
import { ThemeProvider } from '../../theme';
import { formatIrrToToman, parseIrr } from '@/utils';

// next-intl mocked to echo keys; locale = en so money formats with ASCII digits we can assert on.
jest.mock('next-intl', () => ({
  useTranslations: () => (key: string) => key,
  useLocale: () => 'en',
}));

import PriceBreakdown, { PriceBreakdownProps } from './PriceBreakdown';

const ComponentToTest: FunctionComponent<PriceBreakdownProps> = (props) => (
  <ThemeProvider>
    <PriceBreakdown {...props} />
  </ThemeProvider>
);

// Served-shaped figures: service + commission + VAT = total (the phase's reconciliation rule).
const ROWS = [
  { key: 'service_cost', label: 'Service cost', amountIrr: '39060000' },
  { key: 'commission', label: 'Balinyaar fee', amountIrr: '5400000' },
  { key: 'vat', label: 'VAT', amountIrr: '540000' },
];
const TOTAL = '45000000';

describe('<PriceBreakdown/> component', () => {
  it('renders every row label with its Toman-formatted amount', () => {
    render(<ComponentToTest rows={ROWS} totalLabel="Total" totalAmountIrr={TOTAL} />);
    for (const row of ROWS) {
      expect(screen.getByText(row.label)).toBeInTheDocument();
      expect(screen.getByText(formatIrrToToman(row.amountIrr, 'en'))).toBeInTheDocument();
    }
  });

  it('renders a total equal to the integer sum of the served rows', () => {
    render(<ComponentToTest rows={ROWS} totalLabel="Total" totalAmountIrr={TOTAL} />);
    const sum = ROWS.reduce((acc, row) => acc + parseIrr(row.amountIrr), BigInt(0));
    expect(sum.toString()).toBe(TOTAL);
    expect(screen.getByText(new RegExp(formatIrrToToman(TOTAL, 'en')))).toBeInTheDocument();
  });

  it('exposes each row via a data attribute', () => {
    const { container } = render(<ComponentToTest rows={ROWS} totalLabel="Total" totalAmountIrr={TOTAL} />);
    expect(container.querySelector('[data-row="service_cost"]')).toBeInTheDocument();
    expect(container.querySelector('[data-row="total"]')).toBeInTheDocument();
  });

  it('warns loudly in dev when the rows do not reconcile to the total', () => {
    const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
    render(<ComponentToTest rows={ROWS} totalLabel="Total" totalAmountIrr="45000001" />);
    expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('must reconcile'));
    errorSpy.mockRestore();
  });
});
