import { describe, it, expect } from 'vitest'
import { useEffect } from 'react'
import { render } from '../tests/providers'
import {
  useSpatialFilter,
  useViewportSpatialFilter,
  useLassoToolsSpatialFilter,
  useStaticSpatialFilter,
  useGroupedSpatialFilter,
  useGroupedLassoToolsSpatialFilters,
  useGroupedStaticSpatialFilters,
} from './use-spatial-filter'
import { MAP_ID, MASK_ID } from '../tests/config'
import { useMapStore } from './providers/map/provider'
import { useLassoToolsState } from './editable/lasso-tools/provider/provider'
import type { Polygon } from 'geojson'

describe('useSpatialFilter', () => {
  it('should return spatial filter prioritizing lasso tools filter', () => {
    const TestComponent = () => {
      const result = useSpatialFilter({ mapId: MAP_ID })
      return (
        <div>
          <div data-testid='has-spatial-filter'>
            {result.spatialFilter ? 'true' : 'false'}
          </div>
          <div data-testid='has-lasso-filter'>
            {result.lassoToolsSpatialFilter ? 'true' : 'false'}
          </div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-spatial-filter"]')
        ?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="has-lasso-filter"]')?.textContent,
    ).toBe('true')
  })

  it('should return lasso tools spatial filter when available', () => {
    const TestComponent = () => {
      const result = useSpatialFilter({ mapId: MAP_ID })
      const isLassoFilter =
        result.spatialFilter === result.lassoToolsSpatialFilter
      return (
        <div data-testid='is-lasso-filter'>
          {isLassoFilter ? 'true' : 'false'}
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="is-lasso-filter"]')?.textContent,
    ).toBe('true')
  })

  it('should return all spatial filter types', () => {
    const TestComponent = () => {
      const result = useSpatialFilter({ mapId: MAP_ID })
      return (
        <div>
          <div data-testid='has-viewport'>
            {result.viewportSpatialFilter !== undefined ? 'true' : 'false'}
          </div>
          <div data-testid='has-lasso'>
            {result.lassoToolsSpatialFilter !== undefined ? 'true' : 'false'}
          </div>
          <div data-testid='has-static'>
            {result.staticSpatialFilter !== undefined ? 'true' : 'false'}
          </div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)

    const hasViewport = container.querySelector(
      '[data-testid="has-viewport"]',
    )?.textContent
    const hasLasso = container.querySelector(
      '[data-testid="has-lasso"]',
    )?.textContent
    const hasStatic = container.querySelector(
      '[data-testid="has-static"]',
    )?.textContent

    // At least one of them should be defined
    expect([hasViewport, hasLasso, hasStatic].some((v) => v === 'true')).toBe(
      true,
    )
  })
})

describe('useViewportSpatialFilter', () => {
  it('should return undefined when no viewport is set', () => {
    const TestComponent = () => {
      const result = useViewportSpatialFilter({ mapId: MAP_ID })
      return (
        <div data-testid='has-viewport-filter'>{result ? 'true' : 'false'}</div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-viewport-filter"]')
        ?.textContent,
    ).toBe('false')
  })

  it('should return SpatialFilter type when viewport exists', () => {
    const TestComponent = () => {
      const result = useViewportSpatialFilter({ mapId: MAP_ID })
      const hasCoordinates = result && 'coordinates' in result
      const hasType = result && 'type' in result

      return (
        <div>
          <div data-testid='has-coordinates'>
            {hasCoordinates ? 'true' : 'false'}
          </div>
          <div data-testid='has-type'>{hasType ? 'true' : 'false'}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)

    // The structure should be consistent - either both true or both false
    const hasCoordinates = container.querySelector(
      '[data-testid="has-coordinates"]',
    )?.textContent
    const hasType = container.querySelector(
      '[data-testid="has-type"]',
    )?.textContent

    expect(hasCoordinates).toBe(hasType)
  })
})

describe('useLassoToolsSpatialFilter', () => {
  it('should return MultiPolygon type when lasso values exist', () => {
    const TestComponent = () => {
      const result = useLassoToolsSpatialFilter({ mapId: MAP_ID })

      return (
        <div>
          <div data-testid='has-filter'>{result ? 'true' : 'false'}</div>
          <div data-testid='filter-type'>{result?.type ?? 'none'}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)

    const hasFilter = container.querySelector(
      '[data-testid="has-filter"]',
    )?.textContent
    const filterType = container.querySelector(
      '[data-testid="filter-type"]',
    )?.textContent

    // If filter exists, it should be MultiPolygon type
    if (hasFilter === 'true') {
      expect(filterType).toBe('MultiPolygon')
    }
  })

  it('should return geometry with coordinates when lasso values exist', () => {
    const TestComponent = () => {
      const result = useLassoToolsSpatialFilter({ mapId: MAP_ID })
      const hasCoordinates = result && 'coordinates' in result

      return (
        <div data-testid='has-coordinates'>
          {hasCoordinates ? 'true' : 'false'}
        </div>
      )
    }

    const { container } = render(<TestComponent />)

    const hasCoordinates = container.querySelector(
      '[data-testid="has-coordinates"]',
    )?.textContent

    // Should either have coordinates or be undefined
    expect(['true', 'false']).toContain(hasCoordinates)
  })

  it('should handle MultiPolygon geometry in lasso values', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      useEffect(() => {
        setValue(MAP_ID, MASK_ID, undefined)

        setValue(MAP_ID, 'multipolygon-value', {
          id: 'multipolygon-value',
          type: 'mask',
          properties: {
            label: 'MultiPolygon mask',
            visible: true,
          },
          geometry: {
            type: 'MultiPolygon',
            coordinates: [
              [
                [
                  [0, 0],
                  [1, 0],
                  [1, 1],
                  [0, 1],
                  [0, 0],
                ],
              ],
              [
                [
                  [2, 2],
                  [3, 2],
                  [3, 3],
                  [2, 3],
                  [2, 2],
                ],
              ],
            ],
          },
        })
      }, [setValue])

      const result = useLassoToolsSpatialFilter({ mapId: MAP_ID })
      const polygonCount = result?.coordinates?.length ?? 0

      return (
        <div>
          <div data-testid='filter-type'>{result?.type ?? 'none'}</div>
          <div data-testid='polygon-count'>{polygonCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="filter-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="polygon-count"]')?.textContent,
    ).toBe('2')
  })

  it('should combine Polygon and MultiPolygon lasso values', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      useEffect(() => {
        setValue(MAP_ID, MASK_ID, undefined)

        setValue(MAP_ID, 'polygon-value', {
          id: 'polygon-value',
          type: 'mask',
          properties: {
            label: 'Polygon mask',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })

        setValue(MAP_ID, 'multipolygon-value-mixed', {
          id: 'multipolygon-value-mixed',
          type: 'mask',
          properties: {
            label: 'MultiPolygon mask',
            visible: true,
          },
          geometry: {
            type: 'MultiPolygon',
            coordinates: [
              [
                [
                  [2, 2],
                  [3, 2],
                  [3, 3],
                  [2, 3],
                  [2, 2],
                ],
              ],
              [
                [
                  [4, 4],
                  [5, 4],
                  [5, 5],
                  [4, 5],
                  [4, 4],
                ],
              ],
            ],
          },
        })
      }, [setValue])

      const result = useLassoToolsSpatialFilter({ mapId: MAP_ID })
      const polygonCount = result?.coordinates?.length ?? 0

      return (
        <div>
          <div data-testid='filter-type'>{result?.type ?? 'none'}</div>
          <div data-testid='polygon-count'>{polygonCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="filter-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="polygon-count"]')?.textContent,
    ).toBe('3')
  })
})

describe('useStaticSpatialFilter', () => {
  it('should return undefined when no static spatial filter exists', () => {
    const TestComponent = () => {
      const result = useStaticSpatialFilter({ mapId: MAP_ID })
      return (
        <div data-testid='has-static-filter'>{result ? 'true' : 'false'}</div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-static-filter"]')?.textContent,
    ).toBe('false')
  })

  it('should create multipolygon from static Polygon geometry', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      const polygon: Polygon = {
        type: 'Polygon',
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      }

      setSpatialFilter(MAP_ID, 'filter-1', polygon)

      const result = useStaticSpatialFilter({ mapId: MAP_ID })

      return (
        <div>
          <div data-testid='has-filter'>{result ? 'true' : 'false'}</div>
          <div data-testid='filter-type'>{result?.type ?? 'none'}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-filter"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="filter-type"]')?.textContent,
    ).toBe('MultiPolygon')
  })

  it('should handle MultiPolygon geometry', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      const multiPolygon = {
        type: 'MultiPolygon' as const,
        coordinates: [
          [
            [
              [0, 0],
              [1, 0],
              [1, 1],
              [0, 1],
              [0, 0],
            ],
          ],
          [
            [
              [2, 2],
              [3, 2],
              [3, 3],
              [2, 3],
              [2, 2],
            ],
          ],
        ],
      }

      setSpatialFilter(MAP_ID, 'filter-1', multiPolygon)

      const result = useStaticSpatialFilter({ mapId: MAP_ID })
      const coordCount = result?.coordinates?.length ?? 0

      return (
        <div>
          <div data-testid='filter-type'>{result?.type ?? 'none'}</div>
          <div data-testid='coord-count'>{coordCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="filter-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="coord-count"]')?.textContent,
    ).toBe('2')
  })

  it('should create valid MultiPolygon geometry structure', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      const polygon: Polygon = {
        type: 'Polygon',
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      }

      setSpatialFilter(MAP_ID, 'test-filter', polygon)

      const result = useStaticSpatialFilter({ mapId: MAP_ID })

      const isValidStructure =
        result?.type === 'MultiPolygon' &&
        Array.isArray(result?.coordinates) &&
        result?.coordinates.length > 0

      return (
        <div data-testid='is-valid'>{isValidStructure ? 'true' : 'false'}</div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="is-valid"]')?.textContent,
    ).toBe('true')
  })
})

describe('useGroupedSpatialFilter', () => {
  it('should return empty object when no lasso values exist', () => {
    const TestComponent = () => {
      const result = useGroupedSpatialFilter({ mapId: 'non-existent-map' })
      // With no map data, it should return empty viewport filter
      const isEmpty = Object.keys(result.spatialFilter).length === 0

      return <div data-testid='is-empty'>{isEmpty ? 'true' : 'false'}</div>
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="is-empty"]')?.textContent,
    ).toBe('true')
  })

  it('should group values by groupId', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)
      const result = useGroupedSpatialFilter({ mapId: MAP_ID })

      // Use useEffect to set values after initial render
      useEffect(() => {
        // Clear existing test mask from provider
        setValue(MAP_ID, MASK_ID, undefined)

        // Add values with different groupIds
        setValue(MAP_ID, 'value-1', {
          id: 'value-1',
          type: 'mask',
          groupId: 1,
          properties: {
            label: 'Test 1',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })

        setValue(MAP_ID, 'value-2', {
          id: 'value-2',
          type: 'mask',
          groupId: 2,
          properties: {
            label: 'Test 2',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [2, 2],
                [3, 2],
                [3, 3],
                [2, 3],
                [2, 2],
              ],
            ],
          },
        })
      }, [setValue])

      // Now returns simple SpatialFilter[] - just check count
      const groupCount = result.spatialFilter.length
      const hasFilters = groupCount > 0

      return (
        <div>
          <div data-testid='has-group-1'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='has-group-2'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='group-count'>{groupCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-group-1"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="has-group-2"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('2')
  })

  it('should use "default" groupId for values without groupId', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)
      const result = useGroupedSpatialFilter({ mapId: MAP_ID })

      useEffect(() => {
        setValue(MAP_ID, 'value-no-group', {
          id: 'value-no-group',
          type: 'mask',
          properties: {
            label: 'Test No Group',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })
      }, [setValue])

      const hasDefaultGroup = result.spatialFilter.length > 0

      return (
        <div data-testid='has-default-group'>
          {hasDefaultGroup ? 'true' : 'false'}
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-default-group"]')?.textContent,
    ).toBe('true')
  })
  it('should create MultiPolygon geometry for each group', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      setValue(MAP_ID, 'group1-value1', {
        id: 'group1-value1',
        type: 'mask',
        groupId: 5,
        properties: {
          label: 'Test 1',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [0, 0],
              [1, 0],
              [1, 1],
              [0, 1],
              [0, 0],
            ],
          ],
        },
      })

      const result = useGroupedSpatialFilter({ mapId: MAP_ID })
      const testFilter = result.spatialFilter[0]
      const isMultiPolygon = testFilter?.type === 'MultiPolygon'
      const hasCoordinates = testFilter && 'coordinates' in testFilter

      return (
        <div>
          <div data-testid='is-multipolygon'>
            {isMultiPolygon ? 'true' : 'false'}
          </div>
          <div data-testid='has-coordinates'>
            {hasCoordinates ? 'true' : 'false'}
          </div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="is-multipolygon"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="has-coordinates"]')?.textContent,
    ).toBe('true')
  })

  it('should only include visible values in groups', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      setValue(MAP_ID, 'visible-value', {
        id: 'visible-value',
        type: 'mask',
        groupId: 10,
        properties: {
          label: 'Visible',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [0, 0],
              [1, 0],
              [1, 1],
              [0, 1],
              [0, 0],
            ],
          ],
        },
      })

      setValue(MAP_ID, 'hidden-value', {
        id: 'hidden-value',
        type: 'mask',
        groupId: 10,
        properties: {
          label: 'Hidden',
          visible: false,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [2, 2],
              [3, 2],
              [3, 3],
              [2, 3],
              [2, 2],
            ],
          ],
        },
      })

      const result = useGroupedSpatialFilter({ mapId: MAP_ID })
      const testFilter = result.spatialFilter[0]
      // Should only have 1 polygon (the visible one) in the multipolygon
      const polygonCount = testFilter?.coordinates?.length ?? 0

      return <div data-testid='polygon-count'>{polygonCount}</div>
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="polygon-count"]')?.textContent,
    ).toBe('1')
  })

  it('should combine multiple values in the same group into one MultiPolygon', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      useEffect(() => {
        // Clear the existing test mask first
        setValue(MAP_ID, MASK_ID, undefined)

        setValue(MAP_ID, 'same-group-1', {
          id: 'same-group-1',
          type: 'mask',
          groupId: 15,
          properties: {
            label: 'First',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })

        setValue(MAP_ID, 'same-group-2', {
          id: 'same-group-2',
          type: 'mask',
          groupId: 15,
          properties: {
            label: 'Second',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [2, 2],
                [3, 2],
                [3, 3],
                [2, 3],
                [2, 2],
              ],
            ],
          },
        })
      }, [setValue])

      const result = useGroupedSpatialFilter({ mapId: MAP_ID })
      const combinedFilter = result.spatialFilter[0]
      const polygonCount = combinedFilter?.coordinates?.length ?? 0

      return (
        <div>
          <div data-testid='is-multipolygon'>
            {combinedFilter?.type === 'MultiPolygon' ? 'true' : 'false'}
          </div>
          <div data-testid='polygon-count'>{polygonCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="is-multipolygon"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="polygon-count"]')?.textContent,
    ).toBe('2')
  })
})

