import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, useLocation } from 'react-router-dom';
import Lenis from '@studio-freight/lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import BackToTop from './components/BackToTop';
import HomePage from './src/pages/HomePage';
import AboutPage from './src/pages/AboutPage';
import ServicesPage from './src/pages/ServicesPage';
import BlogPage from './src/pages/BlogPage';
import ContactPage from './src/pages/ContactPage';

// Register GSAP plugins globally
gsap.registerPlugin(ScrollTrigger, ScrollToPlugin);

// Grain Overlay Component
const GrainOverlay = () => (
  <div className="fixed inset-0 w-full h-full pointer-events-none z-50 opacity-50 dark:opacity-100 bg-grain mix-blend-overlay"></div>
);

const AppContent: React.FC = () => {
  const location = useLocation();

  useEffect(() => {
    // Initialize Lenis for smooth scrolling
    const lenis = new Lenis({
      duration: 1.2,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      direction: 'vertical',
      gestureDirection: 'vertical',
      smooth: true,
      smoothTouch: false,
      touchMultiplier: 2,
    } as any);

    // Synchronize Lenis with GSAP ScrollTrigger
    lenis.on('scroll', ScrollTrigger.update);

    const ticker = (time: number) => {
      lenis.raf(time * 1000);
    };

    // Use GSAP ticker for smoother animation loop integration
    gsap.ticker.add(ticker);

    // Disable lag smoothing to prevent jumps
    gsap.ticker.lagSmoothing(0);

    // Reset scroll on route change
    lenis.scrollTo(0, { immediate: true });

    return () => {
      gsap.ticker.remove(ticker);
      lenis.destroy();
    };
  }, [location.pathname]);

  return (
    <div className="relative w-full min-h-screen bg-background-light dark:bg-background-dark">
      <GrainOverlay />
      <Navbar />
      <main>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/about" element={<AboutPage />} />
          <Route path="/services" element={<ServicesPage />} />
          <Route path="/blog" element={<BlogPage />} />
          <Route path="/contact" element={<ContactPage />} />
        </Routes>
      </main>
      <Footer />
      <BackToTop />
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <AppContent />
    </Router>
  );
}