'use client';
import { useEffect, useState } from "react";
import ContactHero from "@/components/ContactHero";
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 getLegalNoticeSeoMeta(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 LegalNoticePage() {
    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 () => {
            try {
                const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
                const res = await fetch(
                    `${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/legal-notice`,
                    {
                        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 legalNoticePageJson = await res.json();
                    setPageData(legalNoticePageJson);
                    setSeo(getLegalNoticeSeoMeta(legalNoticePageJson));
                }
            } 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 ?? [];
    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 bannerSection = findSectionData("banner-section");
    const contentSection = findSectionData("content-section");

    const heroTitle = bannerSection?.title ?? "";
    const heroDescription = bannerSection?.description ?? "";
    const heroBg = bannerSection?.bg_image?.items?.[0] ?? {};
    const heroBgMobile =
        heroBg?.image_mobile ?? "";
    const heroBgDesktop =
        heroBg?.image_desktop ?? "";
    const heroBgMobileAlt =
        heroBg?.mobile_image_alt_tag ?? "";
    const heroBgDesktopAlt =
        heroBg?.desktop_image_alt_tag ?? "";

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

    return (
        <>
            <StaticPageSchema
                apiSlug="legal-notice"
                pageUrl="/legal-notice"
                fallbackTitle="Legal Notice"
                fallbackDescription="Review the Biomket legal notice."
            />
            <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">
            <style dangerouslySetInnerHTML={{
                __html: `
                .legal-content-container ol {
                    list-style-type: decimal !important;
                    padding-left: 1.5rem !important;
                }
                .legal-content-container li {
                    margin-bottom: 1.5rem !important;
                }
                .legal-content-container li::marker {
                    font-weight: 600;
                    color: #2A4F45;
                }
                .legal-content-container p {
                    margin-bottom: 1rem;
                }
            `}} />
            <ContactHero
                headline={
                    <h1 className="font-lexend font-extralight text-[#ffffff] max-w-[782px]">
                        {(() => {
                            const words = heroTitle.trim().split(/\s+/);
                            return (
                                <>
                                    {words.slice(0, 2).join(" ")}{" "}
                                    {words.length > 2 ? (
                                        <span className="font-medium">{words.slice(2).join(" ")}</span>
                                    ) : null}
                                </>
                            );
                        })()}
                    </h1>
                }
                description={heroDescription}
                showSearch={false}
                backgroundImageMobile={heroBgMobile || undefined}
                backgroundImageDesktop={heroBgDesktop || undefined}
                backgroundImageMobileAlt={heroBgMobileAlt || undefined}
                backgroundImageDesktopAlt={heroBgDesktopAlt || undefined}
            />

            <BackgroundGradients count={1} />

            <div className="mb-[70px] max-w-[1840px] mx-auto font-outfit">
                <div className="bg-[#F7FAF8] rounded-[20px] border border-[#053F31]/20 p-[30px] text-[20px] leading-[150%] text-[#000000] legal-content-container">
                    <div dangerouslySetInnerHTML={{ __html: contentSection?.html_text || "" }} />
                </div>
            </div>

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