// Flag for whether or not to show only your own conversations

let showOwnConversationsOnly = true;

const keys = ["rtlPrompt", "fixMath", "betterFont"];




function applySettings() {
  chrome.storage.local.get(keys, (res) => {
    const defaults = { rtlPrompt: false, fixMath: false, betterFont: false };
    const toSet = {};
    keys.forEach((k) => {
      if (res[k] === undefined) {
        res[k] = defaults[k];
        toSet[k] = defaults[k];
      }
    });
    if (Object.keys(toSet).length) chrome.storage.local.set(toSet);

    document.getElementById("prompt-textarea").style.textAlign = res.rtlPrompt
      ? "right"
      : "left";

    if (res.fixMath) {
      const assistantMessages = document.querySelectorAll(
        '[data-message-author-role="assistant"]'
      );

      assistantMessages.forEach((message) => {
        let textContent = message.textContent;
        message.style.border = "1px solid gray";
        message.style.padding = "10px 30px";
        message.style.borderRadius = "5px";
        message.style.overflow = "auto";

        let containsPersian = /[آ-ی]/.test(textContent);
        let codeBlocks = message.querySelectorAll("pre, code");
        let table = message.querySelectorAll("table");

        if (containsPersian) {
          message.style.direction = "rtl";
          message.style.textAlign = "right";

          codeBlocks.forEach((block) => {
            block.style.direction = "ltr";
            block.style.textAlign = "left";
          });
        } else {
          message.style.direction = "ltr";
          message.style.textAlign = "left";

          codeBlocks.forEach((block) => {
            block.style.direction = "ltr";
            block.style.textAlign = "left";
          });
        }

        table.forEach((p) => {
          p.style.paddingLeft = "60px";
        });

        const katexElements = message.querySelectorAll(".katex");
        katexElements.forEach((el) => {
          el.style.textAlign = "left";
          el.setAttribute("dir", "ltr");
        });
      });
    } else {
      const assistantMessages = document.querySelectorAll(
        '[data-message-author-role="assistant"]'
      );

      assistantMessages.forEach((message) => {
        message.style.border = "";
        message.style.padding = "";
        message.style.borderRadius = "";
        message.style.overflow = "";
        message.style.direction = "";
        message.style.textAlign = "";

        let codeBlocks = message.querySelectorAll("pre, code");
        codeBlocks.forEach((block) => {
          block.style.direction = "";
          block.style.textAlign = "";
        });

        let table = message.querySelectorAll("table");
        table.forEach((p) => {
          p.style.paddingLeft = "";
        });

        const katexElements = message.querySelectorAll(".katex");
        katexElements.forEach((el) => {
          el.style.textAlign = "";
          el.removeAttribute("dir");
        });
      });
    }

    const fontUrl = chrome.runtime.getURL("fonts/Vazirmatn-RD-Regular.woff2");
    const fontFaceId = "better-font-family-style";
    if (!document.getElementById(fontFaceId)) {
      const s = document.createElement("style");
      s.id = fontFaceId;

      s.textContent = `
      @font-face {
        font-family: 'Vazirmatn';
        font-style: normal;
        font-weight: 400;
        src: url('${fontUrl}') format('woff2');
      }
    `;
      document.head.appendChild(s);
    }

    const styleId = "better-font-style";
    if (res.betterFont) {
      if (!document.getElementById(styleId)) {
        const s = document.createElement("style");
        s.id = styleId;

        s.textContent = `
      textarea, input, button, p, div, span, h1, h2, h3, h4, h5, h6 {
        font-family: 'Vazirmatn', sans-serif !important;
        direction: auto;
      }
    `;
        document.head.appendChild(s);
      }
    } else {
      document.getElementById(styleId)?.remove();
    }
  });
}

const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.addedNodes.length > 0) {
      console.log("DOM changed, applying settings...");
      applySettings();
    }
  }
});

observer.observe(document.body, {
  childList: true,
  subtree: true,
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "updateSettings") {
    applySettings();

    sendResponse({ success: true });
    return true;
  }
});

// Load the setting from storage
chrome.storage.local.get(["ownConversationsOnly", "userToken"], (result) => {
  // If the setting isn't found, default to true
  showOwnConversationsOnly =
    result.ownConversationsOnly !== undefined
      ? result.ownConversationsOnly
      : true;

  // If user has a token, force enable conversation filtering
  if (result.userToken) {
    showOwnConversationsOnly = true;
  }
});

// Added: global flag for showing projects
let showProjects = true;
chrome.storage.local.get(["showProjects", "userToken"], (result) => {
  showProjects = result.showProjects !== undefined ? result.showProjects : true;

  // If user has a token, force enable project filtering
  if (result.userToken) {
    showProjects = true;
  }
});

