function clearChromeStorage() {
  chrome.storage.local.clear(function () {
    if (chrome.runtime.lastError) {
      console.error("Error clearing Chrome storage:", chrome.runtime.lastError);
    } else {
      chrome.storage.local.set({ logout: 1 }, () => {
      });
    }
  });
}

function clearDatabaseValues(dbName) {
  const openRequest = indexedDB.open(dbName);

  openRequest.onsuccess = function () {
    const db = openRequest.result;
    const transaction = db.transaction(db.objectStoreNames, "readwrite");

    for (const storeName of db.objectStoreNames) {
      const store = transaction.objectStore(storeName);
      const clearRequest = store.clear(); // Deletes all entries in the store

      clearRequest.onsuccess = function () {
      };

      clearRequest.onerror = function (e) {
        console.error(`Error deleting entries from ${storeName}:`, e);
      };
    }

    transaction.oncomplete = function () {
      cleanupAndRedirect();
    };

    transaction.onerror = function (e) {
      console.error("Error in transaction:", e);
    };
  };

  openRequest.onerror = function (e) {
    console.error("Error opening database:", e);
  };
}




function cleanupAndRedirect() {

  // Remove local storage items
  localStorage.removeItem("userDetail");
  localStorage.removeItem("todoDetail");

  // Clear additional user details in Chrome storage
  chrome.storage.local.set({ userDetailChrome: "" }, () => {
  });

  window.location.href = "../index.html";
}

async function callLogoutAPI() {
  try {
    const response = await fetch(
      "https://api.workstatus.io/api/v1/logout",
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("authToken")}`,
        },
      }
    );

    const result = await response.json();
    if (response.ok) {
    } else {
      console.error("Logout API failed:", result);
    }
  } catch (error) {
    console.error("Error calling Logout API:", error);
  }
}

async function logout() {

  // Call the logout API
  await callLogoutAPI();

  // Clear storage and close connections before clearing database values
  clearChromeStorage();
  clearDatabaseValues("wstracker_new_db");
}

// Periodically attempt logout
async function periodicLogoutCheck() {
  await logout();
}

// Run logout initially
// logout();

// Schedule periodic logout
const logoutInterval = setInterval(periodicLogoutCheck, 5000);
