(() => {
  "use strict";


  function byId(id) { return document.getElementById(id); }
  function safeCall(fn, ...args) { try { if (typeof fn === "function") return fn(...args); } catch {} }
  function toastMsg(message) { safeCall(window.toast, message); }

  function apiBase() {
    try { return window.DeckConnection?.getURL?.() || ""; }
    catch { return ""; }
  }

  async function postJson(path, body) {
    if (typeof window.api === "function") return await window.api(path, "POST", body);
    const res = await fetch(apiBase() + path, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body || {})
    });
    return await res.json();
  }

  async function initiateProjectSwitch(input = {}) {
    const key = String(input.serialNo || input.name || input.projectKey || input.key || "").trim();
    if (!key) return { ok: false, error: "missing_project_key" };

    if (window.LaunchGate?.requireSignIn?.('project_switch')) {
      return { ok: false, error: "account_required", message: "Sign in to select a project." };
    }

    if (typeof window.__editorBeforeExit === "function") {
      const allowed = await window.__editorBeforeExit();
      if (!allowed) return { ok: false, cancelled: true, error: "project_switch_cancelled" };
    }

    const result = await postJson("/projects/select", {
      name: String(input.name || "").trim(),
      serialNo: String(input.serialNo || "").trim(),
      key: String(input.key || input.projectKey || "").trim(),
      location: String(input.location || "").trim(),
      path: String(input.path || "").trim(),
      projectFile: String(input.projectFile || "").trim(),
      source: input.source || "monitor"
    });

    if (!result?.ok) {
      toastMsg(result?.message || result?.error || "Project switch failed");
      safeCall(window.appendLog, `✗ project switch failed: ${result?.message || result?.error || "unknown"}`, "fail");
      return result;
    }

    const projectState = result.projectState || result;
    if (window.MonitorProject?.renderProject) await window.MonitorProject.renderProject(projectState);
    if (window.MonitorProject?.loadProjectSelector) await window.MonitorProject.loadProjectSelector();
    if (window.VerbatimPanels?.refreshAfterProjectSwitch) await window.VerbatimPanels.refreshAfterProjectSwitch(projectState);
    window.dispatchEvent(new CustomEvent("verbatim:project-switched", { detail: { result, projectState } }));

    safeCall(window.appendLog, `✓ project switched: ${result.activeProject || key}`, "pass");
    return result;
  }
  window.DeckProject = { initiateProjectSwitch };
})();
