// VeryPay — Method (scroll-pinned 4 steps)
function Method() {
  const steps = [
    {
      n: "01",
      title: "Diagnóstico",
      body: "Conversa de 30 minutos. A gente entende seu volume, ticket médio, prazo de venda, divisão entre crédito/débito/Pix, e onde está o dinheiro que você não vê."
    },
    {
      n: "02",
      title: "Escolha do produto",
      body: "Com base no diagnóstico, montamos a configuração ideal: adquirente, plano, antecipação, split, conta integrada. Você não escolhe entre opções — recebe a recomendação."
    },
    {
      n: "03",
      title: "Implantação",
      body: "Maquininha entregue, conta criada, integrações ligadas, time treinado. Tudo em até 5 dias úteis. Sem você precisar correr atrás de boleto, manual ou suporte."
    },
    {
      n: "04",
      title: "Relacionamento contínuo",
      body: "Mensalmente revisamos suas métricas. Trimestralmente ajustamos o produto se algo mudou no seu negócio. Não é suporte — é gestão ativa."
    }
  ];

  const wrapRef = useRef(null);
  const [active, setActive] = useState(0);
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const onScroll = () => {
      if (!wrapRef.current) return;
      const rect = wrapRef.current.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      if (total <= 0) return;
      const scrolled = Math.max(0, Math.min(total, -rect.top));
      const p = scrolled / total;
      setProgress(p);
      const idx = Math.min(steps.length - 1, Math.floor(p * steps.length * 0.999));
      setActive(idx);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);

  const current = steps[active];

  return (
    <section id="metodo" className="light" style={{ overflow: "hidden", paddingBottom: 0 }}>
      <div className="container">
        <SectionMeta label="MÉTODO" index="05" dark />
        <h2 className="display ink" style={{ maxWidth: "18ch" }}>
          <Reveal>Quatro passos para</Reveal>
          <br />
          <Reveal delay={0.1}>recebimento sob medida.</Reveal>
        </h2>

        {/* Desktop pinned */}
        <div
          ref={wrapRef}
          className="method-track method-desktop"
          style={{ minHeight: `${steps.length * 100}vh`, maxHeight: `${steps.length * 120}vh`, position: "relative" }}
        >
          <div
            className="method-progress"
            style={{ position: "sticky", top: 80, marginTop: 40 }}
          >
            <div className="fill" style={{ width: `${(active + 1) * (100 / steps.length)}%` }}></div>
          </div>

          <div
            style={{
              position: "sticky",
              top: 130,
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              gap: 80,
              alignItems: "center",
              height: "calc(100vh - 200px)",
              minHeight: 540
            }}
            className="method-sticky"
          >
            <div className="method-left">
              <div className="step-num" style={{ position: "relative" }}>
                <span className="barlet"></span>
                {current.n}
              </div>
              <h3>{current.title}</h3>
              <p>{current.body}</p>
              <div style={{ marginTop: 28, display: "flex", gap: 8, alignItems: "center" }}>
                {steps.map((_, i) => (
                  <span
                    key={i}
                    style={{
                      width: i === active ? 28 : 6,
                      height: 4,
                      background: i <= active ? "var(--magenta)" : "rgba(15,21,33,0.15)",
                      transition: "all 0.4s cubic-bezier(.2,.8,.2,1)",
                      borderRadius: 2
                    }}
                  ></span>
                ))}
                <span className="mono" style={{ fontSize: 11, color: "rgba(15,21,33,0.45)", marginLeft: 12 }}>
                  PASSO {String(active + 1).padStart(2, "0")} / {String(steps.length).padStart(2, "0")}
                </span>
              </div>
            </div>
            <div className="method-illust">
              <MethodIllust step={active} />
            </div>
          </div>
        </div>

        {/* Mobile accordion */}
        <div className="method-mobile" style={{ marginTop: 40 }}>
          {steps.map((s, i) => (
            <div key={s.n} style={{ borderTop: "1px solid rgba(15,21,33,0.1)", padding: "28px 0" }}>
              <div style={{ display: "flex", gap: 18 }}>
                <span className="mono" style={{ fontSize: 14, color: "var(--magenta)", letterSpacing: "0.08em" }}>
                  {s.n}
                </span>
                <div style={{ flex: 1 }}>
                  <h3 style={{
                    fontFamily: "var(--font-display)", fontWeight: 800,
                    fontSize: 26, color: "var(--ink)", marginBottom: 12, letterSpacing: "-0.02em"
                  }}>{s.title}</h3>
                  <p style={{ fontSize: 16, lineHeight: 1.55, color: "rgba(15,21,33,0.7)" }}>{s.body}</p>
                  <div style={{ height: 220, marginTop: 22, background: "var(--offwhite-2)", borderRadius: 3, overflow: "hidden" }}>
                    <MethodIllust step={i} />
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <style>{`
        @media (max-width: 1024px) {
          .method-desktop { display: none; }
        }
        @media (min-width: 1025px) {
          .method-mobile { display: none; }
        }
      `}</style>
    </section>
  );
}

function MethodIllust({ step }) {
  return (
    <div style={{ position: "relative", width: "100%", height: "100%", minHeight: 340 }}>
      {[IllustDiagnostic, IllustChoose, IllustImplant, IllustRelation].map((C, i) => (
        <div
          key={i}
          style={{
            position: "absolute",
            inset: 0,
            opacity: i === step ? 1 : 0,
            transform: `scale(${i === step ? 1 : 0.97})`,
            transition: "opacity 0.55s, transform 0.7s cubic-bezier(.2,.8,.2,1)",
            pointerEvents: i === step ? "auto" : "none"
          }}
        >
          <C active={i === step} />
        </div>
      ))}
    </div>
  );
}

function IllustDiagnostic({ active }) {
  // lupa magenta sobre gráfico de vendas com pontos brilhando
  const [t, setT] = useState(0);
  useEffect(() => {
    if (!active) return;
    let raf;
    let start = performance.now();
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active]);

  const lensX = 0.3 + Math.sin(t * 0.7) * 0.25;
  const lensY = 0.5 + Math.cos(t * 0.6) * 0.18;
  return (
    <svg viewBox="0 0 600 420" className="illust-svg" preserveAspectRatio="xMidYMid meet">
      <defs>
        <linearGradient id="bars" x1="0" y1="1" x2="0" y2="0">
          <stop offset="0" stopColor="rgba(39,102,123,0.4)" />
          <stop offset="1" stopColor="rgba(39,102,123,0.9)" />
        </linearGradient>
      </defs>
      {/* faint grid */}
      {Array.from({ length: 5 }).map((_, i) => (
        <line key={i} x1="40" x2="560" y1={80 + i * 70} y2={80 + i * 70} stroke="rgba(15,21,33,0.06)" />
      ))}
      {/* bars */}
      {Array.from({ length: 14 }).map((_, i) => {
        const h = 40 + Math.abs(Math.sin(i * 1.3 + 1)) * 200;
        return <rect key={i} x={50 + i * 36} y={400 - h} width="22" height={h} fill="url(#bars)" rx="1" />;
      })}
      {/* shining points */}
      {[2, 5, 9].map((i) => {
        const h = 40 + Math.abs(Math.sin(i * 1.3 + 1)) * 200;
        return (
          <circle key={i} cx={61 + i * 36} cy={400 - h} r="6" fill="#EE4389">
            <animate attributeName="r" values="4;8;4" dur="2s" repeatCount="indefinite" />
            <animate attributeName="opacity" values="0.6;1;0.6" dur="2s" repeatCount="indefinite" />
          </circle>
        );
      })}
      {/* lens */}
      <g transform={`translate(${lensX * 600}, ${lensY * 420})`}>
        <circle r="62" fill="rgba(238,67,137,0.10)" stroke="#BA2F7D" strokeWidth="2.2" />
        <line x1="44" y1="44" x2="86" y2="86" stroke="#BA2F7D" strokeWidth="6" strokeLinecap="round" />
        <circle r="62" fill="none" stroke="rgba(238,67,137,0.35)" strokeDasharray="4 6" strokeWidth="1">
          <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="14s" repeatCount="indefinite" />
        </circle>
      </g>
    </svg>
  );
}

function IllustChoose({ active }) {
  return (
    <svg viewBox="0 0 600 420" className="illust-svg">
      <defs>
        <filter id="glow"><feGaussianBlur stdDeviation="6" /></filter>
      </defs>
      {/* fan of cards */}
      {[-3, -2, -1, 1, 2, 3].map((i) => (
        <g key={i} transform={`translate(${300 + i * 22}, ${220 + Math.abs(i) * 12}) rotate(${i * 7})`}>
          <rect x="-70" y="-95" width="140" height="190" rx="6" fill="#EAE5DE" stroke="rgba(15,21,33,0.12)" />
          <rect x="-56" y="-78" width="60" height="6" fill="rgba(15,21,33,0.18)" />
          <rect x="-56" y="-62" width="100" height="4" fill="rgba(15,21,33,0.10)" />
        </g>
      ))}
      {/* selected card with glow */}
      <g transform="translate(300, 180)">
        <rect x="-80" y="-110" width="160" height="220" rx="6" fill="#fff" stroke="#BA2F7D" strokeWidth="2" filter="url(#glow)" opacity="0.4" />
        <rect x="-80" y="-110" width="160" height="220" rx="6" fill="#fff" stroke="#BA2F7D" strokeWidth="2" />
        <text x="-66" y="-78" fontFamily="Geist Mono" fontSize="11" fill="#BA2F7D" letterSpacing="1.2">RECOMENDADO</text>
        <rect x="-66" y="-62" width="90" height="8" fill="rgba(15,21,33,0.4)" />
        <rect x="-66" y="-44" width="120" height="4" fill="rgba(15,21,33,0.12)" />
        <rect x="-66" y="-32" width="100" height="4" fill="rgba(15,21,33,0.12)" />
        {/* checkmark */}
        <circle cx="0" cy="60" r="22" fill="#BA2F7D" />
        <path d="M -10 60 L -2 68 L 12 52" stroke="#fff" strokeWidth="3" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </g>
    </svg>
  );
}

function IllustImplant({ active }) {
  const [step, setStep] = useState(0);
  useEffect(() => {
    if (!active) return;
    setStep(0);
    const ints = [];
    for (let i = 1; i <= 5; i++) {
      ints.push(setTimeout(() => setStep(i), i * 350));
    }
    return () => ints.forEach(clearTimeout);
  }, [active]);

  return (
    <svg viewBox="0 0 600 420" className="illust-svg">
      <text x="60" y="120" fontFamily="Geist Mono" fontSize="12" fill="rgba(15,21,33,0.5)" letterSpacing="1.2">IMPLANTAÇÃO / 5 DIAS</text>
      {/* timeline line */}
      <line x1="80" y1="220" x2="520" y2="220" stroke="rgba(15,21,33,0.15)" strokeWidth="2" />
      <line x1="80" y1="220" x2={80 + (step * 110)} y2="220" stroke="#BA2F7D" strokeWidth="2"
        style={{ transition: "all 0.4s" }} />

      {[1, 2, 3, 4, 5].map((d, i) => {
        const x = 80 + i * 110;
        const done = step >= d;
        return (
          <g key={d}>
            <circle
              cx={x}
              cy="220"
              r={done ? 16 : 10}
              fill={done ? "#BA2F7D" : "#fff"}
              stroke={done ? "#BA2F7D" : "rgba(15,21,33,0.2)"}
              strokeWidth="2"
              style={{ transition: "all 0.4s cubic-bezier(.2,.8,.2,1)" }}
            />
            {done && (
              <path d={`M ${x - 6} 220 L ${x - 2} 224 L ${x + 6} 215`}
                stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" />
            )}
            <text x={x} y="270" textAnchor="middle" fontFamily="Geist Mono" fontSize="11" fill={done ? "#BA2F7D" : "rgba(15,21,33,0.45)"} letterSpacing="1.2">D+{d}</text>
            <text x={x} y="180" textAnchor="middle" fontFamily="Geist" fontSize="13" fontWeight="600" fill="#0F1521" opacity={done ? 1 : 0.4} style={{ transition: "opacity 0.4s" }}>
              {["Setup", "Conta", "Integra", "Treino", "Live"][i]}
            </text>
          </g>
        );
      })}
    </svg>
  );
}

function IllustRelation({ active }) {
  const [t, setT] = useState(0);
  useEffect(() => {
    if (!active) return;
    let raf;
    let s = performance.now();
    const tick = (n) => {
      setT((n - s) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [active]);

  const ping1 = (t * 0.5) % 1;
  const ping2 = ((t * 0.5) + 0.5) % 1;
  return (
    <svg viewBox="0 0 600 420" className="illust-svg">
      {/* two nodes */}
      <g transform="translate(140, 210)">
        <circle r="58" fill="rgba(39,102,123,0.15)" stroke="#27667B" strokeWidth="2" />
        <circle r="58" fill="none" stroke="rgba(39,102,123,0.3)" strokeDasharray="2 6">
          <animateTransform attributeName="transform" type="rotate" from="0" to="360" dur="20s" repeatCount="indefinite" />
        </circle>
        <text textAnchor="middle" dy="-2" fontFamily="Geist Mono" fontSize="10" fill="#27667B" letterSpacing="1.2">CLIENTE</text>
        <text textAnchor="middle" dy="14" fontFamily="Geist" fontWeight="700" fontSize="14" fill="#0F1521">você</text>
      </g>
      <g transform="translate(460, 210)">
        <circle r="58" fill="rgba(238,67,137,0.15)" stroke="#BA2F7D" strokeWidth="2" />
        <circle r="58" fill="none" stroke="rgba(238,67,137,0.3)" strokeDasharray="2 6">
          <animateTransform attributeName="transform" type="rotate" from="360" to="0" dur="20s" repeatCount="indefinite" />
        </circle>
        <text textAnchor="middle" dy="-2" fontFamily="Geist Mono" fontSize="10" fill="#BA2F7D" letterSpacing="1.2">VERYPAY</text>
        <text textAnchor="middle" dy="14" fontFamily="Geist" fontWeight="700" fontSize="14" fill="#0F1521">time</text>
      </g>
      {/* connecting line */}
      <line x1="198" y1="210" x2="402" y2="210" stroke="#BA2F7D" strokeWidth="1.5" opacity="0.5" />
      {/* pings travelling */}
      <circle cx={198 + ping1 * 204} cy="210" r="6" fill="#BA2F7D">
        <animate attributeName="opacity" values="1;0.3;1" dur="2s" repeatCount="indefinite" />
      </circle>
      <circle cx={402 - ping2 * 204} cy="210" r="6" fill="#27667B">
        <animate attributeName="opacity" values="1;0.3;1" dur="2s" repeatCount="indefinite" />
      </circle>
      {/* labels above */}
      <text x="300" y="160" textAnchor="middle" fontFamily="Geist Mono" fontSize="10" fill="rgba(15,21,33,0.5)" letterSpacing="1.2">MENSAL / TRIMESTRAL</text>
    </svg>
  );
}

window.Method = Method;
