// Convert.jsx — S2.5: What conversion-aware actually means
// Left head + an animated "conversion page" mockup (blueprint texture behind it) + 6 feature cards.

// CW audit animation — a seamless ~14s loop in four stages:
//  1) PDP diagnostic lens fades in, 8 friction signal cards drift in around it
//  2) connector lines pulse inward; each signal card lights up; diagnosis summary appears; cards compress
//  3) the empty CRO roadmap board takes center; 9 roadmap items populate in priority order (NOW brightest)
//  4) the #1 item connects to the implementation panel, which shows briefly, then resets to the lens.
// Driven by one rAF timeline writing styles directly (no per-frame React renders) so the loop is exact.
const CWA_SIGNALS = [
  { f: "trust_proof",     cx: 16, cy: 18, w: 32, dx: -0.78, dy: -0.62 },
  { f: "product_images",  cx: 51, cy: 11, w: 29, dx:  0.03, dy: -1.00 },
  { f: "reviews",         cx: 85, cy: 18, w: 32, dx:  0.77, dy: -0.64 },
  { f: "mobile_ux",       cx: 86, cy: 50, w: 32, dx:  1.00, dy:  0.05 },
  { f: "add_to_cart_cta", cx: 85, cy: 80, w: 32, dx:  0.74, dy:  0.67 },
  { f: "price_clarity",   cx: 51, cy: 85, w: 29, dx:  0.03, dy:  1.00 },
  { f: "tracking_events", cx: 16, cy: 80, w: 37, dx: -0.77, dy:  0.64 },
  { f: "shipping_returns",cx: 13, cy: 50, w: 32, dx: -1.00, dy:  0.05 },
];
const CWA_TONE = { trust_proof: "red", product_images: "violet", reviews: "red", mobile_ux: "red",
  add_to_cart_cta: "red", price_clarity: "red", tracking_events: "red", shipping_returns: "violet" };
const CWA_ITEMS = [
  "roadmap_reduce_checkout_friction", "roadmap_clarify_pdp_pricing", "roadmap_improve_product_images",
  "roadmap_build_social_proof", "roadmap_optimize_mobile", "roadmap_speed_performance",
  "roadmap_ab_test_pdp", "roadmap_email_capture", "roadmap_tracking_cleanup",
];
const CWA_L = 14000; // loop length (ms)

