/* ABM "The Asset" - M4 scroll interaction. Babel.
   The four+ research layers move through one column; the page
   collage drifts the opposite way; the focal page lights the exact
   data behind each block (mapped to the real Rios Golden Cut page).
   → window.SC_V1 / SC_V2 / SC_V3 (explorer) + window.AssetScroll (prod) */
(function () {
  const { useState, useEffect, useRef } = React;

  // UNIFIED: per-layer accent comes from theme-driven CSS vars (--sc-*),
  // so the §4 colours follow whichever unified style is active. color-mix
  // keeps the translucent glows live on theme switch.
  const HEX = { person: "var(--sc-person)", company: "var(--sc-company)", offer: "var(--sc-offer)", signals: "var(--sc-signals)", proof: "var(--sc-proof)", matched: "var(--sc-matched)" };
  const hexA = (h, a) => `color-mix(in srgb, ${h} ${Math.round(a * 100)}%, transparent)`;

  // one card per researched layer, ordered to match the page top→bottom
  const CARDS = [
    { key: "person",  cat: "Target person",  nm: "The growth owner",        role: "Role-matched persona",   rows: ["Owns growth & marketing", "Decision-maker seniority", "Background & tenure", "Goals & triggers"] },
    { key: "company", cat: "Target company", nm: "Rios Golden Cut",         role: "13 salons · San Antonio", rows: ["13 locations", "Hair-salon vertical", "Live site & brand", "Revenue & footprint"] },
    { key: "offer",   cat: "Offer & play",   nm: "The ROI model",           role: "Calculated for this account", rows: ["13 locations modeled", "$1.13M/yr upside", "6 revenue levers", "Per-location math"] },
    { key: "signals", cat: "Live signals",   nm: "What they struggle with", role: "Tracked continuously",   rows: ["Missed bookings", "No-shows & churn", "Generic experiences", "Disconnected tools"] },
    { key: "proof",   cat: "Proof",          nm: "Matched social proof",    role: "Their industry, their size", rows: ["30,000 businesses", "Industry logos", "Video testimonial", "Same vertical"] },
    { key: "matched", cat: "Matched offer",  nm: "Tailored solution",       role: "Mapped to their goals",  rows: ["Built for their stack", "Revenue per guest", "Clear next step", "Their named plan"] },
  ];

  // highlight rects on the focal page (% of the cropped page), tagged by card key
  const HLS = [
    { key: "person",  x: 2.5,  y: 4.4,  w: 46,   h: 11.4, tag: "Persona → headline" },
    { key: "company", x: 50.5, y: 2.5,  w: 48.5, h: 13,   tag: "Company → hero image" },
    { key: "offer",   x: 0.8,  y: 17.8, w: 98.4, h: 20.7, tag: "ROI model → value calc" },
    { key: "proof",   x: 18.8, y: 38.9, w: 62.4, h: 7.2,  tag: "Proof → logos" },
    { key: "signals", x: 0.8,  y: 47.6, w: 98.4, h: 23.9, tag: "Signals → their pains" },
    { key: "proof",   x: 0.8,  y: 72.3, w: 98.4, h: 12.2, tag: "Proof → testimonial" },
    { key: "matched", x: 0.8,  y: 85,   w: 98.4, h: 13.2, tag: "Matched offer → solution" },
  ];
  // section center % for page-led scroll (proof centers to show logos + video together)
  const SEC_Y = { person: 9, company: 9, offer: 28, signals: 59, proof: 60, matched: 91 };

  const CROP = { x0: 0.358, w: 0.392, y0: 0.018, h: 0.982, iw: 1020, ih: 1405, img: (window.__resources || {}).pagesTop || "assets/pages-top.png" };
  const ASPECT = (CROP.h * CROP.ih) / (CROP.w * CROP.iw);
  const N = CARDS.length;

  function useScrollProgress() {
    const ref = useRef(null); const [p, setP] = useState(0);
    useEffect(() => {
      const el = ref.current; if (!el) return;
      let stop = false, last = -1, raf = 0;
      const tick = () => {
        if (stop) return;
        const vh = window.innerHeight || 800;
        const r = el.getBoundingClientRect();
        const total = el.offsetHeight - vh;
        if (r.bottom > -50 && r.top < vh + 50) {
          const scrolled = Math.min(total, Math.max(0, -r.top));
          const np = total > 0 ? scrolled / total : 0;
          if (Math.abs(np - last) > 0.0005) { last = np; setP(np); }
        }
        raf = requestAnimationFrame(tick);
      };
      raf = requestAnimationFrame(tick);
      return () => { stop = true; cancelAnimationFrame(raf); };
    }, []);
    return [ref, p];
  }

  function FocalPage({ width, translateY = 0, active }) {
    const height = width * ASPECT;
    const bg = {
      backgroundImage: `url(${CROP.img})`,
      backgroundSize: `${width / CROP.w}px ${height / CROP.h}px`,
      backgroundPosition: `${-(CROP.x0 / CROP.w) * width}px ${-(CROP.y0 / CROP.h) * height}px`,
    };
    return (
      <div className="sc-focal" style={{ width, height, ...bg, transform: `translateY(${translateY}px)` }}>
        {HLS.map((hl, i) => {
          const lit = hl.key === active; const c = HEX[hl.key];
          return (
            <div key={i} className="sc-hl" style={{
              left: hl.x + "%", top: hl.y + "%", width: hl.w + "%", height: hl.h + "%",
              borderColor: lit ? c : hexA(c, 0.28), background: lit ? hexA(c, 0.18) : "transparent",
              opacity: lit ? 1 : 0.4, boxShadow: lit ? `0 0 26px -2px ${hexA(c, 0.5)}` : "none",
            }}>
              <span className="sc-htag" style={{ background: c, opacity: lit ? 1 : 0 }}>{hl.tag}</span>
            </div>
          );
        })}
      </div>
    );
  }

  function Card({ d, on }) {
    const c = HEX[d.key];
    return (
      <div className={"sc-card" + (on ? " on" : "")} style={{ "--cc": c, opacity: on ? 1 : 0.42, transform: on ? "scale(1)" : "scale(0.965)" }}>
        <div className="ch"><span className="d" style={{ background: c }} /><span className="c" style={{ color: c }}>{d.cat}</span><span className="n">{("0" + (CARDS.indexOf(d) + 1))} / 0{N}</span></div>
        <div className="nm">{d.nm}</div>
        <div className="role">{d.role}</div>
        <div className="rows">{d.rows.map((r) => <div className="row" key={r}><span className="ar" style={{ color: c }}>→</span><span>{r}</span></div>)}</div>
      </div>
    );
  }

  function Wall({ p }) {
    return (
      <React.Fragment>
        <div className="sc-wall" style={{ transform: `translateY(${-p * 58}vh)` }}>
          <img src={(window.__resources || {}).pagesAll || "assets/pages-all.png"} alt="" style={{ height: "230vh", opacity: 0.28, filter: "saturate(0.78)" }} />
        </div>
        <div className="sc-wallvig" style={{ background: "linear-gradient(90deg, var(--ad-bg) 8%, rgba(7,19,29,0.5) 34%, rgba(7,19,29,0.06) 72%)" }} />
        <div className="sc-wallvig" style={{ background: "linear-gradient(180deg, rgba(7,19,29,0.92), rgba(7,19,29,0) 15%, rgba(7,19,29,0) 85%, rgba(7,19,29,0.92))" }} />
      </React.Fragment>
    );
  }

  function Dots({ active }) {
    return <div className="sc-dots">{CARDS.map((d, i) => <i key={i} className={active === i ? "on" : ""} style={active === i ? { background: HEX[d.key] } : null} />)}</div>;
  }
  function VLabel({ n, t }) { return <div className="sc-vlabel"><span className="bar" /><span className="t">Variation {n} · {t}</span></div>; }
  function Cue() { return <div className="sc-scrollcue"><span className="dot" />Scroll</div>; }

  const idxFrom = (p) => Math.min(N - 1, Math.max(0, Math.floor(p * (N - 0.0001))));
  const winPx = (f) => (typeof window !== "undefined" ? window.innerHeight : 900) * f;
  const pageTY = (active, ph, f) => Math.max(-(ph - winPx(f)), Math.min(0, winPx(f) / 2 - (SEC_Y[CARDS[active].key] / 100) * ph));

  /* ---------- V1 - CARDS LED (focal fixed full, cards rail scrolls) ---------- */
  function SC_V1() {
    const [ref, p] = useScrollProgress();
    const active = idxFrom(p);
    const unit = 220; const track = (1.5 - active) * unit;
    const fh = winPx(0.78); const fw = fh / ASPECT;
    return (
      <div className="sc-pin" ref={ref} style={{ height: N * 110 + "vh" }}>
        <div className="sc-sticky">
          <VLabel n="1" t="Cards lead · page reacts" />
          <Wall p={p} />
          <div className="sc-stage lyt-cards">
            <div className="sc-focalwin"><FocalPage width={fw} active={CARDS[active].key} /></div>
            <div className="sc-cards" style={{ overflow: "visible" }}>
              <div className="sc-cardtrack" style={{ transform: `translateY(${track}px)` }}>
                {CARDS.map((d, i) => <Card key={d.key} d={d} on={i === active} />)}
              </div>
            </div>
          </div>
          <Dots active={active} /><Cue />
        </div>
      </div>
    );
  }

  /* ---------- V2 - PAGE LED (page scrolls top→bottom, card follows) ---------- */
  function SC_V2() {
    const [ref, p] = useScrollProgress();
    const active = idxFrom(p);
    const fw = 312, ph = fw * ASPECT;
    return (
      <div className="sc-pin" ref={ref} style={{ height: N * 112 + "vh" }}>
        <div className="sc-sticky">
          <VLabel n="2" t="Page scrolls · see the whole thing" />
          <Wall p={p} />
          <div className="sc-stage lyt-page">
            <div className="sc-cards"><Card d={CARDS[active]} on={true} /></div>
            <div className="sc-focalwin" style={{ height: "80vh", overflow: "hidden", borderRadius: 14 }}>
              <FocalPage width={fw} translateY={pageTY(active, ph, 0.8)} active={CARDS[active].key} />
            </div>
          </div>
          <Dots active={active} /><Cue />
        </div>
      </div>
    );
  }

  /* ---------- V3 - SPLIT (big card + page side by side, synced) ---------- */
  function SplitStage({ p, active }) {
    const fw = 300, ph = fw * ASPECT;
    return (
      <div className="sc-stage lyt-split">
        <div className="sc-focalwin" style={{ height: "82vh", overflow: "hidden", borderRadius: 14, justifySelf: "end" }}>
          <FocalPage width={fw} translateY={pageTY(active, ph, 0.82)} active={CARDS[active].key} />
        </div>
        <div className="sc-cards" style={{ maxWidth: 440 }}><Card d={CARDS[active]} on={true} /></div>
      </div>
    );
  }
  function SC_V3() {
    const [ref, p] = useScrollProgress();
    const active = idxFrom(p);
    return (
      <div className="sc-pin" ref={ref} style={{ height: N * 112 + "vh" }}>
        <div className="sc-sticky">
          <VLabel n="3" t="Split · input meets page" />
          <Wall p={p} />
          <SplitStage p={p} active={active} />
          <Dots active={active} /><Cue />
        </div>
      </div>
    );
  }

  /* ---------- PRODUCTION - homepage section (dark, full-bleed) ---------- */
  function AssetScroll() {
    const [ref, p] = useScrollProgress();
    const active = idxFrom(p);
    return (
      <div className="sc-page">
        <div className="sc-intro">
          <div className="ad-kick" style={{ marginBottom: 18 }}><span className="bar" /><span className="tag">ABM PAGES · THE ASSET</span></div>
          <h1>Every page is a <span className="em">research dossier</span> in disguise</h1>
          <p>Everything the system knows - the person, the account, its live signals, the ROI model and matched proof - compiles into the one asset a buyer actually opens. Scroll and watch each layer light up the block it built.</p>
        </div>
        <div className="sc-pin" ref={ref} style={{ height: N * 116 + "vh" }}>
          <div className="sc-sticky">
            <Wall p={p} />
            <SplitStage p={p} active={active} />
            <Dots active={active} />
            <div className="sc-scrollcue"><span className="dot" />Scroll · the page assembles</div>
          </div>
        </div>
      </div>
    );
  }

  window.SC_V1 = SC_V1; window.SC_V2 = SC_V2; window.SC_V3 = SC_V3; window.AssetScroll = AssetScroll;
})();
