$("#projectDropdown").hide();

$(".projectDropdown").on("click", ".init", function () {
  $(this).closest("ul").children("li:not(.init)").toggle();
});

// --- Popup dynamic resize helpers ---
const COMPACT_HEIGHT = 400; // matches base popup height
const MAX_POPUP_HEIGHT = 800;
const COMPACT_LIST_MAX = 50; // px

let isExpanded = false;

function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
}

// Grow only to the dropdown content height; if content is too large, cap the
// popup at MAX_POPUP_HEIGHT and enable inner scrolling for the list only.
function expandForDropdown(dropdownId, listUlId) {
  if (isExpanded) return;
  const dropdown = document.getElementById(dropdownId);
  const listUl = document.getElementById(listUlId);
  if (!dropdown || !listUl) return;

  // Current popup height and list height
  const currentPopupHeight = document.documentElement.clientHeight;
  const currentListHeight = Math.max(0, listUl.getBoundingClientRect().height);

  // Desired list height (content) and allowed increase within Chrome limits
  const desiredListHeight = listUl.scrollHeight;
  const maxIncrease = Math.max(0, MAX_POPUP_HEIGHT - currentPopupHeight);

  const appliedListHeight = Math.min(
    desiredListHeight,
    currentListHeight + maxIncrease
  );

  // Update list sizing and scrolling only if needed
  listUl.style.maxHeight = appliedListHeight + "px";
  listUl.style.overflowY =
    appliedListHeight < desiredListHeight ? "auto" : "hidden";

  // Grow popup exactly by the extra list space required
  const increaseBy = Math.max(0, appliedListHeight - currentListHeight);
  const newHeight = clamp(
    currentPopupHeight + increaseBy,
    COMPACT_HEIGHT,
    MAX_POPUP_HEIGHT
  );

  document.documentElement.style.height = newHeight + "px";
  document.body.style.height = newHeight + "px";
  const popup = document.getElementById("popupWindow");
  if (popup) popup.style.minHeight = newHeight + "px";

  isExpanded = true;
}

function shrinkPopup() {
  if (!isExpanded) return;
  isExpanded = false;
  const targetHeight = COMPACT_HEIGHT;
  document.documentElement.style.height = targetHeight + "px";
  document.body.style.height = targetHeight + "px";
  const popup = document.getElementById("popupWindow");
  if (popup) popup.style.minHeight = targetHeight + "px";

  // Return list max-height to compact
  const projectUl = document.getElementById("projectlist");
  const taskUl = document.getElementById("todolist");
  if (projectUl) {
    projectUl.style.maxHeight = COMPACT_LIST_MAX + "px";
    projectUl.style.overflowY = "auto";
  }
  if (taskUl) {
    taskUl.style.maxHeight = COMPACT_LIST_MAX + "px";
    taskUl.style.overflowY = "auto";
  }
}

// Close dropdowns and shrink when clicking outside dropdown areas
document.addEventListener("click", function (e) {
  const withinProject = e.target.closest && e.target.closest("#projectblock");
  const withinTask = e.target.closest && e.target.closest("#taskblock");
  const withinBreak = e.target.closest && e.target.closest(".break-section");
  if (!withinProject && !withinTask && !withinBreak) {
    $("#projectDropdown").hide();
    $("#taskDropdown").hide();
    shrinkPopup();
  }
});

let toShow = 0;
$("#projectblock").on("click", function (event) {
  if (event.target.tagName === "INPUT") return;
  if (event.target.tagName === "LABEL") return;
  if (event.target.tagName == "DIV") return;
  if (toShow == 0) {
    document.getElementById("taskblock").style.display = "none";
    document.getElementById("searchProject").value = "";
    jQuery("#projectlist li").each(function () {
      jQuery(this).show();
    });
    toShow = 1;
    expandForDropdown("projectDropdown", "projectlist");
  } else {
    toShow = 0;
    document.getElementById("taskblock").style.display = "block";
    // Only shrink if both dropdowns are hidden
    if (
      !$("#taskDropdown").is(":visible") &&
      !$("#projectDropdown").is(":visible")
    ) {
      shrinkPopup();
    }
  }
});

let toShow2 = 0;
$("#taskblock").on("click", function (event) {
  if (event.target.tagName === "INPUT") return;
  if (event.target.tagName === "LABEL") return;
  if (event.target.tagName == "DIV") return;
  if (toShow2 == 0) {
    document.getElementById("projectblock").style.display = "none";
    document.getElementById("searchTask").value = "";
    jQuery("#todolist li").each(function () {
      jQuery(this).show();
    });
    toShow2 = 1;
    expandForDropdown("taskDropdown", "todolist");
  } else {
    toShow2 = 0;
    document.getElementById("projectblock").style.display = "block";
    if (
      !$("#taskDropdown").is(":visible") &&
      !$("#projectDropdown").is(":visible")
    ) {
      shrinkPopup();
    }
  }
});

