// Why Rank — full-bleed image, heading bottom-left, cream cards stacked right.
function WhyRank({ whyImg = "assets/images/community.webp" }) {
  const items = [
    { h: "Structured, Not Speculative", b: "We don’t gamble with your money. Every decision is deliberate." },
    { h: "Built for Long-Term Growth",  b: "We focus on sustainable wealth, not short-term wins." },
    { h: "Transparent Process",         b: "No guesswork. You see how your money is working." },
    { h: "Client-First Strategy",       b: "Your goals drive everything we do." },
  ];

  // Stagger the cards in from below as the section enters the viewport.
  // Reverses on scroll-back so the entrance can replay.
  React.useEffect(() => {
    if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    if (!window.gsap || !window.ScrollTrigger) return;
    const { gsap } = window;
    const tween = gsap.from(".why-card", {
      y: 100,
      opacity: 0,
      filter: "blur(6px)",
      duration: 0.8,
      stagger: 0.18,
      ease: "sine.out",
      scrollTrigger: {
        trigger: ".why",
        start: "top 75%",
        toggleActions: "play none none reverse",
      },
    });
    return () => {
      if (tween.scrollTrigger) tween.scrollTrigger.kill();
      tween.kill();
    };
  }, []);

  // Scroll-driven morph: the WhyRank background photo travels into the WhoFor
  // image card. While WhyRank is still entering from below it stays a normal
  // section background; once its top hits the viewport top it pins and lerps
  // toward WhoFor's image rect. Symmetric formula → seamless in reverse.
  React.useEffect(() => {
    if (matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const photo = document.querySelector(".why-photo");
    const whoMedia = document.querySelector(".who-media");
    const why = document.getElementById("why");
    if (!photo || !whoMedia || !why) return;
    const whoImg = whoMedia.querySelector("img");

    const reset = () => {
      Object.assign(photo.style, {
        position: "", inset: "", right: "", bottom: "",
        top: "", left: "", width: "", height: "",
        borderRadius: "", zIndex: "",
      });
      photo.style.removeProperty("--why-wash");
    };

    let rafId = null;
    const update = () => {
      rafId = null;
      const whyRect = why.getBoundingClientRect();
      const whyH = why.offsetHeight || window.innerHeight;

      if (whyRect.top > 0) {
        // WhyRank not yet at the top — plain section background
        reset();
        if (whoImg) whoImg.style.opacity = "";
        return;
      }

      // Pin + lerp toward WhoFor's live image rect (p = 0 at why-top, 1 once
      // WhyRank is fully scrolled past, clamped beyond so it tracks WhoFor).
      // Two phases: mp (0→1 over p 0–0.65) flies the photo into WhoFor's rect
      // with square corners; rp (0→1 over p 0.65–1) rounds the corners only
      // after the photo has fully settled. Symmetric → reverses seamlessly.
      const p = Math.max(0, Math.min(1, -whyRect.top / whyH));
      const mp = Math.min(1, p / 0.65);
      const rp = Math.max(0, (p - 0.65) / 0.35);
      const t = whoMedia.getBoundingClientRect();
      const vw = window.innerWidth;
      const vh = window.innerHeight;

      if (whoImg) whoImg.style.opacity = "0";
      Object.assign(photo.style, {
        position: "fixed",
        inset: "auto",
        right: "auto",
        bottom: "auto",
        zIndex: "0",
        top: `${mp * t.top}px`,
        left: `${mp * t.left}px`,
        width: `${(1 - mp) * vw + mp * t.width}px`,
        height: `${(1 - mp) * vh + mp * t.height}px`,
        borderRadius: `${rp * 48}px`,
      });
      photo.style.setProperty("--why-wash", (1 - mp).toFixed(3));
    };

    const onScroll = () => { if (rafId == null) rafId = requestAnimationFrame(update); };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", update);
    if (window.ScrollTrigger) window.ScrollTrigger.addEventListener("refresh", update);

    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", update);
      if (window.ScrollTrigger) window.ScrollTrigger.removeEventListener("refresh", update);
      if (rafId != null) cancelAnimationFrame(rafId);
      if (whoImg) whoImg.style.opacity = "";
      reset();
    };
  }, []);

  return (
    <section id="why" className="why">
      <div className="why-photo">
        <img src={whyImg} alt="" loading="lazy" decoding="async"/>
      </div>
      <div className="why-grid">
        <div className="why-headline">
          <h2>The Rank Difference</h2>
        </div>
        <div className="why-stack">
          {items.map(it => (
            <div className="why-card" key={it.h}>
              <h4>{it.h}</h4>
              <p>{it.b}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}
window.WhyRank = WhyRank;
