/* ============== "Em camadas" exploded keycap on scroll ============== */

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

const LAYERS = [
  {
    id: "surface",
    title: "Superfície Lunar",
    desc: "O primeiro contato. A interface que seu time e seus clientes enxergam todos os dias — limpa, intuitiva, pensada para a operação real.",
  },
  {
    id: "shell",
    title: "Crosta Metálica",
    desc: "Arquitetura sólida, autenticação, criptografia, audit log. Estabilidade e segurança como fundação, não como adendo.",
  },
  {
    id: "circuits",
    title: "Circuitos",
    desc: "Integrações com tudo que sua empresa já usa — ERPs, APIs, calendários, WhatsApp. Os sistemas finalmente conversam.",
  },
  {
    id: "gears",
    title: "Engrenagens",
    desc: "Lógica de negócio modelada com clareza. Automações que devolvem tempo ao time e eliminam retrabalho.",
  },
  {
    id: "matrix",
    title: "Fluxo de Dados",
    desc: "Código, inteligência, dados em tempo real. O motor que faz tudo aqui em cima funcionar, versão por versão, deploy por deploy.",
  },
  {
    id: "core",
    title: "O Núcleo",
    desc: "O resultado: software vivo, gente cuidando, impacto medido no negócio. É onde a Lunar Code mora.",
  },
];

// Opacity floor for layers that have been peeled — they remain as faint ghosts
const GHOST_OPACITY = 0.10;

