// ── Command Menu ──────────────────────────────────────────────────────────────

const menuOverlay = document.getElementById("cmd-overlay");
const menuTrigger = document.getElementById("menu-trigger");
const menuBackdrop = document.getElementById("cmd-backdrop");

let menuIsOpen = false;

function openMenu() {
  menuIsOpen = true;
  menuOverlay.classList.add("open");
  menuOverlay.removeAttribute("aria-hidden");
  menuTrigger.classList.add("menu-open");
  menuTrigger.setAttribute("aria-expanded", "true");
  document.addEventListener("keydown", onMenuKey);
}

function closeMenu() {
  menuIsOpen = false;
  menuOverlay.classList.remove("open");
  menuOverlay.setAttribute("aria-hidden", "true");
  menuTrigger.classList.remove("menu-open");
  menuTrigger.setAttribute("aria-expanded", "false");
  document.removeEventListener("keydown", onMenuKey);
}

function toggleMenu() {
  if (menuIsOpen) {
    closeMenu();
  } else {
    openMenu();
  }
}

function onMenuKey(e) {
  if (e.key === "Escape") {
    closeMenu();
  }
}

// ── Trigger & backdrop ────────────────────────────────────────────────────────
menuTrigger.addEventListener("click", toggleMenu);
menuBackdrop.addEventListener("click", closeMenu);

// Keyboard shortcut: press M to open (when not focused on input)
document.addEventListener("keydown", (e) => {
  if (menuIsOpen) {
    return;
  }
  if (e.key === "m" || e.key === "M") {
    if (
      document.activeElement.tagName === "INPUT" ||
      document.activeElement.tagName === "TEXTAREA"
    ) {
      return;
    }
    e.preventDefault();
    openMenu();
  }
});

// ── Page Overlay (native in-app navigation) ───────────────────────────────────
// Use direct-child selectors to avoid matching duplicates inside chat messages
function getPageOverlay() {
  return document.querySelector("body > .page-overlay");
}
function _getPageBackBtn() {
  return document.querySelector("body > .page-overlay #page-back-btn");
}
function getPageTitle() {
  return document.querySelector("body > .page-overlay #page-overlay-title");
}
function getPagePopoutBtn() {
  return document.querySelector("body > .page-overlay #page-popout-btn");
}
function getPageFrame() {
  return document.querySelector("body > .page-overlay #page-overlay-frame");
}

let overlayIsOpen = false;

function openPageOverlay(name, standardUrl) {
  // Derive the proxy URL: strip 18789 origin, prefix with /standard, add ?embed=1
  // Also pass token + gatewayUrl via hash so the SPA auto-connects
  let proxyUrl;
  try {
    const parsed = new URL(standardUrl);
    proxyUrl = `/standard${parsed.pathname}${parsed.search ? parsed.search + "&embed=1" : "?embed=1"}`;
  } catch {
    proxyUrl = `/standard/?embed=1`;
  }
  // The SPA reads token and gatewayUrl from hash params → triggers auto-connect
  proxyUrl +=
    "#token=" +
    encodeURIComponent(window.__SYMI_EMBED_TOKEN || "") +
    "&gatewayUrl=" +
    encodeURIComponent("ws://127.0.0.1:3333");

  getPageTitle().textContent = name.toUpperCase();
  getPagePopoutBtn().href = standardUrl;
  getPageFrame().src = proxyUrl;

  overlayIsOpen = true;
  getPageOverlay().classList.add("open");
  getPageOverlay().setAttribute("aria-hidden", "false");
  document.addEventListener("keydown", onOverlayKey);
}

function closePageOverlay() {
  overlayIsOpen = false;
  // Clean up native settings panel if open
  if (window.closeNativeSettings) {
    window.closeNativeSettings();
  }
  getPageOverlay().classList.remove("open");
  getPageOverlay().setAttribute("aria-hidden", "true");
  // Restore iframe + popout button for next use
  getPageFrame().style.display = "";
  getPagePopoutBtn().style.display = "";
  // Delay clearing src so the close animation plays cleanly
  setTimeout(() => {
    if (!overlayIsOpen) {
      getPageFrame().src = "";
    }
  }, 300);
  document.removeEventListener("keydown", onOverlayKey);
}

function onOverlayKey(e) {
  if (e.key === "Escape") {
    closePageOverlay();
  }
}

document.querySelector("body > .page-overlay #page-back-btn")?.addEventListener("click", () => {
  // Go back to the menu instead of closing everything
  closePageOverlay();
  openMenu();
});

// ── Item routing ──────────────────────────────────────────────────────────────
// Page display names (mapped from the menu item text)
const PAGE_NAMES = {
  "/overview": "Overview",
  "/channels": "Channels",
  "/instances": "Instances",
  "/sessions": "Sessions",
  "/usage": "Usage",
  "/cron": "Cron Jobs",
  "/tasks": "Background Tasks",
  "/agents": "Agents",
  "/skills": "Skills",
  "/nodes": "Nodes",
  "/config": "Config",
  "/debug": "Debug",
  "/tools": "Agent Tools",
  "/logs": "Logs",
};

// All internal pages rendered natively (no iframe)
const NATIVE_PAGES = {
  "/overview": "overview",
  "/channels": "channels",
  "/instances": "instances",
  "/sessions": "sessions",
  "/usage": "usage",
  "/cron": "cron",
  "/tasks": "tasks",
  "/agents": "agents",
  "/skills": "skills",
  "/nodes": "nodes",
  "/config": "config",
  "/debug": "debug",
  "/tools": "tools",
  "/logs": "logs",
};

function openNativePage(pageName, pageKey) {
  if (window.closeNativeSettings) {
    window.closeNativeSettings();
  }
  getPageTitle().textContent = pageName.toUpperCase();
  getPagePopoutBtn().style.display = "none";
  getPageFrame().style.display = "none";
  overlayIsOpen = true;
  getPageOverlay().classList.add("open");
  getPageOverlay().setAttribute("aria-hidden", "false");
  document.addEventListener("keydown", onOverlayKey);
  if (window.openNativeSettings) {
    window.openNativeSettings(pageKey);
  }
}

document.querySelectorAll(".cmd-item[data-href]").forEach((item) => {
  item.addEventListener("click", (e) => {
    e.preventDefault();
    const href = item.dataset.href;

    if (href === "#chat") {
      closeMenu();
      if (window.closeNativeSettings) {
        window.closeNativeSettings();
      }
      closePageOverlay();
      return;
    }

    // Internal pages rendered natively
    if (href.includes("127.0.0.1:18789")) {
      let pathname = "/";
      try {
        pathname = new URL(href).pathname;
      } catch {}

      const pageKey = NATIVE_PAGES[pathname];
      if (pageKey) {
        const pageName = PAGE_NAMES[pathname] ?? "Page";
        closeMenu();
        openNativePage(pageName, pageKey);
        return;
      }
    }

    // External links open in new tab
    window.open(href, "_blank", "noopener");
    closeMenu();
  });
});

// Expose for external use (e.g., if other modules need to close the overlay)
window.openPageOverlay = openPageOverlay;
window.closePageOverlay = closePageOverlay;
