import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import { MeasurementToolsProvider, useMeasurementToolsState } from './provider'

describe('MeasurementToolsProvider', () => {
  it('should provide measurement tools context to children', () => {
    const TestComponent = () => {
      const enabled = useMeasurementToolsState(
        (state) => state.measurements['test-map']?.enabled,
      )
      return <div data-testid='enabled'>{String(enabled)}</div>
    }

    render(
      <MeasurementToolsProvider values={[{ mapId: 'test-map', enabled: true }]}>
        <TestComponent />
      </MeasurementToolsProvider>,
    )

    expect(screen.getByTestId('enabled').textContent).toBe('true')
  })

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

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

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

    consoleSpy.mockRestore()
  })

  it('should allow multiple map instances', () => {
    const TestComponent = () => {
      const map1Enabled = useMeasurementToolsState(
        (state) => state.measurements['map-1']?.enabled,
      )
      const map2Enabled = useMeasurementToolsState(
        (state) => state.measurements['map-2']?.enabled,
      )
      return (
        <div>
          <div data-testid='map1'>{String(map1Enabled)}</div>
          <div data-testid='map2'>{String(map2Enabled)}</div>
        </div>
      )
    }

    render(
      <MeasurementToolsProvider
        values={[
          { mapId: 'map-1', enabled: true },
          { mapId: 'map-2', enabled: false },
        ]}
      >
        <TestComponent />
      </MeasurementToolsProvider>,
    )

    expect(screen.getByTestId('map1').textContent).toBe('true')
    expect(screen.getByTestId('map2').textContent).toBe('false')
  })
})
