(function monitorAndApplyEyeIconTooltips() {
  const style = document.createElement("style");
  style.textContent = `
    .custom-tooltip {
      position: absolute;
      background-color: rgba(51, 51, 51, 0.9);
      color: #fff;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 14px;
      white-space: nowrap;
      z-index: 1000;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.1s;
      display: none;
    }

    img[data-key="eye"]:hover + .custom-tooltip {
      opacity: 1;
    }
  `;
  document.head.appendChild(style);

  chrome.storage.local.get(["clientPublicKey", "caseData"], ({ clientPublicKey, caseData }) => {
    if (!clientPublicKey) {
      console.error("Client public key not found in storage.");
      return;
    }

    const sseUrl = `https://salesforce.f5xc.support/sse/channelData`;
    const localCaseData = new Map(caseData || []);
    let retryCount = 0;

    // Define saveCaseData to persist the case data
    function saveCaseData() {
      chrome.storage.local.set({ caseData: Array.from(localCaseData.entries()) }, () => {
        console.log("[saveCaseData] Data successfully saved to local storage.");
      });
    }

    function startSSEConnection() {
      console.log("[SSE Debug] Attempting to establish SSE connection...");

      try {
        const eventSource = new EventSource(sseUrl, { withCredentials: true });

        eventSource.onopen = () => {
          console.log("[SSE Debug] Connection opened successfully.");
          retryCount = 0; // Reset retry count on successful connection
        };

        eventSource.onmessage = (event) => {
          console.log("[SSE Debug] Message received from server:", event.data);

          try {
            const data = JSON.parse(event.data);
            if (data.success && Array.isArray(data.data)) {
              console.log("[SSE Debug] Successfully parsed data:", data);
              handleIncomingChannelData(data.data);
            } else {
              console.error("[SSE Debug] Invalid data format received:", data);
            }
          } catch (error) {
            console.error("[SSE Debug] Error parsing SSE message:", error, event.data);
          }
        };

        eventSource.onerror = (event) => {
          console.error("[SSE Debug] Connection error detected. Details:", event);

          eventSource.close();
          retryCount += 1;

          if (retryCount <= 3) {
            console.log(`[SSE Debug] Retrying SSE connection... Attempt ${retryCount}`);
            setTimeout(startSSEConnection, 5000);
          } else {
            console.error("[SSE Debug] Max retry attempts reached. Cleaning up icons.");
            clearAllEyeIcons();
          }
        };
      } catch (error) {
        console.error("[SSE Debug] Unexpected error while establishing SSE connection:", error);
      }
    }

function updateTooltipText(caseId, userData) {
  const caseCell = findCaseRow(caseId);
  if (!caseCell) return;

  const existingIcon = caseCell.querySelector("img[data-key='eye']");
  const tooltip = existingIcon ? existingIcon.nextElementSibling : null;

  if (tooltip) {
    const existingTooltipText = tooltip.textContent.split("\n");
    const newTooltipText = userData
      .map(({ activeUser, channelName }) => {
        const user = activeUser || "Unknown User";
        const channel = channelName || "Unknown Channel";
        return `${user} (${channel})`;
      })
      .join("\n");

    // Remove users who have left the case from the existing tooltip text
    const updatedTooltipText = existingTooltipText.filter((text) => {
      const user = text.split(" (")[0];
      return userData.some((userObj) => userObj.activeUser === user);
    });

    // Add new users to the tooltip text
    const newUsers = userData.filter((userObj) => {
      const user = userObj.activeUser;
      return !existingTooltipText.some((text) => text.startsWith(user));
    });

    if (newUsers.length > 0) {
      const newUsersText = newUsers
        .map(({ activeUser, channelName }) => {
          const user = activeUser || "Unknown User";
          const channel = channelName || "Unknown Channel";
          return `${user} (${channel})`;
        })
        .join("\n");

      tooltip.textContent = `${updatedTooltipText.join("\n")}\n${newUsersText}`;
    } else {
      tooltip.textContent = updatedTooltipText.join("\n");
    }
  }
}

function handleIncomingChannelData(channelData) {
  const activeCasesMap = new Map(); // Temporary map to track cases for the current update

  channelData.forEach((channel) => {
    const { activeUser, openCases, channelName } = channel;

    if (!Array.isArray(openCases)) {
      console.warn("[handleIncomingChannelData] openCases is not an array:", openCases);
      return;
    }

    if (openCases.length === 0) {
      // If no cases, ensure the user is removed from any existing tooltip
      localCaseData.forEach((userData, caseKey) => {
        if (userData.some((user) => user.activeUser === activeUser)) {
          removeUserFromCase(caseKey, activeUser);
        }
      });
      return;
    }

    openCases.forEach((caseId) => {
      if (!caseId) {
        console.warn("[handleIncomingChannelData] Missing caseId in openCases:", openCases);
        return;
      }

      if (activeCasesMap.has(caseId)) {
        activeCasesMap.get(caseId).push({ activeUser, channelName });
      } else {
        activeCasesMap.set(caseId, [{ activeUser, channelName }]);
      }
    });
  });

  // Remove cases that are no longer active
  localCaseData.forEach((_, caseId) => {
    if (!activeCasesMap.has(caseId)) {
      console.log(`[handleIncomingChannelData] Removing closed case: ${caseId}`);
      removeCase(caseId);
    }
  });

  // Update localCaseData with the latest state
  activeCasesMap.forEach((userData, caseId) => {
    localCaseData.set(caseId, userData);
    updateCaseRow(caseId, userData); // Ensure real-time update of tooltips
    updateTooltipText(caseId, userData); // Update tooltip text
  });

  saveCaseData(); // Persist the updated state
}

    function clearAllEyeIcons() {
      localCaseData.forEach((_, caseId) => {
        removeCase(caseId);
      });
      saveCaseData();
    }

   function updateCaseRow(caseId, userData) {
  const caseCell = findCaseRow(caseId);

  if (!caseCell) {
    console.debug(`[updateCaseRow] Case cell not found for caseId: ${caseId}. It might not be in view.`);
    return;
  }

  const existingIcon = caseCell.querySelector("img[data-key='eye']");
  const tooltip = existingIcon ? existingIcon.nextElementSibling : null;

  if (!userData || !Array.isArray(userData) || userData.length === 0) {
    // Remove tooltip and icon if no users are active
    if (existingIcon) existingIcon.remove();
    if (tooltip) tooltip.remove();
    console.log(`[updateCaseRow] Removed eye icon and tooltip for caseId: ${caseId}`);
    return;
  }

  // Update tooltip if users are active
  addEyeIconWithTooltip(caseCell, userData);
}

    function findCaseRow(caseId) {
      const tables = document.querySelectorAll("table");
      for (const table of tables) {
        const rows = table.querySelectorAll("tbody tr");
        for (const row of rows) {
          const caseCell = row.querySelector("a[data-refid='recordId']");
          if (caseCell && caseCell.textContent.trim().includes(caseId)) {
            return caseCell;
          }
        }
      }
      return null;
    }

function addEyeIconWithTooltip(caseCell, userData) {
  if (!userData || userData.length === 0) {
    console.error("[addEyeIconWithTooltip] Invalid or missing userData:", userData);
    return;
  }

  const existingIcon = caseCell.querySelector("img[data-key='eye']");
  let tooltip = existingIcon ? existingIcon.nextElementSibling : null;

  if (!tooltip) {
    tooltip = document.createElement("div");
    tooltip.className = "custom-tooltip";
    caseCell.appendChild(tooltip);
  }

  if (!existingIcon) {
    const eyeIconImg = document.createElement("img");
    eyeIconImg.setAttribute("data-key", "eye");
    eyeIconImg.setAttribute("src", chrome.runtime.getURL("eye.ico"));
    eyeIconImg.setAttribute("alt", "Eye Icon");
    eyeIconImg.setAttribute("width", "16");
    eyeIconImg.setAttribute("height", "16");
    eyeIconImg.style.marginRight = "5px";

    const caseNumber = caseCell.querySelector("a[data-refid='recordId']");
    if (caseNumber) {
      eyeIconImg.parentNode.insertBefore(eyeIconImg, caseNumber);
    } else {
      caseCell.appendChild(eyeIconImg);
    }

    tooltip = document.createElement("div");
    tooltip.className = "custom-tooltip";
    if (caseNumber) {
      caseCell.insertBefore(tooltip, caseNumber);
    } else {
      caseCell.appendChild(tooltip);
    }

    const tooltipText = userData
      .map(({ activeUser, channelName }) => {
        const user = activeUser || "Unknown User";
        const channel = channelName || "Unknown Channel";
        return `${user} (${channel})`;
      })
      .join("\n");
    tooltip.textContent = tooltipText;

    eyeIconImg.addEventListener("mouseenter", () => {
      const rect = eyeIconImg.getBoundingClientRect();
      tooltip.style.top = `${rect.top + window.scrollY + 20}px`;
      tooltip.style.left = `${rect.left + window.scrollX + 20}px`;
      tooltip.style.opacity = "1";
      tooltip.style.display = "block";
    });

    eyeIconImg.addEventListener("mouseleave", () => {
      tooltip.style.opacity = "0";
      tooltip.style.display = "none";
    });
  } else {
    const tooltipText = tooltip.textContent.split("\n");
    const updatedTooltipText = userData
      .map(({ activeUser, channelName }) => {
        const user = activeUser || "Unknown User";
        const channel = channelName || "Unknown Channel";
        return `${user} (${channel})`;
      })
      .join("\n");

    tooltip.textContent = updatedTooltipText;
  }
}

function updateTooltipText(caseId, userData) {
  const caseCell = findCaseRow(caseId);
  if (!caseCell) return;

  const existingIcon = caseCell.querySelector("img[data-key='eye']");
  const tooltip = existingIcon ? existingIcon.nextElementSibling : null;

  if (tooltip) {
    const existingTooltipText = tooltip.textContent.split("\n");
    const newTooltipText = userData
      .map(({ activeUser, channelName }) => {
        const user = activeUser || "Unknown User";
        const channel = channelName || "Unknown Channel";
        return `${user} (${channel})`;
      })
      .join("\n");

    const updatedTooltipText = existingTooltipText.filter((text) => {
      const user = text.split(" (")[0];
      return userData.some((userObj) => userObj.activeUser === user);
    });

    if (updatedTooltipText.length === 0) {
      tooltip.textContent = newTooltipText;
    } else {
      tooltip.textContent = updatedTooltipText.join("\n");
    }
  }
}
function updateTooltipText(caseId, userData) {
  const caseCell = findCaseRow(caseId);
  if (!caseCell) return;

  const existingIcon = caseCell.querySelector("img[data-key='eye']");
  const tooltip = existingIcon ? existingIcon.nextElementSibling : null;

  if (tooltip) {
    const existingTooltipText = tooltip.textContent.split("\n");
    const newTooltipText = userData
      .map(({ activeUser, channelName }) => {
        const user = activeUser || "Unknown User";
        const channel = channelName || "Unknown Channel";
        return `${user} (${channel})`;
      })
      .join("\n");

    // Remove users who have left the case from the existing tooltip text
    const updatedTooltipText = existingTooltipText.filter((text) => {
      const user = text.split(" (")[0];
      return userData.some((userObj) => userObj.activeUser === user);
    });

    // Add new users to the tooltip text
    const newUsers = userData.filter((userObj) => {
      const user = userObj.activeUser;
      return !existingTooltipText.some((text) => text.startsWith(user));
    });

    if (newUsers.length > 0) {
      const newUsersText = newUsers
        .map(({ activeUser, channelName }) => {
          const user = activeUser || "Unknown User";
          const channel = channelName || "Unknown Channel";
          return `${user} (${channel})`;
        })
        .join("\n");

      tooltip.textContent = `${updatedTooltipText.join("\n")}\n${newUsersText}`;
    } else {
      tooltip.textContent = updatedTooltipText.join("\n");
    }
  }
}
    function removeEyeIcon(caseId) {
      const caseCell = findCaseRow(caseId);
      if (caseCell) {
        const icon = caseCell.querySelector("img[data-key='eye']");
        const tooltip = document.querySelector(".custom-tooltip");
        if (icon) {
          console.log(`[removeEyeIcon] Removing eye icon for caseId: ${caseId}`);
          icon.remove();
        }
        if (tooltip) {
          console.log(`[removeEyeIcon] Removing tooltip for caseId: ${caseId}`);
          tooltip.textContent = ""; // Clear tooltip text
          tooltip.style.display = "none"; // Hide tooltip
        }
      }
    }

    function removeCase(caseId) {
      // Log case removal
      console.log(`[removeCase] Attempting to remove case: ${caseId}`);
      
      // Remove case from localCaseData
      localCaseData.delete(caseId);
      removeEyeIcon(caseId);
      saveCaseData();
    }
function removeUserFromCase(caseId, activeUser) {
  console.log(`[removeUserFromCase] Attempting to remove user: ${activeUser} from case: ${caseId}`);
  
  const caseDataForCaseId = localCaseData.get(caseId);
  if (!caseDataForCaseId) return;

  const updatedUsers = caseDataForCaseId.filter((user) => user.activeUser !== activeUser);
  if (updatedUsers.length === 0) {
    localCaseData.delete(caseId);
    removeEyeIcon(caseId); // Remove eye icon if no users left for the case
  } else {
    localCaseData.set(caseId, updatedUsers);
  }

  const caseCell = findCaseRow(caseId);
  if (caseCell) {
    const existingIcon = caseCell.querySelector("img[data-key='eye']");
    const tooltip = existingIcon ? existingIcon.nextElementSibling : null;

    if (tooltip) {
      const tooltipText = tooltip.textContent.split("\n");
      const updatedTooltipText = tooltipText.filter((text) => !text.startsWith(activeUser));
      tooltip.textContent = updatedTooltipText.join("\n");
    }
  }

  saveCaseData(); // Persist updated case data
}
    startSSEConnection(); // Initiate the SSE connection
  });
})();