async function addLog(log, time) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("wstracker_new_db", 1);

    request.onsuccess = () => {
      const db = request.result;
      const transaction = db.transaction("logger", "readwrite");
      const store = transaction.objectStore("logger");

      const addRequest = store.add({ log, time });

      addRequest.onsuccess = () => resolve("Log added successfully");
      addRequest.onerror = (event) =>
        reject("Error adding log: " + event.target.error);
    };

    request.onerror = (event) =>
      reject("Error opening database: " + event.target.error);
  });
}

function json(url) {
  return fetch(url).then((res) => res.json());
}
$("#logout").show();
$("#startdefault").show();
$("#start").hide();
$("#stop").hide();

const getUserData = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("userDetailChrome", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.userDetailChrome || null); // Resolve with the data or null
      }
    });
  });
};

async function getAwsCredentials() {
  const userData = await getUserData();
  const sdToken = userData.sd_token;
  const orgId = userData.org_id;
  const userId = userData.user_id;
  const authorizationToken = userData.sd_token;
  const url = "https://api.workstatus.io/api/v1/data/key";
  const headers = {
    "Content-Type": "application/json",
    Authorization: `Bearer ${authorizationToken}`,
    SDToken: sdToken, // Replace with actual token
    OrgID: orgId, // Replace with actual org ID
    UserID: userId, // Replace with actual user ID
    bucket: "aws", // Replace with actual bucket
  };

  const body = JSON.stringify({
    org_id: orgId, // Replace with actual org ID
  });

  await addLog(
    "INFO- :: PAYLOAD :: https://api.workstatus.io/api/v1/data/key ",
    moment().format("YYYY-MM-DD HH:mm:ss")
  );

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: headers,
      body: body,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    await addLog(
      "INFO- :: RESPONSE :: https://api.workstatus.io/api/v1/data/key " + data,
      moment().format("YYYY-MM-DD HH:mm:ss")
    );
    chrome.storage.local.set({ config: data.response.data }, function () {
      if (chrome.runtime.lastError) {
        console.error("Error storing data:", chrome.runtime.lastError);
      } else {
      }
    });
  } catch (error) {
    await addLog(error, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.error("Error:", error);
  }
}

const syncTimerData = async () => {
  const postData = {
    date: moment().format("YYYY-MM-DD"),
    tracker: 0,
  };
  const retriveItem = JSON.parse(localStorage.getItem("userDetail"));
  const headers = {
    SDToken: retriveItem.sd_token,
    Authorization: `Bearer ${retriveItem.token}`,
    OrgID: retriveItem.org_id,
    "Content-Type": "application/json",
    UserID: retriveItem.id,
    deviceType: "Chrome_extension",
  };
  const syncUrl = "https://api.workstatus.io/api/v1/activity/syncTimer";

  try {
    const syncResponse = await fetch(syncUrl, {
      method: "POST",
      headers,
      body: JSON.stringify(postData),
    });

    const syncResult = await syncResponse.json();

    if (syncResult.response.code !== "200") {
    } else {
      await addLog(
        "INFO- :: RESPONSE= " + syncResult.response,
        moment().format("YYYY-MM-DD HH:mm:ss")
      );
      for (const item of syncResult.response.data) {
        let tmp = item.todoId == null ? 0 : item.todoId;
        await addSyncTimerData(item.timeLog, item.projectId, tmp);
      }
    }
  } catch (error) {
    await addLog(error, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.error("Error syncing timer:", error);
  }
};

async function updateStartTime(newStartTime) {
  return new Promise((resolve) => {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = () => {
      let db = idb.result;
      let tx = db.transaction("currentTimerData", "readwrite");
      let store = tx.objectStore("currentTimerData");
      let getRequest = store.openCursor();
      getRequest.onsuccess = (event) => {
        let cursor = event.target.result;
        if (cursor) {
          let record = cursor.value;
          record.startTime = newStartTime;
          let updateRequest = cursor.update(record);
          updateRequest.onsuccess = () => {
            resolve("Idle time updated successfully");
          };
          updateRequest.onerror = () => {
            resolve("Failed to update idle time");
          };
        } else {
          resolve("No data found to update");
        }
      };
      getRequest.onerror = () => {
        resolve("Failed to retrieve data");
      };
    };
    idb.onerror = () => {
      resolve("Database connection error");
    };
  });
}

async function setSelectedData() {
  try {
    let paramval = await getCurrentTimerData();
    if (paramval.length > 0) {
      document.getElementById("selectedProjecttop").innerHTML =
        paramval[0].projectName;
      document.getElementById("selectedProject").innerHTML =
        paramval[0].projectName;
      document.getElementById("project_id").value = paramval[0].projectId;

      const todoId = parseInt(paramval[0].todoId) || 0;
      if (todoId > 0) {
        document.getElementById("selectedTasktop").innerHTML =
          paramval[0].todoName;
        document.getElementById("selectedTask").innerHTML =
          paramval[0].todoName;
        document.getElementById("task_id").value = todoId; // use value, not innerHTML
      } else {
        document.getElementById("task_id").value = "0";
        // Optionally reset task labels if no task
        // document.getElementById("selectedTasktop").innerHTML = "";
        // document.getElementById("selectedTask").innerHTML = "Select Task";
      }
    }
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
}

setSelectedData();

var hours = 0;
var mins = 0;
var seconds = 0;

async function deleteAllSyncTimerData() {
  return new Promise((resolve) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SyncDataTimer", "readwrite");
        let store = tx.objectStore("SyncDataTimer");
        let clearRequest = store.clear(); // Clear all records

        clearRequest.onsuccess = () => {
          resolve(true); // Resolve with true if deletion is successful
        };

        clearRequest.onerror = () => {
          resolve(false); // Resolve with false on deletion error
        };
      };

      idb.onerror = () => {
        resolve(false); // Resolve with false on database connection error
      };
    } catch (err) {
      resolve(false); // Resolve with false on synchronous errors
    }
  });
}