// var allOptions = $(".projectDropdown").children("li:not(.init)");
// $(".projectDropdown").on("click", "li:not(.init)", function () {
//   let pid = $(this).attr("data-id");
//   // console.log("selectedProject",$(this).text());
//   $("#selectedProject").html($(this).text());
//   $("#selectedProjecttop").html($(this).text());
//   $("#projectDropdown").hide();
//   $("#selectedTask").html("Select Task");
//   $("#selectedTasktop").html("");
//   $("#startdefault").hide();
//   $("#start").show();
//   $("#stop").hide();
//   //  $("#start").html('<img  src="../images/play-enabled.png">');
//   $("#editnote").html('<img src="../images/edit-enabled.png">');
//   $("#project_id").val(pid);
//   $("#task_id").val("0");
//   setTodos(parseInt(pid));
//   /////////////////////////////////
//   // timediffminutes();
//   let lasval = $("#tt").val();
//   lasval=600
//   var startTimestamp = moment().startOf("day").add(lasval, "s");
//   document.getElementById("timer").innerHTML =
//     startTimestamp.format("HH:mm:ss");
//   // startTimer(lasval);
//   /////////////////////////////////
// });

// Combine event handlers for project and task selection
$(".projectDropdown, .taskDropdown").on(
  "click",
  "li:not(.init)",
  async function () {
    // debugger
    let isProject = $(this).closest(".projectDropdown").length > 0;
    let isTask = $(this).closest(".taskDropdown").length > 0;
    let pid = 0;

    if (isProject) {
      // Project is clicked
      pid = $(this).attr("data-id");
      $("#selectedProject").html($(this).text());
      $("#selectedProjecttop").html($(this).text());
      $("#projectDropdown").hide();
      $("#selectedTask").html("Select Task");
      $("#selectedTasktop").html("");
      $("#startdefault").hide();
      $("#start").show();
      $("#stop").hide();
      $("#editnote").html('<img src="../images/edit-enabled.png">');
      $("#project_id").val(pid);
      $("#task_id").val("0");
      await getTodos(pid);
      await setTaskData(pid);
      // setTodos(parseInt(pid));
    }

    let tid = 0;
    if (isTask) {
      tid = $(this).attr("data-id");
      $("#task_id").val(tid);
      console.log("selectedTask", $(this).text());
      $("#selectedTask").html($(this).text());
      $("#selectedTasktop").html($(this).text());
      $("#taskDropdown").hide();
    }
    // After selecting any item, shrink back
    shrinkPopup();
    let lastval = await getSyncTimerData(pid, tid);
    var startTimestamp = moment().startOf("day").add(lastval, "s");
    document.getElementById("timer").innerHTML =
      startTimestamp.format("HH:mm:ss");
  }
);

$(".dropbtn").click(function () {
  $("#taskDropdown").hide();
  $("#projectDropdown").toggle();
  if ($("#projectDropdown").is(":visible")) {
    isExpanded = false; // allow recalculation each time dropdown is opened
    expandForDropdown("projectDropdown", "projectlist");
  } else if (!$("#taskDropdown").is(":visible")) {
    shrinkPopup();
  }
});
$(".dropbtn2").click(function () {
  $("#projectDropdown").hide();
  $("#taskDropdown").toggle();
  if ($("#taskDropdown").is(":visible")) {
    isExpanded = false; // allow recalculation each time dropdown is opened
    expandForDropdown("taskDropdown", "todolist");
  } else if (!$("#projectDropdown").is(":visible")) {
    shrinkPopup();
  }
});

$(".taskDropdown").on("click", ".init", function () {
  $(this).closest("ul").children("li:not(.init)").toggle();
});

// var allOptions = $(".taskDropdown").children("li:not(.init)");
// $(".taskDropdown").on("click", "li:not(.init)", function () {
//   let tid = $(this).attr("data-id");
//   $("#task_id").val(tid);
//   $("#selectedTask").html($(this).text());
//   $("#selectedTasktop").html($(this).text());
//   $("#taskDropdown").hide();
//   /////////////////////////////////
//   // timediffminutes();
//   let lasval = $("#tt").val();
//   // startTimer(lasval);
//   /////////////////////////////////
// });
// Debug: Check if button exists
console.log("Take Break button exists:", $("#takeBreakBtn").length > 0);
console.log("Break dropdown exists:", $(".breakDropdown").length > 0);

// Function to truncate long text for button display
function truncateText(text, maxLength = 15) {
  if (text.length <= maxLength) {
    return text;
  }
  return text.substring(0, maxLength) + "...";
}

