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

function Harness({ initial = '' }: { initial?: string }) {
  const [value, setValue] = useState(initial);
  return (
    <ThemeProvider>
      <PhoneNumberField value={value} onChange={setValue} label="Phone" />
    </ThemeProvider>
  );
}

describe('<PhoneNumberField/> component', () => {
  it('normalizes Persian digits to ASCII', async () => {
    const user = userEvent.setup();
    render(<Harness />);
    const input = screen.getByRole('textbox') as HTMLInputElement;
    await user.type(input, '۰۹۱۲');
    expect(input.value).toBe('0912');
  });

  it('strips non-digit characters', async () => {
    const user = userEvent.setup();
    render(<Harness />);
    const input = screen.getByRole('textbox') as HTMLInputElement;
    await user.type(input, 'a0b9c1');
    expect(input.value).toBe('091');
  });

  it('caps the value at 11 digits', async () => {
    const user = userEvent.setup();
    render(<Harness />);
    const input = screen.getByRole('textbox') as HTMLInputElement;
    await user.type(input, '0912345678999');
    expect(input.value).toBe('09123456789');
  });

  it('validates Iranian mobile numbers', () => {
    expect(isIranianMobile('09123456789')).toBe(true);
    expect(isIranianMobile('0912345678')).toBe(false);
    expect(isIranianMobile('19123456789')).toBe(false);
  });

  it('carries autoComplete="tel" so the browser/keyboard can offer the saved number', () => {
    render(<Harness />);
    expect(screen.getByRole('textbox')).toHaveAttribute('autocomplete', 'tel');
  });
});
