let client;
init();

async function init() {
  console.log("Initializing app...");
  await new Promise((resolve) => setTimeout(resolve, 100)); 
  client = await app.initialized();

  client.events.on("app.activated", async function () {
    console.log(" App activated! Calling RoleAccess...");
    await RoleAccess();
  });
}


let newRulePloadDB5; 
const duplicates = [];
let type1 = 0;
let type3 = 0;
let type4 = 0;
let storedvalue;

let counthourly = 0;
let countupdates = 0;
let countcreate = 0;
let isFetching = false; 
let isFetchingHourly = false;
let isFetchingType4 = false; 
let isFetchingType3 = false; 
let currentRuleId = null;
let currentAutomationId = null;
let globalAgents = []; 
let isFetchingRules = false; 


const automationTypeIdOneRecords = [];
const automationTypeIdfourRecords = [];
const automationTypeIdthreeRecords = [];


let entitytype4 = [];
let entitytype1 = [];
let entitytype3 = [];

  const duplicatesType1 = [];
  const duplicatesType3 = [];
  const duplicatesType4 = [];

  let sessionTabStore = {};
  let activeTab;


  async function setupTabListener(tabContainerId, sharedKey) {
      while (typeof client === "undefined") {
          console.warn("⚠️ Waiting for 'client' to be ready...");
          await new Promise((resolve) => setTimeout(resolve, 500));
      }
  
      let fwTabs = document.querySelector(`#${tabContainerId} fw-tabs`);
  
      if (!fwTabs) {
          console.error(`❌ ERROR: <fw-tabs> NOT found inside #${tabContainerId}!`);
          return;
      }
  
      console.log(`✅ Found <fw-tabs> inside #${tabContainerId}. Attaching event listener...`);
  
      let savedTab = sessionTabStore[sharedKey] || "Ticket Creation";
  
      let tabElement = fwTabs.querySelector(`fw-tab[panel='${savedTab}']`);
      let pageContainer = document.getElementById(tabContainerId);
  
      if (tabElement) {
          if (pageContainer.style.display !== "none") {
              console.log(`✅ Restoring tab: ${savedTab}`);
              tabElement.click();
          } else {
              console.warn(`⚠️ Page #${tabContainerId} hidden. Waiting to restore tab:`, savedTab);
  
              const observer = new MutationObserver((mutationsList, observer) => {
                  for (let mutation of mutationsList) {
                      if (mutation.attributeName === "style" && pageContainer.style.display !== "none") {
                          console.log(`✅ Page visible now. Restoring tab:`, savedTab);
                          tabElement.click();
                          observer.disconnect();
                      }
                  }
              });
  
              observer.observe(pageContainer, { attributes: true });
          }
      } else {
          console.warn(`⚠️ Saved tab not found in DOM:`, savedTab);
      }
  
      fwTabs.addEventListener("fwChange", (event) => {
          let tabIndex = event.detail.tabIndex;
          let tabs = fwTabs.querySelectorAll("fw-tab");
  
          if (tabs[tabIndex]) {
               activeTab = tabs[tabIndex].getAttribute("panel");
              console.log(`🟢 Active tab changed to: ${activeTab}`);
              sessionTabStore[sharedKey] = activeTab; 
          } else {
              console.warn(`⚠️ No active tab found at index ${tabIndex}`);
          }
      });
  }
  

  document.addEventListener("DOMContentLoaded", async () => {
    console.log("📌 Page Loaded! Restoring last visited tab (from memory)...");
    await setupTabListener("Automation-page", "LastVisitedTab");
  });


document.addEventListener("DOMContentLoaded", function () {
  let progressBar = document.getElementById("progress-container");

  if (progressBar) {
    
      progressBar.style.transition = "width 0.2s linear, opacity 0.3s"; 
      progressBar.style.width = "0%"; 
      progressBar.style.height = "3px"; 
    
      progressBar.style.opacity = "0";

      progressBar.start = function () {
          progressBar.style.width = "70%"; 
          progressBar.style.opacity = "1";
      };

      progressBar.done = function () {
          progressBar.style.width = "100%";
          setTimeout(() => {
              progressBar.style.width = "0%"; 
              progressBar.style.opacity = "0";
          }, 1000); 
      };
  } else {
      console.error("❌ Progress bar element not found!");
  }
});

  function createLoadingBanner(targetElementId) {
    console.log("main banner function called");
 
    if (document.getElementById("loadingBanner")) return;
  

    let banner = document.createElement("div");
    banner.id = "loadingBanner";
    banner.className = "loading-banner";
      
banner.innerHTML = `⚠️ The system is still processing additional data. Please wait...
<span class="loading-spinner"></span>`;

setTimeout(() => {
document.querySelector('.loading-spinner').style.animation = 'spin 1s linear infinite';
}, 10);
  

    banner.style.position = "fixed";
    banner.style.top = "20px";
    banner.style.right = "700px";
    banner.style.backgroundColor =" #fff3cd";
    banner.style.padding = "12px";
    banner.style.borderRadius = "5px";
    banner.style.boxShadow = "0px 2px 5px rgba(0,0,0,0.2)";
    banner.style.display = "none"; 
    banner.style.color =" #856404";
  
 
    let targetElement = document.getElementById(targetElementId);
    if (targetElement) {
      targetElement.appendChild(banner);
    } else {
      document.body.appendChild(banner); 
    }
  }
  function showLoadingBanner() {
    console.log("showbanner called")
    let banner = document.getElementById("loadingBanner");
    if (banner) banner.style.display = "block";
  }
  
  function hideLoadingBanner() {
    console.log("hidebanner called")
    let banner = document.getElementById("loadingBanner");
    if (banner) banner.style.display = "none";
  }
    
  function removeLoadingBanner() {
    console.log("remove banner called")
    let banner = document.getElementById("loadingBanner");
    if (banner) {
        banner.remove(); 
        console.log("✅ Loading banner removed permanently.");
    }
}




async function RoleAccess() {
  try {
    let iparamSelectedCategory = await client.iparams.get();
    console.log("🔍 iparamSelectedCategory:", iparamSelectedCategory);

    let selectedCategoryArray = iparamSelectedCategory.accessvalue || [];
    let fdFields = iparamSelectedCategory.fd_fields; 

    if (!Array.isArray(selectedCategoryArray)) {
      console.error("❌ accessvalue is not an array", selectedCategoryArray);
      return;
    }

    selectedCategoryArray = selectedCategoryArray.map(value => value.toString().trim());

    console.log("✅ Formatted selectedCategoryArray:", selectedCategoryArray);

    const contactData = await client.data.get("loggedInUser");
    console.log("👤 Logged-in user data:", contactData);

    let loggedInAgentIdStr = contactData.loggedInUser.id.toString().trim();
    let loggedInGroupsStr = (contactData.loggedInUser.group_ids || []).map(g => g.toString().trim());
    let loggedInRolesStr = (contactData.loggedInUser.role_ids || []).map(r => r.toString().trim());

    console.log("🔹 loggedInAgentIdStr:", loggedInAgentIdStr);
    console.log("🔹 loggedInGroupsStr:", loggedInGroupsStr);
    console.log("🔹 loggedInRolesStr:", loggedInRolesStr);
    console.log("🔹 fdFields:", fdFields);

    let hasAccess = false;

    if (fdFields === "agent") {
      console.log("🔍 Checking agent access...");
      hasAccess = selectedCategoryArray.includes(loggedInAgentIdStr);
    } else if (fdFields === "role") {
      console.log("🔍 Checking role access...");
      hasAccess = loggedInRolesStr.some(role => selectedCategoryArray.includes(role));
    } else if (fdFields === "group") {
      console.log("🔍 Checking group access...");
      hasAccess = loggedInGroupsStr.some(group => selectedCategoryArray.includes(group));
    } else {
      console.error("❌ Unknown fd_fields value:", fdFields);
    }

    console.log("🔹 Final hasAccess:", hasAccess);

    if (hasAccess) {
      console.log("Access granted! Initializing UI...");
      document.getElementById("loader").style.display = "none";
      document.getElementById("Automation-page").style.display = "block";
      document.getElementById("no_user").style.display = "none";
      
      setTimeout(async () => {
        await checkAndSetButtonState(1,'Ticketcreation');
      }, 1000);
      
    
    }
    else {
      console.log(" Access denied! Hiding automation page...");
      document.getElementById("Automation-page").style.display = "none";
      document.getElementById("no_user").style.display = "block";
    }
  } catch (error) {
    console.error(" Error in RoleAccess function:", error);
  }
}
let intervalId;
let storedvalue1;
async function checkAndSetButtonState(data, containerid) {
  try {
      
    let storedvalue1 = await client.db.get("RulesDB");
  
    localStorage.setItem("checkState_data", JSON.stringify(data));
    localStorage.setItem("checkState_containerid", containerid);

    console.log("automationtypeid inside checkAndSetButtonState",data);
  
    console.log("Initially stored all value from RulesDB:", storedvalue1);
    console.log("creationtotal",storedvalue1.creationTotal);
    console.log("hourlyTotal",storedvalue1.hourlyTotal);
    console.log("updateTotal",storedvalue1.updateTotal);
    console.log("Initial stored true/false value from RulesDB:", storedvalue1.stored);
  

    if (
      storedvalue1.creationTotal === 0 ||
      storedvalue1.hourlyTotal === 0 ||
      storedvalue1.updateTotal === 0
    ) {
      await initializeDatabase();

      switch (activeTab) {
        case "Ticket Creation":
          if ( storedvalue1.creationTotal === 0)
           {   handleDuplicateRulestype(1);

           }
           else{

            showLoader("Ticketcreation");
           } 
          
  
          break;
        case "Ticket Updates":
          if ( storedvalue1.updateTotal === 0){
          handleDuplicateRulestype(4);
          } else{

            showLoader("TicketUpdates");
           } 
          break;
        case "Hourly Triggers":
          if ( storedvalue1.hourlyTotal === 0){
          handleDuplicateRulestype(3);} else{

            showLoader("HourlyTriggers");
           } 
          break;
        default:
          console.warn("⚠️ Unknown tab type:", activeTab);
      }
    } else {
      if (containerid === "Ticketcreation") {
        showLoader("Ticketcreation");
      } else if (containerid === "TicketUpdates") {
        showLoader("TicketUpdates");
      } else if (containerid === "HourlyTriggers") {
        showLoader("HourlyTriggers");
      }
    }

    const isButtonEnabled = !!storedvalue1.stored;
    const button = document.querySelector("fw-button");

    if (!isButtonEnabled) {
      createLoadingBanner("banner");
      showLoadingBanner();
    }

    if (button) {
      button.disabled = !isButtonEnabled;
      console.log(`Button is now ${isButtonEnabled ? "ENABLED" : "DISABLED"}`);
    }

    if (isButtonEnabled) {
      hideLoadingBanner();
      removeLoadingBanner();
      console.log("✅ Loading banner removed.");
      clearInterval(intervalId);
      return;
    }

    // ✅ Retrieve from localStorage
    if (!intervalId) {
      intervalId = setInterval(() => {
        const savedData = JSON.parse(localStorage.getItem("checkState_data"));
        const savedContainerId = localStorage.getItem("checkState_containerid");
        checkAndSetButtonState(savedData, savedContainerId);
      }, 60000);
    }

  } catch (error) {
    if (error.status === 404) {
      console.warn("⚠️ RulesDB not found, assuming first-time install.");
      const button = document.querySelector("fw-button");
      if (button) {
        button.disabled = true;
      }
    } else {
      console.error("❌ Error retrieving stored value from RulesDB:", error);
    }
  }
}

// async function checkAndSetButtonState() {
//   try {
    
//     let storedvalue1 = await client.db.get("RulesDB");
//     console.log("Initially stored all value from RulesDB:", storedvalue1);
//     console.log("creationtotal",storedvalue1.creationTotal);
//     console.log("hourlyTotal",storedvalue1.hourlyTotal);
//     console.log("updateTotal",storedvalue1.updateTotal);
//     console.log("Initial stored true/false value from RulesDB:", storedvalue1.stored);
//     const isButtonEnabled = !!storedvalue1.stored;

   
//     const button = document.querySelector("fw-button");

   
//     if (!isButtonEnabled) {
//       createLoadingBanner("banner");
//       showLoadingBanner();
//     }

  
//     if (button) {
//       button.disabled = !isButtonEnabled;
//       console.log(`Button is now ${isButtonEnabled ? "ENABLED" : "DISABLED"}`);
//     }

   
//     if (isButtonEnabled) {
//       hideLoadingBanner();
//       removeLoadingBanner();
//       console.log("✅ Loading banner removed.");
//       clearInterval(intervalId); 
//       return;
//     }

//     if (!intervalId) {
//       intervalId = setInterval(checkAndSetButtonState, 60000);
//     }

//   } catch (error) {
//     if (error.status === 404) {
//       console.warn("⚠️ RulesDB not found, assuming first-time install.");
//       const button = document.querySelector("fw-button");
//       if (button) {
//         button.disabled = true;
//       }
//     } else {
//       console.error("❌ Error retrieving stored value from RulesDB:", error);
//     }
//   }
// }




async function initializeDatabase() {
  try {
    console.log("Initializing database...");
    const entity = await client.db.entity({ version: "v1" });
    console.log("Entity Initialized:", entity);

    
   
    newRulePloadDB5 = entity.get("newRulePloadDB5");
    console.log("📌 Entity Reference:", newRulePloadDB5);

  
    const data1 = await newRulePloadDB5.schema();
    console.log("📄 Schema Data:", data1);

  } catch (error) {
    console.error("❌ Error initializing database:", error);
  }
}

let recentcount = 0;
let agentcount = 0;
async function recentdata() {
  console.log("recentdata called");
  console.log(` Setting up Workflow-Automation-page...`);
  await setupTabListener("Workflow-Automation-page", "LastVisitedTab");

  hideLoadingBanner();
  if(agentcount === 0){
    await  GetAgents().then(agents => {
      console.log("✅ Agents fetching completed. Final List:", agents);
      globalAgents = agents; 
      console.log("🔍 Checking globalAgents before function call:", globalAgents);
      
    });
    agentcount++;
  }
 
  document.getElementById("Automation-page").style.display = "none";
  document.getElementById("button").style.display = "none";
  document.getElementById("main-container1").style.display = "block";
  

  if(recentcount === 0){
   
    let workflowPage = document.getElementById("Workflow-Automation-page");
    if (workflowPage) {
      workflowPage.style.visibility = "visible"; 
      workflowPage.style.opacity = "1"; 
    } else {
      console.error("❌ Still not found!");
    }
    recentcount++;
  }else{
   
  document.getElementById("Workflow-Automation-page").style.display = "block";
  document.getElementById("button1").style.display = "block";

  }
      

 console.log("recentdata function completes");


  
}
async function entitydata(){
  isFetchingHourly = false;
  counthourly = 0;
  isFetching = false;
  countupdates = 0;
  isFetchingRules= false;
   countcreate  = 0;
  
document.getElementById("Ticketcreation1").innerHTML = "";
  document.getElementById("TicketUpdates1").innerHTML = "";
  document.getElementById("HourlyTriggers1").innerHTML = "";
  automationTypeIdOneRecords.length = 0;
  duplicatesType1.length = 0;
  console.log(" empty array of type3 records ",automationTypeIdOneRecords);
  console.log(" empty array inside finally block log ",duplicatesType1);

  automationTypeIdthreeRecords.length = 0;
  duplicatesType3.length = 0;
  console.log(" empty array of type3 records ",automationTypeIdthreeRecords);
  console.log(" empty array inside finally block log ",duplicatesType3);
  console.log("array inside finally block log",duplicatesType4);

  automationTypeIdfourRecords.length = 0;
  duplicatesType4.length = 0;
  console.log(" empty array of type3 records ",automationTypeIdfourRecords);
  console.log(" empty array inside finally block log ",duplicatesType4);

  document.getElementById("Workflow-Automation-page").style.display = "none";
  document.getElementById("button1").style.display = "none";
  
  document.getElementById("Automation-page").style.display = "block";
  document.getElementById("button").style.display = "block";
  await setupTabListener("Automation-page", "LastVisitedTab");
  

 }


async function GetAgents(page = 1, agentsArray = []) {
  console.log(`Fetching agents for page ${page}`);

  try {
      const GetAgentsResponse = await client.request.invokeTemplate('recentagents', {
          context: { page: page }
      });

      const responses = GetAgentsResponse.response;
      const agentData = JSON.parse(responses);

      if (agentData.length === 0) {
          console.log("✅ No more agents to fetch. Total agents:", agentsArray.length);
          return agentsArray;
      }

      agentsArray.push(...agentData);

      
      return await GetAgents(page + 1, agentsArray);

  } catch (error) {
      console.error("❌ Error fetching agents:", error);

      if (error.headers && error.headers.status.includes("401")) {  
          document.getElementById("Automation-page").style.display = "none";
          document.getElementById("Workflow-Automation-page").style.display = "none";
          document.getElementById("no_user2").style.display = "block";
      }

      return agentsArray; 
  }
}


function showLoader(containerId) {
  console.log("showLoader called for container:", containerId);

  const container = document.getElementById(containerId);
  let spinnerContainer = document.getElementById("spinner-container");


  if (!container) {
    console.error("Target container not found:", containerId);
    return;
  }

  if (!spinnerContainer) {
    console.log("Spinner container not found, creating new one.");
    spinnerContainer = document.createElement("div");
    spinnerContainer.id = "spinner-container";
    spinnerContainer.innerHTML = `<fw-spinner id="spinner" class="spinner" size="large"></fw-spinner>`;
    document.body.appendChild(spinnerContainer);
  }

 
  if (!container.contains(spinnerContainer)) {
    console.log("Appending spinner to container:", containerId);
    container.appendChild(spinnerContainer);
  }


  spinnerContainer.classList.add("show");
}

function hideLoader() {
  const spinnerContainer = document.getElementById("spinner-container");
  if (spinnerContainer) {
 
    spinnerContainer.classList.remove("show");
  }
}






async function fetchAndUseRules(automation_type_id) {
  console.log("data", automation_type_id);
  console.log("fetchAndUseRules() called", isFetchingRules, countcreate);

  if (automation_type_id === 1) {
    if (isFetchingRules || countcreate > 0) return;

    isFetchingRules = true;
    

    try {
      console.log("Before showing spinner: ", document.getElementById("spinner-container"));
      showLoader("Ticketcreation1");
      console.log("After showing spinner: ", document.getElementById("spinner-container"));
      
      const allRules = await listrules();
      console.log("Ticket Creation Rules:", allRules);

      allRules.forEach(rule => {
        if (rule.active) automationTypeIdOneRecords.push(rule);
      });

      console.log("automationTypeIdOneRecords", automationTypeIdOneRecords);
      findDuplicatesWithinType(automationTypeIdOneRecords, duplicatesType1);
      console.log("Duplicate Records for Automation Type ID 1:", duplicatesType1);

      displayGroupedRules4(duplicatesType1, "Ticketcreation1", 1, globalAgents);
      countcreate++;
    } catch (error) {
      console.error("❌ Error fetching rules:", error);
      handleError(error);
    } finally {
      hideLoader("Ticketcreation1");
      isFetchingRules = false;
    }

  } else if (automation_type_id === 3) {
    if (isFetchingHourly || counthourly > 0) return;

    isFetchingHourly = true;
    console.log("hourlycount at start", counthourly);

    showLoader("HourlyTriggers1");

    try {
      const hourlyRules = await listhourlyrules();
      console.log("Hourly Rules:", hourlyRules);

      hourlyRules.forEach(rule => {
        if (rule.active) automationTypeIdthreeRecords.push(rule);
      });

      console.log("automationTypeIdthreeRecords", automationTypeIdthreeRecords);
      findDuplicatesWithinType(automationTypeIdthreeRecords, duplicatesType3);
      console.log("Duplicate Records for Automation Type ID 3:", duplicatesType3);

      displayGroupedRules4(duplicatesType3, "HourlyTriggers1", 3, globalAgents);
      counthourly++;
    } catch (error) {
      console.error("Error fetching hourly rules:", error);
      handleError(error);
    } finally {
      hideLoader("HourlyTriggers1");
      isFetchingHourly = false;
    }

  } else if (automation_type_id === 4) {
    if (isFetching || countupdates > 0) return;

    isFetching = true;
    console.log("Fetching rules...");

    showLoader("TicketUpdates1");

    try {
      const updateRules = await listupdaterules();
      console.log("Update Rules:", updateRules);

      updateRules.forEach(rule => {
        if (rule.active) automationTypeIdfourRecords.push(rule);
      });

      console.log("automationTypeIdfourRecords", automationTypeIdfourRecords);
      findDuplicatesWithinType(automationTypeIdfourRecords, duplicatesType4);
      console.log("Duplicate Records for Automation Type ID 4:", duplicatesType4);

      processAndDisplayDuplicates(duplicatesType4, "TicketUpdates1", globalAgents);
      countupdates++;
    } catch (error) {
      console.error("Error fetching update rules:", error);
      handleError(error);
    } finally {
      hideLoader("TicketUpdates1");
      isFetching = false;
    }
  }
}

function handleError(error) {
  if (error.status === 401) {
    document.getElementById("Automation-page").style.display = "none";
    document.getElementById("Workflow-Automation-page").style.display = "none";
    document.getElementById("no_user2").style.display = "block";
  } else if (error.status === 429) {
    document.getElementById("Automation-page").style.display = "none";
    document.getElementById("Workflow-Automation-page").style.display = "none";
    document.getElementById("no_user1").style.display = "block";
  }
}


async function listrules(page = 1, rulesArray = []) {
  console.log(`Fetching rules for page ${page}`);

  try {
      const rulesResponse = await client.request.invokeTemplate('listrules', {
          context: {
              page: page
          }
      });

      const responses = rulesResponse.response;
      const rulesData = JSON.parse(responses);

      if (rulesData.length === 0) {
          console.log("✅ No more rules to fetch. Total rules:", rulesArray.length);
          return rulesArray; 
      }

      rulesArray.push(...rulesData);

      // Fetch the next page
      return await listrules(page + 1, rulesArray);

  } catch (error) {
      console.error("❌ Error fetching rules:", error);
      if (error.headers && error.headers.status.includes("401")) { 
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user2").style.display = "block";
       
    }
    else  if (error.status === 429 || (error.headers && error.headers.status && error.headers.status.includes("429"))) { 
      document.getElementById("Automation-page").style.display = "none";
      document.getElementById("Workflow-Automation-page").style.display = "none";
      
      document.getElementById("no_user1").style.display = "block";
    }
      return rulesArray; 
  }
}