const ExplodedMoon = ({ progress }) => {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    let raf, last = performance.now();
    const tick = (now) => { setT((p) => p + (now - last) / 1000); last = now; raf = requestAnimationFrame(tick); };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const N = 6;
  const R = 160;
  const ease = (x) => (x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2);

  const peel = (i) => {
    const start = i / N;
    const end = (i + 1) / N;
    return Math.max(0, Math.min(1, (progress - start) / (end - start)));
  };

  const around = (n, fn, phase = 0) => Array.from({ length: n }, (_, i) => fn(i, ((i + phase) / n) * Math.PI * 2));

  // Layers fade from 1.0 to GHOST_OPACITY — creating a transparent echo of past layers
  const peelStyle = (i) => {
    const p = ease(peel(i));
    return {
      opacity: GHOST_OPACITY + (1 - GHOST_OPACITY) * (1 - p),
      transform: `scale(${1 + p * 0.055})`,
      transformOrigin: "center",
      transition: "opacity 0.35s linear, transform 0.35s linear",
      pointerEvents: "none",
    };
  };

  const revealStyle = (i) => {
    if (i === 0) return { transformOrigin: "center" };
    const r = ease(peel(i - 1));
    return {
      transform: `scale(${0.96 + r * 0.04})`,
      transformOrigin: "center",
      transition: "transform 0.35s linear",
    };
  };

  return (
    <div className="moon-stage">
      <svg viewBox="-220 -220 440 440" width="100%" height="100%" style={{ overflow: "visible" }}>
        <defs>
          <clipPath id="moonClip"><circle cx="0" cy="0" r={R} /></clipPath>

          {/* Surface gradients */}
          <radialGradient id="surfaceFill" cx="0.35" cy="0.32">
            <stop offset="0" stopColor="#f5f7ff" />
            <stop offset="0.45" stopColor="#c2cde6" />
            <stop offset="0.92" stopColor="#5a6a8e" />
            <stop offset="1" stopColor="#2a3148" />
          </radialGradient>
          <radialGradient id="craterShade" cx="0.35" cy="0.35">
            <stop offset="0" stopColor="rgba(20,28,50,0.7)" />
            <stop offset="0.7" stopColor="rgba(20,28,50,0.35)" />
            <stop offset="1" stopColor="rgba(20,28,50,0)" />
          </radialGradient>
          <radialGradient id="craterRim" cx="0.35" cy="0.35">
            <stop offset="0.7" stopColor="rgba(255,255,255,0)" />
            <stop offset="0.95" stopColor="rgba(255,255,255,0.25)" />
            <stop offset="1" stopColor="rgba(255,255,255,0)" />
          </radialGradient>
          <radialGradient id="terminatorFill" cx="0.82" cy="0.5" r="0.85">
            <stop offset="0.4" stopColor="rgba(0,0,0,0)" />
            <stop offset="1" stopColor="rgba(0,0,0,0.65)" />
          </radialGradient>

          <radialGradient id="shellFill" cx="0.38" cy="0.35">
            <stop offset="0" stopColor="#5e6678" />
            <stop offset="0.55" stopColor="#353c50" />
            <stop offset="1" stopColor="#0e1018" />
          </radialGradient>

          <radialGradient id="circuitsFill" cx="0.5" cy="0.5">
            <stop offset="0" stopColor="#10213f" />
            <stop offset="0.7" stopColor="#070d1d" />
            <stop offset="1" stopColor="#04060c" />
          </radialGradient>

          <radialGradient id="gearsFill" cx="0.4" cy="0.4">
            <stop offset="0" stopColor="#3d4458" />
            <stop offset="1" stopColor="#0a0e1c" />
          </radialGradient>
          <radialGradient id="gearMetal" cx="0.35" cy="0.35">
            <stop offset="0" stopColor="#d8dde9" />
            <stop offset="0.6" stopColor="#838ba2" />
            <stop offset="1" stopColor="#2a3142" />
          </radialGradient>

          <radialGradient id="matrixFill" cx="0.5" cy="0.5">
            <stop offset="0" stopColor="rgba(91,141,239,0.32)" />
            <stop offset="0.8" stopColor="#080e1c" />
            <stop offset="1" stopColor="#04060c" />
          </radialGradient>

          {/* Chip / core gradients */}
          <radialGradient id="pcbFill" cx="0.5" cy="0.5">
            <stop offset="0" stopColor="#05091a" />
            <stop offset="0.7" stopColor="#030812" />
            <stop offset="1" stopColor="#02060e" />
          </radialGradient>
          <linearGradient id="chipBodyFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#1c2342" />
            <stop offset="0.45" stopColor="#10162e" />
            <stop offset="1" stopColor="#080e1e" />
          </linearGradient>
          <radialGradient id="chipDieFill" cx="0.38" cy="0.32">
            <stop offset="0" stopColor="#1e2c50" />
            <stop offset="0.6" stopColor="#0d162c" />
            <stop offset="1" stopColor="#070910" />
          </radialGradient>
          <linearGradient id="pinFill" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#b8c6dc" />
            <stop offset="0.5" stopColor="#7888a8" />
            <stop offset="1" stopColor="#3c4862" />
          </linearGradient>

          <radialGradient id="coreCorona" cx="0.5" cy="0.5">
            <stop offset="0" stopColor="rgba(255,255,255,0.9)" />
            <stop offset="0.25" stopColor="rgba(174,202,255,0.65)" />
            <stop offset="0.6" stopColor="rgba(91,141,239,0.3)" />
            <stop offset="1" stopColor="rgba(91,141,239,0)" />
          </radialGradient>
          <radialGradient id="farHalo" cx="0.5" cy="0.5">
            <stop offset="0.35" stopColor="rgba(91,141,239,0)" />
            <stop offset="0.6" stopColor="rgba(91,141,239,0.2)" />
            <stop offset="1" stopColor="rgba(91,141,239,0)" />
          </radialGradient>

          <filter id="neonGlow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="1.4" result="b" />
            <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
          <filter id="softGlow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="5" />
          </filter>
          <filter id="chipGlow" x="-40%" y="-40%" width="180%" height="180%">
            <feGaussianBlur stdDeviation="2" result="b" />
            <feMerge><feMergeNode in="b" /><feMergeNode in="SourceGraphic" /></feMerge>
          </filter>
        </defs>

        {/* === Background halo + drifting starfield === */}
        <circle r="215" fill="url(#farHalo)" opacity={0.5 + progress * 0.5} />
        <g transform={`rotate(${t * 0.5})`}>
          {around(38, (i, a) => {
            const r = 192 + ((i * 23) % 32);
            const x = Math.cos(a + i * 0.11) * r;
            const y = Math.sin(a + i * 0.11) * r;
            const tw = 0.35 + 0.55 * (0.5 + 0.5 * Math.sin(t * 1.5 + i * 0.7));
            return <circle key={i} cx={x} cy={y} r={0.5 + (i % 4) * 0.3} fill="rgba(232,236,245,0.9)" opacity={tw} />;
          })}
        </g>

        {/* === Layer 5 · Chip · Lunar Code (always at bottom) === */}
        <g style={revealStyle(5)}>
          <circle r={165 + Math.sin(t * 1.2) * 10} fill="url(#coreCorona)" opacity={0.15 + ease(peel(4)) * 0.5} />
          <circle r={118 + Math.sin(t * 1.8 + 1) * 7} fill="url(#coreCorona)" opacity={0.28 + ease(peel(4)) * 0.35} />

          {/* PCB disc base */}
          <circle r={R} fill="url(#pcbFill)" />

          <g clipPath="url(#moonClip)">
            {/* PCB substrate grid */}
            <g stroke="rgba(0,180,100,0.06)" strokeWidth="0.5" fill="none">
              {Array.from({ length: 17 }, (_, i) => i * 20 - 160).map(x => (
                <line key={`vg${x}`} x1={x} y1="-160" x2={x} y2="160" />
              ))}
              {Array.from({ length: 17 }, (_, i) => i * 20 - 160).map(y => (
                <line key={`hg${y}`} x1="-160" y1={y} x2="160" y2={y} />
              ))}
            </g>

            {/* PCB traces from chip pins to disc edge */}
            <g stroke="rgba(0,200,140,0.28)" strokeWidth="0.9" fill="none">
              {/* Top */}
              <path d="M-56,-66 L-56,-125" />
              <path d="M-40,-66 L-40,-88 L-92,-88" />
              <path d="M-8,-66 L-8,-135" />
              <path d="M8,-66 L8,-82 L52,-82 L52,-145" />
              <path d="M40,-66 L40,-78 L88,-78 L88,-145" />
              <path d="M56,-66 L56,-108 L115,-108" />
              {/* Bottom */}
              <path d="M-56,66 L-56,122" />
              <path d="M-24,66 L-24,82 L-78,82 L-78,145" />
              <path d="M8,66 L8,95 L48,95 L48,145" />
              <path d="M56,66 L56,118 L-95,118" />
              {/* Left */}
              <path d="M-96,-30 L-148,-30" />
              <path d="M-96,0 L-158,0" />
              <path d="M-96,30 L-145,30" />
              {/* Right */}
              <path d="M96,-15 L145,-15" />
              <path d="M96,0 L155,0" />
              <path d="M96,15 L128,15 L128,58" />
            </g>

            {/* Trace end-pads */}
            {[
              [-56,-125],[-92,-88],[-8,-135],[52,-145],[88,-145],[115,-108],
              [-56,122],[-78,145],[48,145],[-95,118],
              [-148,-30],[-158,0],[-145,30],[145,-15],[155,0],[128,58],
            ].map(([x, y], i) => (
              <circle key={i} cx={x} cy={y} r="3.5"
                fill="rgba(0,200,140,0.1)" stroke="rgba(0,200,140,0.4)" strokeWidth="0.6" />
            ))}

            {/* Passive SMD components on PCB */}
            {[
              { x: -115, y: -44 },{ x: 108, y: -50 },
              { x: -108, y: 50 }, { x: 112, y: 54 },
              { x: -30, y: -102 },{ x: 36, y: -100 },
              { x: -36, y: 98 },  { x: 22, y: 102 },
            ].map(({ x, y }, i) => {
              const horiz = Math.abs(y) > 90;
              const w = horiz ? 7 : 12, h = horiz ? 12 : 7;
              return (
                <g key={i} transform={`translate(${x},${y})`}>
                  <rect x={-w/2} y={-h/2} width={w} height={h} rx="1.5"
                    fill="rgba(38,48,78,0.9)" stroke="rgba(100,130,200,0.4)" strokeWidth="0.5" />
                  <line x1={-w/2-4} y1="0" x2={-w/2} y2="0" stroke="rgba(150,175,220,0.5)" strokeWidth="0.8" />
                  <line x1={w/2} y1="0" x2={w/2+4} y2="0" stroke="rgba(150,175,220,0.5)" strokeWidth="0.8" />
                </g>
              );
            })}

            {/* Chip drop shadow */}
            <rect x="-83" y="-53" width="166" height="106" rx="8"
              fill="rgba(0,0,0,0.55)" transform="translate(4,5)" />

            {/* ── Chip body ── */}
            <rect x="-83" y="-53" width="166" height="106" rx="8"
              fill="url(#chipBodyFill)"
              stroke="rgba(91,141,239,0.88)" strokeWidth="1.5" />

            {/* Chip edge highlight */}
            <rect x="-83" y="-53" width="166" height="106" rx="8"
              fill="none" stroke="rgba(174,202,255,0.25)" strokeWidth="0.5"
              transform="translate(-0.5,-0.5)" />

            {/* Pin 1 corner notch + marker */}
            <path d="M-83 -53 L-66 -53 L-83 -36 Z" fill="rgba(0,0,0,0.7)" />
            <circle cx="-73" cy="-43" r="2.5" fill="rgba(174,202,255,0.55)" />

            {/* ── Pins · top (8) ── */}
            {[-56,-40,-24,-8,8,24,40,56].map((x, i) => (
              <g key={`pt${i}`}>
                <rect x={x-4} y="-67" width="8" height="14" rx="2.5"
                  fill="url(#pinFill)" stroke="rgba(200,215,240,0.35)" strokeWidth="0.4" />
                <line x1={x} y1="-67" x2={x} y2="-53"
                  stroke="rgba(91,141,239,0.4)" strokeWidth="0.6" />
              </g>
            ))}
            {/* ── Pins · bottom (8) ── */}
            {[-56,-40,-24,-8,8,24,40,56].map((x, i) => (
              <g key={`pb${i}`}>
                <rect x={x-4} y="53" width="8" height="14" rx="2.5"
                  fill="url(#pinFill)" stroke="rgba(200,215,240,0.35)" strokeWidth="0.4" />
                <line x1={x} y1="53" x2={x} y2="67"
                  stroke="rgba(91,141,239,0.4)" strokeWidth="0.6" />
              </g>
            ))}
            {/* ── Pins · left (5) ── */}
            {[-30,-15,0,15,30].map((y, i) => (
              <g key={`pl${i}`}>
                <rect x="-97" y={y-4} width="14" height="8" rx="2.5"
                  fill="url(#pinFill)" stroke="rgba(200,215,240,0.35)" strokeWidth="0.4" />
                <line x1="-97" y1={y} x2="-83" y2={y}
                  stroke="rgba(91,141,239,0.4)" strokeWidth="0.6" />
              </g>
            ))}
            {/* ── Pins · right (5) ── */}
            {[-30,-15,0,15,30].map((y, i) => (
              <g key={`pr${i}`}>
                <rect x="83" y={y-4} width="14" height="8" rx="2.5"
                  fill="url(#pinFill)" stroke="rgba(200,215,240,0.35)" strokeWidth="0.4" />
                <line x1="83" y1={y} x2="97" y2={y}
                  stroke="rgba(91,141,239,0.4)" strokeWidth="0.6" />
              </g>
            ))}

            {/* ── Die area ── */}
            <rect x="-56" y="-37" width="112" height="74" rx="4"
              fill="url(#chipDieFill)"
              stroke="rgba(91,141,239,0.38)" strokeWidth="0.8" />

            {/* Die internal grid */}
            <g stroke="rgba(91,141,239,0.1)" strokeWidth="0.5" fill="none">
              {[-37,0,37].map(x => <line key={x} x1={x} y1="-37" x2={x} y2="37" />)}
              {[-25,0,25].map(y => <line key={y} x1="-56" y1={y} x2="56" y2={y} />)}
            </g>

            {/* Die sub-blocks */}
            {[
              [-54,-35,22,20],[-54,15,22,20],
              [32,-35,22,20],[32,15,22,20],
            ].map(([x,y,w,h], i) => (
              <rect key={i} x={x} y={y} width={w} height={h} rx="2"
                fill="rgba(91,141,239,0.07)"
                stroke="rgba(91,141,239,0.22)" strokeWidth="0.5" />
            ))}

            {/* ── LUNAR CODE text ── */}
            <text x="0" y="-6" textAnchor="middle"
              fontFamily="JetBrains Mono, monospace"
              fontSize="14" fontWeight="700"
              fill="rgba(255,255,255,0.96)"
              letterSpacing="5"
              filter="url(#chipGlow)">LUNAR</text>
            <text x="0" y="13" textAnchor="middle"
              fontFamily="JetBrains Mono, monospace"
              fontSize="14" fontWeight="700"
              fill="var(--accent-2)"
              letterSpacing="5"
              filter="url(#chipGlow)">CODE</text>

            {/* Model / part number */}
            <text x="0" y="30" textAnchor="middle"
              fontFamily="JetBrains Mono, monospace"
              fontSize="6.5"
              fill="rgba(138,175,255,0.48)"
              letterSpacing="2">LC‑01 · CUSTOM</text>

            {/* Pin 1 label */}
            <text x="-74" y="-20" textAnchor="middle"
              fontFamily="JetBrains Mono, monospace"
              fontSize="5" fill="rgba(138,175,255,0.38)" letterSpacing="1">1</text>

            {/* Status LEDs */}
            {[{ x:75, y:-43, c:"#22ee88"}, {x:-75, y:-43, c:"#5b8def"}].map(({x,y,c},i)=>{
              const on = Math.sin(t * (2.2 + i * 1.5)) > 0.15;
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r="5" fill={c} opacity={on ? 0.18 : 0.04} />
                  <circle cx={x} cy={y} r="2.8" fill={c} opacity={on ? 0.92 : 0.22}
                    filter="url(#neonGlow)" />
                </g>
              );
            })}

            {/* Data-packet pulses orbiting the chip */}
            {around(6, (i, a) => {
              const speed = 0.65 + i * 0.12;
              const phase = (t * speed + i * (1/6)) % 1;
              const ri = 100, ro = 150;
              const rr = ri + (ro - ri) * phase;
              return (
                <circle key={i}
                  cx={Math.cos(a) * rr} cy={Math.sin(a) * rr}
                  r="2.4" fill="var(--accent-2)"
                  opacity={(1 - phase) * 0.8}
                  filter="url(#neonGlow)" />
              );
            })}
          </g>

          {/* Rim */}
          <circle r={R} fill="none" stroke="rgba(91,141,239,0.6)" strokeWidth="1.5"
            filter="url(#neonGlow)" />
        </g>

        {/* === Layer 4 · Matrix · data rain (ghost persists after peel) === */}
        <g style={{ ...peelStyle(4), ...revealStyle(4) }}>
          <circle r={R} fill="url(#matrixFill)" />
          <g clipPath="url(#moonClip)">
            {Array.from({ length: 13 }).map((_, col) => {
              const x = -150 + col * 25;
              const speed = 32 + (col % 3) * 14;
              const offset = (t * speed + col * 31) % 320;
              return Array.from({ length: 14 }).map((_, row) => {
                const y = -160 + ((row * 22) + offset) % 320;
                const fade = 1 - row / 14;
                const ch = row === 0 ? "1" : (col * 7 + row * 11) % 2;
                return (
                  <text key={`${col}-${row}`} x={x} y={y}
                    fontFamily="JetBrains Mono, monospace" fontSize="11"
                    fill={row === 0 ? "#ffffff" : "var(--accent-2)"}
                    opacity={fade}>
                    {ch}
                  </text>
                );
              });
            })}
          </g>
          <circle r={R} fill="none" stroke="rgba(138,175,255,0.45)" strokeWidth="0.8" />
          <circle r={R - 8} fill="none" stroke="rgba(138,175,255,0.18)" strokeWidth="0.5" strokeDasharray="2 5" />
        </g>

        {/* === Layer 3 · Gears === */}
        <g style={{ ...peelStyle(3), ...revealStyle(3) }}>
          <circle r={R} fill="url(#gearsFill)" />
          <g clipPath="url(#moonClip)">
            <Gear cx={-58} cy={-42} r={52} teeth={14} rotation={t * 26} fill="url(#gearMetal)" />
            <Gear cx={54} cy={28} r={44} teeth={12} rotation={-t * 32 + 12} fill="url(#gearMetal)" />
            <Gear cx={-18} cy={72} r={32} teeth={10} rotation={t * 42 + 18} fill="url(#gearMetal)" />
            <Gear cx={70} cy={-78} r={22} teeth={8} rotation={-t * 50} fill="url(#gearMetal)" />
          </g>
          <circle r={R} fill="none" stroke="rgba(138,175,255,0.35)" strokeWidth="0.8" />
        </g>

        {/* === Layer 2 · Circuits · neon traces === */}
        <g style={{ ...peelStyle(2), ...revealStyle(2) }}>
          <circle r={R} fill="url(#circuitsFill)" />
          <g clipPath="url(#moonClip)">
            <g stroke="var(--accent-2)" strokeWidth="1.4" fill="none" filter="url(#neonGlow)" opacity="0.95">
              <path d="M-160 -55 L-90 -55 L-65 -78 L0 -78 L22 -55 L160 -55" />
              <path d="M-160 45 L-95 45 L-72 68 L72 68 L95 45 L160 45" />
              <path d="M-55 -160 L-55 -100 L-32 -78" />
              <path d="M55 -160 L55 -125 L78 -100 L78 -55" />
              <path d="M-78 160 L-78 100 L-45 68" />
              <path d="M90 160 L90 110 L55 78" />
              <path d="M0 0 L0 -78 M0 0 L0 78 M0 0 L-78 0 M0 0 L78 0" />
            </g>
            {[
              [-65,-78],[65,-78],[-78,68],[78,68],
              [-55,-160],[55,-160],[-78,160],[90,160],
              [-160,-55],[160,-55],[-160,45],[160,45],
              [0,0],
            ].map(([x, y], i) => {
              const isPulse = Math.floor(t * 1.5) % 13 === i;
              return (
                <g key={i}>
                  <circle cx={x} cy={y} r={isPulse ? 7 : 6} fill="rgba(91,141,239,0.25)" />
                  <circle cx={x} cy={y} r={isPulse ? 4 : 3} fill="var(--accent-2)" filter="url(#neonGlow)" />
                </g>
              );
            })}
          </g>
          <circle r={R} fill="none" stroke="rgba(138,175,255,0.45)" strokeWidth="0.8" />
        </g>

        {/* === Layer 1 · Shell · titanium panels + rivets === */}
        <g style={{ ...peelStyle(1), ...revealStyle(1) }}>
          <circle r={R} fill="url(#shellFill)" />
          <g clipPath="url(#moonClip)" stroke="rgba(255,255,255,0.09)" strokeWidth="0.8" fill="none">
            {around(12, (i, a) => (
              <line key={i}
                x1={Math.cos(a) * 56} y1={Math.sin(a) * 56}
                x2={Math.cos(a) * R} y2={Math.sin(a) * R}
              />
            ))}
            <circle r="56" />
            <circle r="108" />
          </g>
          {around(28, (i, a) => (
            <circle key={i}
              cx={Math.cos(a) * 130} cy={Math.sin(a) * 130}
              r="2" fill="#1a1e2e" stroke="#9aa2b8" strokeWidth="0.5"
            />
          ))}
          <circle r="42" fill="none" stroke="var(--accent-2)" strokeWidth="0.6" opacity={0.25 + ease(peel(1)) * 0.4} />
          <text x="0" y="-128" textAnchor="middle"
            fill="rgba(255,255,255,0.45)"
            fontFamily="JetBrains Mono, monospace" fontSize="9" letterSpacing="2">
            LUNAR · 02
          </text>
          <circle r={R} fill="none" stroke="rgba(255,255,255,0.18)" strokeWidth="0.8" />
        </g>

        {/* === Layer 0 · Surface · lunar crust (topmost) === */}
        <g style={peelStyle(0)}>
          <circle r={R} fill="url(#surfaceFill)" />
          <g clipPath="url(#moonClip)">
            {[
              [-46,-58,26],[38,24,36],[-70,72,22],[70,-94,17],
              [96,82,12],[-108,-22,10],[22,118,11],[-22,-128,8],
              [-128,46,9],[118,-34,7],[60,130,6],[-58,0,5],
            ].map(([x, y, s], i) => (
              <g key={i}>
                <ellipse cx={x} cy={y} rx={s} ry={s * 0.88} fill="url(#craterShade)" />
                <ellipse cx={x} cy={y} rx={s} ry={s * 0.88} fill="url(#craterRim)" />
              </g>
            ))}
          </g>
          <circle r={R} fill="url(#terminatorFill)" opacity="0.55" />
          <circle r={R} fill="none" stroke="rgba(255,255,255,0.22)" strokeWidth="0.8" />
          <circle r={R - 2} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="0.4" />
        </g>

        <circle r={R} fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.5" />
      </svg>

      <style>{moonStyles}</style>
    </div>
  );
};

