import { useState, useEffect, useRef } from "react";

export const useScrollSnap = (sectionIds) => {
  const [activeSection, setActiveSection] = useState(sectionIds[0] || "");
  const containerRef = useRef(null);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    const sections = sectionIds.map(id => document.getElementById(id)).filter(Boolean);

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter(e => e.isIntersecting)
          .sort((a, b) => b.intersectionRatio - a.intersectionRatio)[0];
        
        if (visible) {
          setActiveSection(visible.target.id);
        }
      },
      { threshold: [0.55, 0.7] }
    );

    sections.forEach(section => observer.observe(section));

    return () => {
      sections.forEach(section => observer.unobserve(section));
    };
  }, [sectionIds]);

  const scrollToSection = (sectionId) => {
    const element = document.getElementById(sectionId);
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };

  return { activeSection, scrollToSection, containerRef };
};
