/* global React, Star4, StarBurst, StarRays, Squiggle, BlobTop, BlobCorner, useMagnetic, Nav, FooterCTA, Roadster, useTweaks, TweaksPanel, TweakSection, TweakColor, productHref */
const { useState, useRef, useEffect, useLayoutEffect } = React;

// ============================================================
//  PRODUCT HERO — photo arch left, details right
// ============================================================
function ProductHero({ product, variant, setVariant }) {
  const rootRef = useRef(null);
  const ctaRef = useMagnetic(0.15, 70);
  // Each product ships four bespoke shots — clicking a thumb swaps the arch photo.
  const [photoIdx, setPhotoIdx] = useState(0);

  useLayoutEffect(() => {
    const gsap = window.gsap;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const ctx = gsap.context(() => {
      const tl = gsap.timeline({ defaults: { ease: "power3.out" } });
      tl.set(".entry-swipe", { x: "-100%" })
        .to(".entry-swipe", { x: "100%", duration: 0.85, ease: "power3.inOut" }, 0)
        .to(".nav-wrap", { autoAlpha: 1, y: 0, duration: 0.45 }, 0.4)
        .fromTo(".pdp-shape-cyan-top", { autoAlpha: 0, y: -50 }, { autoAlpha: 1, y: 0, duration: 0.7 }, 0.5)
        .fromTo(".pdp-shape-cyan-br",  { autoAlpha: 0, x: 60 }, { autoAlpha: 1, x: 0, duration: 0.7 }, 0.55)
        .fromTo(".pdp-photo", { autoAlpha: 0, x: -50, scale: 0.92 }, { autoAlpha: 1, x: 0, scale: 1, duration: 0.85, ease: "back.out(1.2)" }, 0.6)
        .fromTo(".pdp-photo-burst", { autoAlpha: 0, scale: 0.3, rotation: -30 }, { autoAlpha: 1, scale: 1, rotation: 0, duration: 0.55, stagger: 0.1, ease: "back.out(1.7)" }, 0.9)
        .fromTo(".pdp-info > *", { autoAlpha: 0, y: 24 }, { autoAlpha: 1, y: 0, duration: 0.5, stagger: 0.07 }, 0.85)
        .fromTo(".pdp-stars > *", { autoAlpha: 0, scale: 0.3 }, { autoAlpha: 1, scale: 1, duration: 0.5, stagger: 0.05, ease: "back.out(2)" }, 1.0);

      if (!reduced) {
        gsap.utils.toArray(".pdp-stars > *").forEach((el, i) => {
          gsap.to(el, { rotation: 360, duration: 16 + i * 2, repeat: -1, ease: "none", transformOrigin: "50% 50%" });
        });
        gsap.to(".pdp-photo-burst.tl", { rotation: 360, duration: 24, ease: "none", repeat: -1, transformOrigin: "50% 50%" });
        gsap.to(".pdp-photo-burst.bl", { rotation: -360, duration: 28, ease: "none", repeat: -1, transformOrigin: "50% 50%" });
      }
    });
    return () => ctx.revert();
  }, []);

  return (
    <section ref={rootRef} className="pdp-hero" id="top">
      {/* background shapes */}
      <div className="pdp-shapes" aria-hidden="true">
        <div className="pdp-shape pdp-shape-cyan-top"><BlobTop color="var(--cyan)" /></div>
        <div className="pdp-shape pdp-shape-cyan-br"><BlobCorner color="var(--cyan)" /></div>
        {/* left-edge burst stars (bleed off the left side) */}
        <div className="pdp-shape pdp-star-burst tl"><StarRays /></div>
        <div className="pdp-shape pdp-star-burst bl"><StarRays /></div>
        <Squiggle className="pdp-squig-1" color="var(--red)" thick={6} />
        <Squiggle className="pdp-squig-2" color="var(--red)" thick={6} />
      </div>

      {/* sparkle stars */}
      <div className="pdp-stars" aria-hidden="true">
        <Star4 className="pdp-star-1" color="var(--cyan)" outlined outline="var(--ink)" />
        <Star4 className="pdp-star-2" color="var(--cyan)" outlined outline="var(--ink)" />
        <Star4 className="pdp-star-3" color="var(--cyan)" outlined outline="var(--ink)" />
        <Star4 className="pdp-star-4" color="var(--cream)" outlined outline="var(--ink)" />
      </div>

      <div className="pdp-grid">
        {/* breadcrumbs */}
        <nav className="pdp-breadcrumbs" aria-label="Breadcrumb">
          <a href="index.html">Home</a> <span>★</span> <a href="index.html#lineup">Lineup</a> <span>★</span> <strong>{product.name}</strong>
        </nav>

        {/* photo arch — left */}
        <div className="pdp-photo">
          <div className="ring-outer" />
          <div className="ring-mid" />
          <div className="ring-inner">
            <img src={product.gallery[photoIdx] || product.photo} alt={product.name} decoding="async" fetchpriority="high" />
          </div>
          <div className="pdp-photo-burst tl">
            <StarBurst color="var(--cream)" outline="var(--ink)" />
          </div>
          <div className="pdp-photo-burst bl">
            <StarBurst color="var(--cream)" outline="var(--ink)" />
          </div>
          {/* thumb row */}
          <div className="pdp-thumbs">
            {product.gallery.map((src, i) => (
              <button
                key={i}
                className={`pdp-thumb ${i === photoIdx ? "is-active" : ""}`}
                data-magnetic
                onClick={() => setPhotoIdx(i)}
                aria-pressed={i === photoIdx}
                aria-label={`View photo ${i + 1} of ${product.gallery.length}`}
              >
                <img src={src} alt="" loading="lazy" decoding="async" />
              </button>
            ))}
          </div>
        </div>

        {/* details — right */}
        <div className="pdp-info">
          <div className="pdp-eyebrow">
            <span className="ln" />
            <span>★ Cat. {product.sku}</span>
          </div>
          <h1 className="pdp-title">{product.name}<span className="dot">.</span></h1>
          <div className="pdp-tag">{product.tag}</div>

          {/* trust line — only claims we can actually stand behind */}
          <div className="pdp-rating">
            <span className="pdp-rev-count">★ Made to order — mock-up with every quote</span>
          </div>

          <p className="pdp-desc">{product.desc}</p>

          {/* Options modeled on Vistaprint food-packaging product pages:
              print coverage, size, material/wall, quantity tiers. */}
          {product.prints && product.prints.length > 0 && (
          <div className="pdp-option">
            <div className="pdp-opt-label">
              <span>Print</span>
              <span className="muted">{variant.print}</span>
            </div>
            <div className="pdp-sizes">
              {product.prints.map((p) => (
                <button
                  key={p}
                  className={`pdp-size ${variant.print === p ? "is-active" : ""}`}
                  aria-pressed={variant.print === p}
                  onClick={() => setVariant((v) => ({ ...v, print: p }))}
                  data-magnetic
                >{p}</button>
              ))}
            </div>
          </div>
          )}

          {product.sizes && product.sizes.length > 0 && (
          <div className="pdp-option">
            <div className="pdp-opt-label">
              <span>Size</span>
              <span className="muted">{variant.size}</span>
            </div>
            <div className="pdp-sizes">
              {product.sizes.map((s) => (
                <button
                  key={s}
                  className={`pdp-size ${variant.size === s ? "is-active" : ""}`}
                  aria-pressed={variant.size === s}
                  onClick={() => setVariant((v) => ({ ...v, size: s }))}
                  data-magnetic
                >{s}</button>
              ))}
            </div>
          </div>
          )}

          {product.materials && product.materials.length > 0 && (
          <div className="pdp-option">
            <div className="pdp-opt-label">
              <span>Material</span>
              <span className="muted">{variant.material}</span>
            </div>
            <div className="pdp-sizes">
              {product.materials.map((m) => (
                <button
                  key={m}
                  className={`pdp-size ${variant.material === m ? "is-active" : ""}`}
                  aria-pressed={variant.material === m}
                  onClick={() => setVariant((v) => ({ ...v, material: m }))}
                  data-magnetic
                >{m}</button>
              ))}
            </div>
          </div>
          )}

          {product.quantities && product.quantities.length > 0 && (
          <div className="pdp-option">
            <div className="pdp-opt-label">
              <span>Quantity</span>
              <span className="muted">{variant.quantity} units</span>
            </div>
            <div className="pdp-sizes">
              {product.quantities.map((q) => (
                <button
                  key={q}
                  className={`pdp-size ${variant.quantity === q ? "is-active" : ""}`}
                  aria-pressed={variant.quantity === q}
                  onClick={() => setVariant((v) => ({ ...v, quantity: q }))}
                  data-magnetic
                >{q}</button>
              ))}
            </div>
          </div>
          )}

          {/* call to action — quote, not checkout */}
          <div className="pdp-buy">
            <a ref={ctaRef} href="contact.html" className="btn-pill btn-red pdp-cart" data-magnetic>
              Request a Quote →
            </a>
          </div>

          {/* perks */}
          <ul className="pdp-perks">
            <li><span>★</span> Pantone-matched custom print</li>
            <li><span>★</span> Recycled &amp; compostable options</li>
            <li><span>★</span> Printed &amp; finished in our shop</li>
          </ul>
        </div>
      </div>
    </section>
  );
}

