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

jest.mock('next-intl', () => ({
  useLocale: () => 'en',
}));

import JalaliDatePicker from './JalaliDatePicker';
import { gregorianEngine, todayIso } from './calendarEngine';

describe('<JalaliDatePicker/> — grid variant', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);

  it('emits the ISO Gregorian date of the clicked day', () => {
    const onChange = jest.fn();
    const value = '2026-07-01';
    wrap(<JalaliDatePicker value={value} onChange={onChange} />);
    fireEvent.click(screen.getByText('15'));
    expect(onChange).toHaveBeenCalledWith('2026-07-15');
  });

  it('marks today distinctly', () => {
    const { container } = wrap(<JalaliDatePicker value={null} onChange={jest.fn()} />);
    expect(container.querySelector(`[data-day="${todayIso()}"][data-today="true"]`)).toBeInTheDocument();
  });

  it('disables days outside the min/max range', () => {
    const cursorMonth = gregorianEngine.fromIso('2026-07-15');
    const min = gregorianEngine.toIso(cursorMonth.year, cursorMonth.month, 10);
    wrap(<JalaliDatePicker value="2026-07-15" min={min} onChange={jest.fn()} />);
    const early = screen.getByText('5');
    expect(early.closest('button')).toBeDisabled();
  });

  it('navigates to the next month', () => {
    const { container } = wrap(<JalaliDatePicker value="2026-07-15" onChange={jest.fn()} />);
    expect(screen.getByText('July 2026')).toBeInTheDocument();
    const nextButton = container.querySelector('[data-icon="forward"]')?.closest('button');
    expect(nextButton).not.toBeNull();
    fireEvent.click(nextButton as HTMLButtonElement);
    expect(screen.getByText('August 2026')).toBeInTheDocument();
  });
});

describe('<JalaliDatePicker/> — chips variant', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);

  it('renders chipDayCount tappable chips starting today and emits ISO on click', () => {
    const onChange = jest.fn();
    const { container } = wrap(<JalaliDatePicker variant="chips" value={null} onChange={onChange} chipDayCount={5} />);
    const chips = container.querySelectorAll('[data-day]');
    expect(chips.length).toBe(5);
    expect(chips[0]).toHaveAttribute('data-day', todayIso());
    fireEvent.click(chips[1]);
    expect(onChange).toHaveBeenCalledTimes(1);
  });
});
