/* ──────────────────────────────────────────────────────────
   Iceberg section — "Why most AI initiatives fail."
   Larger iceberg, triangular-profile connector anchors,
   no global blue blur (the 95% sits cleanly).
   ────────────────────────────────────────────────────────── */
const { useState, useEffect, useRef, useMemo, useLayoutEffect } = React;

// Iceberg PNG geometry — cropped tight on top/bottom, FULL width preserved so the
// thin horizontal waterline ripples in the source survive on the left/right.
const ICEBERG_SRC = 'assets/iceberg-v2.png';
const WATERLINE_FRAC = 0.3030;        // 266 / 878
const SUBMERGED_TOP_HALF_W = 0.2256;  // iceberg body half-width / image width (462/2/1024)
const ICEBERG_ASPECT = 878 / 1024;    // image h/w ratio (≈0.857, slightly wider than tall)
const ICEBERG_CENTER_FRAC = 0.4951;   // iceberg body center x / image width (slightly off-center)

/* ─── Water canvas — unchanged behaviour ────────────────── */
function WaterCanvas({ height = 220 }) {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    let W = canvas.clientWidth;
    let H = canvas.clientHeight;
    const resize = () => {
      W = canvas.clientWidth; H = canvas.clientHeight;
      canvas.width = W * dpr;
      canvas.height = H * dpr;
      const ctx = canvas.getContext('2d');
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    const ctx = canvas.getContext('2d');

    const bubbles = [];
    const NUM_BUBBLES = 32;
    for (let i = 0; i < NUM_BUBBLES; i++) {
      bubbles.push({
        x: Math.random(),
        y: 0.2 + Math.random() * 0.8,
        r: 0.4 + Math.random() * 1.4,
        v: 0.04 + Math.random() * 0.10,
        a: 0.06 + Math.random() * 0.18,
      });
    }

    let raf;
    const start = performance.now();
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    const draw = (now) => {
      const t = (now - start) / 1000;
      ctx.clearRect(0, 0, W, H);

      const waterY = H * 0.18;

      const grad = ctx.createLinearGradient(0, waterY, 0, H);
      grad.addColorStop(0,    'rgba(14, 34, 54, 0.92)');
      grad.addColorStop(0.45, 'rgba(8, 22, 38, 0.92)');
      grad.addColorStop(1,    'rgba(5, 14, 25, 0.96)');
      ctx.fillStyle = grad;
      ctx.fillRect(0, waterY, W, H - waterY);

      const skyGrad = ctx.createLinearGradient(0, 0, 0, waterY);
      skyGrad.addColorStop(0, 'rgba(7,16,27,0)');
      skyGrad.addColorStop(1, 'rgba(26,53,80,0.18)');
      ctx.fillStyle = skyGrad;
      ctx.fillRect(0, 0, W, waterY);

      const waveLayers = [
        { amp: 2.0, len: 380, sp: 0.15, off: 0,    a: 0.65, w: 1.0, color: 'rgba(180,210,235,' },
        { amp: 1.4, len: 220, sp: 0.22, off: 100,  a: 0.45, w: 0.8, color: 'rgba(140,180,210,' },
        { amp: 0.9, len: 140, sp: 0.32, off: 200,  a: 0.28, w: 0.6, color: 'rgba(120,160,200,' },
      ];

      waveLayers.forEach((L) => {
        ctx.beginPath();
        const move = reduced ? 0 : t * L.sp * L.len;
        for (let x = 0; x <= W; x += 2) {
          const y = waterY + Math.sin((x + L.off + move) / L.len * Math.PI * 2) * L.amp;
          if (x === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.strokeStyle = L.color + L.a + ')';
        ctx.lineWidth = L.w;
        ctx.stroke();
      });

      const hl = ctx.createLinearGradient(0, waterY - 2, 0, waterY + 4);
      hl.addColorStop(0,   'rgba(220,232,245,0)');
      hl.addColorStop(0.5, 'rgba(220,232,245,0.32)');
      hl.addColorStop(1,   'rgba(220,232,245,0)');
      ctx.fillStyle = hl;
      ctx.fillRect(0, waterY - 2, W, 6);

      if (!reduced) {
        const NUM_STREAKS = 14;
        for (let i = 0; i < NUM_STREAKS; i++) {
          const phase = (t * 0.06 + i / NUM_STREAKS) % 1;
          const x = phase * (W + 200) - 100;
          const yOff = ((i * 53) % 40) - 8;
          const y = waterY + yOff + Math.sin(t * 0.3 + i) * 1.2;
          if (y > waterY + 6 && y < H - 10) {
            ctx.beginPath();
            ctx.ellipse(x, y, 30 + (i % 3) * 14, 0.4, 0, 0, Math.PI*2);
            ctx.fillStyle = `rgba(150,190,220,${0.04 + (i%4)*0.015})`;
            ctx.fill();
          }
        }
      }

      const submergedH = H - waterY;
      bubbles.forEach(b => {
        if (!reduced) b.y -= b.v * 0.003;
        if (b.y < -0.02) {
          b.y = 1.0 + Math.random() * 0.1;
          b.x = Math.random();
          b.r = 0.4 + Math.random() * 1.4;
        }
        const px = b.x * W + Math.sin(t * 0.4 + b.y * 6) * 4;
        const py = waterY + b.y * submergedH;
        ctx.beginPath();
        ctx.arc(px, py, b.r, 0, Math.PI*2);
        ctx.fillStyle = `rgba(190,215,235,${b.a})`;
        ctx.fill();
      });

      raf = requestAnimationFrame(draw);
    };
    raf = requestAnimationFrame(draw);

    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, [height]);

  return (
    <canvas ref={canvasRef} style={{
      width:'100%', height: height + 'px', display:'block',
      pointerEvents:'none',
    }} />
  );
}

/* ──────────────────────────────────────────────────────────
   Mobile iceberg — transparent PNG asset, 2-col layout.
   Left = iceberg, right = text with connector line to tip
   and a static horizontal divider at the iceberg midpoint.
   ────────────────────────────────────────────────────────── */

function IcebergMobile({ foundations }) {
  // Iceberg fills the full section width as a background layer.
  // A frosted-glass panel on the right overlays it — translucent so
  // the blurred iceberg shows through behind the text.
  // The panel is split into two flex zones by the waterline divider,
  // each zone vertically centers its content.

  const SECTION_H  = 580;   // px — section height
  const IMG_SIZE   = SECTION_H; // square image rendered at this size
  const imgLeftPx  = -(Math.round(0.26 * IMG_SIZE)); // ≈ -151px: iceberg sits centered in the left column, left edge not clipped
  const waterlineH = Math.round(0.32 * IMG_SIZE);    // ≈ 186px — top zone height

  const [openKey, setOpenKey] = useState(null);      // tapped foundation → popup
  const [show, setShow] = useState(false);           // drives fade in/out
  const openItem = foundations.find(f => f.key === openKey);
  const openPopup  = (k) => { setOpenKey(k); requestAnimationFrame(() => requestAnimationFrame(() => setShow(true))); };
  const closePopup = () => { setShow(false); setTimeout(() => setOpenKey(null), 280); };

  return (
    <section id="why-matai" data-theme="dark" style={{
      background:'var(--night)', color:'rgba(250,246,236,0.9)',
      position:'relative', overflow:'hidden',
    }}>
      {/* ── Block 1: headline + 95% ── */}
      <div style={{ padding:'80px 24px 48px' }}>
        <Reveal>
          <Eyebrow tone="ice" style={{ marginBottom:'20px' }}>The Reality</Eyebrow>
          <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
            fontWeight:500, fontSize:'clamp(38px, 10vw, 56px)', lineHeight:1.02,
            letterSpacing:'-0.02em', color:'#FFFFFF', marginBottom:'20px' }}>
            Why most AI initiatives{' '}
            <span className="accent-italic on-dark">fail.</span>
          </h2>
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'15px',
            lineHeight:1.65, color:'rgba(232,238,246,0.66)', marginBottom:'36px' }}>
            The promise of AI captures attention. The enterprise capabilities
            required for success are often overlooked.
          </p>
          <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
            fontWeight:500, fontSize:'clamp(80px, 22vw, 120px)', lineHeight:0.9,
            letterSpacing:'-0.04em',
            background:'linear-gradient(180deg, #F5E7C7 0%, #C9A875 60%, #8A6F45 100%)',
            WebkitBackgroundClip:'text', backgroundClip:'text',
            WebkitTextFillColor:'transparent', marginBottom:'12px' }}>
            95%
          </div>
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14px',
            lineHeight:1.55, color:'rgba(232,238,246,0.78)', marginBottom:'8px' }}>
            of enterprise AI pilots fail to reach production deployment.
          </p>
          <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:400, fontSize:'10px',
            letterSpacing:'0.18em', textTransform:'uppercase',
            color:'rgba(232,238,246,0.32)' }}>
            Source · MIT Report via Fortune, 2025
          </p>
        </Reveal>
      </div>

      {/* ── Block 2: iceberg background + frosted text panel ── */}
      <div style={{ position:'relative', height: SECTION_H + 'px', overflow:'hidden' }}>

        {/* Iceberg: full-width background layer */}
        <img src="assets/iceberg-standalone.png" alt=""
          style={{
            position:'absolute', top:0,
            left: imgLeftPx + 'px',
            height: IMG_SIZE + 'px',
            width:  IMG_SIZE + 'px',
            objectFit:'contain',
            pointerEvents:'none',
            zIndex:1,
          }} />

        {/* Frosted glass text panel — right 54%, full height, translucent */}
        <div style={{
          position:'absolute', top:0, bottom:0, right:0, left:'46%',
          zIndex:2,
          backdropFilter:'blur(10px)',
          WebkitBackdropFilter:'blur(10px)',
          background:'rgba(7,16,27,0.38)',
          display:'flex', flexDirection:'column',
        }}>

          {/* TOP zone: height = waterlineH, vertically centered */}
          <div style={{
            height: waterlineH + 'px', flexShrink:0,
            display:'flex', alignItems:'center',
            padding:'0 16px 0 14px',
          }}>
            <div>
              <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
                fontSize:'20px', fontWeight:500, color:'#FFFFFF',
                marginBottom:'8px', letterSpacing:'-0.01em', lineHeight:1.1 }}>
                The visible 10%
              </div>
              <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'12px',
                color:'rgba(232,238,246,0.62)', lineHeight:1.55 }}>
                Demos, pilots, chatbots, and AI assistants, create excitement
                but rarely deliver enterprise value alone.
              </p>
            </div>
          </div>

          {/* BOTTOM zone: top-aligned with padding so content sits in the
              upper portion of the submerged iceberg, not the full bottom half */}
          <div style={{
            flex:1,
            display:'flex', alignItems:'flex-start',
            padding:'22px 16px 0 14px',
          }}>
            <div>
              <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
                fontSize:'14px', fontWeight:300, color:'#FFFFFF',
                marginBottom:'10px', letterSpacing:'-0.005em' }}>
                What lies beneath
              </div>
              {/* Titles only — tap to open a popup with the explainer */}
              <div style={{ display:'flex', flexDirection:'column', gap:'11px' }}>
                {foundations.map((f) => (
                  <button key={f.key} onClick={() => openPopup(f.key)} style={{
                    display:'flex', gap:'8px', alignItems:'center', width:'100%',
                    background:'none', border:'none', padding:0, cursor:'pointer', textAlign:'left' }}>
                    <div style={{ width:'4px', height:'4px', borderRadius:'50%',
                      background:'rgba(217,194,154,0.6)', flexShrink:0 }} />
                    <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
                      fontSize:'13px', fontWeight:300, color:'rgba(245,250,255,0.9)', flex:1 }}>{f.t}</div>
                    <div aria-hidden style={{ fontFamily:"'Inter',sans-serif", fontSize:'13px',
                      color:'rgba(217,194,154,0.7)', flexShrink:0 }}>+</div>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom fade */}
      <div aria-hidden style={{
        position:'absolute', left:0, right:0, bottom:0, height:'80px',
        background:'linear-gradient(to bottom, rgba(7,16,27,0) 0%, var(--ocean-mid) 100%)',
        pointerEvents:'none', zIndex:10,
      }} />

      {/* Tap popup — title + explainer with an X to close */}
      {openItem && (
        <div onClick={closePopup} style={{
          position:'fixed', inset:0, zIndex:200,
          display:'flex', alignItems:'center', justifyContent:'center', padding:'32px',
          background:'rgba(7,16,27,0.6)', WebkitBackdropFilter:'blur(3px)', backdropFilter:'blur(3px)',
          opacity: show ? 1 : 0, transition:'opacity .28s ease',
        }}>
          <div onClick={(e) => e.stopPropagation()} style={{
            position:'relative', width:'100%', maxWidth:'320px',
            background:'var(--night-2)', border:'1px solid rgba(217,194,154,0.25)',
            borderRadius:'16px', padding:'30px 26px 26px',
            boxShadow:'0 30px 60px -20px rgba(0,0,0,0.6)',
            opacity: show ? 1 : 0,
            transform: show ? 'translateY(0) scale(1)' : 'translateY(10px) scale(0.96)',
            transition:'opacity .28s ease, transform .3s cubic-bezier(.2,.7,.2,1)',
          }}>
            <button onClick={closePopup} aria-label="Close" style={{
              position:'absolute', top:'12px', right:'12px', width:'30px', height:'30px',
              borderRadius:'50%', border:'1px solid rgba(217,194,154,0.25)',
              background:'transparent', color:'rgba(245,250,255,0.7)', cursor:'pointer',
              display:'flex', alignItems:'center', justifyContent:'center', padding:0 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                strokeWidth="2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
            <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
              fontSize:'20px', fontWeight:400, color:'#FFFFFF', marginBottom:'12px',
              paddingRight:'24px', letterSpacing:'-0.01em', lineHeight:1.15 }}>
              {openItem.t}
            </div>
            <div style={{ width:'24px', height:'1px', background:'rgba(217,194,154,0.5)', marginBottom:'14px' }} />
            <div style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14px',
              color:'rgba(232,238,246,0.7)', lineHeight:1.6 }}>
              {openItem.d}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

