/**
 * Vitest Setup File
 * Global mocks and configurations for unit tests
 */

import { vi } from 'vitest'

// Mock localStorage for tests
const localStorageMock = {
  store: {} as Record<string, string>,
  getItem(key: string) {
    return this.store[key] || null
  },
  setItem(key: string, value: string) {
    this.store[key] = value
  },
  removeItem(key: string) {
    delete this.store[key]
  },
  clear() {
    this.store = {}
  }
}

Object.defineProperty(globalThis, 'localStorage', {
  value: localStorageMock
})

// Mock sessionStorage
Object.defineProperty(globalThis, 'sessionStorage', {
  value: localStorageMock
})

// Mock window.matchMedia
Object.defineProperty(globalThis, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn()
  }))
})

// Mock ResizeObserver
globalThis.ResizeObserver = vi.fn().mockImplementation(() => ({
  observe: vi.fn(),
  unobserve: vi.fn(),
  disconnect: vi.fn()
}))

// Mock IntersectionObserver
globalThis.IntersectionObserver = vi.fn().mockImplementation(() => ({
  observe: vi.fn(),
  unobserve: vi.fn(),
  disconnect: vi.fn()
}))

// Mock window.scrollTo
globalThis.scrollTo = vi.fn()

// Mock HTMLMediaElement methods
globalThis.HTMLMediaElement.prototype.play = vi.fn().mockResolvedValue(undefined)
globalThis.HTMLMediaElement.prototype.pause = vi.fn()
globalThis.HTMLMediaElement.prototype.load = vi.fn()

// Mock canvas context for video screenshots
HTMLCanvasElement.prototype.getContext = vi.fn().mockReturnValue({
  drawImage: vi.fn(),
  fillRect: vi.fn(),
  clearRect: vi.fn(),
  getImageData: vi.fn(),
  putImageData: vi.fn(),
  createImageData: vi.fn()
})

HTMLCanvasElement.prototype.toDataURL = vi.fn().mockReturnValue('data:image/png;base64,mock')

// Mock URL.createObjectURL
globalThis.URL.createObjectURL = vi.fn().mockReturnValue('blob:mock-url')
globalThis.URL.revokeObjectURL = vi.fn()

// Clean up after each test
afterEach(() => {
  localStorageMock.clear()
  vi.clearAllMocks()
})
