import '@testing-library/jest-dom/vitest'

// Ensure happy-dom environment is properly initialized
if (typeof window === 'undefined' || typeof document === 'undefined') {
  throw new Error('happy-dom environment not initialized. Check vitest config.')
}

// Polyfill window.matchMedia for jsdom (required by TDesign)
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: (query: string) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: () => {},
    removeListener: () => {},
    addEventListener: () => {},
    removeEventListener: () => {},
    dispatchEvent: () => false,
  }),
})

// Polyfill window.getComputedStyle to suppress jsdom warnings
const originalGetComputedStyle = window.getComputedStyle
window.getComputedStyle = (elt: Element, pseudoElt?: string | null) => {
  try {
    return originalGetComputedStyle(elt, pseudoElt)
  } catch {
    return {} as CSSStyleDeclaration
  }
}

// Polyfill ResizeObserver for TDesign
global.ResizeObserver = class ResizeObserver {
  observe() {}
  unobserve() {}
  disconnect() {}
}

// Suppress TDesign Form internal act() warnings
// These warnings come from TDesign's FormItem component internal async state updates
// They don't affect test reliability - all tests pass successfully
const originalError = console.error
console.error = (...args: unknown[]) => {
  const message = args[0]
  // Filter out TDesign FormItem act() warnings
  if (
    typeof message === 'string' &&
    message.includes('An update to FormItem inside a test was not wrapped in act(...)')
  ) {
    return
  }
  originalError(...args)
}
