// ── Symframe Mode Chips ─────────────────────────────────────────────
// Stage D of the Dynamic Glass Panel arc — see ~/Documents/dynamic-glass-panel.md §5 Stage D.
//
// Wires the four mode chips in the symframe header to
// window.symframe.setMode() and updates the AUTO pill visibility +
// active-chip indicator in response to mode changes (from either the
// user clicking a chip OR the agent calling setMode via display_artifact).
//
// Mode-vs-user resolution:
//   - User click → setMode(mode, { user: true })
//                → modeState.userOverride = true
//                → AUTO pill becomes visible
//                → Agent setMode calls are stored as pendingAgent
//                  but NOT applied to the DOM
//   - AUTO click → clearUserOverride()
//                → userOverride = false, pendingAgent is applied
//                → AUTO pill hides
// ─────────────────────────────────────────────────────────────────────

"use strict";

(function () {
  const modesContainer = document.getElementById("symframe-modes");
  const autoPill = document.getElementById("mode-auto");
  if (!modesContainer || typeof window.symframe?.setMode !== "function") {
    return;
  }

  const chips = modesContainer.querySelectorAll(".mode-chip");

  function syncChips(state) {
    for (const chip of chips) {
      const mode = chip.getAttribute("data-mode");
      const active = mode === state.current;
      chip.classList.toggle("active", active);
      chip.setAttribute("aria-selected", active ? "true" : "false");
    }
    if (autoPill) {
      autoPill.hidden = !state.userOverride;
    }
  }

  // Initial sync from current mode state
  syncChips(window.symframe.getMode());

  // Listen for future mode changes (agent OR user)
  window.symframe.onModeChange(syncChips);

  // Wire chip clicks → user-initiated setMode
  for (const chip of chips) {
    chip.addEventListener("click", () => {
      const mode = chip.getAttribute("data-mode");
      if (mode) {
        window.symframe.setMode(mode, { user: true });
      }
    });
  }

  // AUTO pill → release the override
  if (autoPill) {
    autoPill.addEventListener("click", () => {
      window.symframe.clearUserOverride();
    });
  }
})();
