// #region SetupTestsModule [C:3] [TYPE Module] [SEMANTICS store, test, mock, setup, environment]
// @BRIEF Global vitest test setup with mocks for SvelteKit modules ($app/environment, $app/stores, $app/navigation, localStorage).
// @RELATION DEPENDS_ON -> [StoresMock]
// @RELATION DEPENDS_ON -> [NavigationMock]
// @RELATION DEPENDS_ON -> [EnvironmentMock]

// #region setupTests:Module [TYPE Function]
// @UX_STATE: Idle -> Global test environment exposes stable mocked browser services.
// @RELATION DEPENDS_ON -> [StoresMock]
// @RELATION DEPENDS_ON -> [NavigationMock]
// @RELATION DEPENDS_ON -> [EnvironmentMock]
// @PURPOSE: Global test setup with mocks for SvelteKit modules
// @LAYER UI

import { vi } from 'vitest';

// Mock $app/environment
vi.mock('$app/environment', () => ({
  browser: true,
  dev: true,
  building: false
}));

// Mock $app/stores
vi.mock('$app/stores', () => {
  const { writable } = require('svelte/store');
  return {
    page: writable({ url: new URL('http://localhost'), params: {}, route: { id: 'test' } }),
    navigating: writable(null),
    updated: { check: vi.fn(), subscribe: writable(false).subscribe }
  };
});

// Mock $app/navigation
vi.mock('$app/navigation', () => ({
  goto: vi.fn(),
  push: vi.fn(),
  replace: vi.fn(),
  prefetch: vi.fn(),
  prefetchRoutes: vi.fn()
}));

// Mock localStorage
const localStorageMock = (() => {
  let store = {};
  return {
    getItem: vi.fn((key) => store[key] || null),
    setItem: vi.fn((key, value) => { store[key] = value; }),
    removeItem: vi.fn((key) => { delete store[key]; }),
    clear: () => { store = {}; },
    get length() { return Object.keys(store).length; },
    key: vi.fn((i) => Object.keys(store)[i] || null)
  };
})();

Object.defineProperty(global, 'localStorage', { value: localStorageMock });
Object.defineProperty(global, 'sessionStorage', { value: localStorageMock });

// Mock console.log to reduce noise in tests
const originalLog = console.log;
console.log = vi.fn((...args) => {
  // Keep activity store and task drawer logs for test output
  const firstArg = args[0];
  if (typeof firstArg === 'string' && 
      (firstArg.includes('[EXT:frontend:activityStore]') || 
       firstArg.includes('[EXT:frontend:taskDrawer]') ||
       firstArg.includes('[SidebarStore]'))) {
    originalLog.apply(console, args);
  }
});

// #endregion setupTests:Module
// #endregion SetupTestsModule
