// All page sections — marquee, nav, hero, shop catalog, podcast teaser, footer.

const MARQUEE_ITEMS = [
  "MR. GARBAGE U.S.A.",
  "GARBAGE IS BEAUTIFUL",
  "DROP 01 · OUT NOW",
  "FREE HAULING ON LOADS OVER $80",
  "PODCAST · S/01 ARRIVING SOON",
  "MMXXVI",
];

function Marquee() {
  const items = [...MARQUEE_ITEMS, ...MARQUEE_ITEMS, ...MARQUEE_ITEMS];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {items.map((t, i) => (
          <span key={i}><span className="dot" /> {t}</span>
        ))}
      </div>
    </div>
  );
}

const NAV_ITEMS = [
  { href: "#top", label: "Home", num: "01" },
  { href: "#shop", label: "Shop", num: "02" },
  { href: "#podcast", label: "Podcast", num: "03" },
  { href: "#founder", label: "About", num: "04" },
  { href: "#about", label: "Contact", num: "05" },
];

function Nav({ cartCount, bumping, onCartClick }) {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.body.style.overflow = open ? "hidden" : "";
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);

  return (
    <React.Fragment>
      <nav className="nav" aria-label="Primary">
        <a href="#top" className="nav-logo swarm" aria-label="Mr. Garbage U.S.A. — home">
          <img src="assets/logo-wordmark.png" alt="Mr. Garbage U.S.A." className="nav-logo-img" />
        </a>
        <div className="nav-links" role="menubar">
          {NAV_ITEMS.filter(i => i.label !== "Home").map(i => (
            <a key={i.href} href={i.href} className="swarm" role="menuitem">{i.label}</a>
          ))}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <CartPill count={cartCount} bumping={bumping} onClick={onCartClick} />
          <button
            className={`nav-toggle swarm ${open ? "open" : ""}`}
            onClick={() => setOpen(!open)}
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            aria-controls="mobile-menu"
          >
            <span className="bar" aria-hidden />
          </button>
        </div>
      </nav>

      <div id="mobile-menu" className={`nav-mobile ${open ? "open" : ""}`} role="dialog" aria-modal="true" aria-hidden={!open}>
        <ul>
          {NAV_ITEMS.map(i => (
            <li key={i.href}>
              <a href={i.href} onClick={() => setOpen(false)}>
                <span>{i.label}</span>
                <span className="num">{i.num}</span>
              </a>
            </li>
          ))}
        </ul>
        <div className="nav-mobile-foot">
          <span>MONROE, CT</span>
          <span>EST. 1982</span>
        </div>
      </div>
    </React.Fragment>
  );
}

function Hero() {
  const videoRef = React.useRef(null);

  React.useEffect(() => {
    const v = videoRef.current;
    if (!v) return;
    // respect reduced motion
    const reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) {
      v.removeAttribute("autoplay");
      v.pause();
      return;
    }
    // some browsers need explicit play after metadata loads
    const tryPlay = () => { v.play && v.play().catch(() => {}); };
    v.addEventListener("loadedmetadata", tryPlay);
    return () => v.removeEventListener("loadedmetadata", tryPlay);
  }, []);

  return (
    <section id="top" className="hero">
      <div className="hero-video">
        <video
          ref={videoRef}
          src="assets/landfill-hero.mp4"
          poster="assets/landfill-hero-poster.jpg"
          autoPlay
          muted
          loop
          playsInline
          preload="metadata"
          aria-hidden="true"
        />
      </div>
      <div className="hero-rule top" aria-hidden />
      <div className="hero-rule bottom" aria-hidden />

      <div className="hero-content">
        <div className="container">
          <div className="hero-block">
            <div className="hero-tag reveal in">
              <span className="text">garbage is beautiful.</span>
            </div>

            <p className="hero-sub reveal delay-2">
              Part catalog. Part broadcast. Built from the work nobody sees.
            </p>

            <div className="hero-cta-row reveal delay-3">
              <a href="#shop" className="btn btn-primary swarm" aria-label="Shop the Garbage catalog">
                Shop the Garbage <span className="arrow">→</span>
              </a>
              <a href="#podcast" className="btn btn-ghost swarm" aria-label="Listen to the broadcast">
                Listen Now <span className="arrow">→</span>
              </a>
            </div>

            <p className="hero-origin reveal delay-3">
              Built in Monroe, Connecticut. Since 1982.
            </p>

            <img
              src="assets/seal.png"
              alt="Garbage Is Beautiful — official seal"
              className="hero-seal reveal delay-3"
            />
          </div>
        </div>
      </div>
    </section>
  );
}

