// ============================================================
// 🧠 Jemy-dev OS — HUD Mock Environment (Phase 9.2)
// Purpose: Universal mock layer for AI Summary, Neural Voice,
//          Depth Provider, and Export Center (both runtime + tests).
// ============================================================

import { vi } from 'vitest';

// ============================================================
// 🧩 1. Speech Synthesis & Recognition Mocks
// ============================================================

export const setupSpeechMocks = () => {
  if (typeof window === 'undefined') return;

  // 🗣️ Voice Synthesis
  (window as any).speechSynthesis = {
    getVoices: vi.fn(() => [
      { name: 'Mock Voice', lang: 'en-US', default: true },
      { name: 'Alt Voice', lang: 'en-GB', default: false },
    ]),
    speak: vi.fn(),
    cancel: vi.fn(),
    paused: false,
    speaking: false,
    pending: false,
    onvoiceschanged: null,
  };

  // 🎙️ Speech Recognition (for NeuralDialogHUD)
  (window as any).SpeechRecognition = vi.fn().mockImplementation(() => ({
    start: vi.fn(),
    stop: vi.fn(),
    abort: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    onresult: null,
    onerror: null,
    onend: null,
  }));
};

// ============================================================
// 🧩 2. DOM & Browser API Mocks
// ============================================================

export const setupDOMMocks = () => {
  // 🧩 ResizeObserver mock
  (window as any).ResizeObserver = vi.fn().mockImplementation(() => ({
    observe: vi.fn(),
    unobserve: vi.fn(),
    disconnect: vi.fn(),
  }));

  // 👁️ IntersectionObserver mock
  (window as any).IntersectionObserver = vi.fn().mockImplementation(() => ({
    observe: vi.fn(),
    unobserve: vi.fn(),
    disconnect: vi.fn(),
  }));

  // 🌐 Window navigation & open mock
  (window as any).open = vi.fn();
  (window as any).location = {
    href: '',
    assign: vi.fn(),
    reload: vi.fn(),
  };
};

// ============================================================
// 🧩 3. Local Storage & Memory Simulation
// ============================================================

export const setupStorageMock = () => {
  (global as any).localStorage = {
    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 = {};
    },
  };
};

// ============================================================
// 🧩 4. Unified Initializer (for both runtime & tests)
// ============================================================

export const initializeHUDMockEnvironment = () => {
  setupSpeechMocks();
  setupDOMMocks();
  setupStorageMock();

  console.log(
    '✅ [HUD Mock Env] Initialized synthetic browser layer for testing / runtime emulation.'
  );
};
