import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import './homepage.css';
import { ClipLoader } from 'react-spinners';
import SEOHead from './SEO/SEOHead';
import DynamicStructuredData from './SEO/DynamicStructuredData';
import { businessConfig } from '../config/businessConfig';
import { featureFlags } from '../config/featureFlags';
import { InfoBanner } from './Header/InfoBanner/InfoBanner';

// Import skeletons for better loading experience
import GraphicsSkeleton from './GraphicsDisplay/GraphicsSkeleton';
import GraphicsSkeletonV2 from './GraphicsDisplay/GraphicsSkeletonV2';
import FullPageGraphicsContainer from './GraphicsDisplay/FullPageGraphicsContainer';

// Lazy load all components with improved chunking
const Graphics = lazy(() => import('./GraphicsDisplay/Graphics.tsx'));
const BottomContainer = lazy(() => import('./parts/BottomContainer.jsx'));

// Group critical above-the-fold components
const NewestProducts = lazy(() => import('./Homepage/NewestProducts'));
const NewestProductsV2 = lazy(() => import('./Homepage/NewestProductsV2'));
const BestsellersV2 = lazy(() => import('./Homepage/BestsellersV2'));
const OccasionalProducts = lazy(() => import('./Homepage/OccassionalProducts'));
const OccasionalProductsV2 = lazy(() => import('./Homepage/OccasionalProductsV2'));
const PicturesPresents = lazy(() => import('./Homepage/PicturePresents'));
const PicturesPresentsV2 = lazy(() => import('./Homepage/PicturesPresentsV2Container'));
const DisplayImageSectionV2 = lazy(() => import('./Homepage/DisplayImageSectionV2Container'));

// Group below-the-fold components
const FeatureGrid = lazy(() => import('./GraphicsDisplay/FeatureGrid'));
const FeatureSectionV2 = lazy(() => import('./GraphicsDisplay/FeatureSectionV2'));
const CustomProjectSection = lazy(() => import('./GraphicsDisplay/CustomProjectSection'));
const CustomProjectSectionV2 = lazy(() => import('./GraphicsDisplay/CustomProjectSectionV2'));
const WoodSection = lazy(() => import('./Homepage/WoodSection'));
const WoodSectionV2 = lazy(() => import('./Homepage/WoodSectionV2Container'));


// Enhanced loading component with configurable height
export const LoadingFallback = ({ height = '200px' }) => (
  <div className='loading-container' style={{ minHeight: height }}>
    <ClipLoader size={24} color="#a9e603" />
  </div>
);

// Intersection Observer component for below-the-fold content
export function LazyComponent({
  children,
  height = '200px',
  preload = false,
  id = '',
  containContent = true,
  className = '',
  style = {}
}) {
  const [isVisible, setIsVisible] = useState(preload);
  const ref = useRef(null);

  useEffect(() => {
    // Skip observation if preload is true
    if (preload) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { rootMargin: '200px' }
    );

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

    return () => observer.disconnect();
  }, [preload, id]);

  // Combine className prop with conditional classes
  const containerClasses = `lazy-component-container ${containContent ? 'contain-content' : ''} ${className}`;

  return (
    <div
      ref={ref}
      className={containerClasses}
      style={{ minHeight: isVisible ? 'auto' : height, ...style }}
    >
      {isVisible ? children : <LoadingFallback height={height} />}
    </div>
  );
}

