import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MapProvider, useMapStore } from './provider'
import { CartoBasemaps } from '../../const'

describe('MapProvider', () => {
  it('should provide map context to children', () => {
    const TestComponent = () => {
      const basemap = useMapStore((state) => state.maps['test-map']?.basemap)
      return <div data-testid='basemap'>{basemap}</div>
    }

    render(
      <MapProvider
        values={[
          {
            id: 'test-map',
            basemap: CartoBasemaps.positron,
            initialViewState: {
              latitude: 0,
              longitude: 0,
              zoom: 1,
            },
          },
        ]}
      >
        <TestComponent />
      </MapProvider>,
    )

    expect(screen.getByTestId('basemap').textContent).toBe(
      CartoBasemaps.positron,
    )
  })

  it('should throw error when useMapStore is used outside provider', () => {
    const TestComponent = () => {
      useMapStore((state) => state.maps)
      return <div>Test</div>
    }

    // Suppress console.error for this test
    const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {
      /* empty */
    })

    expect(() => render(<TestComponent />)).toThrow(
      'Missing MapProvider in the tree',
    )

    consoleSpy.mockRestore()
  })

  it('should allow multiple map instances', () => {
    const TestComponent = () => {
      const map1Basemap = useMapStore((state) => state.maps['map-1']?.basemap)
      const map2Basemap = useMapStore((state) => state.maps['map-2']?.basemap)
      return (
        <div>
          <div data-testid='map1'>{map1Basemap}</div>
          <div data-testid='map2'>{map2Basemap}</div>
        </div>
      )
    }

    render(
      <MapProvider
        values={[
          {
            id: 'map-1',
            basemap: CartoBasemaps.positron,
            initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
          },
          {
            id: 'map-2',
            basemap: CartoBasemaps.darkMatter,
            initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
          },
        ]}
      >
        <TestComponent />
      </MapProvider>,
    )

    expect(screen.getByTestId('map1').textContent).toBe(CartoBasemaps.positron)
    expect(screen.getByTestId('map2').textContent).toBe(
      CartoBasemaps.darkMatter,
    )
  })
})
