// Background script/service worker: popup delegates actions through this bridge.

function withActiveTab(callback) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    if (!tabs || !tabs.length) {
      callback(null);
      return;
    }
    callback(tabs[0]);
  });
}

function injectContentScript(tabId, callback) {
  if (chrome.scripting && chrome.scripting.executeScript) {
    chrome.scripting.executeScript(
      {
        target: { tabId: tabId },
        files: ["content-script.js"]
      },
      function () {
        callback(true);
      }
    );
    return;
  }

  if (chrome.tabs && chrome.tabs.executeScript) {
    chrome.tabs.executeScript(tabId, { file: "content-script.js" }, function () {
      callback(true);
    });
    return;
  }

  callback(false);
}

function sendTabMessage(tabId, message, callback) {
  chrome.tabs.sendMessage(tabId, message, function (response) {
    if (chrome.runtime.lastError) {
      callback(null);
      return;
    }
    callback(response || null);
  });
}

function ensureContentScript(tabId, callback) {
  sendTabMessage(tabId, { type: "ping" }, function (response) {
    if (response && response.ok) {
      callback(true);
      return;
    }
    injectContentScript(tabId, function (ok) {
      callback(ok);
    });
  });
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (!request || request.type !== "popupAction") {
    return;
  }

  withActiveTab(function (tab) {
    if (!tab || typeof tab.id !== "number") {
      sendResponse({ ok: false, error: "No active tab" });
      return;
    }

    ensureContentScript(tab.id, function (ready) {
      if (!ready) {
        sendResponse({ ok: false, error: "Failed to inject content script" });
        return;
      }

      sendTabMessage(tab.id, { type: request.action }, function (response) {
        sendResponse(response || { ok: false, error: "No response from tab" });
      });
    });
  });

  return true;
});

