// Shared helpers + hooks
const { useState, useEffect, useRef, useLayoutEffect, useMemo, useCallback } = React;

// Intersection reveal hook
function useReveal(opts = { threshold: 0.12, once: true }) {
  const ref = useRef(null);
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const obs = new IntersectionObserver(
      ([e]) => {
        if (e.isIntersecting) {
          setVisible(true);
          if (opts.once) obs.disconnect();
        } else if (!opts.once) setVisible(false);
      },
      { threshold: opts.threshold, rootMargin: opts.rootMargin || '0px' }
    );
    obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  return [ref, visible];
}

// Count-up hook (animates from 0 to target, supporting +72, +47%, 14x, 1/10th, etc.)
function useCountUp(targetStr, { active, duration = 1400 } = {}) {
  const [val, setVal] = useState(active ? targetStr : '');
  useEffect(() => {
    if (!active) return;
    // parse: leading sign, number, suffix
    const m = targetStr.match(/^([+\-]?)([\d.,]+)(.*)$/);
    if (!m) { setVal(targetStr); return; }
    const sign = m[1];
    const numStr = m[2].replace(/,/g, '');
    const suffix = m[3];
    const target = parseFloat(numStr);
    if (isNaN(target)) { setVal(targetStr); return; }
    const start = performance.now();
    let raf;
    const step = (t) => {
      const p = Math.min(1, (t - start) / duration);
      const ease = 1 - Math.pow(1 - p, 3);
      const current = target * ease;
      const decimals = numStr.includes('.') ? numStr.split('.')[1].length : 0;
      setVal(`${sign}${current.toFixed(decimals)}${suffix}`);
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [active, targetStr, duration]);
  return val;
}

// Tilt helper (mousemove)
function useTilt({ max = 8 } = {}) {
  const ref = useRef(null);
  const [t, setT] = useState({ x: 0, y: 0 });
  const onMove = (e) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const cx = r.left + r.width / 2;
    const cy = r.top + r.height / 2;
    const dx = (e.clientX - cx) / (r.width / 2);
    const dy = (e.clientY - cy) / (r.height / 2);
    setT({ x: -dy * max, y: dx * max });
  };
  const onLeave = () => setT({ x: 0, y: 0 });
  return { ref, onMouseMove: onMove, onMouseLeave: onLeave, tilt: t };
}

// Aurora backdrop — reusable
function Aurora({ opacity = 1, dots = true }) {
  return (
    <div className="absolute" style={{ position:'absolute', inset:0, pointerEvents:'none', overflow:'hidden', opacity }}>
      <div className="aurora-1" style={{
        position:'absolute', top:'-18%', left:'-8%', width:'55%', height:'55%',
        borderRadius:'50%',
        background:`radial-gradient(ellipse, rgba(var(--accent-rgb),calc(0.18 * var(--glow))) 0%, transparent 70%)`,
        filter:'blur(60px)'
      }} />
      <div className="aurora-2" style={{
        position:'absolute', top:'8%', right:'-12%', width:'50%', height:'50%',
        borderRadius:'50%',
        background:`radial-gradient(ellipse, rgba(124,58,237,calc(0.18 * var(--glow))) 0%, transparent 70%)`,
        filter:'blur(80px)'
      }} />
      <div className="aurora-3" style={{
        position:'absolute', bottom:'-12%', left:'22%', width:'48%', height:'48%',
        borderRadius:'50%',
        background:`radial-gradient(ellipse, rgba(0,100,180,calc(0.15 * var(--glow))) 0%, transparent 70%)`,
        filter:'blur(70px)'
      }} />
      {dots && <div className="dot-grid" style={{ position:'absolute', inset:0, opacity: 0.55 }} />}
    </div>
  );
}

// Pill component
function Pill({ children, color, style }) {
  const c = color || 'var(--accent)';
  const rgbVar = color ? null : 'var(--accent-rgb)';
  return (
    <span className="pill" style={{
      color: c,
      background: color ? `${color}18` : 'var(--accent-soft)',
      borderColor: color ? `${color}44` : 'rgba(var(--accent-rgb),0.3)',
      ...style
    }}>
      {children}
    </span>
  );
}

// Section title scaffold
function SectionHeader({ eyebrow, title, sub, align = 'center', accent, children }) {
  const [ref, vis] = useReveal();
  return (
    <div ref={ref} className={`reveal ${vis?'in':''}`} style={{
      textAlign: align, marginBottom: 56,
      maxWidth: align === 'center' ? 820 : 'none',
      marginLeft: align === 'center' ? 'auto' : 0,
      marginRight: align === 'center' ? 'auto' : 0,
    }}>
      {eyebrow && <Pill>{eyebrow}</Pill>}
      <h2 className="display" style={{
        fontSize: 'clamp(36px, 4.6vw, 64px)',
        marginTop: eyebrow ? 18 : 0,
        color: 'var(--text)',
      }}>
        {title}
      </h2>
      {sub && <p style={{
        fontSize: 16, color:'var(--muted-strong)', marginTop: 18, lineHeight: 1.7,
        maxWidth: 640, marginLeft: align==='center'?'auto':0, marginRight:align==='center'?'auto':0,
      }}>{sub}</p>}
      {children}
    </div>
  );
}

Object.assign(window, {
  useReveal, useCountUp, useTilt,
  Aurora, Pill, SectionHeader
});
