/* global React, gsap */
/* eslint-disable */

// Watercolor pink butterflies + flowers + atmosphere
// Animations driven entirely by GSAP (ScrollTrigger + timelines)

const { useEffect, useMemo, useRef } = React;

/* ============================================================
   Watercolor butterfly SVG
   ============================================================ */
function ButterflySVG({ variant = 1, size = 90 }) {
  const id = useMemo(() => "bf" + Math.random().toString(36).slice(2, 8), []);
  const palettes = [
    { a: "#ffd2e0", b: "#ff9bbf", c: "#e25b8a", d: "#7a2d4a" },
    { a: "#ffe1ec", b: "#f8a7c4", c: "#d65a85", d: "#4a1d33" },
    { a: "#fbc6da", b: "#e88aae", c: "#b53d6a", d: "#3a1326" },
    { a: "#ffeaf2", b: "#f4b0cb", c: "#cf6f95", d: "#5a223c" },
    { a: "#f7b8d2", b: "#e87aad", c: "#a93668", d: "#2c0f1d" },
  ];
  const p = palettes[(variant - 1) % palettes.length];

  return (
    <svg viewBox="0 0 200 180" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <defs>
        <radialGradient id={id + "wingA"} cx="50%" cy="50%" r="60%">
          <stop offset="0%"   stopColor={p.a} stopOpacity="0.95" />
          <stop offset="55%"  stopColor={p.b} stopOpacity="0.95" />
          <stop offset="100%" stopColor={p.c} stopOpacity="0.9" />
        </radialGradient>
        <radialGradient id={id + "wingB"} cx="50%" cy="60%" r="65%">
          <stop offset="0%"   stopColor={p.a} stopOpacity="0.85" />
          <stop offset="60%"  stopColor={p.b} stopOpacity="0.95" />
          <stop offset="100%" stopColor={p.c} stopOpacity="0.95" />
        </radialGradient>
        <filter id={id + "soft"}><feGaussianBlur stdDeviation="0.4" /></filter>
      </defs>

      {/* body */}
      <ellipse cx="100" cy="92" rx="3.5" ry="42" fill={p.d} />
      <ellipse cx="100" cy="52" rx="4.5" ry="6"  fill={p.d} />
      {/* antennae */}
      <path d={`M100 50 Q88 32 82 22`} stroke={p.d} strokeWidth="1.2" fill="none" />
      <circle cx="81" cy="21" r="2.5" fill={p.c} />
      <path d={`M100 50 Q112 32 118 22`} stroke={p.d} strokeWidth="1.2" fill="none" />
      <circle cx="119" cy="21" r="2.5" fill={p.c} />

      {/* upper wings */}
      <path className="wings" d="M100 72 Q62 42 36 48 Q14 54 18 76 Q24 100 58 98 Q82 96 100 88 Z"
        fill={`url(#${id}wingA)`} filter={`url(#${id}soft)`} />
      <path className="wings" d="M100 72 Q138 42 164 48 Q186 54 182 76 Q176 100 142 98 Q118 96 100 88 Z"
        fill={`url(#${id}wingA)`} filter={`url(#${id}soft)`} />

      {/* lower wings */}
      <path className="wings" d="M100 88 Q68 92 44 110 Q28 124 38 140 Q50 154 72 148 Q92 142 100 122 Z"
        fill={`url(#${id}wingB)`} filter={`url(#${id}soft)`} opacity="0.92" />
      <path className="wings" d="M100 88 Q132 92 156 110 Q172 124 162 140 Q150 154 128 148 Q108 142 100 122 Z"
        fill={`url(#${id}wingB)`} filter={`url(#${id}soft)`} opacity="0.92" />

      {/* wing details */}
      <path className="wings" d="M100 80 Q74 64 56 68 Q42 72 48 84 Q56 96 78 94 Q94 92 100 86 Z"
        fill={p.a} opacity="0.35" filter={`url(#${id}soft)`} />
      <path className="wings" d="M100 80 Q126 64 144 68 Q158 72 152 84 Q144 96 122 94 Q106 92 100 86 Z"
        fill={p.a} opacity="0.35" filter={`url(#${id}soft)`} />

      {/* dots */}
      {[{cx:66,cy:74},{cx:134,cy:74},{cx:60,cy:108},{cx:140,cy:108}].map((d,i) => (
        <circle key={i} className="wings" cx={d.cx} cy={d.cy} r="3.5"
          fill={p.c} opacity="0.5" filter={`url(#${id}soft)`} />
      ))}
    </svg>
  );
}

/* ============================================================
   Watercolor flower SVG
   ============================================================ */