const Gear = ({ cx, cy, r, teeth, rotation, fill }) => {
  const inner = r * 0.78;
  const path = [];
  const step = (Math.PI * 2) / (teeth * 2);
  for (let i = 0; i < teeth * 2; i++) {
    const a = i * step;
    const rad = i % 2 === 0 ? r : inner;
    path.push((i === 0 ? "M" : "L") + (Math.cos(a) * rad).toFixed(2) + "," + (Math.sin(a) * rad).toFixed(2));
  }
  path.push("Z");
  return (
    <g transform={`translate(${cx} ${cy}) rotate(${rotation})`}>
      <path d={path.join(" ")} fill={fill} stroke="rgba(255,255,255,0.15)" strokeWidth="0.6" />
      <circle cx="0" cy="0" r={r * 0.4} fill="rgba(10,14,28,0.8)" stroke="rgba(255,255,255,0.2)" strokeWidth="0.6" />
      <circle cx="0" cy="0" r={r * 0.18} fill="var(--accent-2)" opacity="0.6" />
      {Array.from({ length: 5 }).map((_, i) => {
        const a = (i / 5) * Math.PI * 2;
        return <circle key={i} cx={Math.cos(a) * r * 0.6} cy={Math.sin(a) * r * 0.6} r="2" fill="rgba(255,255,255,0.4)" />;
      })}
    </g>
  );
};


