// Initialize time change tracking
chrome.storage.local.set({ time_changed: 0 });
chrome.storage.local.set({ isBreakTimeExceeded: false });

// Utility function for fetch requests
function json(url) {
  return fetch(url).then((res) => res.json());
}

// Password input enter key handler
const input = document.getElementById("password");
input.addEventListener("keypress", function (event) {
  if (event.key === "Enter") {
    event.preventDefault();
    document.getElementById("myButton").click();
  }
});

// Optimized notification function
function showNotification(title, message) {
  chrome.notifications.create("notification-id", {
    type: "basic",
    iconUrl: "../images/48.png",
    title: title,
    message: message,
  });
}

// Password toggle functionality
$(document).on("click", ".toggle-password", function () {
  $(this).toggleClass("fa-eye fa-eye-slash");
  var input = $("#password");
  input.attr("type") === "password"
    ? input.attr("type", "text")
    : input.attr("type", "password");
});

// Main login button click handler
document.getElementById("myButton").addEventListener("click", loginAction);

// Optimized login function
async function loginAction() {
  // debugger;
  const tempmail = document.getElementById("email").value;
  const temppass = document.getElementById("password").value;

  // Form validation
  if (!validateForm(tempmail, temppass)) return false;

  // Update button state
  const loginButton = document.getElementById("myButton");
  setButtonLoading(loginButton, true);

  try {
    // Parallel API calls for initial data
    const [locationData, browserType] = await Promise.all([
      getLocationData(),
      checkBrowser(),
    ]);

    // Store location data in parallel
    await storeLocationData(locationData);

    // Check server time
    const timeValid = await validateServerTime(locationData.time_zone.name);
    if (!timeValid) {
      throw new Error("Please check your Clock time and internet connection");
    }

    // Perform login
    const loginResult = await performLogin(
      tempmail,
      temppass,
      browserType,
      locationData
    );

    if (loginResult.response.code !== "200") {
      throw new Error(loginResult.response.message);
    } else if (
      loginResult.response.data.org_id == null ||
      loginResult.response.latest_plan.status == 0
    ) {
      throw new Error("Either Organisation is expired or User is deleted");
    }

    // Store user data and perform post-login actions in parallel

    // await deleteDatabaseIfExists();
    try {
      await Promise.all([
        storeUserData(loginResult.response.data),
        // initializePostLoginData(),
      ]);
    } catch (err) {}
    // debugger

    // Show success and redirect
    showNotification("Login Successful", "You have successfully logged in.");
    window.location.href = "projectList.html";
    //window.location.href=chrome.runtime.getURL("html/projectList.html")
  } catch (error) {
    if (error.message == "Login successfully.") {
      $("#logerror").html(`<b style='color:red'>User has been deleted</b>`);
    } else {
      $("#logerror").html(`<b style='color:red'>${error.message}</b>`);
    }
    setButtonLoading(loginButton, false);
  }
}

// Helper Functions
function validateForm(email, password) {
  let isValid = true;

  if (!email) {
    $("#emailerr").html("Please enter a valid email");
    isValid = false;
  } else {
    $("#emailerr").html("");
  }

  if (!password) {
    $("#passerr").html("Please enter a password");
    isValid = false;
  } else {
    $("#passerr").html("");
  }

  return isValid;
}

function setButtonLoading(button, isLoading) {
  button.innerHTML = isLoading ? "Loading..." : "Sign In";
  button.disabled = isLoading;
  button.style.backgroundColor = isLoading ? "#d3d3d3" : "";
  button.style.color = isLoading ? "#808080" : "";
}

async function getLocationData() {
  const apiKey = "ed5e95c005f0103f9c62fa9b97c591965ebf9e0e90dabd2da7bd2820";
  return await json(`https://api.ipdata.co?api-key=${apiKey}`);
}

async function storeLocationData(data) {
  return Promise.all([
    chrome.storage.local.set({ latitude: data.latitude }),
    chrome.storage.local.set({ longitude: data.longitude }),
    chrome.storage.local.set({ time_zone: data.time_zone.name || "" }),
    chrome.storage.local.set({ ip_address: data.ip || 0 }),
  ]);
}

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

  if (timerdata.response.code !== 200) return false;

  const serverTime = moment(timerdata.response.time);
  const clientTime = moment(new Date());
  const timeDifference = Math.abs(serverTime.diff(clientTime, "minutes"));

  return timeDifference <= 1;
}

async function performLogin(email, password, deviceType, locationData) {
  const loginData = {
    deviceId: Date.now().toString(36) + Math.random().toString(36).substr(2),
    deviceType: deviceType,
    ip_address: locationData.ip || "111.111.111.111",
    os_version: "10",
    email: email,
    password: password,
  };

  return await $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: endpointUrl + "login",
    data: JSON.stringify(loginData),
  });
}

async function storeUserData(userData) {
  try {
    await Promise.all([
      setUserdatalogin("userDetail", userData),
      setLocalStorage("userDetail", userData),
      chrome.storage.local.set({ userDetail: userData }),
      chrome.storage.local.set({ userDetailChrome: userData }),
    ]);

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

// Existing helper functions (unchanged)
async function setLocalStorage(datakey, value) {
  // debugger;
  try {
    window.localStorage.setItem(datakey, JSON.stringify(value));
  } catch (err) {}
}

function setUserdatalogin(tbl, value) {
  // debugger;
  try {
    return new Promise((res, rej) => {
      createDb().then(
        function (val) {
          res("DB created successfully!");
          return true;
        },
        function (err) {
          rej(err);
          return false;
        }
      );
    });
  } catch (err) {}
}
async function checkBrowser() {
  // Get the user-agent string
  let userAgentString = navigator.userAgent;

  // Detect Chrome
  let chromeAgent = userAgentString.indexOf("Chrome") > -1;

  // Detect Edge
  let edgeAgent = userAgentString.indexOf("Edg") > -1;

  // Detect Internet Explorer
  let IExplorerAgent =
    userAgentString.indexOf("MSIE") > -1 || userAgentString.indexOf("rv:") > -1;

  // Detect Firefox
  let firefoxAgent = userAgentString.indexOf("Firefox") > -1;

  // Detect Safari
  let safariAgent = userAgentString.indexOf("Safari") > -1;

  // Discard Safari since it also matches Chrome
  if (chromeAgent && safariAgent) safariAgent = false;

  if (chromeAgent && edgeAgent) chromeAgent = false;

  if (IExplorerAgent && firefoxAgent) IExplorerAgent = false;

  // Detect Opera
  let operaAgent = userAgentString.indexOf("OP") > -1;

  // Discard Chrome since it also matches Opera
  if (chromeAgent && operaAgent) chromeAgent = false;

  if (safariAgent) {
    return "Safari";
  }

  if (chromeAgent) {
    return "Chrome";
  }

  if (IExplorerAgent) {
    return "Explorer";
  }

  if (operaAgent) {
    return "Opera";
  }

  if (firefoxAgent) {
    return "Firefox";
  }

  if (edgeAgent) {
    return "Edge";
  }
}
