import { APP_ORIGIN } from "./config.js";

const MENU_ID = "open-pdf-in-dash-sign";

function isPdfUrl(url = "") {
  try {
    const parsed = new URL(url);
    return parsed.protocol === "https:" && parsed.pathname.toLowerCase().endsWith(".pdf");
  } catch {
    return false;
  }
}

function createPdfContextMenu() {
  chrome.contextMenus.removeAll(() => {
    if (chrome.runtime.lastError) {
      console.error("Dash Sign could not reset context menus:", chrome.runtime.lastError.message);
      return;
    }
    chrome.contextMenus.create({
      id: MENU_ID,
      title: "Open PDF in Dash Sign",
      contexts: ["link"],
      targetUrlPatterns: ["https://*/*.pdf", "https://*/*.PDF"]
    }, () => {
      if (chrome.runtime.lastError) console.error("Dash Sign context menu failed:", chrome.runtime.lastError.message);
    });
  });
}

chrome.runtime.onInstalled.addListener(createPdfContextMenu);
chrome.runtime.onStartup.addListener(createPdfContextMenu);

chrome.runtime.onInstalled.addListener(() => {
  if (chrome.sidePanel?.setPanelBehavior) {
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch((error) => {
      console.error("Dash Sign could not configure the side panel:", error);
    });
  }
});

chrome.runtime.onStartup.addListener(() => {
  if (chrome.sidePanel?.setPanelBehavior) {
    chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch((error) => {
      console.error("Dash Sign could not configure the side panel:", error);
    });
  }
});

chrome.contextMenus.onClicked.addListener((info) => {
  if (info.menuItemId !== MENU_ID || !isPdfUrl(info.linkUrl)) return;

  const url = `${APP_ORIGIN}/extension/bridge#pdfUrl=${encodeURIComponent(info.linkUrl)}`;
  chrome.tabs.create({ url }, () => {
    if (chrome.runtime.lastError) console.error("Dash Sign could not open the handoff tab:", chrome.runtime.lastError.message);
  });
});