// ============================================================
//  SPECS — 4-up grid
// ============================================================
function Specs({ product }) {
  const rootRef = useRef(null);
  useLayoutEffect(() => {
    const gsap = window.gsap;
    const ctx = gsap.context(() => {
      gsap.fromTo(".spec-ticket",
        { autoAlpha: 0, y: 40, rotation: 4 },
        { autoAlpha: 1, y: 0, rotation: 1.2, duration: 0.8, ease: "back.out(1.3)",
          scrollTrigger: { trigger: ".spec-ticket", start: "top 82%" } });
      gsap.fromTo(".spec-row",
        { autoAlpha: 0, x: -14 },
        { autoAlpha: 1, x: 0, duration: 0.45, stagger: 0.06,
          scrollTrigger: { trigger: ".spec-ticket", start: "top 78%" } });
    }, rootRef);
    return () => ctx.revert();
  }, []);

  return (
    <section ref={rootRef} className="pdp-specs">
      <div className="section pdp-specs-cols">
        <div className="pdp-specs-intro">
          <div className="section-eyebrow"><span className="ln" /><span className="t-label">★ Spec Sheet</span></div>
          <h2 className="h2">Down to the<br/><span className="alt">last detail.</span></h2>
          <p className="pdp-specs-sub">
            Pick your size and run up top — this is the fixed stuff: materials,
            food safety, and the fine print. Anything not listed comes with
            your quote, just ask.
          </p>
          <a className="pdp-specs-link" href="contact.html" data-magnetic>
            Take this ticket to the counter →
          </a>
        </div>

        {/* the guest check — specs rung up like a diner receipt */}
        <div className="spec-ticket">
          <div className="spec-ticket-head" aria-hidden="true">
            <span className="star">★</span>ORDER UP!<span className="star">★</span>
          </div>
          <div className="spec-ticket-meta">
            <span>Guest check</span>
            <span>№ {product.sku}</span>
          </div>
          <ul className="spec-rows">
            {product.specs
              // Size & Material live as interactive pickers in the hero above —
              // the ticket carries only the fixed "fine print" you can't click.
              .filter((s) => !/^(sizes?|materials?)$/i.test(s.name.trim()))
              .map((s, i) => (
                <li key={s.name} className="spec-row">
                  <span className="spec-key"><em>{String(i + 1).padStart(2, "0")}</em>{s.name}</span>
                  <span className="spec-dots" aria-hidden="true" />
                  <span className="spec-val">{s.value}</span>
                </li>
              ))}
          </ul>
          <div className="spec-ticket-foot" aria-hidden="true">★ Thank you — come again ★</div>
        </div>
      </div>
    </section>
  );
}