async function listupdaterules(page = 1, rulesArray = []) {
  console.log(`Fetching rules for page ${page}`);

  try {
      const rulesResponse = await client.request.invokeTemplate('listupdaterules', {
          context: {
              page: page
          }
      });

      const responses = rulesResponse.response;
      const rulesData = JSON.parse(responses);

      if (rulesData.length === 0) {
          console.log("✅ No more rules to fetch. Total rules:", rulesArray.length);
          return rulesArray; 
      }

      rulesArray.push(...rulesData);

      // Fetch the next page
      return await listupdaterules(page + 1, rulesArray);

  } catch (error) {
      console.error("❌ Error fetching rules:", error);
      if (error.headers && error.headers.status.includes("401"))  {
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user2").style.display = "block";
       
      }
      else  if (error.status === 429 || (error.headers && error.headers.status && error.headers.status.includes("429"))) { 
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user1").style.display = "block";
      }
      return rulesArray; 
  }
}

async function listhourlyrules(page = 1, rulesArray = []) {
  console.log(`Fetching rules for page ${page}`);

  try {
      const rulesResponse = await client.request.invokeTemplate('listhourlyrules', {
          context: {
              page: page
          }
      });

      const responses = rulesResponse.response;
      const rulesData = JSON.parse(responses);

      if (rulesData.length === 0) {
          console.log("✅ No more rules to fetch. Total rules:", rulesArray.length);
          return rulesArray; 
      }

      rulesArray.push(...rulesData);

      // Fetch the next page
      return await listhourlyrules(page + 1, rulesArray);

  } catch (error) {
      console.error("❌ Error fetching rules:", error);
      if (error.headers && error.headers.status.includes("401"))  {
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user2").style.display = "block";
        
      }
    else  if (error.status === 429 || (error.headers && error.headers.status && error.headers.status.includes("429"))) { 
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user1").style.display = "block";
      }
      return rulesArray; 
  }
}


function deepEqual(obj1, obj2) {
  if (obj1 === obj2) return true;

  if (typeof obj1 === 'string' && typeof obj2 === 'string') {
    return normalizeText(stripHTML4(obj1)) === normalizeText(stripHTML4(obj2));
  }

  if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) {
    return false;
  }

  const keys1 = Object.keys(obj1).sort();
  const keys2 = Object.keys(obj2).sort();
  if (keys1.length !== keys2.length) return false;

  for (const key of keys1) {
    if (!keys2.includes(key)) return false;

    let val1 = obj1[key];
    let val2 = obj2[key];

    if (typeof val1 === 'string' && typeof val2 === 'string') {
      val1 = normalizeText(stripHTML4(val1));
      val2 = normalizeText(stripHTML4(val2));
    }

    if (Array.isArray(val1) && Array.isArray(val2)) {
      if (val1.length !== val2.length) return false;

      const usedIndices = new Set();
      for (const item1 of val1) {
        const matchIndex = val2.findIndex((item2, idx) => {
          if (usedIndices.has(idx)) return false;
          if (deepEqual(item1, item2)) {
            usedIndices.add(idx);
            return true;
          }
          return false;
        });
        if (matchIndex === -1) return false;
      }
      continue;
    }

    if (typeof val1 === 'object' && typeof val2 === 'object') {
      if (!deepEqual(val1, val2)) return false;
    } else if (val1 !== val2) {
      return false;
    }
  }

  return true;
}

function normalizeText(text) {
  if (typeof text !== 'string') return '';

  const cleaned = text
    .replace(/[.,]/g, '')                            // remove punctuation
    .replace(/\s+/g, ' ')                            // normalize spaces
    .replace(/([a-zA-Z])\s+(\d)/g, '$1$2')           // collapse letter-number like "hello 2" → "hello2"
    .replace(/(\d)\s+([a-zA-Z])/g, '$1$2')           // collapse number-letter like "3 hi" → "3hi"
    .trim()
    .toLowerCase();

  // If it's purely digits and spaces (e.g. "123  45 67"), remove *all* spaces
  if (/^[\d\s]+$/.test(text)) {
    return text.replace(/\s+/g, '');
  }

  return cleaned;
}

function stripHTML4(htmlString) {
  if (typeof htmlString !== 'string') {
    htmlString = String(htmlString || '');
  }
  return htmlString
    .replace(/<\/?[^>]+(>|$)/g, "")
    .replace(/&nbsp;/gi, " ")
    .replace(/[.,]/g, "")
    .replace(/\s+/g, " ")
    .trim();
}


function normalizeConditionsForGrouping(conditions) {
  if (!Array.isArray(conditions)) return [];

  return conditions.map(set => {
    const normalizedProps = (set.properties || []).map(prop => {
      const copy = { ...prop };
      delete copy.case_sensitive;

      for (const key in copy) {
        if (typeof copy[key] === 'string') {
          copy[key] = normalizeText(stripHTML4(copy[key]));
        } else if (Array.isArray(copy[key])) {
          copy[key] = copy[key].map(v =>
            typeof v === 'string' ? normalizeText(stripHTML4(v)) : v
          ).sort();
        }
      }

      return sortObjectValues(copy);
    }).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));

    return {
      match_type: set.match_type?.toLowerCase(),
      properties: normalizedProps
    };
  });
}

function areConditionsEquivalent(setA, setB) {
  if (setA.length !== setB.length) return false;

  const permutations = generatePermutations(setB);
  return permutations.some(perm => {

    return setA.every((a, i) => deepEqual(a, perm[i]));
  });
}

function generatePermutations(array) {
  if (array.length <= 1) return [array];

  const perms = [];
  for (let i = 0; i < array.length; i++) {
    const rest = [...array.slice(0, i), ...array.slice(i + 1)];
    for (const perm of generatePermutations(rest)) {
      perms.push([array[i], ...perm]);
    }
  }
  return perms;
}

function findDuplicatesWithinType(records, duplicatesArray) {
  const seenRecords = [];

  records.forEach((rule) => {
    const { summary, actions, conditions } = rule;

    if (summary && actions && conditions) {
      const normalizedSummary = sortObjectValues(summary);
      const normalizedActions = sortObjectValues(actions);
      const normalizedConditions = normalizeConditionsForGrouping(conditions);

      const duplicate = seenRecords.find(seen => {
        const summaryMatch = deepEqual(sortObjectValues(seen.summary), normalizedSummary);
        const actionMatch = deepEqual(sortObjectValues(seen.actions), normalizedActions);
        const conditionMatch = areConditionsEquivalent(seen.conditions, normalizedConditions);

        return summaryMatch && actionMatch && conditionMatch;
      });

      if (duplicate) {
        duplicatesArray.push(rule);
        if (!duplicatesArray.includes(duplicate.rule)) {
          duplicatesArray.push(duplicate.rule);
        }
      } else {
        seenRecords.push({
          summary: normalizedSummary,
          actions: normalizedActions,
          conditions: normalizedConditions,
          rule
        });
      }
    }
  });
}

function sortObjectValues(obj) {
  if (Array.isArray(obj)) {
    return obj
      .map(item =>
        typeof item === 'object' && item !== null
          ? sortObjectValues(item)
          : normalizeText(stripHTML4(item))
      )
      .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
  }

  if (typeof obj === 'object' && obj !== null) {
    if (obj.hasOwnProperty('condition_set_1') || obj.hasOwnProperty('condition_set_2')) {
      const { operator, ...rest } = obj;
      const allConditions = Object.values(rest).flat().map(val =>
        normalizeText(stripHTML4(val))
      ).sort();

      return {
        operator: normalizeText(stripHTML4(operator || '')),
        conditions: allConditions
      };
    }

    return Object.fromEntries(
      Object.entries(obj)
        .map(([key, value]) => [key, sortObjectValues(value)])
        .sort(([a], [b]) => a.localeCompare(b))
    );
  }

  return normalizeText(stripHTML4(obj));
}


function capitalizeFirstLetter(text) {
  if (!text) return text;
  return text.charAt(0).toUpperCase() + text.slice(1);
}

function normalizeConditionProps(set) {
  return (set?.[0]?.properties || [])
    .map(prop => {
      return [
        normalizeText(stripHTML4(prop.field_name)),
        normalizeText(stripHTML4(prop.operator)),
        normalizeText(stripHTML4(prop.value))
      ].join(":");
    })
    .sort();
}

function normalizeAction(action = {}) {
  const result = [];

  Object.entries(action).forEach(([key, value]) => {
    if (value === null || value === "") return;

    const normalizedKey = normalizeText(stripHTML4(key));

    if (typeof value === "string") {
      result.push(`${normalizedKey}:${normalizeText(stripHTML4(value))}`);
    } else if (Array.isArray(value)) {
      const normalizedArray = value.map(v => normalizeText(stripHTML4(v))).sort();
      result.push(`${normalizedKey}:[${normalizedArray.join(",")}]`);
    } else if (typeof value === "object") {
      result.push(`${normalizedKey}:{${normalizeAction(value)}}`);
    }
  });

  return result.sort().join(" ");
}
function combineConditionsAndActions4({
  condition_set_1_summary,
  condition_set_2_summary,
  operator,
  condition_set_1_real,
  condition_set_2_real,
  actions_summary,
  actions_real
}) {
  
  const processedConditionSet1 = (condition_set_1_summary || []).map(stripHTML4);
  const processedConditionSet2 = (condition_set_2_summary || []).map(stripHTML4);

  const originalConditions = [
    ...processedConditionSet1,
    operator ? ` ${operator} ` : "",
    ...processedConditionSet2,
  ].join(" ");

  let originalActionText = "";
  if (Array.isArray(actions_summary) && actions_summary.length > 0) {
    originalActionText = actions_summary.map(stripHTML4).join(" ");
  }

  const originalContent = `${originalConditions} ${originalActionText}`.trim();


  const normalizedSet1 = normalizeConditionProps(condition_set_1_real);
  const normalizedSet2 = normalizeConditionProps(condition_set_2_real);
  const allNormalizedConditions = [...normalizedSet1, ...normalizedSet2].sort((a, b) =>
    a.localeCompare(b)
  );

  const normalizedOperator = normalizeText(operator || "");

  const sortedConditions = [...allNormalizedConditions, normalizedOperator].join(" ");

  const sortedActions = (actions_real || []).map(normalizeAction).sort().join(" ");

  const sortedContent = `${sortedConditions} ${sortedActions}`.trim();

  return { originalContent, sortedContent };
}


function normalizeText1(text) {
  if (typeof text !== "string") return text;
  return text
    .replace(/<[^>]*>/g, "") 
    .replace(/[.,]/g, "")      
    .replace(/\s+/g, " ")      
    .trim();
}


let currentPage4 = 1;
const itemsPerPage4 = 5;

