import fetchData from "@/api/fetch-data";
import { getLocale } from "next-intl/server";
import MainBannerRedesignTwo from "./MainBannerRedesignTwo/MainBannerRedesignTwo";
import MainSectionRedesignTwo from "./MainSectionRedesignTwo";

export default async function MainFetchingRedesignTwo({
  mainArray = [],
  styles = "md:basis-1/2 lg:basis-1/3 xl:basis-1/6",
  iconColor = "text-white",
}) {
  const locale = await getLocale();
  let bannersData = [];
  let sections = [];
  let filteredData = [];
  // fetching banner that displayed in home
  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 newMainArray = mainArray.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 = newMainArray.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" ? (
            <MainBannerRedesignTwo
              data={item}
              displayTitle={item.is_title_displayed}
              published={item.published}
            />
          ) : (
            <MainSectionRedesignTwo
              sectionId={item.id}
              sectionType={item.type}
              title={item.title}
              displayTitle={item.is_title_displayed}
              published={item.published}
              styles={styles}
              iconColor={iconColor}
            />
          )}
        </div>
      ))}
    </div>
  ) : null;
}