chrome.storage.onChanged.addListener((changes, area) => {
  if (area === "sync") {
    // Handle token changes
    if (changes.userToken) {
      if (changes.userToken.newValue) {
        // If token is added, force enable filtering
        showOwnConversationsOnly = true;
        showProjects = true;

        // Apply filtering immediately
        const listItem = document.querySelectorAll('a[href^="/c/"]');
        if (listItem[0]) {
          deleteListItemsNotInStorage();
        }

        const projectList = document.querySelectorAll('a[href^="/g/"]');
        if (projectList) {
          deleteProjectNotInStorage(projectList);
        }
      }
    }

    // Handle conversation setting changes
    if (changes.ownConversationsOnly) {
      showOwnConversationsOnly = changes.ownConversationsOnly.newValue;
      if (showOwnConversationsOnly) {
        const listItem = document.querySelectorAll('a[href^="/c/"]');
        if (listItem[0]) {
          deleteListItemsNotInStorage();
        }
      }
    } else if (changes.showProjects) {
      // Added block for projects
      showProjects = changes.showProjects.newValue;
      const projectList = document.querySelectorAll('a[href^="/g/"]');
      if (projectList[0]) {
        deleteProjectNotInStorage(projectList);
      }
    }
  }
});

function deleteListItemsNotInStorage() {
  if (!showOwnConversationsOnly) return;

  chrome.storage.local.get({ conversations: [] }, function (result) {
    const storedConversations = result.conversations;
    // Directly query the <a> elements with href starting with "/c/"
    const conversationLinks = document.querySelectorAll('a[href^="/c/"]');

    // Iterate through each conversation link and handle visibility
    conversationLinks.forEach((anchor) => {
      const href = anchor.getAttribute("href");
      const conversationId = href.split("/c/")[1];

      // Find the <li> element containing the conversation link
      const listItem = anchor.closest("div");

      // If the conversation ID is not in storage, hide or remove the item
      if (!storedConversations.includes(conversationId)) {
        if (anchor) {
          anchor.style.display = "none"; // Hide the entire list item
        }
      }
    });
  });
}

function deleteProjectNotInStorage() {
  if (!showProjects) return;

  chrome.storage.local.get({ projects: [] }, function (result) {
    const storedProjects = result.projects;

    // Directly query the <a> elements with href starting with "/g/"
    const projectLinks = document.querySelectorAll('a[href^="/g/"]');

    // Iterate through each project link and handle visibility
    projectLinks.forEach((anchor) => {
      const href = anchor.getAttribute("href");
      const projectId = href.match(
        /\/g\/(g-p-[0-9a-f]+)(?:-[^\/]+)?\/project/i
      )?.[1];

      // Find the parent element (div or other container) of the project link
      const projectItem = anchor.closest("div");

      // If the project ID is not in storage, hide the entire project item
      if (projectId && !storedProjects.includes(projectId)) {
        if (anchor) {
          anchor.style.display = "none"; // Hide the entire project item
        }
      }
    });
  });
}

let observedParents = new WeakSet();
let observedElements = new WeakSet();

function selectListItemByTestIdIncludes() {
  const initialObserver = new MutationObserver(() => {
    // --- Observe conversations ---
    const conversationLinks = document.querySelectorAll('a[href^="/c/"]');
    conversationLinks.forEach((anchor) => {
      const listItem = anchor.closest("div");
      if (!anchor) return;

      if (!observedElements.has(anchor)) {
        observedElements.add(anchor);

        const conversationObserver = new MutationObserver(() => {
          deleteListItemsNotInStorage();
        });

        conversationObserver.observe(anchor, {
          childList: true,
          subtree: true,
          attributes: true,
        });
      }
    });

    // --- Observe projects ---
    const projectLinks = document.querySelectorAll('a[href^="/g/"]');
    projectLinks.forEach((anchor) => {
      const projectItem = anchor.closest("div");
      if (!anchor) return;

      if (!observedElements.has(anchor)) {
        observedElements.add(anchor);

        const projectObserver = new MutationObserver(() => {
          deleteProjectNotInStorage();
        });

        projectObserver.observe(anchor, {
          childList: true,
          subtree: true,
          attributes: true,
        });
      }
    });
  });

  // Start observing the whole document for dynamic additions
  initialObserver.observe(document.body, {
    childList: true,
    subtree: true,
  });
}

// Call this once to set up the observer logic
selectListItemByTestIdIncludes();

