const { useState, useEffect, useRef } = React;

function useFadeIn() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Safety: ensure content reveals even if IO never fires (background tabs, etc.)
    const fallback = setTimeout(() => el.classList.add('visible'), 1500);
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { el.classList.add('visible'); io.unobserve(el); clearTimeout(fallback); }
      });
    }, { threshold: 0.12, rootMargin: '-40px 0px' });
    io.observe(el);
    return () => { io.disconnect(); clearTimeout(fallback); };
  }, []);
  return ref;
}

function FadeIn({ children, delay = 0, className = '', style = {}, ...rest }) {
  const ref = useFadeIn();
  return (
    <div ref={ref} className={`fade-in ${className}`} style={{ transitionDelay: `${delay}ms`, ...style }} {...rest}>
      {children}
    </div>
  );
}

function useCountUp(target, duration = 1400) {
  const [value, setValue] = useState(0);
  const ref = useRef(null);
  const started = useRef(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !started.current) {
          started.current = true;
          const start = performance.now();
          const step = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setValue(target * eased);
            if (p < 1) requestAnimationFrame(step);
            else setValue(target);
          };
          requestAnimationFrame(step);
        }
      });
    }, { threshold: 0.3 });
    io.observe(el);
    return () => io.disconnect();
  }, [target, duration]);
  return [value, ref];
}

function Section({ id, children, className = '', style }) {
  return (
    <section id={id} className={`section ${className}`} style={style}>
      <div className="container">{children}</div>
    </section>
  );
}

function Eyebrow({ children }) {
  return (
    <div className="eyebrow">
      <span className="eyebrow-dot"></span>
      <span>{children}</span>
    </div>
  );
}

// Safety net: if CSS animations don't progress (paused iframe), force-reveal hero-rise elements
if (typeof window !== 'undefined') {
  setTimeout(() => {
    document.querySelectorAll('.hero-rise').forEach((el) => {
      const anims = el.getAnimations ? el.getAnimations() : [];
      const stuck = anims.length && anims.every(a => (a.currentTime || 0) < 50);
      if (stuck || anims.length === 0) {
        el.style.opacity = '1';
        el.style.transform = 'none';
      }
    });
  }, 1800);
}

Object.assign(window, { useFadeIn, FadeIn, useCountUp, Section, Eyebrow });
