import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import React from 'react';

// Use doMock to avoid hoisting issues and potential caching conflicts
vi.doMock('../google-maps-loader', () => ({
  useGoogleMapsLoader: () => ({
    isLoaded: true,
    loadError: undefined,
    load: async () => {},
  }),
}));

describe('Map', () => {
  let Map: any;

  const mockMap = {
    setCenter: vi.fn(),
    setZoom: vi.fn(),
    addListener: vi.fn(() => ({ remove: vi.fn() })),
  };

  const mockInfoWindow = {
    open: vi.fn(),
    close: vi.fn(),
    setContent: vi.fn(),
    addListener: vi.fn(() => ({ remove: vi.fn() })),
  };

  beforeEach(async () => {
    vi.clearAllMocks();

    // Dynamically import Map after doMock
    const module = await import('./map');
    Map = module.Map;

    // Mock Google Maps Globals
    global.google = {
      maps: {
        Map: vi.fn(function () {
          return mockMap;
        }),
        InfoWindow: vi.fn(function () {
          return mockInfoWindow;
        }),
        Circle: vi.fn(function () {
          return { setMap: vi.fn() };
        }),
        Polygon: vi.fn(function () {
          return { setMap: vi.fn() };
        }),
        marker: {
          AdvancedMarkerElement: vi.fn(),
        },
      },
    } as any;
  });

  afterEach(() => {
    delete (global as any).google;
    vi.resetModules();
  });

  it('renders correctly when loaded', () => {
    render(<Map apiKey="AIza-test" />);
    const mapElement = document.querySelector('gmp-map');
    expect(mapElement).toBeInTheDocument();
  });

  it('renders markers correctly', () => {
    const markers = [
      { position: { lat: 10, lng: 20 }, title: 'Marker 1' },
      { position: { lat: 30, lng: 40 }, title: 'Marker 2' },
    ];

    render(<Map apiKey="AIza-test" markers={markers} />);

    const advancedMarkers = document.querySelectorAll('gmp-advanced-marker');
    expect(advancedMarkers.length).toBe(2);
    expect(advancedMarkers[0]).toHaveAttribute('title', 'Marker 1');
  });
});
