// ── Subagents (modal + RPC poller only) ─────────────────────────────────────
// Stage C of the Dynamic Glass Panel arc — see ~/Documents/dynamic-glass-panel.md.
//
// Before Stage C this file owned the SUBAGENTS sticky panel: list
// rendering, Quick Deploy preset buttons, staging chips, count badge,
// custom spawn button. The sticky panel is gone; in-flight sub-agents
// now surface in the AWAITING footer (glass-ui/js/symframe-awaiting.js).
//
// What survives here:
//   - The subagent spawn modal (overlay + form + submit handler)
//   - The fetchSubagents poll loop (30s interval + gateway:connected)
//   - The agent preset data (AGENT_PRESETS) — kept as data for possible
//     future Stage D re-exposure (preset picker in the spawn modal)
//   - window.subagentsPanel exported API:
//       refresh()           — force a fetch
//       open()              — open the spawn modal (custom)
//       getActive()         — current subagents snapshot
//   - CustomEvent dispatch after each successful fetch so the AWAITING
//     surface (and any future consumer) re-renders without polling
//     a parallel copy of the same RPC.
// ─────────────────────────────────────────────────────────────────────────────

"use strict";

(function () {
  // Agent presets — kept as DATA only (Stage C dropped the quick-deploy
  // UI; the spawn modal still defaults to custom). A future Stage D mode
  // could surface these in a preset picker inside the modal.
  const AGENT_PRESETS = {
    research: {
      label: "Research Agent",
      taskTemplate: "Research and summarize: ",
      model: "sonnet",
      thinking: "",
    },
    review: {
      label: "Code Review Agent",
      taskTemplate: "Review this code and provide detailed feedback:\n",
      model: "sonnet",
      thinking: "",
    },
    writer: {
      label: "Writer Agent",
      taskTemplate: "Draft content for: ",
      model: "sonnet",
      thinking: "",
    },
    analyst: {
      label: "Analyst Agent",
      taskTemplate: "Analyze and report on: ",
      model: "sonnet",
      thinking: "",
    },
    planner: {
      label: "Planner Agent",
      taskTemplate: "Create an action plan for: ",
      model: "sonnet",
      thinking: "",
    },
    debug: {
      label: "Debug Agent",
      taskTemplate: "Debug and fix this issue:\n",
      model: "sonnet",
      thinking: "",
    },
    docs: {
      label: "Documentation Agent",
      taskTemplate: "Write documentation for: ",
      model: "sonnet",
      thinking: "",
    },
    test: { label: "Test Agent", taskTemplate: "Write tests for: ", model: "sonnet", thinking: "" },
  };

  // ── State ──
  let subagents = [];
  let _pollInterval = null;

  // ── Modal DOM refs (these elements live in their own overlay block
  // further down in index.html and are untouched by Stage C). ──
  const modalOverlay = document.getElementById("subagent-modal-overlay");
  const modalClose = document.getElementById("subagent-modal-close");
  const modalCancel = document.getElementById("subagent-modal-cancel");
  const modalSubmit = document.getElementById("subagent-modal-submit");
  const taskInput = document.getElementById("subagent-task");
  const labelInput = document.getElementById("subagent-label");
  const modelSelect = document.getElementById("subagent-model");
  const thinkingSelect = document.getElementById("subagent-thinking");

  // ── Fetch + notify ──
  async function fetchSubagents() {
    if (!window.gateway?.connected) {
      return;
    }
    try {
      const result = await window.gateway.rpc("subagents.list", {
        sessionKey: window.SESSION_KEY || "agent:main:main",
      });
      if (result?.subagents) {
        subagents = result.subagents;
        // Notify any subscriber (the AWAITING surface listens for this)
        window.dispatchEvent(new CustomEvent("symi:subagents-updated", { detail: { subagents } }));
      }
    } catch (err) {
      console.debug("[subagents] Failed to fetch:", err.message);
    }
  }

  // ── Modal ──
  function openModal() {
    if (!modalOverlay) {
      return;
    }
    modalOverlay.classList.add("open");
    modalOverlay.setAttribute("aria-hidden", "false");
    if (taskInput) {
      taskInput.focus();
    }
    document.addEventListener("keydown", onModalKey);
  }

  function closeModal() {
    if (!modalOverlay) {
      return;
    }
    modalOverlay.classList.remove("open");
    modalOverlay.setAttribute("aria-hidden", "true");
    document.removeEventListener("keydown", onModalKey);
    if (taskInput) {
      taskInput.value = "";
    }
    if (labelInput) {
      labelInput.value = "";
    }
    if (modelSelect) {
      modelSelect.value = "";
    }
    if (thinkingSelect) {
      thinkingSelect.value = "";
    }
  }

  function onModalKey(e) {
    if (e.key === "Escape") {
      closeModal();
    }
  }

  // ── Spawn (custom-only path; preset staging dropped in Stage C) ──
  async function spawnFromModal() {
    if (!taskInput) {
      return;
    }
    const task = taskInput.value.trim();
    if (!task) {
      taskInput.focus();
      return;
    }
    const label = (labelInput?.value || "").trim() || "Custom Subagent";
    const model = modelSelect?.value || undefined;
    const thinking = thinkingSelect?.value || undefined;

    if (modalSubmit) {
      modalSubmit.disabled = true;
    }
    try {
      if (!window.gateway?.connected) {
        throw new Error("Gateway not connected");
      }
      const uuid = crypto.randomUUID();
      const sessionKey = `agent:main:subagent:${uuid}`;
      await window.gateway.rpc("agent", {
        message: task,
        sessionKey,
        deliver: false,
        lane: "subagent",
        label,
        model,
        thinking,
        timeout: 300,
      });
      closeModal();
      setTimeout(fetchSubagents, 500);
    } catch (err) {
      console.error("[subagents] Failed to spawn:", err);
      alert("Failed to spawn subagent: " + (err.message || "Unknown error"));
    } finally {
      if (modalSubmit) {
        modalSubmit.disabled = false;
      }
    }
  }

  // ── Init ──
  function init() {
    // Modal controls
    if (modalClose) {
      modalClose.addEventListener("click", closeModal);
    }
    if (modalCancel) {
      modalCancel.addEventListener("click", closeModal);
    }
    if (modalSubmit) {
      modalSubmit.addEventListener("click", spawnFromModal);
    }
    if (modalOverlay) {
      modalOverlay.addEventListener("click", (e) => {
        if (e.target === modalOverlay) {
          closeModal();
        }
      });
    }
    if (taskInput) {
      taskInput.addEventListener("keydown", (e) => {
        if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
          void spawnFromModal();
        }
      });
    }

    // Initial fetch + 5-sec polling cycle (matches pre-Stage-C cadence)
    void fetchSubagents();
    _pollInterval = setInterval(fetchSubagents, 5000);

    // Fetch on gateway connect / reconnect
    window.addEventListener("gateway:connected", fetchSubagents);
    window.addEventListener("gateway:hello", fetchSubagents);
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }

  // Public API — kept stable across the Stage C refactor.
  window.subagentsPanel = {
    refresh: fetchSubagents,
    open: openModal,
    getActive: () => [...subagents],
    presets: AGENT_PRESETS,
  };
})();
