import { describe, it, expect, vi, beforeEach } from 'vitest'
import { useMapScreenshot } from './use-map-screenshot'
import { act, renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { MapProvider, useMapStore } from './providers/map/provider'
import { CartoBasemaps, GmapsBasemap } from './const'
import { MAP_ID } from '../tests/config'
import html2canvas from 'html2canvas'
import type { ReactNode } from 'react'

// Mock html2canvas — resolves a real HTMLCanvasElement so `drawImage` sees a
// valid CanvasImageSource in environments that type-check the argument.
vi.mock('html2canvas', () => ({
  default: vi.fn(() => {
    const canvas = document.createElement('canvas')
    canvas.width = 200
    canvas.height = 200
    return Promise.resolve(canvas)
  }),
}))

describe('useMapScreenshot', () => {
  let queryClient: QueryClient

  beforeEach(() => {
    queryClient = new QueryClient({
      defaultOptions: { queries: { retry: false } },
    })
    vi.clearAllMocks()
  })

  const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={queryClient}>
      <MapProvider
        values={[
          {
            id: MAP_ID,
            basemap: CartoBasemaps.positron,
            initialViewState: {
              latitude: 0,
              longitude: 0,
              zoom: 1,
            },
          },
        ]}
      >
        {children}
      </MapProvider>
    </QueryClientProvider>
  )

  it('should initialize with default values', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    expect(result.current.screenshot).toBeUndefined()
    expect(result.current.isLoading).toBe(false)
    expect(result.current.error).toBeUndefined()
  })

  it('should have takeScreenshot function', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    expect(typeof result.current.takeScreenshot).toBe('function')
  })

  it('should set isLoading when layers are not loaded', async () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    act(() => {
      result.current.takeScreenshot()
    })

    await waitFor(() => {
      expect(result.current.isLoading).toBe(true)
    })
  })

  it('should handle missing map instance gracefully', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Call takeScreenshot without proper setup
    result.current.takeScreenshot()

    // Should not throw
    expect(result.current.error).toBeUndefined()
  })

  it('should set isLoading to false initially', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    expect(result.current.isLoading).toBe(false)
  })

  it('should check if all layers are loaded', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // isAllLoaded combines isLoaded and areLayersLoaded
    expect(typeof result.current.isLoading).toBe('boolean')
  })

  it('should handle basemap type correctly', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Should initialize without errors even with basemap checks
    expect(result.current).toBeDefined()
  })

  it('should handle screenshot state', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    expect(result.current.screenshot).toBeUndefined()
  })

  it('should handle error state', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    expect(result.current.error).toBeUndefined()
  })

  it('should get deck instance function from store', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Hook should initialize without errors
    expect(result.current).toBeDefined()
  })

  it('should get overlay instance function from store', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Hook should initialize without errors
    expect(result.current).toBeDefined()
  })

  it('should check layers loaded status', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Should have access to areLayersLoaded state
    expect(result.current).toBeDefined()
  })

  it('should check map loaded status', () => {
    const { result } = renderHook(() => useMapScreenshot({ mapId: MAP_ID }), {
      wrapper,
    })

    // Should have access to isLoaded state
    expect(result.current).toBeDefined()
  })

  it('should call html2canvas with scale=pixelRatio on the Google Maps branch', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 1,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          // Default pixelRatio is 2 — capture should be at 2× regardless
          // of the display's DPR.
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeCanvas = document.createElement('canvas')
      fakeCanvas.width = 600
      fakeCanvas.height = 400
      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => fakeCanvas,
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
      }

      act(() => {
        // Wire up fake instances on the refs that the hook reads through
        // getDeckInstance / getOverlayInstance.
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      expect(html2canvas).toHaveBeenCalledWith(
        expect.any(HTMLElement),
        expect.objectContaining({ scale: 2, useCORS: true }),
      )

      // Deck was bumped to the requested DPR, then restored.
      expect(fakeDeck.setProps).toHaveBeenNthCalledWith(1, {
        useDevicePixels: 2,
      })
      expect(fakeDeck.setProps).toHaveBeenLastCalledWith({
        useDevicePixels: true,
      })
      expect(fakeDeck.redraw).toHaveBeenCalledWith('screenshot-resize')
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should not draw while the basemap-idle flag is false', async () => {
    const gmapsWrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={queryClient}>
        <MapProvider
          values={[
            {
              id: MAP_ID,
              basemap: GmapsBasemap.roadmap,
              initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
            },
          ]}
        >
          {children}
        </MapProvider>
      </QueryClientProvider>
    )

    const { result } = renderHook(
      () => ({
        screenshot: useMapScreenshot({ mapId: MAP_ID }),
        setLoad: useMapStore((s) => s.setLoad),
        setLayersLoad: useMapStore((s) => s.setLayersLoad),
        maps: useMapStore((s) => s.maps),
      }),
      { wrapper: gmapsWrapper },
    )

    const fakeCanvas = document.createElement('canvas')
    fakeCanvas.width = 600
    fakeCanvas.height = 400
    const fakeDeck = {
      width: 200,
      height: 200,
      getCanvas: () => fakeCanvas,
      redraw: vi.fn(),
      needsRedraw: () => false as const,
    }
    const fakeGmaps = {
      getDiv: () => document.createElement('div'),
      getRenderingType: () => 'RASTER',
    }

    act(() => {
      const mapState = result.current.maps[MAP_ID]!
      mapState.instanceRef!.current = {
        // @ts-expect-error - minimal fake for test
        deck: fakeDeck,
      }
      mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
      result.current.setLoad(MAP_ID, true)
      result.current.setLayersLoad(MAP_ID, true)
      // Intentionally do NOT call setIdle — gate should block the draw.
    })

    vi.useFakeTimers()
    try {
      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      // The mutation retries internally (500ms delay × up to 10 attempts) while
      // isAllLoaded is false. Advance fake time through several retry cycles
      // and confirm no draw ever happens.
      await act(async () => {
        await vi.advanceTimersByTimeAsync(2000)
      })

      expect(html2canvas).not.toHaveBeenCalled()
      expect(result.current.screenshot.screenshot).toBeUndefined()
      expect(result.current.screenshot.isLoading).toBe(true)
    } finally {
      vi.useRealTimers()
    }
  })

  it('should wait for deck.needsRedraw() to return false before drawing', async () => {
    const gmapsWrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={queryClient}>
        <MapProvider
          values={[
            {
              id: MAP_ID,
              basemap: GmapsBasemap.roadmap,
              initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
            },
          ]}
        >
          {children}
        </MapProvider>
      </QueryClientProvider>
    )

    const { result } = renderHook(
      () => ({
        screenshot: useMapScreenshot({ mapId: MAP_ID }),
        setLoad: useMapStore((s) => s.setLoad),
        setLayersLoad: useMapStore((s) => s.setLayersLoad),
        setIdle: useMapStore((s) => s.setIdle),
        maps: useMapStore((s) => s.maps),
      }),
      { wrapper: gmapsWrapper },
    )

    const fakeCanvas = document.createElement('canvas')
    fakeCanvas.width = 600
    fakeCanvas.height = 400
    // First 3 polls report busy, subsequent polls report idle. We need 2
    // consecutive idle frames to resolve, so html2canvas must fire only after
    // at least call #5.
    const needsRedraw = vi
      .fn<(opts?: { clearRedrawFlags: boolean }) => string | false>()
      .mockReturnValueOnce('view changed')
      .mockReturnValueOnce('view changed')
      .mockReturnValueOnce('view changed')
      .mockReturnValue(false)
    const fakeDeck = {
      width: 200,
      height: 200,
      getCanvas: () => fakeCanvas,
      redraw: vi.fn(),
      needsRedraw,
    }
    const fakeGmaps = {
      getDiv: () => document.createElement('div'),
      getRenderingType: () => 'RASTER',
    }

    act(() => {
      const mapState = result.current.maps[MAP_ID]!
      mapState.instanceRef!.current = {
        // @ts-expect-error - minimal fake for test
        deck: fakeDeck,
      }
      mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
      result.current.setLoad(MAP_ID, true)
      result.current.setLayersLoad(MAP_ID, true)
      result.current.setIdle(MAP_ID, true)
    })

    act(() => {
      result.current.screenshot.takeScreenshot()
    })

    await waitFor(() => {
      expect(html2canvas).toHaveBeenCalled()
    })

    // 3 busy + at least 2 idle calls before draw resolves.
    expect(needsRedraw.mock.calls.length).toBeGreaterThanOrEqual(5)
    // All calls must use the non-mutating peek option.
    for (const call of needsRedraw.mock.calls) {
      expect(call[0]).toEqual({ clearRedrawFlags: false })
    }
  })

  it('should honor an explicit pixelRatio override', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 1,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          screenshot: useMapScreenshot({
            mapId: MAP_ID,
            pixelRatio: 3,
          }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => document.createElement('canvas'),
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
      }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      expect(html2canvas).toHaveBeenCalledWith(
        expect.any(HTMLElement),
        expect.objectContaining({ scale: 3 }),
      )
      expect(fakeDeck.setProps).toHaveBeenNthCalledWith(1, {
        useDevicePixels: 3,
      })
      expect(fakeDeck.setProps).toHaveBeenLastCalledWith({
        useDevicePixels: true,
      })
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should default to the native DPR when it is already above 2', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 3,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          // No pixelRatio — default should resolve to max(2, 3) = 3,
          // which already matches the display, so no resize.
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => document.createElement('canvas'),
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
      }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      // Captures at the native 3× — html2canvas scale matches, deck untouched.
      expect(html2canvas).toHaveBeenCalledWith(
        expect.any(HTMLElement),
        expect.objectContaining({ scale: 3 }),
      )
      expect(fakeDeck.setProps).not.toHaveBeenCalled()
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should not resize deck when pixelRatio already matches window.devicePixelRatio', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 2,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          // Default pixelRatio=2, window DPR=2 → no resize required.
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => document.createElement('canvas'),
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
      }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      expect(fakeDeck.setProps).not.toHaveBeenCalled()
      expect(fakeDeck.redraw).not.toHaveBeenCalledWith('screenshot-resize')
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should resize maplibre via setPixelRatio + triggerRepaint, await idle, then restore on the CARTO basemap branch', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 1,
    })

    try {
      const { result } = renderHook(
        () => ({
          // Default pixelRatio resolves to max(2, 1) = 2; window=1 →
          // both deck and maplibre need to resize.
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper },
      )

      const fakeDeckCanvas = document.createElement('canvas')
      fakeDeckCanvas.width = 600
      fakeDeckCanvas.height = 400
      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => fakeDeckCanvas,
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }

      const fakeMaplibreCanvas = document.createElement('canvas')
      fakeMaplibreCanvas.width = 600
      fakeMaplibreCanvas.height = 400
      const idleHandlers: (() => void)[] = []
      const innerMap = {
        getCanvas: () => fakeMaplibreCanvas,
        getPixelRatio: vi.fn(() => 1),
        setPixelRatio: vi.fn(),
        triggerRepaint: vi.fn(),
        once: vi.fn((event: string, cb: () => void) => {
          if (event === 'idle') idleHandlers.push(cb)
        }),
      }
      const fakeMaplibre = { getMap: () => innerMap, redraw: vi.fn() }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        // @ts-expect-error - minimal fake for test
        mapState.overlayRef!.current = fakeMaplibre
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      // The hook must register `once('idle', cb)` after calling
      // setPixelRatio + triggerRepaint, then suspend until cb is invoked.
      await waitFor(() => {
        expect(idleHandlers.length).toBe(1)
      })

      // Verify the setup ran before we resolve idle.
      expect(innerMap.setPixelRatio).toHaveBeenNthCalledWith(1, 2)
      expect(innerMap.triggerRepaint).toHaveBeenCalledTimes(1)
      expect(fakeDeck.setProps).not.toHaveBeenCalled() // deck waits for maplibre

      // Fire idle: capture proceeds, deck resizes, drawImage runs, restore.
      act(() => {
        for (const cb of idleHandlers) cb()
      })

      await waitFor(() => {
        expect(result.current.screenshot.screenshot).toBeDefined()
      })

      // Deck was resized after maplibre idle, then restored.
      expect(fakeDeck.setProps).toHaveBeenNthCalledWith(1, {
        useDevicePixels: 2,
      })
      expect(fakeDeck.setProps).toHaveBeenLastCalledWith({
        useDevicePixels: true,
      })
      expect(fakeDeck.redraw).toHaveBeenCalledWith('screenshot-resize')

      // Maplibre was restored to its original pixel ratio with another
      // triggerRepaint (fire-and-forget, no second idle wait).
      expect(innerMap.setPixelRatio).toHaveBeenCalledTimes(2)
      expect(innerMap.setPixelRatio).toHaveBeenNthCalledWith(2, 1)
      expect(innerMap.triggerRepaint).toHaveBeenCalledTimes(2)
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should never touch maplibre setPixelRatio on the Google Maps branch', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 1,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => document.createElement('canvas'),
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      // The gmaps overlay does NOT expose `getMap` — the hook must detect
      // that and skip the maplibre branch entirely. We deliberately attach
      // a poisoned getMap that would fail loudly if it ever ran.
      const poisonedGetMap = vi.fn(() => {
        throw new Error('getMap must not be called for gmaps basemaps')
      })
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
        getMap: poisonedGetMap,
      }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      expect(poisonedGetMap).not.toHaveBeenCalled()
      // Deck still resizes (the gmaps branch only skips maplibre).
      expect(fakeDeck.setProps).toHaveBeenNthCalledWith(1, {
        useDevicePixels: 2,
      })
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should skip maplibre setPixelRatio when pixelRatio already matches window.devicePixelRatio', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 2,
    })

    try {
      const { result } = renderHook(
        () => ({
          // Default pixelRatio resolves to max(2, 2) = 2 → no resize.
          screenshot: useMapScreenshot({ mapId: MAP_ID }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper },
      )

      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => document.createElement('canvas'),
        redraw: vi.fn(),
        needsRedraw: () => false as const,
        props: { useDevicePixels: true },
        setProps: vi.fn(),
      }
      const innerMap = {
        getCanvas: () => document.createElement('canvas'),
        getPixelRatio: vi.fn(() => 2),
        setPixelRatio: vi.fn(),
        triggerRepaint: vi.fn(),
        once: vi.fn(),
      }
      const fakeMaplibre = { getMap: () => innerMap, redraw: vi.fn() }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        // @ts-expect-error - minimal fake for test
        mapState.overlayRef!.current = fakeMaplibre
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(result.current.screenshot.screenshot).toBeDefined()
      })

      expect(innerMap.setPixelRatio).not.toHaveBeenCalled()
      expect(innerMap.triggerRepaint).not.toHaveBeenCalled()
      expect(innerMap.once).not.toHaveBeenCalled()
      expect(fakeDeck.setProps).not.toHaveBeenCalled()
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should override window.devicePixelRatio when a pixelRatio prop is provided', async () => {
    const originalDprDescriptor = Object.getOwnPropertyDescriptor(
      window,
      'devicePixelRatio',
    )
    Object.defineProperty(window, 'devicePixelRatio', {
      configurable: true,
      value: 3,
    })

    try {
      const gmapsWrapper = ({ children }: { children: ReactNode }) => (
        <QueryClientProvider client={queryClient}>
          <MapProvider
            values={[
              {
                id: MAP_ID,
                basemap: GmapsBasemap.roadmap,
                initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
              },
            ]}
          >
            {children}
          </MapProvider>
        </QueryClientProvider>
      )

      const { result } = renderHook(
        () => ({
          screenshot: useMapScreenshot({
            mapId: MAP_ID,
            pixelRatio: 1,
          }),
          setLoad: useMapStore((s) => s.setLoad),
          setLayersLoad: useMapStore((s) => s.setLayersLoad),
          setIdle: useMapStore((s) => s.setIdle),
          maps: useMapStore((s) => s.maps),
        }),
        { wrapper: gmapsWrapper },
      )

      const fakeCanvas = document.createElement('canvas')
      fakeCanvas.width = 600
      fakeCanvas.height = 400
      const fakeDeck = {
        width: 200,
        height: 200,
        getCanvas: () => fakeCanvas,
        redraw: vi.fn(),
        needsRedraw: () => false as const,
      }
      const fakeGmaps = {
        getDiv: () => document.createElement('div'),
        getRenderingType: () => 'RASTER',
      }

      act(() => {
        const mapState = result.current.maps[MAP_ID]!
        mapState.instanceRef!.current = {
          // @ts-expect-error - minimal fake for test
          deck: fakeDeck,
        }
        mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
        result.current.setLoad(MAP_ID, true)
        result.current.setLayersLoad(MAP_ID, true)
        result.current.setIdle(MAP_ID, true)
      })

      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      await waitFor(() => {
        expect(html2canvas).toHaveBeenCalled()
      })

      expect(html2canvas).toHaveBeenCalledWith(
        expect.any(HTMLElement),
        expect.objectContaining({ scale: 1, useCORS: true }),
      )
    } finally {
      if (originalDprDescriptor) {
        Object.defineProperty(window, 'devicePixelRatio', originalDprDescriptor)
      } else {
        // @ts-expect-error - removing a property we added
        delete window.devicePixelRatio
      }
    }
  })

  it('should not draw while the basemap-idle flag is false', async () => {
    const gmapsWrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={queryClient}>
        <MapProvider
          values={[
            {
              id: MAP_ID,
              basemap: GmapsBasemap.roadmap,
              initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
            },
          ]}
        >
          {children}
        </MapProvider>
      </QueryClientProvider>
    )

    const { result } = renderHook(
      () => ({
        screenshot: useMapScreenshot({ mapId: MAP_ID }),
        setLoad: useMapStore((s) => s.setLoad),
        setLayersLoad: useMapStore((s) => s.setLayersLoad),
        maps: useMapStore((s) => s.maps),
      }),
      { wrapper: gmapsWrapper },
    )

    const fakeCanvas = document.createElement('canvas')
    fakeCanvas.width = 600
    fakeCanvas.height = 400
    const fakeDeck = {
      width: 200,
      height: 200,
      getCanvas: () => fakeCanvas,
      redraw: vi.fn(),
      needsRedraw: () => false as const,
    }
    const fakeGmaps = {
      getDiv: () => document.createElement('div'),
      getRenderingType: () => 'RASTER',
    }

    act(() => {
      const mapState = result.current.maps[MAP_ID]!
      mapState.instanceRef!.current = {
        // @ts-expect-error - minimal fake for test
        deck: fakeDeck,
      }
      mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
      result.current.setLoad(MAP_ID, true)
      result.current.setLayersLoad(MAP_ID, true)
      // Intentionally do NOT call setIdle — gate should block the draw.
    })

    vi.useFakeTimers()
    try {
      act(() => {
        result.current.screenshot.takeScreenshot()
      })

      // The mutation retries internally (500ms delay × up to 10 attempts) while
      // isAllLoaded is false. Advance fake time through several retry cycles
      // and confirm no draw ever happens.
      await act(async () => {
        await vi.advanceTimersByTimeAsync(2000)
      })

      expect(html2canvas).not.toHaveBeenCalled()
      expect(result.current.screenshot.screenshot).toBeUndefined()
      expect(result.current.screenshot.isLoading).toBe(true)
    } finally {
      vi.useRealTimers()
    }
  })

  it('should wait for deck.needsRedraw() to return false before drawing', async () => {
    const gmapsWrapper = ({ children }: { children: ReactNode }) => (
      <QueryClientProvider client={queryClient}>
        <MapProvider
          values={[
            {
              id: MAP_ID,
              basemap: GmapsBasemap.roadmap,
              initialViewState: { latitude: 0, longitude: 0, zoom: 1 },
            },
          ]}
        >
          {children}
        </MapProvider>
      </QueryClientProvider>
    )

    const { result } = renderHook(
      () => ({
        screenshot: useMapScreenshot({ mapId: MAP_ID }),
        setLoad: useMapStore((s) => s.setLoad),
        setLayersLoad: useMapStore((s) => s.setLayersLoad),
        setIdle: useMapStore((s) => s.setIdle),
        maps: useMapStore((s) => s.maps),
      }),
      { wrapper: gmapsWrapper },
    )

    const fakeCanvas = document.createElement('canvas')
    fakeCanvas.width = 600
    fakeCanvas.height = 400
    // First 3 polls report busy, subsequent polls report idle. We need 2
    // consecutive idle frames to resolve, so html2canvas must fire only after
    // at least call #5.
    const needsRedraw = vi
      .fn<(opts?: { clearRedrawFlags: boolean }) => string | false>()
      .mockReturnValueOnce('view changed')
      .mockReturnValueOnce('view changed')
      .mockReturnValueOnce('view changed')
      .mockReturnValue(false)
    const fakeDeck = {
      width: 200,
      height: 200,
      getCanvas: () => fakeCanvas,
      redraw: vi.fn(),
      needsRedraw,
    }
    const fakeGmaps = {
      getDiv: () => document.createElement('div'),
      getRenderingType: () => 'RASTER',
    }

    act(() => {
      const mapState = result.current.maps[MAP_ID]!
      mapState.instanceRef!.current = {
        // @ts-expect-error - minimal fake for test
        deck: fakeDeck,
      }
      mapState.overlayRef!.current = fakeGmaps as unknown as google.maps.Map
      result.current.setLoad(MAP_ID, true)
      result.current.setLayersLoad(MAP_ID, true)
      result.current.setIdle(MAP_ID, true)
    })

    act(() => {
      result.current.screenshot.takeScreenshot()
    })

    await waitFor(() => {
      expect(html2canvas).toHaveBeenCalled()
    })

    // 3 busy + at least 2 idle calls before draw resolves.
    expect(needsRedraw.mock.calls.length).toBeGreaterThanOrEqual(5)
    // All calls must use the non-mutating peek option.
    for (const call of needsRedraw.mock.calls) {
      expect(call[0]).toEqual({ clearRedrawFlags: false })
    }
  })
})
