import PQueue from "p-queue";

let ports: chrome.runtime.Port[] = [];
const queue = new PQueue({ concurrency: 1 });

chrome.runtime.onConnect.addListener((port) => {
  ports.push(port);
  port.onDisconnect.addListener(() => {
    ports = ports.filter((p) => p !== port);
  });
});

(() => {
  const evtSource = new EventSource(
    `${import.meta.env.VITE_API_URL}/products/publist-stream`
  );

  evtSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log("New event:", data);
    queue.add(() => handlePublish(data, 30000));
  };

  evtSource.onerror = (err) => {
    console.error("EventSource failed:", err);
  };
})();

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function handlePublish(data: any, timeoutMs = 5 * 60 * 1000) {
  return new Promise<void>((resolve) => {
    chrome.tabs.create(
      { url: "https://www.facebook.com/marketplace/create/item", active: true },
      (tab) => {
        if (!tab?.id) return resolve();
        const tabId = tab.id;

        let resolved = false;
        const cleanup = () => {
          if (resolved) return;
          resolved = true;
          chrome.runtime.onConnect.removeListener(onConnectListener);
          chrome.tabs.onRemoved.removeListener(onTabClosed);
          clearTimeout(timeoutId);
          resolve();
        };

        const onConnectListener = (port: chrome.runtime.Port) => {
          if (port.sender?.tab?.id === tabId) {
            port.postMessage({ type: "publist-event", payload: data });
            chrome.runtime.onConnect.removeListener(onConnectListener);
          }
        };
        chrome.runtime.onConnect.addListener(onConnectListener);

        const onTabClosed = (closedTabId: number) => {
          if (closedTabId === tabId) {
            cleanup();
          }
        };
        chrome.tabs.onRemoved.addListener(onTabClosed);

        // Timeout tùy chỉnh
        const timeoutId = setTimeout(() => {
          console.warn(`Tab ${tabId} timeout (${timeoutMs}ms) - auto resolve`);
          if (tabId) chrome.tabs.remove(tabId);
          cleanup();
        }, timeoutMs);
      }
    );
  });
}

chrome.runtime.onMessage.addListener((message, sender) => {
  if (message.type === "close-tab") {
    const tabId = sender.tab?.id;
    if (tabId) chrome.tabs.remove(tabId);
  }
});
