// Warthog browser node — service worker helpers.
// Default: toolbar icon opens the browser side panel (stays open while browsing).
// Optional: full tab for a larger dashboard. Don't run the node in two surfaces at once.
let dashboardTabId = null;

async function enableSidePanelOnAction() {
  try {
    await chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  } catch (e) {
    console.warn('[wart] setPanelBehavior failed', e);
  }
  try {
    await chrome.sidePanel.setOptions({
      path: 'sidepanel.html',
      enabled: true,
    });
  } catch (e) {
    console.warn('[wart] setOptions failed', e);
  }
}

chrome.runtime.onInstalled.addListener(() => {
  enableSidePanelOnAction();
});
chrome.runtime.onStartup.addListener(() => {
  enableSidePanelOnAction();
});
// Also on SW wake
enableSidePanelOnAction();

async function openFullDashboard() {
  const url = chrome.runtime.getURL('node.html');
  if (dashboardTabId != null) {
    try {
      const tab = await chrome.tabs.get(dashboardTabId);
      if (tab && tab.id != null) {
        await chrome.tabs.update(tab.id, { active: true });
        if (tab.windowId != null) {
          await chrome.windows.update(tab.windowId, { focused: true });
        }
        return;
      }
    } catch {
      dashboardTabId = null;
    }
  }
  const created = await chrome.tabs.create({ url });
  dashboardTabId = created.id ?? null;
}

async function openSidePanel(sender) {
  // Prefer the window that asked; fall back to current window.
  let windowId = sender?.tab?.windowId;
  if (windowId == null) {
    const win = await chrome.windows.getCurrent();
    windowId = win?.id;
  }
  if (windowId == null) {
    throw new Error('No windowId for side panel');
  }
  await chrome.sidePanel.open({ windowId });
}

chrome.tabs.onRemoved.addListener((tabId) => {
  if (tabId === dashboardTabId) dashboardTabId = null;
});

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg && msg.type === 'wart-open-full-tab') {
    openFullDashboard()
      .then(() => sendResponse({ ok: true }))
      .catch((e) => {
        console.error('[wart]', e);
        sendResponse({ ok: false, error: String(e && e.message ? e.message : e) });
      });
    return true;
  }
  if (msg && msg.type === 'wart-open-side-panel') {
    openSidePanel(sender)
      .then(() => sendResponse({ ok: true }))
      .catch((e) => {
        console.error('[wart]', e);
        sendResponse({ ok: false, error: String(e && e.message ? e.message : e) });
      });
    return true;
  }
  return false;
});