export const HomePage = () => {
  const [isMobile, setIsMobile] = useState(false);

  // Check if mobile on mount and resize
  useEffect(() => {
    const checkIfMobile = () => {
      setIsMobile(window.innerWidth <= 900);
    };

    checkIfMobile();
    window.addEventListener('resize', checkIfMobile);

    return () => {
      window.removeEventListener('resize', checkIfMobile);
    };
  }, []);

  // Prefetch critical components
  useEffect(() => {
    const prefetchCriticalComponents = () => {
      const prefetch = async () => {
        try {
          await import('./Homepage/OccassionalProducts');
          await import('./Homepage/PicturePresents');
        } catch (err) {
          console.error('Error prefetching components:', err);
        }
      };

      if ('requestIdleCallback' in window) {
        window.requestIdleCallback(prefetch);
      } else {
        setTimeout(prefetch, 1000);
      }
    };

    prefetchCriticalComponents();
  }, []);



  return (
    <>
      {/* Homepage SEO */}
      <SEOHead 
              title="RoyalGift – Personalizowane Prezenty z Dedykacją | Lampki Led, Prezenty ze zdjęciem, Statuetki"
       description="Każdy prezent ma znaczenie. W RoyalGift tworzymy eleganckie upominki z Twoją dedykacją – personalizowane, dopracowane w każdym detalu, gotowe do wręczenia w 24h."
        keywords="prezenty personalizowane, lampki LED z grawerunkiem, prezenty LED, grawer laserem gratis, dekoracje LED, RoyalGift, prezenty urodzinowe, prezenty na walentynki, prezenty świąteczne, gaming prezenty, anime prezenty, prezenty sportowe, lampki nocne, wysyłka 24h, darmowa dostawa"
        type="website"
        url={`${businessConfig.url}/`}
      />
      
      {/* Dynamic Structured Data from CMS */}
      <DynamicStructuredData />
      
      {/* Info banner - only shown with full page graphics */}
      {featureFlags.useFullPageGraphics && <InfoBanner />}
      
      <div className={`home-page ${featureFlags.useFullPageGraphics ? 'with-overlay-header' : ''}`}>
        {/* Main carousel section - high priority, always load immediately */}
        <LazyComponent preload={true} id="Graphics" height={featureFlags.useFullPageGraphics ? "70vh" : "400px"}>
        <Suspense fallback={featureFlags.useFullPageGraphics ? <GraphicsSkeletonV2 isMobile={isMobile} /> : <GraphicsSkeleton isMobile={isMobile} />}>
          {featureFlags.useFullPageGraphics ? <FullPageGraphicsContainer /> : <Graphics />}
        </Suspense>
      </LazyComponent>

      {/* Group 1: Initial visible products - medium priority, likely visible */}
      <LazyComponent height="520px" preload={true} id="OccasionalProducts">
        <Suspense fallback={<LoadingFallback height="520px" />}>
          {featureFlags.useOccasionalProductsV2 ? <OccasionalProductsV2 /> : <OccasionalProducts />}
        </Suspense>
      </LazyComponent>

      
      <LazyComponent height="300px" id="WoodSection">
        <Suspense fallback={<LoadingFallback height="300px" />}>
          {featureFlags.useWoodSectionV2 ? <WoodSectionV2 /> : <WoodSection />}
        </Suspense>
      </LazyComponent>


        {/* Updated NewestProducts section with better mobile styling */}
        <LazyComponent
          height="auto"
          id="NewestProducts"
          style={{
            position: 'relative',
            zIndex: 1,
            paddingTop: isMobile ? '0px' : '0px', // Reduced padding for mobile
            width: '100%', // Ensure full width on mobile
            overflow: 'visible' // Prevent any content clipping
          }}
        >
          <Suspense fallback={<LoadingFallback height={isMobile ? '280px' : '350px'} />}>
            {featureFlags.useNewestProductsV2 ? <NewestProductsV2 /> : <NewestProducts />}
          </Suspense>
        </LazyComponent>
      <div className="sections-container" style={{ position: 'relative', zIndex: 1 }}>
        <LazyComponent
          height="300px"
          preload={true}
          id="PicturesPresents"
          containContent={false}
          className="picture-presents-container"
          style={{
            position: 'relative',
            zIndex: 1,
          }}
        >
          <Suspense fallback={<LoadingFallback height="300px" />}>
            {featureFlags.usePhotoGiftsV2 ? <PicturesPresentsV2 /> : <PicturesPresents />}
          </Suspense>
        </LazyComponent>

        {/* Display Image Section - Full-width hero with overlay */}
        {featureFlags.useDisplayImageSectionV2 && (
          <LazyComponent
            height="600px"
            preload={false}
            id="DisplayImageSection"
            containContent={true}
          >
            <Suspense fallback={<LoadingFallback height="600px" />}>
              <DisplayImageSectionV2 />
            </Suspense>
          </LazyComponent>
        )}


        {/* Bestsellers section - displays top 8 products for current month */}
        <LazyComponent
          height="auto"
          id="Bestsellers"
          style={{
            position: 'relative',
            zIndex: 1,
            paddingTop: isMobile ? '0px' : '0px',
            width: '100%',
            overflow: 'visible'
          }}
        >
          <Suspense fallback={<LoadingFallback height={isMobile ? '280px' : '350px'} />}>
            <BestsellersV2 />
          </Suspense>
        </LazyComponent>
      </div>

      
      <LazyComponent height="200px" id="FeatureGrid">
        <Suspense fallback={<LoadingFallback height="200px" />}>
          {featureFlags.useRedesignedInfoBanner ? <FeatureSectionV2 /> : <FeatureGrid />}
        </Suspense>
      </LazyComponent>


      {/* Group 3: Bottom sections - lowest priority, only load when scrolled to */}
      <LazyComponent height="250px" id="CustomProjectSection">
        <Suspense fallback={<LoadingFallback height="250px" />}>
          {featureFlags.useCustomProjectSectionV2 ? <CustomProjectSectionV2 /> : <CustomProjectSection />}
        </Suspense>
      </LazyComponent>


   



      <LazyComponent id="BottomContainer">
        <Suspense fallback={<LoadingFallback />}>
          <BottomContainer />
        </Suspense>
      </LazyComponent>
      </div>
    </>
  );
};