async function getTotalSyncTimerData() {
  return new Promise((resolve) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SyncDataTimer", "readonly");
        let store = tx.objectStore("SyncDataTimer");
        let request = store.getAll(); // Get all records
        request.onsuccess = () => {
          const allData = request.result;
          // Calculate the sum of all timeLog values, checking that item is not null
          const totalTimeLog = allData.reduce((sum, item) => {
            if (item != null && item.timeLog != null) {
              return sum + (parseInt(item.timeLog) || 0); // Add timeLog if it exists, otherwise add 0
            }
            return sum; // If item is null or timeLog is null, don't add anything
          }, 0);

          resolve(parseInt(totalTimeLog)); // Return the total sum
        };

        request.onerror = () => {
          resolve(0); // Resolve with 0 on error
        };
      };

      idb.onerror = () => {
        resolve(0); // Resolve with 0 on database connection error
      };
    } catch (err) {
      resolve(0); // Resolve with 0 on synchronous errors
    }
  });
}

async function getSyncTimerData(projectId, todoId) {
  return new Promise((resolve) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SyncDataTimer", "readonly");
        let store = tx.objectStore("SyncDataTimer");
        let request = store.getAll(); // Get all records

        request.onsuccess = () => {
          const allData = request.result;
          // Find the first matching record
          const matchingData = allData.find(
            (item) =>
              item != null &&
              item.projectId == projectId &&
              item.todoId == todoId
          );

          if (matchingData) {
            resolve(matchingData.timeLog); // Return timeLog if match is found
          } else {
            resolve(0); // Return 0 if no match
          }
        };

        request.onerror = () => {
          resolve(0); // Resolve with 0 on error
        };
      };

      idb.onerror = () => {
        resolve(0); // Resolve with 0 on database connection error
      };
    } catch (err) {
      resolve(0); // Resolve with 0 on synchronous errors
    }
  });
}