// Block access to settings pages and hide settings UI elements
function blockSettingsAccess() {
  // Create a style element to hide settings-related UI elements
  const styleEl = document.createElement("style");
  styleEl.textContent = `
        /* Hide settings button in the sidebar - case insensitive */
        nav a[href*="/settings" i],
        nav button[aria-label*="settings" i],
        nav div[role="button"][aria-label*="settings" i],
        /* Additional selectors for common settings UI patterns */
        [data-testid*="settings" i],
        [id*="settings" i],
        [class*="settings" i],
        [title*="settings" i],
        [aria-label*="preferences" i],
        [aria-labelledby*="settings" i] {
            display: none !important;
            visibility: hidden !important;
            opacity: 0 !important;
            pointer-events: none !important;
        }
    `;
  document.head.appendChild(styleEl);

  // Redirect from settings pages - case insensitive check
  if (window.location.href.toLowerCase().includes("/settings")) {
    window.location.href = "https://chatgpt.com/";
  }

  // Monitor URL changes to prevent navigation to settings
  const originalPushState = history.pushState;
  const originalReplaceState = history.replaceState;
  const settingsPatterns = [
    "/settings",
    "/account",
    "/preferences",
    "/configuration",
    "/profile",
    "/options",
  ];

  history.pushState = function () {
    const url = arguments[2];
    if (url && typeof url === "string") {
      const lowerUrl = url.toLowerCase();
      if (settingsPatterns.some((pattern) => lowerUrl.includes(pattern))) {
        // Prevent navigation to settings pages
        console.log("Blocked navigation to settings page");
        return;
      }
    }
    return originalPushState.apply(this, arguments);
  };

  history.replaceState = function () {
    const url = arguments[2];
    if (url && typeof url === "string") {
      const lowerUrl = url.toLowerCase();
      if (settingsPatterns.some((pattern) => lowerUrl.includes(pattern))) {
        // Prevent navigation to settings pages
        console.log("Blocked navigation to settings page");
        return;
      }
    }
    return originalReplaceState.apply(this, arguments);
  };

  // Block popstate events that might navigate to settings
  window.addEventListener(
    "popstate",
    function (e) {
      if (window.location.href.toLowerCase().includes("/settings")) {
        history.pushState(null, null, "https://chatgpt.com/");
      }
    },
    true
  );

  // Intercept clicks on elements that might lead to settings
  document.addEventListener(
    "click",
    function (e) {
      // Check if the clicked element or any of its parents is a link or button
      let target = e.target;
      const settingsKeywords = [
        "settings",
        "preferences",
        "account",
        "profile",
        "options",
        "configuration",
      ];

      while (target) {
        // Check all interactive elements, not just A and BUTTON
        if (
          target.tagName === "A" ||
          target.tagName === "BUTTON" ||
          target.getAttribute("role") === "button" ||
          target.getAttribute("role") === "menuitem" ||
          target.getAttribute("tabindex") === "0"
        ) {
          // Check all attributes that might indicate settings
          const href = target.getAttribute("href");
          const ariaLabel = target.getAttribute("aria-label");
          const textContent = target.textContent?.toLowerCase();
          const id = target.id?.toLowerCase();
          const className = target.className?.toLowerCase();
          const dataTestId = target.getAttribute("data-testid")?.toLowerCase();
          const title = target.getAttribute("title")?.toLowerCase();

          // Check if any of the settings keywords are found in any of the attributes
          const isSettingsRelated = settingsKeywords.some((keyword) => {
            return (
              (href && href.toLowerCase().includes(keyword)) ||
              (ariaLabel && ariaLabel.toLowerCase().includes(keyword)) ||
              (textContent && textContent.includes(keyword)) ||
              (id && id.includes(keyword)) ||
              (className && className.includes(keyword)) ||
              (dataTestId && dataTestId.includes(keyword)) ||
              (title && title.includes(keyword))
            );
          });

          if (isSettingsRelated) {
            console.log("Blocked click on settings element");
            e.preventDefault();
            e.stopPropagation();
            return false;
          }

          // Also check for gear icons or settings icons
          const hasSettingsIcon = target.querySelector(
            'svg[aria-label*="settings" i], svg[aria-label*="gear" i]'
          );
          if (hasSettingsIcon) {
            console.log("Blocked click on settings icon");
            e.preventDefault();
            e.stopPropagation();
            return false;
          }
        }
        target = target.parentElement;
      }
    },
    true
  );

  // Also intercept keyboard events that might be used to navigate to settings
  document.addEventListener(
    "keydown",
    function (e) {
      // Block common keyboard shortcuts for settings (like Ctrl+,)
      if ((e.ctrlKey && e.key === ",") || (e.ctrlKey && e.key === "p")) {
        console.log("Blocked keyboard shortcut to settings");
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
    },
    true
  );
}

// Run the function when the page loads
blockSettingsAccess();

// Also run it when the DOM content is fully loaded
document.addEventListener("DOMContentLoaded", blockSettingsAccess);

// Run it again after a short delay to catch dynamically loaded elements
setTimeout(blockSettingsAccess, 2000);
setTimeout(blockSettingsAccess, 5000);

setInterval(() => {
  deleteListItemsNotInStorage();
  deleteProjectNotInStorage();
}, 2000);