// chrome.storage.local.get(["time_changed"]).then((timechangedresult) => {
//   if(timechangedresult.time_changed == 1){
//     window.location.href = "error.html";
//   }
// });
let retriveItem = JSON.parse(localStorage.getItem("userDetail"));
$("#profile").html(
  "Logged in as " + retriveItem.name + "<br>" + retriveItem.email
);

function json(url) {
  return fetch(url).then((res) => res.json());
}


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

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

      const time=moment().format("YYYY-MM-DD HH:mm:ss")

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

      addRequest.onsuccess = () => resolve("Added Today Start Time successfully");
      addRequest.onerror = (event) =>
        reject("Error adding todayStartTime: " + event.target.error);
    };
    request.onerror = (event) =>
      reject("Error opening database: " + event.target.error);
  });
}

async function addSyncTimerData(timeLog, projectId, todoId) {
  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("SyncDataTimer")) {
          db.createObjectStore("SyncDataTimer", {
            keyPath: "id",
            autoIncrement: true,
          });
        }
      };

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SyncDataTimer", "readwrite");
        let store = tx.objectStore("SyncDataTimer");
        const data = {
          timeLog: timeLog,
          projectId: projectId,
          todoId: todoId,
        };

        store.add(data); // Add data without expecting any ID in return

        tx.oncomplete = () => {
          resolve("Data stored successfully"); // Just resolve success message
        };

        tx.onerror = () => {
          reject(tx.error); // Reject on error
        };
      };

      idb.onerror = () => {
        reject(idb.error); // Handle database connection error
      };
    } catch (err) {
      reject(err); // Handle synchronous errors
    }
  });
}

// async function storeTaskData(pid, data) {
//   return new Promise((resolve) => {
//     let idb = indexedDB.open("wstracker_new_db", 1);

//     idb.onupgradeneeded = () => {
//       let db = idb.result;
//       if (!db.objectStoreNames.contains("taskStore")) {
//         db.createObjectStore("taskStore", {
//           keyPath: "id",
//           autoIncrement: true,
//         });
//       }
//     };

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

//       let request = store.put({ p_id: pid, data: data ?? null });

//       request.onsuccess = () => resolve("Data stored successfully");
//       request.onerror = () => resolve("Failed to store data");
//     };

//     idb.onerror = () => resolve("Database connection error");
//   });
// }

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

    idb.onupgradeneeded = () => {
      let db = idb.result;
      if (!db.objectStoreNames.contains("taskStore")) {
        db.createObjectStore("taskStore", { keyPath: "p_id" });
      }
    };

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

      let getRequest = store.get(pid);

      getRequest.onsuccess = () => {
        let existingData = getRequest.result;
        let newData = existingData
          ? { ...existingData, data }
          : { p_id: pid, data };
        let request = store.put(newData);
        request.onsuccess = () => resolve("Data stored/updated successfully");
        request.onerror = () => resolve("Failed to store/update data");
      };
      getRequest.onerror = () => resolve("Error retrieving existing data");
    };
    idb.onerror = () => resolve("Database connection error");
  });
}

async function setTaskData(pid) {
  // debugger
  return new Promise((resolve) => {
    let idb = indexedDB.open("wstracker_new_db", 1);

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

      getRequest.onsuccess = () => {
        let curRes = getRequest.result;
        let options = "";

        if (curRes) {
          // Find the object with the matching p_id
          let taskObj = curRes.find(
            (item) => item != null && parseInt(item.p_id) === parseInt(pid)
          );

          if (taskObj && Array.isArray(taskObj.data)) {
            taskObj.data.forEach((item) => {
              options += `<li data-id="${item.id}">${item.name}</li>`;
            });
          }
        }

        $("#todolist").html(options);
        $(".loader").hide();
      };

      getRequest.onerror = () => $("#todolist").html("");
    };

    idb.onerror = () => $("#todolist").html("");
  });
}

async function setUserdata(tbl, value, version) {
  try {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = async () => {
      let res = idb.result;
      let tx = res.transaction(tbl, "readwrite");
      let store = tx.objectStore(tbl);
      const lastinsertdata = store.put(value);
      res.close();
      setTimeout(() => {
        return lastinsertdata.result;
      }, 100);
    };
  } catch (err) {
    return false;
  }
}