/* ──────────────────────────────────────────────────────────
   Section
   ────────────────────────────────────────────────────────── */
function IcebergSection() {
  const isMobile = useIsMobile();

  // Foundation points — depth from waterline (0..1 of submerged height)
  const foundations = [
    { key: 'strategy',   t: 'Strategic Alignment',             d: 'Unclear priorities, fragmented initiatives, and limited business focus.',      depth: 0.05 },
    { key: 'governance', t: 'Governance & Oversight',          d: 'Insufficient controls, accountability, and risk management.',                  depth: 0.20 },
    { key: 'data',       t: 'Enterprise Readiness',            d: 'Gaps in data, processes, operating models, and organizational preparedness.',  depth: 0.36 },
    { key: 'workflow',   t: 'Technology Integration',          d: 'Disconnected systems, siloed workflows, and implementation complexity.',       depth: 0.54 },
    { key: 'change',     t: 'Workforce Adoption',              d: 'Low engagement, unclear responsibilities, and resistance to change.',          depth: 0.72 },
    { key: 'measure',    t: 'Measurement & Value Realization', d: 'Limited visibility into outcomes, performance, and business impact.',          depth: 0.88 },
  ];

  if (isMobile) return <IcebergMobile foundations={foundations} />;

  const [hovered, setHovered] = useState(null);
  const stageRef = useRef(null);
  const icebergFrameRef = useRef(null);
  const labelRefs = useRef({});

  // Above-water connector — anchors on the tip of the iceberg (depth < 0).
  // For depth in [-1, 0]: halfW = maxHalfW * (1 + depth); ty = waterlineY + (visibleH * depth)
  // For depth in [0, 1]:  halfW = maxHalfW * (1 - depth); ty = waterlineY + submergedH * depth
  const visible10 = { key: 'visible10', depth: -0.55, anchorSide: 'right' };

  const [lines, setLines] = useState([]);
  const [stageH, setStageH] = useState(0);
  const [stageW, setStageW] = useState(0);

  useEffect(() => {
    const compute = () => {
      const stage = stageRef.current;
      const frame = icebergFrameRef.current;
      if (!stage || !frame) return;
      const sRect = stage.getBoundingClientRect();
      const fRect = frame.getBoundingClientRect();
      // iceberg-frame has explicit aspect-ratio + height:100%, so fRect IS the iceberg
      const iW = fRect.width;
      const iH = fRect.height;
      const iLeftRel = fRect.left - sRect.left;
      const iTopRel = fRect.top - sRect.top;
      const iCenterX = iLeftRel + iW * ICEBERG_CENTER_FRAC;
      const waterlineY = iTopRel + iH * WATERLINE_FRAC;
      const submergedH = iH * (1 - WATERLINE_FRAC);
      const maxHalfW = iW * SUBMERGED_TOP_HALF_W;

      const visibleH = iH * WATERLINE_FRAC;
      // Only visible10 (the pointer up to the tip) draws a connector line.
      // Foundation items just use the bullet dot — no leading lines per latest direction.
      const newLines = [visible10].map(f => {
        const labelEl = labelRefs.current[f.key];
        if (!labelEl) return null;
        // Aim the connector at the title's vertical centre, not the box midpoint,
        // so the line + dot stay locked to the headline regardless of body length.
        const titleEl = labelEl.querySelector('[data-vis10-title]') || labelEl;
        const tRect = titleEl.getBoundingClientRect();
        const lRect = labelEl.getBoundingClientRect();
        const lLeft = lRect.left - sRect.left;
        const lMid  = (tRect.top + tRect.height / 2) - sRect.top;
        let halfW, ty;
        if (f.depth >= 0) {
          halfW = maxHalfW * (1 - f.depth);
          ty = waterlineY + submergedH * f.depth;
        } else {
          halfW = maxHalfW * (1 + f.depth);
          ty = waterlineY + visibleH * f.depth;
        }
        const insetFromEdge = 4;
        const tx = iCenterX + halfW - insetFromEdge;
        // Land the connector dot just INSIDE the label's left padding so the
        // line terminates exactly at the bullet — not floating short of it.
        return { key: f.key, x1: tx, y1: ty, x2: lLeft + 7, y2: lMid, side: 'right' };
      }).filter(Boolean);

      setLines(newLines);
      setStageH(sRect.height);
      setStageW(sRect.width);
    };
    compute();
    const ro = new ResizeObserver(compute);
    if (stageRef.current) ro.observe(stageRef.current);
    if (icebergFrameRef.current) ro.observe(icebergFrameRef.current);
    Object.values(labelRefs.current).forEach(el => el && ro.observe(el));
    window.addEventListener('resize', compute);
    window.addEventListener('scroll', compute, { passive: true });

    // Recompute after fonts settle AND after the Reveal slide-up transition
    // finishes (~0.85s) — otherwise the title rect is measured 28px low and
    // the SVG line + bullet end up misaligned.
    const t1 = setTimeout(compute, 50);
    const t2 = setTimeout(compute, 400);
    const t3 = setTimeout(compute, 1100);
    const onTransitionEnd = (e) => {
      if (e.propertyName === 'transform' || e.propertyName === 'opacity') compute();
    };
    const visEl = labelRefs.current['visible10'];
    const visReveal = visEl && visEl.closest('.reveal');
    if (visReveal) visReveal.addEventListener('transitionend', onTransitionEnd);

    return () => {
      ro.disconnect();
      window.removeEventListener('resize', compute);
      window.removeEventListener('scroll', compute);
      clearTimeout(t1); clearTimeout(t2); clearTimeout(t3);
      if (visReveal) visReveal.removeEventListener('transitionend', onTransitionEnd);
    };
  }, []);

  return (
    <section id="why-matai" data-theme="dark" data-screen-label="why-ai-fails" style={{
      background:'var(--night)',
      color:'rgba(250,246,236,0.9)',
      position:'relative', overflow:'hidden',
      padding:'120px 40px 200px',
    }}>
      {/* Focused ambient glow — sits BEHIND the iceberg only, not over the headline/95% */}
      <div aria-hidden style={{
        position:'absolute', left:'50%', top:'54%', transform:'translate(-50%, -50%)',
        width:'820px', height:'820px', borderRadius:'50%',
        background:'radial-gradient(circle, rgba(40,75,110,0.24) 0%, rgba(20,40,60,0.06) 40%, rgba(0,0,0,0) 65%)',
        pointerEvents:'none', filter:'blur(40px)', zIndex: 0,
      }} />

      <div style={{ maxWidth:'1480px', margin:'0 auto', position:'relative' }}>

        <div ref={stageRef} style={{ position:'relative',
          display:'grid', gridTemplateColumns:'0.95fr 1fr 0.95fr', gap:'28px',
          minHeight:'720px', alignItems:'stretch',
        }}>

          {/* ─── ABSOLUTE iceberg frame ─ width-sized so frame matches image exactly ─── */}
          <div ref={icebergFrameRef} style={{
            position:'absolute', top:'50%', left:'50%',
            transform:'translate(-50%, -50%)',
            width:'min(100%, 820px)', aspectRatio:'1024 / 878',
            pointerEvents:'none', zIndex: 2,
          }}>
            <div className="anim" style={{
              position:'relative',
              width:'100%', height:'100%',
              animation:'icebergFloat 11s ease-in-out infinite',
            }}>
              <img src={ICEBERG_SRC} alt=""
                style={{
                  width:'100%', height:'100%', objectFit:'contain', display:'block',
                  filter:'drop-shadow(0 80px 60px rgba(0,0,0,0.55))',
                }} />

              {/* Hover dim overlays — masked to the iceberg shape so only the
                  ice dims. Hovering "the visible 10%" dims the submerged base;
                  hovering a "what lies beneath" item dims the peak above water. */}
              <div aria-hidden style={{
                position:'absolute', inset:0, pointerEvents:'none', zIndex:2,
                WebkitMaskImage:`url(${ICEBERG_SRC})`, maskImage:`url(${ICEBERG_SRC})`,
                WebkitMaskSize:'contain', maskSize:'contain',
                WebkitMaskRepeat:'no-repeat', maskRepeat:'no-repeat',
                WebkitMaskPosition:'center', maskPosition:'center',
                background:`linear-gradient(to bottom, rgba(7,16,27,0) ${WATERLINE_FRAC*100}%, rgba(7,16,27,0.55) ${WATERLINE_FRAC*100+22}%, rgba(7,16,27,0.7) 100%)`,
                opacity: hovered === 'visible10' ? 1 : 0,
                transition:'opacity .45s ease',
              }} />
              <div aria-hidden style={{
                position:'absolute', inset:0, pointerEvents:'none', zIndex:2,
                WebkitMaskImage:`url(${ICEBERG_SRC})`, maskImage:`url(${ICEBERG_SRC})`,
                WebkitMaskSize:'contain', maskSize:'contain',
                WebkitMaskRepeat:'no-repeat', maskRepeat:'no-repeat',
                WebkitMaskPosition:'center', maskPosition:'center',
                background:`linear-gradient(to bottom, rgba(7,16,27,0.66) 0%, rgba(7,16,27,0.5) ${WATERLINE_FRAC*100-6}%, rgba(7,16,27,0) ${WATERLINE_FRAC*100+6}%)`,
                opacity: (hovered && hovered !== 'visible10') ? 1 : 0,
                transition:'opacity .45s ease',
              }} />
            </div>
            {/* Above-water atmospheric glow on the iceberg tip */}
            <div aria-hidden style={{
              position:'absolute', left:'50%', top:'14%', transform:'translate(-50%, -50%)',
              width:'520px', height:'240px', borderRadius:'50%',
              background:'radial-gradient(ellipse, rgba(180,210,235,0.16) 0%, rgba(180,210,235,0) 60%)',
              pointerEvents:'none', filter:'blur(28px)', zIndex: 1,
            }} />
          </div>

          {/* ─── LEFT: headline + 95% ────────────────────────────────── */}
          <div style={{ display:'flex', flexDirection:'column',
            paddingTop:'10px', paddingBottom:'20px', position:'relative', zIndex: 5 }}>
            <Reveal>
              <Eyebrow tone="ice" style={{ marginBottom:'14px' }}>The Reality</Eyebrow>
              <h2 style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
                fontSize:'clamp(38px, 4.2vw, 56px)', lineHeight:1.02,
                letterSpacing:'-0.02em', color:'#FFFFFF', marginBottom:'14px',
                textWrap:'balance' }}>
                Why most AI initiatives <span className="accent-italic on-dark">fail.</span>
              </h2>
              <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'13.5px',
                lineHeight:1.55, color:'rgba(232,238,246,0.66)', maxWidth:'320px' }}>
                The promise of AI captures attention. The enterprise capabilities
                required for success are often overlooked.
              </p>
            </Reveal>

            <Reveal delay={0.15}>
              <div style={{ marginTop:'48px', position:'relative' }}>
                <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14", fontWeight:500,
                  fontSize:'clamp(96px, 11vw, 156px)', lineHeight:0.9,
                  letterSpacing:'-0.04em',
                  background:'linear-gradient(180deg, #F5E7C7 0%, #C9A875 60%, #8A6F45 100%)',
                  WebkitBackgroundClip:'text', backgroundClip:'text',
                  WebkitTextFillColor:'transparent', marginBottom:'18px' }}>
                  95%
                </div>
                <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14.5px',
                  lineHeight:1.55, color:'rgba(232,238,246,0.78)', maxWidth:'300px',
                  marginBottom:'10px' }}>
                  of enterprise AI pilots fail to reach production deployment.
                </p>
                <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:400, fontSize:'10.5px',
                  letterSpacing:'0.18em', textTransform:'uppercase',
                  color:'rgba(232,238,246,0.32)' }}>
                  Source · MIT Report via Fortune, 2025
                </p>
              </div>
            </Reveal>
          </div>

          {/* ─── CENTER column: empty placeholder (iceberg is absolutely positioned) */}
          <div aria-hidden></div>

          {/* ─── RIGHT: visible 10% above water, foundation items below ─── */}
          <div style={{
            position:'relative', minHeight:'100%',
            paddingTop:'10px', paddingBottom:'20px', zIndex: 5,
          }}>
            {/* Above water — absolute, anchored just above the iceberg waterline */}
            <div style={{
              position:'absolute', left:0, right:0,
              bottom: `calc(${(1 - WATERLINE_FRAC) * 100}% + 36px)`,
            }}>
              <Reveal>
                <div
                  ref={el => labelRefs.current['visible10'] = el}
                  onMouseEnter={() => setHovered('visible10')}
                  onMouseLeave={() => setHovered(null)}
                  style={{
                    position:'relative', padding:'10px 14px 12px 16px',
                    borderRadius:'8px', cursor:'pointer',
                    background: hovered === 'visible10' ? 'rgba(201,168,117,0.06)' : 'transparent',
                    transition:'background .3s',
                  }}>
                  <div data-vis10-title style={{ fontFamily:"'Bodoni Moda', serif",
                    fontVariationSettings:"'opsz' 14",
                    fontSize:'34px', fontWeight:500,
                    color:'#FFFFFF', marginBottom:'12px',
                    letterSpacing:'-0.015em', lineHeight:1.05 }}>
                    The visible 10%
                  </div>
                  <p style={{ fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'14.5px',
                    color:'rgba(232,238,246,0.66)', lineHeight:1.6, maxWidth:'340px' }}>
                    Demos, pilots, chatbots, and AI assistants, create excitement but
                    rarely deliver enterprise value alone.
                  </p>
                </div>
              </Reveal>
            </div>

            {/* Below water — absolutely anchored at the iceberg waterline */}
            <div style={{
              position:'absolute', left:0, right:0,
              top: `calc(${WATERLINE_FRAC * 100}% + 18px)`,
              padding:'14px 0 14px 12px',
              borderRadius:'8px',
              background:'linear-gradient(to left, rgba(7,16,27,0.92) 0%, rgba(7,16,27,0.88) 55%, rgba(7,16,27,0) 100%)',
            }}>
              <Reveal delay={0.1}>
                <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
                  fontSize:'22px', fontWeight:300,
                  color:'#FFFFFF', marginBottom:'14px', letterSpacing:'-0.005em' }}>
                  What lies beneath
                </div>
              </Reveal>

              <div style={{ display:'flex', flexDirection:'column', gap:'6px' }}>
                {foundations.map((f, i) => {
                  const on = hovered === f.key;
                  return (
                    <Reveal key={f.key} delay={0.15 + i * 0.04}>
                      <div
                        ref={el => labelRefs.current[f.key] = el}
                        onMouseEnter={() => setHovered(f.key)}
                        onMouseLeave={() => setHovered(null)}
                        style={{
                          position:'relative', padding:'6px 12px 6px 20px',
                          borderRadius:'6px', cursor:'pointer',
                          background: on ? 'rgba(201,168,117,0.06)' : 'transparent',
                          transition:'background .3s',
                        }}>
                        <div style={{ position:'absolute', left:'3px', top:'50%',
                          transform:'translateY(-50%)',
                          width:'6px', height:'6px', borderRadius:'50%',
                          background: on ? 'var(--gold-soft)' : 'rgba(232,238,246,0.42)',
                          boxShadow: on ? '0 0 12px rgba(217,194,154,0.6)' : 'none',
                          transition:'background .3s, box-shadow .3s',
                        }} />
                        <div style={{ fontFamily:"'Bodoni Moda', serif", fontVariationSettings:"'opsz' 14",
                          fontSize:'17px', fontWeight:300,
                          color: on ? '#FFFFFF' : 'rgba(245,250,255,0.85)',
                          letterSpacing:'-0.005em',
                          transition:'color .3s' }}>{f.t}</div>
                        {/* Hover popover — explainer blurb (keeps the list compact) */}
                        <div style={{
                          position:'absolute', top:'calc(100% - 2px)', left:'16px', right:'6px',
                          zIndex: on ? 25 : 20,
                          background:'var(--night-2)', border:'1px solid rgba(217,194,154,0.22)',
                          borderRadius:'10px', padding:'10px 13px',
                          boxShadow:'0 18px 38px -16px rgba(0,0,0,0.65)',
                          fontFamily:"'Inter',sans-serif", fontWeight:300, fontSize:'12.5px',
                          color:'rgba(232,238,246,0.8)', lineHeight:1.5,
                          opacity: on ? 1 : 0,
                          transform: on ? 'translateY(0)' : 'translateY(-4px)',
                          pointerEvents:'none',
                          transition:'opacity .25s ease, transform .25s ease',
                        }}>{f.d}</div>
                      </div>
                    </Reveal>
                  );
                })}
              </div>
            </div>
          </div>

          {/* ─── SVG connector overlay ────────────────────────── */}
          <svg aria-hidden style={{ position:'absolute', inset:0, width:'100%',
            height: stageH || '100%', pointerEvents:'none', zIndex: 3 }}
            viewBox={`0 0 ${stageW || 1280} ${stageH || 940}`}
            preserveAspectRatio="none">
            <defs>
              <linearGradient id="goldLine" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0" stopColor="#D9C29A" stopOpacity="0.0" />
                <stop offset="0.4" stopColor="#D9C29A" stopOpacity="0.85" />
                <stop offset="1" stopColor="#F5E7C7" stopOpacity="1" />
              </linearGradient>
            </defs>
            {lines.map(l => {
              const on = hovered === l.key;
              // Curve direction depends on which side the label sits on
              const stubLen = 28;
              const stubX = l.side === 'left' ? l.x1 - stubLen : l.x1 + stubLen;
              const d = `M ${l.x1} ${l.y1} L ${stubX} ${l.y1} C ${(stubX + l.x2)/2} ${l.y1}, ${(stubX + l.x2)/2} ${l.y2}, ${l.x2} ${l.y2}`;
              return (
                <g key={l.key}>
                  <path d={d}
                    fill="none"
                    stroke={on ? 'url(#goldLine)' : 'rgba(217,194,154,0.18)'}
                    strokeWidth={on ? 1.3 : 0.7}
                    style={{ transition:'stroke .35s, stroke-width .35s' }}
                  />
                  {/* iceberg-side anchor dot */}
                  <circle cx={l.x1} cy={l.y1} r={on ? 3.6 : 2.2}
                    fill={on ? '#F5E7C7' : 'rgba(217,194,154,0.55)'}
                    style={{ transition:'fill .3s, r .3s' }} />
                  {/* label-side anchor dot — the visible bullet on the callout */}
                  <circle cx={l.x2} cy={l.y2} r={on ? 4.5 : 3.4}
                    fill={on ? 'var(--gold-soft)' : 'rgba(232,238,246,0.55)'}
                    style={{
                      transition:'fill .3s, r .3s, filter .3s',
                      filter: on ? 'drop-shadow(0 0 8px rgba(217,194,154,0.65))' : 'none',
                    }} />
                </g>
              );
            })}
          </svg>

          {/* Water canvas — anchored to iceberg's waterline */}
          <IcebergWater stageRef={stageRef} icebergFrameRef={icebergFrameRef} />
        </div>
      </div>

      {/* Bottom fade — eases iceberg's midnight into the ocean-blue next section */}
      <div aria-hidden style={{
        position:'absolute', left:0, right:0, bottom:0, height:'90px',
        background:'linear-gradient(to bottom, rgba(7,16,27,0) 0%, var(--ocean-mid) 100%)',
        pointerEvents:'none', zIndex: 10,
      }} />
    </section>
  );
}

