// Shared helpers for the Hadid Group site kit.
const { useState, useEffect, useRef } = React;

// Fade-up on scroll into view.
function Reveal({ children, delay = 0, y = 28, as = 'div', className = '', style = {} }) {
  const ref = useRef(null);
  const instant = typeof window !== 'undefined' && window.__instantReveal;
  const [shown, setShown] = useState(instant);
  useEffect(() => {
    if (instant) return;
    const el = ref.current;
    if (!el) return;
    let done = false;
    const reveal = () => { if (!done) { done = true; setShown(true); cleanup(); } };
    // already in view on mount → show immediately
    const r0 = el.getBoundingClientRect();
    if (r0.top < window.innerHeight && r0.bottom > 0) { setShown(true); return; }
    let io = null;
    if ('IntersectionObserver' in window) {
      io = new IntersectionObserver(
        (entries) => entries.forEach((e) => { if (e.isIntersecting) reveal(); }),
        { threshold: 0.12, rootMargin: '0px 0px -6% 0px' }
      );
      io.observe(el);
    }
    const onScroll = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight * 0.92 && r.bottom > 0) reveal();
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    // safety: never leave content hidden
    const t = setTimeout(() => setShown(true), 1500);
    function cleanup() {
      if (io) io.disconnect();
      window.removeEventListener('scroll', onScroll);
      clearTimeout(t);
    }
    return cleanup;
  }, []);
  const Tag = as;
  return (
    <Tag ref={ref} className={className} style={{
      opacity: shown ? 1 : 0,
      transform: shown ? 'none' : `translateY(${y}px)`,
      transition: instant ? 'none' : `opacity 0.8s cubic-bezier(0.22,1,0.36,1) ${delay}ms, transform 0.8s cubic-bezier(0.22,1,0.36,1) ${delay}ms`,
      ...style,
    }}>
      {children}
    </Tag>
  );
}

// Smooth scroll to a section id.
function scrollToId(id) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 76, behavior: 'smooth' });
}

// Section wrapper with container + vertical rhythm.
function Section({ id, dark = false, band = false, children, style = {}, pad = true }) {
  const bg = band ? 'var(--gold-band)' : dark ? 'var(--navy-900)' : 'var(--cream)';
  return (
    <section id={id} style={{
      background: bg,
      padding: pad ? 'var(--section-y) 0' : 0,
      ...style,
    }}>
      <div style={{ maxWidth: 'var(--container)', margin: '0 auto', padding: '0 var(--gutter)' }}>
        {children}
      </div>
    </section>
  );
}

Object.assign(window, { Reveal, scrollToId, Section });
