// @vitest-environment jsdom
import { render, act } from "@testing-library/react";
import { AnalyticsLoader } from "./loader.js";
import type { Logger } from "@/observability/logger/types";

// Mock the facade so we don't load real adapters
vi.mock("./facade.js", () => ({
  createAnalytics: vi.fn(() => ({ track: vi.fn(), page: vi.fn() })),
}));

const stubLogger: Logger = {
  debug: vi.fn(),
  info: vi.fn(),
  warn: vi.fn(),
  error: vi.fn(),
  child: vi.fn(),
};

describe("AnalyticsLoader", () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it("renders children and initializes analytics via setTimeout fallback", async () => {
    const { getByText } = render(
      <AnalyticsLoader
        enabled={{ metrica: true, ctm: false, variocube: false, dynatrace: false }}
        consent={{ analytics: true, telemetry: true }}
        logger={stubLogger}
      >
        <span>child</span>
      </AnalyticsLoader>,
    );

    expect(getByText("child")).toBeDefined();

    // Fire the setTimeout(init, 1) callback
    await act(async () => {
      vi.advanceTimersByTime(10);
    });

    const { createAnalytics } = await import("./facade.js");
    expect(createAnalytics).toHaveBeenCalled();
  });
});
