/* InkSection, liquid scroll-linked color switch.
   As the user scrolls into this section, a dark ink blob rises from the bottom
   using an SVG path with a wavy top edge that animates. The page reads
   light → dark → light again as the user passes through.

   Implementation:
   - Tracks scroll progress (0..1) across an extra-tall sticky section.
   - The blob's vertical offset and the wave amplitude are driven by progress.
   - Inner content fades from dark-on-light to light-on-dark and back.
*/
function InkSection() {
  const wrap = useRef(null);
  const [p, setP] = useState(0); // 0..1 progress through section
  const [t, setT] = useState(0); // continuous time for wave wobble

  useEffect(() => {
    let raf;
    const tick = () => { setT((x) => x + 0.012); raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  useEffect(() => {
    const onScroll = () => {
      const el = wrap.current; if (!el) return;
      const r = el.getBoundingClientRect();
      const vh = window.innerHeight;
      // Progress: 0 when section just enters from bottom, 1 when leaving top
      const raw = (vh - r.top) / (r.height + vh);
      setP(Math.max(0, Math.min(1, raw)));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => { window.removeEventListener("scroll", onScroll); window.removeEventListener("resize", onScroll); };
  }, []);

  // Blob shape progress: 0 = below screen, 0.5 = covering, 1 = above screen
  // 3-stage curve: rises from p=0.15..0.45, holds dark from 0.45..0.7, retreats up from 0.7..0.95
  let cover = 0;
  if (p < 0.15) cover = 0;
  else if (p < 0.45) cover = (p - 0.15) / 0.30;            // 0 → 1 (rising)
  else if (p < 0.70) cover = 1 + (p - 0.45) / 0.25 * 0;    // 1 (held)
  else if (p < 0.95) cover = 1 - (p - 0.70) / 0.25;        // 1 → 0 (falling out top, but we invert)
  else cover = 0;

  // Whether ink has passed the top edge (retreating)
  const retreating = p >= 0.70;

  // Construct wavy ink path (SVG viewBox 100x100, percentage-friendly)
  // Top edge wobbles with sine; vertical baseline = (1 - cover) * 100 when rising, or rising further up when retreating
  const baseline = retreating
    ? -(1 - cover) * 100 + (1 - cover) * 100  // when retreating, top edge moves UP past 0
    : (1 - cover) * 100;
  // Simpler: blob top y position; when rising 100→0, when retreating 0→ -110 (off top)
  const topY = retreating
    ? -((p - 0.70) / 0.25) * 110             // 0 → -110
    : (1 - cover) * 100;                     // 100 → 0

  // Wave amplitude, larger when actively moving, smaller when settled
  const moving = (p > 0.15 && p < 0.45) || (p > 0.70 && p < 0.95);
  const amp = moving ? 6 : 2.5;
  const w = (x) => Math.sin(x + t * 1.4) * amp;

  // Build the path: 5 control nodes across top
  const pts = [0, 25, 50, 75, 100].map((x, i) => ({ x, y: topY + w(i * 1.1) }));
  const path = `
    M0,${topY + 8}
    Q ${pts[0].x + 12.5},${pts[0].y - 4} ${pts[1].x},${pts[1].y}
    T ${pts[2].x},${pts[2].y}
    T ${pts[3].x},${pts[3].y}
    T ${pts[4].x},${pts[4].y}
    L 100,110 L 0,110 Z
  `;

  // Content darkness: 1 = fully on dark, 0 = fully on light
  const dark = Math.max(0, Math.min(1, (p - 0.30) / 0.18)) * (1 - Math.max(0, Math.min(1, (p - 0.74) / 0.16)));

  // Lava-lamp bubbles rising through the stage. Continuous loop driven by t,
  // visible only while the section is in view. Ellipses with rx/ry varying
  // through the cycle give organic teardrop shapes; the goo filter merges
  // neighbouring blobs. Bubbles share the ink colour, so they read as black
  // blobs on the light background and disappear into the dark wave as it rises.
  const bubbles = [
    { x: 90,  baseR: 38, speed: 0.30, phase: 0.0, aspect: 0.95 },
    { x: 240, baseR: 56, speed: 0.42, phase: 1.4, aspect: 1.10 },
    { x: 400, baseR: 30, speed: 0.36, phase: 0.6, aspect: 0.80 },
    { x: 560, baseR: 64, speed: 0.26, phase: 2.1, aspect: 1.15 },
    { x: 720, baseR: 42, speed: 0.40, phase: 1.0, aspect: 0.90 },
    { x: 880, baseR: 34, speed: 0.34, phase: 1.8, aspect: 1.00 },
  ];
  // Fade in as the section enters, fade out as it leaves
  const bubbleFadeIn  = Math.min(1, Math.max(0, (p - 0.04) / 0.14));
  const bubbleFadeOut = Math.min(1, Math.max(0, (0.98 - p) / 0.10));
  const bubbleAlpha   = bubbleFadeIn * bubbleFadeOut;

  const fg = dark > 0.5 ? "#F7F6F1" : "#0A0A0A";
  const sub = dark > 0.5 ? "rgba(247,246,241,0.62)" : "rgba(58,58,55,0.85)";
  const accent = dark > 0.5 ? "#9AB6D6" : "#4B6E92";

  return (
    <section ref={wrap} id="engine" style={{ position: "relative", height: "220vh", background: "var(--bone)" }}>
      <div style={{ position: "sticky", top: 0, height: "100vh", overflow: "hidden" }}>
        {/* Ink blob, full-bleed SVG */}
        <svg
          viewBox="0 0 100 100"
          preserveAspectRatio="none"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }}
          aria-hidden="true"
        >
          <defs>
            <linearGradient id="ink-grad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#0A0A0A" />
              <stop offset="60%" stopColor="#0B1F3A" />
              <stop offset="100%" stopColor="#050505" />
            </linearGradient>
            <filter id="ink-blur"><feGaussianBlur stdDeviation="0.25" /></filter>
          </defs>
          <path d={path} fill="url(#ink-grad)" filter="url(#ink-blur)" />
          {/* Subtle highlight stripe along the top edge */}
          <path
            d={`M0,${topY + 0.3} Q ${pts[0].x + 12.5},${pts[0].y - 4.3} ${pts[1].x},${pts[1].y - 0.3} T ${pts[2].x},${pts[2].y - 0.3} T ${pts[3].x},${pts[3].y - 0.3} T ${pts[4].x},${pts[4].y - 0.3}`}
            stroke="rgba(255,255,255,0.18)" strokeWidth="0.18" fill="none"
            style={{ opacity: dark > 0.05 && dark < 0.95 ? 1 : 0 }}
          />
        </svg>

        {/* Lava-lamp bubbles, aspect-preserved so blobs stay round-ish */}
        <svg
          viewBox="0 0 1000 1000"
          preserveAspectRatio="xMidYMid slice"
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none", opacity: bubbleAlpha }}
          aria-hidden="true"
        >
          <defs>
            <filter id="ink-bubbles-goo">
              <feGaussianBlur in="SourceGraphic" stdDeviation="14" result="b"/>
              <feColorMatrix in="b" type="matrix"
                values="1 0 0 0 0  0 1 0 0 0  0 0 1 0 0  0 0 0 24 -11"/>
            </filter>
          </defs>
          <g filter="url(#ink-bubbles-goo)" fill="#0A0A0A">
            {bubbles.map((b, i) => {
              const cycle = ((t * b.speed * 0.25 + b.phase) % 1);
              // Rise from y=1150 (below) to y=-150 (above the top of the stage)
              const y = 1150 - cycle * 1300;
              // Sideways drift
              const x = b.x + Math.sin(t * 0.6 + b.phase * 2) * 22;
              // Vertical stretch + horizontal squeeze as the bubble rises (teardrop)
              const ry = b.baseR * b.aspect * (0.78 + cycle * 0.45);
              const rx = b.baseR * (1.22 - cycle * 0.38);
              return <ellipse key={i} cx={x} cy={y} rx={rx} ry={ry} />;
            })}
          </g>
        </svg>

        {/* Animated grid overlay, visible only on dark */}
        <div style={{
          position: "absolute", inset: 0, opacity: dark * 0.5,
          backgroundImage: `linear-gradient(rgba(155,182,214,0.10) 1px, transparent 1px), linear-gradient(90deg, rgba(155,182,214,0.10) 1px, transparent 1px)`,
          backgroundSize: "64px 64px",
          maskImage: "radial-gradient(circle at 50% 50%, #000 30%, transparent 75%)",
          WebkitMaskImage: "radial-gradient(circle at 50% 50%, #000 30%, transparent 75%)",
          pointerEvents: "none",
        }} />

        {/* Content, fades color */}
        <div className="container" style={{ position: "relative", zIndex: 2, height: "100%", display: "flex", flexDirection: "column", justifyContent: "center", color: fg, transition: "color .25s linear" }}>
          <div style={{ maxWidth: 1100 }}>
            <div style={{
              fontFamily: "var(--font-sans)",
              fontSize: 12,
              fontWeight: 500,
              letterSpacing: "-0.005em",
              color: accent,
              transition: "color .25s linear",
            }}>
              The assessment engine
            </div>
            <h2 className="display" style={{ fontSize: "clamp(48px, 7vw, 112px)", margin: "20px 0 0", lineHeight: 1.02 }}>
              The deal goes in.<br/>
              <span className="serif-em" style={{ color: accent }}>A pathway</span> comes out.
            </h2>
            <p className="body-l" style={{ marginTop: 28, maxWidth: 640, color: sub, fontSize: 19 }}>
              At the centre of the platform is an assessment engine that reads every deal across leverage, security,
              stage, location and timing, then maps it to the lender profiles most likely to engage.
            </p>
          </div>

          {/* Three engine pillars */}
          <div style={{ marginTop: 64, display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 24 }} className="ink-pillars">
            {[
              { n: "01", k: "Read the deal",    v: "Metrics parsed into a structured deal view: leverage, presales, permits, timing." },
              { n: "02", k: "Map appetite",     v: "Cross-checked against curated private credit and non-bank funder profiles." },
              { n: "03", k: "Return a pathway", v: "Indicative direction, lender profile and next step, not a generic introduction." },
            ].map((it, i) => (
              <div key={it.n} style={{
                padding: 28,
                border: `1px solid ${dark > 0.5 ? "rgba(247,246,241,0.18)" : "rgba(10,10,10,0.14)"}`,
                background: dark > 0.5 ? "rgba(247,246,241,0.04)" : "rgba(10,10,10,0.02)",
                backdropFilter: "blur(6px)",
                borderRadius: 4,
                transition: "border-color .3s ease, background .3s ease",
              }}>
                <div className="mono" style={{ fontSize: 12, color: accent, letterSpacing: "0.04em" }}>- {it.n}</div>
                <div style={{ fontSize: 22, fontWeight: 500, marginTop: 24, letterSpacing: "-0.015em" }}>{it.k}</div>
                <div className="body" style={{ fontSize: 14, marginTop: 8, color: sub }}>{it.v}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom-right scroll hint */}
        <div style={{ position: "absolute", right: 32, bottom: 32, color: fg, opacity: 0.6, fontSize: 12, fontFamily: "var(--font-mono)", transition: "color .25s linear" }}>
         , scroll
        </div>
      </div>

      <style>{`
        @media (max-width: 800px) {
          #engine .ink-pillars { grid-template-columns: 1fr !important; gap: 12px !important; }
        }
      `}</style>
    </section>
  );
}
window.InkSection = InkSection;