const Anatomia = () => {
  const sectionRef = React.useRef(null);
  const rightRef = React.useRef(null);
  const itemRefs = React.useRef([]);
  const progress = useScrollProgress(sectionRef);

  const activeIdx = Math.min(
    LAYERS.length - 1,
    Math.max(0, Math.floor(progress * LAYERS.length * 1.05))
  );

  React.useEffect(() => {
    const el = itemRefs.current[activeIdx];
    const container = rightRef.current;
    if (!el || !container) return;
    const containerRect = container.getBoundingClientRect();
    const elRect = el.getBoundingClientRect();
    const relativeTop = elRect.top - containerRect.top + container.scrollTop;
    container.scrollTop = Math.max(0, relativeTop - containerRect.height / 2 + elRect.height / 2);
  }, [activeIdx]);

  return (
    <section id="anatomia" className="anatomia" ref={sectionRef}>
      <div className="anatomia-sticky">
        <div className="wrap anatomia-inner">
          <div className="anatomia-left">
            <ExplodedMoon progress={progress} />
            <div className="anatomia-progress" aria-hidden>
              <div className="anatomia-progress-bar" style={{ height: `${progress * 100}%` }} />
            </div>
          </div>

          <div className="anatomia-right" ref={rightRef}>
            <span className="eyebrow">Anatomia · 04</span>
            <h2>Software em <span className="italic">camadas</span>.</h2>
            <p className="lead" style={{ marginTop: 12, marginBottom: "clamp(16px, 3vh, 36px)" }}>
              Cada sistema que entregamos é desmontável — pensado em camadas que conversam entre si, mas evoluem independentemente. Role para ver o que tem dentro.
            </p>

            <ol className="anatomia-list">
              {LAYERS.map((l, i) => (
                <li key={l.id} ref={el => { itemRefs.current[i] = el; }} className={`anatomia-item ${i === activeIdx ? "active" : ""} ${i < activeIdx ? "passed" : ""}`}>
                  <div className="ai-marker">
                    <span className="ai-dot" />
                    <span className="ai-line" />
                  </div>
                  <div className="ai-body">
                    <div className="ai-num">{String(i + 1).padStart(2, "0")}</div>
                    <h3>{l.title}</h3>
                    <p>{l.desc}</p>
                  </div>
                </li>
              ))}
            </ol>
          </div>
        </div>
      </div>

      <style>{anatomiaStyles}</style>
    </section>
  );
};

