document.addEventListener("DOMContentLoaded", () => {
  const featureA = document.getElementById("featureA");
  // Load saved state
  chrome.storage.local.get(["featureA"], (data) => {
    featureA.checked = data.featureA || false;
  });

  featureA.addEventListener("change", () => {
    chrome.storage.local.set({ featureA: featureA.checked });
    notifyContentScript();
  });
});

function notifyContentScript() {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        const currentTabUrl = tabs[0].url;

        // Check if the current tab is a web page (not a chrome:// URL)
        if (!currentTabUrl.startsWith("chrome://")) {
          chrome.scripting.executeScript({
            target: { tabId: tabs[0].id },
            func: (isEnabled) => {
              window.postMessage({ type: "TOGGLE_FRONTEND", isEnabled }, "*");
            },
            args: [featureA.checked]
          });
        } else {
          console.log(
            "Cannot execute content script on a privileged Chrome URL"
          );
        }
      });
    }
  });
}