async function updateSyncTimerData(projectId, todoId, newTimeLog) {
  return new Promise((resolve, reject) => {
    try {
      projectId = parseInt(projectId);
      todoId = parseInt(todoId);
      newTimeLog = parseInt(newTimeLog);

      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SyncDataTimer", "readwrite");
        let store = tx.objectStore("SyncDataTimer");
        let request = store.getAll();

        request.onsuccess = () => {
          const allData = request.result;
          let matchingData = null;
          let matchingKey = null;
          // Loop through the data to find a match
          for (let key in allData) {
            let item = allData[key];
            if (
              item != null &&
              item.projectId === projectId &&
              item.todoId === todoId
            ) {
              matchingData = item;
              matchingKey = parseInt(key);
              break;
            }
          }

          if (matchingData) {
            // Update existing record
            matchingData.timeLog = newTimeLog;
            const updateRequest = store.put(matchingData, matchingKey + 1);
            updateRequest.onsuccess = () => {
              resolve("TimeLog updated successfully");
            };

            updateRequest.onerror = () => {
              reject("Failed to update TimeLog");
            };
          } else {
            // If no match, create a new record
            const newData = { projectId, todoId, timeLog: newTimeLog };
            const addRequest = store.add(newData);

            addRequest.onsuccess = () => {
              resolve("TimeLog added successfully");
            };

            addRequest.onerror = () => {
              reject("Failed to add new TimeLog");
            };
          }
        };

        request.onerror = () => {
          reject("Failed to fetch data");
        };
      };

      idb.onerror = () => {
        reject("Database connection error");
      };
    } catch (err) {
      reject("Error occurred");
    }
  });
}

async function addCurrentTimerData(
  projectId,
  projectName,
  todoId,
  todoName,
  startTime
) {
  return new Promise((resolve) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onupgradeneeded = () => {
        let db = idb.result;

        // Create object store if it doesn't exist
        if (!db.objectStoreNames.contains("currentTimerData")) {
          db.createObjectStore("currentTimerData", {
            keyPath: "id",
            autoIncrement: true,
          });
        }
      };

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("currentTimerData", "readwrite");
        let store = tx.objectStore("currentTimerData");

        const data = {
          projectId: projectId,
          projectName: projectName,
          todoId: todoId,
          todoName: todoName,
          startTime: startTime,
          idleTime: 0,
        };

        let request = store.add(data);

        request.onsuccess = () => {
          resolve("Data stored successfully");
        };

        request.onerror = () => {
          resolve("Failed to store data");
        };
      };

      idb.onerror = () => {
        resolve("Database connection error");
      };
    } catch (err) {
      resolve("Error occurred");
    }
  });
}

async function updateIdleTime(newIdleTime) {
  return new Promise((resolve) => {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = () => {
      let db = idb.result;
      let tx = db.transaction("currentTimerData", "readwrite");
      let store = tx.objectStore("currentTimerData");
      let getRequest = store.openCursor();
      getRequest.onsuccess = (event) => {
        let cursor = event.target.result;
        if (cursor) {
          let record = cursor.value;
          record.idleTime =
            (parseInt(record.idleTime) || 0) + (parseInt(newIdleTime) || 0);
          let updateRequest = cursor.update(record);
          updateRequest.onsuccess = () => {
            resolve("Idle time updated successfully");
          };
          updateRequest.onerror = () => {
            resolve("Failed to update idle time");
          };
        } else {
          resolve("No data found to update");
        }
      };
      getRequest.onerror = () => {
        resolve("Failed to retrieve data");
      };
    };
    idb.onerror = () => {
      resolve("Database connection error");
    };
  });
}

const getIfTimerStart = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("timerstate", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.timerstate || 0); // Resolve with the data or null
      }
    });
  });
};

const getIdleTimeSec = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("idleTimeSec", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.idleTimeSec || 0); // Resolve with the data or null
      }
    });
  });
};