// Handle break selection -> start break
$(".breakDropdown").on("click", "li", async function () {
  const breakId = $(this).attr("data-break");
  const breakText = $(this).text();

  // Hide dropdown
  $("#breakDropdown").removeClass("show");

  try {
    await new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        { action: "break", isStartOrStop: "start", breakId },
        (response) => {
          console.log("Break start response received:", response);
          console.log("Chrome runtime last error:", chrome.runtime.lastError);
          chrome.storage.local.set({ breakstarted: true });
          if (chrome.runtime.lastError) return reject(chrome.runtime.lastError);
          if (response && response.message) return resolve(response);
          reject(new Error(response?.error || "No response received"));
        }
      );
    });

    // Update button text to show stop state with truncated text
    const truncatedText = truncateText(breakText);
    $("#takeBreakBtn")
      .text(`Stop: ${truncatedText}`)
      .attr("data-break-id", breakId)
      .attr("data-break-name", breakText)
      .attr("data-break-state", "started")
      .attr("title", `Stop: ${breakText}`);

    // Persist break state so it survives page reloads
    try {
      await chrome.storage.local.set({
        currentBreak: { id: breakId, name: breakText, state: "started" },
      });
    } catch (err) {
      console.error("Failed to persist break state:", err);
    }

    // Re-evaluate button enabled/disabled state
    setBreakButtonDisabledState();

    // Disable all other interactions when break is active
    disableAllInteractions();
  } catch (e) {
    console.error("Failed to start break:", e);
  }
});

// Toggle dropdown on Take Break / Stop click, or stop if already started
$("#takeBreakBtn").on("click", async function (e) {
  console.log("Take Break button clicked!");
  e.stopPropagation();
  const state = $(this).attr("data-break-state");
  const breakId = $(this).attr("data-break-id");
  const breakName = $(this).attr("data-break-name");
  console.log(
    "Button state:",
    state,
    "breakId:",
    breakId,
    "breakName:",
    breakName
  );

  if (state === "started" && breakId) {
    // Stop current break
    try {
      await new Promise((resolve, reject) => {
        chrome.runtime.sendMessage(
          { action: "break", isStartOrStop: "stop", breakId },
          (response) => {
            console.log("Break stop response received:", response);
            console.log("Chrome runtime last error:", chrome.runtime.lastError);
            if (chrome.runtime.lastError)
              return reject(chrome.runtime.lastError);
            if (response && response.message) return resolve(response);
            reject(new Error(response?.error || "No response received"));
          }
        );
      });

      // Reset button back to Take Break
      $(this)
        .text("Take Break")
        .removeAttr("data-break-id")
        .removeAttr("data-break-name")
        .removeAttr("title")
        .attr("data-break-state", "stopped");

      // Clear persisted break state
      try {
        await chrome.storage.local.remove(["currentBreak"]);
      } catch (err) {
        console.error("Failed to clear break state:", err);
      }

      // Re-evaluate button enabled/disabled state
      setBreakButtonDisabledState();

      // Re-enable all interactions when break is stopped
      enableAllInteractions();
    } catch (e) {
      console.error("Failed to stop break:", e);
    }
  } else {
    // Show dropdown to choose a break
    console.log("Break dropdown items:", $(".breakDropdown li").length);
    console.log("Break dropdown HTML:", $(".breakDropdown").html());

    // If no break items, try to fetch them first
    if ($(".breakDropdown li").length === 0) {
      console.log("No break items found, fetching break list...");
      // Call the function to fetch break list
      try {
        if (typeof getBreakList === "function") {
          await getBreakList();
        } else {
          console.log(
            "getBreakList function not available, trying to call it from window"
          );
          if (typeof window.getBreakList === "function") {
            await window.getBreakList();
          } else {
            console.log("getBreakList not found on window either");
          }
        }
      } catch (e) {
        console.error("Error fetching break list:", e);
      }
    }

    $("#breakDropdown").toggleClass("show");
    $("#projectDropdown").hide();
    $("#taskDropdown").hide();
  }
});

// Close break dropdown when clicking outside
$(document).click(function (e) {
  if (!$(e.target).closest(".break-section").length) {
    $("#breakDropdown").removeClass("show");
  }
});

// Initialize break button state from persisted storage (handles page reloads/navigation)
$(async function () {
  try {
    const result = await chrome.storage.local.get(["currentBreak"]);
    const currentBreak = result.currentBreak;
    if (currentBreak && currentBreak.state === "started") {
      const truncatedText = truncateText(currentBreak.name);
      $("#takeBreakBtn")
        .text(`Stop: ${truncatedText}`)
        .attr("data-break-id", currentBreak.id)
        .attr("data-break-name", currentBreak.name)
        .attr("data-break-state", "started")
        .attr("title", `Stop: ${currentBreak.name}`);

      // Disable all interactions if break is already active
      disableAllInteractions();
    } else {
      $("#takeBreakBtn")
        .text("Take Break")
        .removeAttr("data-break-id")
        .removeAttr("data-break-name")
        .removeAttr("title")
        .attr("data-break-state", "stopped");
    }
    // After initializing label/state, enforce enabled/disabled based on timer
    setBreakButtonDisabledState();
  } catch (err) {
    console.error("Failed to initialize break button state:", err);
  }
});