function FlowerSVG({ variant = 1 }) {
  const id = useMemo(() => "fl" + Math.random().toString(36).slice(2, 8), []);
  const configs = [
    { petals: 6, outerR: 42, innerR: 22, pColor: "#ffd2e0", cColor: "#ff9bbf", stemColor: "#c87890" },
    { petals: 5, outerR: 38, innerR: 20, pColor: "#ffe0ec", cColor: "#f8b4cc", stemColor: "#d4809a" },
    { petals: 8, outerR: 35, innerR: 18, pColor: "#ffcad8", cColor: "#f09ab8", stemColor: "#b8607a" },
  ];
  const c = configs[(variant - 1) % configs.length];
  const petals = Array.from({ length: c.petals }, (_, i) => {
    const angle = (i / c.petals) * Math.PI * 2;
    const cx = Math.cos(angle) * c.innerR * 1.6;
    const cy = Math.sin(angle) * c.innerR * 1.6;
    return { cx, cy, angle };
  });

  return (
    <svg viewBox="-60 -80 120 140" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <defs>
        <radialGradient id={id + "p"} cx="50%" cy="50%" r="60%">
          <stop offset="0%" stopColor={c.pColor} stopOpacity="0.95" />
          <stop offset="100%" stopColor={c.cColor} stopOpacity="0.85" />
        </radialGradient>
        <radialGradient id={id + "c"} cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#fff5f8" />
          <stop offset="100%" stopColor={c.cColor} />
        </radialGradient>
        <filter id={id + "f"}><feGaussianBlur stdDeviation="0.6" /></filter>
      </defs>
      {/* stem */}
      <path d="M0 20 Q4 40 2 60" stroke={c.stemColor} strokeWidth="2.5" fill="none"
        strokeLinecap="round" opacity="0.7" />
      {/* leaf */}
      <path d="M2 44 Q14 38 18 48 Q12 52 2 48 Z" fill={c.stemColor} opacity="0.5" />
      {/* petals */}
      {petals.map((petal, i) => (
        <ellipse key={i}
          cx={petal.cx} cy={petal.cy}
          rx={c.outerR * 0.38} ry={c.outerR * 0.6}
          fill={`url(#${id}p)`}
          filter={`url(#${id}f)`}
          opacity="0.88"
          transform={`rotate(${(petal.angle * 180) / Math.PI} ${petal.cx} ${petal.cy})`}
        />
      ))}
      {/* center */}
      <circle cx="0" cy="0" r={c.innerR * 0.55} fill={`url(#${id}c)`}
        filter={`url(#${id}f)`} />
      <circle cx="0" cy="0" r={c.innerR * 0.28} fill={c.cColor} opacity="0.7" />
    </svg>
  );
}

/* ============================================================
   Static butterflies — entrance with GSAP, gentle float loop
   ============================================================ */
function StaticButterflies({ items }) {
  const refs = useRef([]);

  useEffect(() => {
    if (typeof gsap === "undefined") return;
    refs.current.forEach((el, i) => {
      if (!el) return;
      const item = items[i];
      const delay = item.delay || 0;

      // Entrance
      gsap.fromTo(el,
        { opacity: 0, scale: 0.4, y: 30 },
        { opacity: item.opacity ?? 0.92, scale: 1, y: 0,
          duration: 1.4, delay: delay + 0.3,
          ease: "back.out(1.4)" }
      );

      // Continuous gentle float
      gsap.to(el, {
        y: "random(-14, 14)",
        x: "random(-8, 8)",
        rotation: `random(-6, 6)`,
        duration: "random(3.5, 5.5)",
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay: delay,
      });

      // Wing flutter: animate scaleX of `.wings` children
      const wings = el.querySelectorAll(".wings");
      if (wings.length) {
        gsap.to(wings, {
          scaleX: 0.55,
          duration: 0.32,
          repeat: -1,
          yoyo: true,
          ease: "sine.inOut",
          stagger: 0.05,
          transformOrigin: "center center",
        });
      }
    });
  }, [items]);

  return (
    <>
      {items.map((item, i) => (
        <div
          key={i}
          className="butterfly"
          ref={(el) => (refs.current[i] = el)}
          style={{
            top:     item.top,
            left:    item.left,
            right:   item.right,
            bottom:  item.bottom,
            width:   item.size,
            height:  item.size,
            opacity: 0,
            transform: `rotate(${item.rot || 0}deg)`,
          }}
        >
          <ButterflySVG variant={item.variant} size={item.size} />
        </div>
      ))}
    </>
  );
}

/* ============================================================
   Flying butterflies — GSAP-driven sinusoidal flight path
   ============================================================ */
