(() => {
  "use strict";

  const MIN_SPLASH_MS = 2000;

  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();
  }

  function showSwitchSplash(label) {
    const splash = byId("project-switch-splash");
    const text = byId("project-splash-text");
    if (text) text.textContent = label ? `Loading ${label}` : "Loading project";
    if (splash) {
      splash.classList.add("active");
      splash.setAttribute("aria-hidden", "false");
    }
  }

  function hideSwitchSplash() {
    const splash = byId("project-switch-splash");
    if (splash) {
      splash.classList.remove("active");
      splash.setAttribute("aria-hidden", "true");
    }
  }

  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" };

    const started = Date.now();
    showSwitchSplash(input.label || input.name || input.serialNo || key);

    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) {
      const wait = Math.max(0, MIN_SPLASH_MS - (Date.now() - started));
      await new Promise(resolve => setTimeout(resolve, wait));
      hideSwitchSplash();
      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;
    const renderWork = window.MonitorProject?.renderProject ? window.MonitorProject.renderProject(projectState) : projectState;

    const wait = Math.max(0, MIN_SPLASH_MS - (Date.now() - started));
    await new Promise(resolve => setTimeout(resolve, wait));
    await renderWork;

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

  window.DeckProject = { initiateProjectSwitch };
})();
