chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log(request.action);
});

const viewData = () => {
  chrome.storage.local.get("userInfo", function (result) {
    if (chrome.runtime.lastError) {
      return;
    } else {
      console.table(result);
    }
  });
};

document.addEventListener("MyCustomEvent", async function (e) {
  console.log("MyCustomEvent received in MCE");
  const data = e.detail;
  chrome.storage.local.remove("userInfo", function () {
    const error = chrome?.runtime?.lastError;
    if (error) {
      console.error("Error removing item: ", error);
    } else {
      console.log("Item removed from local storage in MCE");
    }
  });

  chrome.storage.local.set({ userInfo: data }, () => {
    console.log("New data set in userInfo", data);
  });
});

document.addEventListener("isInstalled", async function (e) {
  const version = chrome.runtime.getManifest().version;
  const event = new CustomEvent("isInstalledResponse", {
    detail: { message: "installed", version },
  });
  document.dispatchEvent(event);
});

document.addEventListener("LogOut", async function (e) {
  chrome.storage.local.remove("userInfo", () => {
    var error = chrome.runtime.lastError;
    if (error) {
      console.error(error);
    } else {
      console.log("Item removed from local storage");
    }
  });
});

document.addEventListener("removeExtension", function () {
  chrome.runtime.sendMessage({ action: "removeExtension" });
});