import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '../../theme';
import AddressMapPicker from './AddressMapPicker';
import type { LatLng } from '@/services/addresses/types';

function renderPicker(value: LatLng | null, center?: LatLng) {
  const onChange = jest.fn();
  const utils = render(
    <ThemeProvider>
      <AddressMapPicker
        value={value}
        onChange={onChange}
        center={center}
        helperText="Drop a pin"
        latLabel="Latitude"
        lngLabel="Longitude"
      />
    </ThemeProvider>,
  );
  return { ...utils, onChange };
}

describe('<AddressMapPicker/> component', () => {
  it('prompts to drop a pin when no coordinate is set', () => {
    renderPicker(null);
    expect(screen.getAllByText('Drop a pin').length).toBeGreaterThan(0);
  });

  it('emits real coordinates around the centre when the canvas is tapped', () => {
    const center = { latitude: 35.6892, longitude: 51.389 };
    const { onChange } = renderPicker(null, center);
    fireEvent.click(screen.getByRole('application'), { clientX: 10, clientY: 10 });
    // jsdom reports a 0×0 rect, so the tap resolves to the viewport centre = the city centroid.
    expect(onChange).toHaveBeenCalledTimes(1);
    expect(onChange).toHaveBeenCalledWith(center);
  });

  it('shows the coordinate readout once a pin is placed', () => {
    renderPicker({ latitude: 35.6892, longitude: 51.389 });
    expect(screen.getByText(/35\.68920/)).toBeInTheDocument();
    expect(screen.getByText(/51\.38900/)).toBeInTheDocument();
  });
});
