import React, { createContext, useContext, ReactNode, useState, useEffect, useRef } from 'react';

interface ScrollContextType {
  scrollToSection: (sectionId: string) => void;
  isStuck: boolean;
  scrollContainerRef: React.RefObject<HTMLElement | null>;
}

const ScrollContext = createContext<ScrollContextType | undefined>(undefined);

export const useScroll = () => {
  const context = useContext(ScrollContext);
  if (!context) {
    throw new Error('useScroll must be used within a ScrollProvider');
  }
  return context;
};

interface ScrollProviderProps {
  children: ReactNode;
}

export const ScrollProvider: React.FC<ScrollProviderProps> = ({ children }) => {
  const [isStuck, setIsStuck] = useState(false);
  const scrollContainerRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    const handleScroll = (e: Event) => {
      const scrollTop = e.target instanceof Element ? e.target.scrollTop : 0;
      const headerHeight = 100; // Adjust as needed
      setIsStuck(scrollTop > headerHeight);
    };

    // Try to find the scroll container
    const findScrollContainer = () => {
      // First try to find the live dashboard scroll container
      const container = document.getElementById('dashboard-scroll-container');
      if (container) {
        scrollContainerRef.current = container;
        return container;
      }
      
      // Fallback to the MainLayout scroll container
      const mainLayoutContainer = document.querySelector('.overflow-auto.h-\\[calc\\(100vh-3\\.5rem\\)\\]');
      if (mainLayoutContainer) {
        scrollContainerRef.current = mainLayoutContainer as HTMLElement;
        return mainLayoutContainer;
      }
      
      // Final fallback to window
      return null;
    };

    const container = findScrollContainer();
    
    if (container) {
      container.addEventListener('scroll', handleScroll, { passive: true });
      return () => container.removeEventListener('scroll', handleScroll);
    } else {
      // Fallback to window scroll
      const windowScroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const headerHeight = 100;
        setIsStuck(scrollTop > headerHeight);
      };
      window.addEventListener('scroll', windowScroll, { passive: true });
      return () => window.removeEventListener('scroll', windowScroll);
    }
  }, []);

  const scrollToSection = (sectionId: string) => {
    const element = document.getElementById(sectionId);
    if (element && scrollContainerRef.current) {
      const container = scrollContainerRef.current;
      const elementTop = element.offsetTop;
      const containerTop = container.offsetTop;
      const scrollTop = elementTop - containerTop - 80; // 80px offset for header
      
      container.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      });
    } else if (element) {
      // Fallback to window scrolling
      element.scrollIntoView({ 
        behavior: 'smooth',
        block: 'start'
      });
    }
  };

  return (
    <ScrollContext.Provider value={{ scrollToSection, isStuck, scrollContainerRef }}>
      {children}
    </ScrollContext.Provider>
  );
};