// OrbitCosmo app window — the whole memory (search, sessions, graph) opens in an
// app-style popup window (no tab strip, no omnibox) instead of a browser
// tab. One instance: if it's already open we focus it (found by URL, so this
// survives service-worker restarts). Bounds persist in storage so the window
// comes back where you left it. One reason to change: how the window behaves.

const APP_URL = chrome.runtime.getURL("src/app.html");
const APP_BOUNDS_KEY = "orbit_appBounds";

export function openAppWindow(sendResponse) {
  chrome.tabs.query({ url: APP_URL }, (tabs) => {
    const existing = tabs && tabs[0];
    if (existing?.windowId != null) {
      chrome.windows.update(existing.windowId, { focused: true }, () =>
        sendResponse({ ok: !chrome.runtime.lastError }));
      return;
    }
    chrome.storage.local.get(APP_BOUNDS_KEY, (r) => {
      const b = r[APP_BOUNDS_KEY] || {};
      chrome.windows.create(
        {
          url: APP_URL,
          type: "popup",
          width: b.width || 1100,
          height: b.height || 720,
          ...(b.left != null && b.top != null ? { left: b.left, top: b.top } : {}),
        },
        () => sendResponse({ ok: true })
      );
    });
  });
}

// Remember where the app window sits (fires when a move/resize settles).
chrome.windows?.onBoundsChanged?.addListener((win) => {
  if (win?.id == null) return;
  chrome.tabs.query({ windowId: win.id, url: APP_URL }, (tabs) => {
    if (chrome.runtime.lastError || !tabs || !tabs.length) return;
    chrome.storage.local.set({
      [APP_BOUNDS_KEY]: { left: win.left, top: win.top, width: win.width, height: win.height },
    });
  });
});