async function getProjectList() {
  const url = "https://api.workstatus.io/api/v1/project/list";
  const retriveItem = JSON.parse(localStorage.getItem("userDetail"));
  const data = {
    organization_id: retriveItem.org_id,
    keyword: "",
  };

  const headers = {
    SDToken: retriveItem.sd_token,
    Authorization: `Bearer ${retriveItem.token}`,
    OrgID: retriveItem.org_id,
    "Content-Type": "application/json",
    UserID: retriveItem.id,
    deviceType: "Chrome_extension",
  };

  try {
    const projectResponse = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(data),
    });

    const projectResult = await projectResponse.json();
    if (projectResult.response.code !== "200") {
      $("#error").html(
        `<b style='color:red'>${projectResult.response.message}</b>`
      );
    } else {
      $("#error").html(
        `<b style='color:green'>${projectResult.response.message}</b>`
      );
      projectResult.response.data.forEach((item) => {
        setUserdata("project_list", item, 2);
        // getTodos(item.id);
      });
    }
  } catch (error) {
    await addLog("Error - API: https://api.workstatus.io/api/v1/project/list  " + error, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.error("Error fetching project list:", error);
  }


  // Sync Timer Section
  const postData = {
    date: moment().format("YYYY-MM-DD"),
    tracker: 0,
  };

  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 {
      for (const item of syncResult.response.data) {
        let tmp = item.todoId == null ? 0 : item.todoId;
        await addSyncTimerData(item.timeLog, item.projectId, tmp);
        await setUserdata("syncTimer", item, 2);
        addTodayStartTime()
      }
    }
  } catch (error) {
    await addLog("Error - API: https://api.workstatus.io/api/v1/activity/syncTimer  " + error, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.error("Error syncing timer:", error);
  }
}

async function getTodos(id) {
  // debugger
  $(".loader").show();
  const url = "https://api.workstatus.io/api/v1/todos/list";
  retriveItem = JSON.parse(localStorage.getItem("userDetail"));
  const data = {
    memberIds: [retriveItem.id],
    organization_id: retriveItem.org_id,
    project_id: id,
  };
  const header = {
    SDToken: retriveItem.sd_token,
    Authorization: "Bearer " + retriveItem.token,
    OrgID: retriveItem.org_id,
    "Content-Type": "application/json",
    UserID: retriveItem.id,
    deviceType: "Chrome_extension",
  };

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: header,
      body: JSON.stringify(data),
    });

    const result = await response.json();

    if (result.response.code !== "200" && result.response.code !== "400") {
      document.getElementById(
        "error"
      ).innerHTML = `<b style='color:red'>${result.response.message}</b>`;
    } else {
      await storeTaskData(id, result.response.data);
    }
  } catch (error) {
    await addLog("Error - API: https://api.workstatus.io/api/v1/todos/list  " + error, moment().format("YYYY-MM-DD HH:mm:ss"));
    console.error("Error fetching todos:", error);
    document.getElementById(
      "error"
    ).innerHTML = `<b style='color:red'>Error fetching todos</b>`;
  }
}

function getscreenshotInterval() {
  const url = "https://api.workstatus.io/api/v1/user/screenshotInterval";
  retriveItem = JSON.parse(localStorage.getItem("userDetail"));
  const data = {
    organization_id: retriveItem.org_id,
    user_id: retriveItem.id,
  };

  const header = {
    SDToken: retriveItem.sd_token,
    Authorization: "Bearer " + retriveItem.token,
    OrgID: retriveItem.org_id,
    "Content-Type": "application/json",
    UserID: retriveItem.id,
    deviceType: "Chrome_extension",
  };
  $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: JSON.stringify(data),
    headers: header,
    success: function (result) {
      // let resdata = JSON.parse(result);
      if (result.response.code != "200") {
        window.location.href = "logout.html";
      } else {
        setLocalStorage("todoDetail", result.response.data);
        chrome.storage.local
          .set({ todoDetailChrome: result.response.data })
          .then(() => {
          });
        chrome.storage.local.set({
          SSInterval: result.response.data.timeInterval,
        });
        chrome.storage.local.set({
          SSNotify: result.response.data.notification_status,
        });
        chrome.storage.local.set({
          SSFrequency: result.response.data.ssfrequencystatus,
        });

        chrome.storage.local.set({
          isSSBlur: result.response.data.screenshotblurstatus,
        });
        chrome.storage.local.set({
          breakLimit: result.response.data.break_limit,
        });
        chrome.storage.local.set({
          breakStatus: result.response.data.break_status,
        });
        
        // Check and update break button visibility
        checkBreakStatus();
        


        setUserdata("screenshot_interval", result.response.data, 6);

      }



      // do something here
    },
    error: async function (result) {
      await addLog("Error - API: https://api.workstatus.io/api/v1/user/screenshotInterval  " + result, moment().format("YYYY-MM-DD HH:mm:ss"));
      window.location.href = "logout.html";
    },
  });
}

// Function to fetch break list from API
async function getBreakList() {
  try {
    const url = "https://api.workstatus.io/api/v1/setting/definingbreak/list";
    const retriveItem = JSON.parse(localStorage.getItem("userDetail"));
    
    const data = {
      org_id: retriveItem.org_id
    };

    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 response = await fetch(url, {
      method: "POST",
      headers: headers,
      body: JSON.stringify(data),
    });

    const result = await response.json();

    if (result.response.code === "200") {
      // Filter breaks with status: 1
      const activeBreaks = result.response.data.filter(breakItem => breakItem.status === 1);
      
      // Update dropdown with active breaks
      updateBreakDropdown(activeBreaks);
      
      // Store break list in storage
      await chrome.storage.local.set({
        breakList: activeBreaks
      });
    } else {
      console.error('Error fetching break list:', result.response.message);
    }
  } catch (error) {
    console.error('Error fetching break list:', error);
  }
}

