jest.mock("../MapComponent", () => ({
  useData: jest.fn(),
  useMap: jest.fn(),
}));
jest.mock("../mapLifecycle", () => ({
  markMapResourcePersistent: <T>(resource: T) => resource,
}));

jest.mock("ol/source/XYZ.js", () => ({
  __esModule: true,
  default: class MockXyzSource {
    constructor(readonly options: unknown) {}
  },
}));
jest.mock("ol/layer/Tile.js", () => ({
  __esModule: true,
  default: class MockTileLayer {
    private readonly source: unknown;
    private readonly properties = new Map<string, unknown>();
    constructor(options: any) {
      this.source = options.source;
    }
    getSource() {
      return this.source;
    }
    set(key: string, value: unknown) {
      this.properties.set(key, value);
    }
    get(key: string) {
      return this.properties.get(key);
    }
  },
}));
jest.mock("ol/layer/Group", () => ({
  __esModule: true,
  default: class MockGroup {
    private readonly layers: unknown[];
    private readonly properties = new Map<string, unknown>();
    constructor(options: any) {
      this.layers = options.layers;
    }
    getLayers() {
      return { getArray: () => this.layers };
    }
    set(key: string, value: unknown) {
      this.properties.set(key, value);
    }
    get(key: string) {
      return this.properties.get(key);
    }
  },
}));

import { createBaseLayerEntries, createBaseLayerSources } from "./BaseLayers";

const getLeafSources = (layer: any): unknown[] => {
  const childLayers = layer.getLayers?.().getArray?.();
  if (Array.isArray(childLayers)) {
    return childLayers.flatMap(getLeafSources);
  }
  return [layer.getSource?.()];
};

describe("base layer resources", () => {
  it("loads every tile source with anonymous CORS for canvas export", () => {
    const sources = createBaseLayerSources();

    Object.values(sources).forEach((source) => {
      expect(
        (source as unknown as { options: { crossOrigin?: string } }).options
          .crossOrigin,
      ).toBe("anonymous");
    });
  });

  it("creates independent layers backed by one shared source pool", () => {
    const sources = createBaseLayerSources();
    const primary = createBaseLayerEntries(sources);
    const compare = createBaseLayerEntries(sources);

    expect(primary).toHaveLength(compare.length);
    primary.forEach((entry, index) => {
      expect(entry.layer).not.toBe(compare[index].layer);
      expect(getLeafSources(entry.layer)).toEqual(
        getLeafSources(compare[index].layer),
      );
      expect(entry.layer.get("exportAttribution")).toBe(entry.attribution);
    });
  });
});
