import { render, screen } from '@testing-library/react';
import { NextIntlClientProvider, useTranslations } from 'next-intl';
import { FunctionComponent } from 'react';
import enMessages from '../../../messages/en.json';
import faMessages from '../../../messages/fa.json';

/*
 * The auth screens' `t.rich` call sites, exercised against the REAL message catalogue and the
 * REAL next-intl formatter.
 *
 * `OtpStep.test.tsx` stubs `t.rich` to an identity function, which is precisely how a broken
 * message shipped: `otp_sent_to` carried a `{phone}` *value* placeholder while the component
 * passed a *function* for it, so next-intl handed the function straight through and React was
 * asked to render it — "Functions are not valid as a React child". A value placeholder and a
 * rich-text tag are not interchangeable, and only the real formatter can tell them apart.
 */

const MASKED_PHONE = '0912*****34';
const CLOCK = '01:59';

const PhoneEcho: FunctionComponent = () => {
  const t = useTranslations('auth');
  return <p>{t.rich('otp_sent_to', { phone: () => <bdi dir="ltr">{MASKED_PHONE}</bdi> })}</p>;
};

const ResendCountdown: FunctionComponent = () => {
  const t = useTranslations('auth');
  return <p>{t.rich('resend_in', { time: () => <bdi dir="ltr">{CLOCK}</bdi> })}</p>;
};

describe.each([
  ['fa', faMessages],
  ['en', enMessages],
])('auth rich-text messages (%s)', (locale, messages) => {
  function renderWithLocale(node: React.ReactNode) {
    render(
      <NextIntlClientProvider locale={locale} messages={messages}>
        {node}
      </NextIntlClientProvider>
    );
  }

  it('renders the masked phone as a real node inside otp_sent_to', () => {
    renderWithLocale(<PhoneEcho />);
    expect(screen.getByText(MASKED_PHONE)).toBeInTheDocument();
  });

  it('isolates the phone in an LTR <bdi> so RTL bidi never reorders the digit runs', () => {
    renderWithLocale(<PhoneEcho />);
    expect(screen.getByText(MASKED_PHONE).tagName.toLowerCase()).toBe('bdi');
  });

  it('renders the countdown as a real node inside resend_in', () => {
    renderWithLocale(<ResendCountdown />);
    expect(screen.getByText(CLOCK)).toBeInTheDocument();
  });
});
