import React, { lazy, useEffect, useState } from 'react';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import Navbar from './components/Navbar';
import Hero from './components/Hero';
import LazyComponent from './components/LazyComponent';
import { Toaster } from './components/ui/sonner';
import { useClarity, useClarityTracking } from './hooks/useClarity';
import SmoothScrollProvider from './components/SmoothScrollProvider';
import ScrollProgressBar from './components/ScrollProgressBar';

const About = lazy(() => import('./components/About'));
const Services = lazy(() => import('./components/Services'));
const Projects = lazy(() => import('./components/Projects'));
const Testimonials = lazy(() => import('./components/Testimonials'));
const HowItWorks = lazy(() => import('./components/HowItWorks'));
const Skills = lazy(() => import('./components/Skills'));
const Experience = lazy(() => import('./components/Experience'));
const Contact = lazy(() => import('./components/Contact'));
const Footer = lazy(() => import('./components/Footer'));

const App: React.FC = () => {
  const { trackPageView, setUserProperties } = useClarity();
  const { trackScrollDepth, trackTimeOnPage } = useClarityTracking();
  const [showProgressBar, setShowProgressBar] = useState(false);

  useEffect(() => {
    const onHashChange = () => { setTimeout(() => ScrollTrigger.refresh(), 150); };
    window.addEventListener('hashchange', onHashChange);
    return () => window.removeEventListener('hashchange', onHashChange);
  }, []);

  useEffect(() => {
    const id = requestAnimationFrame(() => {
      const callback = () => setShowProgressBar(true);
      if (typeof requestIdleCallback !== 'undefined') {
        requestIdleCallback(callback, { timeout: 500 });
      } else {
        setTimeout(callback, 300);
      }
    });
    return () => cancelAnimationFrame(id);
  }, []);

  useEffect(() => {
    let cleanup: (() => void) | undefined;
    const run = () => {
      setUserProperties({ user_type: 'portfolio_visitor', page_type: 'portfolio', site_version: '2.0.0' });
      trackPageView('home');

      let maxScrollDepth = 0;
      let scrollTick = false;
      const handleScroll = () => {
        if (scrollTick) return;
        scrollTick = true;
        requestAnimationFrame(() => {
          scrollTick = false;
          const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
          const documentHeight = document.documentElement.scrollHeight - window.innerHeight;
          const scrollDepth = documentHeight > 0 ? Math.round((scrollTop / documentHeight) * 100) : 0;
          if (scrollDepth > maxScrollDepth) {
            maxScrollDepth = scrollDepth;
            if (scrollDepth >= 25 && scrollDepth % 25 === 0) trackScrollDepth(scrollDepth);
          }
        });
      };

      const startTime = Date.now();
      const trackTime = () => {
        const timeSpent = Math.round((Date.now() - startTime) / 1000);
        if (timeSpent > 0 && timeSpent % 30 === 0) trackTimeOnPage(timeSpent);
      };

      window.addEventListener('scroll', handleScroll, { passive: true });
      const timeInterval = setInterval(trackTime, 30000);
      return () => { window.removeEventListener('scroll', handleScroll); clearInterval(timeInterval); };
    };

    const schedule = () => { cleanup = run(); };
    if (typeof requestIdleCallback !== 'undefined') {
      const id = requestIdleCallback(schedule, { timeout: 2000 });
      return () => { cancelIdleCallback(id); cleanup?.(); };
    }
    const t = setTimeout(schedule, 500);
    return () => { clearTimeout(t); cleanup?.(); };
  }, [trackPageView, setUserProperties, trackScrollDepth, trackTimeOnPage]);

  return (
    <SmoothScrollProvider>
      <div className="App" style={{ background: '#ffffff' }}>

        {showProgressBar && <ScrollProgressBar />}
        <Navbar />

        <main>
          {/* 1. Hero: High-impact value prop + social proof */}
          <Hero />

          {/* 2. The "Why": Problem / Solution */}
          <LazyComponent minHeight="600px" className="section-padding">
            <About />
          </LazyComponent>

          {/* 3. Services */}
          <LazyComponent minHeight="700px" className="section-padding">
            <Services />
          </LazyComponent>

          {/* 4. The Showcase: Bento Grid Projects */}
          <LazyComponent minHeight="1200px" className="section-padding">
            <Projects />
          </LazyComponent>

          {/* 5. Social Proof: Testimonials */}
          <LazyComponent minHeight="600px" className="section-padding">
            <Testimonials />
          </LazyComponent>

          {/* 6. The Process: Audit → Strategy → Build → Launch → Grow */}
          <LazyComponent minHeight="500px" className="section-padding">
            <HowItWorks />
          </LazyComponent>

          {/* 6. Tech Stack: Skills Bento Grid */}
          <LazyComponent minHeight="800px" className="section-padding">
            <Skills />
          </LazyComponent>

          {/* 7. Career: Experience Timeline */}
          <LazyComponent minHeight="600px" className="section-padding">
            <Experience />
          </LazyComponent>

          {/* 8. The Close: High-Conversion Contact */}
          <LazyComponent minHeight="600px" className="section-padding">
            <Contact />
          </LazyComponent>
        </main>

        <LazyComponent minHeight="250px">
          <Footer />
        </LazyComponent>

        <Toaster />
      </div>
    </SmoothScrollProvider>
  );
};

export default App;
