// FlowArt scroll effect — adapted from TypeScript for CDN/vanilla-React usage.
// Requires GSAP + ScrollTrigger loaded globally before this script.

gsap.registerPlugin(ScrollTrigger);

function FlowSection({ children, style, ariaLabel }) {
  return (
    <section
      data-flow-section
      aria-label={ariaLabel}
      style={{ position: 'relative', minHeight: '100vh', width: '100%', overflow: 'hidden' }}
    >
      <div
        data-flow-inner
        className="flow-art-container"
        style={{
          position: 'relative',
          minHeight: '100vh',
          width: '100%',
          transformOrigin: 'bottom left',
          willChange: 'transform',
          ...style,
        }}
      >
        {children}
      </div>
    </section>
  );
}

function FlowArt({ children, ariaLabel }) {
  const containerRef = React.useRef(null);
  const [reducedMotion, setReducedMotion] = React.useState(false);
  const childCount = React.Children.count(children);

  React.useEffect(() => {
    const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
    const update = () => setReducedMotion(mq.matches);
    update();
    mq.addEventListener('change', update);
    return () => mq.removeEventListener('change', update);
  }, []);

  React.useEffect(() => {
    if (!containerRef.current || reducedMotion) return;

    const sections = Array.from(
      containerRef.current.querySelectorAll('[data-flow-section]')
    );
    if (sections.length === 0) return;

    const triggers = [];

    sections.forEach((section, i) => {
      gsap.set(section, { zIndex: i + 1 });

      const inner = section.querySelector('.flow-art-container');
      if (!inner) return;

      if (i > 0) {
        gsap.set(inner, { rotation: 30, transformOrigin: 'bottom left' });
        const tween = gsap.to(inner, {
          rotation: 0,
          ease: 'none',
          scrollTrigger: {
            trigger: section,
            start: 'top bottom',
            end: 'top 25%',
            scrub: true,
          },
        });
        if (tween.scrollTrigger) triggers.push(tween.scrollTrigger);
      }

      if (i < sections.length - 1) {
        triggers.push(
          ScrollTrigger.create({
            trigger: section,
            start: 'bottom bottom',
            end: 'bottom top',
            pin: true,
            pinSpacing: false,
          })
        );
      }
    });

    ScrollTrigger.refresh();

    return () => {
      triggers.forEach((t) => t.kill());
    };
  }, [reducedMotion, childCount]);

  return (
    <main
      ref={containerRef}
      aria-label={ariaLabel || 'Story scroll'}
      style={{ width: '100%', overflowX: 'hidden' }}
    >
      {children}
    </main>
  );
}

window.FlowSection = FlowSection;
window.FlowArt = FlowArt;
