/* =========================================================
   RHeroAnimated — scroll-locked fertilization sequence
   Sticky hero (200vh tall). As you scroll through it,
   progress 0→1 animates: egg arrives, sperm swim in,
   one fertilises, DNA helix forms, hero copy settles.
   ========================================================= */

// helper: lerp + clamp
const _lerp = (a, b, t) => a + (b - a) * t;
const _clamp = (v, lo = 0, hi = 1) => Math.max(lo, Math.min(hi, v));
const _stage = (p, a, b) => _clamp((p - a) / (b - a));
const _ease = (t) => t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;

function useScrollProgress(ref) {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const el = ref.current; if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = el.offsetHeight - window.innerHeight;
      const scrolled = -rect.top;
      setP(_clamp(scrolled / Math.max(1, total)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [ref]);
  return p;
}

function RHeroAnimated() {
  const ref = React.useRef(null);
  const p = useScrollProgress(ref);

  // Timeline — explicit phases that match the biology so the viewer
  // can actually see the sperm cross the membrane, enter the egg, and
  // be absorbed before DNA forms. Settle has a long dwell so the final
  // caption is comfortable to read.
  const introT      = _ease(_stage(p, 0.00, 0.10));   // intro copy fades out
  const eggInT      = _ease(_stage(p, 0.10, 0.22));   // egg materialises
  const swimT       = _ease(_stage(p, 0.16, 0.36));   // 5 sperm fan toward the egg
  const penetrateT  = _ease(_stage(p, 0.34, 0.50));   // lead sperm crosses the membrane (head moves egg-edge → center)
  const insideT     = _ease(_stage(p, 0.46, 0.62));   // sperm head visible *inside* the egg, dissolving
  const fertiliseT  = _ease(_stage(p, 0.44, 0.58));   // (kept — other sperm fade out)
  const dnaT        = _ease(_stage(p, 0.58, 0.76));   // DNA helix draws inside the egg
  const settleT     = _ease(_stage(p, 0.62, 0.82));   // caption appears with generous dwell
  const exitT       = _ease(_stage(p, 0.96, 1.00));   // gentle fade for handoff

  // Pre-compute element transforms
  const eggScale = _lerp(0.0, 1.0, eggInT);
  const eggGlow  = eggInT * _lerp(1, 1.35, settleT);

  // sperm: 5 of them, fanned around the egg
  const sperms = [
    { id: 0, fromX: -1100, fromY: -180, ang: -15, fertilise: true },
    { id: 1, fromX: -1200, fromY:  120, ang:  8 },
    { id: 2, fromX:  1100, fromY: -140, ang: 170 },
    { id: 3, fromX:  1240, fromY:   80, ang: 195 },
    { id: 4, fromX:  -780, fromY:  340, ang: -40 },
  ];

  return (
    <section ref={ref} className="r-anim-hero" id="top">
      {/* sticky stage */}
      <div className="r-anim-stage">
        {/* layered teal bg + subtle pen photo */}
        <div className="r-anim-bg-photo" />
        <div className="r-anim-bg-tint" />
        <div className="r-anim-bg-grain" />

        {/* The fertilisation scene */}
        <svg className="r-anim-scene" viewBox="-700 -400 1400 800" preserveAspectRatio="xMidYMid meet">
          <defs>
            <radialGradient id="eggBody" cx="35%" cy="30%" r="80%">
              <stop offset="0%"  stopColor="#FFFFFF" stopOpacity="1" />
              <stop offset="35%" stopColor="#FFF7E8" stopOpacity="0.98" />
              <stop offset="75%" stopColor="#E9D9BA" stopOpacity="0.95" />
              <stop offset="100%" stopColor="#B89F76" stopOpacity="0.90" />
            </radialGradient>
            <radialGradient id="eggHalo" cx="50%" cy="50%" r="50%">
              <stop offset="0%"  stopColor="#7BC4C5" stopOpacity="0.55" />
              <stop offset="60%" stopColor="#3FA0A2" stopOpacity="0.15" />
              <stop offset="100%" stopColor="#3FA0A2" stopOpacity="0" />
            </radialGradient>
            <radialGradient id="eggCore" cx="50%" cy="50%" r="45%">
              <stop offset="0%"  stopColor="#FBEDE9" stopOpacity="0.95" />
              <stop offset="100%" stopColor="#D7C4A5" stopOpacity="0" />
            </radialGradient>
            <linearGradient id="spermBody" x1="0" y1="0" x2="1" y2="0">
              <stop offset="0%" stopColor="#FFFFFF" stopOpacity="1" />
              <stop offset="100%" stopColor="#CFEAEA" stopOpacity="0.85" />
            </linearGradient>
            <linearGradient id="dnaStrand" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"  stopColor="#5BB5B6" />
              <stop offset="50%" stopColor="#D7C4A5" />
              <stop offset="100%" stopColor="#3B587A" />
            </linearGradient>
            <filter id="softGlow" x="-50%" y="-50%" width="200%" height="200%">
              <feGaussianBlur stdDeviation="6" result="b" />
              <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
            </filter>
            {/* Clip used to render the lead sperm *inside* the egg —
                anything in this clipPath is masked to the egg's body so
                it visibly sits behind the membrane. */}
            <clipPath id="insideEgg">
              <circle cx="0" cy="0" r="178" />
            </clipPath>
          </defs>

          {/* Outer halo around egg */}
          <circle cx="0" cy="0" r={210 + 18 * settleT} fill="url(#eggHalo)" opacity={0.55 + 0.4 * eggGlow} />

          {/* Approaching sperm — the lead one stops at the membrane
              edge (radius ~180); the others retreat once fertilisation
              starts. The lead sperm then continues *into* the egg in
              the next render block (clipped to the membrane). */}
          {sperms.map((s) => {
            const t = swimT;
            const isLead = s.fertilise;
            // Lead sperm fades out of the outside layer as it crosses
            // the membrane (penetrateT > 0); inside layer takes over.
            const opacity = isLead
              ? swimT * (1 - penetrateT)
              : swimT * Math.max(0, 1 - fertiliseT * 1.1);
            // Target landing point: lead = membrane edge along its approach
            //                       others = 18% of original, scatter
            const dirLen = Math.hypot(s.fromX, s.fromY) || 1;
            const landX = isLead ? (-s.fromX / dirLen) * 175 : s.fromX * 0.18;
            const landY = isLead ? (-s.fromY / dirLen) * 175 : s.fromY * 0.18;
            const x = _lerp(s.fromX, landX, t);
            const y = _lerp(s.fromY, landY, t);
            const wiggle = Math.sin(p * 28 + s.id * 1.7) * 14 * (1 - t * 0.6);
            return (
              <g key={s.id} transform={`translate(${x}, ${y + wiggle}) rotate(${s.ang})`} opacity={opacity}>
                <Sperm />
              </g>
            );
          })}

          {/* Lead sperm INSIDE the egg — clipped to the membrane, head
              travels from the entry point to the egg's centre as
              penetrateT runs, then dissolves into the cytoplasm while
              insideT runs. Tail shortens first; head shrinks last. */}
          {(penetrateT > 0 || insideT > 0) && (() => {
            const lead = sperms.find(s => s.fertilise);
            if (!lead) return null;
            const dirLen = Math.hypot(lead.fromX, lead.fromY) || 1;
            // entry point on the membrane (radius 175), in the direction
            // the lead sperm was approaching from.
            const ex = (-lead.fromX / dirLen) * 175;
            const ey = (-lead.fromY / dirLen) * 175;
            // head journey: entry → centre over penetrateT
            const hx = _lerp(ex, 0, penetrateT);
            const hy = _lerp(ey, 0, penetrateT);
            // Tail fades & shortens first, head dissolves last.
            const tailOp = Math.max(0, 1 - penetrateT * 1.3);
            const headScale = _lerp(1, 0.0, _ease(insideT));
            const headOp = Math.max(0, 1 - insideT);
            // Subtle scale-up of the egg core to "absorb" the sperm.
            return (
              <g clipPath="url(#insideEgg)">
                <g transform={`translate(${hx}, ${hy}) rotate(${lead.ang})`}>
                  {/* Tail — shortens as it crosses */}
                  <g opacity={tailOp}>
                    <path d="M20,0 C56,-16 84,18 122,0 C156,-16 196,18 236,0"
                          stroke="#FFFFFF" strokeOpacity="0.9" strokeWidth="3"
                          fill="none" strokeLinecap="round" />
                  </g>
                  {/* Head — shrinks + fades inside the cytoplasm */}
                  <g transform={`scale(${headScale})`} opacity={headOp}>
                    <ellipse cx="0" cy="0" rx="22" ry="14"
                             fill="url(#spermBody)"
                             filter="url(#softGlow)" />
                    <ellipse cx="-6" cy="-4" rx="7" ry="4"
                             fill="#FFFFFF" opacity="0.9" />
                  </g>
                </g>
                {/* Gentle absorption shimmer at the centre — visible as
                    the head dissolves, fades as DNA takes over. */}
                <circle cx="0" cy="0"
                        r={28 + 22 * insideT}
                        fill="#FFFFFF"
                        opacity={0.55 * insideT * (1 - dnaT)} />
              </g>
            );
          })()}

          {/* Egg body — biggest, on top of halo, below DNA */}
          <g transform={`scale(${eggScale})`}>
            <circle cx="0" cy="0" r="180" fill="url(#eggBody)" filter="url(#softGlow)" />
            <circle cx="0" cy="0" r="180" fill="none" stroke="#FFFFFF" strokeWidth="2" opacity="0.6" />
            {/* inner zona pellucida ring */}
            <circle cx="0" cy="0" r="160" fill="none" stroke="#FFFFFF" strokeWidth="1" opacity={0.5 - 0.3 * settleT} strokeDasharray="2 4" />
            {/* core highlight */}
            <ellipse cx="-50" cy="-55" rx="50" ry="32" fill="#FFFFFF" opacity={0.55 - 0.2 * settleT} />
            {/* fertilisation core: appears once dnaT > 0 */}
            <circle cx="0" cy="0" r={36 + 18 * dnaT} fill="url(#eggCore)" opacity={dnaT} />
          </g>

          {/* DNA double helix forms inside the egg */}
          {dnaT > 0 && <DNAHelix t={dnaT} settleT={settleT} />}

          {/* Pulse ring when settled */}
          {settleT > 0 && (
            <g>
              <circle cx="0" cy="0" r={180 * (1 + 0.5 * settleT)} fill="none" stroke="#5BB5B6" strokeWidth="2" opacity={0.5 * (1 - settleT)} />
              <circle cx="0" cy="0" r={180 * (1 + 0.85 * settleT)} fill="none" stroke="#D7C4A5" strokeWidth="1.5" opacity={0.4 * (1 - settleT)} />
            </g>
          )}
        </svg>

        {/* Hero copy — fades in two phases */}
        <div className="r-anim-copy">
          <div className="r-anim-copy-intro" style={{ opacity: 1 - introT, transform: `translateY(${-12 * introT}px)` }}>
            <span className="td-eyebrow r-anim-eyebrow">International Egg Donation Agency</span>
            <h1 className="r-anim-title">
              A Global Standard in <em>Fertility Care.</em>
            </h1>
            <p className="r-anim-lede">
              With over 15 years of experience, Traveling Donors provides fully
              managed egg donation, sperm donation, and surrogacy programs
              across the world's leading fertility destinations.
            </p>
          </div>

          <div className="r-anim-copy-settle" style={{ opacity: settleT, transform: `translateY(${24 * (1 - settleT)}px)` }}>
            <span className="td-eyebrow r-anim-eyebrow" style={{color: "var(--td-sand-200)"}}>Care you can feel</span>
            <h2 className="r-anim-title r-anim-title-settle">
              Where two stories become <em>one family.</em>
            </h2>
            <div className="r-anim-cta">
              <a href={window.TD_WHATSAPP || "#"} target="_blank" rel="noopener" className="r-btn r-btn-primary">
                Book a Private Consultation →
              </a>
              <a href="#services" className="r-btn r-btn-on-teal">
                Explore Our Donor Collection
              </a>
            </div>
          </div>
        </div>

        {/* scroll indicator — anchored to bottom of stage */}
        <div className="r-anim-scrollcue" style={{ opacity: Math.max(0, 1 - p * 4) }}>
          <span>Scroll to begin</span>
          <i data-lucide="chevron-down"></i>
        </div>

        {/* exit gradient — soft fade to next section's bg */}
        <div className="r-anim-exit-fade" style={{ opacity: exitT }} />
      </div>
    </section>
  );
}

function Sperm() {
  return (
    <g>
      {/* head */}
      <ellipse cx="0" cy="0" rx="22" ry="14" fill="url(#spermBody)" />
      <ellipse cx="-6" cy="-4" rx="7" ry="4" fill="#FFFFFF" opacity="0.85" />
      {/* tail — wavy, longer & more visible */}
      <path d="M20,0 C56,-16 84,18 122,0 C156,-16 196,18 236,0"
            stroke="#FFFFFF" strokeOpacity="0.92" strokeWidth="3" fill="none" strokeLinecap="round" />
      <path d="M20,0 C56,-16 84,18 122,0 C156,-16 196,18 236,0"
            stroke="#CFEAEA" strokeOpacity="0.5" strokeWidth="1.5" fill="none" strokeLinecap="round" />
    </g>
  );
}

function DNAHelix({ t, settleT }) {
  // Two sinusoidal strands, with rungs between them
  const segments = 14;
  const totalH = 220;
  const ampX = 38;
  const visible = Math.floor(segments * t);
  const points = [];
  for (let i = 0; i <= segments; i++) {
    const y = -totalH/2 + (i / segments) * totalH;
    const phase = (i / segments) * Math.PI * 3 + settleT * 1.4;
    points.push({
      x1: Math.sin(phase) * ampX,
      x2: Math.sin(phase + Math.PI) * ampX,
      y
    });
  }
  return (
    <g opacity={1 - settleT * 0.2} transform={`rotate(${-12 + settleT * 8})`}>
      {/* strands */}
      <path
        d={points.slice(0, visible + 1).map((pt, i) => `${i === 0 ? "M" : "L"} ${pt.x1} ${pt.y}`).join(" ")}
        stroke="url(#dnaStrand)" strokeWidth="3.5" fill="none" strokeLinecap="round" />
      <path
        d={points.slice(0, visible + 1).map((pt, i) => `${i === 0 ? "M" : "L"} ${pt.x2} ${pt.y}`).join(" ")}
        stroke="url(#dnaStrand)" strokeWidth="3.5" fill="none" strokeLinecap="round" />
      {/* rungs */}
      {points.slice(0, visible + 1).map((pt, i) => (
        <line key={i} x1={pt.x1} y1={pt.y} x2={pt.x2} y2={pt.y}
              stroke="#FFFFFF" strokeOpacity={0.55} strokeWidth="1.2" />
      ))}
      {/* nucleotide nodes */}
      {points.slice(0, visible + 1).map((pt, i) => (
        <g key={"d" + i}>
          <circle cx={pt.x1} cy={pt.y} r="3.2" fill="#FFFFFF" />
          <circle cx={pt.x2} cy={pt.y} r="3.2" fill="#D7C4A5" />
        </g>
      ))}
    </g>
  );
}

Object.assign(window, { RHeroAnimated });
