// How it works — horizontal sticky timeline (scroll-driven)

function HowItWorks() {
  const wrapRef = React.useRef(null);
  const railRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0); // 0..1
  const [isMobile, setIsMobile] = React.useState(false);

  React.useEffect(() => {
    const check = () => setIsMobile(window.matchMedia("(max-width: 800px)").matches);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);

  React.useEffect(() => {
    if (isMobile) return;
    const wrap = wrapRef.current;
    const rail = railRef.current;
    if (!wrap || !rail) return;

    let raf = 0;
    const update = () => {
      const rect = wrap.getBoundingClientRect();
      const total = rect.height - window.innerHeight;
      const scrolled = Math.min(Math.max(-rect.top, 0), total);
      const p = total > 0 ? scrolled / total : 0;
      setProgress(p);

      // translate rail
      const railW = rail.scrollWidth;
      const viewW = window.innerWidth;
      const maxShift = Math.max(0, railW - viewW + 0);
      rail.style.setProperty("--tx", `-${p * maxShift}px`);
    };
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        update();
      });
    };
    update();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", update);
      if (raf) cancelAnimationFrame(raf);
    };
  }, [isMobile]);

  const days = [
    { day: "01", title: "Onboarding & kickoff",
      desc: "Introductions, brief intake, and project setup. We capture product, target audience, budget range, and timeline." },
    { day: "02", title: "Partner sourcing",
      desc: "We start matching your brief against our vetted partner pool, identifying the strongest fits across media and agencies." },
    { day: "03", title: "Partner sourcing",
      desc: "We finalize the matching, validating availability and capacity with each shortlisted partner directly." },
    { day: "04", title: "Vetting, rates & shortlist",
      desc: "We confirm rates, formats, and availability, then deliver the shortlist with audience data and direct contacts." },
    { day: "05", title: "Warm intro",
      desc: "We make a warm introduction to the partners you choose. From here, you talk directly. We stay available for support.",
      final: true },
  ];

  const Header = (
    <div className="timeline-head">
      <div>
        <div className="section-tag" style={{ marginBottom: 22, paddingBottom: 0, borderBottom: 0 }}>
          <span className="dash" />
          <span>04 / How it works</span>
        </div>
        <h2 className="h-section" style={{ maxWidth: "22ch" }}>
          From the start to warm intro in 5 days.
        </h2>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10, minWidth: 260 }}>
        <div className="timeline-counter">
          {`DAY ${String(Math.min(5, Math.max(1, Math.round(progress * 5) + 1))).padStart(2, "0")} / 05`}
        </div>
        <div className="timeline-progress">
          <span style={{ "--tp": `${progress * 100}%` }} />
        </div>
        <div className="mono" style={{ fontSize: 11, color: "var(--muted)", letterSpacing: "0.18em", textTransform: "uppercase" }}>
          Mon → Fri
        </div>
      </div>
    </div>
  );

  if (isMobile) {
    return (
      <section id="how" style={{ background: "var(--bg-2)" }}>
        <div className="container">
          <div className="section-tag reveal">
            <span className="dash" />
            <span>04 / How it works</span>
          </div>
          <h2 className="h-section reveal" style={{ maxWidth: "22ch" }}>
            From the start to warm intro in 5 days.
          </h2>
          <div className="timeline-stack" style={{ marginTop: 40 }}>
            {days.map((d) => (
              <div key={d.day} className={"timeline-card reveal " + (d.final ? "is-final" : "")}>
                <div className="day">DAY {d.day}{d.final ? " · Warm intro" : ""}</div>
                <div className="day-num">{d.day.split("").map((c, i) => <span key={i} style={{ color: i === 1 && d.final ? "var(--accent)" : undefined }}>{c}</span>)}</div>
                <h3>{d.title}</h3>
                <p>{d.desc}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="how" style={{ background: "var(--bg-2)", padding: 0 }}>
      <div className="timeline-wrap" ref={wrapRef}>
        <div className="timeline-track">
          <div className="timeline-stage">
            {Header}
            <div className="timeline-rail" ref={railRef}>
              {days.map((d, i) => (
                <article
                  key={d.day}
                  className={"timeline-card " + (d.final ? "is-final" : "")}
                >
                  <div className="day">{d.final ? "DAY 05 · Warm intro" : `DAY ${d.day}`}</div>
                  <div className="day-num">
                    {d.day.split("").map((c, idx) => (
                      <span key={idx} style={{ color: d.final && idx === 1 ? "var(--accent)" : undefined }}>{c}</span>
                    ))}
                  </div>
                  <h3>{d.title}</h3>
                  <p>{d.desc}</p>
                  <div style={{ marginTop: "auto", paddingTop: 16, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <span className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", color: d.final ? "var(--accent)" : "var(--muted)", textTransform: "uppercase" }}>
                      {d.final ? "→ You talk directly" : `Step 0${i + 1} of 05`}
                    </span>
                    {d.final && <ArrowR size={18} />}
                  </div>
                </article>
              ))}
              <div style={{ flex: "0 0 25vw" }} aria-hidden />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

window.HowItWorks = HowItWorks;
