import BackgroundGradients from "@/components/BackgroundGradients";
import Footer from "@/components/Footer";
import Hero from "@/components/Hero";
import HowItWorksSection from "@/components/HowItWorksSection";
import MarketplaceSection from "@/components/MarketplaceSection";
import type { Product } from "@/components/ProductCard";
import type { Metadata } from "next";
export const dynamic = "force-dynamic";
import WasteCategoriesSection, {
  type WasteCategoriesSectionData,
} from "@/components/WasteCategoriesSection";
import WasteManagementSection from "@/components/WasteManagementSection";
import WhyBiomketSection from "@/components/WhyBiomketSection";
import { buildDynamicMetadata } from "@/lib/metadata";
import { websiteSchema } from "@/lib/schema";
import { getMedusaLocaleHeaderForStoreApi } from "@/i18n/localeSwitcher";
import { cookies } from "next/headers";

function toMarketplacePathSegment(value: unknown): string {
  const raw = String(value ?? "")
    .trim()
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
  return raw;
}

function isRealCategorySegment(value: string): boolean {
  const t = String(value ?? "").trim();
  return t.length > 0 && t !== "undefined" && t !== "uncategorized";
}

function collectCategoryTreePathSlugs(tree: unknown): string[] {
  const slugs: string[] = [];
  let node: unknown = tree;
  while (node && typeof node === "object" && !Array.isArray(node)) {
    const rec = node as Record<string, unknown>;
    const slug = toMarketplacePathSegment(rec.slug);
    if (isRealCategorySegment(slug)) slugs.push(slug);
    node = rec.sub_category ?? rec.subcategory ?? null;
  }
  return slugs;
}

function marketplaceProductUrlPartsFromApiItem(item: Record<string, unknown>): {
  marketplace_path_segments: string[];
  category_slug: string;
  subcategory_slug: string;
  product_slug: string;
} | null {
  const product_slug = toMarketplacePathSegment(item?.handle ?? item?.slug ?? "");
  if (!product_slug) return null;

  const treeSegments = collectCategoryTreePathSlugs(item?.category_tree);
  if (treeSegments.length > 0) {
    return {
      marketplace_path_segments: treeSegments,
      category_slug: treeSegments[0]!,
      subcategory_slug: treeSegments[1] ?? "",
      product_slug,
    };
  }

  const categoryObj = (item?.category ?? null) as Record<string, unknown> | null;
  const nestedSubcategory = (categoryObj?.subcategory ?? null) as Record<string, unknown> | null;
  const categoryRaw =
    item?.category_slug ??
    item?.category_handle ??
    item?.category_name ??
    item?.category_label ??
    (typeof item?.category === "string" ? item.category : null) ??
    categoryObj?.slug ??
    categoryObj?.handle ??
    categoryObj?.name;
  const subcategoryRaw =
    item?.subcategory_slug ??
    item?.subcategory_handle ??
    item?.subcategory_name ??
    item?.subcategory_label ??
    nestedSubcategory?.slug ??
    nestedSubcategory?.handle ??
    nestedSubcategory?.name;
  const flatSegments = [toMarketplacePathSegment(categoryRaw), toMarketplacePathSegment(subcategoryRaw)].filter(
    isRealCategorySegment,
  );
  if (flatSegments.length > 0) {
    return {
      marketplace_path_segments: flatSegments,
      category_slug: flatSegments[0]!,
      subcategory_slug: flatSegments[1] ?? "",
      product_slug,
    };
  }

  return {
    marketplace_path_segments: [],
    category_slug: "",
    subcategory_slug: "",
    product_slug,
  };
}

const HOME_ZIGZAG_COUNT = 6;

async function getMedusaLocaleHeaderValue(): Promise<string> {
  const jar = await cookies();
  return getMedusaLocaleHeaderForStoreApi(jar);
}

