'use client';

import React, { useEffect, useState, createContext, useContext } from 'react';
import Lenis from '@studio-freight/lenis';
import { usePathname } from 'next/navigation';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

interface SmoothScrollProps {
    children: React.ReactNode;
}

const LenisContext = createContext<Lenis | null>(null);

export const useLenis = () => useContext(LenisContext);

export const SmoothScroll: React.FC<SmoothScrollProps> = ({ children }) => {
    const [lenis, setLenis] = useState<Lenis | null>(null);
    const pathname = usePathname();

    // Initialise Lenis once and integrate with GSAP ScrollTrigger
    useEffect(() => {
        const lenisInstance = new Lenis({
            duration: 1.0,
            easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
            smoothWheel: true,
            wheelMultiplier: 1,
            touchMultiplier: 1.5,
        });

        setLenis(lenisInstance);

        // Integrate Lenis with GSAP ScrollTrigger
        lenisInstance.on('scroll', ScrollTrigger.update);

        function raf(time: number) {
            lenisInstance.raf(time);
            requestAnimationFrame(raf);
        }

        requestAnimationFrame(raf);

        return () => {
            lenisInstance.destroy();
        };
    }, []);

    // Scroll on navigation:
    // - if there's a hash, scroll to that element
    // - otherwise scroll to top
    useEffect(() => {
        const hashId = window.location.hash?.replace('#', '');

        // If there's a hash, prefer scrolling to the element (after layout paints).
        if (hashId) {
            window.setTimeout(() => {
                const target = document.getElementById(hashId);
                if (target) {
                    if (lenis) {
                        lenis.scrollTo(target, { offset: -80 });
                    } else {
                        target.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }
            }, 50);
            return;
        }

        if (lenis) {
            lenis.scrollTo(0, { immediate: true });
        } else {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }, [pathname, lenis]);

    return (
        <LenisContext.Provider value={lenis}>
            <div className="w-full">{children}</div>
        </LenisContext.Provider>
    );
};