$("#stop").hide();
$("#start").click(function () {
  chrome.storage.local.set({ isIdle: false });
  chrome.storage.local.set({ isIdleSub: 0 });
  //   "999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"
  // );

  chrome.runtime.sendMessage({ action: "triggerFunction" });

  //////////////////////// project js code /////////////////////////
  chrome.storage.local.get(["time_zone"]).then((time_zoneresult) => {
    json(
      endpointUrl + `getCurrentTime?timezone=${time_zoneresult.time_zone}`
    ).then(async (timerdata) => {
      //   "ServerSavedTIme" + moment(timerdata.response.time).format("YYYY-MM-DD")
      // );
      if (timerdata.response.code == 200) {
        if (
          moment(new Date()).format("YYYY-MM-DD") !=
          moment(timerdata.response.time).format("YYYY-MM-DD")
        ) {
          setTimeout(() => {
            $("#start").hide();
            $("#logout").show();
            $(".selection-dropdown-box").css("pointer-events", "");
          }, 1000);
          // chrome.runtime.reload();
        } else {
          var projectid = $("#project_id").val();
          var taskid = $("#task_id").val();
          var pname = $("#selectedProjecttop").text();
          var taskname = $("#selectedTasktop").text();

          if (parseInt(projectid) > 0) {
            if (projectid) {
              chrome.storage.local.set({ ProjectID: projectid });
              chrome.storage.local.set({ TaskID: taskid });
              //////////////////////////////////
              let idb = indexedDB.open("wstracker_new_db");
              idb.onsuccess = () => {
                let res = idb.result;
                let tx = res.transaction("screenshot_interval", "readonly");
                let store = tx.objectStore("screenshot_interval");
                let cursor = store.openCursor();
                cursor.onsuccess = () => {
                  let curRes = cursor.result;

                  if (curRes) {
                    //   "---------------curr result prev--------------"
                    // );
                    if (curRes.value) {
                      //   "----------------CURR rEsult h ye -----------------"
                      // );
                    } else {
                      curRes.continue();
                    }
                  }
                };
              };
            }
          }

          $(".selection-dropdown-box").css("pointer-events", "none");
          $(".selection-dropdown-box").css("opacity", "0.4");

          // let lasval = $("#tt").val();
          let lasval = await getSyncTimerData(projectid, taskid);
          chrome.storage.local.set({ timerstate: 1 });

          // await syncTimerData()
          let startTime = moment().format("YYYY-MM-DD HH:mm:ss");
          await addCurrentTimerData(
            projectid,
            pname,
            taskid,
            taskname,
            startTime
          );

          $("#logout").hide();
          $("#start").hide();
          $("#stop").show();
          chrome.storage.local.set({ nhikrna: 0 });
          chrome.storage.local.set({ idleFromPrev: 0 });

          chrome.storage.local.set({ currentRunningProjectid: projectid });
          chrome.storage.local.set({ currentRunningTaskid: taskid });
          setTimeout(async () => {
            await startTimer(projectid, taskid);
          }, 100);
          await getAwsCredentials();
        }
      }
    });
  });
});


const getBreakStatus = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("breakStatusForStop", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.breakStatusForStop || null); // Resolve with the data or null
      }
    });
  });
};


$("#stop").click(function (er) {
  chrome.runtime.sendMessage({ action: "stopInterval" });
  stopTimerNow();
});

async function stopTimerNow() {
  chrome.storage.local.set({ timerstate: 0 });

  try {
    $(".loader").show();

    let localTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
    if (localTimezone === "Asia/Calcutta") {
      localTimezone = "Asia/Kolkata";
    }

    const timerdata = await json(
      endpointUrl + `getCurrentTime?timezone=${localTimezone}`
    );

    if (timerdata.response.code == 200) {
      clearTimeout(timerrID);
      clearTimeout(timerrID2);
      let currentdata = await getCurrentTimerData();
      let lastval = await getSyncTimerData(
        currentdata[0].projectId,
        currentdata[0].todoId
      );
      let startTime = moment(currentdata[0].startTime);
      let currentTime = moment();
      let timeDiff = currentTime.diff(startTime, "second");
      let reduceTime = currentdata[0].idleTime;
      let tsec = parseInt(timeDiff) + parseInt(lastval) - parseInt(reduceTime);

      // let pID=pareseInt(currentdata[0].projectId)
      // let tID=parseInt(currentdata[0].todoId)
      // tsec=parseInt(tsec)
      await updateSyncTimerData(
        currentdata[0].projectId,
        currentdata[0].todoId,
        tsec
      );

  
      let val=await getBreakStatus();
      debugger;
      console.log("Break status on stop:", val);
      if( val==null || val=="stop"){
        await deleteCurrentTimerData();
      }
      
      await deleteAllSyncTimerData();
      // await syncTimerData();

    

      setTimeout(() => {
        $("#start").show();
        $("#logout").show();
        $(".selection-dropdown-box").css("pointer-events", "");
        window.location.href = "projectList.html";
        $("")
        //window.location.href=chrome.runtime.getURL("html/projectList.html")
        //Display()
      }, 2000);
    } else {
      $("#perror").html("<b style='color:red'>Please connect to internet</b>");
    }
  } catch (e) {
    $("#perror").html("<b style='color:red'>Please connect to internet</b>");
  }
}

