// 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: "Send", i: "ri-upload-2-line", t: "Share your site and what you need.",
      d: "Use the pricing tool, talk to Sol, or fill out the short intake. Send your current website, the pages you need, and the main action you want visitors to take.",
      chips: ["Current site", "Business details", "Call scheduled"] },
    { n: "02", label: "Prototype", i: "ri-layout-4-line", t: "See a working homepage before we meet.",
      d: "Within 24 hours, we prepare a first homepage prototype around your business, offer, proof, and visitor path. You can react to it, request changes, or use it as the starting point for the full site.",
      chips: ["Homepage prototype", "Message direction", "Site strategy"] },
    { n: "03", label: "Launch + Care", i: "ri-rocket-2-line", t: "We build, launch, host, and support it.",
      d: "Once the direction is approved, Siteworks designs and develops the rest of the site, connects forms or lead tools, launches it, handles hosting, and supports ongoing updates.",
      chips: ["Design + development", "Managed hosting", "Ongoing support"] },
  ];
  const imgSrc = (idx) => assetUrl(`assets/how-step${idx + 1}.png`);

  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="Send your current site, answer a few questions, and we'll prepare a working homepage prototype within 24 hours. From there, we refine the direction, build the site, launch it, host it, and keep it cared for.">
          A better website starts <span className="gradient-text">before the first call.</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">Send your site and see your first homepage prototype in <span className="gradient-text">24 hours.</span></h3>
          <div className="sw-foot-actions">
            <a href="#cta" className="btn btn-primary">Request my homepage prototype <i className="ri-arrow-right-line" /></a>
            <a href="#review" className="btn btn-secondary">See pricing</a>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Process });
