import "@testing-library/jest-dom/vitest";
import { afterAll, afterEach } from "vitest";

import { server } from "./server";

// Node v26 does not expose localStorage as a global unless --localstorage-file
// is passed. Provide a minimal in-memory shim so i18n and other modules that
// call localStorage.getItem/setItem work in jsdom tests.
if (typeof globalThis.localStorage === "undefined") {
  const store: Record<string, string> = {};
  Object.defineProperty(globalThis, "localStorage", {
    value: {
      getItem: (key: string) => store[key] ?? null,
      setItem: (key: string, value: string) => { store[key] = value; },
      removeItem: (key: string) => { delete store[key]; },
      clear: () => { Object.keys(store).forEach((k) => { delete store[k]; }); },
      get length() { return Object.keys(store).length; },
      key: (i: number) => Object.keys(store)[i] ?? null,
    },
    writable: true,
  });
}

// jsdom does not implement matchMedia. useMediaQuery (used by the shell
// sidebar) calls it on mount, so provide a minimal non-matching stub.
if (typeof window !== "undefined" && typeof window.matchMedia !== "function") {
  Object.defineProperty(window, "matchMedia", {
    value: (query: string): MediaQueryList =>
      ({
        matches: false,
        media: query,
        onchange: null,
        addEventListener: () => {},
        removeEventListener: () => {},
        addListener: () => {},
        removeListener: () => {},
        dispatchEvent: () => false,
      }) as MediaQueryList,
    writable: true,
  });
}

// Start MSW at module level so its fetch patch is in place before any test
// module captures globalThis.fetch via openapi-fetch's createClient().
server.listen({ onUnhandledRequest: "error" });

afterEach(() => server.resetHandlers());
afterAll(() => server.close());