// ============================================================
//  CUSTOMIZATION callout — cyan band
// ============================================================
function Customize({ product }) {
  const rootRef = useRef(null);
  const ctaRef = useMagnetic(0.15, 70);

  useLayoutEffect(() => {
    const gsap = window.gsap;
    const ctx = gsap.context(() => {
      gsap.fromTo(".pdp-customize-card",
        { autoAlpha: 0, y: 40 },
        { autoAlpha: 1, y: 0, duration: 0.7, stagger: 0.12,
          scrollTrigger: { trigger: ".pdp-customize-grid", start: "top 80%" }
        });
    }, rootRef);
    return () => ctx.revert();
  }, []);

  return (
    <section ref={rootRef} className="pdp-customize">
      <div className="section">
        <div className="pdp-customize-head">
          <div>
            <div className="section-eyebrow light"><span className="ln" /><span className="t-label">★ Make it yours</span></div>
            <h2 className="h2 light">Put your name<br/>on the <span className="alt2">cup.</span></h2>
          </div>
          <p className="sub light">
            Send us your logo, brand colors, or a napkin sketch — we&rsquo;ll
            mock it up with your quote. Single-color screen print to four-color
            offset, all Pantone-matched, all printed in the shop.
          </p>
        </div>

        <div className="pdp-customize-grid">
          {[
            { n: "01", t: "Single-color", d: "Logo or wordmark in one ink. Our most popular finish.", c: "var(--yellow)" },
            { n: "02", t: "Two-color", d: "Logo plus an accent, hand-registered on press.", c: "var(--cream)" },
            { n: "03", t: "Full-color", d: "Photo-quality 4-color process. Up to 200 lpi.", c: "var(--red)" },
          ].map((o, i) => (
            <div key={i} className="pdp-customize-card" style={{ background: o.c }}>
              <div className="num">{o.n}</div>
              <h3>{o.t}</h3>
              <p>{o.d}</p>
            </div>
          ))}
        </div>

        {/* The Special Craft — house finishes, shown on paper cups only */}
        {product && product.craft ? (
          <div className="pdp-craft">
            <div className="pdp-craft-head">
              <h3 className="pdp-craft-title">★ The Special Craft</h3>
              <p className="pdp-craft-lead">
                House finishes, quoted with any paper cup — point at one and
                we&rsquo;ll price it with your run.
              </p>
            </div>
            <div className="pdp-craft-row" role="list">
              {(window.WC_CRAFTS || []).map((c) => (
                <figure key={c.name} className="pdp-craft-tile" role="listitem">
                  <img src={c.photo} alt={c.alt} loading="lazy" decoding="async" />
                  <figcaption>{c.name}</figcaption>
                </figure>
              ))}
            </div>
            <a className="pdp-craft-link" href="blog/premium-cup-finishes.html">Read the finishes guide →</a>
          </div>
        ) : null}

        <div className="pdp-customize-cta">
          <a ref={ctaRef} href="contact.html" className="btn-pill btn-red" data-magnetic>
            Send us a sketch →
          </a>
        </div>
      </div>
    </section>
  );
}