function displayGroupedRules4(records, containerId, automation_type_id,globalAgents) {
  console.log("automationtypeid log at start of displaygroups",automation_type_id  )
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Container with ID "${containerId}" not found.`);
    return;
  }

  container.innerHTML = ""; 

  if (records.length <= 1) {
    container.innerHTML = `
    <div style="
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80%;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin: 300px auto; /* Push it down + center horizontally */
">
 

          No duplicate rules found.
      </div>`;
    return;
}

const groupedRules = new Map();

records.forEach((record) => {
  const rule = record.parsedPayload || record.rule || record;
  if (!rule || !rule.summary) return;

  const { name, summary, position, updated_at, last_updated_by, affected_tickets_count, id } = rule;

  if (summary.conditions) {
    const actions = summary.actions || [];

    const { originalContent, sortedContent } = combineConditionsAndActions4({
      condition_set_1_summary: summary.conditions.condition_set_1,
      condition_set_2_summary: summary.conditions.condition_set_2,
      operator: summary.conditions.operator,
      condition_set_1_real: record.conditions.filter(cond => cond.name === "condition_set_1"),
      condition_set_2_real: record.conditions.filter(cond => cond.name === "condition_set_2"),
      actions_summary: summary.actions,
      actions_real: record.actions
    });


    if (!groupedRules.has(sortedContent)) {
      groupedRules.set(sortedContent, []);
    }

    groupedRules.get(sortedContent).push({
      name,
      position,
      combinedContent: originalContent, 
      conditions: summary.conditions,
      actions: actions,
      updated_at,
      last_updated_by,
      affected_tickets_count,
      id,automation_type_id
    });
  }
});

const groupedRulesArray = Array.from(groupedRules.values()).filter(group => group.length > 1);
  const totalgroup = Math.ceil(groupedRulesArray.length );
  console.log(totalgroup,"*********************")
  const totalPages4 = Math.ceil(groupedRulesArray.length / itemsPerPage4);
  currentPage4 = Math.max(1, Math.min(currentPage4, totalPages4)); // Ensure valid page number

  console.log("Total Pages:", totalPages4, "Current Page:", currentPage4);

  const startIdx = (currentPage4 - 1) * itemsPerPage4;
  const paginatedRules = groupedRulesArray.slice(startIdx, startIdx + itemsPerPage4);

  console.log("Displaying Records:", paginatedRules);

  let arrayLength = paginatedRules.length;
  console.log("Records Length:", arrayLength);

  
  paginatedRules.forEach((titles) => {
    const rulesCount = titles.length;

    if (rulesCount === 1) {
        console.log(`Skipping group with only 1 rule: ${titles[0].name}`);
        return; 
    }
    
    const groupContainer = document.createElement("div");
    groupContainer.style.border = "1px solid #ccc";
    groupContainer.style.padding = "16px";
    groupContainer.style.margin = "16px";
    groupContainer.style.borderRadius = "8px";
    groupContainer.style.backgroundColor = "#f5f7f9";
    groupContainer.style.width = "87%";

    titles.forEach(({  name, position, combinedContent, conditions, actions,updated_at,last_updated_by,affected_tickets_count,automation_type_id,id
    }, index) => {
      const card = document.createElement("div");
      // card.className = "fw-card-1 fw-py-16 fw-flex fw-flex-column";
    card.style.border = "1px solid #ddd";
    card.style.padding = "16px";
    card.style.margin = "8px 0"
    card.style.fontFamily =
      "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
    card.style.borderRadius = "8px";
    card.style.backgroundColor = index === 0 ? "#fff" : "#e5f2fd";
    card.style.marginBottom = "10px";
    card.style.paddingBottom = "0";
    card .style.overflow ="hidden"
     
     
      
    const cardHeader = document.createElement("div");
    cardHeader.style.display = "flex";
    cardHeader.style.justifyContent = "space-between";
    cardHeader.style.alignItems = "center";
      
      // Create a wrapper for the title
      const cardTitle = document.createElement("h4");
      cardTitle.style.margin = "0";
      cardTitle.style.cursor = "pointer";
      cardTitle.style.fontSize = "14px";
      cardTitle.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
      cardTitle.style.color = "#183247";
      cardTitle.style.transition = "color 0.2s ease";
      cardTitle.style.fontWeight = "600"; 

// Create the serial number (position)
if (position) {
  const serialNumber = document.createElement("span");
  serialNumber.textContent = position + ". ";
  serialNumber.style.color = "#183247"; // Keep serial number color fixed
  cardTitle.appendChild(serialNumber);
}

// Create the actual name (clickable part)
const titleText = document.createElement("span");
titleText.textContent = name;
titleText.style.color = "#183247"; 
titleText.style.transition = "color 0.2s ease";

// Add hover effect for only the name
titleText.addEventListener("mouseover", () => {
    titleText.style.color = "#007bff"; // Change only name color on hover
});
titleText.addEventListener("mouseout", () => {
    titleText.style.color = "#183247"; // Reset name color when not hovering
});
titleText.addEventListener("click", () => {
    titleText.style.color = "#ff5733"; // Change title color on click
    console.log("automation type id before popup",automation_type_id)
    showPopupCard(name, { conditions: conditions, actions: actions },automation_type_id)
});

// Append name to title
cardTitle.appendChild(titleText);




      // Append title and actions to the cardHeader
      cardHeader.appendChild(cardTitle);
      // Create a container for the horizontal line and the gap
const cardContainer = document.createElement("div");

// Style the container to have a background color in the gap
cardContainer.style.backgroundColor = "#f0f0f0";  // Set the background color for the gap (change to desired color)
cardContainer.style.paddingBottom = "20px";  
cardContainer.style.marginLeft="-15px";
cardContainer.style.borderRadius = "4px";
// cardContainer.style.width="103%";
cardContainer.style.position = "relative";
cardContainer.style.width = "calc(103% + 30px)";

// Create a horizontal line after the cardBody
const horizontalLine = document.createElement("div");
horizontalLine.style.height = "1px"; // Set the height to 1px for a thin line
horizontalLine.style.backgroundColor = "#ccc"; // Set the color of the horizontal line
horizontalLine.style.marginTop = "16px"; // Add space above the line (adjust as needed)
// horizontalLine.style.width = "100%"; // Ensure the line stretches the full width of the container
horizontalLine.style.marginLeft="-3px";
      

      function truncateContent(content, maxLength, lines) {
        // Truncate the content to the desired number of characters
        let truncated = content;
      
        // Adjust for the desired line count and maximum length
        if (content.length > maxLength) {
          truncated = content.slice(0, maxLength) + "...";
        }
      
        // Break content into lines manually for multi-line truncation
        const words = truncated.split(" ");
        const result = [];
        let line = "";
        let currentLine = 1;
      
        for (let i = 0; i < words.length; i++) {
          if (line.length + words[i].length + 1 <= maxLength / lines) {
            line += (line ? " " : "") + words[i];
          } else {
            result.push(line);
            line = words[i];
            currentLine++;
            if (currentLine > lines) break; // Stop adding more lines if max lines are reached
          }
        }
      
        if (currentLine <= lines && line) {
          result.push(line);
        }
      
        return result.join(" ") + (currentLine > lines ? "..." : "");
      }
      function calculateLastModified(updated_at) {
        const updatedDate = new Date(updated_at);
        const currentDate = new Date();
    
        const diffInMilliseconds = currentDate - updatedDate;
        const seconds = Math.floor(diffInMilliseconds / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        const months = Math.floor(days / 30);  // Approximate months
        const years = Math.floor(days / 365);  // Approximate years
    
        if (years > 0) {
            return years === 1 ? "a year ago" : `${years} years ago`;
        } else if (months > 0) {
            return months === 1 ? "a month ago" : `${months} months ago`;
        } else if (days > 0) {
            return `${days} day${days > 1 ? "s" : ""} ago`;
        } else if (hours > 0) {
            return `${hours} hour${hours > 1 ? "s" : ""} ago`;
        } else if (minutes > 0) {
            return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
        } else {
            return "Just now";
        }
    }
    
    
      
      
   
      // console.log("updated at",calculateLastModified(updated_at));
      
      const lastModifiedRow = document.createElement("div");
      lastModifiedRow.style.display = "grid";
      lastModifiedRow.style.gridTemplateColumns = "repeat(auto-fit, minmax(150px, 1fr))"; // Responsive columns with minimum size 150px
      lastModifiedRow.style.alignItems = "center";
      lastModifiedRow.style.gap = "16px"; // Space between items
      lastModifiedRow.style.width = "100%"; // Ensure full width
      lastModifiedRow.style.gridTemplateRows = "auto"; // Auto row size to fit content
      
      // Function to create a label-value pair container
      function createLabelValue(labelText, valueText) {
        const container = document.createElement("div");
        container.style.display = "flex";
        container.style.flexDirection = "row"; // Make sure content is horizontal
        container.style.alignItems = "center"; // Align vertically in center
      
        const label = document.createElement("span");
        label.textContent = labelText;
        label.style.color = "#183247";
        label.style.marginTop = "10px";
        label.style.marginLeft = "15%";
        label.style.fontSize = "12px";
        label.style.fontFamily ="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";

        
        const value = document.createElement("span");
        value.textContent = valueText;
        value.style.color = "#183247";
        value.style.fontWeight = "600";
        value.style.fontSize = "12px";
        value.style.marginTop = "10px";
        value.style.marginLeft = "10px";
        value.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";

        value.style.marginLeft = "10px"; // Add space between label and value
      
        container.appendChild(label);
        container.appendChild(value);
      
        return container;
      }
      
      // Create and append content to the lastModifiedRow
      const lastModifiedText = calculateLastModified(updated_at);
      lastModifiedRow.appendChild(createLabelValue("Last Modified :", lastModifiedText));
      
      // Vertical line between sections
      const verticalLine = document.createElement("div");
      verticalLine.style.gridRow = "span 1"; // Ensuring vertical line doesn't span more than one row
      verticalLine.style.height = "20px"; 
      verticalLine.style.marginTop = "10px";
      verticalLine.style.marginLeft = "30px"; // Add gap at the top// Adjust the height as needed
      verticalLine.style.borderLeft = "2px solid #ccc";
      lastModifiedRow.appendChild(verticalLine);
      
      // Matching agent data
      const agentsid = last_updated_by;
      const matchingAgent = globalAgents.find(agent => String(agent.id) === String(agentsid));
      const agentNameText = matchingAgent ? matchingAgent.contact.name : "Unknown Agent";
      lastModifiedRow.appendChild(createLabelValue("By :", agentNameText));
      
      // Vertical line after the agent name
      const verticalLine2 = document.createElement("div");
      verticalLine2.style.gridRow = "span 1"; // Same for second vertical line
      verticalLine2.style.height = "20px";
      verticalLine2.style.marginTop = "10px"; 
      verticalLine2.style.marginLeft = "30px"; // Adjust the height as needed
      verticalLine2.style.borderLeft = "2px solid #ccc";
      lastModifiedRow.appendChild(verticalLine2);
      
      // Impacted tickets info
      const affectedTicketsText = affected_tickets_count === 0 ? "--" : affected_tickets_count;
      // lastModifiedRow.appendChild(createLabelValue("Impacted tickets (Last 7 days) :", affectedTicketsText));
      const impactedTickets = createLabelValue("Impacted tickets (Last 7 days) :", affectedTicketsText);
  impactedTickets.firstChild.style.marginLeft = "-50%"; // Adjust label alignment
  lastModifiedRow.appendChild(impactedTickets);
      
 

 
      const cardBody = document.createElement("div"); // Create a container for card content and actions
      cardBody.style.display = "flex"; // Flexbox to align items horizontally
      cardBody.style.justifyContent = "space-between"; // Ensure there's space between content and actions
      cardBody.style.alignItems = "flex-start"; // Align items to the top (optional, depending on your needs)
               

const truncatedContent = truncateContent(combinedContent, 200, 2);

const cardContent = document.createElement("pre");
cardContent.textContent = truncatedContent;

// Style the card content
cardContent.style.marginTop = "8px";
cardContent.style.padding = "8px";
cardContent.style.color="#183247";
cardContent.style.fontweight="600";
cardContent.style.fontFamily= "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
cardContent.style.whiteSpace = "pre-wrap"; // Ensure text wraps
cardContent.style.overflow = "hidden"; // Hide overflow content
cardContent.style.textOverflow = "ellipsis"; // Add ellipsis for overflow
cardContent.style.maxWidth = "75%"; // Limit the card width to half the container's width
cardContent.style.fontSize="12px";
cardContent.style.marginLeft="15px";


     // Create the container for card actions
const cardActionsContainer = document.createElement("div");
cardActionsContainer.style.display = "flex"; // Display actions horizontally
cardActionsContainer.style.justifyContent = "flex-end"; // Align to the right
cardActionsContainer.style.marginTop = "10px"; // Add some spacing above the actions
cardActionsContainer.style.gap = "8px"; // Set space between the toggle and the delete icon

      // Add fw-toggle
      // const fwToggle = document.createElement("fw-toggle");
      // fwToggle.setAttribute("size", "medium");
      // fwToggle.setAttribute("checked", "");

      // Add fw-icon
      const fwIcon = document.createElement("fw-icon");
      fwIcon.setAttribute("name", "delete");
      fwIcon.setAttribute("size", "18");
      fwIcon.style.cursor = "pointer";
      fwIcon.style.color = "red"; // Set the color to red
      // Add a pointer cursor for interactivity
      fwIcon.title = "Delete";

      fwIcon.addEventListener("click", () => {
        console.log("Delete icon clicked");
    
        currentRuleId = id; // Store the rule ID globally
        currentAutomationId = automation_type_id;
    
        console.log("rule id:", currentRuleId);
        console.log("automationid:", currentAutomationId);
        // const modal = document.getElementById("deleteConfirmationPopup");

        // if (modal) {
        //   modal.setAttribute("is-open", "true");
      
        //   modal.addEventListener(
        //     "fwSubmit",
        //     () => {
        //       console.log("Delete confirmed.");
             
        //       try {
        //             recenetconfirmDeletion();
                  
          
        //         } catch (error) {
        //             console.error("❌ Error in deletion process:", error);
        //         }
      
              
        //       modal.removeAttribute("is-open");
        //     },
        //     { once: true }
        //   );
      
        //   // Handle Cancel (Close)
        //   modal.querySelector("fw-modal-footer").addEventListener(
        //     "fwClose",
        //     () => {
        //       modal.removeAttribute("is-open");
        //       console.log("Delete operation was cancelled.");
        //     },
        //     { once: true }
        //   );
        // } else {
        //   console.error("Modal element with ID 'composition' not found.");
        // }

        // ✅ Create the modal dynamically
        const modal = document.createElement("fw-modal");
        console.log("modal created")
        modal.setAttribute("id", "deleteConfirmationPopup");
        modal.setAttribute("title-text", "Delete Rule");
        modal.setAttribute("is-open", "false");
        
        const content = document.createElement("fw-text");
        content.textContent = "Are you sure you want to delete the rule?";
        
        const footer = document.createElement("fw-modal-footer");
        
        modal.appendChild(content);
        modal.appendChild(footer);
        document.body.appendChild(modal); // ✅ Add modal to the DOM
        
        // ✅ Open and handle modal logic
        const existingModal = document.getElementById("deleteConfirmationPopup");
        
        if (existingModal) {
          existingModal.setAttribute("is-open", "true");
        
          // Confirm (Submit) action
          existingModal.addEventListener(
            "fwSubmit",
            () => {
              console.log("Delete confirmed.");
        
              try {
                recenetconfirmDeletion(); // Ensure this function is defined elsewhere
              } catch (error) {
                console.error("❌ Error in deletion process:", error);
              }
        
              existingModal.removeAttribute("is-open");
            },
            { once: true }
          );
        
          // Cancel (Close) action
          existingModal
            .querySelector("fw-modal-footer")
            .addEventListener(
              "fwClose",
              () => {
                existingModal.removeAttribute("is-open");
                console.log("Delete operation was cancelled.");
              },
              { once: true }
            );
        } else {
          console.error("Modal element with ID 'deleteConfirmationPopup' not found.");
        }


        
    });
    

    //   fwIcon.addEventListener("click", () => {
    //     console.log("Delete icon clicked");
    
    //     currentRuleId = id; // Store the rule ID globally
    //     currentAutomationId = automation_type_id;
    
    //     console.log("rule id:", currentRuleId);
    //     console.log("automationid:", currentAutomationId);
    
    //     showDeletePopup(); 
    // });
    
 
// function showDeletePopup() {
//   document.getElementById("deleteConfirmationPopup").style.display = "flex";
// }


// function hideDeletePopup() {
//   document.getElementById("deleteConfirmationPopup").style.display = "none";
// }


async function Fetchentity(automationTypeId, nextMarker = null, allRecords1 = []) {
  try {
    if (!newRulePloadDB5) {
      console.error(" Entity is not initialized yet!");
      showLoader();
      setTimeout(() => {
        location.reload();
    }, 1000);
    }

    showLoader(); 

    let queryObj = {
      query: {
        $and: [
          { automation_type_id: automationTypeId },
      
          { active: "true" } 
        ]
      } 
    };


    if (nextMarker) {
      console.log(" Next marker found:", nextMarker);
      queryObj.next = { marker: nextMarker };
    }

    console.log("📤 Fetching records with query:", JSON.stringify(queryObj, null, 2));

    const response = await newRulePloadDB5.getAll(queryObj);

    if (!response.records || !Array.isArray(response.records)) {
      console.error("❌ Invalid response format:", response);
      hideLoader(); 
      return allRecords1;
    }

    console.log(`📥 Retrieved ${response.records.length} records`);
    allRecords1 = allRecords1.concat(response.records);

    const newNextMarker = response.links?.next?.marker || null;

    if (newNextMarker) {
      console.log(` More pages exist. Next marker: ${newNextMarker}`);
      return Fetchentity(automationTypeId, newNextMarker, allRecords1);
    } else {
      console.log("✅ No more pages.");
      console.log(`📌 Total Filtered Records: ${allRecords1.length}`);

      hideLoader();


      if (automationTypeId === 1) {
       return findDuplicateRulestype1and3(allRecords1);
     } else if(automationTypeId === 3)
     {
       return findDuplicateRulestype1and3(allRecords1);
     }
      else {
       console.warn("⚠️ Unknown automationTypeId:", automationTypeId);
       return allRecords1;
     }
      
    }
  } catch (error) {
    console.error("❌ Error fetching filtered records:", error);
    hideLoader(); 
    return [];
  }
}
function getDisplayIdByRuleId(entityRecords, currentRuleId) {
  console.log("Checking all records for Rule ID:", currentRuleId);

  if (!Array.isArray(entityRecords) || entityRecords.length === 0) {
    console.warn(" No records found in entity storage.");
    return { displayId: null, updatedArray: entityRecords };
  }

  const recordIndex = entityRecords.findIndex(record =>
    String(record?.data?.rule_id) === String(currentRuleId)
  );

  if (recordIndex === -1) {
    console.warn(`❌ Rule ID ${currentRuleId} not found in records.`);
    return { displayId: null, updatedArray: entityRecords };
  }

  const matchedRecord = entityRecords[recordIndex];
  const displayId = matchedRecord.display_id;

  // ✅ Remove the record from the original array
  entityRecords.splice(recordIndex, 1);

  console.log(`✅ Record with Rule ID ${currentRuleId} and Display ID ${displayId} removed.`);

  return { displayId, updatedArray: entityRecords };
}
async function recenetconfirmDeletion() {
  console.log("Deleting rule with ID:", currentRuleId);
  console.log("count no 1 delete function called ******************");

  // Normalize automation ID to number
  currentAutomationId = Number(currentAutomationId);
  console.log("Current Automation ID is:", currentAutomationId);

  try {
    console.log("count no 2 try block called ******************");

    // Start progress loader
    let progressLoader = document.querySelector("#progress-container");
    if (progressLoader && typeof progressLoader.start === "function") {
      progressLoader.start();
    }

    // Delete the rule from server
    const getdeleteruleResponse = await client.request.invokeTemplate("deleterule", {
      context: {
        automationid: currentAutomationId,
        ruleid: currentRuleId,
      },
    });

    console.log("getdeleteruleResponse", getdeleteruleResponse);

    if (getdeleteruleResponse.status === 204) {
      console.log("✅ Rule deleted successfully!");

      // Show success toast
      const valid = document.getElementById("type_toast");
      valid.setAttribute("content", "Rule deleted successfully");
      valid.setAttribute("type", "success");
      valid.setAttribute("open", true);

      if (currentAutomationId === 1) {
        console.log("Automation ID 1 logic executing...", duplicatesType1);

        const ruleIndex = duplicatesType1.findIndex(rule => String(rule.id) === String(currentRuleId));
        if (ruleIndex !== -1) {
          const ruleToDelete = duplicatesType1[ruleIndex];
          console.log("🗑️ Deleting rule with ID:", ruleToDelete.id);
        
          duplicatesType1.splice(ruleIndex, 1);
          console.log("✅ Removed from duplicatesType1 array.", duplicatesType1);
       
          displayGroupedRules4(duplicatesType1, "Ticketcreation1", automation_type_id, globalAgents);

          if (progressLoader && typeof progressLoader.done === "function") {
            progressLoader.done();
          }
        } else {
          console.warn(`❌ Rule with ID ${currentRuleId} not found in duplicatesType1.`);
        }

       
        if (entitytype1.length === 0) {
          console.log("entitytype1 is empty. Fetching records...");
          entitytype1 = await Fetchentity(1);
        }

        const { displayId, updatedArray } = getDisplayIdByRuleId(entitytype1, currentRuleId);
        console.log("Updated entitytype1 after deletion:", updatedArray);
        displayGroupedRules(updatedArray, "Ticketcreation");

        if (displayId) {
          try {
            console.log("Deleting record with Display ID:", displayId);
            await newRulePloadDB5.delete(displayId);
          } catch (error) {
            console.warn(`Error deleting Display ID ${displayId}, continuing...`);
          }
        }

      } else if (currentAutomationId === 3) {
        console.log("Automation ID 3 logic executing...", duplicatesType3);

        const ruleIndex = duplicatesType3.findIndex(rule => String(rule.id) === String(currentRuleId));
        if (ruleIndex !== -1) {
          const ruleToDelete = duplicatesType3[ruleIndex];
          console.log("🗑️ Deleting rule with ID:", ruleToDelete.id);
        
          duplicatesType3.splice(ruleIndex, 1);
          console.log("✅ Removed from duplicatesType3 array.", duplicatesType3);
       
        
          displayGroupedRules4(duplicatesType3, "HourlyTriggers1", automation_type_id, globalAgents);

          if (progressLoader && typeof progressLoader.done === "function") {
            progressLoader.done();
          }
        } else {
          console.warn(`❌ Rule with ID ${currentRuleId} not found in duplicatesType3.`);
        }

        // Entity handling
        if (entitytype3.length === 0) {
          console.log("entitytype3 is empty. Fetching records...");
          entitytype3 = await Fetchentity(3);
        }

        const { displayId, updatedArray } = getDisplayIdByRuleId(entitytype3, currentRuleId);
        console.log("Updated entitytype3 after deletion:", updatedArray);
        displayGroupedRules(updatedArray, "HourlyTriggers");

        if (displayId) {
          try {
            console.log("Deleting record with Display ID:", displayId);
            await newRulePloadDB5.delete(displayId);
          } catch (error) {
            console.warn(`Error deleting Display ID ${displayId}, continuing...`);
          }
        }
      } else {
        console.warn("Unhandled automation ID:", currentAutomationId);
      }
    }
  } catch (error) {
    console.error("❌ Error deleting rule:", error);
  }
}



    
    
    
    // // Attach event listeners to the confirmation buttons (only once)
    // document.getElementById("confirmDeleteBtn").addEventListener("click", recenetconfirmDeletion);
    // document.getElementById("cancelDeleteBtn").addEventListener("click", hideDeletePopup);
    

             
             
          // Append fw-toggle and fw-icon to cardActions
          // cardActionsContainer.appendChild(fwToggle);
          cardActionsContainer.appendChild(fwIcon);
          card.appendChild(cardHeader);
          cardBody.appendChild(cardContent);
          cardBody.appendChild(cardActionsContainer);
          card.appendChild(cardBody);
          cardContainer.appendChild(horizontalLine);
          // card.appendChild(horizontalLine);
         
          cardContainer.appendChild(lastModifiedRow);
          card.appendChild(cardContainer)
          groupContainer.appendChild(card);
        });
    
        container.appendChild(groupContainer);
      });
    // Add pagination component
    addFwPagination4(containerId,records,totalgroup,automation_type_id);
    }

// Function to add pagination for displayGroupedRules4
function addFwPagination4(containerId, records, totalgroup, automation_type_id) {
  console.log('Adding pagination to container:', containerId);
  console.log("Automation Type ID at Page Change:", automation_type_id);

  

  let container1 = document.getElementById(containerId);
  if (!container1) {
      console.warn(`Container with ID "${containerId}" not found.`);
      return;
  }

  if (totalgroup <= itemsPerPage4) {
      console.log("Total records are less than or equal to items per page, skipping pagination.");
      return;
  }

  let existingPagination1 = container1.querySelector("#fw-pagination-4");
  if (existingPagination1) {
      existingPagination1.remove(); // Remove old pagination if it exists
  }

  const pagination1 = document.createElement("fw-pagination");
  pagination1.id = "fw-pagination-4";

  pagination1.setAttribute("total", totalgroup);
  pagination1.setAttribute("per-page", itemsPerPage4);
  pagination1.setAttribute("page", currentPage4);

  console.log("Pagination Element:", pagination1);

  const paginationWrapper1 = document.createElement("div");
  // paginationWrapper1.style.display = "flex";
  paginationWrapper1.style.justifyContent = "flex-start";
  paginationWrapper1.style.alignItems = "center";
  // paginationWrapper1.style.width = "100%";
  paginationWrapper1.style.marginLeft = "45%";

  paginationWrapper1.appendChild(pagination1);
  container1.appendChild(paginationWrapper1);

  
  pagination1.addEventListener("fwChange", (event) => {
      console.log("fwChange Event Triggered", event);
      currentPage4 = event.detail.page;
      console.log("Updated Page:", currentPage4);

      // Retrieve automation_type_id from localStorage if missing
      let storedAutomationTypeId = localStorage.getItem("automation_type_id");

      console.log("Retrieved automation_type_id from localStorage:", storedAutomationTypeId);

      // Update the displayed rules for the current container, passing automation_type_id correctly
      displayGroupedRules4(records, containerId, storedAutomationTypeId,globalAgents);
  });
}




function combineConditionsAndActions({
  condition_set_1_summary,
  condition_set_2_summary,
  operator,
  condition_set_1_real,
  condition_set_2_real,
  actions_summary,
  actions_real,
  performer = "",
  eventText = []
}) {
  // ✅ Normalize performer and events
  const processedPerformer = normalizeText(stripHTML4(performer));
  const processedEventText = eventText.map(e => normalizeText(stripHTML4(e))).sort().join(" ");

  // ✅ 1. Prepare readable (original) content
  const processedConditionSet1 = (condition_set_1_summary || []).map(stripHTML4);
  const processedConditionSet2 = (condition_set_2_summary || []).map(stripHTML4);

  const originalConditions = [
    ...processedConditionSet1,
    operator ? ` ${operator} ` : "",
    ...processedConditionSet2,
  ].join(" ");

  let originalActionText = "";
  if (Array.isArray(actions_summary) && actions_summary.length > 0) {
    originalActionText = actions_summary.map(stripHTML4).join(" ");
  }

  const originalContent = `${stripHTML4(performer)} ${eventText.map(stripHTML4).join(" ")} ${originalConditions} ${originalActionText}`.trim();

  // ✅ 2. Normalize conditions for grouping (ignore order and set)
  const normalizedSet1 = normalizeConditionProps(condition_set_1_real);
  const normalizedSet2 = normalizeConditionProps(condition_set_2_real);

  const allNormalizedConditions = [...normalizedSet1, ...normalizedSet2].sort((a, b) =>
    a.localeCompare(b)
  );

  const normalizedOperator = normalizeText(operator || "");

  const sortedConditions = [...allNormalizedConditions, normalizedOperator].join(" ");

  // ✅ 3. Normalize and deep-compare actions
  const sortedActions = (actions_real || []).map(normalizeAction).sort().join(" ");

  // ✅ 4. Final sorted content (used for grouping)
  const sortedContent = `${processedPerformer} ${processedEventText} ${sortedConditions} ${sortedActions}`.trim();

  return { originalContent, sortedContent };
}

let currentPageDuplicates = 1;
const itemsPerPageDuplicates = 5;

function processAndDisplayDuplicates(duplicates, containerId,globalAgents) {
  console.log("function processAndDisplayDuplicates called");

  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Container with ID "${containerId}" not found.`);
    return;
  }

  container.innerHTML = ""; // Clear container

 
  if (duplicates.length <= 1) {
    container.innerHTML = `
    <div style="
  display: flex;
  justify-content: center;
  align-items: center;
  width: 80%;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin: 300px auto; /* Push it down + center horizontally */
">
 

          No duplicate rules found.
      </div>`;
return;
  }


  const groupedRules = new Map();

  duplicates.forEach((record) => {
    const rule = record.parsedPayload || record.rule || record;

    if (!rule || !rule.summary) {
      console.warn("Skipping record due to missing data:", record);
      return;
    }

    const { name, summary, position, updated_at, last_updated_by, affected_tickets_count, id } = rule;

    if (summary && summary.conditions) {
      const actions = summary.actions || [];
      const performer = summary.performer || "";
      const eventText = summary.events || [];

      // ✅ Get both sorted and original content
      const { originalContent, sortedContent } = combineConditionsAndActions({
        performer: performer,
        eventText: eventText,
        condition_set_1_summary: summary.conditions.condition_set_1,
        condition_set_2_summary: summary.conditions.condition_set_2,
        operator: summary.conditions.operator,
        condition_set_1_real: record.conditions.filter(cond => cond.name === "condition_set_1"),
        condition_set_2_real: record.conditions.filter(cond => cond.name === "condition_set_2"),
        actions_summary: summary.actions,
        actions_real: record.actions
      });
      
      // ✅ Use sortedContent for grouping
      if (!groupedRules.has(sortedContent)) {
        groupedRules.set(sortedContent, []);
      }

      // ✅ Store both sortedContent (for grouping) and originalContent (for display)
      groupedRules.get(sortedContent).push({
        name,
        position,
        combinedContent: originalContent, // ✅ Use originalContent for display
        performer,
        eventText,
        conditions: summary.conditions,
        actions,
        updated_at,
        last_updated_by,
        affected_tickets_count,
        id,
      });
    }
  });

  const groupedRulesArray = Array.from(groupedRules.values()).filter(group => group.length > 1);

  const totalgroup = Math.ceil(groupedRulesArray.length );
  console.log(totalgroup,"*********************")
  const totalPagesDuplicates = Math.ceil(groupedRulesArray.length / itemsPerPageDuplicates);
  currentPageDuplicates = Math.max(1, Math.min(currentPageDuplicates, totalPagesDuplicates));

  console.log("Total Pages:", totalPagesDuplicates, "Current Page:", currentPageDuplicates);

  const startIdx = (currentPageDuplicates - 1) * itemsPerPageDuplicates;
  const paginatedRules = groupedRulesArray.slice(startIdx, startIdx + itemsPerPageDuplicates);

  console.log("Displaying Records:", paginatedRules);
  
  let arrayLength = paginatedRules.length;
  console.log("Records Length:", arrayLength);

  paginatedRules.forEach((titles) => {
    const rulesCount = titles.length;

    // ✅ Skip the group if it contains only one rule
    if (rulesCount === 1) {
        console.log(`Skipping group with only 1 rule: ${titles[0].name}`);
        return; // Stop further execution for this group
    }
    const groupContainer = document.createElement("div");
    groupContainer.style.border = "1px solid #ccc";
    groupContainer.style.padding = "16px";
    groupContainer.style.margin = "16px";
    groupContainer.style.borderRadius = "8px";
    groupContainer.style.backgroundColor = "#f5f7f9";
    groupContainer.style.width = "87%";
  
    titles.forEach(({ name, position, combinedContent, performer, 
      eventText, conditions, actions,updated_at,
      last_updated_by,
      affected_tickets_count,id}, index) => {
      const card = document.createElement("div");
      card.style.border = "1px solid #ccc";
      card.style.padding = "16px";
      card.style.margin = "8px 0";
      card.style.fontFamily =
        "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
      card.style.borderRadius = "8px";
      card.style.backgroundColor = index === 0 ? "#fff" : "#e5f2fd";
      card.style.marginBottom = "10px";
      card.style.paddingBottom = "0";
     card.style.overflow="hidden";
  
      const cardHeader = document.createElement("div");
      cardHeader.style.display = "flex";
      cardHeader.style.justifyContent = "space-between";
      cardHeader.style.alignItems = "center";
    // Create a wrapper for the title
const cardTitle = document.createElement("h4");
cardTitle.style.margin = "0";
cardTitle.style.cursor = "pointer";
cardTitle.style.fontSize = "14px";
cardTitle.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
cardTitle.style.color = "#183247";
cardTitle.style.transition = "color 0.2s ease";
cardTitle.style.fontWeight = "600"; 

// Create the serial number (position)
if (position) {
const serialNumber = document.createElement("span");
serialNumber.textContent = position + ". ";
serialNumber.style.color = "#183247"; // Keep serial number color fixed
cardTitle.appendChild(serialNumber);
}

// Create the actual name (clickable part)
const titleText = document.createElement("span");
titleText.textContent = name;
titleText.style.color = "#183247"; 
titleText.style.transition = "color 0.2s ease";

// Add hover effect for only the name
titleText.addEventListener("mouseover", () => {
titleText.style.color = "#007bff"; // Change only name color on hover
});
titleText.addEventListener("mouseout", () => {
titleText.style.color = "#183247"; // Reset name color when not hovering
});
titleText.addEventListener("click", () => {
titleText.style.color = "#ff5733"; // Change title color on click
showPopupCard1(name, { performer: performer, 
eventText: eventText, conditions: conditions, actions: actions, });
});

// Append name to title
cardTitle.appendChild(titleText);
      // Append title and actions to the cardHeader
      cardHeader.appendChild(cardTitle);
      

      const cardContainer = document.createElement("div");

// Style the container to have a background color in the gap
cardContainer.style.backgroundColor = "#f0f0f0";  // Set the background color for the gap (change to desired color)
cardContainer.style.paddingBottom = "20px";  
cardContainer.style.marginLeft="-15px";
cardContainer.style.borderRadius = "4px";
// cardContainer.style.width="103%";
cardContainer.style.position = "relative";

cardContainer.style.width = "calc(103% + 30px)";

// Create a horizontal line after the cardBody
const horizontalLine = document.createElement("div");
horizontalLine.style.height = "1px"; // Set the height to 1px for a thin line
horizontalLine.style.backgroundColor = "#ccc"; // Set the color of the horizontal line
horizontalLine.style.marginTop = "16px"; // Add space above the line (adjust as needed)
horizontalLine.style.width = "100%"; // Ensure the line stretches the full width of the container
horizontalLine.style.marginLeft="-3px";


function truncateContent(content, maxLength, lines) {
// Truncate the content to the desired number of characters
let truncated = content;

// Adjust for the desired line count and maximum length
if (content.length > maxLength) {
  truncated = content.slice(0, maxLength) + "...";
}

// Break content into lines manually for multi-line truncation
const words = truncated.split(" ");
const result = [];
let line = "";
let currentLine = 1;

for (let i = 0; i < words.length; i++) {
  if (line.length + words[i].length + 1 <= maxLength / lines) {
    line += (line ? " " : "") + words[i];
  } else {
    result.push(line);
    line = words[i];
    currentLine++;
    if (currentLine > lines) break; // Stop adding more lines if max lines are reached
  }
}

if (currentLine <= lines && line) {
  result.push(line);
}

return result.join(" ") + (currentLine > lines ? "..." : "");
}
function calculateLastModified(updated_at) {
const updatedDate = new Date(updated_at);
const currentDate = new Date();

const diffInMilliseconds = currentDate - updatedDate;
const seconds = Math.floor(diffInMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);  // Approximate months
const years = Math.floor(days / 365);  // Approximate years

if (years > 0) {
    return years === 1 ? "a year ago" : `${years} years ago`;
} else if (months > 0) {
    return months === 1 ? "a month ago" : `${months} months ago`;
} else if (days > 0) {
    return `${days} day${days > 1 ? "s" : ""} ago`;
} else if (hours > 0) {
    return `${hours} hour${hours > 1 ? "s" : ""} ago`;
} else if (minutes > 0) {
    return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
} else {
    return "Just now";
}
}

// console.log("updated at",calculateLastModified(updated_at));

   
      // console.log("updated at",calculateLastModified(updated_at));
      
      const lastModifiedRow = document.createElement("div");
      lastModifiedRow.style.display = "grid";
      lastModifiedRow.style.gridTemplateColumns = "repeat(auto-fit, minmax(150px, 1fr))"; // Responsive columns with minimum size 150px
      lastModifiedRow.style.alignItems = "center";
      lastModifiedRow.style.gap = "16px"; // Space between items
      lastModifiedRow.style.width = "100%"; // Ensure full width
      lastModifiedRow.style.gridTemplateRows = "auto"; // Auto row size to fit content
      
      // Function to create a label-value pair container
      function createLabelValue(labelText, valueText) {
        const container = document.createElement("div");
        container.style.display = "flex";
        container.style.flexDirection = "row"; // Make sure content is horizontal
        container.style.alignItems = "center"; // Align vertically in center
      
        const label = document.createElement("span");
        label.textContent = labelText;
        label.style.color = "#183247";
        label.style.marginTop = "10px";
        label.style.marginLeft = "15%";
        label.style.fontSize = "12px";
        label.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";

        
        const value = document.createElement("span");
        value.textContent = valueText;
        value.style.color = "#183247";
        value.style.fontWeight = "600";
        value.style.fontSize = "12px";
        value.style.marginTop = "10px";
        value.style.marginLeft = "10px";
        value.style.fontFamily ="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";

        value.style.marginLeft = "10px"; // Add space between label and value
      
        container.appendChild(label);
        container.appendChild(value);
      
        return container;
      }
      
      // Create and append content to the lastModifiedRow
      const lastModifiedText = calculateLastModified(updated_at);
      lastModifiedRow.appendChild(createLabelValue("Last Modified :", lastModifiedText));
      
      // Vertical line between sections
      const verticalLine = document.createElement("div");
      verticalLine.style.gridRow = "span 1"; // Ensuring vertical line doesn't span more than one row
      verticalLine.style.height = "20px"; 
      verticalLine.style.marginTop = "10px";
      verticalLine.style.marginLeft = "30px"; // Add gap at the top// Adjust the height as needed
      verticalLine.style.borderLeft = "2px solid #ccc";
      lastModifiedRow.appendChild(verticalLine);
      
      // Matching agent data
      const agentsid = last_updated_by;
      const matchingAgent = globalAgents.find(agent => String(agent.id) === String(agentsid));
      const agentNameText = matchingAgent ? matchingAgent.contact.name : "Unknown Agent";
      lastModifiedRow.appendChild(createLabelValue("By :", agentNameText));
      
      // Vertical line after the agent name
      const verticalLine2 = document.createElement("div");
      verticalLine2.style.gridRow = "span 1"; // Same for second vertical line
      verticalLine2.style.height = "20px";
      verticalLine2.style.marginTop = "10px"; 
      verticalLine2.style.marginLeft = "30px"; // Adjust the height as needed
      verticalLine2.style.borderLeft = "2px solid #ccc";
      lastModifiedRow.appendChild(verticalLine2);
      
      // Impacted tickets info
      const affectedTicketsText = affected_tickets_count === 0 ? "--" : affected_tickets_count;
      // lastModifiedRow.appendChild(createLabelValue("Impacted tickets (Last 7 days) :", affectedTicketsText));
      
      const impactedTickets = createLabelValue("Impacted tickets (Last 7 days) :", affectedTicketsText);
  impactedTickets.firstChild.style.marginLeft = "-50%"; // Adjust label alignment
  lastModifiedRow.appendChild(impactedTickets);




const cardBody = document.createElement("div"); // Create a container for card content and actions
cardBody.style.display = "flex"; // Flexbox to align items horizontally
cardBody.style.justifyContent = "space-between"; // Ensure there's space between content and actions
cardBody.style.alignItems = "flex-start"; // Align items to the top (optional, depending on your needs)
       

const truncatedContent = truncateContent(combinedContent, 200, 2);

const cardContent = document.createElement("pre");
cardContent.textContent = truncatedContent;

// Style the card content
cardContent.style.marginTop = "8px";
cardContent.style.padding = "8px";
cardContent.style.whiteSpace = "pre-wrap"; // Ensure text wraps
cardContent.style.overflow = "hidden"; // Hide overflow content
cardContent.style.textOverflow = "ellipsis"; // Add ellipsis for overflow
cardContent.style.maxWidth = "75%"; // Limit the card width to half the container's width
cardContent.style.fontSize="12px";
cardContent.style.color="#183247";
cardContent.style.fontweight="600";
cardContent.style.fontFamily= "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
cardContent.style.marginLeft="15px"

// Create the container for card actions
const cardActionsContainer = document.createElement("div");
cardActionsContainer.style.display = "flex"; // Display actions horizontally
cardActionsContainer.style.justifyContent = "flex-end"; // Align to the right
cardActionsContainer.style.marginTop = "10px"; // Add some spacing above the actions
cardActionsContainer.style.gap = "8px"; // Set space between the toggle and the delete icon

// Add fw-toggle
// const fwToggle = document.createElement("fw-toggle");
// fwToggle.setAttribute("size", "medium");
// fwToggle.setAttribute("checked", "");

// Add fw-icon
const fwIcon = document.createElement("fw-icon");
fwIcon.setAttribute("name", "delete");
fwIcon.setAttribute("size", "18");
fwIcon.style.cursor = "pointer";
fwIcon.style.color = "red"; // Set the color to red
// Add a pointer cursor for interactivity
fwIcon.title = "Delete";
fwIcon.addEventListener("click", () => {
  console.log("Delete icon clicked");

  console.log("Rule ID:", id);
  // const modal = document.getElementById("deleteConfirmationPopup");

  // if (modal) {
  //   modal.setAttribute("is-open", "true");

  //   modal.addEventListener(
  //     "fwSubmit",
  //     () => {
  //       console.log("Delete confirmed.");
       
  //       try {
  //         confirmDeletions(id);
            
    
  //         } catch (error) {
  //             console.error("❌ Error in deletion process:", error);
  //         }

        
  //       modal.removeAttribute("is-open");
  //     },
  //     { once: true }
  //   );

  //   // Handle Cancel (Close)
  //   modal.querySelector("fw-modal-footer").addEventListener(
  //     "fwClose",
  //     () => {
  //       modal.removeAttribute("is-open");
  //       console.log("Delete operation was cancelled.");
  //     },
  //     { once: true }
  //   );
  // } else {
  //   console.error("Modal element with ID 'composition' not found.");
  // }


  const modal = document.createElement("fw-modal");
  modal.setAttribute("id", "deleteConfirmationPopup");
  modal.setAttribute("title-text", "Delete Rule");
  modal.setAttribute("is-open", "false");
  
  // Modal content
  const content = document.createElement("fw-text");
  content.textContent = "Are you sure you want to delete the rule?";
  modal.appendChild(content);
  
  // Modal footer
  const footer = document.createElement("fw-modal-footer");
  modal.appendChild(footer);
  
  // Add modal to document
  document.body.appendChild(modal);
  
  // ✅ Show and handle modal behavior
  const deleteModal = document.getElementById("deleteConfirmationPopup");
  
  if (deleteModal) {
    deleteModal.setAttribute("is-open", "true");
  
    // Confirm (Submit) action
    deleteModal.addEventListener(
      "fwSubmit",
      () => {
        console.log("Delete confirmed.");
  
        try {
          confirmDeletions(id); // Ensure `id` is defined in scope
        } catch (error) {
          console.error("❌ Error in deletion process:", error);
        }
  
        deleteModal.removeAttribute("is-open");
      },
      { once: true }
    );
  
    // Cancel (Close) action
    const footer = deleteModal.querySelector("fw-modal-footer");
    if (footer) {
      footer.addEventListener(
        "fwClose",
        () => {
          deleteModal.removeAttribute("is-open");
          console.log("Delete operation was cancelled.");
        },
        { once: true }
      );
    }
  } else {
    console.error("Modal element with ID 'deleteConfirmationPopup' not found.");
  }
  

  
});



async function Fetchentity(automationTypeId, nextMarker = null, allRecords1 = []) {
  try {
    if (!newRulePloadDB5) {
      console.error(" Entity is not initialized yet!");
      showLoader();
      setTimeout(() => {
        location.reload();
    }, 1000);
    }

    showLoader(); 

    let queryObj = {
      query: {
        $and: [
          { automation_type_id: automationTypeId },
      
          { active: "true" } 
        ]
      } 
    };


    if (nextMarker) {
      console.log("Next marker found:", nextMarker);
      queryObj.next = { marker: nextMarker };
    }

    console.log("📤 Fetching records with query:", JSON.stringify(queryObj, null, 2));

    const response = await newRulePloadDB5.getAll(queryObj);

    if (!response.records || !Array.isArray(response.records)) {
      console.error("❌ Invalid response format:", response);
      hideLoader(); 
      return allRecords1;
    }

    console.log(`📥 Retrieved ${response.records.length} records`);
    allRecords1 = allRecords1.concat(response.records);

    const newNextMarker = response.links?.next?.marker || null;

    if (newNextMarker) {
      console.log(`More pages exist. Next marker: ${newNextMarker}`);
      return Fetchentity(automationTypeId, newNextMarker, allRecords1);
    } else {
      console.log("✅ No more pages.");
      console.log(`📌 Total Filtered Records: ${allRecords1.length}`);

      hideLoader();


      if (automationTypeId === 4) {
   
        return findDuplicateRulestype4(allRecords1);
      } else {
        console.warn("⚠️ Unknown automationTypeId:", automationTypeId);
        return allRecords1;
      }
      
    }
  } catch (error) {
    console.error("❌ Error fetching filtered records:", error);
    hideLoader(); 
    return [];
  }
}
async function confirmDeletions(id) {
  console.log(" Deleting rule with ID:", id);

  // Start progress loader
  let progressLoader = document.querySelector("#progress-container");
  if (progressLoader && typeof progressLoader.start === "function") {
      progressLoader.start();
  }

  try {
      let getdeleteruleResponse = await client.request.invokeTemplate("deleterule", {
          context: { 
              automationid: 4, 
              ruleid: id 
          }
      });

      console.log("getdeleteruleResponse", getdeleteruleResponse);

      if (getdeleteruleResponse.status === 204) {
          console.log("✅ Rule deleted successfully!");

          // Show success toast
          let valid = document.getElementById('type_toast');
          valid.setAttribute('content', 'Rule deleted successfully');
          valid.setAttribute('type', 'success');
          valid.setAttribute('open', true);

          // ✅ Remove from UI
          removeDeletedRuleFromUI(id);
       

          console.log("Before deletion, existing rule IDs:", duplicatesType4.map(rule => rule.id));

          // ✅ Convert to string for comparison
          const ruleIdToDelete = String(id);

          // ✅ Find and delete rule from duplicatesType4
          const index = duplicatesType4.findIndex(rule => String(rule.id) === ruleIdToDelete);
          console.log("Rule index found:", index);

          if (index !== -1) {
              duplicatesType4.splice(index, 1); // Remove rule from array
              console.log("✅ Rule removed from duplicatesType4.");
          } else {
              console.warn("⚠️ Rule not found in duplicatesType4. Possible ID mismatch.");
          }

        
              console.log("Duplicates after deleting:", duplicatesType4);
              processAndDisplayDuplicates(duplicatesType4, "TicketUpdates1",globalAgents);
    

              let progressLoader = document.querySelector("#progress-container");
              if (progressLoader && typeof progressLoader.start === "function") {
                progressLoader.done();
              }


              if (entitytype4.length === 0) {
                console.log(" entitytype4 is empty. Fetching records...");
                entitytype4 = await Fetchentity(4); 
                // console.log("entity fethed after clicking recent data",entitytype4);
                // const { displayId, updatedArray } = getDisplayIdByRuleId(entitytype4, id);
                // console.log("**********Updated entitytype4 after deletion:***********", updatedArray);
                // displayGroupedRules(updatedArray,"TicketUpdates");
                // if (!displayId) return; // Ensure rule ID is available
              
                // try {
                //     console.log(" Deleting rule with ID:", displayId);
                //     await newRulePloadDB5.delete(displayId);
              
                // } catch (error) {
                //     console.warn(` Error deleting record with Display ID ${displayId}, but continuing...`);
                // }    
        
              }

              const { displayId, updatedArray } = getDisplayIdByRuleId(entitytype4, id);
              console.log("**********Updated entitytype4 after deletion:***********", updatedArray);
              displayGroupedRules(updatedArray,"TicketUpdates");
              if (!displayId) return; // Ensure rule ID is available
            
              try {
                  console.log(" Deleting rule with ID:", displayId);
                  await newRulePloadDB5.delete(displayId);
            
              } catch (error) {
                  console.warn(` Error deleting record with Display ID ${displayId}, but continuing...`);
              }   
      }
  } catch (error) {
      console.error("❌ Error deleting rule:", error);

      // Show error toast
      let errorToast = document.getElementById('type_toast');
      errorToast.setAttribute('content', "Failed to delete rule. Please try again.");
      errorToast.setAttribute('type', 'error');
      errorToast.setAttribute('open', true);
  } finally {
      // Ensure progress loader stops if an error occurs
      if (progressLoader && typeof progressLoader.done === "function") {
          progressLoader.done();
      }
  }

  // Hide the popup after action
 
}

// Function to remove the deleted rule from UI
function removeDeletedRuleFromUI(ruleId) {
    let ruleCard = document.querySelector(`[data-rule-id="${ruleId}"]`);
    if (ruleCard) {
        ruleCard.remove();
    }
}
function getDisplayIdByRuleId(entityRecords, id) {
  console.log("Checking all records for Rule ID:", id);

  if (!Array.isArray(entityRecords) || entityRecords.length === 0) {
    console.warn(" No records found in entity storage.");
    return { displayId: null, updatedArray: entityRecords };
  }

  const recordIndex = entityRecords.findIndex(record =>
    String(record?.data?.rule_id) === String(id)
  );

  if (recordIndex === -1) {
    console.warn(`❌ Rule ID ${id} not found in records.`);
    return { displayId: null, updatedArray: entityRecords };
  }

  const matchedRecord = entityRecords[recordIndex];
  const displayId = matchedRecord.display_id;

  // ✅ Remove the record from the original array
  entityRecords.splice(recordIndex, 1);

  console.log(`✅ Record with Rule ID ${id} and Display ID ${displayId} removed.`);

  return { displayId, updatedArray: entityRecords };
}

  
cardActionsContainer.appendChild(fwIcon);
card.appendChild(cardHeader);
cardBody.appendChild(cardContent);
cardBody.appendChild(cardActionsContainer);
card.appendChild(cardBody);
cardContainer.appendChild(horizontalLine);
// card.appendChild(horizontalLine);

cardContainer.appendChild(lastModifiedRow);
card.appendChild(cardContainer)
groupContainer.appendChild(card);
    });

    
    container.appendChild(groupContainer);
  });


  addFwPaginationDuplicates(containerId, duplicates,totalgroup);
}


