import '@testing-library/jest-dom'

import React from 'react'

import {cleanup} from '@testing-library/react'
import {afterEach, vi} from 'vitest'

// Clean up after each test to prevent test pollution
afterEach(() => {
  cleanup()
})

// Mock window.matchMedia if not available (for components using media queries)
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query: string) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(), // deprecated
    removeListener: vi.fn(), // deprecated
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
})

// Mock IntersectionObserver (used by List component)
global.IntersectionObserver = vi.fn().mockImplementation(() => ({
  observe: vi.fn(),
  unobserve: vi.fn(),
  disconnect: vi.fn(),
  root: null,
  rootMargin: '',
  thresholds: [],
  takeRecords: vi.fn(),
}))

// Mock ResizeObserver (used by react-virtuoso)
global.ResizeObserver = vi.fn().mockImplementation(() => ({
  observe: vi.fn(),
  unobserve: vi.fn(),
  disconnect: vi.fn(),
}))

// Set default window size for virtuoso calculations
Object.defineProperty(window, 'innerHeight', {
  writable: true,
  configurable: true,
  value: 768,
})

Object.defineProperty(window, 'innerWidth', {
  writable: true,
  configurable: true,
  value: 1024,
})

vi.mock('react-virtuoso', () => ({
  Virtuoso: vi.fn().mockImplementation(props => {
    const {data, itemContent, style, className, components, endReached} = props
    const items = data || []

    // Simulating virtualization
    const maxVisibleItems = 20
    const visibleItems = items.slice(0, maxVisibleItems)

    React.useEffect(() => {
      if (endReached && items.length >= maxVisibleItems) {
        // Simulating reaching the end after a short delay
        const timer = setTimeout(() => endReached(), 100)
        return () => clearTimeout(timer)
      }
      return undefined
    }, [endReached, items.length])

    return React.createElement(
      'div',
      {
        className,
        style,
        'data-testid': 'virtuoso-scroller',
        'data-virtuoso-scroller': 'true',
        'data-item-count': items.length,
        'data-visible-items': visibleItems.length,
      },
      components?.Header && components.Header(),
      React.createElement(
        'div',
        {'data-testid': 'virtuoso-item-list'},
        visibleItems.map((item: any, index: number) =>
          React.createElement(
            'div',
            {key: `virtuoso-item-${String(item?.id || index)}`},
            itemContent?.(index, item)
          )
        )
      ),
      components?.Footer && components.Footer()
    )
  }),
}))
