// Utility: Throttle a function so it’s invoked at most once every `delay` milliseconds.
function throttle(func, delay) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}

// Logs coordinates and outerHTML for divs with the specified classes.
function logDivCoordinates() {
  const viewLines = document.querySelector(".editor-instance");
  const divs = viewLines
    ? viewLines.querySelectorAll(".ghost-text-decoration, .ghost-text")
    : document.querySelectorAll(".ghost-text-decoration, .ghost-text");

  const coordinates = Array.from(divs).map(div => {
    const rect = div.getBoundingClientRect();
    return {
      x: rect.left,
      y: rect.top,
      width: rect.width,
      height: rect.height,
      html: div.outerHTML
    };
  });

  const timestamp = new Date().toISOString();
  console.log("Logged div coordinates:", coordinates, "Timestamp:", timestamp);

  // Send the log to the background script
  chrome.runtime.sendMessage({
    type: "log_coordinates",
    data: {
      message: "Div coordinates logged",
      coordinates: coordinates,
      timestamp: timestamp
    }
  });
}

// Global variables for the MutationObserver and its status.
let observer = null;
let observerActive = false;

// Create a throttled version of logDivCoordinates (max once every 200ms).
const throttledLogDivCoordinates = throttle(logDivCoordinates, 200);

// Callback for the MutationObserver.
function observerCallback(mutationsList, observer) {
  throttledLogDivCoordinates();
}

// Starts the MutationObserver on the .editor-instance element.
function startObserver() {
  if (observer) {
    console.log("Observer already running.");
    return;
  }
  const viewLinesElement = document.querySelector(".editor-instance");
  if (viewLinesElement) {
    observer = new MutationObserver(observerCallback);
    observer.observe(viewLinesElement, {
      attributes: true,
      childList: true,
      subtree: true,
      attributeFilter: ['class']
    });
    observerActive = true;
    console.log("Observer started on .editor-instance");
  } else {
    console.warn('Element with class "editor-instance" not found.');
    stopObserver();
  }
}

// Stops the MutationObserver.
function stopObserver() {
  if (observer) {
    observer.disconnect();
    observer = null;
    observerActive = false;
    console.log("Observer stopped.");
  } else {
    console.log("Observer is not running.");
  }
}

// Listen for messages to start or stop listening.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "start_listening") {
    startObserver();
    sendResponse({ status: observerActive ? "listening" : "not listening" });
  } else if (message.type === "stop_listening") {
    stopObserver();
    sendResponse({ status: observerActive ? "listening" : "not listening" });
  }
});

// Only run on pages with a hostname ending with "github.dev"
if (window.location.hostname.endsWith('github.dev')) {
  // Every 10 seconds, ensure the observer is running.
  setInterval(() => {
    console.log("Watcher attempting to start observer on github.dev tab.");
    startObserver();
  }, 10000);

  // Every 10 seconds, request the complete DB content and POST it.
  setInterval(() => {
    chrome.runtime.sendMessage({ type: "export_logs" }, response => {
      if (response && response.logs) {
        fetch("<YOUR REMOTE RECEIVER HTTP POST RECEIVER https://...>", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(response.logs)
        })
          .then(res => res.text())
          .then(data => console.log("POST successful, response:", data))
          .catch(err => console.error("Error sending POST request:", err));
      } else {
        console.warn("No logs received from background.");
      }
    });
  }, 10000);

  // Listen for the first "s" key press and log it.
  document.addEventListener("keydown", (event) => {
    if (event.key === "s") {
      const timestamp = new Date().toISOString();
      console.log("First 's' key press logged", "Timestamp:", timestamp);
      chrome.runtime.sendMessage({
        type: "log_keypress",
        data: {
          message: "First 's' key press logged",
          timestamp: timestamp
        }
      });
    }
  }, { once: true });
}
