import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach, beforeAll, afterAll, vi } from 'vitest';
import { server } from './mocks/server';

// Mock WordPress globals
Object.defineProperty(window, 'sequensyAPI', {
  value: {
    root: 'http://localhost:9000/wp-json/sequensy/v1',
    nonce: 'test-nonce-12345',
    activeScreen: 'workflows',
    license: {
      is_active: true,
      tier: 'professional',
    },
  },
  writable: true,
});

// Mock WordPress i18n (wp.i18n)
Object.defineProperty(window, 'wp', {
  value: {
    i18n: {
      __: (text: string) => text,
      _e: (text: string) => text,
      _x: (text: string) => text,
      _n: (single: string, plural: string, number: number) => (number === 1 ? single : plural),
      _nx: (single: string, plural: string, number: number) => (number === 1 ? single : plural),
      sprintf: (format: string, ...args: unknown[]) => {
        let result = format;
        args.forEach((arg) => {
          result = result.replace(/%[sd]/, String(arg));
        });
        return result;
      },
      isRTL: () => false,
      setLocaleData: () => {},
    },
  },
  writable: true,
});

// Mock matchMedia (required by some Radix UI components)
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query: string) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
});

// Mock ResizeObserver (required by React Flow and Radix)
global.ResizeObserver = vi.fn().mockImplementation(() => ({
  observe: vi.fn(),
  unobserve: vi.fn(),
  disconnect: vi.fn(),
}));

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

// Mock scrollIntoView (not available in jsdom)
Element.prototype.scrollIntoView = vi.fn();

// MSW setup
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => {
  cleanup();
  server.resetHandlers();
});
afterAll(() => server.close());
