'use client';
import React, { useEffect, useState } from 'react';
import ContactHero from '@/components/ContactHero';
import WhoWeAre from '@/components/WhoWeAre';
import SectorServe from '@/components/SectorServe';
import ValueProposition from '@/components/ValueProposition';
import TeamSection from '@/components/TeamSection';
import Footer from '@/components/Footer';
import BackgroundGradients from '@/components/BackgroundGradients';
import ErrorFallback from "@/components/ErrorFallback";
import PageLoading from "@/components/PageLoading";
import StaticPageSchema from "@/components/StaticPageSchema";
import { getStoredLocale, getStoredLocaleRaw, LOCALE_CHANGE_EVENT } from '@/i18n/localeSwitcher';

type SeoMeta = {
  title: string;
  description: string;
  keywords: string[];
};

function getAboutSeoMeta(data: any): SeoMeta {
  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 };
}

export default function AboutPage() {
  const [pageData, setPageData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [seo, setSeo] = useState<SeoMeta>({
    title: "Biomket",
    description: "Biomket marketplace",
    keywords: [],
  });

  useEffect(() => {
    let isMounted = true;

    const loadPageData = async () => {
      setIsLoading(true);
      try {
        const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
        const res = await fetch(
          `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/about-us`,
          {
            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;
        if (isMounted) {
          const aboutPageJson = await res.json();
          console.log("aboutPageJson", aboutPageJson);
          setPageData(aboutPageJson);
          setSeo(getAboutSeoMeta(aboutPageJson));
        }
      } catch {
      } finally {
        if (isMounted) setIsLoading(false);
      }
    };

    loadPageData();

    const onLocaleChange = () => {
      void loadPageData();
    };
    if (typeof window !== "undefined") {
      window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    }
    return () => {
      isMounted = false;
      if (typeof window !== "undefined") {
        window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
      }
    };
  }, []);

  useEffect(() => {
    document.title = seo.title || "Biomket";

    const descriptionContent = seo.description || "Biomket marketplace";
    let descriptionMeta = document.querySelector('meta[name="description"]');
    if (!descriptionMeta) {
      descriptionMeta = document.createElement("meta");
      descriptionMeta.setAttribute("name", "description");
      document.head.appendChild(descriptionMeta);
    }
    descriptionMeta.setAttribute("content", descriptionContent);

    const keywordsContent = seo.keywords.length > 0 ? seo.keywords.join(", ") : "";
    let keywordsMeta = document.querySelector('meta[name="keywords"]');
    if (!keywordsMeta) {
      keywordsMeta = document.createElement("meta");
      keywordsMeta.setAttribute("name", "keywords");
      document.head.appendChild(keywordsMeta);
    }
    if (keywordsContent) {
      keywordsMeta.setAttribute("content", keywordsContent);
    } else {
      keywordsMeta.removeAttribute("content");
    }
  }, [seo]);

  const sections = pageData?.page?.sections ?? [];
  console.log("sections", sections);
  const findSectionData = (...keys: string[]) => {
    const section = sections.find((s: any) =>
      keys.some((k) => String(s?.key ?? "").toLowerCase().includes(k.toLowerCase()))
    );
    const data = section?.components?.[0]?.instance?.data;
    return data?.items?.[0] ?? data ?? null;
  };

  const img_sections = pageData?.page?.sections ?? [];
  console.log("sections", img_sections);
  const findImgSectionData = (...keys: string[]) => {
    const section = img_sections.find((s: any) =>
      keys.some((k) => String(s?.key ?? "").toLowerCase().includes(k.toLowerCase()))
    );
    const data = section?.components?.[0]?.instance?.data;
console.log("img_section", data);
    return data?.items?.[0] ?? data ?? null;
  };

  const heroSection = findSectionData("pahehero");
  const whoWeAreSection = findSectionData("who-we-are");
  const sectorServeSection = findImgSectionData("sector-we-serve");
  const valuePropositionSection = findSectionData("our-vlaue-proposition");
  const teamSection = findSectionData("our-team");
  console.log("heroSection", sectorServeSection);

  const teamBulletText = teamSection?.rich_text?.items?.[0]?.html_text || "";
  const teamTitleMatch = teamBulletText.match(/<p>(.*?)<\/p>/);
  const teamBulletTitle = teamTitleMatch ? teamTitleMatch[1].replace(/<\/?strong>/g, '').trim() : undefined;
  const teamLiMatches = teamBulletText.match(/<li>(.*?)<\/li>/g);
  let teamBullets: string[][] | undefined = undefined;
  if (teamLiMatches) {
    const allPoints = teamLiMatches.map((m: string) => m.replace(/<\/?li>/g, '').trim());
    const mid = Math.ceil(allPoints.length / 2);
    teamBullets = [allPoints.slice(0, mid), allPoints.slice(mid)];
  }

  const heroBg = heroSection?.bg_image?.items?.[0];
  const teamBg = teamSection?.bg_image?.items?.[0];
  console.log("teamBg", sectorServeSection);
  const sectorServeBg = sectorServeSection?.bg_image?.items?.[0];

  if (isLoading) {
    return <PageLoading />;
  }
  if (!pageData) return <ErrorFallback title="About Us" message="Our systems are temporarily unavailable. We apologize for the inconvenience. Please try again later." />;
  if (sections.length === 0) return <ErrorFallback title="About Us" message="Our systems are temporarily unavailable. We apologize for the inconvenience. Please try again later." />;

  return (
    <>
      <StaticPageSchema
        apiSlug="about-us"
        pageUrl="/about"
        fallbackTitle="About Biomket"
        fallbackDescription="Learn more about Biomket and our mission."
      />
      <main className="min-h-screen px-[20px] md:px-[40px] xl:px-[60px] xl:max-w-[1440px] 2xl:max-w-[1920px] mx-auto font-outfit">
        <ContactHero
        headline={
          heroSection?.title ? (
            <h1 className="font-extralight text-white font-lexend leading-tight">
              {(() => {
                const words = heroSection.title.trim().split(/\s+/);
                return (
                  <>
                    {words.slice(0, 3).join(" ")}{" "}
                    {words.length > 3 ? (
                      <span className="font-medium">{words[3]}</span>
                    ) : null}
                    <br />
                    {words.length > 4 ? (
                      <span className="font-medium">{words.slice(4).join(" ")}</span>
                    ) : null}
                  </>
                );
              })()}
            </h1>
          ) : null
        }
        description={heroSection?.description}
        showSearch={false}
        backgroundImageMobile={heroBg?.image_mobile}
        backgroundImageDesktop={heroBg?.image_desktop}
        backgroundImageMobileAlt={heroBg?.mobile_image_alt_tag}
        backgroundImageDesktopAlt={heroBg?.desktop_image_alt_tag}
      />

      <BackgroundGradients count={3} />

      <WhoWeAre
        title={whoWeAreSection?.title}
        description={whoWeAreSection?.description}
        cards={whoWeAreSection?.cards?.items}
      />

      <SectorServe
        title={sectorServeSection?.title}
        description={sectorServeSection?.description}
        sectors={sectorServeSection?.sectors_?.items?.map((s: any) => ({
          iconSrc: s.svg,
          title: s.title,
          desc: s.description
        }))}
        backgroundImageMobile={sectorServeBg?.image_mobile}
        backgroundImageDesktop={sectorServeBg?.image_desktop}
        backgroundImageMobileAlt={sectorServeBg?.mobile_image_alt_tag}
        backgroundImageDesktopAlt={sectorServeBg?.desktop_image_alt_tag}
      />

      <ValueProposition
        title={valuePropositionSection?.title}
        cards={valuePropositionSection?.cards?.items}
      />

      <TeamSection
        title={teamSection?.title}
        description={teamSection?.description}
        bulletPointsTitle={teamBulletTitle}
        bulletPoints={teamBullets}
        cards={teamSection?.cards?.items}
        backgroundImageMobile={teamBg?.image_mobile}
        backgroundImageDesktop={teamBg?.image_desktop}
      />

        <Footer />
      </main>
    </>
  );
}