// Make getBreakList globally accessible
window.getBreakList = getBreakList;

// Function to update break dropdown with active breaks
function updateBreakDropdown(activeBreaks) {
  const breakDropdown = document.querySelector('.breakDropdown');
  if (breakDropdown && activeBreaks.length > 0) {
    let options = '';
    activeBreaks.forEach(breakItem => {
      options += `<li data-break="${breakItem.id}" title="${breakItem.break_name}">${breakItem.break_name}</li>`;
    });
    breakDropdown.innerHTML = options;
  }
}

// Function to check break status and show/hide break button
async function checkBreakStatus() {
  try {
    const result = await chrome.storage.local.get(['breakStatus']);
    const breakStatus = result.breakStatus;
    
    const breakSection = document.getElementById('breakSection');
    if (breakSection) {
      if (breakStatus === 1) {
        breakSection.style.display = 'block';
        // Fetch break list when showing the section
        await getBreakList();
      } else {
        // For testing purposes, show the break section even if breakStatus is not 1
        // Remove this line in production if break status should control visibility
        breakSection.style.display = 'none';
        await getBreakList();
      }
    }
  } catch (error) {
    console.error('Error checking break status:', error);
  }
}

async function initializePostLoginData() {
  const result = await Promise.all([getProjectList(), getscreenshotInterval()]);
  // Check break status after data is loaded
  checkBreakStatus();
  return result;
}

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

async function setAllData() {
  let val = await checkIfAlredyLoaded();
  if (val == 0) {
    await initializePostLoginData();
    chrome.storage.local.set({ fileLoaded: 1 });
    setTotalTime();
  }
}
setAllData();

$("#start--").on("click", function (e) {
  var projectid = $("#project_id").val();
  var taskid = $("#task_id").val();
  var pname = $("#selectedProjecttop").text();
  var taskname = $("#selectedTasktop").text();
  if (parseInt(projectid) > 0) {
    try {
      if (projectid) {
        //////////////////////////////////
        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;
          };
        };
        //////////////////////////////////////
        setTimeout(() => {
          // window.location.href="timer.html?pid="+projectid+"&taskid="+taskid+"&projectname="+pname+"&taskname="+taskname;
        }, 100);
      } else {
        $("#perror").html("<b style='color:red'>Something went wrong</b>");
      }
      e.preventDefault();
    } catch (err) {
      e.preventDefault();
    }
    ///////////////////////////////////////////////
  } else {
    $("#perror").html("<b style='color:red'>Please select a project</b>");
  }
  e.preventDefault();
});

async function setLocalStorage(datakey, value) {
  window.localStorage.setItem(datakey, JSON.stringify(value));
}
let previousProjectList = ""; // Store the last loaded project list

function getProjects() {
  // let options = '<option selected>Select Project</option>';
  let options = "";
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("project_list", "readonly");
    let store = tx.objectStore("project_list");
    let cursor = store.openCursor();
    cursor.onsuccess = () => {
      let curRes = cursor.result;
      if (curRes) {
        if (curRes.value) {
          options +=
            '<li data-id="' +
            curRes.value.id +
            '">' +
            curRes.value.name +
            "</li>";
        }
        curRes.continue();
      }
      $("#projectlist").html(options);
    };
    cursor.oncomplete = () => {
      tx.close();
    };
  };
}

function setTodos(pid) {
  let options = "";
  let idb = indexedDB.open("wstracker_new_db");
  idb.onsuccess = () => {
    let res = idb.result;
    let tx = res.transaction("todo_list", "readonly");
    let store = tx.objectStore("todo_list");
    const myIndex = store.index("projectidindx");
    const getRequest = myIndex.getAll(pid);
    getRequest.onsuccess = () => {
      let curRes = getRequest.result;
      if (curRes) {
        curRes.forEach((item) => {
          options += '<li data-id="' + item.id + '">' + item.name + "</li>";
        });
      }
      $("#todolist").html(options);
    };
  };
}

$("#projectlist").change(function () {
  let pid = this.value;
  setTodos(parseInt(pid));
});

let userLocation = navigator.geolocation;
function myGeolocator() {
  if (userLocation) {
    return userLocation.getCurrentPosition(success);
  } else {
    chrome.storage.local.set({ latitude: 0 });
    chrome.storage.local.set({ longitude: 0 });
  }
}

function success(data) {
  let lat = data.coords.latitude;
  let long = data.coords.longitude;
  chrome.storage.local.set({ latitude: lat });
  chrome.storage.local.set({ longitude: long });
}
var latlongdata = myGeolocator();

let runCount = 1;
setInterval(async () => {
  let val = await checkIfAlredyLoaded();
    if (val == 1) {
      $(".loader").hide();
      if (runCount == 1) {
        getProjects();
        checkBreakStatus(); // Check break status on page load
        runCount = 0;
      }
    } else {
    $(".loader").show();
  }
}, 1000);
////////////////////////////// end location section /////////////////////

// setTimeout(() => {

// }, 2000);