"use client";

// components/WhyYoungEngineers/WhyYoungEngineersLazyWrapper.tsx
import { useState, useEffect, useRef, useMemo } from "react";
import dynamic from "next/dynamic";
import { getHomePageDataAction } from "@/src/lib/actions/homePageAction";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import WhyYoungEngineersSkeleton from "../../ui/skeletons/WhyYoungEngineersSkeleton";
import staticData from "@/src/data/home.json";

const ClientWhyYoungEngineers = dynamic(
  () => import("./Client"),
  {
    ssr: false,
    loading: () => <WhyYoungEngineersSkeleton />,
  }
);

interface LazyWrapperProps {
  initialData?: any;
}

export default function WhyYoungEngineersLazyWrapper({ initialData }: LazyWrapperProps) {
  const ref = useRef<HTMLDivElement>(null);
  const [fullData, setFullData] = useState<any>(initialData || null);
  const [isLoading, setIsLoading] = useState(false);
  const [hasLoaded, setHasLoaded] = useState(!!initialData);
  const { currentLanguage, isInitialized } = useLanguage();

  useEffect(() => {
    // If we already have data (from props or previous fetch), don't fetch again
    if (!isInitialized || hasLoaded || isLoading || initialData) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !hasLoaded) {
          setIsLoading(true);

          const params = new URLSearchParams(window.location.search);
          const franchiseeId = params.get("franchiseeId");

          // Note: Standardize to use currentLanguage for the fetch
          getHomePageDataAction()
            .then((response) => {
              if (response.success && response.data) {
                setFullData(response.data);
                setHasLoaded(true);
              }
            })
            .catch((error) => {
              console.error("[WhyYoungEngineersLazyWrapper] Failed to load:", error);
            })
            .finally(() => {
              setIsLoading(false);
            });

          if (ref.current) {
            observer.unobserve(ref.current);
          }
        }
      },
      { rootMargin: "200px" }
    );

    if (ref.current) {
      observer.observe(ref.current);
    }

    return () => {
      if (ref.current) {
        observer.unobserve(ref.current);
      }
    };
  }, [hasLoaded, isLoading, initialData, currentLanguage, isInitialized]);

  // Update fullData if initialData changes (e.g. on language switch in parent)
  useEffect(() => {
    if (initialData) {
      setFullData(initialData);
      setHasLoaded(true);
    }
  }, [initialData]);

  // Select content based on current language
  // Use mergeContentWithTranslation logic if possible, or simple selection
  const homeContent = useMemo(() => {
    if (!fullData) return null;

    // If we passed already-merged content from HomePageClient, use it directly
    if (fullData.whyYoungEngineers && !fullData.default) {
      return fullData;
    }

    const def = fullData.default || {};
    const trans = fullData.translated;

    // If we're on default language, or no translation available
    if (currentLanguage === "default" || !trans) {
      return def;
    }

    // Logic for language selection (compatible with dynamic codes)
    return trans;
  }, [fullData, currentLanguage]);

  const whyRawData = homeContent?.whyYoungEngineers;

  // Load static slides for images
  const staticSlides = staticData.whyYoungEngineers.slides;

  // Merge: static images + dynamic text (from both default and translated)
  const whyData = useMemo(() => {
    if (!whyRawData) return null;

    // Parse sliders if it's a string
    const apiSliders = whyRawData && typeof whyRawData.sliders === 'string'
      ? JSON.parse(whyRawData.sliders || '[]')
      : whyRawData?.sliders || [];

    // Drive the slider count from the API; fall back to static per-index for text/images
    const source = apiSliders.length ? apiSliders : staticSlides;
    const mergedSliders = source.map((_: any, index: number) => {
      const apiSlide = apiSliders[index] || {};
      const staticSlide = staticSlides[index] || staticSlides[0] || {};
      return {
        sliderHeading: apiSlide.sliderHeading || staticSlide.title?.split("—")[0] || `Feature ${index + 1}`,
        title: apiSlide.title || staticSlide.title,
        description: apiSlide.description || staticSlide.desc,
        image: apiSlide.image || staticSlide.image, // API per-slider image, fallback to static
        ctaButtonText: apiSlide.ctaButtonText, // per-slider CTA (Client falls back to default if empty)
        ctaButtonLink: apiSlide.ctaButtonLink,
      };
    });

    return {
      mainHeading: whyRawData.mainHeading || "Why Young Engineers",
      sliders: mergedSliders,
      ctaButtonText: whyRawData.ctaButtonText || "Discover Programs",
    };
  }, [whyRawData, staticSlides]);

  return (
    <div ref={ref}>
      {whyData ? <ClientWhyYoungEngineers data={whyData} /> : <WhyYoungEngineersSkeleton />}
    </div>
  );
}
