// Mobile Work page sections
// Translates desktop's 6-act scroll narrative into vertical scroll with subtle reveals.

const { useState: wS, useEffect: wE, useRef: wR } = React;

// Animation utilities (ported from the desktop work page, Act I)
const mLerp = (a, b, t) => a + (b - a) * t;
const mRemap = (t, lo, hi) => Math.max(0, Math.min(1, (t - lo) / (hi - lo)));
const mEaseOut = (t) => 1 - Math.pow(1 - t, 3);

// Pinned-scroll progress 0..1 across a tall section with a sticky inner panel.
function useMPinnedProgress(ref) {
  const [p, setP] = wS(0);
  wE(() => {
    let raf;
    const tick = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const el = ref.current; if (!el) return;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight;
        const distance = el.offsetHeight - vh; // total pinned distance
        if (distance <= 0) { setP(0); return; }
        setP(Math.max(0, Math.min(1, -r.top / distance)));
      });
    };
    tick();
    window.addEventListener("scroll", tick, { passive: true });
    window.addEventListener("resize", tick);
    return () => {
      window.removeEventListener("scroll", tick);
      window.removeEventListener("resize", tick);
      cancelAnimationFrame(raf);
    };
  }, []);
  return p;
}

// ─────────────────────────────────────────────
// WORK HERO — "Arrival": ported desktop opening animation.
// As you scroll, a photo rises + scales while three headlines crossfade,
// landing on "NY, NJ, & PA." Text starts ink-dark on bone, then turns white
// as the photo arrives behind it.
// ─────────────────────────────────────────────
function WorkHero({ onInquire }) {
  const ref = wR(null);
  const p = useMPinnedProgress(ref);

  const photoScale = mLerp(0.84, 1.04, mEaseOut(mRemap(p, 0, 1)));
  const photoOp    = mRemap(p, 0, 0.2);

  const lines = [
    { text: "Thousands of homes protected.", accent: false },
    { text: "Across three states.",          accent: false },
    { text: "NY, NJ, & PA.",                 accent: true  },
  ];

  return (
    <section ref={ref} style={{ position: "relative", height: "260vh", background: "var(--bone)" }}>
      <div style={{ position: "sticky", top: 0, height: "100vh", overflow: "hidden" }}>
        {/* Photo — centered, rises + scales in */}
        <div style={{
          position: "absolute", left: "50%", top: "50%", transform: "translate(-50%, -50%)",
          width: "min(86vw, 560px)", zIndex: 2, willChange: "transform",
        }}>
          <div style={{
            transform: `translateY(${mLerp(60, 0, mEaseOut(mRemap(p, 0, 0.6)))}px) scale(${photoScale})`,
            opacity: photoOp,
            width: "100%", aspectRatio: "16/10", overflow: "hidden",
            boxShadow: "0 30px 60px -28px rgba(10,9,8,0.4), 0 12px 28px -14px rgba(10,9,8,0.2)",
            transformOrigin: "50% 50%", position: "relative", willChange: "transform, opacity",
          }}>
            <img src="../assets/work/p-luxury-gold-1.jpg" alt="" style={{
              width: "100%", height: "100%", objectFit: "cover", display: "block",
            }}/>
            <div style={{
              position: "absolute", inset: 0,
              background: `rgba(10,9,8,${0.4 * mRemap(p, 0.02, 0.22)})`,
              pointerEvents: "none",
            }}/>
          </div>
        </div>

        {/* Headline — dead center, three crossfading lines */}
        <div style={{
          position: "absolute", left: 0, right: 0, top: "50%", transform: "translateY(-50%)",
          height: "clamp(54px, 14vw, 92px)", display: "grid", placeItems: "center",
          padding: "0 24px", zIndex: 4,
        }}>
          {lines.map((ln, i) => {
            const winStart = i * 0.33, winEnd = (i + 1) * 0.33;
            const local = (p - winStart) / (winEnd - winStart);
            const RAMP_IN = 0.15, RAMP_OUT = 0.18, HOLD_END = 1 - RAMP_OUT;
            let op = 0;
            if (i === 0) {
              const RO = 0.40, HE = 1 - RO;
              op = local < HE ? 1 : Math.max(0, 1 - (local - HE) / RO);
            } else if (i === 1) {
              const RI = 0.30;
              if (p < winStart) op = 0;
              else if (local < RI) op = local / RI;
              else if (local < HOLD_END) op = 1;
              else op = Math.max(0, 1 - (local - HOLD_END) / RAMP_OUT);
            } else {
              if (p < winStart) op = 0;
              else op = local < RAMP_IN ? Math.max(0, local / RAMP_IN) : 1;
            }
            const t = mRemap(p, 0.02, 0.22);
            const txt = ln.accent
              ? "#fff"
              : `rgb(${Math.round(mLerp(10, 255, t))},${Math.round(mLerp(9, 255, t))},${Math.round(mLerp(8, 255, t))})`;
            const shadow = t > 0.05
              ? `0 2px 18px rgba(10,9,8,${0.55 * t}), 0 0 30px rgba(10,9,8,${0.4 * t})`
              : "none";
            return (
              <h1 key={i} className="serif" style={{
                position: "absolute", inset: 0,
                fontSize: "clamp(30px, 8.5vw, 46px)", lineHeight: 1.02, letterSpacing: "-0.025em",
                color: txt, fontStyle: ln.accent ? "italic" : "normal",
                opacity: op, display: "grid", placeItems: "center", textAlign: "center", margin: 0,
                textShadow: shadow, willChange: "opacity, color",
              }}>
                {ln.text}
              </h1>
            );
          })}
        </div>

        {/* Bouncing scroll cue — fades as scroll begins */}
        <div style={{
          position: "absolute", left: "50%", bottom: "clamp(28px, 6vh, 56px)",
          transform: `translateX(-50%) scale(${mLerp(1, 0.4, mRemap(p, 0, 0.06))})`,
          opacity: mLerp(1, 0, mRemap(p, 0, 0.06)),
          transformOrigin: "50% 50%", zIndex: 5, pointerEvents: "none",
        }}>
          <svg width="20" height="30" viewBox="0 0 22 32" fill="none"
               style={{ animation: "marrival-bounce 1.6s ease-in-out infinite", display: "block" }}>
            <path d="M11 2 L11 26 M3 18 L11 26 L19 18" stroke="var(--ink)" strokeWidth="1.5"
                  strokeLinecap="square" strokeLinejoin="miter" fill="none"/>
          </svg>
        </div>
        <style>{`@keyframes marrival-bounce { 0%,100%{transform:translateY(0);} 50%{transform:translateY(8px);} }`}</style>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// WORK WALL — alternating full-bleed photos with floating captions
// ─────────────────────────────────────────────
function WorkWall() {
  // Matches the home page "Our Work" section — same images, order, and titles.
  const photos = [
    { img: "../assets/work-penthouse-916.jpg",  caption: "Penthouse · Manhattan",         stone: "Honed black marble" },
    { img: "../assets/work-coastal-916.jpg",    caption: "Coastal residence",             stone: "Polished Calacatta" },
    { img: "../assets/work-grey-marble.jpg",    caption: "Waterfall island & backsplash", stone: "Quartzite" },
    { img: "../assets/work-white-waterfall.jpg",caption: "Waterfall island · New Jersey", stone: "Honed quartz" },
    { img: "../assets/work-navy-kitchen.jpg",   caption: "Navy kitchen · Brooklyn",       stone: "Polished quartz" },
    { img: "../assets/work-white-hood.jpg",     caption: "Full kitchen",                  stone: "Polished quartzite" },
    { img: "../assets/work-black-kitchen.jpg",  caption: "Forest-view kitchen · New York",stone: "Honed marble" },
  ];
  return (
    <section style={{ background: "var(--bone)", padding: "60px 0" }}>
      <div className="container" style={{ marginBottom: 36 }}>
        <LineEyebrow style={{ marginBottom: 14 }}>The Wall · Thousands of Homes</LineEyebrow>
        <h2 className="serif" style={{ fontSize: 32, lineHeight: 1.04, letterSpacing: "-0.02em" }}>
          Stone that <em style={{ color: "var(--maroon)" }}>got to maintain its beauty.</em>
        </h2>
      </div>
      <div style={{ display: "grid", gap: 36 }}>
        {photos.map((p, i) => (
          <Reveal key={i} delay={i * 40}>
            <figure>
              <div className="img-wrap" style={{ aspectRatio: "4/5" }}>
                <img src={p.img} alt={p.caption} />
              </div>
              <figcaption className="container" style={{
                marginTop: 14, display: "flex", justifyContent: "space-between", alignItems: "baseline",
              }}>
                <div>
                  <div className="serif" style={{ fontSize: 19, letterSpacing: "-0.01em" }}>{p.stone}</div>
                  <div className="mono" style={{ fontSize: 10, letterSpacing: "0.14em", color: "var(--mute)", textTransform: "uppercase", marginTop: 4 }}>
                    {p.caption}
                  </div>
                </div>
                <div className="mono" style={{ fontSize: 10, color: "var(--mute)", fontVariantNumeric: "tabular-nums" }}>
                  {String(i + 1).padStart(2, "0")} / {String(photos.length).padStart(2, "0")}
                </div>
              </figcaption>
            </figure>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// FINISHES — segmented toggle showing Clear vs Satin
// ─────────────────────────────────────────────
function WorkFinishes() {
  const [active, setActive] = wS(0);
  const finishes = [
    { name: "Clear", sub: "Polished", img: "../assets/work-clear-6.jpg", desc: "A high-clarity film for polished marble. Looks identical to bare stone, takes the abuse stone can't." },
    { name: "Satin", sub: "Honed",    img: "../assets/work-satin-2.png", desc: "A matte film engineered for honed stone. Preserves the tactile softness — and adds depth that brings out the stone's natural color." },
  ];
  return (
    <section style={{ padding: "70px 0", background: "var(--cream)" }}>
      <div className="container" style={{ marginBottom: 26 }}>
        <LineEyebrow style={{ marginBottom: 14 }}>Two Finishes</LineEyebrow>
        <h2 className="serif" style={{ fontSize: 32, lineHeight: 1.04, letterSpacing: "-0.02em" }}>
          One protection, <em style={{ color: "var(--maroon)" }}>two finishes.</em>
        </h2>
      </div>

      <div className="container" style={{ marginBottom: 22 }}>
        <div style={{ display: "flex", border: "1px solid var(--line)", padding: 4, background: "var(--bone)", position: "relative" }}>
          <div style={{
            position: "absolute", top: 4, bottom: 4,
            left: active === 0 ? 4 : "50%",
            width: "calc(50% - 4px)",
            background: "var(--ink)",
            transition: "left .35s cubic-bezier(.2,.7,.2,1)",
          }}/>
          {finishes.map((f, i) => (
            <button key={i} onClick={() => setActive(i)} style={{
              flex: 1, padding: "12px 0", fontSize: 13, fontWeight: 500,
              color: active === i ? "var(--bone)" : "var(--ink)",
              position: "relative", zIndex: 1,
              transition: "color .3s",
            }}>
              StoneGuard® {f.name}
            </button>
          ))}
        </div>
      </div>

      <div style={{ position: "relative" }}>
        {finishes.map((f, i) => (
          <div key={i} style={{
            transition: "opacity .4s ease, transform .4s cubic-bezier(.2,.7,.2,1)",
            opacity: active === i ? 1 : 0,
            transform: active === i ? "translateY(0)" : "translateY(12px)",
            position: active === i ? "relative" : "absolute",
            top: 0, left: 0, right: 0,
            pointerEvents: active === i ? "auto" : "none",
          }}>
            <div className="img-wrap" style={{ aspectRatio: "4/5" }}>
              <img src={f.img} alt={f.name} />
            </div>
            <div className="container" style={{ marginTop: 24 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: "0.16em", color: "var(--mute)", marginBottom: 8, textTransform: "uppercase" }}>
                {f.sub} stone
              </div>
              <h3 className="serif" style={{ fontSize: 28, letterSpacing: "-0.015em", lineHeight: 1.05, marginBottom: 12 }}>StoneGuard® {f.name}</h3>
              <p className="body" style={{ fontSize: 14 }}>{f.desc}</p>
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// PROCESS — 4 install moments (matches desktop's pinned-photo callouts)
// ─────────────────────────────────────────────
function WorkProcess() {
  const steps = [
    { n: "01", t: "Protect the kitchen", d: "Cover all cabinets and flooring to control the water used during the process.",                                                                      phase: "First 30 min" },
    { n: "02", t: "Clean the surfaces",  d: "We bring the surface to a contaminant-free state. Every trace of dust, dirt, and grime is removed so the stone is perfectly smooth before the film goes on.", phase: "Next 60 min" },
    { n: "03", t: "Lay & squeegee",      d: "The film is laid over the stone on a thin layer of pH-balanced liquid, then squeegeed by hand to bond it smoothly to the surface.",                        phase: "Next 3 hrs" },
    { n: "04", t: "Cure",                d: "Your surface is immediately ready for use. Leave stationary countertop items off for 24 hours.",                                                            phase: "Overnight" },
  ];
  return (
    <section style={{ padding: "70px 0", background: "var(--ink)", color: "var(--bone)" }}>
      <div className="container">
        <Reveal>
          <div className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(245,242,237,0.5)", marginBottom: 14 }}>
            <span style={{ display: "inline-block", width: 18, height: 1, background: "currentColor", verticalAlign: "middle", marginRight: 8, opacity: 0.7 }}/>
            The Process
          </div>
        </Reveal>
        <h2 className="serif" style={{ fontSize: 36, lineHeight: 1.02, letterSpacing: "-0.022em", marginBottom: 36 }}>
          <Reveal>One day,</Reveal>
          <Reveal delay={120}>
            <span style={{ color: "var(--bronze)", fontStyle: "italic", display: "block" }}>four steps.</span>
          </Reveal>
          <Reveal delay={240}>Then it disappears.</Reveal>
        </h2>
        <div style={{ position: "relative" }}>
          <div style={{
            position: "absolute", top: 24, bottom: 24, left: 18,
            width: 1, background: "rgba(245,242,237,0.18)",
          }}/>
          {steps.map((s, i) => (
            <Reveal key={i} delay={i * 80}>
              <div style={{ display: "flex", gap: 18, paddingBottom: 28, position: "relative" }}>
                <div style={{
                  width: 38, height: 38, borderRadius: "50%",
                  border: "1px solid rgba(245,242,237,0.35)",
                  display: "grid", placeItems: "center",
                  flexShrink: 0, background: "var(--ink)",
                  fontFamily: "'JetBrains Mono', monospace", fontSize: 11, letterSpacing: "0.05em",
                  color: "var(--bronze)",
                }}>{s.n}</div>
                <div style={{ flex: 1, paddingTop: 4 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10, marginBottom: 6 }}>
                    <h3 className="serif" style={{ fontSize: 22, letterSpacing: "-0.01em" }}>{s.t}</h3>
                    <span className="mono" style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--bronze)", whiteSpace: "nowrap" }}>
                      {s.phase}
                    </span>
                  </div>
                  <p style={{ fontSize: 14, lineHeight: 1.55, color: "rgba(245,242,237,0.7)" }}>{s.d}</p>
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────
// ATLAS — service regions, simple list
// ─────────────────────────────────────────────
function WorkAtlas() {
  const regions = [
    { state: "New York",     desc: "From the Boroughs, to Poughkeepsie, to the Hamptons." },
    { state: "New Jersey",   desc: "We have the whole state covered." },
    { state: "Pennsylvania", desc: "Within a 2-hour drive of NYC." },
  ];
  return (
    <section style={{ padding: "70px 0", background: "var(--bone)" }}>
      <div className="container">
        <Reveal>
          <LineEyebrow style={{ marginBottom: 14 }}>Service Area</LineEyebrow>
          <h2 className="serif" style={{ fontSize: 32, lineHeight: 1.04, letterSpacing: "-0.02em", marginBottom: 32 }}>
            Where we work.
          </h2>
        </Reveal>
        <div style={{ borderTop: "1px solid var(--line)" }}>
          {regions.map((r, i) => (
            <Reveal key={i} delay={i * 60}>
              <div style={{ padding: "22px 0", borderBottom: "1px solid var(--line)" }}>
                <div className="serif" style={{ fontSize: 26, letterSpacing: "-0.015em", marginBottom: 10 }}>{r.state}</div>
                <div style={{ fontSize: 13, color: "var(--mute)", lineHeight: 1.6 }}>
                  {r.desc}
                </div>
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { WorkHero, WorkWall, WorkFinishes, WorkProcess, WorkAtlas, WorkRiver });

// ─────────────────────────────────────────────
// THE RIVER — closing photo grid with subtle scroll-driven parallax,
// resolving into the final CTA. The mobile equivalent of the
// desktop's 3-column river that decelerates into the close.
// ─────────────────────────────────────────────
function WorkRiver({ onInquire }) {
  const ref = wR(null);
  const [p, setP] = wS(0);

  wE(() => {
    let raf;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const el = ref.current; if (!el) return;
        const r = el.getBoundingClientRect();
        const vh = window.innerHeight;
        // 0 when section enters bottom of viewport, 1 when top scrolls out
        const prog = Math.max(0, Math.min(1, (vh - r.top) / (vh + r.height)));
        setP(prog);
      });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => { window.removeEventListener("scroll", onScroll); cancelAnimationFrame(raf); };
  }, []);

  const columns = [
    // Two outer columns drift UP fast; the middle drifts DOWN at a slower,
    // contrasting speed — a criss-crossing "river."
    { photos: ["../assets/work-clear-1.jpg", "../assets/work-satin-3.png", "../assets/work-clear-6.jpg"], speed: 1.0, dir: -1 },
    { photos: ["../assets/work-satin-1.png", "../assets/work-clear-3.jpg", "../assets/hero-5313.jpg"],    speed: 0.5, dir:  1 },
    { photos: ["../assets/work-clear-5.jpg", "../assets/work-clear-4.jpg", "../assets/work-clear-2.jpg"], speed: 1.0, dir: -1 },
  ];
  const RIVER_AMP = 260; // total vertical drift (px) across the scroll, at speed 1

  return (
    <section ref={ref} style={{
      background: "var(--black)", color: "var(--bone)",
      position: "relative", overflow: "hidden",
      padding: "70px 0 30px",
    }}>
      <div className="container" style={{ marginBottom: 32, position: "relative", zIndex: 2 }}>
        <Reveal>
          <div className="mono" style={{ fontSize: 10, letterSpacing: "0.2em", textTransform: "uppercase", color: "rgba(245,242,237,0.5)", marginBottom: 14 }}>
            <span style={{ display: "inline-block", width: 18, height: 1, background: "currentColor", verticalAlign: "middle", marginRight: 8, opacity: 0.7 }}/>
            The River
          </div>
        </Reveal>
        <h2 className="serif" style={{ fontSize: 38, lineHeight: 0.98, letterSpacing: "-0.022em" }}>
          <Reveal>Every one of them</Reveal>
          <Reveal delay={120}>
            <span style={{ color: "var(--bronze)", fontStyle: "italic", display: "block" }}>still flawless.</span>
          </Reveal>
        </h2>
      </div>

      {/* Three-column moving river */}
      <div style={{ position: "relative" }}>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
          gap: 6, padding: "0 6px",
        }}>
          {columns.map((col, ci) => {
            // Centered at the section's midpoint (p=0.5), drifts as you scroll.
            // No CSS transition — the transform tracks scroll directly (rAF), so
            // it never lags behind the finger.
            const y = (p - 0.5) * RIVER_AMP * col.speed * col.dir;
            // Doubled strip → always taller than the window, so the drift never
            // exposes a gap (the inner panel is self-centered via translateY -50%).
            const strip = col.photos.concat(col.photos);
            return (
              <div key={ci} style={{ position: "relative", height: 380, overflow: "hidden" }}>
                <div style={{
                  position: "absolute", left: 0, right: 0, top: "50%",
                  // Build the sign explicitly — calc(-50% + -130px) is invalid CSS.
                  transform: `translate3d(0, calc(-50% ${y >= 0 ? "+" : "-"} ${Math.abs(y).toFixed(1)}px), 0)`,
                  display: "flex", flexDirection: "column", gap: 6,
                  willChange: "transform",
                }}>
                  {strip.map((src, pi) => (
                    <div key={pi} style={{
                      aspectRatio: "3/4", overflow: "hidden", background: "#0F0E0D",
                    }}>
                      <img src={src} alt="" style={{
                        width: "100%", height: "100%", objectFit: "cover",
                        filter: "brightness(0.85) saturate(0.9)",
                      }}/>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>

        {/* Top + bottom vignettes (span the whole row) */}
        <div style={{
          position: "absolute", top: 0, left: 0, right: 0, height: 60,
          background: "linear-gradient(to bottom, var(--black), transparent)",
          pointerEvents: "none",
        }}/>
        <div style={{
          position: "absolute", bottom: 0, left: 0, right: 0, height: 60,
          background: "linear-gradient(to top, var(--black), transparent)",
          pointerEvents: "none",
        }}/>
      </div>

      {/* Stat strip — quiet, end-of-chapter */}
      <div className="container" style={{ marginTop: 36, position: "relative" }}>
        <Reveal>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 1fr", gap: 0,
            borderTop: "1px solid rgba(245,242,237,0.18)",
          }}>
            {[
              { v: "1,000+",  l: "Homes protected" },
              { v: "10+ yrs", l: "Experience" },
              { v: "5.0",     l: "Google rating" },
              { v: "Lifetime", l: "Warranty" },
            ].map((s, i) => (
              <div key={i} style={{
                padding: "20px 0",
                borderBottom: "1px solid rgba(245,242,237,0.18)",
                borderRight: i % 2 === 0 ? "1px solid rgba(245,242,237,0.18)" : "none",
                paddingRight: i % 2 === 0 ? 12 : 0,
                paddingLeft:  i % 2 === 1 ? 16 : 0,
              }}>
                <div className="serif" style={{ fontSize: 28, letterSpacing: "-0.01em", lineHeight: 1, marginBottom: 6 }}>
                  {s.v}
                </div>
                <div className="mono" style={{ fontSize: 9, letterSpacing: "0.18em", textTransform: "uppercase", color: "rgba(245,242,237,0.55)" }}>
                  {s.l}
                </div>
              </div>
            ))}
          </div>
        </Reveal>
      </div>
    </section>
  );
}