describe('useGroupedLassoToolsSpatialFilters', () => {
  it('should return object with default group for existing lasso values', () => {
    const TestComponent = () => {
      const result = useGroupedLassoToolsSpatialFilters({ mapId: MAP_ID })
      const hasDefault = result.length > 0
      const groupCount = result.length

      return (
        <div>
          <div data-testid='has-default'>{hasDefault ? 'true' : 'false'}</div>
          <div data-testid='group-count'>{groupCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    // Should have at least the default group from test setup
    expect(
      container.querySelector('[data-testid="has-default"]')?.textContent,
    ).toBe('true')
  })

  it('should return MultiPolygon geometry for each group', () => {
    const TestComponent = () => {
      const result = useGroupedLassoToolsSpatialFilters({ mapId: MAP_ID })
      const defaultFilter = result[0]
      const geometryType = defaultFilter?.type

      return (
        <div>
          <div data-testid='geometry-type'>{geometryType ?? 'none'}</div>
          <div data-testid='has-coordinates'>
            {defaultFilter?.coordinates ? 'true' : 'false'}
          </div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="geometry-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="has-coordinates"]')?.textContent,
    ).toBe('true')
  })

  it('should handle multiple groups when groupId is set', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      // Add a value with a different groupId
      setValue(MAP_ID, 'test-group-value', {
        id: 'test-group-value',
        type: 'mask',
        groupId: 20,
        properties: {
          label: 'Custom Group',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [5, 5],
              [6, 5],
              [6, 6],
              [5, 6],
              [5, 5],
            ],
          ],
        },
      })

      const result = useGroupedLassoToolsSpatialFilters({ mapId: MAP_ID })
      const hasCustomGroup = result.length > 0
      const groupCount = result.length

      return (
        <div>
          <div data-testid='has-custom-group'>
            {hasCustomGroup ? 'true' : 'false'}
          </div>
          <div data-testid='group-count'>{groupCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-custom-group"]')?.textContent,
    ).toBe('true')
    // Should have both default and custom-group
    const groupCount = container.querySelector(
      '[data-testid="group-count"]',
    )?.textContent
    expect(Number(groupCount)).toBeGreaterThanOrEqual(1)
  })

  it('should filter groups by groupIds parameter', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      // Add values with different groupIds
      setValue(MAP_ID, 'group-1-value', {
        id: 'group-1-value',
        type: 'mask',
        groupId: 1,
        properties: {
          label: 'Group 1',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [0, 0],
              [1, 0],
              [1, 1],
              [0, 1],
              [0, 0],
            ],
          ],
        },
      })

      setValue(MAP_ID, 'group-2-value', {
        id: 'group-2-value',
        type: 'mask',
        groupId: 2,
        properties: {
          label: 'Group 2',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [2, 2],
              [3, 2],
              [3, 3],
              [2, 3],
              [2, 2],
            ],
          ],
        },
      })

      setValue(MAP_ID, 'group-3-value', {
        id: 'group-3-value',
        type: 'mask',
        groupId: 3,
        properties: {
          label: 'Group 3',
          visible: true,
        },
        geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [4, 4],
              [5, 4],
              [5, 5],
              [4, 5],
              [4, 4],
            ],
          ],
        },
      })

      // Filter to only include groups 1 and 3
      const result = useGroupedLassoToolsSpatialFilters({
        mapId: MAP_ID,
        groupIds: [1, 3],
      })

      // With groupIds filter, we should get 2 filters (one for each group)
      const hasFilters = result.length > 0
      const groupCount = result.length

      return (
        <div>
          <div data-testid='has-group-1'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='has-group-2'>false</div>
          <div data-testid='has-group-3'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='group-count'>{groupCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-group-1"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="has-group-2"]')?.textContent,
    ).toBe('false')
    expect(
      container.querySelector('[data-testid="has-group-3"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('2')
  })

  it('should return all groups when groupIds is empty', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      useEffect(() => {
        // Clear the default test mask first
        setValue(MAP_ID, MASK_ID, undefined)

        setValue(MAP_ID, 'group-1-value', {
          id: 'group-1-value',
          type: 'mask',
          groupId: 1,
          properties: {
            label: 'Group 1',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })

        setValue(MAP_ID, 'group-2-value', {
          id: 'group-2-value',
          type: 'mask',
          groupId: 2,
          properties: {
            label: 'Group 2',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [2, 2],
                [3, 2],
                [3, 3],
                [2, 3],
                [2, 2],
              ],
            ],
          },
        })
      }, [setValue])

      // Empty groupIds should return all groups
      const result = useGroupedLassoToolsSpatialFilters({
        mapId: MAP_ID,
        groupIds: [],
      })

      const groupCount = result.length

      return <div data-testid='group-count'>{groupCount}</div>
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('2')
  })

  it('should combine Polygon and MultiPolygon values in the same group', () => {
    const TestComponent = () => {
      const setValue = useLassoToolsState((state) => state.setValue)

      useEffect(() => {
        setValue(MAP_ID, MASK_ID, undefined)

        setValue(MAP_ID, 'mixed-polygon', {
          id: 'mixed-polygon',
          type: 'mask',
          groupId: 30,
          properties: {
            label: 'Polygon',
            visible: true,
          },
          geometry: {
            type: 'Polygon',
            coordinates: [
              [
                [0, 0],
                [1, 0],
                [1, 1],
                [0, 1],
                [0, 0],
              ],
            ],
          },
        })

        setValue(MAP_ID, 'mixed-multipolygon', {
          id: 'mixed-multipolygon',
          type: 'mask',
          groupId: 30,
          properties: {
            label: 'MultiPolygon',
            visible: true,
          },
          geometry: {
            type: 'MultiPolygon',
            coordinates: [
              [
                [
                  [2, 2],
                  [3, 2],
                  [3, 3],
                  [2, 3],
                  [2, 2],
                ],
              ],
              [
                [
                  [4, 4],
                  [5, 4],
                  [5, 5],
                  [4, 5],
                  [4, 4],
                ],
              ],
            ],
          },
        })
      }, [setValue])

      const result = useGroupedLassoToolsSpatialFilters({
        mapId: MAP_ID,
        groupIds: [30],
      })
      const combinedFilter = result[0]
      const polygonCount = combinedFilter?.coordinates?.length ?? 0

      return (
        <div>
          <div data-testid='filter-type'>{combinedFilter?.type ?? 'none'}</div>
          <div data-testid='polygon-count'>{polygonCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="filter-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="polygon-count"]')?.textContent,
    ).toBe('3')
  })
})