function FlyingButterflies({ count = 2 }) {
  const containerRef = useRef(null);

  useEffect(() => {
    if (typeof gsap === "undefined") return;
    const container = containerRef.current;
    if (!container) return;

    const elements = container.querySelectorAll(".fly-x");
    elements.forEach((el, i) => {
      const delay = i * 8 + Math.random() * 4;
      const dur   = 22 + Math.random() * 12;
      const yBase = 5 + Math.random() * 55; // % from top

      // Reset to start position
      gsap.set(el, { x: "-12vw", y: `${yBase}vh`, opacity: 0 });

      // Flight timeline — cross-screen with sinusoidal vertical drift
      const tl = gsap.timeline({ repeat: -1, delay });
      tl.to(el, {
        x: "112vw",
        duration: dur,
        ease: "none",
      });
      tl.to(el, { opacity: 0.9, duration: 1.2 }, 0);
      tl.to(el, { opacity: 0, duration: 1.5 }, dur - 1.5);

      // Sinusoidal vertical wobble layered on top
      gsap.to(el, {
        y: `+=${15 + Math.random() * 20}`,
        duration: dur / 4,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay,
      });

      // Wing flutter
      const wings = el.querySelectorAll(".wings");
      if (wings.length) {
        gsap.to(wings, {
          scaleX: 0.5,
          duration: 0.28,
          repeat: -1,
          yoyo: true,
          ease: "sine.inOut",
          stagger: 0.06,
          transformOrigin: "center center",
        });
      }
    });
  }, [count]);

  return (
    <div ref={containerRef} style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none", zIndex: 1 }}>
      {Array.from({ length: count }, (_, i) => (
        <div key={i} className="fly-x" style={{ opacity: 0, position: "absolute" }}>
          <ButterflySVG variant={(i % 5) + 1} size={70 + (i % 3) * 15} />
        </div>
      ))}
    </div>
  );
}

/* ============================================================
   Particles — GSAP stagger float-up
   ============================================================ */
function Particles({ count = 28 }) {
  const containerRef = useRef(null);

  const particles = useMemo(() => {
    return Array.from({ length: count }, (_, i) => ({
      id: i,
      left:    `${Math.random() * 98}%`,
      size:    3 + Math.random() * 5,
      delay:   Math.random() * 12,
      dur:     8 + Math.random() * 14,
      drift:   (Math.random() - 0.5) * 60,
    }));
  }, [count]);

  useEffect(() => {
    if (typeof gsap === "undefined") return;
    const container = containerRef.current;
    if (!container) return;

    const els = container.querySelectorAll(".particle");
    els.forEach((el, i) => {
      const p = particles[i];
      if (!p) return;

      gsap.set(el, { y: 20, opacity: 0 });

      gsap.to(el, {
        y:       -(window.innerHeight * 1.1),
        x:       p.drift,
        opacity: keyframeOpacity,
        duration: p.dur,
        delay:    p.delay,
        repeat:   -1,
        ease:     "none",
        onStart() {
          gsap.set(el, { opacity: 0, y: 20 });
        },
        onRepeat() {
          gsap.set(el, { opacity: 0, y: 20, x: (Math.random() - 0.5) * 60 });
        },
      });

      // Fade in and out within the travel
      gsap.to(el, {
        keyframes: [
          { opacity: 0,   duration: 0 },
          { opacity: 0.9, duration: p.dur * 0.18 },
          { opacity: 0.7, duration: p.dur * 0.64 },
          { opacity: 0,   duration: p.dur * 0.18 },
        ],
        delay:    p.delay,
        repeat:   -1,
        duration: p.dur,
        ease:     "none",
      });
    });
  }, [particles]);

  return (
    <div className="particles" ref={containerRef}>
      {particles.map((p) => (
        <div
          key={p.id}
          className="particle"
          style={{
            left:   p.left,
            bottom: 0,
            width:  p.size,
            height: p.size,
          }}
        />
      ))}
    </div>
  );
}

// Dummy ref for opacity — GSAP keyframes object handles it inline
const keyframeOpacity = undefined;

/* ============================================================
   Flowers — GSAP sway
   ============================================================ */
function Flowers({ items }) {
  const refs = useRef([]);

  useEffect(() => {
    if (typeof gsap === "undefined") return;
    refs.current.forEach((el, i) => {
      if (!el) return;
      const item = items[i];

      // Entrance
      gsap.fromTo(el,
        { opacity: 0, scale: 0.5, y: 20 },
        { opacity: item.opacity ?? 0.85, scale: 1, y: 0,
          duration: 1.6, delay: (item.delay || 0) + 0.2,
          ease: "back.out(1.6)" }
      );

      // Gentle sway with GSAP (smoother than CSS keyframe)
      gsap.to(el, {
        rotation: 4,
        duration: 3 + Math.random() * 3,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        transformOrigin: "bottom center",
        delay: item.delay || 0,
        startAt: { rotation: -4 },
      });
    });
  }, [items]);

  return (
    <>
      {items.map((item, i) => (
        <div
          key={i}
          className="flower"
          ref={(el) => (refs.current[i] = el)}
          style={{
            top:    item.top,
            left:   item.left,
            right:  item.right,
            bottom: item.bottom,
            width:  item.size,
            height: item.size,
            opacity: 0,
          }}
        >
          <FlowerSVG variant={item.variant} />
        </div>
      ))}
    </>
  );
}