// ============================================================
//  PAIRS WITH — related products
// ============================================================
function PairsWith() {
  const rootRef = useRef(null);
  useLayoutEffect(() => {
    const gsap = window.gsap;
    const ctx = gsap.context(() => {
      gsap.fromTo(".pdp-pair-card",
        { autoAlpha: 0, y: 50 },
        { autoAlpha: 1, y: 0, duration: 0.7, stagger: 0.1, ease: "power3.out",
          scrollTrigger: { trigger: ".pdp-pair-grid", start: "top 80%" }
        });
    }, rootRef);
    return () => ctx.revert();
  }, []);

  const items = [
    { n: "02", name: "Noodle Buckets", desc: "The fold-top takeout pail, microwave-safe kraft.", photo: "assets/products/noodle-buckets-1.jpg", c: "var(--red)" },
    { n: "03", name: "Snap / Card-Buckle Sleeves", desc: "Ships flat, snaps on — full-wrap sleeve art.", photo: "assets/products/snap-card-buckle-sleeves-1.jpg", c: "var(--yellow)" },
    { n: "04", name: "Custom Cup Stickers", desc: "Die-cut stickers — brand stock cups, low MOQ.", photo: "assets/products/custom-cup-stickers-1.jpg", c: "var(--cream)" },
  ];

  return (
    <section ref={rootRef} className="pdp-pairs">
      <div className="section">
        <div className="section-eyebrow"><span className="ln" /><span className="t-label">★ Pairs Well With</span></div>
        <h2 className="h2">Pull up<br/><span className="alt">another stool.</span></h2>

        <div className="pdp-pair-grid">
          {items.map((it, i) => (
            <a key={i} href={productHref(it.name)} className="pdp-pair-card" style={{ background: it.c }} data-magnetic>
              <div className="pdp-pair-photo">
                <img src={it.photo} alt="" loading="lazy" decoding="async" />
              </div>
              <div className="pdp-pair-meta">
                <div className="pdp-pair-num">★ {it.n}</div>
                <h3 className="pdp-pair-name">{it.name}</h3>
                <p className="pdp-pair-desc">{it.desc}</p>
                <div className="pdp-pair-foot">
                  <span className="price">View details</span>
                  <span className="arrow">→</span>
                </div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

// expose
Object.assign(window, { ProductHero, Specs, Customize, PairsWith });