async function getHomePage() {
  const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
  if (!base) return null;
  try {
    const xMedusaLocale = await getMedusaLocaleHeaderValue();
    const res = await fetch(`${base}/store/pages/home`, {
      method: "GET",
      headers: {
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        "x-medusa-locale": xMedusaLocale,
      },
      cache: "no-store"
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

async function getProduct() {
  const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
  if (!base) return null;
  try {
    const xMedusaLocale = await getMedusaLocaleHeaderValue();
    const res = await fetch(`${base}/store/product-cards`, {
      method: "GET",
      headers: {
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
        "x-medusa-locale": xMedusaLocale,
      },
      cache: "no-store"
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

function getHomeSeoMeta(data: any) {
  const seoSection = data?.page?.sections?.find((section: any) => section.key === "seo");
  const seoComponent = seoSection?.components?.find(
    (component: any) =>
      component?.type?.name === "seo_meta"
  );
  const seoItem = seoComponent?.instance?.data ?? {};

  const title = typeof seoItem?.title === "string" ? seoItem.title : "";
  const description = typeof seoItem?.description === "string" ? seoItem.description : "";
  const keywordsRaw = typeof seoItem?.keywords === "string" ? seoItem.keywords : "";
  const keywords = keywordsRaw
    .split(",")
    .map((keyword: string) => keyword.trim())
    .filter(Boolean);

  return { title, description, keywords };
}

function getHomeOpenGraph(data: any) {
  const seoSection = data?.page?.sections?.find((section: any) => section.key === "open-graph-section");
  const seoComponent = seoSection?.components?.find(
    (component: any) =>
      component?.type?.name === "open_graph"
  );
  const seoItem = seoComponent?.instance?.data ?? {};

  const title = typeof seoItem?.title === "string" ? seoItem.title : "";
  const description = typeof seoItem?.description === "string" ? seoItem.description : "";
  const image =
    typeof seoItem?.image?.items?.[0]?.image === "string" ? seoItem.image.items[0].image : "";

  return { title, description, image };
}

export async function generateMetadata(): Promise<Metadata> {
  const data = (await getHomePage()) ?? { page: { sections: [] } };
  const seo = getHomeSeoMeta(data);
  const openGraph = getHomeOpenGraph(data);
  return buildDynamicMetadata({
    seoTitle: seo.title,
    seoDescription: seo.description,
    seoKeywords: seo.keywords,
    ogTitle: openGraph.title,
    ogDescription: openGraph.description,
    ogImage: openGraph.image,
    pageUrl: "/",
    fallbackTitle: "Biomket",
    fallbackDescription: "Biomket marketplace",
  });
}

export default async function Home() {
  const schema = await websiteSchema();
  const data = (await getHomePage()) ?? { page: { sections: [] } };
  const productData = (await getProduct()) ?? { products: [] };

  const bannerSection = data?.page?.sections?.find(
    (section: any) => section.key === "bannersection"
  );
  const bannerData = bannerSection?.components?.[0]?.instance?.data?.items?.[0];
  const bannerBg = bannerData?.bg_image?.items?.[0] ?? {};
  const heroData = {
    title: bannerData?.title || "",
    description: bannerData?.description || "",
    webImage:
      bannerBg?.image_desktop ??
      bannerBg?.desktop_image ??
      bannerData?.image_desktop ??
      bannerData?.desktop_image ??
      "",
    tabletImage:
      bannerBg?.image_tablet ??
      bannerBg?.tablet_image ??
      bannerBg?.image_desktop ??
      bannerData?.image_tablet ??
      bannerData?.tablet_image ??
      "",
    mobileImage:
      bannerBg?.image_mobile ??
      bannerBg?.mobile_image ??
      bannerData?.image_mobile ??
      bannerData?.mobile_image ??
      "",
    desktopImageAlt:
      bannerBg?.desktop_image_alt_tag ??
      "",
    mobileImageAlt:
      bannerBg?.mobile_image_alt_tag ??
      "",
    buttons:
      bannerData?.button?.items?.map((item: any, index: number) => ({
        label: item.button_text ?? "",
        href: item.button_url ?? "",
        variant: index % 2 == 0 ? "primary" : "secondary",
      })) ?? [],
  };

  const wasteCategoriesSection = data?.page?.sections?.find(
    (section: any) => section.key === "wastecategoriessection"
  );
  const wcData = wasteCategoriesSection?.components?.[0]?.instance?.data;
  const wasteCategoriesData: WasteCategoriesSectionData | null = wcData
    ? {
      title: wcData.title ?? "",
      description: wcData.description ?? "",
      cards:
        wcData.cards?.items?.map((item: { svg?: string; title?: string }, i: number) => ({
          svg: item.svg ?? "",
          title: item.title ?? "",
          id: String(i + 1),
        })) ?? [],
      bgImageDesktop: wcData.bg_image?.items?.[0]?.image_desktop ?? "",
      bgImageMobile: wcData.bg_image?.items?.[0]?.image_mobile ?? "",
    }
    : null;

  const marketplaceSection = data?.page?.sections?.find(
    (section: any) => section.key == "organicwastemarketplace"
  );
  const mpData = marketplaceSection?.components?.[0]?.instance?.data?.items?.[0];
  const pData = productData?.products ?? [];
  const productEntries = pData
    .map((item: any): [string | number, Product] | null => {
      const parts = marketplaceProductUrlPartsFromApiItem(item as Record<string, unknown>);
      if (!parts) return null;
      const id = item.id ?? String(Math.random());
      return [
        id,
        {
          id,
          handle: item.handle ?? "",
          marketplace_path_segments: parts.marketplace_path_segments,
          category_slug: parts.category_slug,
          subcategory_slug: parts.subcategory_slug,
          product_slug: parts.product_slug,
          image: item.image ?? "",
          category: item.category_label ?? "",
          title: item.name ?? "",
          location: item.location ?? "",
          available_quantity: item.available_quantity ?? "",
          code: item.code ?? "",
          price_amount: item.price_amount ?? "",
          currency_symbol: item.currency_symbol ?? "",
          inStock: item.availability ?? false,
          unit: item.unit ?? "",
        },
      ];
    })
    .filter(
      (entry: [string | number, Product] | null): entry is [string | number, Product] =>
        entry !== null
    );
  const productsMap = new Map(productEntries);
  const marketplaceData = {
    title: mpData?.title ?? "",
    description: mpData?.description ?? "",
    button: mpData?.button?.items?.[0] ?? "",
    products: Array.from(productsMap.values()) as Product[],
  };

  const wasteManagementSection = data?.page?.sections?.find(
    (section: any) => section.key === "waste-management"
  );
  const wmData = wasteManagementSection?.components?.[0]?.instance?.data;
  const wasteManagementData = wmData
    ? {
      title: wmData.title ?? wmData.title ?? "",
      description: wmData.description ?? "",
      buttonLabel: wmData.button?.items?.[0]?.button_text ?? wmData.button?.items?.[0]?.button_text ?? "",
      buttonHref: wmData.button?.items?.[0]?.button_url ?? wmData.button?.items?.[0]?.button_url ?? "",
      features:
        wmData.optimization_steps?.items?.map(
          (item: { svg?: string; title?: string; description?: string }, i: number) => ({
            id: String(i + 1),
            svg: item.svg ?? "",
            title: item.title ?? "",
            description: item.description ?? "",
          })
        ) ?? [],
    }
    : null;

  const howItWorksSection = data?.page?.sections?.find(
    (section: any) => section.key === "how-it-works"
  );
  const hiwData = howItWorksSection?.components?.[0]?.instance?.data.items?.[0];
  const howItWorksData = hiwData
    ? {
      title: hiwData.title ?? hiwData.title ?? "",
      description: hiwData.description ?? "",
      buttonLabel: hiwData.button?.items?.[0]?.button_text ?? hiwData.buttontext ?? "",
      buttonHref: hiwData.button?.items?.[0]?.button_url ?? hiwData.buttonurl ?? "",
      steps:
        hiwData.works_steps?.items?.map(
          (item: { svg?: string; title?: string; description?: string; number?: string }, i: number) => ({
            id: String(i + 1),
            number: item.number ?? String(i + 1).padStart(2, "0"),
            svg: item.svg ?? "",
            title: item.title ?? "",
            description: item.description ?? "",
          })
        ) ?? hiwData.works_steps?.items?.map(
          (item: { svg?: string; title?: string; description?: string; number?: string }, i: number) => ({
            id: String(i + 1),
            number: item.number ?? String(i + 1).padStart(2, "0"),
            svg: item.svg ?? "",
            title: item.title ?? "",
            description: item.description ?? "",
          })
        ) ?? [],
    }
    : null;

  const whyBiomketSection = data?.page?.sections?.find(
    (section: any) => section.key === "why-biomket"
  );
  const wbData = whyBiomketSection?.components?.[0]?.instance?.data;
  type WbCardItem = {
    svg?: string;
    logo_svg?: string;
    title?: string;
    description?: string;
    link?: string;
    url?: string;
  };
  const wbCardsAsArray = Array.isArray(wbData?.cards) ? wbData.cards : [];
  const wbCardsFromArrayWrapper =
    wbCardsAsArray.length === 1 &&
      Array.isArray((wbCardsAsArray[0] as { items?: unknown[] })?.items)
      ? ((wbCardsAsArray[0] as { items?: WbCardItem[] }).items ?? [])
      : [];
  const wbCardItems: WbCardItem[] = Array.isArray(wbData?.cards?.items)
    ? (wbData.cards.items as WbCardItem[])
    : wbCardsFromArrayWrapper.length > 0
      ? wbCardsFromArrayWrapper
      : Array.isArray(wbData?.items)
        ? (wbData.items as WbCardItem[])
        : wbCardsAsArray as WbCardItem[];
  const wbTitle =
    typeof wbData?.title === "string"
      ? wbData.title
      : typeof wbData?.title?.value === "string"
        ? wbData.title.value
        : typeof wbData?.title?.text === "string"
          ? wbData.title.text
          : "";
  const whyBiomketData = wbData
    ? {
      title: wbTitle,
      cards: wbCardItems.map((item, i) => ({
        id: i,
        title: item.title ?? "",
        description: item.description ?? "",
        link: item.url ?? item.link ?? "#",
        svg: item.logo_svg ?? item.svg ?? "",
      })),
    }
    : null;

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
      />
      <div className="min-h-screen flex flex-col text-black max-w-[1920px] mx-auto px-[20px] md:px-[40px] xl:px-[60px] overflow-x-hidden">
        <Hero
          title={heroData.title}
          description={heroData.description}
          buttons={heroData.buttons}
          desktopImage={heroData.webImage || undefined}
          tabletImage={heroData.tabletImage || undefined}
          mobileImage={heroData.mobileImage || undefined}
          desktopImageAlt={heroData.desktopImageAlt || undefined}
          mobileImageAlt={heroData.mobileImageAlt || undefined}
        />

        <BackgroundGradients count={HOME_ZIGZAG_COUNT} />

        <MarketplaceSection
          title={marketplaceData.title}
          description={marketplaceData.description}
          button={marketplaceData.button}
          products={marketplaceData.products}
        />

        <WasteCategoriesSection data={wasteCategoriesData} />
        <WasteManagementSection data={wasteManagementData} />
        <HowItWorksSection data={howItWorksData} />
        <WhyBiomketSection data={whyBiomketData} />
        <Footer />
      </div>
    </>
  );
}