import fetchData from "@/api/fetch-data";
import { getLocale } from "next-intl/server";
import SideBannerRedesignTwo from "./SideBannerRedesignTwo";
import SideSectionRedesignTwo from "./SideSectionRedesignTwo/SideSectionRedesignTwo";
export default async function SideFetchingRedesignTwo({ sideArray = [] }) {
  const locale = await getLocale();
  let bannersData = [];
  let sections = [];
  let filteredData = [];
  // fetching banner that displayed in side 
  const response = await fetchData({ endPoint: `/sections/banner`, locale: locale });
  if (response.status == "success") {
    const data = response.data;
    // Filter out items with display_in: "sidebar"
    filteredData = data?.filter(item => item.banner.display_in == "sidebar");
    bannersData = filteredData?.sort((a, b) => {
      // Sort by display_order in ascending order
      if (a.banner.display_order !== b.banner.display_order) {
        return a.banner.display_order - b.banner.display_order;
      }
      // If display_order is the same, sort by id in ascending order
      return a.id - b.id;
    });
  }
  // Replace banner objects in mainArray with those from bannersData
  const newSideArray = sideArray.map(item => {
    // Check if the type is "banner"
    if (item.type === 'banner') {
      // Find the corresponding new banner in bannersData
      const newItem = bannersData.find(banner => banner.id === item.id);
      // If a new item is found, replace the old item with the new one
      return newItem
        ? {
          ...item,
          section_title: newItem.section_title,
          ...newItem.banner // Spread the properties of the new banner into the old item
        }
        : item; // If no new item is found, keep the old item
    }
    return item; // Keep other items as they are
  });
  // Sort the array by display_order in descending order
  sections = newSideArray.sort((a, b) => {
    return parseInt(a.display_order) - parseInt(b.display_order);
  });

  return (
    sections.length > 0 ? (
      <div className=" space-y-6">
        {sections.map((item) => (
          <div key={item.id} >
            {item.type === 'banner' ?

              <SideBannerRedesignTwo data={item} displayTitle={item.is_title_displayed} published={item.published} />
              :
              <SideSectionRedesignTwo sectionType={item.type} title={item.title} displayTitle={item.is_title_displayed} published={item.published} />
            }
          </div>
        ))}
      </div>
    ) : null
  );
}