import { serverApiClient } from "@/utils/serverApiClient";
import { MainMenu, MenuItem } from "./menuType";

const MAX_ITEMS = 8;

function limitItems(
  items: MenuItem[],
  limit: number,
  moreUrl: string,
  moreLabel: string,
): MenuItem[] {
  const sliced = items.slice(0, limit);

  if (items.length <= limit) return sliced;

  return [
    ...sliced,
    {
      title: moreLabel,
      url: moreUrl,
      type: "cta",
    },
  ];
}

/**
 * Safe mapper (prevents undefined / bad API)
 */
function mapItems(
  data: any[] | undefined,
  basePath: string,
  key: "slug" | "url",
): MenuItem[] {
  if (!Array.isArray(data)) return [];

  return data.map((item) => ({
    title: item?.title ?? "",
    url: `${basePath}/${item?.[key] ?? ""}`,
  }));
}

export async function getMegaItems(): Promise<MainMenu[]> {
  let dynamicDesignHouses: MenuItem[] = [];
  let dynamicCoCreators: MenuItem[] = [];
  let dynamicStories: MenuItem[] = [];

  try {
    const result = await serverApiClient("design-list", {
      revalidate: 120,
    });

    if (result?.success && result?.data) {
      dynamicDesignHouses = mapItems(
        result.data.design_house,
        "/design-houses",
        "slug",
      );

      dynamicCoCreators = mapItems(
        result.data.co_creator,
        "/co-creators",
        "slug",
      );

      dynamicStories = mapItems(result.data.stories, "/stories", "url");
    }
  } catch (error) {
    console.error("Mega menu fetch failed:", error);
  }

  return [
    {
      title: "Co-Creation",
      children: [
        {
          group: "Featured Co-Creators",
          items: limitItems(
            dynamicCoCreators,
            MAX_ITEMS,
            "/stories",
            "More co-creators",
          ),
        },
        {
          group: "Stories",
          items: limitItems(
            dynamicStories,
            MAX_ITEMS,
            "/stories",
            "More stories",
          ),
        },
        {
          group: "whatCC",
          items: [
            {
              title: "(What is Co-creation?)",
              url: "/co-creation",
            },
          ],
        },
      ],
    },
    {
      title: "Atelier",
      children: [
        {
          group: "",
          items: [
            { title: "Tops", url: "/category?category=tops" },
            { title: "Vest", url: "/category?category=vests" },
            { title: "Bottoms", url: "/category?category=bottom" },
            { title: "Co-ord Sets", url: "/category?category=co-ord-set" },
            { title: "Suits", url: "/category?category=suits" },
          ],
        },
        {
          group: "",
          items: [
            { title: "One-Pieces", url: "/category?category=one-pieces" },
            { title: "Outerwear", url: "/category?category=outerwear" },
            { title: "Athleisure", url: "/category?category=knitwear" },
            { title: "Bags", url: "/category?category=bags" },
          ],
        },
        {
          group: "CatAllLink",
          items: [{ title: "View All", url: "/category", type: "cta" }],
        },
      ],
    },
    {
      title: "Brand Partners",
      children: [
        {
          group: "Services",
          items: [
            {
              title: "Become a brand partner",
              url: "https://brands.mymorni.com/",
            },
          ],
        },
        {
          group: "Case Studies",
          items: [
            {
              title: "High Frequency Jackets for One Golden Thread",
              url: "https://brands.mymorni.com/brand-partners/one-golden-thread",
            },
            {
              title: "Ethereal Silhouettes for Zhinh",
              url: "https://brands.mymorni.com/brand-partners/zhinh",
            },
            {
              title: "Kala Cotton Collection for Mala",
              url: "https://brands.mymorni.com/brand-partners/mala",
            },
            {
              title: "Chef Jackets and Totes for Greenr",
              url: "https://brands.mymorni.com/brand-partners/greenr",
            },
            {
              title: "Elevated Everyday Essentials for MARJON",
              url: "https://brands.mymorni.com/brand-partners/marjon",
            },
          ],
        },
      ],
    },
    {
      title: "MorniVerse",
      children: [
        {
          group: "Discover",
          items: [
            { title: "Materials", url: "/fabrics" },
            { title: "Library", url: "/library" },
            { title: "Journal", url: "/journal" },
            { title: "About", url: "/about" },
          ],
        },
        {
          group: "Fun Projects",
          items: [
            { title: "Mushrooms", url: "https://stories.mymorni.ai/mushroom" },
            {
              title: "Peter Cat Recording Co 2024 Tour",
              url: "/project/peter-cat-recording-co",
            },
            {
              title: "Young The Giant 2023 Tour",
              url: "https://stories.mymorni.ai/young-the-giant",
            },
            {
              title: "Odyssey the Film",
              url: "https://stories.mymorni.ai/odyssey",
            },
          ],
        },
      ],
    },
    {
      title: "Design Houses",
      children: [
        {
          group: "",
          items: limitItems(
            dynamicDesignHouses,
            MAX_ITEMS,
            "/stories",
            "More stories",
          ),
        },
      ],
    },
  ];
}