/* Water canvas wrapper — uses the static iceberg frame for stable positioning */
function IcebergWater({ stageRef, icebergFrameRef }) {
  const [pos, setPos] = useState(null);

  useEffect(() => {
    const compute = () => {
      const stage = stageRef.current;
      const frame = icebergFrameRef.current;
      if (!stage || !frame) return;
      const sRect = stage.getBoundingClientRect();
      const fRect = frame.getBoundingClientRect();
      // iceberg-frame has aspect-ratio + height:100% — fRect.height IS iceberg height
      const waterlineY = (fRect.top - sRect.top) + fRect.height * WATERLINE_FRAC;
      const canvasH = 520;
      const surfaceFrac = 0.18;
      const top = waterlineY - canvasH * surfaceFrac;
      setPos({ top, h: canvasH });
    };
    compute();
    const ro = new ResizeObserver(compute);
    if (stageRef.current) ro.observe(stageRef.current);
    if (icebergFrameRef.current) ro.observe(icebergFrameRef.current);
    window.addEventListener('resize', compute);
    return () => { ro.disconnect(); window.removeEventListener('resize', compute); };
  }, []);

  if (!pos) return null;
  return (
    <div aria-hidden style={{
      position:'absolute', top: pos.top + 'px',
      left:'-40px', right:'-40px',
      height: pos.h + 'px',
      zIndex: 1, pointerEvents:'none',
    }}>
      <WaterCanvas height={pos.h} />
    </div>
  );
}

Object.assign(window, { IcebergSection });