function addFwPaginationDuplicates(containerId,duplicates,totalgroup) {
  console.log("Adding pagination to container:", containerId);

  let container = document.getElementById(containerId);

  if (!container) {
    console.warn(`Container with ID "${containerId}" not found.`);
    return;
  }
  console.log("itemsperpage duplicates*********",itemsPerPageDuplicates)
  if (totalgroup <= itemsPerPageDuplicates) {
    
    console.log("Total records are less than or equal to items per page, skipping pagination.");
    return;
  }

  let existingPagination2 = container.querySelector("#fw-pagination-duplicates");
  if (existingPagination2) {
    existingPagination2.remove(); 
  }

  const pagination2 = document.createElement("fw-pagination");
  pagination2.id = "fw-pagination-duplicates";
console.log("total group inside", )
  pagination2.setAttribute("total", totalgroup);
  pagination2.setAttribute("per-page", itemsPerPageDuplicates);
  pagination2.setAttribute("page", currentPageDuplicates);

  console.log("Pagination Element:", pagination2);

  const paginationWrapper2 = document.createElement("div");
  // paginationWrapper2.style.display = "flex";
  paginationWrapper2.style.justifyContent = "flex-start";
  paginationWrapper2.style.alignItems = "center";
  // paginationWrapper2.style.width = "100%";
  paginationWrapper2.style.marginLeft = "45%";

  paginationWrapper2.appendChild(pagination2);
  container.appendChild(paginationWrapper2);

  pagination2.addEventListener("fwChange", (event) => {
    console.log("fwChange Event Triggered", event);
    currentPageDuplicates = event.detail.page;
    console.log("Updated Page:", currentPageDuplicates);

    // Update the displayed rules for the current container
    processAndDisplayDuplicates(duplicates, containerId,globalAgents);
  });
}


async function Filterrecords(automationTypeId, containerid, nextMarker = null, allRecords = []) {
  try {
    if (!newRulePloadDB5) {
      console.error(" Entity is not initialized yet!");
      showLoader();
      setTimeout(() => {
        location.reload();
    }, 1000);
    }

  
    if (containerid === "Ticketcreation") {
      showLoader("Ticketcreation");
    } else if (containerid === "TicketUpdates") {
      showLoader("TicketUpdates");
    } else if (containerid === "HourlyTriggers") {
      showLoader("HourlyTriggers");
    }

    const queryObj = {
      query: {
        $and: [
          { automation_type_id: automationTypeId },
          { active: "true" }
        ]
      }
    };

   
    if (nextMarker) {
      console.log("🔄 Next marker found:", nextMarker);
      queryObj.next = { marker: nextMarker };
    }

    console.log("📤 Fetching records with query:", JSON.stringify(queryObj, null, 2));
    const response = await newRulePloadDB5.getAll(queryObj);

    if (!response.records || !Array.isArray(response.records)) {
      console.error("❌ Invalid response format:", response);
      
    
    }

    console.log(`📥 Retrieved ${response.records.length} records`);
    allRecords = allRecords.concat(response.records);

    const newNextMarker = response.links?.next?.marker || null;

    if (newNextMarker) {
      
      console.log(`🔄 More pages exist. Next marker: ${newNextMarker}`);
      return await Filterrecords(automationTypeId, containerid, newNextMarker, allRecords);
    }

    // ✅ All pages fetched
    console.log("✅ No more pages.");
    console.log(`📌 Total Filtered Records: ${allRecords.length}`);
    console.log("allrecords fetched from entity", allRecords);

    hideLoader();

    // ✅ Proceed to rule check
    if (automationTypeId === 1 || automationTypeId === 3) {
      return findDuplicateRulestype1and3(allRecords);
    } else if (automationTypeId === 4) {
      return findDuplicateRulestype4(allRecords);
    } else {
      console.warn("⚠️ Unknown automationTypeId:", automationTypeId);
      return allRecords;
    }
  } catch (error) {
    console.error("❌ Error fetching filtered records:", error);
    hideLoader(); 
    return [];
  }
}

// async function Filterrecords(automationTypeId,containerid, nextMarker = null, allRecords = []) {


//   console.log("filterrecords called for automationtypeid",containerid);

//   try {
//     if (!newRulePloadDB5) {
//       console.error(" Entity is not initialized yet!");
//       showLoader();
//       setTimeout(() => {
//         location.reload();
//     }, 1000);
//     }

  
//     if (containerid === "Ticketcreation") {
//       showLoader("Ticketcreation");
//     } else if (containerid === "TicketUpdates") {
//       showLoader("TicketUpdates");
//     } else if (containerid === "HourlyTriggers") {
//       showLoader("HourlyTriggers");
//     }
    

//     let queryObj = {
//       query: {
//         $and: [
//           { automation_type_id: automationTypeId },
      
//           { active: "true" } 
//         ]
//       } 
//     };

//     if (nextMarker) {
//       console.log(" Next marker found:", nextMarker);
//       queryObj.next = { marker: nextMarker };
//     }

//     console.log("Fetching records with query:", JSON.stringify(queryObj, null, 2));