describe('useGroupedStaticSpatialFilters', () => {
  it('should return empty object when no static spatial filters exist', () => {
    const TestComponent = () => {
      const result = useGroupedStaticSpatialFilters({ mapId: 'non-existent' })
      const groupCount = result.length

      return <div data-testid='group-count'>{groupCount}</div>
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('0')
  })

  it('should create MultiPolygon geometry for static filters', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      setSpatialFilter(MAP_ID, 'test-filter', {
        type: 'Polygon',
        groupId: 25,
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      })

      const result = useGroupedStaticSpatialFilters({ mapId: MAP_ID })
      const testFilter = result[0]

      return (
        <div>
          <div data-testid='geometry-type'>{testFilter?.type ?? 'none'}</div>
          <div data-testid='has-coordinates'>
            {testFilter?.coordinates ? 'true' : 'false'}
          </div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="geometry-type"]')?.textContent,
    ).toBe('MultiPolygon')
    expect(
      container.querySelector('[data-testid="has-coordinates"]')?.textContent,
    ).toBe('true')
  })

  it('should use default groupId when none is specified', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      setSpatialFilter(MAP_ID, 'no-group-filter', {
        type: 'Polygon',
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      })

      const result = useGroupedStaticSpatialFilters({ mapId: MAP_ID })
      const hasDefault = result.length > 0

      return (
        <div data-testid='has-default'>{hasDefault ? 'true' : 'false'}</div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-default"]')?.textContent,
    ).toBe('true')
  })

  it('should filter groups by groupIds parameter', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      setSpatialFilter(MAP_ID, 'filter-1', {
        type: 'Polygon',
        groupId: 1,
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      })

      setSpatialFilter(MAP_ID, 'filter-2', {
        type: 'Polygon',
        groupId: 2,
        coordinates: [
          [
            [2, 2],
            [3, 2],
            [3, 3],
            [2, 3],
            [2, 2],
          ],
        ],
      })

      setSpatialFilter(MAP_ID, 'filter-3', {
        type: 'Polygon',
        groupId: 3,
        coordinates: [
          [
            [4, 4],
            [5, 4],
            [5, 5],
            [4, 5],
            [4, 4],
          ],
        ],
      })

      // Filter to only include groups 1 and 3
      const result = useGroupedStaticSpatialFilters({
        mapId: MAP_ID,
        groupIds: [1, 3],
      })

      // With groupIds filter, we should get 2 filters (one for each group)
      const hasFilters = result.length > 0
      const groupCount = result.length

      return (
        <div>
          <div data-testid='has-group-1'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='has-group-2'>false</div>
          <div data-testid='has-group-3'>{hasFilters ? 'true' : 'false'}</div>
          <div data-testid='group-count'>{groupCount}</div>
        </div>
      )
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="has-group-1"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="has-group-2"]')?.textContent,
    ).toBe('false')
    expect(
      container.querySelector('[data-testid="has-group-3"]')?.textContent,
    ).toBe('true')
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('2')
  })

  it('should return all groups when groupIds is empty', () => {
    const TestComponent = () => {
      const setSpatialFilter = useMapStore((state) => state.setSpatialFilter)

      setSpatialFilter(MAP_ID, 'filter-1', {
        type: 'Polygon',
        groupId: 1,
        coordinates: [
          [
            [0, 0],
            [1, 0],
            [1, 1],
            [0, 1],
            [0, 0],
          ],
        ],
      })

      setSpatialFilter(MAP_ID, 'filter-2', {
        type: 'Polygon',
        groupId: 2,
        coordinates: [
          [
            [2, 2],
            [3, 2],
            [3, 3],
            [2, 3],
            [2, 2],
          ],
        ],
      })

      // Empty groupIds should return all groups
      const result = useGroupedStaticSpatialFilters({
        mapId: MAP_ID,
        groupIds: [],
      })

      const groupCount = result.length

      return <div data-testid='group-count'>{groupCount}</div>
    }

    const { container } = render(<TestComponent />)
    expect(
      container.querySelector('[data-testid="group-count"]')?.textContent,
    ).toBe('2')
  })
})
