// ─────────────────────────────────────────────────────────────────────────
//  BuyerJourneyMobile, phone-native rebuild of the buyer journey.
//
//  Why a separate component:
//    The desktop component (BuyerJourneyCinema) uses a sticky 100vh
//    viewport per stage with copy on the left and a UI mock on the
//    right. On a 390×844 phone that model wastes the screen, the
//    mock is fixed height: 460, the copy is ~250px of content, and
//    each 100vh slide ends up half empty. Plus there's no horizontal
//    space for the side-by-side layout, so it stacks anyway.
//
//  What this does instead:
//    • Sticky horizontal stage tab bar at the top (01 Discover / 02
//      Search / …). Tap to jump.
//    • Per-stage card with the UI mock UP TOP (visual hook first),
//      then eyebrow, headline, surface, body copy, and (on Close)
//      the compliance chips.
//    • All five stages live as a continuous vertical scroll. No
//      sticky-cinema, no 100vh forcing. Each card is exactly as
//      tall as it needs to be.
//    • The mock is hard-clamped to a phone-friendly height (260px
//      via aspect-ratio scaling on the inner mock body, browser
//      chrome above) so listing cards stay scannable.
//
//  Visibility split: see mobile.css, .journey-desktop-only / .journey-mobile-only
// ─────────────────────────────────────────────────────────────────────────