const PRODUCTS = [
  { cat: "MG-001", name: "Logo Tee",       desc: "100% Combed Cotton · Printed in PA",        price: 32, tag: "new",    tagText: "NEW",      category: "apparel" },
  { cat: "MG-002", name: "Trucker Hat",    desc: "Foam Front · Mesh Back · Embroidered",      price: 28, tag: null,     tagText: null,       category: "accessories" },
  { cat: "MG-003", name: "Roll-Off Pin",   desc: "Hard Enamel on Brass · 1.25\"",             price: 12, tag: "new",    tagText: "NEW",      category: "accessories" },
  { cat: "MG-004", name: "Manifesto Tote", desc: "12oz Canvas · Screen-Printed",              price: 24, tag: null,     tagText: null,       category: "accessories" },
  { cat: "MG-005", name: "Box Mug",        desc: "Stoneware · 14oz · Dishwasher Safe",        price: 18, tag: "limited",tagText: "LIMITED",  category: "accessories" },
  { cat: "MG-006", name: "Specimen Print", desc: "Riso · 11×17 · Numbered Ed/200",            price: 45, tag: "drop",   tagText: "DROP 01",  category: "drops" },
  { cat: "MG-007", name: "Workshirt",      desc: "Twill · Chain-Stitched Patch · Unisex",     price: 88, tag: "soldout",tagText: "SOLD OUT", soldout: true, category: "apparel" },
  { cat: "MG-008", name: "Crew Sweat",     desc: "Reverse-Weave Fleece · Embroidered Tongue", price: 96, tag: "limited",tagText: "LIMITED",  category: "apparel" },
  { cat: "MG-009", name: "Field Cap",      desc: "Six-Panel · Brushed Twill · Adjustable",    price: 38, tag: null,     tagText: null,       category: "apparel" },
];

const SHOP_FILTERS = [
  { key: "all",         label: "All" },
  { key: "apparel",     label: "Apparel" },
  { key: "accessories", label: "Accessories" },
  { key: "drops",       label: "Limited Drops" },
];

function Product({ p, onAdd }) {
  return (
    <article className="product swarm">
      <div className="product-photo">
        <span className="ph-label" aria-hidden>PHOTO TO COME</span>
        {p.tagText && <span className={`ph-tag ${p.tag}`}>{p.tagText}</span>}
        <span className="ph-cat">{p.cat}</span>
        <span className="ph-mark">{p.name.split(" ")[0]}</span>
      </div>
      <div className="product-meta">
        <div className="left">
          <div className="cat">NO. {p.cat}</div>
          <div className="name">{p.name}</div>
        </div>
        <div className="price">${p.price}</div>
      </div>
      <p className="product-desc">{p.desc}</p>
      <button
        className={`product-cta swarm ${p.soldout ? "disabled" : ""}`}
        onClick={() => !p.soldout && onAdd(p)}
        disabled={p.soldout}
      >
        {p.soldout ? "Sold Out" : "+ Add to Haul"}
      </button>
    </article>
  );
}

function Exhibit({ exhibitRef, lidRef, contentsRef }) {
  return (
    <section id="exhibit" className="section exhibit" aria-labelledby="exhibit-heading">
      <div className="container">
        <div className="reveal">
          <div className="section-tag">
            <span className="num">EXHIBIT 01</span>
            <span className="bar" />
            <span>FIELD STUDY · THE ROLL-OFF</span>
          </div>
          <div className="exhibit-head">
            <h2 id="exhibit-heading" className="exhibit-headline">
              Two&nbsp;hundred&nbsp;thousand
              <br />
              roll-offs in service across the United States, est.&nbsp;2024.
            </h2>
            <p className="exhibit-copy">
              Dempsey Dumpster Service patented the first roll-off body in 1935, in Knoxville, Tennessee. The container that emerged — a steel trapezoid, eight feet wide, painted a green that has never quite left us — is still the silhouette we recognize on every back lot from Bangor to Bakersfield. <em>Open it.</em>
            </p>
          </div>
        </div>

        <div className="exhibit-stage" ref={exhibitRef}>
          <Dumpster lidRef={lidRef} contentsRef={contentsRef} color="#3A4A2F" trim="#1A1A1A" label="ROLL-OFF · 30YD" id="DPST-001" />
          <div className="exhibit-foot">
            <span><strong>FIG. 1</strong> — open by scrolling</span>
            <span>UNIT NO. DPST-001 · DEPLOYED MONROE, CT</span>
          </div>
        </div>
      </div>
    </section>
  );
}