function ConvViz() {
  const stageRef = useRef(null);
  const R = useRef({}).current;            // id -> DOM node
  const reg = (id) => (el) => { if (el) R[id] = el; };

  useEffect(() => {
    const clamp = (x) => (x < 0 ? 0 : x > 1 ? 1 : x);
    const ease = (x) => x * x * (3 - 2 * x);
    const set = (id, o, x = 0, y = 0, s = 1, b = 1) => {
      const el = R[id]; if (!el) return;
      el.style.opacity = o;
      el.style.transform = `translate(-50%,-50%) translate(${x}px,${y}px) scale(${s})`;
      el.style.filter = b === 1 ? "none" : `brightness(${b})`;
    };
    const layout = (t) => {
      // Stage 1 — lens + halo
      let lensO = 1;
      if (t >= 5500 && t < 6200) lensO = 1 - (t - 5500) / 700;
      else if (t >= 6200 && t < 13000) lensO = 0;
      else if (t >= 13000) lensO = (t - 13000) / 1000;
      const pulse = 1 + 0.05 * Math.sin(t / 560);
      set("lens", lensO, 0, 0, 0.97 + 0.03 * lensO);
      set("halo", lensO * 0.9, 0, 0, (0.92 + 0.12 * lensO) * pulse);

      // signal cards: drift in (staggered), detect-pulse in diagnosis, then compress inward
      CWA_SIGNALS.forEach((c, i) => {
        const oin = ease(clamp((t - (600 + i * 150)) / 850));
        const comp = clamp((t - 4400) / 1000);
        const o = oin * (1 - comp);
        const x = c.dx * 64 * (1 - oin) - c.dx * 34 * comp;
        const y = c.dy * 64 * (1 - oin) - c.dy * 34 * comp;
        const s = (0.84 + 0.16 * oin) * (1 - 0.16 * comp);
        const pp = clamp(1 - Math.abs(t - (2900 + i * 250)) / 280);
        set("sig" + i, o, x, y, s, 1 + 0.75 * pp);
      });

      // connector lines (cards -> lens)
      let connO = 0;
      if (t >= 2300 && t < 3100) connO = (t - 2300) / 800;
      else if (t >= 3100 && t < 4500) connO = 1;
      else if (t >= 4500 && t < 5200) connO = 1 - (t - 4500) / 700;
      if (R.conn) R.conn.style.opacity = connO;

      // diagnosis summary
      let dO = 0;
      if (t >= 4300 && t < 5000) dO = (t - 4300) / 700;
      else if (t >= 5000 && t < 5900) dO = 1;
      else if (t >= 5900 && t < 6500) dO = 1 - (t - 5900) / 600;
      set("diag", dO, 0, 0, 0.92 + 0.08 * dO);

      // Stage 3 — roadmap board
      let bO = 0;
      if (t >= 7000 && t < 7800) bO = (t - 7000) / 800;
      else if (t >= 7800 && t < 12800) bO = 1;
      else if (t >= 12800 && t < 13600) bO = 1 - (t - 12800) / 800;
      set("board", bO, 0, 0, 0.95 + 0.05 * bO);

      CWA_ITEMS.forEach((_, i) => {
        const oin = ease(clamp((t - (7900 + i * 290)) / 620));
        let o = oin;
        if (t >= 12800) o *= 1 - clamp((t - 12800) / 800);
        const now = i < 3;
        let b = now ? 1 : 0.78;
        if (i === 0) b = Math.max(b, 1 + 0.6 * clamp(1 - Math.abs(t - 11900) / 850));
        const el = R["item" + i];
        if (el) {
          el.style.opacity = now ? o : o * 0.9;
          el.style.transform = `translateY(${16 * (1 - oin)}px) scale(${now ? 1 : 0.97})`;
          el.style.filter = `brightness(${b})`;
        }
      });

      // Stage 4 — action connector + implementation panel
      let acO = 0;
      if (t >= 11000 && t < 11600) acO = (t - 11000) / 600;
      else if (t >= 11600 && t < 12700) acO = 1;
      else if (t >= 12700 && t < 13300) acO = 1 - (t - 12700) / 600;
      if (R.aconn) R.aconn.style.opacity = acO;

      let iO = 0;
      if (t >= 11500 && t < 12300) iO = (t - 11500) / 800;
      else if (t >= 12300 && t < 13200) iO = 1;
      else if (t >= 13200 && t < 13900) iO = 1 - (t - 13200) / 700;
      set("impl", iO, 0, 0, 0.94 + 0.06 * iO);
    };

    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) { layout(11000); return; }

    let raf = 0, t0 = 0, running = false;
    const tick = (now) => {
      if (!t0) t0 = now;
      layout((now - t0) % CWA_L);
      raf = requestAnimationFrame(tick);
    };
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !running) { running = true; t0 = 0; raf = requestAnimationFrame(tick); }
        else if (!e.isIntersecting && running) { running = false; cancelAnimationFrame(raf); }
      });
    }, { threshold: 0.2 });
    if (stageRef.current) io.observe(stageRef.current);
    layout(0);
    return () => { io.disconnect(); cancelAnimationFrame(raf); };
  }, []);

  const A = (n) => assetUrl(`assets/cw/${String(n).replaceAll("_", "-")}.avif`);
  const cx = 50, cy = 47;

  return (
    <div className="cwa-stage" ref={stageRef} aria-hidden="true">
      {/* connector lines: signals -> lens */}
      <svg className="cwa-conn" ref={reg("conn")} viewBox="0 0 100 100" preserveAspectRatio="none">
        {CWA_SIGNALS.map((c, i) => (
          <g key={i} className={"cwa-line--" + CWA_TONE[c.f]}>
            <line className="cwa-line-halo" x1={c.cx} y1={c.cy} x2={cx} y2={cy} />
            <line className="cwa-line" x1={c.cx} y1={c.cy} x2={cx} y2={cy} />
            <line className="cwa-line-pulse" x1={c.cx} y1={c.cy} x2={cx} y2={cy} style={{ animationDelay: (i * 0.16) + "s" }} />
          </g>
        ))}
      </svg>
      {/* action connector: roadmap -> implementation */}
      <svg className="cwa-aconn" ref={reg("aconn")} viewBox="0 0 100 100" preserveAspectRatio="none">
        <g className="cwa-line--red">
          <line className="cwa-line-halo" x1="28" y1="38" x2="50" y2="50" />
          <line className="cwa-line" x1="28" y1="38" x2="50" y2="50" />
          <line className="cwa-line-pulse" x1="28" y1="38" x2="50" y2="50" />
        </g>
      </svg>

      <div className="cwa-halo" ref={reg("halo")} />
      <img className="cwa-lens" ref={reg("lens")} src={A("pdp_diagnostic_lens")} alt="" />

      {CWA_SIGNALS.map((c, i) => (
        <img key={c.f} className={"cwa-sig cwa-sig--" + CWA_TONE[c.f]} ref={reg("sig" + i)}
          src={A(c.f)} alt="" style={{ left: c.cx + "%", top: c.cy + "%", width: c.w + "%" }} />
      ))}

      <img className="cwa-diag" ref={reg("diag")} src={A("diagnosis_summary")} alt="" />

      <div className="cwa-board" ref={reg("board")}>
        <img className="cwa-board-bg" src={A("roadmap_empty")} alt="" />
        <div className="cwa-items">
          {CWA_ITEMS.map((it, i) => (
            <img key={it} className={"cwa-item" + (i < 3 ? " cwa-item--now" : "")} ref={reg("item" + i)}
              src={A(it)} alt="" />
          ))}
        </div>
      </div>

      <img className="cwa-impl" ref={reg("impl")} src={A("implementation_test_setup")} alt="" />
    </div>
  );
}

