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

  const container = document.getElementById(containerId);
  console.log("containerlog", container);

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

  container.innerHTML = ""; // Clear container

  if (duplicates.length === 0) {
    container.innerHTML = "<p>No duplicate records found for Automation Type ID 4.</p>";
    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 || [];

      const combinedContent = combineConditionsAndActions({
        performer: performer,
        eventText: eventText,
        condition_set_1: summary.conditions.condition_set_1,
        condition_set_2: summary.conditions.condition_set_2,
        operator: summary.conditions.operator,
        actions: actions,
      });

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

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

  const groupedRulesArray = Array.from(groupedRules.values());

  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 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, 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";
     
  
      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="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);  // 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 = "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);

}
}

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

 
   ruledelete();
  async function ruledelete() {
    console.log('deleterule called');
    try {
      let getdeleteruleResponse=  await client.request.invokeTemplate("deleterule", {
    
        context:{  automationid:4,
          ruleid: id ,}
        });

        // const responses = getdeleteruleResponse.response;
      //   const ruledelete = JSON.parse(responses);
       console.log("getdeleteruleResponse",getdeleteruleResponse);


   }
   
   catch (error) {
     console.error("Error in deleting rule",error);
      
      }
 }



});

// 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
  addFwPaginationDuplicates(containerId, duplicates,totalgroup);
}


explain this code