async function getCurrentTimerData() {
  return new Promise((resolve, reject) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onupgradeneeded = () => {
        let db = idb.result;
        // Create object store if it doesn't exist
        if (!db.objectStoreNames.contains("currentTimerData")) {
          db.createObjectStore("currentTimerData", {
            keyPath: "id",
            autoIncrement: true,
          });
        }
      };

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("currentTimerData", "readonly");
        let store = tx.objectStore("currentTimerData");

        let request = store.getAll();

        request.onsuccess = () => {
          resolve(request.result);
        };

        request.onerror = () => {
          reject("Failed to fetch data");
        };
      };

      idb.onerror = () => {
        reject("Database connection error");
      };
    } catch (err) {
      reject("Error occurred");
    }
  });
}

async function updateTodayDateTime(newTime) {
  return new Promise((resolve) => {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = () => {
      let db = idb.result;
      let tx = db.transaction("todayStartTime", "readwrite");
      let store = tx.objectStore("todayStartTime");
      let getRequest = store.openCursor();
      getRequest.onsuccess = (event) => {
        let cursor = event.target.result;
        if (cursor) {
          let record = cursor.value;
          record.time = newTime;
          let updateRequest = cursor.update(record);
          updateRequest.onsuccess = () => {
            resolve("Idle time updated successfully");
          };
          updateRequest.onerror = () => {
            resolve("Failed to update idle time");
          };
        } else {
          resolve("No data found to update");
        }
      };
      getRequest.onerror = () => {
        resolve("Failed to retrieve data");
      };
    };
    idb.onerror = () => {
      resolve("Database connection error");
    };
  });
}

async function getTodayDateTime() {
  return new Promise((resolve, reject) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onupgradeneeded = () => {
        let db = idb.result;
        // Create object store if it doesn't exist
        if (!db.objectStoreNames.contains("todayStartTime")) {
          db.createObjectStore("todayStartTime", {
            keyPath: "id",
            autoIncrement: true,
          });
        }
      };

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("todayStartTime", "readonly");
        let store = tx.objectStore("todayStartTime");

        let request = store.getAll();

        request.onsuccess = () => {
          resolve(request.result);
        };

        request.onerror = () => {
          reject("Failed to fetch data");
        };
      };

      idb.onerror = () => {
        reject("Database connection error");
      };
    } catch (err) {
      reject("Error occurred");
    }
  });
}

async function deleteCurrentTimerData(id) {
  return new Promise((resolve, reject) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("currentTimerData", "readwrite");
        let store = tx.objectStore("currentTimerData");

        // If id is provided, delete specific entry, otherwise clear all entries
        let request = id ? store.delete(id) : store.clear();

        request.onsuccess = () => {
          resolve("Data deleted successfully");
        };

        request.onerror = () => {
          reject("Failed to delete data");
        };
      };

      idb.onerror = () => {
        reject("Database connection error");
      };
    } catch (err) {
      reject("Error occurred");
    }
  });
}

let timerrID = null;
let timerrID2 = null;