function FounderNote() {
  return (
    <section id="founder" className="section founder">
      <div className="container">
        <div className="reveal">
          <div className="section-tag">
            <span className="num">FORM 02</span>
            <span className="bar" />
            <span>FIELD NOTE · ORIGIN · ON FILE</span>
          </div>
          <h2 className="section-title">Field Note: Pat Caruso.</h2>
        </div>

        <div className="founder-card reveal delay-1">
          <div className="founder-photo">
            <span className="ph-label">PAT PHOTO TO COME</span>
            <span className="date-stamp">EST. 1982</span>
            <span className="ph-stamp">FILE · 02/A</span>
            <img src="assets/mascot.png" alt="Mr. Garbage U.S.A. mascot — standing in for Pat" className="ph-mascot" />
          </div>
          <div className="founder-text">
            <div>
              <div className="founder-eyebrow">FOUNDER · ASSOCIATED REFUSE</div>
              <div className="founder-name">Pat Caruso.</div>
              <div className="founder-role">Monroe, CT · driver, dispatcher, owner of the phone</div>
              <p className="founder-blurb">
                Founded in <em>1982</em>, built one delivery at a time.<br/>
                Still local. <em>Still close to the work.</em>
              </p>
              <div className="founder-sig">
                <span>P. Caruso</span>
                <span className="line" />
                <span className="meta">SIGNED · ON FILE</span>
              </div>
            </div>

            <div className="founder-meta">
              <div>
                <div className="k">Origin</div>
                <div className="v">Monroe, CT</div>
              </div>
              <div>
                <div className="k">Established</div>
                <div className="v">1982</div>
              </div>
              <div>
                <div className="k">Service area</div>
                <div className="v">39 towns</div>
              </div>
              <div>
                <div className="k">Yard</div>
                <div className="v">Hattertown Rd.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Shop({ onAdd }) {
  const [filter, setFilter] = React.useState("all");
  const visible = filter === "all" ? PRODUCTS : PRODUCTS.filter(p => p.category === filter);
  const counts = SHOP_FILTERS.reduce((acc, f) => {
    acc[f.key] = f.key === "all" ? PRODUCTS.length : PRODUCTS.filter(p => p.category === f.key).length;
    return acc;
  }, {});

  return (
    <section id="shop" className="section shop" aria-labelledby="shop-heading">
      <div className="container">
        <div className="reveal">
          <div className="section-tag">
            <span className="num">FORM 02</span>
            <span className="bar" />
            <span>THE COMPANY STORE · DROP 01</span>
          </div>
          <h2 id="shop-heading" className="section-title">
            Goods, plainly made.
          </h2>
          <p className="section-desc" style={{ marginTop: 18 }}>
            Nine items. Printed and assembled in small runs. Each carries a catalog number and a quiet sense of its own materials.
          </p>
        </div>

        <div className="shop-filters reveal delay-1" role="tablist" aria-label="Filter by category">
          {SHOP_FILTERS.map(f => (
            <button
              key={f.key}
              role="tab"
              aria-selected={filter === f.key}
              className={`filter-pill swarm ${filter === f.key ? "active" : ""}`}
              onClick={() => setFilter(f.key)}
            >
              {f.label}<span className="count">{counts[f.key]}</span>
            </button>
          ))}
        </div>

        <div className="shop-grid">
          {visible.length === 0 && <div className="shop-empty">Nothing in this bin yet.</div>}
          {visible.map((p, i) => (
            <div key={p.cat} className={`reveal delay-${(i % 4) + 1}`}>
              <Product p={p} onAdd={onAdd} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

const EPISODES = [
  { num: "001", title: "Patient Zero",      date: "S/01 · 05.12" },
  { num: "002", title: "The Crusher Sermon", date: "S/01 · 05.19" },
  { num: "003", title: "Found Items",       date: "S/01 · 05.26" },
  { num: "004", title: "On Beauty",         date: "S/01 · 06.02" },
];

function Newsletter() {
  const [email, setEmail] = React.useState("");
  const [submitted, setSubmitted] = React.useState(false);

  const onSubmit = (e) => {
    e.preventDefault();
    if (!email) return;
    // TODO: connect to email provider (Klaviyo / Mailchimp / Buttondown).
    // For now this is a placeholder that just acknowledges the submission.
    setSubmitted(true);
  };

  return (
    <section id="newsletter" className="section newsletter">
      <div className="container">
        <div className="reveal">
          <div className="section-tag">
            <span className="num">FORM 04</span>
            <span className="bar" />
            <span>MAILING SLIP · BI-WEEKLY</span>
          </div>
          <h2 className="section-title">Get the Broadcast.</h2>
        </div>

        <div className="newsletter-card reveal delay-1">
          <div className="newsletter-text">
            <div className="newsletter-eyebrow">SIGN THE MANIFEST</div>
            <h3 className="newsletter-title">A short note,<br/>once a fortnight.</h3>
            <p className="newsletter-copy">
              New drops, field notes, and episode announcements — sent when there's something worth hauling.
            </p>
            <div className="newsletter-stamp">
              <span className="pip" /> NO SPAM · UNSUBSCRIBE BY SETTING ON FIRE
            </div>
          </div>

          <form className="newsletter-form" onSubmit={onSubmit} noValidate>
            <div>
              <div className="newsletter-form-label">
                <span>TYPE MAIL</span>
                <span className="ticket">TICKET 04 · 2026</span>
              </div>
              <div className="newsletter-form-row">
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="hauler@yourdomain.com"
                  aria-label="Email address"
                  disabled={submitted}
                />
                <button type="submit" className="swarm" disabled={submitted}>
                  {submitted ? "Signed ✓" : "Sign Up →"}
                </button>
              </div>
              {submitted && (
                <div className="newsletter-success">You're on the manifest.</div>
              )}
            </div>
            <div className="newsletter-foot">
              Bi-weekly dispatch · field notes, broadcast updates, occasional photographs of receptacles.
            </div>
          </form>
        </div>
      </div>
    </section>
  );
}

function PodcastTeaser() {
  return (
    <section id="podcast" className="section podcast">
      <div className="container">
        <div className="reveal">
          <div className="section-tag">
            <span className="num">FORM 03</span>
            <span className="bar" />
            <span>BROADCAST · COMING SOON</span>
          </div>
          <h2 className="section-title">Podcast.<br/>Coming soon.</h2>
        </div>

        <div className="podcast-grid">
          <div className="reveal delay-1">
            <div className="player">
              <div className="player-status">
                <span className="live-dot" />
                <span>S/01 · ARRIVING 05.12</span>
              </div>
              <div className="player-art">
                <img src="assets/crest.png" alt="Garbage Is Beautiful — Season 01 cover art" className="player-art-img" />
              </div>
              <div className="player-meta">
                <div>
                  <div className="player-track-name">Patient Zero</div>
                  <div className="player-track-sub">EP. 001 · PREVIEW</div>
                </div>
              </div>
              <div className="player-controls">
                <button className="player-play swarm" aria-label="Play preview">
                  <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor"><path d="M0 0v16l14-8z" /></svg>
                </button>
                <div className="player-bar" />
                <span className="player-time">01:40</span>
              </div>
            </div>
          </div>

          <div className="reveal delay-2">
            <div className="episode-list" aria-label="Upcoming episodes">
              {EPISODES.map((ep) => (
                <div key={ep.num} className="episode swarm" role="listitem">
                  <div className="episode-num">{ep.num}</div>
                  <div className="episode-info">{ep.title}</div>
                  <div className="episode-meta">{ep.date}</div>
                </div>
              ))}
            </div>
            <div className="subscribe-row" aria-label="Subscribe on">
              <a href="#" className="subscribe-pill swarm" aria-label="Subscribe on Apple Podcasts">
                <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d="M12 2a10 10 0 100 20 10 10 0 000-20zm0 5a3 3 0 110 6 3 3 0 010-6zm0 9c2.2 0 4 1.5 4 3v1H8v-1c0-1.5 1.8-3 4-3z"/></svg>
                Apple
              </a>
              <a href="#" className="subscribe-pill swarm" aria-label="Subscribe on Spotify">
                <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden><circle cx="12" cy="12" r="10"/><path d="M7 10c3-1 7-1 10 1M8 13c2-1 5-1 8 1M9 16c1.5-.5 4-.5 6 .5" stroke="#0E0E0E" strokeWidth="1.4" fill="none"/></svg>
                Spotify
              </a>
              <a href="#" className="subscribe-pill swarm" aria-label="Subscribe via Overcast">
                <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden><circle cx="12" cy="12" r="10"/><path d="M12 6v9M9 12l3 3 3-3" stroke="#0E0E0E" strokeWidth="1.6" fill="none"/></svg>
                Overcast
              </a>
              <a href="#" className="subscribe-pill swarm" aria-label="Subscribe via RSS">
                <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d="M5 5v3c7 0 11 4 11 11h3c0-9-5-14-14-14zM5 11v3c4 0 5 1 5 5h3c0-5-3-8-8-8zM6 17a2 2 0 100 4 2 2 0 000-4z"/></svg>
                RSS
              </a>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer id="about" className="footer">
      <div className="container">
        <div className="ticket">
          {[
            ["TICKET", "04-2026-0142"],
            ["DRIVER", "M. GARBAGE"],
            ["ORIGIN", "MONROE, CT"],
            ["DEST.", "EVERYWHERE"],
            ["GROSS", "048,201 LBS"],
            ["NET", "048,201 LBS"],
          ].map(([k, v], i) => (
            <div key={i} className="ticket-cell">
              <div className="k">{k}</div>
              <div className="v">{v}</div>
            </div>
          ))}
        </div>

        <div className="footer-grid">
          <div className="footer-col">
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 36, fontWeight: 600, lineHeight: 1, letterSpacing: "-0.01em" }}>
              <span>Mr. Garbage</span>
              <span className="mono" style={{ fontStyle: "normal", color: "var(--red)", fontWeight: 700, fontSize: 13, letterSpacing: "0.22em", border: "1.5px solid var(--red)", padding: "2px 6px 1px", transform: "translateY(-4px)", display: "inline-block" }}>U·S·A</span>
            </div>
            <p style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 18, color: "var(--ink-soft)", lineHeight: 1.5, marginTop: 14, maxWidth: 360 }}>
              A small catalog of goods and a forthcoming broadcast. Founded by Pat Caruso in Monroe, CT, 1982.
            </p>
            <img src="assets/seal.png" alt="Garbage Is Beautiful seal" className="footer-seal" />
          </div>
          <div className="footer-col">
            <h4>Show</h4>
            <ul>
              <li><a href="#podcast" className="swarm">Episodes</a></li>
              <li><a href="#" className="swarm">About</a></li>
              <li><a href="#" className="swarm">Press</a></li>
              <li><a href="#" className="swarm">Hosts</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Store</h4>
            <ul>
              <li><a href="#shop" className="swarm">Shop all</a></li>
              <li><a href="#" className="swarm">Shipping</a></li>
              <li><a href="#" className="swarm">Returns</a></li>
              <li><a href="#" className="swarm">Wholesale</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Elsewhere</h4>
            <ul>
              <li><a href="#" className="swarm">Instagram</a></li>
              <li><a href="#" className="swarm">RSS</a></li>
              <li><a href="#" className="swarm">Bandcamp</a></li>
              <li><a href="#" className="swarm">Type mail</a></li>
            </ul>
          </div>
        </div>

        <div className="footer-bottom">
          <span style={{ flex: 1, textAlign: "left" }}>© MMXXVI · MR. GARBAGE U.S.A.</span>
          <span style={{ flex: 1, textAlign: "center" }}>END OF HAUL</span>
          <span style={{ flex: 1, textAlign: "right" }}>SCALE TICKET 0142 · SIGNED M.G.</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Marquee, Nav, Hero, Exhibit, FounderNote, Shop, Newsletter, PodcastTeaser, Footer });
