// Pinwheel — the hero centerpiece. Animated, interactive,
// elements optionally labeled. The four petals respond to
// mouse parallax and an idle "breathing" animation.
//
// Props:
//   size      — px or string (CSS) for outer box (defaults to 100%)
//   interactive  — bool: enable mouse parallax
//   showElements — bool: show Air / Sun / Water / Earth tags
//   spin      — bool: continuous slow rotation
//   speed     — seconds per full rotation (default 80)

// petal path data from the brand mark, normalised to a 1000x1000 viewBox
// (we just use the original viewBox coordinates from the SVG file)
const PETALS = [
  {
    id: 'water',
    color: 'var(--aswe-azure-blue)',
    label: 'Water',
    // upper-left petal — azure = Water
    d: "M515.46,205.15c71.55-5.5,135.09,14.54,114.19,100.29-10.93,44.82-50.29,74.22-86.72,97.44-8.47-8.53-13.24-19.41-21.06-28.58-47.42-55.58-129.67-49.18-180.82-1.98-3.52,3.25-17.97,24.16-15.01,4.95,13.85-89.97,99.68-165.22,189.42-172.12Z",
    // direction the petal points outward (for parallax)
    vec: [-0.4, -0.9],
  },
  {
    id: 'sun',
    color: 'var(--aswe-bright-orange)',
    label: 'Sun',
    // upper-right petal
    d: "M651.93,232.36c7.03-1.44,49.31,45.71,55.4,53.79,34.93,46.38,54.47,106.91,44.36,165.16-12.43,71.64-100.76,92.32-157.04,56.74-20.93-13.24-44.44-48.21-38.65-73.71,3.95-17.4,50.69-43.02,65.1-58.02,26.98-28.08,45.57-77.78,36.85-116.26-1.61-7.12-6.63-15.39-8.15-21.69-.62-2.59-.66-5.44,2.13-6.01Z",
    vec: [0.9, -0.4],
  },
  {
    id: 'air',
    color: 'var(--aswe-cool-gray)',
    label: 'Air',
    // lower-left petal — gray = Air
    d: "M482.08,625.59c-.05,3.28-8.37,3.66-10.41,3.47-63.15-5.92-139.13-99.95-144.44-161.41-7.63-88.27,112.81-146.01,174.78-75.48,4.65,5.29,18.53,21.35,14.06,27.92-3.03,4.45-22.03,16.11-28.04,21.75-39.67,37.27-54.52,93.72-33.45,144.72,5.01,12.13,15.93,33.57,27.51,39.03Z",
    vec: [-0.9, 0.4],
  },
  {
    id: 'earth',
    color: 'var(--aswe-forest-moss-green)',
    label: 'Earth',
    // lower-right petal
    d: "M523.29,447.13c1.85-.46,2.83-.32,4.5.57,3.19,1.7,10.62,30.38,14.12,37.62,25.54,52.71,87.7,73.23,142.81,61.87,8.19-1.69,32.45-13.01,34.79-12.97,2.61.04,5.44,2.22,4.82,4.89-.44,1.92-22.39,26.47-25.73,29.9-35.24,36.18-95.55,71.66-147.76,66.23-83-8.64-103.82-126.06-43.98-176.55,2.92-2.46,13.72-10.91,16.41-11.58Z",
    vec: [0.4, 0.9],
  },
];

function Pinwheel({
  interactive = false,
  showElements = false,
  spin = true,
  speed = 80,
  rings = true,
  assemble = false,
}) {
  const stageRef = useRef(null);
  const [mouse, setMouse] = useState({ x: 0, y: 0 });
  const [revealed, setRevealed] = useState(false);
  // when assemble is true, hold spin off until petals are in place
  const [assembled, setAssembled] = useState(!assemble);

  useEffect(() => {
    if (!assemble) { setAssembled(true); return; }
    setAssembled(false);
    // last petal finishes at ~550ms delay + 700ms anim = ~1.25s.
    const t = setTimeout(() => setAssembled(true), 1300);
    return () => clearTimeout(t);
  }, [assemble]);

  // Reveal element labels once visible (intersection observer)
  useEffect(() => {
    if (!showElements) return;
    const el = stageRef.current;
    if (!el) return;
    // Safety fallback in case IO never fires
    const fallback = setTimeout(() => setRevealed(true), 400);
    let io;
    if (typeof IntersectionObserver !== 'undefined') {
      io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) setRevealed(true);
          });
        },
        { threshold: 0.3 }
      );
      io.observe(el);
    }
    return () => {
      clearTimeout(fallback);
      if (io) io.disconnect();
    };
  }, [showElements]);

  // Mouse parallax — petals subtly drift toward cursor
  useEffect(() => {
    if (!interactive) return;
    const el = stageRef.current;
    if (!el) return;
    let raf = 0;
    const onMove = (e) => {
      const rect = el.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const nx = (e.clientX - cx) / rect.width; // -0.5..0.5
      const ny = (e.clientY - cy) / rect.height;
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => setMouse({ x: nx, y: ny }));
    };
    const onLeave = () => setMouse({ x: 0, y: 0 });
    window.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => {
      window.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
      cancelAnimationFrame(raf);
    };
  }, [interactive]);

  const rotation = spin ? { animation: `pinwheelSpin ${speed}s linear infinite` } : {};

  return (
    <div
      ref={stageRef}
      className={`pinwheel-stage ${revealed ? 'revealed' : ''} ${assemble && !assembled ? 'is-assembling' : ''}`}
    >
      {rings && (
        <React.Fragment>
          <div className="ring" />
          <div className="ring r2" />
          <div className="ring r3" />
        </React.Fragment>
      )}

      <svg
        className="pinwheel-svg"
        viewBox="250 180 580 480"
        style={rotation}
      >
        <g>
          {PETALS.map((p, i) => {
            const offset = interactive
              ? {
                  // each petal drifts a little toward the mouse + a small breathing
                  transform: `translate(${mouse.x * 14 + p.vec[0] * 2}px, ${mouse.y * 14 + p.vec[1] * 2}px)`,
                }
              : {};
            return (
              <path
                key={p.id}
                className="petal"
                d={p.d}
                fill={p.color}
                style={offset}
              />
            );
          })}
        </g>
      </svg>

      {showElements && (
        <React.Fragment>
          <div className="element-tag water">
            <span className="swatch" style={{ background: 'var(--aswe-azure-blue)' }} />
            Water
          </div>
          <div className="element-tag sun">
            <span className="swatch" style={{ background: 'var(--aswe-bright-orange)' }} />
            Sun
          </div>
          <div className="element-tag air">
            <span className="swatch" style={{ background: 'var(--aswe-cool-gray)' }} />
            Air
          </div>
          <div className="element-tag earth">
            <span className="swatch" style={{ background: 'var(--aswe-forest-moss-green)' }} />
            Earth
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// Add the spin keyframes to the document once
(function injectKeyframes() {
  if (document.getElementById('__pinwheel-kf')) return;
  const style = document.createElement('style');
  style.id = '__pinwheel-kf';
  style.textContent = `
    @keyframes pinwheelSpin { to { transform: rotate(360deg); } }
    @keyframes breathing {
      0%, 100% { transform: scale(1); }
      50% { transform: scale(1.015); }
    }
  `;
  document.head.appendChild(style);
})();

Object.assign(window, { Pinwheel, PETALS });
