// Process.jsx — S4: "How it works" — original scroll-spy steps + sticky swapping media.
// Desktop: scroll-spy steps (left) + sticky media (right). Mobile: accordion.
function Process() {
  const steps = [
    { n: "01", label: "Share", i: "ri-upload-2-line", t: "Send your store and tell us what you are trying to fix.",
      d: "Start with the quick scan or book a Shopify audit consult. We look at your store, traffic, goals, and current constraints so we can confirm whether the full audit is the right next step.",
      chips: ["Store URL", "Traffic check", "Goals and constraints"] },
    { n: "02", label: "Audit", i: "ri-search-eye-line", t: "Connect access so we can diagnose the full funnel.",
      d: "After payment and access, we review Shopify, GA4, GTM, tracking, product pages, collections, cart, checkout, mobile UX, proof, offer clarity, and customer context.",
      chips: ["Shopify", "GA4 / GTM", "Funnel review"] },
    { n: "03", label: "Roadmap", i: "ri-list-check-2", t: "Review the roadmap and decide what gets shipped or tested.",
      d: "You receive the audit doc, visual recommendations, competitive context, Loom walkthrough, and follow-up call. Then we help you decide whether to implement internally, run tests, or continue with Conversion Works.",
      chips: ["5 priority fixes", "Loom walkthrough", "Implementation options"] },
  ];
  const imgSrc = (idx) => assetUrl(`assets/how-step${idx + 1}.avif`);

  const isMobile = useIsMobile(720);
  const [active, setActive] = useState(0);
  const [openStep, setOpenStep] = useState(0);
  const railRef = useRef(null);
  const nodeRefs = useRef([]);
  const [fillH, setFillH] = useState(0);
  const [lightY, setLightY] = useState(42);
  const ctaRef = useReveal();
  const layoutRef = useReveal();

  useEffect(() => {
    if (isMobile || !railRef.current) return;
    const stepEls = Array.from(railRef.current.querySelectorAll(".proc-step"));
    let raf = null;
    const compute = () => {
      raf = null;
      if (!railRef.current) return;
      const line = window.innerHeight * 0.42;
      let best = 0, bestDist = Infinity;
      stepEls.forEach((s, i) => {
        const r = s.getBoundingClientRect();
        const c = r.top + r.height / 2;
        const d = Math.abs(c - line);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      setActive(best);
    };
    const onScroll = () => { if (raf == null) raf = requestAnimationFrame(compute); };
    compute();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [isMobile]);

  useEffect(() => {
    if (isMobile) return;
    const node = nodeRefs.current[active];
    if (node) { setFillH(node.offsetTop + 28 - 14); setLightY(node.offsetTop + 28); }
  }, [active, isMobile]);

  return (
    <section id="how" className="section">
      <div className="wrap">
        <SectionHead eyebrow="How It Works" maxWidth={680}
          lead="Share your store, confirm the fit, and we will turn your Shopify data, funnel behavior, tracking, and customer context into a prioritized audit roadmap. From there, you can implement it yourself, bring us in for design and test setup, or move into full optimization.">
          A better conversion plan starts <span className="gradient-text">before anything gets changed.</span>
        </SectionHead>

        {isMobile ? (
          <div className="proc-accordion">
            {steps.map((s, idx) => {
              const isOpen = openStep === idx;
              return (
                <div key={s.n} className={"proc-acc-item" + (isOpen ? " open" : "")}>
                  <button type="button" className="proc-acc-head" onClick={() => setOpenStep(isOpen ? -1 : idx)} aria-expanded={isOpen}>
                    <span className="proc-acc-node"><i className={s.i} /></span>
                    <span className="proc-acc-htext">
                      <span className="proc-step__n">{s.n} / {s.label}</span>
                      <span className="proc-acc-title">{s.t}</span>
                    </span>
                    <i className={"proc-acc-chev " + (isOpen ? "ri-subtract-line" : "ri-add-line")} />
                  </button>
                  <div className="proc-acc-body">
                    <div className="proc-acc-inner">
                      <p className="proc-step__d">{s.d}</p>
                      <div className="proc-chips">{s.chips.map((c) => <span className="tool-chip" key={c}>{c}</span>)}</div>
                      <div className="proc-acc-media glass">
                        <img src={imgSrc(idx)} alt={`${s.t} — illustration`} />
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div ref={layoutRef} className="proc-layout">
            <div ref={railRef} className="proc-rail">
              <div className="proc-line" />
              <div className="proc-line-fill" style={{ height: fillH }} />
              <div className="proc-light" style={{ top: lightY }} />
              {steps.map((s, idx) => (
                <div key={s.n} data-idx={idx} style={{ "--si": idx }} className={`proc-step ${idx === active ? "active" : ""} ${idx < active ? "passed" : ""}`}>
                  <div ref={(el) => (nodeRefs.current[idx] = el)} className="proc-node"><i className={s.i} /></div>
                  <div style={{ paddingTop: 2 }}>
                    <span className="proc-step__n">{s.n} / {s.label}</span>
                    <h3 className="proc-step__t">{s.t}</h3>
                    <p className="proc-step__d">{s.d}</p>
                    <div className="proc-chips">{s.chips.map((c) => <span className="tool-chip" key={c}>{c}</span>)}</div>
                  </div>
                </div>
              ))}
            </div>

            <div className="proc-sticky">
              <div className="proc-media glass">
                <div className="proc-media__stage">
                  {steps.map((s, idx) => (
                    <img key={s.n} className={`proc-slot ${idx === active ? "on" : ""}`} src={imgSrc(idx)} alt={`${s.t} — illustration`} />
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        <div ref={ctaRef} className="reveal sw-foot-cta">
          <h3 className="sw-foot-h">Start with a consult. <span className="gradient-text">Leave with a clearer next step.</span></h3>
          <div className="sw-foot-actions">
            <a href="#cta" className="btn btn-primary">Book a Shopify audit consult <i className="ri-arrow-right-line" /></a>
            <a href="#cta" className="btn btn-secondary">Get 5 free fixes</a>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Process });