const anatomiaStyles = `
.anatomia {
  height: 300vh;
  position: relative;
  background: linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 50%, var(--bg) 100%);
  padding: 0;
}
.anatomia-sticky {
  position: sticky;
  top: 0;
  height: 100vh;
  display: flex;
  align-items: flex-start;
  padding-top: clamp(48px, 7vh, 84px);
  overflow: hidden;
  z-index: 1;
}
.anatomia-sticky::before {
  content: "";
  position: absolute; inset: 0;
  background:
    radial-gradient(ellipse 50% 40% at 30% 50%, rgba(var(--accent-glow), 0.12), transparent 70%);
  pointer-events: none;
}
.anatomia-inner {
  display: grid;
  grid-template-columns: 1.1fr 1fr;
  gap: 60px;
  align-items: center;
  width: 100%;
}
@media (max-width: 980px) {
  .anatomia { height: auto; padding: 120px 0; }
  .anatomia-sticky { position: relative; height: auto; padding-top: 0; }
  .anatomia-inner { grid-template-columns: 1fr; gap: 80px; }
}

.anatomia-left {
  position: relative;
  height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
@media (max-width: 980px) {
  .anatomia-left { height: 80vh; min-height: 600px; }
}

.anatomia-progress {
  position: absolute;
  left: 0;
  top: 10%;
  bottom: 10%;
  width: 1px;
  background: var(--border);
}
.anatomia-progress-bar {
  width: 100%;
  background: linear-gradient(180deg, var(--accent-2), var(--accent));
  transition: height 0.1s linear;
}
@media (max-width: 980px) { .anatomia-progress { display: none; } }

@media (max-height: 750px) {
  .anatomia-sticky { padding-top: 40px; }
  .anatomia-item { padding: 6px 0; }
  .anatomia-item h3 { font-size: clamp(18px, 1.8vh, 24px); }
  .anatomia-right .lead { display: none; }
}

.anatomia-right {
  padding-left: 20px;
  overflow-y: auto;
  max-height: calc(100vh - clamp(48px, 7vh, 84px) - 20px);
  -ms-overflow-style: none;
  scrollbar-width: none;
}
.anatomia-right::-webkit-scrollbar { display: none; }
.anatomia-list {
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 16px;
}
.anatomia-item {
  display: grid;
  grid-template-columns: 28px 1fr;
  gap: 16px;
  padding: clamp(8px, 1.4vh, 14px) 0;
  opacity: 0.35;
  transform: translateX(0px);
  transition: opacity 0.55s var(--ease-out), transform 0.55s var(--ease-out);
}
.anatomia-item.passed { opacity: 0.5; }
.anatomia-item.active {
  opacity: 1;
  transform: translateX(5px);
}

.ai-marker {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.ai-dot {
  width: 10px; height: 10px;
  border-radius: 50%;
  background: var(--text-faint);
  margin-top: 8px;
  transition: all 0.45s var(--ease-out);
}
.anatomia-item.active .ai-dot {
  background: var(--accent-2);
  box-shadow: 0 0 0 4px rgba(91,141,239,0.18), 0 0 18px var(--accent-2);
  transform: scale(1.5);
}
.anatomia-item.passed .ai-dot { background: var(--accent-deep); }
.ai-line {
  flex: 1;
  width: 1px;
  background: var(--border);
  margin-top: 6px;
}
.anatomia-item:last-child .ai-line { display: none; }
.ai-body { padding-bottom: 8px; }
.ai-num {
  font-family: var(--font-mono);
  font-size: 11px;
  letter-spacing: 0.15em;
  color: var(--text-faint);
  margin-bottom: 4px;
  transition: color 0.4s;
}
.anatomia-item.active .ai-num { color: var(--accent-2); }
.anatomia-item h3 {
  font-family: var(--font-display);
  font-size: clamp(22px, 2.2vw, 28px);
  font-weight: 400;
  letter-spacing: -0.01em;
  color: var(--text);
  margin-bottom: 6px;
  transition: color 0.4s;
}
.anatomia-item.active h3 { color: var(--text); }
.anatomia-item p {
  font-size: 14px;
  color: var(--text-dim);
  line-height: 1.6;
  max-width: 400px;
  opacity: 0;
  max-height: 0;
  overflow: hidden;
  margin-top: 0;
  margin-bottom: 0;
  transition: opacity 0.5s var(--ease-out), max-height 0.5s var(--ease-out);
}
.anatomia-item.active p { opacity: 1; max-height: 120px; }
.anatomia-item.passed p { opacity: 0.52; max-height: 120px; }
`;


const moonStyles = `
.moon-stage {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.moon-stage svg {
  width: min(100%, 560px);
  height: auto;
  filter: drop-shadow(0 30px 60px rgba(0, 0, 0, 0.55));
}
.moon-stage svg g {
  transition: opacity 0.45s var(--ease-out);
}

@media (max-width: 980px) {
  .moon-stage svg { width: min(86%, 420px); }
}
`;

window.Anatomia = Anatomia;
