// ── Eager (above the fold) ────────────────────────────────────────────────
import { Navbar } from '../components/Navbar';
import { Hero } from '../components/Hero';
import { LogosSlider } from '../components/LogosSlider';
import { WhatsAppButton } from '../components/WhatsAppButton';

// ── Lazy (below the fold) ─────────────────────────────────────────────────
import { lazy, Suspense, useEffect, useState } from 'react';
import { AnimatePresence } from 'framer-motion';

import { trackSectionView } from '../lib/analytics';
import { Preloader } from '../components/Preloader';
import { initScrollAnimations } from '../lib/scrollAnimations';
import { scrollTo as lenisScrollTo } from '../lib/useSmoothScroll';

const BentoFeatures = lazy(() => import('../components/BentoFeatures').then(m => ({ default: m.BentoFeatures })));
const Manifesto = lazy(() => import('../components/Manifesto').then(m => ({ default: m.Manifesto })));
const ProcessSection = lazy(() => import('../components/ProcessSection').then(m => ({ default: m.ProcessSection })));
const About = lazy(() => import('../components/About').then(m => ({ default: m.About })));
const Capabilities = lazy(() => import('../components/Capabilities').then(m => ({ default: m.Capabilities })));
const Portfolio = lazy(() => import('../components/Portfolio').then(m => ({ default: m.Portfolio })));
const ChatTestimonials = lazy(() => import('../components/ChatTestimonials').then(m => ({ default: m.ChatTestimonials })));
const Testimonials = lazy(() => import('../components/Testimonials').then(m => ({ default: m.Testimonials })));
const Showreel = lazy(() => import('../components/Showreel').then(m => ({ default: m.Showreel })));

const Contact = lazy(() => import('../components/Contact').then(m => ({ default: m.Contact })));
const Footer = lazy(() => import('../components/Footer').then(m => ({ default: m.Footer })));

const Fallback = () => <div className="h-32" aria-hidden="true" />;

export default function Home() {
  const [isLoading, setIsLoading] = useState(() => !sessionStorage.getItem('preloaderShown'));

  const scrollToSection = (selector: string) => {
    const el = document.querySelector(selector) as HTMLElement | null;
    if (el) lenisScrollTo(el, -80);
  };

  const handlePreloaderComplete = () => {
    sessionStorage.setItem('preloaderShown', 'true');
    setIsLoading(false);
  };

  useEffect(() => {
    if (isLoading) return;
    const cleanup = initScrollAnimations();
    return cleanup;
  }, [isLoading]);

  useEffect(() => {
    if (isLoading) return;
    const target = sessionStorage.getItem('scrollTarget');
    if (!target) return;
    sessionStorage.removeItem('scrollTarget');

    let attempts = 0;
    const tryScroll = () => {
      const el = document.querySelector(target) as HTMLElement | null;
      if (el) {
        lenisScrollTo(el, -80);
      } else if (attempts < 20) {
        attempts++;
        setTimeout(tryScroll, 150);
      }
    };
    setTimeout(tryScroll, 300);
  }, [isLoading]);

  useEffect(() => {
    if (isLoading) return;
    const sections = document.querySelectorAll<HTMLElement>('section[id]');
    if (!sections.length) return;
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) trackSectionView((e.target as HTMLElement).id);
        });
      },
      { threshold: 0.25 }
    );
    sections.forEach((s) => observer.observe(s));
    return () => observer.disconnect();
  }, [isLoading]);

  return (
    <div className="relative min-h-screen selection:bg-pinnacle-teal selection:text-black">
      <AnimatePresence>
        {isLoading && <Preloader onComplete={handlePreloaderComplete} />}
      </AnimatePresence>

      {!isLoading && (
        <>
          <Navbar />
          <main id="main-content" className="pb-24 md:pb-0">
            {/* 1. Hero */}
            <Hero />

            {/* 2. Logo ticker strip */}
            <LogosSlider />

            {/* 3. Services grid (Infype-style) */}
            <Suspense fallback={<Fallback />}><BentoFeatures /></Suspense>

            {/* 4. Showreel / Why Choose Us */}
            <Suspense fallback={<Fallback />}><Showreel /></Suspense>

            {/* 5. Services accordion */}
            <Suspense fallback={<Fallback />}><Capabilities /></Suspense>

            {/* 6. Collab / Process section */}
            <Suspense fallback={<Fallback />}><ProcessSection /></Suspense>

            {/* 7. About / Stats */}
            <Suspense fallback={<Fallback />}><About /></Suspense>

            {/* 8. Portfolio grid */}
            <Suspense fallback={<Fallback />}><Portfolio /></Suspense>

            {/* 9. Testimonials */}
            <Suspense fallback={<Fallback />}><ChatTestimonials /></Suspense>
            <Suspense fallback={<Fallback />}><Testimonials /></Suspense>

            {/* 10. FAQ */}
            <Suspense fallback={<Fallback />}><Manifesto /></Suspense>

            {/* 11. Contact */}
            <Suspense fallback={<Fallback />}><Contact /></Suspense>
          </main>

          <Suspense fallback={null}><Footer /></Suspense>

          {/* Mobile sticky CTA bar */}
          <div className="md:hidden fixed bottom-4 left-0 right-0 z-40 px-4">
            <div className="mx-auto max-w-md rounded-2xl border border-[var(--border-primary)] bg-[var(--bg-primary)]/90 backdrop-blur-xl p-2 shadow-2xl">
              <div className="grid grid-cols-2 gap-2">
                <button
                  onClick={() => scrollToSection('#contact')}
                  className="bg-[var(--text-primary)] text-[var(--bg-primary)] rounded-xl py-3 text-[11px] font-black uppercase tracking-[0.15em] border-none cursor-pointer"
                >
                  Book Free Call
                </button>
                <button
                  onClick={() => scrollToSection('#services')}
                  className="bg-[var(--text-primary)]/5 text-[var(--text-primary)] rounded-xl py-3 text-[11px] font-black uppercase tracking-[0.15em] border border-[var(--border-primary)] cursor-pointer"
                >
                  View Services
                </button>
              </div>
            </div>
          </div>
          <WhatsAppButton />
        </>
      )}
    </div>
  );
}
