function Guia() {
  const stats = [
    { prefix: "+$", to: 20, suffix: "M", k: "En ventas generadas" },
    { prefix: "+", to: 45, suffix: "", k: "Clientes atendidos" },
    { prefix: "+", to: 40, to2: 80, suffix: "%", k: "En retorno de inversión (ROI)" },
    { prefix: "+", to: 5, suffix: "", k: "Años de experiencia" },
  ];
  return (
    <section id="guia" className="guia section">
      <Sticker kind="sparkle" className="guia-stk guia-stk-1 anim" />
      <Sticker kind="plus" className="guia-stk guia-stk-2" />
      <div className="wrap">
        <div className="guia-grid">
          <Reveal>
            <FunnelDash />
          </Reveal>

          <Reveal>
            <div className="eyebrow on-dark"><span className="dot"/>Sobre nosotros</div>
            <h2 className="guia-title" style={{marginTop: 16}}>Tu <span className="pink">guía experta</span> en <span className="cyan">crecimiento</span></h2>
            <p className="lead">
              Convertimos la complejidad del marketing digital en sistemas simples
              que funcionan. No vendemos teoría: instalamos sistemas probados con IA,
              datos y estrategia para que obtengas <strong>clientes reales, no solo likes.</strong>
            </p>

            <div className="guia-feats">
              <div className="guia-feat">
                <span className="gf-ic">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M5 13l4 4 10-11" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </span>
                <div>
                  <h4>Resultados reales</h4>
                  <p>Conversiones optimizadas y agendas llenas — no métricas de vanidad.</p>
                </div>
              </div>
              <div className="guia-feat">
                <span className="gf-ic">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M8 4h8M9 4v3a5 5 0 005 5 5 5 0 00-5 5v3M15 4v3a5 5 0 01-5 5 5 5 0 015 5v3M8 20h8" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </span>
                <div>
                  <h4>Metodología comprobada</h4>
                  <p>Datos reales + IA + estrategia, replicable y medible mes a mes.</p>
                </div>
              </div>
            </div>
          </Reveal>
        </div>

        <Reveal as="div" className="guia-stats">
          {stats.map((s, i) => (
            <div key={i} className="gs-item">
              <div className="gs-v"><CountStat {...s} delay={i * 120} /></div>
              <div className="gs-k">{s.k}</div>
            </div>
          ))}
        </Reveal>
      </div>
    </section>
  );
}
Object.assign(window, { Guia });

function CountStat({ prefix = "", to, to2, suffix = "", delay = 0 }) {
  const [v, setV] = useState(0);
  const [v2, setV2] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    let raf, started = false;
    const animate = () => {
      const dur = 1400, t0 = performance.now() + delay;
      const tick = (now) => {
        if (now < t0) { raf = requestAnimationFrame(tick); return; }
        const p = Math.min(1, (now - t0) / dur);
        const e = 1 - Math.pow(1 - p, 3);
        setV(Math.round(to * e));
        if (to2 != null) setV2(Math.round(to2 * e));
        if (p < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    const start = () => { if (started) return; started = true; cleanup(); animate(); };
    const check = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight - 40 && r.bottom > 0) { start(); return true; }
      return false;
    };
    const cleanup = () => {
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
    if (!check()) {
      window.addEventListener("scroll", check, { passive: true });
      window.addEventListener("resize", check);
    }
    return () => { cleanup(); cancelAnimationFrame(raf); };
  }, [to, to2, delay]);
  return (
    <span ref={ref}>{prefix}{v}{to2 != null ? `–${v2}` : ""}{suffix}</span>
  );
}
Object.assign(window, { CountStat });

function FunnelDash() {
  const stages = [
    { k: "Clicks",        target: 6840,  color: "var(--cyan)", w: 100 },
    { k: "Conversiones",  target: 1284,  color: "var(--pink)", w: 64 },
    { k: "Compras",       target: 392,   color: "#FFB020",      w: 36 },
  ];
  const [p, setP] = useState(0);
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current; if (!el) return;
    let raf, started = false;
    const animate = () => {
      const dur = 1700, t0 = performance.now();
      const tick = (now) => {
        const prog = Math.min(1, (now - t0) / dur);
        setP(1 - Math.pow(1 - prog, 3));
        if (prog < 1) raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
    };
    const start = () => { if (started) return; started = true; cleanup(); animate(); };
    const check = () => {
      const r = el.getBoundingClientRect();
      if (r.top < window.innerHeight - 60 && r.bottom > 0) { start(); return true; }
      return false;
    };
    const cleanup = () => {
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
    if (!check()) {
      window.addEventListener("scroll", check, { passive: true });
      window.addEventListener("resize", check);
    }
    return () => { cleanup(); cancelAnimationFrame(raf); };
  }, []);

  const fmt = (n) => Math.round(n).toLocaleString("es-MX");
  const steps = stages.map((s, i) => i === 0 ? null : (s.target / stages[i - 1].target * 100));
  const overall = 392 / 6840 * 100;

  return (
    <div className="funnel-dash" ref={ref}>
      <div className="fd-head">
        <div className="fd-title"><span className="fd-dot"></span>Embudo de conversión</div>
        <div className="fd-range">Últimos 30 días</div>
      </div>

      <div className="fd-stages">
        {stages.map((s, i) => (
          <div key={i} className="fd-stage">
            <div className="fd-stage-top">
              <span className="fd-k">{s.k}</span>
              {steps[i] != null && (
                <span className="fd-step" style={{ opacity: p }}>
                  <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M5 1v8M2 6l3 3 3-3" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  {(steps[i] * p).toFixed(1)}%
                </span>
              )}
              <span className="fd-v" style={{ color: s.color }}>{fmt(s.target * p)}</span>
            </div>
            <div className="fd-bar">
              <i style={{ width: `${s.w * p}%`, background: s.color }}></i>
            </div>
          </div>
        ))}
      </div>

      <div className="fd-foot">
        <div className="fd-conv">
          <span className="fd-conv-label">Tasa de conversión</span>
          <span className="fd-conv-val">{(overall * p).toFixed(1)}%</span>
        </div>
        <div className="fd-spark" aria-hidden="true">
          {[34, 48, 40, 62, 74, 96].map((h, i) => (
            <span key={i} className={i >= 4 ? "up" : ""} style={{ height: `${Math.max(8, h * p)}%` }}></span>
          ))}
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { FunnelDash });
