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

  container.innerHTML = ""; // Clear container

  if (records.length === 0) {
    container.innerHTML = "<p>No duplicate rules found.</p>";
    return;
  }

  const groupedRules = new Map();
  records.forEach((record) => {
    const { data } = record;
    const { name, summary, position, updated_at, last_updated_by, affected_tickets_count, rule_id, automation_type_id } = data;

    if (summary) {
      if (!groupedRules.has(summary)) {
        groupedRules.set(summary, []);
      }
      groupedRules.get(summary).push({
        name, position, summary, updated_at, last_updated_by, affected_tickets_count, rule_id, automation_type_id
      });
    }
  });

  const groupedRulesArray = Array.from(groupedRules.values());
  const totalgroup = Math.ceil(groupedRulesArray.length );
  console.log(totalgroup,"*********************")
  const totalPages = Math.ceil(groupedRulesArray.length / 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 Records:", paginatedRules);

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


  // Display paginated rules
  paginatedRules.forEach((titles) => {
    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 = "1200px";

    titles.forEach(({  name, position, summary,updated_at,last_updated_by,affected_tickets_count,display_id,rule_id,
      automation_type_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";
     
     
      
      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="102.7%";

// 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);  
        const years = Math.floor(days / 365);  
    
        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 = "150px 150px 2px 150px 150px 2px 150px 150px"; // Consistent width for each section
 lastModifiedRow.style.alignItems = "center";
 lastModifiedRow.style.marginTop = "10px";
 lastModifiedRow.style.fontSize = "12px";
 lastModifiedRow.style.gap = "20px";
 lastModifiedRow.style.width = "100%"; // Ensures full width alignment
 
 const lastModifiedLabel = document.createElement("span");
 lastModifiedLabel.textContent = "Last Modified :";
 lastModifiedLabel.style.color = "#183247";
 lastModifiedLabel.style.fontSize = "12px";
 lastModifiedLabel.style.display = "inline-flex";
lastModifiedLabel.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"
lastModifiedLabel.style.marginLeft = "40px"

 const lastModifiedValue = document.createElement("span");
 const lastModifiedText = calculateLastModified(updated_at);
 lastModifiedValue.textContent = lastModifiedText;
 lastModifiedValue.style.color = "#183247";
 lastModifiedValue.style.fontWeight = "600";
 lastModifiedValue.style.display = "inline-flex";
 lastModifiedValue.style.fontSize = "12px";
 lastModifiedValue.style.marginLeft = "-50px"
 lastModifiedValue.style.justifySelf = "start";
 lastModifiedValue.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"

 const verticalLine = document.createElement("div");
 verticalLine.style.height = "20px";
 verticalLine.style.borderLeft = "2px solid #ccc";
 verticalLine.style.alignSelf = "stretch";
 
 lastModifiedRow.appendChild(lastModifiedLabel);
 lastModifiedRow.appendChild(lastModifiedValue);
 lastModifiedRow.appendChild(verticalLine);
 
 const agentsid = last_updated_by;
//  console.log("agentsid", agentsid);
 GetAgents();
 
 async function GetAgents() {
    //  console.log('GetAgents called');
     try {
         const GetAgentsResponse = await client.request.invokeTemplate('GetAgents', {
             context: { id: agentsid },
         });
 
         const responses = GetAgentsResponse.response;
         const agentData = JSON.parse(responses);
        //  console.log("Name:", agentData.contact.name);
 
         const agentNameLabel = document.createElement("span");
         agentNameLabel.textContent = "By :";
         agentNameLabel.style.fontSize = "12px";
         agentNameLabel.style.color = "#183247";
         agentNameLabel.style.whiteSpace = "nowrap";
         agentNameLabel.style.marginLeft="149px"
         agentNameLabel.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"

         const agentNameValue = document.createElement("span");
         agentNameValue.textContent = agentData.contact.name;
         agentNameValue.style.color = "#183247";
         agentNameValue.style.fontWeight = "600";
         agentNameValue.style.whiteSpace = "nowrap";
         agentNameValue.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"
         const verticalLine2 = document.createElement("div");
         verticalLine2.style.height = "20px";
         verticalLine2.style.borderLeft = "2px solid #ccc";
         verticalLine2.style.alignSelf = "stretch";
         verticalLine2.style.marginLeft = "100px";  // Increase for more right shift

 
         lastModifiedRow.appendChild(agentNameLabel);
         lastModifiedRow.appendChild(agentNameValue);
         lastModifiedRow.appendChild(verticalLine2);
 
         const affectedTicketsLabel = document.createElement("span");
         affectedTicketsLabel.textContent = "Impacted tickets (Last 7 days) : ";
         affectedTicketsLabel.style.fontSize = "12px";
         affectedTicketsLabel.style.color = "#183247";
         affectedTicketsLabel.style.marginLeft="140px";
         affectedTicketsLabel.style.whiteSpace = "nowrap";
         affectedTicketsLabel.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"

         const affectedTicketsValue = document.createElement("span");
         affectedTicketsValue.textContent = affected_tickets_count === 0 ? "--" : affected_tickets_count;
         affectedTicketsValue.style.color = "#183247";
         affectedTicketsValue.style.fontWeight = "600";
         affectedTicketsValue.style.marginLeft ="134px"
         affectedTicketsValue.style.whiteSpace = "nowrap";
         affectedTicketsValue.style.fontFamily =" -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif"

         lastModifiedRow.appendChild(affectedTicketsLabel);
         lastModifiedRow.appendChild(affectedTicketsValue);
    }
    
    catch (error) {
      console.error("Agents error",error);
       
       }
  }

  async function deleteRecord(displayId) {
    try {
        const record = await newRulePloadDB2.delete(displayId);
        console.log(`Record with Display ID ${displayId} deleted successfully:`, record);
    } catch (error) {
        console.error(`Error deleting record with Display ID ${displayId}:`, error);
    }
}




 
      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-toggle
//       const fwToggle = document.createElement("fw-toggle");
//       fwToggle.setAttribute("size", "medium");
//       fwToggle.setAttribute("checked", "");
//       // Add event listener to handle state change
// fwToggle.addEventListener("fwChange", (event) => {
//   fwToggle.checked = event.detail.checked; // Keep the state as per user selection
//   console.log("Toggle state changed:", fwToggle.checked);
// });
const fwToggle = document.createElement("fw-toggle");
fwToggle.setAttribute("size", "medium");

// Unique key for storing toggle state (Assuming each card has a unique rule ID)
const ruleId = rule_id; // Ensure rule_id is unique per rule
const storedState = localStorage.getItem(`toggleState_${ruleId}`);

if (storedState !== null) {
  fwToggle.checked = storedState === "true"; // Convert string to boolean
} else {
  fwToggle.setAttribute("checked", ""); // Default state
}

// Event listener to update localStorage on state change
fwToggle.addEventListener("fwChange", (event) => {
  const isChecked = event.detail.checked;
  localStorage.setItem(`toggleState_${ruleId}`, isChecked);
  fwToggle.checked = isChecked; // Ensure UI reflects stored state
  console.log(`Toggle state changed for ${ruleId}:`, isChecked);
});


      // 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", () => {
        groupContainer.removeChild(card); // Remove the card from the group container
        // console.log("display_id",display_id);
        deleteRecord(display_id);
      });

      // 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);
}



change to bootstrap grid alignment with manual alignment mediaquery same as bootstrap