//     const response = await newRulePloadDB5.getAll(queryObj);

//     if (!response.records || !Array.isArray(response.records)) {
//       console.error("Invalid response format:", response);
    
//     }
  

//     // if (response.status === 403) {
//     //   console.log("containerid", containerid);
//     //   if (containerid === "Ticketcreation") {
//     //     showLoader("Ticketcreation");
//     //   } else if (containerid === "TicketUpdates") {
//     //     showLoader("TicketUpdates");
//     //   } else if (containerid === "HourlyTriggers") {
//     //     showLoader("HourlyTriggers");
//     //   }
//     //   // await new Promise(resolve => setTimeout(resolve, 60000)); // wait 2 seconds
//     //   // return   await initializeDatabase();
//     // }
    
//     console.log(` Retrieved ${response.records.length} records`);
   
//     allRecords = allRecords.concat(response.records);

//     const newNextMarker = response.links?.next?.marker || null;
//     try {
//       if (newNextMarker) {
//         console.log(`More pages exist. Next marker: ${newNextMarker}`);
//         return Filterrecords(automationTypeId, newNextMarker, allRecords);
//       } else {
//         console.log("No more pages.");
//         console.log(`Total Filtered Records: ${allRecords.length}`);
    
//         hideLoader(); 
//         console.log("All records fetched from entity", allRecords);
    
//         if (automationTypeId === 1 || automationTypeId === 3) {
//           return findDuplicateRulestype1and3(allRecords);
//         } else if (automationTypeId === 4) {
//           return findDuplicateRulestype4(allRecords);
//         } else {
//           console.warn("⚠️ Unknown automationTypeId:", automationTypeId);
//           return allRecords;
//         }
//       }
//     } catch (error) {
//       hideLoader();
//       if (error.status === 403 || error.message?.includes('403')) {
//         console.error("❌ 403 Forbidden error occurred.");
//         // Optionally display a user-friendly message or retry logic
//       } else {
//         console.error("❌ Unexpected error:", error);
//       }
//       return []; // or handle gracefully
//     }
    
//     // if (newNextMarker) {
//     //   console.log(` More pages exist. Next marker: ${newNextMarker}`);
//     //   return Filterrecords(automationTypeId, newNextMarker, allRecords);
//     // } else {
//     //   console.log(" No more pages.");
//     //   console.log(`Total Filtered Records: ${allRecords.length}`);

//     //   hideLoader(); 
//     //   console.log("allrecords fetched from entity",allRecords);
    
//     //   if (automationTypeId === 1) {
//     //     return findDuplicateRulestype1and3(allRecords);
//     //   } else if(automationTypeId === 3)
//     //   {
  
//     //     return findDuplicateRulestype1and3(allRecords);
//     //   }
//     //   else if (automationTypeId === 4) {

//     //     return findDuplicateRulestype4(allRecords);
//     //   } else {
//     //     console.warn("⚠️ Unknown automationTypeId:", automationTypeId);
//     //     return allRecords;
//     //   }
//     // }
//   } catch (error) {
//     console.error("❌ Error fetching filtered records:", error);
//     hideLoader(); 
//     return [];
//   }
// }


const findDuplicateRulestype1and3 = (records) => {
  const seenRules = new Map();
  const duplicateRecords = [];

  const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

  const cleanText = (text) =>
    stripImageTags(String(text))
      .toLowerCase()
      .replace(/&nbsp;/gi, " ")       // replace non-breaking space
      .replace(/<[^>]*>/g, "")        // remove remaining HTML tags
      .replace(/[,\.]/g, "")          // remove commas and periods
      .replace(/([a-zA-Z])(\d)/g, "$1 $2") // split letters and digits
      .replace(/(\d)([a-zA-Z])/g, "$1 $2") // split digits and letters
      .replace(/\s+/g, " ")           // normalize whitespace
      .trim()
      .replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");  // ensure correct spacing

  const normalizeConditionParts = (rawConditions) => {
    const parts = rawConditions?.split(",") || [];
    const set1 = [];
    const set2 = [];
    let currentSet = null;

    for (let i = 0; i < parts.length; i++) {
      let part = cleanText(parts[i]);
      if (part === "condition set 1") {
        currentSet = set1;
        continue;
      }
      if (part === "condition set 2") {
        currentSet = set2;
        continue;
      }
      if (currentSet) currentSet.push(part);
    }

    set1.sort();
    set2.sort();
    return { set1: set1.join(","), set2: set2.join(",") };
  };

  const normalizeActions = (actions) => {
    if (Array.isArray(actions)) {
      return actions
        .map((action) =>
          Object.values(action)
            .map((v) => cleanText(v))
            .join(" ")
        )
        .sort()
        .join(",");
    } else if (typeof actions === "string") {
      return actions
        .split(",")
        .map((a) => cleanText(a))
        .sort()
        .join(",");
    }
    return "";
  };

  records.forEach((record) => {
    const { conditions, actions, operator } = record.data;

    const { set1, set2 } = normalizeConditionParts(conditions);
    const normalizedActions = normalizeActions(actions);
    const normalizedOperator = operator ? cleanText(operator) : "";

    const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
    const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;

    // Check if key1 or key2 already exists in the seen rules
    if (seenRules.has(key1) || seenRules.has(key2)) {
      const existing = seenRules.get(key1) || seenRules.get(key2);
      if (!duplicateRecords.includes(existing)) {
        duplicateRecords.push(existing);
      }
      duplicateRecords.push(record);
    } else {
      seenRules.set(key1, record);
    }
  });

  return duplicateRecords;
};





//original code 
// function findDuplicateRulestype1and3(records) {
//   const seenRules = new Map();
//   const duplicateRecords = [];

//   const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

//   const removeDotsAndCommas = (text) =>
//     text
//       .replace(/&nbsp;/gi, " ")
//       .replace(/[.,]/g, "")
//       .replace(/\s+/g, " ")
//       .trim();

//   const normalizeConditionParts = (rawConditions) => {
//     const parts = rawConditions?.split(",") || [];
//     const set1 = [];
//     const set2 = [];
//     let currentSet = null;

//     for (let i = 0; i < parts.length; i++) {
//       let part = removeDotsAndCommas(parts[i].trim().toLowerCase());
//       if (part === "condition_set_1") {
//         currentSet = set1;
//         continue;
//       }
//       if (part === "condition_set_2") {
//         currentSet = set2;
//         continue;
//       }
//       if (currentSet) currentSet.push(part);
//     }

//     set1.sort();
//     set2.sort();
//     return { set1: set1.join(","), set2: set2.join(",") };
//   };

//   const normalizeActions = (actions) => {
//     if (Array.isArray(actions)) {
//       return actions
//         .map((action) =>
//           Object.values(action)
//             .map((v) =>
//               removeDotsAndCommas(
//                 stripImageTags(String(v)).toLowerCase().trim()
//               )
//             )
//             .join(" ")
//         )
//         .sort()
//         .join(",");
//     } else if (typeof actions === "string") {
//       return stripImageTags(actions)
//         .split(",")
//         .map((a) => removeDotsAndCommas(a.trim().toLowerCase()))
//         .sort()
//         .join(",");
//     }
//     return "";
//   };

//   records.forEach((record, index) => {
//     const { conditions, actions, operator } = record.data;

//     const { set1, set2 } = normalizeConditionParts(conditions);
//     const normalizedActions = normalizeActions(actions);
//     const normalizedOperator = operator ? operator.trim().toLowerCase() : "";

//     // Try both original and swapped condition set combinations
//     const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
//     const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;

//     console.log(`=== Record ${index + 1} ===`);
//     console.log("Original Conditions:", conditions);
//     console.log("Condition Set 1:", set1);
//     console.log("Condition Set 2:", set2);
//     console.log("Actions:", normalizedActions);
//     console.log("Key 1:", key1);
//     console.log("Key 2:", key2);

//     if (seenRules.has(key1) || seenRules.has(key2)) {
//       console.log(`✅ Duplicate found for Record ${index + 1}`);
//       const existing = seenRules.get(key1) || seenRules.get(key2);
//       if (!duplicateRecords.includes(existing)) {
//         duplicateRecords.push(existing);
//       }
//       duplicateRecords.push(record);
//     } else {
//       seenRules.set(key1, record);
//       console.log(`✅ First time seen for Record ${index + 1}`);
//     }
//   });

//   return duplicateRecords;
// }





// function findDuplicateRulestype1and3(records) {
//   console.log("newfunction**********************")
//   const seenRules = new Map();
//   const duplicateRecords = [];

//   const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

//   const cleanText = (text) =>
//     stripImageTags(String(text))
//       .toLowerCase()
//       .replace(/&nbsp;/gi, " ")
//       .replace(/[.,]/g, "")
//       .replace(/([a-zA-Z])(\d)/g, "$1 $2") // split letters and digits
//       .replace(/(\d)([a-zA-Z])/g, "$1 $2") // split digits and letters
//       .replace(/\s+/g, " ")
//       .trim();

//   const normalizeConditionParts = (rawConditions) => {
//     const parts = rawConditions?.split(",") || [];
//     const set1 = [];
//     const set2 = [];
//     let currentSet = null;

//     for (let i = 0; i < parts.length; i++) {
//       let part = cleanText(parts[i]);
//       if (part === "condition set 1") {
//         currentSet = set1;
//         continue;
//       }
//       if (part === "condition set 2") {
//         currentSet = set2;
//         continue;
//       }
//       if (currentSet) currentSet.push(part);
//     }

//     set1.sort();
//     set2.sort();
//     return { set1: set1.join(","), set2: set2.join(",") };
//   };

//   const normalizeActions = (actions) => {
//     if (Array.isArray(actions)) {
//       return actions
//         .map((action) =>
//           Object.values(action)
//             .map((v) => cleanText(v))
//             .join(" ")
//         )
//         .sort()
//         .join(",");
//     } else if (typeof actions === "string") {
//       return actions
//         .split(",")
//         .map((a) => cleanText(a))
//         .sort()
//         .join(",");
//     }
//     return "";
//   };

//   records.forEach((record, index) => {
//     const { conditions, actions, operator } = record.data;

//     const { set1, set2 } = normalizeConditionParts(conditions);
//     const normalizedActions = normalizeActions(actions);
//     const normalizedOperator = operator ? cleanText(operator) : "";

//     const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
//     const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;

//     console.log(`=== Record ${index + 1} ===`);
//     console.log("Original Conditions:", conditions);
//     console.log("Condition Set 1:", set1);
//     console.log("Condition Set 2:", set2);
//     console.log("Actions:", normalizedActions);
//     console.log("Key 1:", key1);
//     console.log("Key 2:", key2);

//     if (seenRules.has(key1) || seenRules.has(key2)) {
//       console.log(`✅ Duplicate found for Record ${index + 1}`);
//       const existing = seenRules.get(key1) || seenRules.get(key2);
//       if (!duplicateRecords.includes(existing)) {
//         duplicateRecords.push(existing);
//       }
//       duplicateRecords.push(record);
//     } else {
//       seenRules.set(key1, record);
//       console.log(`✅ First time seen for Record ${index + 1}`);
//     }
//   });

//   return duplicateRecords;
// }







let isFetchingType1 = false;
async function handleDuplicateRulestype(data) {
  console.log("type",data);
  try {
    if(data === 1){
      if (isFetchingType1|| type1 > 0) return;

      isFetchingType1 = true;
      console.log("handleDuplicateRulestype1 called");
      const duplicatesType1 = await Filterrecords(data,"Ticketcreation"); 
      entitytype1 = duplicatesType1;
      
      console.log(" Final duplicate records of type 1:", duplicatesType1);
      console.log("entity copy array",entitytype1);
      displayGroupedRules(duplicatesType1, "Ticketcreation");
    }else if (data ===3){
      if (isFetchingType3 || type3 > 0) return; 
  
    isFetchingType3 = true; 
    console.log("handleDuplicateRulestype3 called");
      const duplicatesType3 = await Filterrecords(data,"HourlyTriggers"); 
      entitytype3 = duplicatesType3;
    
      console.log(" Final duplicate records of type 3:", duplicatesType3);
      console.log("entity copy array",entitytype3);
      displayGroupedRules(duplicatesType3, "HourlyTriggers"); 
      type3++;
    }
    else{
      if (isFetchingType4 || type4 > 0) return; 
  
      isFetchingType4 = true; 
      console.log("handleDuplicateRulestype4 called");
  
      const duplicatesType4 = await Filterrecords(data,"TicketUpdates"); 
      entitytype4 = duplicatesType4;
   
      console.log(" Final duplicate records of type 4:", duplicatesType4);
      console.log("entity copy array",entitytype4);
      displayGroupedRules(duplicatesType4, "TicketUpdates");
      type4++; 
    }
  } catch (error) {
      console.error("❌ Error fetching duplicate rules in handleduplicate:", error);
      if(error.status === 401){
        document.getElementById("Automation-page").style.display = "none";
        document.getElementById("Workflow-Automation-page").style.display = "none";
        
        document.getElementById("no_user2").style.display = "block";
      
      }
  }
}


function stripHTML(input) {
  if (!input || typeof input !== 'string') return '';

  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = input;

  const text = tempDiv.textContent || tempDiv.innerText || '';

  return text
    .replace(/\u00A0/g, ' ')   
    .replace(/&nbsp;/gi, ' ') 
    .replace(/\s+/g, ' ')      
    .trim();
}


