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

function Harness({ length = 4, onComplete }: { length?: number; onComplete?: (v: string) => void }) {
  const [value, setValue] = useState('');
  return (
    <ThemeProvider>
      <OtpInput length={length} value={value} onChange={setValue} onComplete={onComplete} aria-label="code" />
    </ThemeProvider>
  );
}

describe('<OtpInput/> component', () => {
  it('renders one box per length', () => {
    render(<Harness length={5} />);
    expect(screen.getAllByRole('textbox')).toHaveLength(5);
  });

  it('accepts a digit into the first box', async () => {
    const user = userEvent.setup();
    render(<Harness length={4} />);
    const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
    await user.type(boxes[0], '7');
    expect(boxes[0].value).toBe('7');
  });

  it('normalizes Persian digits', async () => {
    const user = userEvent.setup();
    render(<Harness length={4} />);
    const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
    await user.type(boxes[0], '۹');
    expect(boxes[0].value).toBe('9');
  });

  it('calls onComplete with the full code once every box is filled', async () => {
    const user = userEvent.setup();
    const onComplete = jest.fn();
    render(<Harness length={4} onComplete={onComplete} />);
    const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
    await user.type(boxes[0], '1');
    await user.type(boxes[1], '2');
    await user.type(boxes[2], '3');
    await user.type(boxes[3], '4');
    expect(onComplete).toHaveBeenCalledWith('1234');
  });

  it('carries autoComplete="one-time-code" so the OS can offer the SMS code', () => {
    render(<Harness length={4} />);
    const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
    boxes.forEach((box) => expect(box).toHaveAttribute('autocomplete', 'one-time-code'));
  });

  it('backspace on an empty box clears the previous digit and moves focus there in one keypress', async () => {
    const user = userEvent.setup();
    render(<Harness length={4} />);
    const boxes = screen.getAllByRole('textbox') as HTMLInputElement[];
    await user.type(boxes[0], '1');
    await user.type(boxes[1], '2');
    boxes[2].focus();
    await user.keyboard('{Backspace}');
    expect(boxes[1].value).toBe('');
    expect(boxes[1]).toHaveFocus();
  });
});
