/* global React, Reveal, RevealGroup, RevealLines, MagneticButton */
const { useState: useState_h, useEffect: useEffect_h, useRef: useRef_h } = React;

const HERO_IMG = "assets/hero-home.jpg";
const PIN_IMG = "assets/hardanger-sideboard.jpg";
const STORY_A = "assets/detail-tenon.jpg";
const STORY_B = "assets/atelier-hero.jpg";

const COLLECTION = [
  { name: "Sognefjord", sub: "Three-Seat Sofa", price: "$4,820", img: "assets/sognefjord-bone.jpg" },
  { name: "Lysefjord", sub: "Lounge Chair", price: "$2,640", img: "assets/lysefjord-lounge.jpg" },
  { name: "Geirangerfjord", sub: "Dining Table", price: "$3,980", img: "assets/geirangerfjord-table.jpg" },
  { name: "Hardanger", sub: "Sideboard", price: "$5,420", img: "assets/hardanger-sideboard.jpg" },
  { name: "Trollfjord", sub: "Reading Chair", price: "$2,280", img: "assets/trollfjord-reading.jpg" },
];

function HomePage({ onNavigate }) {
  /* Hero parallax */
  const heroImgRef = useRef_h(null);
  useEffect_h(() => {
    const el = heroImgRef.current;
    if (!el) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf;
    const tick = () => {
      const y = window.scrollY;
      el.style.transform = `translate3d(0, ${y * 0.22}px, 0) scale(1.08)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <main>
      {/* HERO */}
      <section className="hero" data-screen-label="01 Hero">
        <div className="hero-image" ref={heroImgRef} style={{ backgroundImage: `url(${HERO_IMG})` }}></div>
        <div className="hero-grain"></div>

        <div className="hero-content">
          <h1 className="t-display hero-title">
            <RevealLines lines={["Furniture", <span key="i" style={{ fontStyle: "italic" }}>made the</span>, "slow way."]} gap={120} />
          </h1>
          <div className="col" style={{ gap: 24, alignItems: "flex-start" }}>
            <Reveal delay={500}>
              <p className="t-body" style={{ color: "rgba(242,235,224,0.78)", maxWidth: "38ch", fontSize: 17 }}>
                Investment pieces designed in Los Angeles and built to order at our atelier in Vietnam. Single designer. Fifty-year frame warranty. Every joinery joint left visible, on purpose.
              </p>
            </Reveal>
            <Reveal delay={680}>
              <MagneticButton className="btn btn--bone" data-cursor="View" onClick={() => onNavigate("plp")}>
                <span>The Spring Collection</span>
                <span className="arrow">→</span>
              </MagneticButton>
            </Reveal>
          </div>
        </div>

        <div className="hero-bottom-bar">
          <Reveal delay={800}>
            <div className="hero-meta">Vol. 04 · Spring/Summer 2026 · Designed in L.A. · Built in V.N.</div>
          </Reveal>
          <Reveal delay={900}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 18, color: "rgba(242,235,224,0.85)" }}>
              <span className="num" style={{ fontFamily: '"GT Sectra","Instrument Serif",serif', fontSize: 56, fontStyle: "italic", lineHeight: 1 }}>10</span>
              <span className="hero-meta">Signature pieces · the bestsellers</span>
            </div>
          </Reveal>
        </div>
      </section>

      {/* PINNED CRAFT — the signature scroll moment */}
      <PinnedCraft onNavigate={onNavigate} />

      {/* TICKER */}
      <section className="press" aria-hidden="false">
        <div className="ticker">
          <span>Built to outlast its first owner</span>
          <span>Built to outlast its first owner</span>
          <span>Built to outlast its first owner</span>
          <span>Built to outlast its first owner</span>
        </div>
      </section>

      {/* HORIZONTAL COLLECTION */}
      <section className="h-collection" data-screen-label="02 Collection">
        <div className="heading-row">
          <div>
            <Reveal><div className="t-eyebrow" style={{ color: "rgba(242,235,224,0.55)" }}>Catalog Vol. 04 — five from fifty-nine</div></Reveal>
            <h2 className="t-h1" style={{ marginTop: 24, maxWidth: "14ch" }}>
              <RevealLines lines={["A short field guide", <span key="i" style={{ fontStyle: "italic" }}>to the Norwegian fjords.</span>]} gap={120} />
            </h2>
          </div>
          <Reveal delay={400}>
            <MagneticButton className="btn" style={{ color: "var(--bone)", borderColor: "rgba(242,235,224,0.4)" }} data-cursor="View" onClick={() => onNavigate("plp")}>
              <span>All 59 pieces</span><span className="arrow">→</span>
            </MagneticButton>
          </Reveal>
        </div>
        <div className="scroller" data-cursor="Drag →">
          {COLLECTION.map((p, i) => (
            <Reveal key={p.name} delay={i * 100} className="h-card" variant="img">
              <div className="h-card-img" style={{ backgroundImage: `url(${p.img})` }} onClick={() => onNavigate("pdp")} data-cursor="Open"></div>
              <div className="meta">
                <div>
                  <div className="name">{p.name}</div>
                  <div className="sub">{p.sub}</div>
                </div>
                <div className="price">{p.price}</div>
              </div>
            </Reveal>
          ))}
        </div>
      </section>

      {/* STORY */}
      <section className="story" data-screen-label="03 Story">
        <div className="story-grid">
          <div className="story-image-stack">
            <Reveal variant="img"><div className="a" style={{ backgroundImage: `url(${STORY_A})` }}></div></Reveal>
            <Reveal variant="img" delay={200}><div className="b" style={{ backgroundImage: `url(${STORY_B})` }}></div></Reveal>
          </div>
          <div className="story-text col" style={{ gap: 32 }}>
            <Reveal><div className="t-eyebrow" style={{ color: "var(--accent)" }}>The Atelier — Vietnam</div></Reveal>
            <h2 className="t-h2"><RevealLines lines={["Eight weeks,", "two pairs of hands,", <span key="i" style={{ fontStyle: "italic" }}>one through-tenon.</span>]} gap={100} /></h2>
            <Reveal delay={500}>
              <p className="t-body t-body-lg" style={{ color: "var(--ink-soft)", textWrap: "pretty" }}>
                Delina Living makes nothing on speculation. Astrid draws the piece from her studio in Los Angeles; the frame is dovetailed at the atelier, the legs are dry-fitted, the through-tenon is hand-finished and proud of the surface — and then we wait for the wood to settle for ten days before the final sand. The result is a piece you order in March and receive in May, that will be in your family in 2076.
              </p>
            </Reveal>
            <Reveal delay={700}>
              <MagneticButton className="btn btn--ghost" data-cursor="Read">
                <span>Inside the workshop</span><span className="arrow">→</span>
              </MagneticButton>
            </Reveal>
          </div>
        </div>
      </section>

      {/* PROOF / STATS */}
      <section className="proof">
        <Reveal>
          <div className="t-eyebrow" style={{ color: "var(--accent)" }}>By the numbers</div>
          <h2 className="t-h2" style={{ marginTop: 18, maxWidth: "16ch" }}><span style={{ fontStyle: "italic" }}>What "investment furniture"</span> actually means.</h2>
        </Reveal>
        <div className="proof-grid" style={{ marginTop: 64 }}>
          {[
            { num: "50", suf: "yr", lbl: "Frame warranty on every seating piece — the longest in the category." },
            { num: "8", suf: "wk", lbl: "Standard lead time, frame to door. Made-to-order, never warehoused." },
            { num: "1", suf: "", lbl: "Designer. Every piece by Astrid Vance, in-house since founding." },
            { num: "12", suf: "", lbl: "Craftspeople in our Vietnam atelier. Each trained a decade before touching a Delina Living joint." },
          ].map((s, i) => (
            <Reveal key={i} delay={i * 100} className="stat">
              <div className="num">{s.num}<span style={{ fontStyle: "normal", fontSize: "0.4em", marginLeft: 6, letterSpacing: "0.04em" }}>{s.suf}</span></div>
              <div className="lbl">{s.lbl}</div>
            </Reveal>
          ))}
        </div>
      </section>

      {/* PRESS LOGOS */}
      <div className="press-logos">
        {["Dwell", "Architectural Digest", "T Magazine", "Cereal", "Wallpaper*"].map((n) => (
          <Reveal key={n}><div>{n}</div></Reveal>
        ))}
      </div>

      {/* NEWSLETTER */}
      <section className="newsletter" data-screen-label="04 Newsletter">
        <div>
          <Reveal><div className="t-eyebrow" style={{ color: "var(--accent)" }}>The Delina Living Letter</div></Reveal>
          <h2 className="t-h2" style={{ marginTop: 18, maxWidth: "16ch" }}>
            <RevealLines lines={["One letter a month,", <span key="i" style={{ fontStyle: "italic" }}>about wood and rooms.</span>]} gap={100} />
          </h2>
        </div>
        <div className="col" style={{ gap: 16 }}>
          <Reveal>
            <p className="t-body" style={{ maxWidth: "44ch" }}>
              New pieces from the atelier, the occasional essay on materials, and early access to the Spring and Autumn drops. No discounts, no pop-ups, no urgency.
            </p>
          </Reveal>
          <Reveal delay={200}>
            <div className="form">
              <form onSubmit={(e) => e.preventDefault()}>
                <input type="email" placeholder="you@somewhere.com" data-cursor="Type" />
                <MagneticButton className="btn btn--solid" data-cursor="Send">
                  <span>Subscribe</span><span className="arrow">→</span>
                </MagneticButton>
              </form>
            </div>
          </Reveal>
        </div>
      </section>

      <Footer onNavigate={onNavigate} />
    </main>
  );
}

/* =================================================
   Pinned product + three craft details (Aesop/Bottega pattern)
================================================= */
function PinnedCraft({ onNavigate }) {
  const pinRef = useRef_h(null);
  const wrapRef = useRef_h(null);

  /* Slight scale of the image based on scroll progress through the section */
  useEffect_h(() => {
    const wrap = wrapRef.current;
    const img = pinRef.current;
    if (!wrap || !img) return;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    let raf;
    const tick = () => {
      const r = wrap.getBoundingClientRect();
      const total = r.height - window.innerHeight;
      const traveled = Math.min(Math.max(-r.top, 0), total);
      const p = total > 0 ? traveled / total : 0;
      const scale = 1 + p * 0.08;
      img.style.transform = `scale(${scale})`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const steps = [
    {
      n: "01",
      title: "The through-tenon.",
      body: "Every Delina Living piece exposes a hand-finished walnut through-tenon at the joint. It's a structural decision — the load passes through the wood, not the hardware — and an aesthetic one. You see how the chair is held together. We think you should.",
    },
    {
      n: "02",
      title: "Kiln-dried, then left to settle.",
      body: "We dry our acacia and walnut to 8% moisture, then let it sit in the atelier for ten days before final assembly. It's the part of the process no one would notice if we skipped it. We don't skip it.",
    },
    {
      n: "03",
      title: "Hand-rubbed, never sprayed.",
      body: "The finish is six coats of hardwax oil, hand-rubbed between coats with 0000 steel wool. It deepens the grain rather than coating it. After five years the piece looks better than the day it left the atelier — that's the test.",
    },
  ];

  return (
    <section className="pinned-craft" ref={wrapRef} data-screen-label="02 Pinned Craft">
      <div className="stage">
        <div className="pin">
          <div className="img" ref={pinRef} style={{ backgroundImage: `url(${PIN_IMG})` }}></div>
        </div>
        <div className="scroll-col">
          {steps.map((s) => (
            <div key={s.n} className="scroll-step">
              <Reveal><div className="step-num">{s.n} — Detail</div></Reveal>
              <h3 className="t-h2" style={{ fontSize: "clamp(36px, 4vw, 56px)" }}>
                <RevealLines lines={[s.title]} gap={80} />
              </h3>
              <Reveal delay={200}>
                <p className="t-body t-body-lg" style={{ maxWidth: "42ch", color: "var(--ink-soft)" }}>{s.body}</p>
              </Reveal>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

window.HomePage = HomePage;
