// ────────────────────────────────────────────────────────────────────────
//  flow.jsx — shared "continuous flow" layer for the post-reveal sections.
//
//  Exports:
//   • window.useScrollProgress(ref) → live -1..1 as the element travels the
//     viewport (0 = centred). Drives scroll-linked parallax so content MOVES
//     with the scroll instead of snapping in like a slide.
//   • window.useParallax(ref, px)   → ready-made translateY string.
//   • window.FlowAmbience           → one page-wide drifting petal/gold-dust
//     atmosphere, fixed over every section so the whole journey feels like a
//     single continuous scene rather than separate screens.
//   • window.useReducedMotionFlow   → shared reduced-motion flag.
// ────────────────────────────────────────────────────────────────────────
(function () {
  const { useState, useEffect, useRef } = React;

  function useReducedMotionFlow() {
    const [r, setR] = useState(false);
    useEffect(() => {
      const m = window.matchMedia('(prefers-reduced-motion: reduce)');
      const on = () => setR(!!m.matches);
      on();
      m.addEventListener ? m.addEventListener('change', on) : m.addListener(on);
      return () => {m.removeEventListener ? m.removeEventListener('change', on) : m.removeListener(on);};
    }, []);
    return r;
  }
  window.useReducedMotionFlow = useReducedMotionFlow;

  // -1 (just below viewport) → 0 (centred) → 1 (just above viewport)
  function useScrollProgress(ref) {
    const [p, setP] = useState(0);
    const reduced = useReducedMotionFlow();
    useEffect(() => {
      if (reduced) {setP(0);return;}
      let raf = 0;
      const measure = () => {
        raf = 0;
        const el = ref && ref.current;
        if (!el) return;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight || 1;
        const centre = r.top + r.height / 2;
        const v = 1 - 2 * (centre / vh);
        setP(Math.max(-1.4, Math.min(1.4, v)));
      };
      const onScroll = () => {if (!raf) raf = requestAnimationFrame(measure);};
      measure();
      window.addEventListener('scroll', onScroll, { passive: true });
      window.addEventListener('resize', onScroll);
      return () => {
        if (raf) cancelAnimationFrame(raf);
        window.removeEventListener('scroll', onScroll);
        window.removeEventListener('resize', onScroll);
      };
    }, [ref, reduced]);
    return p;
  }
  window.useScrollProgress = useScrollProgress;

  function useParallax(ref, px = 24) {
    const p = useScrollProgress(ref);
    return `translate3d(0, ${(-p * px).toFixed(2)}px, 0)`;
  }
  window.useParallax = useParallax;

  // ── one continuous ambient atmosphere across the whole page ────────────
  const TONES = [
  ['#e07a1f', '#f6b64a'], // marigold
  ['#b5384a', '#e0707f'], // crimson → rose
  ['#c25d86', '#efb4cb'], // magenta blush
  ['#d98a8f', '#f6dcd6'], // soft blush
  ['#a8842f', '#f0d28a'], // antique gold
  ['#cf5a2a', '#f4a35c']];// saffron

  const rnd = (i, salt) => {
    const x = Math.sin((i + 1) * 12.9898 + salt * 78.233) * 43758.5453;
    return x - Math.floor(x);
  };

  function FlowAmbience({ count }) {
    const reduced = useReducedMotionFlow();
    const [n, setN] = useState(count || 0);

    useEffect(() => {
      if (count) return;
      const set = () => setN(window.innerWidth < 640 ? 9 : 15);
      set();
      window.addEventListener('resize', set);
      return () => window.removeEventListener('resize', set);
    }, [count]);

    if (reduced || !n) return null;

    return (
      <div aria-hidden="true" style={{
        position: 'fixed', inset: 0, zIndex: 40, pointerEvents: 'none', overflow: 'hidden'
      }}>
        {Array.from({ length: n }, (_, i) => {
          const left = rnd(i, 1) * 100;
          const size = 9 + rnd(i, 2) * 13;
          const dur = 17 + rnd(i, 3) * 16;
          const delay = -rnd(i, 4) * dur;
          const drift = (rnd(i, 5) - 0.5) * 180;
          const spin = 200 + rnd(i, 6) * 420;
          const kind = rnd(i, 7);
          const [edge, core] = TONES[Math.floor(rnd(i, 8) * TONES.length)];
          const common = {
            position: 'absolute', left: `${left}%`, top: 0,
            '--fdrift': `${drift}px`, '--fspin': `${spin}deg`,
            animation: `flowdrift ${dur}s linear ${delay}s infinite`
          };
          if (kind > 0.78) {
            return <span key={i} style={{ ...common, width: 3, height: 3, borderRadius: '50%',
              background: '#f0cf82', boxShadow: '0 0 6px rgba(240,207,130,0.9)', opacity: 0.7 }} />;
          }
          return (
            <svg key={i} width={size} height={size * 1.28} viewBox="0 0 20 26"
              style={{ ...common, opacity: 0.62, filter: 'drop-shadow(0 1px 2px rgba(60,24,10,0.18))' }}>
              <defs><radialGradient id={`fa${i}`} cx="0.5" cy="0.35" r="0.78">
                <stop offset="0" stopColor={core} /><stop offset="1" stopColor={edge} />
              </radialGradient></defs>
              <path d="M10 0 C 18 8 18 18 10 26 C 2 18 2 8 10 0 Z" fill={`url(#fa${i})`} />
            </svg>);

        })}
        <style>{`
          @keyframes flowdrift {
            0%   { transform: translate3d(0,-8vh,0) rotate(0deg); }
            100% { transform: translate3d(var(--fdrift,40px), 112vh, 0) rotate(var(--fspin,300deg)); }
          }
        `}</style>
      </div>);

  }
  window.FlowAmbience = FlowAmbience;
})();
