import type {
  JsonValue,
  NativePluginApiV1,
  NativePluginViewContext,
  PluginActivationApiV1,
} from "@thortiq/plugin-api";

const VIEW = Object.freeze({ id: "panel", title: "Thortiq Example Host Search View panel", icon: "sparkles" });
const COMMAND = Object.freeze({ id: "refresh", title: "Refresh Thortiq Example Host Search View" });

/**
 * Native full-trust activation. This entry is bundled by scripts/build.mjs into
 * one self-contained import-free ESM file; it never imports Thortiq application
 * internals or a filesystem handle, and never targets the user's live vault.
 */
export function activate(api: PluginActivationApiV1): void {
  if (api.runtime !== "native") {
    throw new Error("Thortiq Example Host Search View requires the declared native runtime.");
  }
  api.commands.register(COMMAND, async () => {
    // Manual refresh: re-read bounded admitted data here.
  });

  api.views.register({
    ...VIEW,
    create(context, container) {
      return createPanel(api as NativePluginApiV1, context, container);
    },
  });
}

function createPanel(
  api: NativePluginApiV1,
  context: NativePluginViewContext,
  container: HTMLElement,
): { getState(): JsonValue; destroy(): void } {
  const doc = container.ownerDocument;
  const root = doc.createElement("section");
  root.className = "thortiq-example-host-search-view-panel";
  const heading = doc.createElement("h2");
  const icon = doc.createElement("img");
  icon.alt = "";
  icon.width = 16;
  icon.height = 16;
  // Package assets are addressed through the host, never a relative runtime URL.
  void api.packageAssets.getUrl("assets/icon.svg").then(url => {
    if (!context.signal.aborted) icon.src = url;
  });
  const label = doc.createElement("span");
  heading.append(icon, label);
  root.append(heading);
  const searchContainer = doc.createElement("div");
  root.append(searchContainer);
  const searchView = api.components.searchView.mount(searchContainer, {
    query: "",
    configuration: {},
    resultsReadOnly: true,
    configurationReadOnly: true,
    allowCreate: false,
    allowMutations: false,
    configurationPersistence: "none",
    includeBare: false,
    includeAssets: false,
    pageSize: 100,
  });

  container.replaceChildren(root);
  context.setTitle(VIEW.title);

  const render = async () => {
    const configured = await api.settings.get("label");
    if (context.signal.aborted) return;
    label.textContent = typeof configured === "string" && configured.length > 0
      ? configured
      : VIEW.title;
  };
  void render();
  const subscription = api.settings.subscribe(keys => {
    if (keys.includes("label")) void render();
  });

  return Object.freeze({
    getState(): JsonValue {
      return Object.freeze({ view: "panel" });
    },
    destroy() {
      subscription.dispose();
      searchView.destroy();

      root.remove();
    },
  });
}



export default Object.freeze({ activate });