// Function to disable all UI interactions except break stop button
function disableAllInteractions() {
  // Disable project and task dropdowns
  $(".selection-dropdown-box").css("pointer-events", "none");
  $(".selection-dropdown-box").css("opacity", "0.4");

  // Disable timer controls (start/stop buttons)
  $("#start").css("pointer-events", "none");
  $("#start").css("opacity", "0.4");
  $("#stop").css("pointer-events", "none");
  $("#stop").css("opacity", "0.4");
  $("#startdefault").css("pointer-events", "none");
  $("#startdefault").css("opacity", "0.4");

  // Disable edit note button
  $("#editnote").css("pointer-events", "none");
  $("#editnote").css("opacity", "0.4");

  // Disable logout button
  $("#logout").css("pointer-events", "none");
  $("#logout").css("opacity", "0.4");

  // Disable refresh button
  $("#syncNow").css("pointer-events", "none");
  $("#syncNow").css("opacity", "0.4");

  // Keep break button enabled but only for stopping
  $("#takeBreakBtn").css("pointer-events", "auto");
  $("#takeBreakBtn").css("opacity", "1");
}

// Function to re-enable all UI interactions
function enableAllInteractions() {
  // Re-enable project and task dropdowns
  $(".selection-dropdown-box").css("pointer-events", "auto");
  $(".selection-dropdown-box").css("opacity", "1");

  // Re-enable timer controls
  $("#start").css("pointer-events", "auto");
  $("#start").css("opacity", "1");
  $("#stop").css("pointer-events", "auto");
  $("#stop").css("opacity", "1");
  $("#startdefault").css("pointer-events", "auto");
  $("#startdefault").css("opacity", "1");

  // Re-enable edit note button
  $("#editnote").css("pointer-events", "auto");
  $("#editnote").css("opacity", "1");

  // Re-enable logout button
  $("#logout").css("pointer-events", "auto");
  $("#logout").css("opacity", "1");

  // Re-enable refresh button
  $("#syncNow").css("pointer-events", "auto");
  $("#syncNow").css("opacity", "1");

  // Break button remains enabled
  $("#takeBreakBtn").css("pointer-events", "auto");
  $("#takeBreakBtn").css("opacity", "1");
}

// Helper: enable button if timer is running OR a break is already started; otherwise disable
async function setBreakButtonDisabledState() {
  try {
    const res = await chrome.storage.local.get(["timerstate", "currentBreak"]);
    const isTimerRunning = res.timerstate === 1;
    const isBreakStarted =
      $("#takeBreakBtn").attr("data-break-state") === "started" ||
      (res.currentBreak && res.currentBreak.state === "started");
    const shouldDisable = !isTimerRunning && !isBreakStarted;
    $("#takeBreakBtn").prop("disabled", shouldDisable);
  } catch (e) {
    // Fail-open: allow button if we can't read state
    $("#takeBreakBtn").prop("disabled", false);
  }
}

// React to timer/break state changes from elsewhere in the app
try {
  chrome.storage.onChanged.addListener((changes, areaName) => {
    if (areaName !== "local") return;
    if (changes.timerstate || changes.currentBreak) {
      setBreakButtonDisabledState();
    }
  });
} catch (e) {
  // Ignore if storage events are not available
}

jQuery("#searchProject").keyup(function () {
  var filter = jQuery(this).val().toLowerCase();
  var found = false;

  jQuery("#projectlist li").each(function () {
    if (jQuery(this).text().toLowerCase().includes(filter)) {
      jQuery(this).show();
      found = true;
    } else {
      jQuery(this).hide();
    }
  });

  // if (!found) {
  //   if (jQuery("#noProjectFound").length ===0) {
  //     jQuery("#projectlist").append("<li id='noProjectFound' style='color: red;'>No data found</li>");
  //   }
  // } else {
  //   jQuery("#noProjectFound").remove();
  // }
});

jQuery("#searchTask").keyup(function () {
  var filter = jQuery(this).val().toLowerCase();
  var found = false;

  jQuery("#todolist li").each(function () {
    if (jQuery(this).text().toLowerCase().includes(filter)) {
      jQuery(this).show();
      found = true;
    } else {
      jQuery(this).hide();
    }
  });

  // if (!found) {
  //   if (jQuery("#noTaskFound").length === 1) {
  //     jQuery("#todolist").append("<li id='noTaskFound' style='color: red;'>No data found</li>");
  //   }
  // } else {
  //   jQuery("#noTaskFound").remove();
  // }
});
