"use client";

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

export function useSectionObserver(sectionIds: string[]) {
  const [visibleSection, setVisibleSection] = useState<string>("");
  const refs = useRef<Map<string, HTMLElement>>(new Map());

  const setRef = useCallback(
    (id: string) => (el: HTMLElement | null) => {
      if (el) refs.current.set(id, el);
    },
    []
  );

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setVisibleSection(entry.target.id);
          }
        });
      },
      { threshold: 0.4 }
    );

    refs.current.forEach((el) => observer.observe(el));

    return () => observer.disconnect();
  }, []);

  return { visibleSection, setRef };
}

export function useCounter(target: number, suffix = "", duration = 40) {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLDivElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && !hasAnimated.current) {
            hasAnimated.current = true;
            let current = 0;
            const step = Math.max(1, Math.floor(target / 30));
            const timer = setInterval(() => {
              current += step;
              if (current >= target) {
                current = target;
                clearInterval(timer);
              }
              setCount(current);
            }, duration);
          }
        });
      },
      { threshold: 0.5 }
    );

    observer.observe(el);
    return () => observer.disconnect();
  }, [target, duration]);

  return { count, ref, display: `${count}${suffix}` };
}

export function useParallax() {
  const ticking = useRef(false);
  const panelRefs = useRef<Map<string, HTMLElement>>(new Map());

  const setPanelRef = useCallback(
    (id: string) => (el: HTMLElement | null) => {
      if (el) panelRefs.current.set(id, el);
    },
    []
  );

  useEffect(() => {
    const handleScroll = () => {
      if (!ticking.current) {
        requestAnimationFrame(() => {
          panelRefs.current.forEach((el) => {
            const rect = el.getBoundingClientRect();
            if (rect.top < window.innerHeight && rect.bottom > 0) {
              const progress = rect.top / window.innerHeight;
              const bg = el.querySelector(
                "[data-parallax-bg]"
              ) as HTMLElement;
              if (bg) {
                bg.style.transform = `scale(${1.08 + progress * 0.04})`;
              }
            }
          });
          ticking.current = false;
        });
        ticking.current = true;
      }
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return { setPanelRef };
}