function showPopupCard(title, content, automation_type_id) {

  if (automation_type_id !== undefined && automation_type_id !== null) {
      localStorage.setItem("automation_type_id", automation_type_id); 
  } else {
      automation_type_id = localStorage.getItem("automation_type_id") || "Unknown";
  }

  console.log("logPopup", automation_type_id);



const overlay = document.createElement("div");
overlay.style.position = "fixed";


overlay.style.top = "0";
overlay.style.left = "0";
overlay.style.width = "100%";
overlay.style.height = "100%";
overlay.style.backgroundColor = "rgba(0, 0, 0, 0.3)"; // Semi-transparent dark background
overlay.style.backdropFilter = "blur(5px)"; // Apply blur effect
overlay.style.zIndex = "999"; // Ensure it appears above everything else
document.body.style.overflow = "hidden";
document.body.appendChild(overlay);
// Create popup container
const popupContainer = document.createElement("div");
popupContainer.style.position = "fixed";
popupContainer.style.top = "50%";
popupContainer.style.left = "50%";
popupContainer.style.transform = "translate(-50%, -50%)";
popupContainer.style.width = "50%"; // Increased default width
popupContainer.style.maxWidth = "95%"; // Ensure it fits on smaller screens
// popupContainer.style.height = "80%"; // Use viewport height to limit size
popupContainer.style.backgroundColor = "#fff";
popupContainer.style.border = "1px solid #ccc";
popupContainer.style.boxShadow = "0 4px 8px rgba(0, 0, 0, 0.2)";
popupContainer.style.borderRadius = "12px"; // Increased border radius for a smoother look
popupContainer.style.overflow = "hidden"; // Prevent content overflow
popupContainer.style.fontFamily =
  "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"; // Apply a system font
popupContainer.style.zIndex = "1000";
popupContainer.style.display = "flex";
popupContainer.style.flexDirection = "column";
popupContainer.style.height = "auto";
popupContainer.style.maxHeight = "80vh";


// Create header for title (fixed position)
const popupHeader = document.createElement("div");
popupHeader.style.padding = "16px 24px";
popupHeader.style.borderBottom = "1px solid #ddd"; // Separate the title visually
popupHeader.style.backgroundColor = "#fff";
popupHeader.style.zIndex = "10"; // Ensure it appears above the scrollable content

// Popup title
const popupTitle = document.createElement("h2");
popupTitle.textContent = title;
popupTitle.style.paddingLeft = "15px"; // Move the title slightly to the right
popupTitle.style.fontSize = "20px";
popupTitle.style.color = "#333";
popupTitle.style.textAlign = "left";
popupHeader.appendChild(popupTitle);



// Content wrapper (flex layout)
const contentWrapper = document.createElement("div");
contentWrapper.style.display = "flex";
contentWrapper.style.flexDirection = "column";
contentWrapper.style.flex = "1"; // Automatically take up available space
contentWrapper.style.overflow = "hidden"; // Prevent content overflow

// Content box (with fixed preview label)
const contentBox = document.createElement("div");
contentBox.style.flex = "1";
contentBox.style.border = "1px solid #ddd";
contentBox.style.borderRadius = "8px";
contentBox.style.backgroundColor = "#f9f9f9";
contentBox.style.padding = "16px";
contentBox.style.margin = "16px 16px"; // Add vertical spacing
contentBox.style.overflow = "hidden"; // Prevent outer scrolling
contentBox.style.marginBottom = "75px"; // Add enough space for the close button
contentBox.style.display = "flex";
contentBox.style.flexDirection = "column";

// Preview label and line (sticky inside content box)
const previewLabelContainer = document.createElement("div");
previewLabelContainer.style.position = "sticky"; // Fix inside the content box
previewLabelContainer.style.top = "0"; // Stick to the top
previewLabelContainer.style.backgroundColor = "#f9f9f9"; // Match the content box background
previewLabelContainer.style.zIndex = "1";
previewLabelContainer.style.padding = "8px 0";

const previewLabel = document.createElement("p");
previewLabel.textContent = "Preview"; // Label text
previewLabel.style.fontSize = "16px";
previewLabel.style.fontWeight = "500";
previewLabel.style.color = "#92a2b1";
previewLabel.style.margin = "0";

const lineBelowLabel = document.createElement("hr");
lineBelowLabel.style.border = "none";
lineBelowLabel.style.borderTop = "1px solid #ddd";
lineBelowLabel.style.margin = "8px 0";

previewLabelContainer.appendChild(previewLabel);
previewLabelContainer.appendChild(lineBelowLabel);

// Scrollable content area

const scrollableContent = document.createElement("div");
scrollableContent.style.overflowY = "auto"; // Enable vertical scrolling
// scrollableContent.style.height = "calc(100% - 40px)"; // Adjust to fit within the content box
scrollableContent.style.height = "auto"; // Allow dynamic growth
scrollableContent.style.maxHeight = "60vh";
scrollableContent.style.flex = "1"; // Fill vertical space in contentBox

scrollableContent.style.minHeight = "0";


  const eventText = document.createElement("div");
  eventText.style.marginBottom = "12px";
  const createCustomBullet = (text, bulletColor, highlightColor) => {
    const listItem = document.createElement("li");
    listItem.style.position = "relative"; // For positioning the custom bullet
    listItem.style.paddingLeft = "10px"; // Space for custom bullet
  
    // Create the custom double circular bullet using a span element
    const bullet = document.createElement("span");
    bullet.style.position = "absolute";
    bullet.style.left = "-15px"; // Bring the bullet closer to the text
    bullet.style.top = "50%"; // Center the bullet vertically
    bullet.style.transform = "translateY(-50%)"; // Center the bullet exactly
    bullet.style.width = "12px"; // Outer ring size
    bullet.style.height = "12px";
    bullet.style.border = `4px solid ${bulletColor || "#dcdfe1"}`; // Outer ring color and border size
    bullet.style.borderRadius = "50%"; // Make it a ring (circle with border)
    bullet.style.display = "inline-block";
  
    // Create the inner circle (smaller circle inside the outer ring)
    const innerBullet = document.createElement("span");
    innerBullet.style.position = "absolute";
    innerBullet.style.left = "50%";
    innerBullet.style.top = "50%";
    innerBullet.style.transform = "translate(-50%, -50%)"; // Centering the inner circle
    innerBullet.style.width = "2px"; // Inner circle size
    innerBullet.style.height = "2px";
    innerBullet.style.borderRadius = "50%"; // Inner circle rounded
    innerBullet.style.display = "inline-block";
  
    // Append the inner circle to the outer circle (bullet)
    bullet.appendChild(innerBullet);
  
    // Split the text into words
    const words = text.split(" ");
    
    // Extract specific words
    const firstWord = words.shift(); // Remove first word
    const secondWord = words.shift(); // Remove second word
    const lastWord = words.pop(); // Extract last word
    const remainingText = words.join(" "); // Remaining words (excluding first, second, and last)
  
    // Construct the innerHTML with the second word in black and the last word in highlight color
    listItem.innerHTML = `
      <span>${firstWord}</span> 
      <span style="color: black; font-weight: 500;">${secondWord}</span> 
      ${remainingText} 
      <span style="color: ${highlightColor}; font-weight: 500;">${lastWord}</span>
    `;
  
    // Append the custom double circular bullet to the list item
    listItem.insertBefore(bullet, listItem.firstChild);
  
    return listItem;
  };
  

  
  // Create the heading "Event:"
  const eventLabel = document.createElement("p");
  eventLabel.textContent = "Event";
  eventLabel.style.margin = "0";
  eventLabel.style.color = "#00a886"; // Blue color for heading
  eventLabel.style.fontWeight = "bold";
  eventLabel.style.fontSize = "16px";

  // Create the unordered list for the event details
  const eventDetail = document.createElement("ul");
  eventDetail.style.margin = "8px 0 0 -15px"; // Add margin and indentation
  eventDetail.style.color = "#333"; // Normal color for text
  eventDetail.style.listStyleType = "none"; // Remove default bullets
  eventDetail.style.fontSize = "14px";
 
  if (Number(automation_type_id) === 1){
  const eventBullet = createCustomBullet(
    "When Ticket is Created", // Text content
    "#2c5cc5", // Bullet color
    "#00a886" // Highlight color for the last word
  );
  eventDetail.appendChild(eventBullet);
  
  // Append the heading and the event detail to the container
  eventText.appendChild(eventLabel);
  eventText.appendChild(eventDetail);

  }

  const createCustomBullet1 = (text, bulletColor, highlightColor) => {
    const listItem = document.createElement("li");
    listItem.style.position = "relative"; // For positioning the custom bullet
    listItem.style.paddingLeft = "10px"; // Space for custom bullet
  
    // Create the custom double circular bullet using a span element
    const bullet = document.createElement("span");
    bullet.style.position = "absolute";
    bullet.style.left = "-15px"; // Bring the bullet closer to the text
    bullet.style.top = "50%"; // Center the bullet vertically
    bullet.style.transform = "translateY(-50%)"; // Center the bullet exactly
    bullet.style.width = "12px"; // Outer ring size
    bullet.style.height = "12px";
    bullet.style.border = `4px solid ${bulletColor || "#dcdfe1"}`; // Outer ring color and border size
    bullet.style.borderRadius = "50%"; // Make it a ring (circle with border)
    bullet.style.display = "inline-block";
  
    // Create the inner circle (smaller circle inside the outer ring)
    const innerBullet = document.createElement("span");
    innerBullet.style.position = "absolute";
    innerBullet.style.left = "50%";
    innerBullet.style.top = "50%";
    innerBullet.style.transform = "translate(-50%, -50%)"; // Centering the inner circle
    innerBullet.style.width = "2px"; // Inner circle size
    innerBullet.style.height = "2px";
    innerBullet.style.borderRadius = "50%"; // Inner circle rounded
    innerBullet.style.display = "inline-block";
  
    // Append the inner circle to the outer circle (bullet)
    bullet.appendChild(innerBullet);
  
    // Split the text into words
    const words = text.split(" ");
    
    // Extract specific words
    const firstWord = words.shift(); // Remove first word
    const secondWord = words.shift(); // Remove second word
    const lastFourWords = words.splice(-4).join(" "); // Get last four words
    const remainingText = words.join(" "); // Remaining words (excluding first, second, and last four)
  
    // Construct the innerHTML with the second word in black and the last four words in highlight color
    listItem.innerHTML = `
      <span>${firstWord}</span> 
      <span style="color: black; font-weight: 500;">${secondWord}</span> 
      ${remainingText} 
      <span style="color: ${highlightColor}; font-weight: 500;">${lastFourWords}</span>
    `;
  
    // Append the custom double circular bullet to the list item
    listItem.insertBefore(bullet, listItem.firstChild);
  
    return listItem;
  };
  

  
  if (Number(automation_type_id) === 3){
    const eventBullet = createCustomBullet1(
      "When Ticket is is checked every hour", // Text content
      "#2c5cc5", // Bullet color
      "#00a886" // Highlight color for the last word
    );
    eventDetail.appendChild(eventBullet);
    
    // Append the heading and the event detail to the container
    eventText.appendChild(eventLabel);
    eventText.appendChild(eventDetail);
  
    }
  // Create the conditions heading
  const conditionText = document.createElement("div");
  conditionText.textContent = "Condition";
  conditionText.style.marginBottom = "8px";
  conditionText.style.fontWeight = "bold";
  conditionText.style.color = "#e86f25"; // Green color for conditions heading
  conditionText.style.fontSize = "16px";
  
  // Create a container for the conditions list
  const conditionsList = document.createElement("ul");
  conditionsList.style.margin = "0 0 12px";
  conditionsList.style.padding = "8px";
  conditionsList.style.border = "1px solid #ddd";
  conditionsList.style.borderRadius = "4px";
  conditionsList.style.backgroundColor = "#fff";
  conditionsList.style.listStyleType = "none"; // Remove default bullet style
  conditionsList.style.fontSize = "14px";
  
 // Extract condition sets and operator
const conditionsArray1 = Array.isArray(content.conditions.condition_set_1)
? content.conditions.condition_set_1
: [];
const conditionsArray2 = Array.isArray(content.conditions.condition_set_2)
? content.conditions.condition_set_2
: [];
const operator = content.conditions.operator || "";




// Function to create a styled bullet point for conditions/actions
const createConditionBullet = (condition, bulletColor = "#dcdfe1") => {
  


  const listItem = document.createElement("li");
  listItem.style.position = "relative";
  listItem.style.paddingLeft = "30px"; // Space for bullet
  listItem.style.display = "flex"; // Prevents breaking lines
  listItem.style.alignItems = "center"; // Keeps elements aligned

  // Create custom bullet
  const bullet = document.createElement("span");
  bullet.style.position = "absolute";
  bullet.style.left = "0";
  bullet.style.top = "50%";
  bullet.style.transform = "translateY(-50%)";
  bullet.style.width = "12px";
  bullet.style.height = "12px";
  bullet.style.border = `4px solid ${bulletColor || "#dcdfe1"}`;
  bullet.style.borderRadius = "50%";

  // Inner circle of bullet
  const innerBullet = document.createElement("span");
  innerBullet.style.position = "absolute";
  innerBullet.style.left = "50%";
  innerBullet.style.top = "50%";
  innerBullet.style.transform = "translate(-50%, -50%)";
  innerBullet.style.width = "8px";
  innerBullet.style.height = "8px";
  innerBullet.style.borderRadius = "50%";

  bullet.appendChild(innerBullet);

  // **Formatting Condition with Colors**
  let formattedCondition = condition
    .replace(/<div/g, ' <div') // Add space before <div> tags if missing
    .replace(/<div\s+class\s*=\s*["']?SummaryKey["']?\s*>(.*?)<\/div>/gi, ' <span style="color: black; font-weight: 500;">$1</span> ') 
    .replace(/<div\s+class\s*=\s*["']?SummaryValue["']?\s*>(.*?)<\/div>/gi, ' <span style="color: #00a886; font-weight: 500;">$1</span> ') 
    .replace(/<div\s+class\s*=\s*["']?SummaryOperator["']?\s*>(.*?)<\/div>/gi, ' <span> $1 </span> ') // Ensure space around operators
    .replace(/>\s+</g, '> <')  // Ensures space between inline elements
    .replace(/\s+/g, ' ')      // Remove multiple spaces
    .trim();                   // Trim any leading/trailing spaces

 

  // // Set bullet first, then append formatted text
  listItem.appendChild(bullet);
  
  // Create a span for the condition text (for proper spacing)
  const textSpan = document.createElement("span");
  textSpan.innerHTML = formattedCondition;
  textSpan.style.marginLeft = "-5px"; // Ensure space between bullet and text
  listItem.appendChild(textSpan);

  console.log("✅ Final List Item InnerHTML:", listItem.innerHTML); // Log final output

  return listItem;
};


// Add conditions from condition_set_1
conditionsArray1.forEach((condition) => {
if (condition === "AND" || condition === "OR") {
  // Add operator as a separate text element
  const operatorItem = document.createElement("div");
  operatorItem.textContent = condition;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  conditionsList.appendChild(operatorItem);
} else {
  conditionsList.appendChild(createConditionBullet(condition, "#2c5cc5")); // Blue bullet
}
});

// Add operator between conditions (if available)
if (operator) {
const operatorItem = document.createElement("div");
operatorItem.textContent = operator;
operatorItem.style.color = "#000000";
operatorItem.style.margin = "8px 0";
operatorItem.style.fontSize = "14px";
operatorItem.style.fontweight="bold"
conditionsList.appendChild(operatorItem);
}

// Add conditions from condition_set_2
conditionsArray2.forEach((condition) => {
if (condition === "AND" || condition === "OR") {
  const operatorItem = document.createElement("div");
  operatorItem.textContent = condition;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  conditionsList.appendChild(operatorItem);
} else {
  conditionsList.appendChild(createConditionBullet(condition, "#2c5cc5")); // Blue bullet
}
});

// Create actions heading
const actionText = document.createElement("div");
actionText.textContent = "Action";
actionText.style.marginBottom = "8px";
actionText.style.fontWeight = "bold";
actionText.style.color = "#2c5cc5";
actionText.style.fontSize = "16px";

// Create actions content
const actionContent = document.createElement("ul");
actionContent.style.margin = "0";
actionContent.style.padding = "8px";
actionContent.style.border = "1px solid #ddd";
actionContent.style.borderRadius = "4px";
actionContent.style.backgroundColor = "#fff";
actionContent.style.listStyleType = "none";
actionContent.style.fontSize = "14px";

const actionsArray = Array.isArray(content.actions) ? content.actions : [];

// Add actions with custom bullets
actionsArray.forEach((action) => {
if (action === "AND" || action === "OR") {
  const operatorItem = document.createElement("div");
  operatorItem.textContent = action;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  actionContent.appendChild(operatorItem);
} else {
  actionContent.appendChild(createConditionBullet(action, "#2c5cc5")); // Blue bullet for actions
}
});
  
  // Append the label and line to the content box
  contentBox.appendChild(previewLabel);
  contentBox.appendChild(lineBelowLabel);
  
  scrollableContent.appendChild(eventText);
  scrollableContent.appendChild(conditionText);
  scrollableContent.appendChild(conditionsList);
  scrollableContent.appendChild(actionText);
  scrollableContent.appendChild(actionContent);
  
  // Append content to the scrollable wrapper
  
  contentBox.appendChild(scrollableContent);
  
  // Create fw-button element with "primary" color
  const closeButton = document.createElement("fw-button");
  closeButton.setAttribute("color", "primary");
  closeButton.textContent = "Close";
  closeButton.style.position = "absolute";
  closeButton.style.bottom = "16px"; // Distance from the bottom
  closeButton.style.right = "16px"; // Distance from the right
  closeButton.style.padding = "8px 16px"; // Padding for the button
  closeButton.style.borderRadius = "4px"; // Rounded corners
  closeButton.style.cursor = "pointer";
  
  // Close popup and remove overlay when the button is clicked
  closeButton.addEventListener("click", () => {
    document.body.removeChild(popupContainer);
    document.body.removeChild(overlay);
    document.body.style.overflow = "";
  });
  
  popupContainer.appendChild(popupHeader); // Fixed title
  popupContainer.appendChild(contentBox);
  
  popupContainer.appendChild(closeButton); // Close button
  
  // Append elements to the document
  document.body.appendChild(overlay);
  document.body.appendChild(popupContainer);
  
  }





let currentPage = 1;
const itemsPerPage = 5;function stripHTML2(htmlString) {
  const div = document.createElement("div");
  div.innerHTML = htmlString;

  // Remove all tags except <img>
  [...div.querySelectorAll("*")].forEach(el => {
    if (el.tagName.toLowerCase() !== "img") {
      el.replaceWith(...el.childNodes);
    }
  });

  let text = div.textContent || div.innerText || "";

  text = text.replace(/\u00a0|&nbsp;/g, " ").replace(/\s+/g, " ").trim();
  return text;
}

function cleanTextEntities(text) {
  return text
    .replace(/\u00a0|&nbsp;/g, " ")
    .replace(/\s+/g, " ")
    .trim();
}

function normalizeText2(text) {
  return text
    .toLowerCase()
    .replace(/&nbsp;/gi, " ")           // Replace &nbsp; with space
    .replace(/[.,]/g, "")   // Remove punctuation
    .replace(/\s+/g, " ")               // Collapse multiple spaces
    .trim()
    .split(" ")                         // Split into words
    .sort()                             // Sort for consistent order
    .join(" ");                         // Rejoin into a string
}

function normalizeList(text) {
  return text
    ? text
        .split(",")
        .map((item) =>
          item
            .trim()
            .toLowerCase()
            .replace(/[.,]/g, "") // Remove periods and commas
            .replace(/\s+/g, " ") // Normalize spacing
        )
        .sort()
        .join(",")
    : "";
}

function removeImgTags(htmlString) {
  const div = document.createElement("div");
  div.innerHTML = htmlString;

  [...div.querySelectorAll("img")].forEach(img => img.remove());
  return div.textContent || div.innerText || "";
}

function displayGroupedRules(records, containerId) {
  const container = document.getElementById(containerId);
  if (!container) {
    console.error(`Container with ID "${containerId}" not found.`);
    return;
  }

  container.innerHTML = "";

  if (records.length <= 1) {
    container.innerHTML = `
      <div style="
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80%;
        font-size: 24px;
        font-weight: bold;
        color: #333;
        text-align: center;
        margin: 300px auto;
      ">
        No duplicate rules found.
      </div>`;
    return;
  }

  const groupedRules = new Map();

  const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

  const cleanText = (text) =>
    text
      .replace(/&nbsp;|\u00a0/g, " ")
      .replace(/[.,]/g, "")
      .replace(/\s+/g, " ")
      .trim()
      .toLowerCase();

  const normalizeConditionParts = (rawConditions) => {
    const parts = rawConditions?.split(",") || [];
    const set1 = [], set2 = [];
    let currentSet = null;

    for (let i = 0; i < parts.length; i++) {
      const part = cleanText(parts[i]);
      if (part === "condition_set_1") {
        currentSet = set1;
        continue;
      }
      if (part === "condition_set_2") {
        currentSet = set2;
        continue;
      }
      if (currentSet) {
        const words = part.split(" ").filter(Boolean).sort().join(" ");
        currentSet.push(words);
      }
    }

    set1.sort();
    set2.sort();
    return {
      key1: `${set1.join(",")}|${set2.join(",")}`,
      key2: `${set2.join(",")}|${set1.join(",")}`, // Full swap allowed
    };
  };

  const normalizeActions = (actions) => {
    let words = [];
    if (Array.isArray(actions)) {
      words = actions.flatMap((action) =>
        Object.values(action).flatMap((v) =>
          cleanText(stripImageTags(String(v)))
            .split(" ")
            .map(word => word.replace(/\s+/g, "")) // REMOVE inner spaces
        )
      );
    } else if (typeof actions === "string") {
      words = actions
        .split(",")
        .flatMap((a) =>
          cleanText(stripImageTags(a))
            .split(" ")
            .map(word => word.replace(/\s+/g, "")) // REMOVE inner spaces
        );
    }
    return words.sort().join(",");
  };
  

  records.forEach((record) => {
    const { data, display_id } = record;
    const {
      name, summary, position, updated_at, last_updated_by,
      affected_tickets_count, rule_id, automation_type_id,
      conditions, actions, agentName, operator
    } = data;

    const { key1, key2 } = normalizeConditionParts(conditions);
    const normalizedActions = normalizeActions(actions);
    const normalizedOperator = operator ? cleanText(operator) : "";

    const groupKey1 = `${key1}|${normalizedActions}|${normalizedOperator}`;
    const groupKey2 = `${key2}|${normalizedActions}|${normalizedOperator}`;

    let groupKey = groupedRules.has(groupKey1)
      ? groupKey1
      : groupedRules.has(groupKey2)
      ? groupKey2
      : groupKey1;

    if (!groupedRules.has(groupKey)) {
      groupedRules.set(groupKey, { rules: [] });
    }

    groupedRules.get(groupKey).rules.push({
      name,
      position,
      summary,
      updated_at,
      last_updated_by,
      affected_tickets_count,
      rule_id,
      automation_type_id,
      display_id,
      agentName
    });
  });

// function stripHTML2(htmlString) {
//   const div = document.createElement("div");
//   div.innerHTML = htmlString;

//   // Remove all tags except <img>
//   [...div.querySelectorAll("*")].forEach(el => {
//     if (el.tagName.toLowerCase() !== "img") {
//       el.replaceWith(...el.childNodes);
//     }
//   });

//   let text = div.textContent || div.innerText || "";

//   text = text.replace(/\u00a0|&nbsp;/g, " ").replace(/\s+/g, " ").trim();
//   return text;
// }

// function cleanTextEntities(text) {
//   return text
//     .replace(/\u00a0|&nbsp;/g, " ")
//     .replace(/\s+/g, " ")
//     .trim();
// }

// function normalizeText2(text) {
//   return text
//     .toLowerCase()
//     .replace(/&nbsp;/gi, " ")           // Replace &nbsp; with space
//     .replace(/[.,]/g, "")   // Remove punctuation
//     .replace(/\s+/g, " ")               // Collapse multiple spaces
//     .trim()
//     .split(" ")                         // Split into words
//     .sort()                             // Sort for consistent order
//     .join(" ");                         // Rejoin into a string
// }


// function normalizeList(text) {
//   return text
//     ? text
//         .split(",")
//         .map((item) =>
//           item
//             .trim()
//             .toLowerCase()
//             .replace(/[.,]/g, "") // Remove periods and commas
//             .replace(/\s+/g, " ") // Normalize spacing
//         )
//         .sort()
//         .join(",")
//     : "";
// }


// function removeImgTags(htmlString) {
//   const div = document.createElement("div");
//   div.innerHTML = htmlString;

//   [...div.querySelectorAll("img")].forEach(img => img.remove());
//   return div.textContent || div.innerText || "";
// }

// function displayGroupedRules(records, containerId) {
//   const container = document.getElementById(containerId);
//   if (!container) {
//     console.error(`Container with ID "${containerId}" not found.`);
//     return;
//   }

//   container.innerHTML = "";

//   if (records.length <= 1) {
//     container.innerHTML = `
//       <div style="
//         display: flex;
//         justify-content: center;
//         align-items: center;
//         width: 80%;
//         font-size: 24px;
//         font-weight: bold;
//         color: #333;
//         text-align: center;
//         margin: 300px auto;
//       ">
//         No duplicate rules found.
//       </div>`;
//     return;
//   }

//   const groupedRules = new Map();

//   const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

//   const cleanText = (text) =>
//     text
//       .replace(/&nbsp;|\u00a0/g, " ")
//       .replace(/[.,]/g, "")
//       .replace(/\s+/g, " ")
//       .trim()
//       .toLowerCase();

//   const normalizeConditionParts = (rawConditions) => {
//     const parts = rawConditions?.split(",") || [];
//     const set1 = [], set2 = [];
//     let currentSet = null;

//     for (let i = 0; i < parts.length; i++) {
//       const part = cleanText(parts[i]);
//       if (part === "condition_set_1") {
//         currentSet = set1;
//         continue;
//       }
//       if (part === "condition_set_2") {
//         currentSet = set2;
//         continue;
//       }
//       if (currentSet) {
//         const words = part.split(" ").filter(Boolean).sort().join(" ");
//         currentSet.push(words);
//       }
//     }

//     set1.sort();
//     set2.sort();
//     return {
//       key1: `${set1.join(",")}|${set2.join(",")}`,
//       key2: `${set2.join(",")}|${set1.join(",")}`, // Full swap allowed
//     };
//   };

//   const normalizeActions = (actions) => {
//     let words = [];
//     if (Array.isArray(actions)) {
//       words = actions.flatMap((action) =>
//         Object.values(action).flatMap((v) =>
//           cleanText(stripImageTags(String(v))).split(" ")
//         )
//       );
//     } else if (typeof actions === "string") {
//       words = actions
//         .split(",")
//         .flatMap((a) => cleanText(stripImageTags(a)).split(" "));
//     }
//     return words.sort().join(",");
//   };

//   records.forEach((record) => {
//     const { data, display_id } = record;
//     const {
//       name, summary, position, updated_at, last_updated_by,
//       affected_tickets_count, rule_id, automation_type_id,
//       conditions, actions, agentName, operator
//     } = data;

//     const { key1, key2 } = normalizeConditionParts(conditions);
//     const normalizedActions = normalizeActions(actions);
//     const normalizedOperator = operator ? cleanText(operator) : "";

//     const groupKey1 = `${key1}|${normalizedActions}|${normalizedOperator}`;
//     const groupKey2 = `${key2}|${normalizedActions}|${normalizedOperator}`;

//     let groupKey = groupedRules.has(groupKey1)
//       ? groupKey1
//       : groupedRules.has(groupKey2)
//       ? groupKey2
//       : groupKey1;

//     if (!groupedRules.has(groupKey)) {
//       groupedRules.set(groupKey, { rules: [] });
//     }

//     groupedRules.get(groupKey).rules.push({
//       name,
//       position,
//       summary,
//       updated_at,
//       last_updated_by,
//       affected_tickets_count,
//       rule_id,
//       automation_type_id,
//       display_id,
//       agentName
//     });
//   });

      // console.log(`✅ Pushed rule into group`, groupedRules.get(groupKey).rules.length);
   
  
  const rawGroupedArray = Array.from(groupedRules.values());

  // 2. Filter out groups with only one rule
  const groupedRulesArray = rawGroupedArray.filter(group => group.rules.length > 1);
  const totalgroup = groupedRulesArray.length;
  console.log("Filtered Group Count (rules > 1):", totalgroup, "*********************");

  // 3. Calculate pagination details
  const totalPages = Math.ceil(totalgroup / itemsPerPage);
  currentPage = Math.max(1, Math.min(currentPage, totalPages)); // Ensure valid page number
  console.log("Total Pages:", totalPages, "Current Page:", currentPage);

  const startIdx = (currentPage - 1) * itemsPerPage;
  const paginatedRules = groupedRulesArray.slice(startIdx, startIdx + itemsPerPage);
  console.log("Displaying Paginated Records:", paginatedRules);

  const arrayLength = paginatedRules.length;
  console.log("Records Length:", arrayLength);
  paginatedRules.forEach(group => {
    console.log(`Rendering group: ${group.originalSummary}`);

    const groupContainer = document.createElement("div");
    groupContainer.style.border = "1px solid #ccc";
    groupContainer.style.padding = "16px";
    groupContainer.style.margin = "16px";
    groupContainer.style.borderRadius = "8px";
    groupContainer.style.backgroundColor = "#f5f7f9";
    groupContainer.style.width = "87%";

    

    // ✅ Correctly loop through the rules array inside the group object
    group.rules.forEach(({ name, position, summary, updated_at, affected_tickets_count, display_id, rule_id, automation_type_id,agentName }, index) => {
      const card = document.createElement("div");
      // card.className = "fw-card-1 fw-py-16 fw-flex fw-flex-column";
    card.style.border = "1px solid #ddd";
    card.style.padding = "16px";
    card.style.margin = "8px 0"
    card.style.fontFamily =
      "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
    card.style.borderRadius = "8px";
    card.style.backgroundColor = index === 0 ? "#fff" : "#e5f2fd";
    card.style.marginBottom = "10px";
    card.style.paddingBottom = "0";
    card .style.overflow ="hidden"
   
      const cardHeader = document.createElement("div");
      cardHeader.style.display = "flex";
      cardHeader.style.justifyContent = "space-between";
      cardHeader.style.alignItems = "center";
      
      // Create a wrapper for the title
const cardTitle = document.createElement("h4");
cardTitle.style.margin = "0";
cardTitle.style.cursor = "pointer";
cardTitle.style.fontSize = "14px";
cardTitle.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
cardTitle.style.color = "#183247";
cardTitle.style.transition = "color 0.2s ease";
cardTitle.style.fontWeight = "600"; 

// Create the serial number (position)
if (position) {
    const serialNumber = document.createElement("span");
    serialNumber.textContent = position + ". ";
    serialNumber.style.color = "#183247"; // Keep serial number color fixed
    cardTitle.appendChild(serialNumber);
}

// Create the actual name (clickable part)
const titleText = document.createElement("span");
titleText.textContent = name;
titleText.style.color = "#183247"; 
titleText.style.transition = "color 0.2s ease";

// Add hover effect for only the name
titleText.addEventListener("mouseover", () => {
    titleText.style.color = "#007bff"; // Change only name color on hover
});
titleText.addEventListener("mouseout", () => {
    titleText.style.color = "#183247"; // Reset name color when not hovering
});
titleText.addEventListener("click", () => {
    titleText.style.color = "#ff5733"; // Change title color on click
   

    
    // let ruleid=rule_id;
    console.log("ruleid",rule_id);
    // let automationid= automation_type_id;
    console.log("automationtypeid",automation_type_id);
    GetRules();
    async function GetRules() {
      //  console.log('GetRules called');
       try {
           const GetRulesResponse = await client.request.invokeTemplate("getid", {
               context: 
               { 
                ruleid: rule_id ,
                automationid:automation_type_id
               },
           });
   
           const responses = GetRulesResponse.response;
           const rulesData = JSON.parse(responses);
           console.log("Rules", rulesData);
           console.log("Rules", rulesData.summary.conditions);
           console.log("Rules", rulesData.summary.actions);
           if(automation_type_id === 1||automation_type_id === 3)
        {
           showPopupCard(rulesData.name, { conditions: rulesData.summary.conditions, actions:rulesData.summary.actions },automation_type_id);
      }else{
        showPopupCard1(rulesData.name, {performer:rulesData.summary.performer,events:rulesData.summary.events, conditions: rulesData.summary.conditions, actions:rulesData.summary.actions });
      }
    }
      catch (error) {
        console.error("Error in getting rules",error);
         
         }
    }
   

});

// Append name to title
cardTitle.appendChild(titleText);




      // Append title and actions to the cardHeader
      cardHeader.appendChild(cardTitle);
      // Create a container for the horizontal line and the gap
const cardContainer = document.createElement("div");

// Style the container to have a background color in the gap
cardContainer.style.backgroundColor = "#f0f0f0";  // Set the background color for the gap (change to desired color)
cardContainer.style.paddingBottom = "20px";  
cardContainer.style.marginLeft="-15px";
cardContainer.style.borderRadius = "4px";
// cardContainer.style.width="103%";
cardContainer.style.position = "relative";

cardContainer.style.width = "calc(103% + 30px)";

// Create a horizontal line after the cardBody
const horizontalLine = document.createElement("div");
horizontalLine.style.height = "1px"; // Set the height to 1px for a thin line
horizontalLine.style.backgroundColor = "#ccc"; // Set the color of the horizontal line
horizontalLine.style.marginTop = "16px"; // Add space above the line (adjust as needed)
// horizontalLine.style.width = "100%"; // Ensure the line stretches the full width of the container
horizontalLine.style.marginLeft="-3px";
      

      function truncateContent(content, maxLength, lines) {
        // Truncate the content to the desired number of characters
        let truncated = content;
      
        // Adjust for the desired line count and maximum length
        if (content.length > maxLength) {
          truncated = content.slice(0, maxLength) + "...";
        }
      
        // Break content into lines manually for multi-line truncation
        const words = truncated.split(" ");
        const result = [];
        let line = "";
        let currentLine = 1;
      
        for (let i = 0; i < words.length; i++) {
          if (line.length + words[i].length + 1 <= maxLength / lines) {
            line += (line ? " " : "") + words[i];
          } else {
            result.push(line);
            line = words[i];
            currentLine++;
            if (currentLine > lines) break; // Stop adding more lines if max lines are reached
          }
        }
      
        if (currentLine <= lines && line) {
          result.push(line);
        }
      
        return result.join(" ") + (currentLine > lines ? "..." : "");
      }
      function calculateLastModified(updated_at) {
        const updatedDate = new Date(updated_at);
        const currentDate = new Date();
    
        const diffInMilliseconds = currentDate - updatedDate;
        const seconds = Math.floor(diffInMilliseconds / 1000);
        const minutes = Math.floor(seconds / 60);
        const hours = Math.floor(minutes / 60);
        const days = Math.floor(hours / 24);
        const months = Math.floor(days / 30);  // Approximate months
        const years = Math.floor(days / 365);  // Approximate years
    
        if (years > 0) {
            return years === 1 ? "a year ago" : `${years} years ago`;
        } else if (months > 0) {
            return months === 1 ? "a month ago" : `${months} months ago`;
        } else if (days > 0) {
            return `${days} day${days > 1 ? "s" : ""} ago`;
        } else if (hours > 0) {
            return `${hours} hour${hours > 1 ? "s" : ""} ago`;
        } else if (minutes > 0) {
            return `${minutes} minute${minutes > 1 ? "s" : ""} ago`;
        } else {
            return "Just now";
        }
    }
    
    
      
      
      // console.log("updated at",calculateLastModified(updated_at));
  // Create a row for "Last Modified"
  const lastModifiedRow = document.createElement("div");
  lastModifiedRow.style.display = "grid";
  lastModifiedRow.style.gridTemplateColumns = "repeat(auto-fit, minmax(150px, 1fr))"; // Responsive columns
  lastModifiedRow.style.alignItems = "center";
  // lastModifiedRow.style.marginTop = "10px";
  lastModifiedRow.style.fontSize = "12px";
  lastModifiedRow.style.gap = "16px"; // Space between items
  lastModifiedRow.style.width = "100%"; // Full width alignment
  lastModifiedRow.style.gridTemplateRows = "auto"; // Auto row size to fit content
  
  // Function to create a label-value pair container
  function createLabelValue(labelText, valueText) {
    const container = document.createElement("div");
    container.style.display = "flex";
    container.style.flexDirection = "row"; // Horizontal alignment
    container.style.alignItems = "center"; // Vertical alignment
  
    const label = document.createElement("span");
    label.textContent = labelText;
    label.style.color = "#183247";
    label.style.marginTop = "10px";
    label.style.marginLeft = "15%";
    label.style.fontSize = "12px";
    label.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
  
    const value = document.createElement("span");
    value.textContent = valueText;
    value.style.color = "#183247";
    value.style.fontWeight = "600";
    value.style.marginTop = "10px";
    value.style.fontSize = "12px";
    value.style.marginLeft = "10px"; // Space between label and value
    value.style.fontFamily = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
  
    container.appendChild(label);
    container.appendChild(value);
  
    return container;
  }
  
  // Create and append the "Last Modified" section to the lastModifiedRow
  const lastModifiedText = calculateLastModified(updated_at);
  lastModifiedRow.appendChild(createLabelValue("Last Modified :", lastModifiedText));
  
  // Vertical line between sections
  const verticalLine = document.createElement("div");
  verticalLine.style.height = "20px";
  verticalLine.style.marginTop = "10px";
  verticalLine.style.borderLeft = "2px solid #ccc";
  verticalLine.style.alignSelf = "stretch"; // Make it stretch vertically between items
  lastModifiedRow.appendChild(verticalLine);
  
  // Create and append the "By" (Agent) section
  const agentNameText = agentName || "Unknown Agent";
  lastModifiedRow.appendChild(createLabelValue("By :", agentNameText));
  
  // Vertical line after the agent name
  const verticalLine2 = document.createElement("div");
  verticalLine2.style.height = "20px";
  verticalLine2.style.marginTop = "10px";
  verticalLine2.style.borderLeft = "2px solid #ccc";
  verticalLine2.style.alignSelf = "stretch";
  lastModifiedRow.appendChild(verticalLine2);
  
  // Create and append the "Impacted tickets" section
  const affectedTicketsText = affected_tickets_count === 0 ? "--" : affected_tickets_count;
  // lastModifiedRow.appendChild(createLabelValue("Impacted tickets (Last 7 days):", affectedTicketsText));
  const impactedTickets = createLabelValue("Impacted tickets (Last 7 days) :", affectedTicketsText);
  impactedTickets.firstChild.style.marginLeft = "-50%"; // Adjust label alignment
  lastModifiedRow.appendChild(impactedTickets);
 
      const cardBody = document.createElement("div"); // Create a container for card content and actions
      cardBody.style.display = "flex"; // Flexbox to align items horizontally
      cardBody.style.justifyContent = "space-between"; // Ensure there's space between content and actions
      cardBody.style.alignItems = "flex-start"; // Align items to the top (optional, depending on your needs)
               

const truncatedContent = truncateContent(summary, 200, 2);

const cardContent = document.createElement("pre");
cardContent.textContent = truncatedContent;

// Style the card content
cardContent.style.marginTop = "8px";
cardContent.style.padding = "8px";
cardContent.style.color="#183247";
cardContent.style.fontweight="600";
cardContent.style.fontFamily= "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif";
cardContent.style.whiteSpace = "pre-wrap"; // Ensure text wraps
cardContent.style.overflow = "hidden"; // Hide overflow content
cardContent.style.textOverflow = "ellipsis"; // Add ellipsis for overflow
cardContent.style.maxWidth = "75%"; // Limit the card width to half the container's width
cardContent.style.fontSize="12px";
cardContent.style.marginLeft="15px";


     // Create the container for card actions
const cardActionsContainer = document.createElement("div");
cardActionsContainer.style.display = "flex"; // Display actions horizontally
cardActionsContainer.style.justifyContent = "flex-end"; // Align to the right
cardActionsContainer.style.marginTop = "10px"; // Add some spacing above the actions
cardActionsContainer.style.gap = "8px"; // Set space between the toggle and the delete icon


        // Add fw-icon
        const fwIcon = document.createElement("fw-icon");
        fwIcon.setAttribute("name", "delete");
        fwIcon.setAttribute("size", "18");
        fwIcon.style.cursor = "pointer";
        fwIcon.style.color = "red"; // Set the color to red
        // Add a pointer cursor for interactivity
        fwIcon.title = "Delete";
        fwIcon.addEventListener("click", () => {
          console.log("ruleid inside entity deletion", rule_id);
             // ✅ Create the modal dynamically
const modal = document.createElement("fw-modal");
modal.setAttribute("id", "deleteConfirmationPopup");
modal.setAttribute("title-text", "Delete Rule");
modal.setAttribute("is-open", "false");

// Modal content
const content = document.createElement("fw-text");
content.textContent = "Are you sure you want to delete the rule?";
modal.appendChild(content);

// Modal footer
const footer = document.createElement("fw-modal-footer");
modal.appendChild(footer);

// Append modal to body
document.body.appendChild(modal);

// ✅ Then use the modal
const deleteModal = document.getElementById("deleteConfirmationPopup");

if (deleteModal) {
  deleteModal.setAttribute("is-open", "true");

  deleteModal.addEventListener(
    "fwSubmit",
    async () => {
      console.log("Delete confirmed.");
      currentRuleId = display_id;

      try {
        await confirmDeletion1(rule_id, automation_type_id);
        await entityconfirmDeletion();
      } catch (error) {
        console.error("❌ Error in deletion process:", error);
      }

      deleteModal.removeAttribute("is-open");
    },
    { once: true }
  );

  // Handle Cancel (Close)
  const footer = deleteModal.querySelector("fw-modal-footer");
  if (footer) {
    footer.addEventListener(
      "fwClose",
      () => {
        deleteModal.removeAttribute("is-open");
        console.log("Delete operation was cancelled.");
      },
      { once: true }
    );
  }
} else {
  console.error("Modal element with ID 'deleteConfirmationPopup' not found.");
}

      
          // const modal = document.getElementById("deleteConfirmationPopup");

          // if (modal) {
          //   modal.setAttribute("is-open", "true");
        
          //   modal.addEventListener(
          //     "fwSubmit",
          //     async () => {
          //       console.log("Delete confirmed.");
          //       currentRuleId = display_id;
          //       try {
          //             await confirmDeletion1(rule_id, automation_type_id); 
          //             await entityconfirmDeletion(); 
            
          //         } catch (error) {
          //             console.error("❌ Error in deletion process:", error);
          //         }
        
                
          //       modal.removeAttribute("is-open");
          //     },
          //     { once: true }
          //   );
        
          //   // Handle Cancel (Close)
          //   modal.querySelector("fw-modal-footer").addEventListener(
          //     "fwClose",
          //     () => {
          //       modal.removeAttribute("is-open");
          //       console.log("Delete operation was cancelled.");
          //     },
          //     { once: true }
          //   );
          // } else {
          //   console.error("Modal element with ID 'composition' not found.");
          // }
        });
        function removeDeletedRuleFromUI(display_id) {
          let ruleCard = document.querySelector(`[data-rule-id="${display_id}"]`);
          if (ruleCard) {
              ruleCard.remove();
          }
      }
         async function confirmDeletion1(rule_id, automation_type_id) {
              console.log("📢 confirmDeletion1 function triggered with rule_id:", rule_id, "and automation_type_id:", automation_type_id);
      
              if (!rule_id || !automation_type_id) {
                  console.warn("⚠️ Missing rule_id or automation_type_id, aborting function.");
                  return;
              }
      
              try {
                  console.log("🚀 Sending request to delete rule...");
      
                  let getdeleteruleResponse1 = await client.request.invokeTemplate("deleterule", {
                      context: {
                          automationid: automation_type_id,
                          ruleid: rule_id,
                      },
                  });
      
                  console.log("✅ getdeleteruleResponse:", getdeleteruleResponse1);
      
                  if (getdeleteruleResponse1.status === 204) {
                      console.log("✅ Rule deleted successfully!");
                      // hideDeletePopup();
                  } else {
                      console.warn("⚠️ Unexpected response:", getdeleteruleResponse1);
                  }
      
              } catch (error) {
                  console.error("❌ Error in confirmDeletion1:", error);
              }
          }
      
          async function entityconfirmDeletion() {
            console.log("entity deletion called");
              if (!currentRuleId) return; // Ensure rule ID is available
      
              try {
                console.log("entity deletion called try");
                  console.log("Deleting rule with ID:", currentRuleId);
                  await newRulePloadDB5.delete(currentRuleId);
  
  
                  
              } catch (error) {
                console.log("entity deletion called catch");
                  console.warn(` Error deleting record with Display ID ${currentRuleId}, but continuing...`);
                  const ruleIndex = records.findIndex(record => record.display_id === currentRuleId);
                if (ruleIndex !== -1) {
              records.splice(ruleIndex, 1);
               console.log(`✅ Rule ${currentRuleId} removed from records array.`);
                } else {
                 console.warn(`⚠️ Rule with display_id ${currentRuleId} not found in records array.`);
                 }
  
                  displayGroupedRules(records, containerId)
                   let toast = document.getElementById('type_toast');
                   toast.setAttribute('content', 'Rule deleted successfully');
                   toast.setAttribute('type', 'success');
                   toast.setAttribute('open', true);
       
                   removeDeletedRuleFromUI(currentRuleId);
                  
       
                   
                 
              }
          }

      
  //   
      // Append fw-toggle and fw-icon to cardActions
      // cardActionsContainer.appendChild(fwToggle);

      cardActionsContainer.appendChild(fwIcon);
      card.appendChild(cardHeader);
      cardBody.appendChild(cardContent);
      cardBody.appendChild(cardActionsContainer);
      card.appendChild(cardBody);
      cardContainer.appendChild(horizontalLine);
      // card.appendChild(horizontalLine);
     
      cardContainer.appendChild(lastModifiedRow);
      card.appendChild(cardContainer)
      groupContainer.appendChild(card);
    });

    container.appendChild(groupContainer);
  });
  
  // Add pagination component
  addFwPagination(containerId,  records, totalgroup);
}


function addFwPagination(containerId, records, totalgroup) {
  console.log('Adding pagination to container:', containerId);

  let container = document.getElementById(containerId);

  if (!container) {
    console.warn(`Container with ID "${containerId}" not found.`);
    return;
  }

  if (totalgroup <= itemsPerPage) {
    console.log("Total records are less than or equal to items per page, skipping pagination.");
    return;
  }

  let existingPagination= container.querySelector("#fw-pagination-4");
  if (existingPagination) {
    existingPagination.remove(); // Remove old pagination if it exists
  }

  const pagination = document.createElement("fw-pagination");
  pagination.id = "fw-pagination-4";

  pagination.setAttribute("total", totalgroup);
  // pagination1.setAttribute("total", totalPages4 * arrayLength);

  // console.log("totalpages",totalPages4 * arrayLength)
  pagination.setAttribute("per-page", itemsPerPage);
  pagination.setAttribute("page", currentPage);

  console.log("Pagination Element:", pagination);

  const paginationWrapper = document.createElement("div");
  paginationWrapper.style.display = "flex";
  // paginationWrapper.style.justifyContent = "flex-start";
  paginationWrapper.style.alignItems = "center";
  // paginationWrapper.style.width = "100%";
  paginationWrapper.style.marginLeft = "45%";

  paginationWrapper.appendChild(pagination);
  container.appendChild(paginationWrapper);

  pagination.addEventListener("fwChange", (event) => {
    console.log("fwChange Event Triggered", event);
    currentPage = event.detail.page;
    console.log("Updated Page:", currentPage);

   // Update the displayed rules for the current container
   displayGroupedRules(records, containerId);


  });
}

 
function showPopupCard1(title, content) {
  console.log("logPopup" ,content);
  const overlay = document.createElement("div");
  overlay.style.position = "fixed";
  overlay.style.top = "0";
  overlay.style.left = "0";
  overlay.style.width = "100%";
  overlay.style.height = "100%";
  overlay.style.backgroundColor = "rgba(0, 0, 0, 0.3)"; // Semi-transparent dark background
  overlay.style.backdropFilter = "blur(5px)"; // Apply blur effect
  overlay.style.zIndex = "999"; // Ensure it appears above everything else
  document.body.style.overflow = "hidden";
  document.body.appendChild(overlay);
  // Create popup container
  const popupContainer = document.createElement("div");
  popupContainer.style.position = "fixed";
  popupContainer.style.top = "50%";
  popupContainer.style.left = "50%";
  popupContainer.style.transform = "translate(-50%, -50%)";
  popupContainer.style.width = "50%"; // Increased default width
  popupContainer.style.maxWidth = "95%"; // Ensure it fits on smaller screens
  // popupContainer.style.height = "80%"; // Use viewport height to limit size
  popupContainer.style.backgroundColor = "#fff";
  popupContainer.style.border = "1px solid #ccc";
  popupContainer.style.boxShadow = "0 4px 8px rgba(0, 0, 0, 0.2)";
  popupContainer.style.borderRadius = "12px"; // Increased border radius for a smoother look
  popupContainer.style.overflow = "hidden"; // Prevent content overflow
  popupContainer.style.fontFamily =
    "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"; // Apply a system font
  popupContainer.style.zIndex = "1000";
  popupContainer.style.display = "flex";
  popupContainer.style.flexDirection = "column";
  popupContainer.style.height = "auto";
  popupContainer.style.maxHeight = "80vh";
  
  
  // Create header for title (fixed position)
  const popupHeader = document.createElement("div");
  popupHeader.style.padding = "16px 24px";
  popupHeader.style.borderBottom = "1px solid #ddd"; // Separate the title visually
  popupHeader.style.backgroundColor = "#fff";
  popupHeader.style.zIndex = "10"; // Ensure it appears above the scrollable content
  
  // Popup title
  const popupTitle = document.createElement("h2");
  popupTitle.textContent = title;
  popupTitle.style.paddingLeft = "15px"; // Move the title slightly to the right
  popupTitle.style.fontSize = "20px";
  popupTitle.style.color = "#333";
  popupTitle.style.textAlign = "left";
  popupHeader.appendChild(popupTitle);
  
  
  
  // Content wrapper (flex layout)
  const contentWrapper = document.createElement("div");
  contentWrapper.style.display = "flex";
  contentWrapper.style.flexDirection = "column";
  contentWrapper.style.flex = "1"; // Automatically take up available space
  contentWrapper.style.overflow = "hidden"; // Prevent content overflow
  
  // Content box (with fixed preview label)
  const contentBox = document.createElement("div");
  contentBox.style.flex = "1";
  contentBox.style.border = "1px solid #ddd";
  contentBox.style.borderRadius = "8px";
  contentBox.style.backgroundColor = "#f9f9f9";
  contentBox.style.padding = "16px";
  contentBox.style.margin = "16px 16px"; // Add vertical spacing
  contentBox.style.overflow = "hidden"; // Prevent outer scrolling
  contentBox.style.marginBottom = "75px"; // Add enough space for the close button
  contentBox.style.display = "flex";
contentBox.style.flexDirection = "column";
  
  // Preview label and line (sticky inside content box)
  const previewLabelContainer = document.createElement("div");
  previewLabelContainer.style.position = "sticky"; // Fix inside the content box
  previewLabelContainer.style.top = "0"; // Stick to the top
  previewLabelContainer.style.backgroundColor = "#f9f9f9"; // Match the content box background
  previewLabelContainer.style.zIndex = "1";
  previewLabelContainer.style.padding = "8px 0";
  
  const previewLabel = document.createElement("p");
  previewLabel.textContent = "Preview"; // Label text
  previewLabel.style.fontSize = "16px";
  previewLabel.style.fontWeight = "500";
  previewLabel.style.color = "#92a2b1";
  previewLabel.style.margin = "0";
  
  const lineBelowLabel = document.createElement("hr");
  lineBelowLabel.style.border = "none";
  lineBelowLabel.style.borderTop = "1px solid #ddd";
  lineBelowLabel.style.margin = "8px 0";
  
  previewLabelContainer.appendChild(previewLabel);
  previewLabelContainer.appendChild(lineBelowLabel);
  
  const scrollableContent = document.createElement("div");
scrollableContent.style.overflowY = "auto"; // Enable vertical scrolling
// scrollableContent.style.height = "calc(100% - 40px)"; // Adjust to fit within the content box
scrollableContent.style.height = "auto"; // Allow dynamic growth
scrollableContent.style.maxHeight = "60vh";
scrollableContent.style.flex = "1"; // Fill vertical space in contentBox

scrollableContent.style.minHeight = "0"
  
  
  
    const eventText = document.createElement("div");
    eventText.style.marginBottom = "12px";
    
    const createCustomBullet = (text, bulletColor, highlightColor) => {
      const listItem = document.createElement("li");
      listItem.style.position = "relative"; // For positioning the custom bullet
      listItem.style.paddingLeft = "10px"; // Space for custom bullet
    
      // Create the custom double circular bullet using a span element
      const bullet = document.createElement("span");
      bullet.style.position = "absolute";
      bullet.style.left = "-15px"; // Bring the bullet closer to the text (adjust this value)
      bullet.style.top = "50%"; // Center the bullet vertically
      bullet.style.transform = "translateY(-50%)"; // Center the bullet exactly
      bullet.style.width = "12px"; // Outer ring size
      bullet.style.height = "12px";
      bullet.style.border = `4px solid ${bulletColor || "#dcdfe1"}`; // Outer ring color and border size
      bullet.style.borderRadius = "50%"; // Make it a ring (circle with border)
      bullet.style.display = "inline-block";
    
      // Create the inner circle (smaller circle inside the outer ring)
      const innerBullet = document.createElement("span");
      innerBullet.style.position = "absolute";
      innerBullet.style.left = "50%";
      innerBullet.style.top = "50%";
      innerBullet.style.transform = "translate(-50%, -50%)"; // Centering the inner circle
      innerBullet.style.width = "2px"; // Inner circle size
      innerBullet.style.height = "2px";
      // innerBullet.style.backgroundColor = bulletColor || "#dcdfe1"; // Inner circle color
      innerBullet.style.borderRadius = "50%"; // Inner circle rounded
      innerBullet.style.display = "inline-block";
    
      // Append the inner circle to the outer circle (bullet)
      bullet.appendChild(innerBullet);
   // Split the text into words
   const words = text.split(" ");
      
   // Extract specific words
   const firstWord = words.shift(); // Remove first word
   const secondWord = words.shift(); // Remove second word
   const lastWord = words.pop(); // Extract last word
   const remainingText = words.join(" "); // Remaining words (excluding first, second, and last)
 
   // Construct the innerHTML with the second word in black and the last word in highlight color
   listItem.innerHTML = `
     <span>${firstWord}</span> 
     <span style="color: black; font-weight: 500;">${secondWord}</span> 
     ${remainingText} 
     <span style="color: ${highlightColor}; font-weight: 500;">${lastWord}</span>
   `;
 
   // Append the custom double circular bullet to the list item
   listItem.insertBefore(bullet, listItem.firstChild);
 
   return listItem;
  
    };
    
    // Function to remove HTML tags while preserving spaces
// const stripHTMLWithSpacing = (htmlString) => {
//   const tempElement = document.createElement("div");
//   tempElement.innerHTML = htmlString;
//   return tempElement.textContent.replace(/\s+/g, ' ').trim(); // Ensure proper spacing
// };

   // Function to create a styled bullet point for conditions/actions
const createConditionBullet = (condition, bulletColor = "#dcdfe1") => {
  // console.log("🔹 Original Condition:", condition); // Log initial condition


  const listItem = document.createElement("li");
  listItem.style.position = "relative";
  listItem.style.paddingLeft = "30px"; // Space for bullet
  listItem.style.display = "flex"; // Prevents breaking lines
  listItem.style.alignItems = "center"; // Keeps elements aligned

  // Create custom bullet
  const bullet = document.createElement("span");
  bullet.style.position = "absolute";
  bullet.style.left = "0";
  bullet.style.top = "50%";
  bullet.style.transform = "translateY(-50%)";
  bullet.style.width = "12px";
  bullet.style.height = "12px";
  bullet.style.border = `4px solid ${bulletColor || "#dcdfe1"}`;
  bullet.style.borderRadius = "50%";

  // Inner circle of bullet
  const innerBullet = document.createElement("span");
  innerBullet.style.position = "absolute";
  innerBullet.style.left = "50%";
  innerBullet.style.top = "50%";
  innerBullet.style.transform = "translate(-50%, -50%)";
  innerBullet.style.width = "8px";
  innerBullet.style.height = "8px";
  innerBullet.style.borderRadius = "50%";

  bullet.appendChild(innerBullet);

  // **Formatting Condition with Colors**
  let formattedCondition = condition
    .replace(/<div/g, ' <div') // Add space before <div> tags if missing
    .replace(/<div\s+class\s*=\s*["']?SummaryKey["']?\s*>(.*?)<\/div>/gi, ' <span style="color: black; font-weight: 500;">$1</span> ') 
    .replace(/<div\s+class\s*=\s*["']?SummaryValue["']?\s*>(.*?)<\/div>/gi, ' <span style="color: #00a886; font-weight: 500;">$1</span> ') 
    .replace(/<div\s+class\s*=\s*["']?SummaryOperator["']?\s*>(.*?)<\/div>/gi, ' <span> $1 </span> ') // Ensure space around operators
    .replace(/>\s+</g, '> <')  // Ensures space between inline elements
    .replace(/\s+/g, ' ')      // Remove multiple spaces
    .trim();                   // Trim any leading/trailing spaces

  // console.log("🟢 Formatted Condition (With Colors):", formattedCondition);

  // **Convert to Plain Text with Spaces**
  // const plainTextCondition = stripHTMLWithSpacing(formattedCondition);
  // console.log("🔹 Plain Text Condition (With Spaces):", plainTextCondition);

  // // Set bullet first, then append formatted text
  listItem.appendChild(bullet);
  
  // Create a span for the condition text (for proper spacing)
  const textSpan = document.createElement("span");
  textSpan.innerHTML = formattedCondition;
  textSpan.style.marginLeft = "-5px"; // Ensure space between bullet and text
  listItem.appendChild(textSpan);

  console.log("✅ Final List Item InnerHTML:", listItem.innerHTML); // Log final output

  return listItem;
};
 // Create the heading "Event:"
    const eventLabel = document.createElement("p");
    eventLabel.textContent = "Event";
    eventLabel.style.margin = "0";
    eventLabel.style.color = "#00a886"; // Blue color for heading
    eventLabel.style.fontWeight = "bold";
    eventLabel.style.fontSize = "16px";
  
    // Create the unordered list for the event details
    const eventDetail = document.createElement("ul");
    eventDetail.style.margin = "8px 0 0 -15px"; // Add margin and indentation
    eventDetail.style.color = "#333"; // Normal color for text
    eventDetail.style.listStyleType = "none"; // Remove default bullets
    eventDetail.style.fontSize = "14px";
    // Add event detail with the custom bullet
    const eventBullet = createCustomBullet(
      "When Ticket is Updated", // Text content
      "#2c5cc5", // Bullet color
      "#00a886" // Highlight color for the last word
    );
    eventDetail.appendChild(eventBullet);
    
    // Append the heading and the event detail to the container
    eventText.appendChild(eventLabel);
    eventText.appendChild(eventDetail);
    // Extract performer text (assuming it's a single string)
      const performerText = typeof content.performer === "string" ? stripHTML(content.performer) : "";
      
      // Add the performer to the content if it exists
      if (performerText) {
        console.log("performerText",performerText)
        const performerItem = createConditionBullet(content.performer, "#2c5cc5"); // Green bullet for performer
        performerItem.style.marginBottom = "10px";
        performerItem.style.marginTop = "10px"; // Add space after performer text
        performerItem.style.marginLeft = "10px"; 
        performerItem.style.fontSize ="14px";
        eventText.appendChild(performerItem);
      }
  // Add Event data to Event content
const eventArray = (Array.isArray(content.events) && content.events.length) 
    ? content.events 
    : (Array.isArray(content.eventText) && content.eventText.length) 
        ? content.eventText 
        : (content.events ? [content.events] : (content.eventText ? [content.eventText] : []));

eventArray.forEach(event => {
    if (event) {
        const eventItem = createConditionBullet(event,  "#2c5cc5");
        eventItem.style.marginBottom = "10px";
        eventItem.style.marginTop = "10px"; // Add space after performer text
        eventItem.style.marginLeft = "10px"; 
        eventItem.style.fontSize ="14px";
        eventText.appendChild(eventItem);

    }
});
     
    
  // Create the conditions heading
  const conditionText = document.createElement("div");
  conditionText.textContent = "Condition";
  conditionText.style.marginBottom = "8px";
  conditionText.style.fontWeight = "bold";
  conditionText.style.color = "#e86f25"; // Green color for conditions heading
  conditionText.style.fontSize = "16px";
  
  // Create a container for the conditions list
  const conditionsList = document.createElement("ul");
  conditionsList.style.margin = "0 0 12px";
  conditionsList.style.padding = "8px";
  conditionsList.style.border = "1px solid #ddd";
  conditionsList.style.borderRadius = "4px";
  conditionsList.style.backgroundColor = "#fff";
  conditionsList.style.listStyleType = "none"; // Remove default bullet style
  conditionsList.style.fontSize = "14px";
  
 // Extract condition sets and operator
const conditionsArray1 = Array.isArray(content.conditions.condition_set_1)
? content.conditions.condition_set_1
: [];
const conditionsArray2 = Array.isArray(content.conditions.condition_set_2)
? content.conditions.condition_set_2
: [];
const operator = content.conditions.operator || "";
console.log("conditions array 1",conditionsArray1);




// // Create condition list container
// const conditionsList = document.createElement("ul");
// conditionsList.style.listStyleType = "none";
// conditionsList.style.padding = "0";

// Add conditions from condition_set_1
conditionsArray1.forEach((condition) => {
if (condition === "AND" || condition === "OR") {
  // Add operator as a separate text element
  const operatorItem = document.createElement("div");
  operatorItem.textContent = condition;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  conditionsList.appendChild(operatorItem);
} else {
  conditionsList.appendChild(createConditionBullet(condition, "#2c5cc5")); // Blue bullet
}
});

// Add operator between conditions (if available)
if (operator) {
const operatorItem = document.createElement("div");
operatorItem.textContent = operator;
operatorItem.style.color = "#000000";
operatorItem.style.margin = "8px 0";
operatorItem.style.fontSize = "14px";
operatorItem.style.fontweight = "500";
conditionsList.appendChild(operatorItem);
}

// Add conditions from condition_set_2
conditionsArray2.forEach((condition) => {
if (condition === "AND" || condition === "OR") {
  const operatorItem = document.createElement("div");
  operatorItem.textContent = condition;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  conditionsList.appendChild(operatorItem);
} else {
  conditionsList.appendChild(createConditionBullet(condition, "#2c5cc5")); // Blue bullet
}
});

// Create actions heading
const actionText = document.createElement("div");
actionText.textContent = "Action";
actionText.style.marginBottom = "8px";
actionText.style.fontWeight = "bold";
actionText.style.color = "#2c5cc5";
actionText.style.fontSize = "16px";

// Create actions content
const actionContent = document.createElement("ul");
actionContent.style.margin = "0";
actionContent.style.padding = "8px";
actionContent.style.border = "1px solid #ddd";
actionContent.style.borderRadius = "4px";
actionContent.style.backgroundColor = "#fff";
actionContent.style.listStyleType = "none";
actionContent.style.fontSize = "14px";

const actionsArray = Array.isArray(content.actions) ? content.actions : [];

// Add actions with custom bullets
actionsArray.forEach((action) => {
if (action === "AND" || action === "OR") {
  const operatorItem = document.createElement("div");
  operatorItem.textContent = action;
  operatorItem.style.color = "#6c757d";
  operatorItem.style.margin = "8px 0 5px 29px";
  actionContent.appendChild(operatorItem);
} else {
  actionContent.appendChild(createConditionBullet(action, "#2c5cc5")); // Blue bullet for actions
}
});
  
  // Append the label and line to the content box
  contentBox.appendChild(previewLabel);
  contentBox.appendChild(lineBelowLabel);
  
  scrollableContent.appendChild(eventText);
  scrollableContent.appendChild(conditionText);
  scrollableContent.appendChild(conditionsList);
  scrollableContent.appendChild(actionText);
  scrollableContent.appendChild(actionContent);
  
  // Append content to the scrollable wrapper
  
  contentBox.appendChild(scrollableContent);
  
  // Create fw-button element with "primary" color
  const closeButton = document.createElement("fw-button");
  closeButton.setAttribute("color", "primary");
  closeButton.textContent = "Close";
  closeButton.style.position = "absolute";
  closeButton.style.bottom = "16px"; // Distance from the bottom
  closeButton.style.right = "16px"; // Distance from the right
  closeButton.style.padding = "8px 16px"; // Padding for the button
  closeButton.style.borderRadius = "4px"; // Rounded corners
  closeButton.style.cursor = "pointer";
  
  // Close popup and remove overlay when the button is clicked
  closeButton.addEventListener("click", () => {
    document.body.removeChild(popupContainer);
    document.body.removeChild(overlay);
    document.body.style.overflow = "";
  });
  
  popupContainer.appendChild(popupHeader); // Fixed title
  popupContainer.appendChild(contentBox);
  // popupContainer.appendChild(headerContainer); // Fixed preview label and line
  // popupContainer.appendChild(wrapper); // Scrollable content
  popupContainer.appendChild(closeButton); // Close button
  
  // Append elements to the document
  document.body.appendChild(overlay);
  document.body.appendChild(popupContainer);
  
  }

  // const normalizeText5 = (text) => {
  //   return text
  //       ? text
  //           .toLowerCase() // Convert everything to lowercase
  //           .split(/\s+/) // Split by spaces
  //           .filter(word => word.trim() !== "") // Remove empty words
  //           .sort() // Sort words alphabetically
  //           .join(" ") // Join words back into a string
  //       : "";
  // };old code without nspb
  
  // Function to normalize, sort, and format list-based values (Case-Insensitive)
  // const normalizeList5 = (value, label) => {
  //   if (!value) return "";
  
  //   const list = value
  //       .toLowerCase() // Convert everything to lowercase
  //       .split(/\s*[,|]\s*/) // Split by commas or pipes (remove spaces)
  //       .map((v) => normalizeText5(v)) // Normalize each item in the list
  //       .sort(); // Sort alphabetically
  
  //   console.log(`🔹 Normalized ${label}:`, list);
  //   return list.join(",");
  // };old code without nspb
  
  
  // // Function to find duplicate rules (Case-Insensitive)
  // function findDuplicateRulestype4(records) { 
  //   console.log("function called");
  
  //   const seenRules = new Map(); // Store unique rules with their first occurrence
  //   const duplicateRecords = []; // Store all duplicate records
  
  //   // Function to remove all <img> tags from HTML content
  //   const stripImageTags = (html) => html ? html.replace(/<img[^>]*>/gi, "") : "";
  
  //   records.forEach((record) => {
  //       const { summary, conditions, actions, operator, events, performer, active } = record.data;
  
  //       if (!active) return; // Skip inactive records
  
  //       console.log("✅ Active Record:", record);
  
  //       // Normalize and sort fields (Ensure **case-insensitive** processing)
  //       const normalizedSummary = normalizeText5(summary);
  //       const normalizedConditions = normalizeList5(conditions, "Conditions");
  //       const normalizedActions = normalizeList5(stripImageTags(actions), "Actions");
  //       const normalizedEvents = normalizeList5(events, "Events");
  //       const normalizedPerformer = normalizeList5(performer, "Performer");
  //       const normalizedOperator = operator ? operator.trim().toLowerCase() : null; // Ensure lowercase
  
  //       console.log("🔹 Normalized Summary:", normalizedSummary);
  //       console.log("🔹 Normalized Conditions:", normalizedConditions);
  //       console.log("🔹 Normalized Actions:", normalizedActions);
  //       console.log("🔹 Normalized Events:", normalizedEvents);
  //       console.log("🔹 Normalized Performer:", normalizedPerformer);
  //       console.log("🔹 Normalized Operator:", normalizedOperator);
  
  //       // Create a unique key to compare records (All in lowercase now)
  //       const recordKey = `${normalizedSummary}|${normalizedConditions}|${normalizedActions}|${normalizedOperator}|${normalizedEvents}|${normalizedPerformer}`;
  
  //       console.log("🔍 Generated Record Key:", recordKey);
  
  //       if (seenRules.has(recordKey)) {
  //           console.log("⚠️ Duplicate Found:", record.display_id);
            
  //           if (!duplicateRecords.includes(seenRules.get(recordKey))) {
  //               duplicateRecords.push(seenRules.get(recordKey)); // Add original rule
  //           }
  //           duplicateRecords.push(record); // Add duplicate rule
  //       } else {
  //           seenRules.set(recordKey, record);
  //       }
  //   });
  
  //   return duplicateRecords;
  // } old code without nspb
  
  
// Function to strip <img> tags
// function stripImageTags(html = '') {
//   return html.replace(/<img[^>]*>/g, "").trim();
// }

// // Function to remove punctuation and normalize text
// const cleanTextEntities5 = (text) => {
//   return text
//     ? text
//         .replace(/ |&nbsp;/gi, " ")
//         .replace(/[.,]/g, "")             // Remove full stops and commas
//         .replace(/\s+/g, " ")            // Collapse multiple spaces
//         .trim()
//     : "";
// };

// const normalizeText5 = (text) => {
//   return text
//     ? cleanTextEntities5(text)
//         .toLowerCase()
//         .split(/\s+/)
//         .filter(word => word.trim() !== "")
//         .sort()
//         .join(" ")
//     : "";
// };

// function findDuplicateRulestype4(records) {
//   const seenRules = new Map();
//   const duplicateRecords = [];

//   const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

//   const removeDotsAndCommas = (text) =>
//     text
//       .replace(/&nbsp;/gi, " ")
//       .replace(/[.,]/g, "")
//       .replace(/\s+/g, " ")
//       .trim()
//       .toLowerCase();

//   const normalizeConditionParts = (rawConditions) => {
//     const parts = rawConditions?.split(",") || [];
//     const set1 = [];
//     const set2 = [];
//     let currentSet = null;

//     for (let i = 0; i < parts.length; i++) {
//       let part = removeDotsAndCommas(parts[i]);
//       if (part === "condition_set_1") {
//         currentSet = set1;
//         continue;
//       }
//       if (part === "condition_set_2") {
//         currentSet = set2;
//         continue;
//       }
//       if (currentSet) currentSet.push(part);
//     }

//     set1.sort();
//     set2.sort();
//     return { set1: set1.join(","), set2: set2.join(",") };
//   };

//   const normalizeField = (value) => {
//     if (Array.isArray(value)) {
//       return value
//         .map((item) =>
//           Object.values(item)
//             .map((v) => removeDotsAndCommas(stripImageTags(String(v))))
//             .join(" ")
//         )
//         .sort()
//         .join(",");
//     } else if (typeof value === "string") {
//       return stripImageTags(value)
//         .split(",")
//         .map((item) => removeDotsAndCommas(item))
//         .sort()
//         .join(",");
//     }
//     return "";
//   }
  

//   records.forEach((record, index) => {
//     const { conditions, actions, operator, events, performer } = record.data;

//     const { set1, set2 } = normalizeConditionParts(conditions);
//     const normalizedActions = normalizeField(actions);
//     const normalizedEvents = normalizeField(events);
//     const normalizedPerformer = normalizeField(performer);
//     const normalizedOperator = operator ? operator.trim().toLowerCase() : "";

//     const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}|${normalizedEvents}|${normalizedPerformer}`;
//     const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}|${normalizedEvents}|${normalizedPerformer}`;

//     console.log(`=== Record ${index + 1} ===`);
//     console.log("Condition Set 1:", set1);
//     console.log("Condition Set 2:", set2);
//     console.log("Actions:", normalizedActions);
//     console.log("Events:", normalizedEvents);
//     console.log("Performer:", normalizedPerformer);
//     console.log("Key 1:", key1);
//     console.log("Key 2:", key2);

//     if (seenRules.has(key1) || seenRules.has(key2)) {
//       console.log(`✅ Duplicate found for Record ${index + 1}`);
//       const existing = seenRules.get(key1) || seenRules.get(key2);
//       if (!duplicateRecords.includes(existing)) {
//         duplicateRecords.push(existing);
//       }
//       duplicateRecords.push(record);
//     } else {
//       seenRules.set(key1, record);
//       console.log(`✅ First time seen for Record ${index + 1}`);
//     }
//   });

//   return duplicateRecords;
// }old code with all condition satisfied




function findDuplicateRulestype4(records) {
  const seenRules = new Map();
  const duplicateRecords = [];

  const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";

  const cleanText = (text) =>
    text
      .replace(/&nbsp;/gi, " ")
      .replace(/[.,]/g, "")
      .replace(/\s+/g, " ")
      .trim()
      .toLowerCase();

  // Split each condition item into words, clean, sort
  const normalizeConditionParts = (rawConditions) => {
    const parts = rawConditions?.split(",") || [];
    const set1 = [];
    const set2 = [];
    let currentSet = null;

    for (let i = 0; i < parts.length; i++) {
      let part = cleanText(parts[i]);
      if (part === "condition_set_1") {
        currentSet = set1;
        continue;
      }
      if (part === "condition_set_2") {
        currentSet = set2;
        continue;
      }
      if (currentSet) {
        const words = part.split(" ").filter(Boolean).sort().join(" ");
        currentSet.push(words);
      }
    }

    set1.sort();
    set2.sort();
    return { set1: set1.join(","), set2: set2.join(",") };
  };

  const normalizeField = (value) => {
    if (Array.isArray(value)) {
      return value
        .map((item) =>
          Object.values(item)
            .map((v) => cleanText(stripImageTags(String(v))))
            .join(" ")
        )
        .sort()
        .join(",");
    } else if (typeof value === "string") {
      return stripImageTags(value)
        .split(",")
        .map((item) => cleanText(item))
        .sort()
        .join(",");
    }
    return "";
  };

  // Normalize actions like we now do for conditions: sort all words
  const normalizeActions = (value) => {
    let words = [];
    if (Array.isArray(value)) {
      words = value.flatMap((item) =>
        Object.values(item).flatMap((v) => cleanText(stripImageTags(String(v))).split(" "))
      );
    } else if (typeof value === "string") {
      words = value
        .split(",")
        .flatMap((item) => cleanText(item).split(" "));
    }
    return words.sort().join(",");
  };

  records.forEach((record, index) => {
    const { conditions, actions, operator, events, performer } = record.data;

    const { set1, set2 } = normalizeConditionParts(conditions);
    const normalizedActions = normalizeActions(actions);
    const normalizedEvents = normalizeField(events);
    const normalizedPerformer = normalizeField(performer);
    const normalizedOperator = operator ? cleanText(operator) : "";

    const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}|${normalizedEvents}|${normalizedPerformer}`;
    const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}|${normalizedEvents}|${normalizedPerformer}`;

    console.log(`\n=== Record ${index + 1} ===`);
    console.log("Condition Set 1:", set1);
    console.log("Condition Set 2:", set2);
    console.log("Actions:", normalizedActions);
    console.log("Operator:", normalizedOperator);
    console.log("Events:", normalizedEvents);
    console.log("Performer:", normalizedPerformer);
    console.log("Key 1:", key1);
    console.log("Key 2:", key2);

    if (seenRules.has(key1) || seenRules.has(key2)) {
      console.log(`🔁 Duplicate found for Record ${index + 1}`);
      const existing = seenRules.get(key1) || seenRules.get(key2);
      if (!duplicateRecords.includes(existing)) {
        duplicateRecords.push(existing);
      }
      duplicateRecords.push(record);
    } else {
      seenRules.set(key1, record);
      console.log(`🆕 First time seen for Record ${index + 1}`);
    }
  });

  return duplicateRecords;
}








  





  


in this how the pagination has handled