function ConvertSection() {
  const cards = [
    { i: "ri-radar-line", tone: "magenta", t: "Every signal in one place",
      d: "We review the funnel across Shopify, analytics, tracking, product pages, cart, checkout, reviews, and customer behavior." },
    { i: "ri-search-eye-line", tone: "violet", t: "Friction gets diagnosed",
      d: "We identify where buyers lose confidence: unclear value, weak proof, mobile friction, checkout hesitation, or tracking gaps." },
    { i: "ri-list-check-2", tone: "magenta", t: "Priorities replace opinions",
      d: "Each opportunity is ranked by impact, effort, confidence, and where it sits in the buyer journey." },
    { i: "ri-file-text-line", tone: "violet", t: "Recommendations are implementation-ready",
      d: "You get plain-English guidance, screenshots, competitive context, and step-by-step instructions your team can follow." },
    { i: "ri-flask-line", tone: "magenta", t: "Test when traffic supports it",
      d: "When there is enough data, we turn roadmap items into experiments. When there is not, we ship low-risk fixes and measure." },
    { i: "ri-line-chart-line", tone: "violet", t: "The roadmap leads into action",
      d: "After the audit, you can implement internally, hire us for design and test setup, or move into full optimization." },
  ];
  const headRef = useReveal();
  const gridRef = useReveal();
  return (
    <section id="convert" className="section section--light convert-sec">
      <div className="wrap">
        <div ref={headRef} className="reveal convert-head">
          <h2 className="h-section">Your Shopify store goes in. A prioritized CRO roadmap comes out.</h2>
          <p className="p-lead"><span className="lead-full">We pull signals from your product pages, cart, checkout, tracking, reviews, analytics, and customer context, then rank the fixes by impact, effort, and confidence so your team knows exactly what to do next.</span><span className="lead-short">We rank fixes by impact, effort, and confidence so your team knows what to do next.</span></p>
        </div>

        <div className="cwa-frame">
          <ConvViz />
        </div>

        <div ref={gridRef} className="reveal cv-cards">
          {cards.map((c) => (
            <div className="cv-feature" key={c.t}>
              <span className={"cv-ico cv-ico--" + c.tone}><i className={c.i} /></span>
              <h3 className="cv-feature__title">{c.t}</h3>
              <p className="cv-feature__desc">{c.d}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { ConvertSection, ConvViz });
