import { describe, expect, it, vi } from "vitest";
import type { SandboxBootstrapCallbackContext } from "@thortiq/plugin-sdk/sandbox";
import { activate } from "../src/activate.js";

describe("Thortiq Kit Sandbox sandbox activation", () => {
  it("opens two views while controller registrations remain exactly once", async () => {
    const register = vi.fn().mockResolvedValue({ destroy: () => {} });
    const registerJob = vi.fn().mockResolvedValue({ destroy: () => {} });
    const controller = {
      kind: "controller",
      api: { commands: { register }, jobs: { register: registerJob } },
      signal: new AbortController().signal,
    } as unknown as SandboxBootstrapCallbackContext;
    await activate(controller);
    const setViewTitle = vi.fn().mockResolvedValue(undefined);
    for (const instanceId of ["view-a", "view-b"]) {
      document.body.innerHTML = '<div id="root"></div>';
      const view = {
        kind: "view",
        api: { workspace: { setViewTitle } },
        initialState: { instanceId },
        resources: {},
        signal: new AbortController().signal,
      } as unknown as SandboxBootstrapCallbackContext;
      const cleanup = await activate(view);
      await vi.waitFor(() => {
        expect(document.querySelector(".thortiq-kit-sandbox-panel")).not.toBeNull();
      });
      cleanup();
    }
    expect(setViewTitle).toHaveBeenCalledTimes(2);
    expect(register).toHaveBeenCalledTimes(1);
    expect(registerJob).toHaveBeenCalledTimes(1);
  });
});