async function startTimer(projectid, taskid) {
  try {
    let lastval = await getSyncTimerData(projectid, taskid);
    var startTimestamp = moment().startOf("day").add(lastval, "s");
    startWorkTodayTimer();
    timerrID = setInterval(function () {
      document.getElementById("timer").innerHTML =
        startTimestamp.format("HH:mm:ss");
      startTimestamp.add(1, "second");
      lastval++;
    }, 1000);
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
}

async function timeStartt() {
  try {
    let timerflag = await getIfTimerStart();
    if (timerflag == 1) {
      startWorkTodayTimer();
      $(".selection-dropdown-box").css("pointer-events", "none");
      $(".selection-dropdown-box").css("opacity", "0.4");
      $("#logout").hide();
      $("#startdefault").hide();
      $("#start").hide();
      $("#stop").show();

      let currentData = await getCurrentTimerData();
      if (currentData != null) {
        let lastval = await getSyncTimerData(
          currentData[0].projectId,
          currentData[0].todoId
        );
        let startTime = moment(currentData[0].startTime);
        let currentTime = moment();
        let timeDiff = currentTime.diff(startTime, "second");

        // let reduceTime = await getIdleTimeSec();
        let reduceTime = currentData[0].idleTime;
        let tsec =
          parseInt(timeDiff) + parseInt(lastval) - parseInt(reduceTime);
        var startTimestamp = moment().startOf("day").add(tsec, "s");
        timerrID = setInterval(function () {
          document.getElementById("timer").innerHTML =
            startTimestamp.format("HH:mm:ss");
          startTimestamp.add(1, "second");
        }, 1000);
      }
    }
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
}

timeStartt();

async function startWorkTodayTimer() {
  try {
    let alltime = await getTotalSyncTimerData();
    let currentData = await getCurrentTimerData();
    if (currentData != null) {
      let startTime = moment(currentData[0].startTime);
      let currentTime = moment();
      let timeDiff = currentTime.diff(startTime, "second");

      let reduceTime = currentData[0].idleTime;
      let tsec = parseInt(timeDiff) + parseInt(alltime) - parseInt(reduceTime);
      var startTimestamp = moment().startOf("day").add(tsec, "s");
      timerrID2 = setInterval(function () {
        document.getElementById("timerData").innerHTML =
          startTimestamp.format("HH:mm:ss");
        startTimestamp.add(1, "second");
      }, 1000);
    }
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
}

async function setTotalTime() {
  try {
    console.log("setTotalTime called");
    const totalTime = await getTotalSyncTimerData();
    if (totalTime) {
      var startTimestamp = moment().startOf("day").add(totalTime, "s");
      document.getElementById("timerData").innerHTML =
        startTimestamp.format("HH:mm:ss");
    }
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.log(err);
  }
}

setTotalTime();

// setTimeout(() => {
//   $(".loader").hide();
// }, 3000);

function notifyBackground() {
  chrome.runtime.sendMessage(
    { action: "executeFunction" }, // Message payload
    (response) => {
      if (chrome.runtime.lastError) {
        console.error("Error sending message:", chrome.runtime.lastError);
      } else {
      }
    }
  );
}

$("#syncNow").click(async function () {
  $("#image").toggleClass("flip");
  notifyBackground();

  let last_synced = moment().format("YYYY-MM-DD HH:mm:ss");
  await chrome.storage.local.set({ last_synced });

  setTimeout(async () => {
    let last_syncedres = await chrome.storage.local.get(["last_synced"]);
    if (last_syncedres.hasOwnProperty("last_synced")) {
      $("#last_synced")
        .show()
        .html("Updated at: " + last_syncedres.last_synced);
    }
  }, 4000);
});

chrome.storage.local.get(["last_synced"]).then((last_syncedres) => {
  if (last_syncedres.hasOwnProperty("last_synced")) {
    $("#last_synced").show();
    $("#last_synced").html("Updated at: " + last_syncedres.last_synced);
  }
});

setInterval(() => {
  chrome.storage.local.get(["isIdle"]).then((res) => {
    if (res.isIdle == true) {
      $("#idleid").html("<b style='color:red'>You were Idle</b>");
      //   "stoppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp"
      // );

      chrome.runtime.sendMessage({ action: "stopInterval" });
      stopTimerNow();
      chrome.storage.local.set({ isIdle: false });
    }
  });
}, 2000);

// const getPopupStatus = async () => {
//   return new Promise((resolve, reject) => {
//     chrome.storage.local.get("idlepopup", (result) => {
//       if (chrome.runtime.lastError) {
//         reject(chrome.runtime.lastError); // Reject if there's an error
//       } else {
//         resolve(result.idlepopup || 0); // Resolve with the data or null
//       }
//     });
//   });
// };

//------------------------------------->>
async function checkChanageDate() {
  try {
    let currentData = await getTodayDateTime();
    if (currentData.length > 0) {
      let startDate = moment(currentData[0].time).format("YYYY-MM-DD");
      let todayDate = moment().format("YYYY-MM-DD");
      if (startDate != todayDate) {
        // debugger;
        chrome.storage.local.set({ isBreakTimeExceeded: false });
        let newStartTime = moment()
          .startOf("day")
          .format("YYYY-MM-DD HH:mm:ss");
        await updateStartTime(newStartTime);
        await updateTodayDateTime(newStartTime);
        await deleteAllSyncTimerData();
        await syncTimerData();
        let isIdlePopup = await getPopupStatus();
        if (isIdlePopup == 1) {
          chrome.storage.local.set({ idleFromPrev: 1 });
        }
        await getAwsCredentials();
      }
    }
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
}

const isUserBack = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("isStoppedFromBreak", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.isStoppedFromBreak || null); // Resolve with the data or null
      }
    });
  });
};

const getProjectIdForBreak = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("currentRunningProjectid", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.currentRunningProjectid || null); // Resolve with the data or null
      }
    });
  });
};