function BuyerJourneyMobile({ T, A, glow, tint }) {
  const stages = window.BUYER_JOURNEY_STAGES || [];
  // Use the phone-native mocks instead of the desktop UIMock, the
  // desktop one renders browser chrome + 3-col grids that don't fit
  // on a 390px screen. The mobile mocks render as faux phone screens
  // (IG mobile feed, Google mobile SERP, mobile marketplace, etc).
  const UIMock = window.BuyerJourneyMobileMock || window.BuyerJourneyUIMock || (() => null);
  const [active, setActive] = React.useState(0);
  const stageRefs = React.useRef([]);
  const tabsRef = React.useRef(null);

  // Active stage = the one whose card is closest to the top of the
  // viewport (after the sticky nav). Update on scroll, throttled via rAF.
  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = 0;
        const cards = stageRefs.current.filter(Boolean);
        if (!cards.length) return;
        // Pick card whose top is closest to (but still above) 200px from top.
        // 200px ≈ page nav (56) + sticky tabs (~80) + a bit of headroom.
        const anchor = 220;
        let bestIdx = 0;
        let bestDist = Infinity;
        cards.forEach((c, i) => {
          const r = c.getBoundingClientRect();
          const d = Math.abs(r.top - anchor);
          // Prefer cards that have crossed the anchor (top < anchor).
          if (r.top <= anchor + 40 && d < bestDist) {
            bestDist = d;
            bestIdx = i;
          }
        });
        setActive(bestIdx);
      });
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // When active changes, scroll the tab into view horizontally so the
  // user always sees the current stage label.
  React.useEffect(() => {
    const tabs = tabsRef.current;
    if (!tabs) return;
    const btn = tabs.querySelector(`[data-tab-idx="${active}"]`);
    if (btn) {
      const tabsRect = tabs.getBoundingClientRect();
      const btnRect = btn.getBoundingClientRect();
      const offset = btnRect.left - tabsRect.left - tabsRect.width / 2 + btnRect.width / 2;
      tabs.scrollBy({ left: offset, behavior: "smooth" });
    }
  }, [active]);

  const jumpTo = (i) => {
    const card = stageRefs.current[i];
    if (!card) return;
    const top = card.getBoundingClientRect().top + window.scrollY - 140; // clear nav + tabs
    window.scrollTo({ top, behavior: "smooth" });
  };

  return (
    <section
      id="journey"
      className="journey-mobile-only"
      style={{
        position: "relative",
        background: T.bgDark,
        color: "#fff",
        padding: "48px 0 24px",
      }}
    >
      {/* Section eyebrow + headline */}
      <div style={{ padding: "0 18px 18px" }}>
        <div
          style={{
            fontSize: 11, fontWeight: 700, color: tint(1),
            textTransform: "uppercase", letterSpacing: ".18em",
            marginBottom: 8,
          }}
        >
          The buyer journey
        </div>
        <div
          style={{
            fontFamily: T.fDisplay, fontSize: 28, fontWeight: 700,
            letterSpacing: "-0.02em", lineHeight: 1.1, color: "#fff",
            marginBottom: 6,
          }}
        >
          The decision is made before they reach out.
        </div>
        <div style={{ fontSize: 14, color: "rgba(255,255,255,.55)", lineHeight: 1.5 }}>
          Tap a stage to jump. Scroll to walk the path.
        </div>
      </div>

      {/* Sticky stage tabs */}
      <div
        style={{
          position: "sticky", top: 56,           // sits below page nav
          zIndex: 5,
          background: T.bgDark,
          borderTop: "1px solid rgba(255,255,255,.06)",
          borderBottom: "1px solid rgba(255,255,255,.06)",
          backdropFilter: "blur(8px)",
        }}
      >
        <div
          ref={tabsRef}
          style={{
            display: "flex", gap: 6,
            overflowX: "auto", overflowY: "hidden",
            padding: "10px 14px",
            scrollbarWidth: "none",
            WebkitOverflowScrolling: "touch",
          }}
        >
          <style>{`
            .jm-tabs::-webkit-scrollbar { display: none; }
          `}</style>
          {stages.map((s, i) => {
            const isActive = i === active;
            return (
              <button
                key={s.id}
                data-tab-idx={i}
                onClick={() => jumpTo(i)}
                style={{
                  flex: "0 0 auto",
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "8px 14px",
                  borderRadius: 999,
                  border: `1px solid ${isActive ? tint(.5) : "rgba(255,255,255,.12)"}`,
                  background: isActive ? tint(.15) : "rgba(255,255,255,.03)",
                  color: isActive ? "#fff" : "rgba(255,255,255,.7)",
                  fontSize: 13, fontWeight: 600,
                  letterSpacing: "-0.005em",
                  cursor: "pointer",
                  whiteSpace: "nowrap",
                  transition: "background .2s, border-color .2s, color .2s",
                }}
              >
                <span
                  style={{
                    fontVariantNumeric: "tabular-nums",
                    fontFamily: T.fDisplay, fontWeight: 700,
                    color: isActive ? A : "rgba(255,255,255,.4)",
                    fontSize: 12, letterSpacing: ".08em",
                  }}
                >
                  {s.n}
                </span>
                {s.eyebrow}
              </button>
            );
          })}
        </div>
      </div>

      {/* Stage cards, stacked vertically, content-sized */}
      <div style={{ padding: "20px 14px 12px", display: "flex", flexDirection: "column", gap: 18 }}>
        {stages.map((s, i) => (
          <article
            key={s.id}
            ref={(el) => (stageRefs.current[i] = el)}
            data-screen-label={`Journey ${s.n} ${s.eyebrow}`}
            style={{
              position: "relative",
              borderRadius: 18,
              overflow: "hidden",
              background: "rgba(255,255,255,.03)",
              border: "1px solid rgba(255,255,255,.08)",
              scrollMarginTop: 140,
            }}
          >
            {/* Phone-native mock, owns its own height (no clamp/fade).
                Each mock renders as a faux handset slice (status bar +
                app chrome + content). We just give it a tinted backdrop
                so it sits visually inside the card. */}
            <div
              style={{
                position: "relative",
                background: "linear-gradient(180deg, rgba(0,0,0,.35), rgba(0,0,0,.1))",
                borderBottom: "1px solid rgba(255,255,255,.06)",
                padding: "18px 14px 14px",
              }}
            >
              {/* Stage chip, sits ABOVE the mock, no longer overlaid */}
              <div
                style={{
                  display: "inline-flex", alignItems: "center", gap: 8,
                  padding: "5px 10px", borderRadius: 999,
                  background: "rgba(10,10,12,.7)",
                  backdropFilter: "blur(8px)",
                  border: `1px solid ${tint(.4)}`,
                  fontSize: 11, fontWeight: 700, color: "#fff",
                  textTransform: "uppercase", letterSpacing: ".12em",
                  marginBottom: 12,
                }}
              >
                <span
                  style={{
                    width: 5, height: 5, borderRadius: 3, background: A,
                  }}
                />
                {s.n} · {s.eyebrow}
              </div>
              <UIMock kind={s.mock} T={T} A={A} tint={tint} active={i === active} />
            </div>

            {/* Copy block */}
            <div style={{ padding: "20px 18px 22px" }}>
              <div
                style={{
                  fontSize: 11, fontWeight: 600,
                  color: "rgba(255,255,255,.45)",
                  textTransform: "uppercase", letterSpacing: ".12em",
                  marginBottom: 10,
                }}
              >
                {s.surface}
              </div>
              <h3
                style={{
                  fontFamily: T.fDisplay, fontSize: 24, fontWeight: 700,
                  letterSpacing: "-0.02em", lineHeight: 1.15,
                  margin: "0 0 12px", color: "#fff",
                  textWrap: "balance",
                }}
              >
                {s.title}
              </h3>
              <p
                style={{
                  fontSize: 14.5, lineHeight: 1.55,
                  color: "rgba(255,255,255,.72)",
                  margin: 0,
                }}
              >
                {s.desc}
              </p>

              {/* Stat callout */}
              {s.stat && (
                <div
                  style={{
                    marginTop: 18,
                    display: "flex", alignItems: "baseline", gap: 12,
                    padding: "12px 14px",
                    borderRadius: 10,
                    background: tint(.08),
                    border: `1px solid ${tint(.25)}`,
                  }}
                >
                  <div
                    style={{
                      fontFamily: T.fDisplay, fontSize: 22, fontWeight: 800,
                      color: "#fff", letterSpacing: "-0.02em",
                      fontVariantNumeric: "tabular-nums",
                    }}
                  >
                    {s.stat.v}
                  </div>
                  <div
                    style={{
                      fontSize: 12, color: "rgba(255,255,255,.65)",
                      lineHeight: 1.35,
                    }}
                  >
                    {s.stat.l}
                  </div>
                </div>
              )}

              {/* Compliance chips on the Close stage */}
              {s.compliance && (
                <div
                  style={{
                    marginTop: 16,
                    display: "flex", flexWrap: "wrap", gap: 6,
                  }}
                >
                  {s.compliance.map((c, ci) => (
                    <div
                      key={ci}
                      style={{
                        display: "inline-flex", alignItems: "center", gap: 6,
                        padding: "6px 10px", borderRadius: 999,
                        background: "rgba(255,255,255,.05)",
                        border: "1px solid rgba(255,255,255,.12)",
                        fontSize: 11.5, fontWeight: 600, color: "#fff",
                        letterSpacing: ".01em",
                      }}
                    >
                      <span
                        style={{
                          width: 5, height: 5, borderRadius: 3, background: A,
                        }}
                      />
                      {c.label}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </article>
        ))}
      </div>
    </section>
  );
}

Object.assign(window, { BuyerJourneyMobile });
