import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { SandboxBootstrapCallbackContext } from "@thortiq/plugin-sdk/sandbox";

const COMMAND = Object.freeze({ id: "refresh", title: "Refresh Thortiq Kit Sandbox" });
const JOB = Object.freeze({
  id: "sync",
  title: "Sync Thortiq Kit Sandbox",
  triggers: Object.freeze([
    Object.freeze({ type: "startup" as const }),
    Object.freeze({ type: "command" as const, command: "refresh" }),
  ]),
  concurrency: "skip-if-running" as const,
});

/**
 * One activation entry for both roles. The controller context owns command and
 * job registration exactly once; view contexts render UI only. Opening two
 * panes creates two view contexts but never a second controller, so the job is
 * never registered twice. No Thortiq internals or vault paths are imported.
 */
export async function activate(
  context: SandboxBootstrapCallbackContext,
): Promise<() => void> {
  if (context.kind === "controller") {
    await context.api.commands.register(COMMAND, async () => {
      // The matching command trigger is lifecycle-owned by the registered job.
    });
    await context.api.jobs.register(JOB, async () => {
      // Perform one bounded, cancellable sync unit here.
    });
    return () => {
      // Controller cleanup runs on scope teardown.
    };
  }

  // View role: the plugin supplies and bundles React inside the opaque page.
  const container = document.querySelector<HTMLElement>("#root");
  if (!container) throw new Error("The sandbox page root is missing.");
  const root = createRoot(container);
  root.render(createElement(
    "section",
    { className: "thortiq-kit-sandbox-panel" },
    createElement("h2", null, "Thortiq Kit Sandbox panel"),
  ));
  await context.api.workspace.setViewTitle("Thortiq Kit Sandbox panel");
  return () => {
    root.unmount();
  };
}