const getTaskIdForBreak = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("currentRunningTaskid", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.currentRunningTaskid || null); // Resolve with the data or null
      }
    });
  });
};

// currentRunningTaskid

// async function autoSelectProjectAndTask(pid, tid) {
//   $(".projectDropdown li[data-id='" + pid + "']").trigger("click");
//   if (tid != "0" || tid != 0 || tid != "" || tid != null) {
//     setTimeout(() => {
//       $(".taskDropdown li[data-id='" + tid + "']").trigger("click");
//     }, 200);
//   }
// }

function isUserBackFromBreak() {
  //  chrome.storage.local.set({ isStoppedFromBreak: true });
  setInterval(async () => {
    let val = await isUserBack();
    if (val == true) {
      chrome.storage.local.set({ isStoppedFromBreak: false });
      chrome.storage.local.set({ breakstarted: false });
      let projectid = await getProjectIdForBreak();
      let taskid = await getTaskIdForBreak();
      chrome.storage.local.set({ isIdle: false });
      chrome.storage.local.set({ isIdleSub: 0 });
      // setTimeout(() => {
      //   // $("#start").hide();
      //   $("#logout").show();
      //   $(".selection-dropdown-box").css("pointer-events", "");
      // }, 1000);
      // await autoSelectProjectAndTask(projectid, taskid);
      var pname = $("#selectedProjecttop").text();
      var taskname = $("#selectedTasktop").text();
      chrome.runtime.sendMessage({ action: "triggerFunction" });
      $(".selection-dropdown-box").css("pointer-events", "none");
      $(".selection-dropdown-box").css("opacity", "0.4");

      // let lasval = $("#tt").val();
      let lasval = await getSyncTimerData(projectid, taskid);
      chrome.storage.local.set({ timerstate: 1 });

      // await syncTimerData()
      let startTime = moment().format("YYYY-MM-DD HH:mm:ss");
      // debugger;
      await deleteCurrentTimerData();
      await deleteAllSyncTimerData();
      await syncTimerData();
      // debugger;
      await addCurrentTimerData(projectid, pname, taskid, taskname, startTime);

      chrome.storage.local.set({ nhikrna: 0 });
      chrome.storage.local.set({ idleFromPrev: 0 });

      await startTimer(projectid, taskid);
      $("#logout").hide();
      $("#start").hide();
      $("#startdefault").hide();
      $("#stop").show();
    }
  }, 2000);
}

checkChanageDate();
//------------------------------------->>
isUserBackFromBreak();

// Message listener to handle setTotalTime action from background.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "setTotalTime") {
    setTotalTime();
    // $("#start").show();
    sendResponse({ status: "setTotalTime called successfully" });
  } else if (request.action === "breakTimeExceeded") {
    document.getElementById("breakcompleted").style.display = "block";
    chrome.storage.local.set({ isBreakTimeExceeded3: true });
    sendResponse({ status: "breakTimeExceeded message received successfully" });
  }
});

//  chrome.storage.local.set({ isBreakTimeExceeded: true });

const ShowPopupOrNot = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("isBreakTimeExceeded", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.isBreakTimeExceeded || null); // Resolve with the data or null
      }
    });
  });
};

const showExceededPopupOrNot = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("isBreakTimeExceeded3", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.isBreakTimeExceeded3 || null); // Resolve with the data or null
      }
    });
  });
};





$("#breakcompletedbtn").click(async function () {
  chrome.storage.local.set({ isBreakTimeExceeded3: false })
   document.getElementById("breakcompleted").style.display = "none";
});


$("#breakbtn").click(async function () {
  chrome.storage.local.set({ isBreakTimeExceeded: false });
});


setInterval(async () => {
  let value = await ShowPopupOrNot();
  if (value == true) {
    document.getElementById("breakdiv").style.display = "block";
    // chrome.storage.local.set({ isBreakTimeExceeded: false });
  } else {
    document.getElementById("breakdiv").style.display = "none";
  }
}, 1000);

setInterval(async () => {
  let value = await showExceededPopupOrNot();
  if (value == true) {
    // chrome.storage.local.set({ isBreakTimeExceeded3: false });
    document.getElementById("breakcompleted").style.display = "block";
    // chrome.storage.local.set({ isBreakTimeExceeded: false });
  } else {
    document.getElementById("breakcompleted").style.display = "none";
  }
}, 1000);
