// pages-home.jsx — Home + Shop + Product pages

const { useState: useStateHS, useEffect: useEffectHS, useMemo } = React;

// ─────────────────────────────────────────────────────────────────────────────
// HOME
function HomePage({ navigate, addToCart }) {
  const featured = (window.PRODUCTS || []).slice(0, 4);
  const totalCount = (window.PRODUCTS || []).length;
  return (
    <main data-screen-label="Home">
      {/* HERO — cinematic 3D scroll (human → DNA → peptide) */}
      <HeroSection3D navigate={navigate} />

      {/* TRUST BAR */}
      <section style={{ paddingTop: 80 }}>
        <div className="container">
          <TrustBar />
        </div>
      </section>

      {/* FEATURED PRODUCTS */}
      <section style={{ paddingTop: 120 }}>
        <div className="container">
          <SectionHeader
            eyebrow="Catalog · Featured"
            title="A small catalog, intentionally."
            action={
              <Button variant="secondary" onClick={() => navigate("shop")}>View all {totalCount || ""}</Button>
            }
          />
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 32,
          }} className="product-grid">
            {featured.map((p) => <ProductCard key={p.id} product={p} navigate={navigate} />)}
          </div>
        </div>
      </section>

      {/* ABOUT TEASER */}
      <section style={{ paddingTop: 140 }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "1fr 1.2fr",
            gap: 80,
            alignItems: "center",
          }} className="about-teaser">
            <div style={{
              width: "100%",
              aspectRatio: "4/5",
              overflow: "hidden",
              border: "1px solid var(--border)",
              position: "relative",
            }}>
              <img
                src="assets/lab-desk.jpg"
                alt="Genmax laboratory — researchers at work"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                  objectPosition: "center",
                  display: "block",
                }}
              />
            </div>
            <div>
              <Eyebrow>About Genmax</Eyebrow>
              <h2 style={{
                fontSize: 44,
                fontWeight: 400,
                letterSpacing: "-0.025em",
                margin: "16px 0 0",
                lineHeight: 1.08,
              }}>
                Founded by researchers who needed peptides they could actually trust.
              </h2>
              <p style={{ fontSize: 15, lineHeight: 1.7, color: "var(--muted)", marginTop: 28, maxWidth: 540 }}>
                Genmax Laboratories produces and sources peptides exclusively for research and laboratory
                use. Every compound is HPLC-verified by an independent partner laboratory before it
                ever leaves our facility. No marketing claims. No medical promises. Just clean data,
                clean compounds, and transparent paperwork.
              </p>
              <div style={{ marginTop: 32 }}>
                <Button variant="secondary" onClick={() => navigate("about")}>Read our standards →</Button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* PROCESS */}
      <section style={{ paddingTop: 140 }}>
        <div className="container">
          <SectionHeader eyebrow="How it works" title="From order to laboratory, in four steps." />
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(4, 1fr)",
            gap: 32,
          }} className="process-grid">
            {[
              ["01", "Select", "Browse the catalog. Every product lists its purity, batch, and intended research use."],
              ["02", "Verify", "Download the third-party HPLC report and certificate of analysis for the exact batch you'll receive."],
              ["03", "Order", "Place your order through encrypted checkout. Lab credentials reviewed where required."],
              ["04", "Receive", "Cold-chain insulated shipment, 2-day worldwide. Tracking and batch documents emailed at dispatch."],
            ].map(([n, t, d]) => (
              <div key={n} style={{ borderTop: "1px solid var(--fg)", paddingTop: 20 }}>
                <Code>{n}</Code>
                <h4 style={{ fontSize: 18, fontWeight: 500, margin: "16px 0 8px", letterSpacing: "-0.01em" }}>{t}</h4>
                <p style={{ fontSize: 13, color: "var(--muted)", lineHeight: 1.6, margin: 0 }}>{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section style={{ paddingTop: 140 }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "1fr 1.5fr",
            gap: 80,
          }} className="faq-grid">
            <div>
              <Eyebrow>FAQ</Eyebrow>
              <h2 style={{
                fontSize: 40,
                fontWeight: 400,
                letterSpacing: "-0.025em",
                margin: "16px 0 0",
                lineHeight: 1.1,
              }}>The questions we get most often.</h2>
              <p style={{ fontSize: 14, color: "var(--muted)", marginTop: 24, lineHeight: 1.6 }}>
                Can't find what you're looking for?{" "}
                <a href="#contact" onClick={(e) => { e.preventDefault(); navigate("contact"); }} style={{ color: "var(--accent)", textDecoration: "none", borderBottom: "1px solid currentColor" }}>Contact our lab</a>.
              </p>
            </div>
            <div>
              <FAQItem defaultOpen q="Are Genmax peptides for human consumption?"
                a="No. All Genmax products are sold strictly for research and laboratory use. They are not intended for human or veterinary consumption, diagnostic use, or therapeutic application. By purchasing, you confirm you are a qualified researcher." />
              <FAQItem q="How is purity verified?"
                a="Every batch is analyzed by HPLC at our facility and re-verified by an independent third-party laboratory. The certificate of analysis (COA) for your specific batch is available on each product page and emailed with your order." />
              <FAQItem q="How are shipments handled?"
                a="Peptides are lyophilized, sealed in inert atmosphere, and shipped in insulated cold-chain packaging with phase-change cooling. 2-day worldwide delivery with full tracking. Refrigeration on arrival is recommended." />
              <FAQItem q="Do you ship internationally?"
                a="Yes. We ship to most countries where research peptides are permitted. Local regulations apply — please confirm import allowances for your jurisdiction before ordering." />
              <FAQItem q="What if my order arrives damaged?"
                a="Every shipment is insured. If a vial arrives damaged or temperature-compromised, contact us within 48 hours with photos and we'll dispatch a replacement at no cost." />
            </div>
          </div>
        </div>
      </section>

      {/* NEWSLETTER */}
      <section style={{ paddingTop: 140 }}>
        <div className="container">
          <Newsletter />
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// SHOP
function ShopPage({ navigate }) {
  const all = window.PRODUCTS || [];
  const cats = ["All", ...Array.from(new Set(all.map((p) => p.category)))];
  const [cat, setCat] = useStateHS("All");
  const [sort, setSort] = useStateHS("featured");
  const filtered = useMemo(() => {
    let r = cat === "All" ? all : all.filter((p) => p.category === cat);
    if (sort === "price-asc") r = [...r].sort((a, b) => a.price - b.price);
    if (sort === "price-desc") r = [...r].sort((a, b) => b.price - a.price);
    if (sort === "name") r = [...r].sort((a, b) => a.name.localeCompare(b.name));
    return r;
  }, [cat, sort, all]);
  return (
    <main data-screen-label="Shop">
      <section style={{ paddingTop: 64, paddingBottom: 40, borderBottom: "1px solid var(--border)" }}>
        <div className="container">
          <Eyebrow>Catalog</Eyebrow>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", marginTop: 12, flexWrap: "wrap", gap: 16 }}>
            <h1 style={{ fontSize: 56, fontWeight: 400, letterSpacing: "-0.03em", margin: 0, lineHeight: 1 }}>
              Shop <span style={{ color: "var(--muted)" }}>· {filtered.length} products</span>
            </h1>
            <Code>Updated {new Date().toLocaleDateString("en-CA")}</Code>
          </div>
        </div>
      </section>

      <section style={{ paddingTop: 32, paddingBottom: 40 }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "220px 1fr",
            gap: 56,
            alignItems: "start",
          }} className="shop-grid">
            {/* Filters */}
            <aside style={{ position: "sticky", top: 96, paddingTop: 8 }} className="shop-filters">
              <Eyebrow>Filter by</Eyebrow>
              <div style={{ marginTop: 16 }}>
                {cats.map((c) => (
                  <button
                    key={c}
                    onClick={() => setCat(c)}
                    style={{
                      display: "block",
                      width: "100%",
                      padding: "10px 0",
                      background: "transparent",
                      border: 0,
                      borderBottom: "1px solid var(--border)",
                      textAlign: "left",
                      color: c === cat ? "var(--fg)" : "var(--muted)",
                      cursor: "pointer",
                      fontFamily: "inherit",
                      fontSize: 13,
                      letterSpacing: c === cat ? "0" : "0.005em",
                      fontWeight: c === cat ? 500 : 400,
                    }}
                  >
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
                      <span style={{
                        width: 6, height: 6, borderRadius: "50%",
                        background: c === cat ? "var(--accent)" : "transparent",
                        border: c === cat ? "none" : "1px solid var(--border)",
                      }} />
                      {c}
                    </span>
                  </button>
                ))}
              </div>
              <div style={{ marginTop: 40 }}>
                <Eyebrow>Sort</Eyebrow>
                <select
                  value={sort}
                  onChange={(e) => setSort(e.target.value)}
                  style={{
                    marginTop: 12,
                    width: "100%",
                    padding: "10px 12px",
                    border: "1px solid var(--border)",
                    background: "var(--bg)",
                    color: "var(--fg)",
                    fontFamily: "inherit",
                    fontSize: 13,
                    borderRadius: 0,
                  }}
                >
                  <option value="featured">Featured</option>
                  <option value="price-asc">Price · low to high</option>
                  <option value="price-desc">Price · high to low</option>
                  <option value="name">Name · A to Z</option>
                </select>
              </div>
              <div style={{ marginTop: 40, padding: 16, border: "1px solid var(--border)", background: "var(--surface)" }}>
                <Eyebrow>Research only</Eyebrow>
                <p style={{ fontSize: 12, lineHeight: 1.55, color: "var(--muted)", margin: "10px 0 0" }}>
                  All compounds are sold for laboratory use only. Not for human consumption.
                </p>
              </div>
            </aside>

            {/* Grid */}
            <div style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, 1fr)",
              gap: 32,
              rowGap: 48,
            }} className="product-grid-3">
              {filtered.map((p) => <ProductCard key={p.id} product={p} navigate={navigate} />)}
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// PRODUCT
function ProductPage({ navigate, productId, addToCart }) {
  const all = window.PRODUCTS || [];
  if (all.length === 0) return null;
  const product = all.find((p) => p.id === productId) || all[0];
  const [qty, setQty] = useStateHS(1);
  const [tab, setTab] = useStateHS("about");
  const recs = all.filter((p) => p.id !== product.id).slice(0, 4);

  return (
    <main data-screen-label="Product">
      {/* Breadcrumb */}
      <div style={{ paddingTop: 32, paddingBottom: 24 }}>
        <div className="container">
          <Code>
            <a onClick={(e) => { e.preventDefault(); navigate("home"); }} href="#" style={{ color: "inherit", textDecoration: "none" }}>Genmax</a>
            {" / "}
            <a onClick={(e) => { e.preventDefault(); navigate("shop"); }} href="#" style={{ color: "inherit", textDecoration: "none" }}>Shop</a>
            {" / "}
            <span style={{ color: "var(--fg)" }}>{product.code} · {product.name}</span>
          </Code>
        </div>
      </div>

      {/* Hero */}
      <section style={{ paddingBottom: 80 }}>
        <div className="container">
          <div style={{
            display: "grid",
            gridTemplateColumns: "1.1fr 1fr",
            gap: 64,
            alignItems: "start",
          }} className="product-hero">
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Placeholder label={product.shortName + " · primary"} ratio="1/1" code={product.code} />
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 16 }}>
                <Placeholder label="vial · side" ratio="1/1" />
                <Placeholder label="label · detail" ratio="1/1" />
                <Placeholder label="COA · scan" ratio="1/1" />
              </div>
            </div>
            <div style={{ position: "sticky", top: 96 }}>
              <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                <Code>{product.code}</Code>
                {product.badge && <Badge tone={product.badge === "New" ? "accent" : "default"}>{product.badge}</Badge>}
              </div>
              <h1 style={{ fontSize: 56, fontWeight: 400, letterSpacing: "-0.03em", margin: "20px 0 0", lineHeight: 1 }}>
                {product.name}
              </h1>
              <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 12 }}>{product.category}</div>

              <div style={{ display: "flex", alignItems: "baseline", gap: 12, marginTop: 32 }}>
                <div style={{ fontSize: 36, fontWeight: 400, letterSpacing: "-0.02em" }}>${product.price}</div>
                <Code>per {product.dose} vial</Code>
              </div>

              <p style={{ fontSize: 15, lineHeight: 1.7, color: "var(--muted)", marginTop: 32, maxWidth: 460 }}>
                {product.blurb} Sold strictly for laboratory and research use.
              </p>

              {/* Key specs */}
              <div style={{
                marginTop: 32,
                border: "1px solid var(--border)",
                background: "var(--surface)",
              }}>
                {[
                  ["Purity (HPLC)", product.purity],
                  ["Form", product.form],
                  ["Storage", product.storage],
                  ["Grade", product.grade],
                ].map(([k, v], i, arr) => (
                  <div key={k} style={{
                    display: "flex",
                    justifyContent: "space-between",
                    padding: "14px 16px",
                    borderBottom: i === arr.length - 1 ? "none" : "1px solid var(--border)",
                    fontSize: 13,
                  }}>
                    <span style={{ color: "var(--muted)" }}>{k}</span>
                    <span style={{ color: "var(--fg)", fontFamily: "var(--mono)" }}>{v}</span>
                  </div>
                ))}
              </div>

              {/* Quantity + add */}
              <div style={{ marginTop: 32, display: "flex", gap: 12 }}>
                <div style={{ display: "flex", alignItems: "center", border: "1px solid var(--border)" }}>
                  <button onClick={() => setQty(Math.max(1, qty - 1))} style={{
                    width: 44, height: 52, background: "transparent", border: 0, fontFamily: "var(--mono)", fontSize: 16, color: "var(--fg)", cursor: "pointer",
                  }}>−</button>
                  <div style={{ width: 36, textAlign: "center", fontFamily: "var(--mono)", fontSize: 14 }}>{qty}</div>
                  <button onClick={() => setQty(qty + 1)} style={{
                    width: 44, height: 52, background: "transparent", border: 0, fontFamily: "var(--mono)", fontSize: 16, color: "var(--fg)", cursor: "pointer",
                  }}>+</button>
                </div>
                <Button size="lg" full onClick={() => addToCart(product, qty)}>
                  Add to cart · ${product.price * qty}
                </Button>
              </div>

              {/* trust mini */}
              <div style={{ marginTop: 24, display: "flex", flexWrap: "wrap", gap: 16, fontSize: 12, color: "var(--muted)" }}>
                <span>◇ HPLC verified</span>
                <span>◇ Cold-chain shipping</span>
                <span>◇ COA included</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Tabs */}
      <section style={{ paddingTop: 40 }}>
        <div className="container">
          <div style={{ display: "flex", gap: 0, borderBottom: "1px solid var(--border)", flexWrap: "wrap" }}>
            {[
              ["about", "About"],
              ["specs", "Specifications"],
              ["mechanism", "Mechanism"],
              ["docs", "Documentation"],
              ["ship", "Shipping & storage"],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setTab(k)} style={{
                padding: "16px 24px 16px 0",
                marginRight: 32,
                background: "transparent",
                border: 0,
                borderBottom: tab === k ? "1px solid var(--fg)" : "1px solid transparent",
                marginBottom: -1,
                cursor: "pointer",
                fontFamily: "inherit",
                fontSize: 14,
                color: tab === k ? "var(--fg)" : "var(--muted)",
                fontWeight: 500,
              }}>{l}</button>
            ))}
          </div>
          <div style={{ paddingTop: 40, paddingBottom: 24 }}>
            {tab === "about" && (
              <div style={{ maxWidth: 760 }}>
                {product.description ? (
                  product.description.split("\n\n").map((para, i) => (
                    <p key={i} style={{
                      fontSize: 15,
                      lineHeight: 1.75,
                      color: i === product.description.split("\n\n").length - 1 ? "var(--muted)" : "var(--fg)",
                      margin: i === 0 ? "0 0 20px" : "0 0 20px",
                    }}>{para}</p>
                  ))
                ) : (
                  <p style={{ fontSize: 14, color: "var(--muted)" }}>
                    Detailed compound information available on the COA shipped with this product.
                  </p>
                )}
                {product.researchAreas && product.researchAreas.length > 0 && (
                  <div style={{ marginTop: 32, paddingTop: 24, borderTop: "1px solid var(--border)" }}>
                    <Eyebrow>Research areas</Eyebrow>
                    <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 8 }}>
                      {product.researchAreas.map((area) => (
                        <span key={area} style={{
                          fontSize: 12,
                          padding: "6px 12px",
                          border: "1px solid var(--border)",
                          background: "var(--surface)",
                          color: "var(--fg)",
                          letterSpacing: "0.01em",
                        }}>{area}</span>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
            {tab === "specs" && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 64, maxWidth: 960 }} className="tab-grid">
                <div>
                  <Eyebrow>Identification</Eyebrow>
                  <dl style={{ marginTop: 16 }}>
                    {[
                      ["Compound", product.name],
                      ["Scientific name", product.scientificName || "—"],
                      ["CAS reference", product.cas || "[batch-specific]"],
                      ["Sequence", product.sequence || "[available on COA]"],
                      ["Molecular formula", product.formula || "—"],
                      ["Molecular weight", product.mw ? `${product.mw} g/mol` : "[batch-specific]"],
                    ].filter(([_, v]) => v && v !== "—").map(([k, v]) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderBottom: "1px solid var(--border)", fontSize: 13, gap: 16 }}>
                        <dt style={{ color: "var(--muted)", flexShrink: 0 }}>{k}</dt>
                        <dd style={{ margin: 0, color: "var(--fg)", fontFamily: "var(--mono)", textAlign: "right", wordBreak: "break-word" }}>{v}</dd>
                      </div>
                    ))}
                  </dl>
                </div>
                <div>
                  <Eyebrow>Quality</Eyebrow>
                  <dl style={{ marginTop: 16 }}>
                    {[
                      ["Purity threshold", product.purity],
                      ["Test method", "HPLC + MS"],
                      ["Third-party lab", "Verified · ID on COA"],
                      ["Endotoxin", "< 0.25 EU/mg"],
                    ].map(([k, v]) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "12px 0", borderBottom: "1px solid var(--border)", fontSize: 13 }}>
                        <dt style={{ color: "var(--muted)" }}>{k}</dt>
                        <dd style={{ margin: 0, color: "var(--fg)", fontFamily: "var(--mono)" }}>{v}</dd>
                      </div>
                    ))}
                  </dl>
                </div>
              </div>
            )}
            {tab === "mechanism" && (
              <div style={{ maxWidth: 720 }}>
                {product.mechanism ? (
                  <p style={{ fontSize: 15, lineHeight: 1.75, color: "var(--fg)", margin: 0 }}>
                    {product.mechanism}
                  </p>
                ) : (
                  <p style={{ fontSize: 14, color: "var(--muted)", margin: 0 }}>
                    Mechanistic information for this compound is available in the linked published research.
                    Consult primary literature for current mechanistic models.
                  </p>
                )}
              </div>
            )}
            {tab === "docs" && (
              <div style={{ maxWidth: 720 }}>
                <p style={{ fontSize: 14, lineHeight: 1.7, color: "var(--muted)", margin: 0 }}>
                  The certificate of analysis (COA) for your batch is delivered with the shipment and
                  available for download below. Each document includes the batch identifier, HPLC
                  chromatogram, mass spectrometry confirmation, and signatures from both our facility
                  and the verifying third-party laboratory.
                </p>
                <div style={{ marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap" }}>
                  <Button variant="secondary">↓ COA · current batch</Button>
                  <Button variant="secondary">↓ HPLC chromatogram</Button>
                  <Button variant="secondary">↓ Mass spec report</Button>
                </div>
              </div>
            )}
            {tab === "ship" && (
              <div style={{ maxWidth: 720 }}>
                <p style={{ fontSize: 14, lineHeight: 1.7, color: "var(--muted)", margin: 0 }}>
                  All peptides ship lyophilized in vacuum-sealed vials, packed in insulated cold-chain
                  containers with phase-change cooling rated for 72 hours of transit. Once received,
                  store unopened vials at the temperature listed in the specifications. After
                  reconstitution, refer to compound-specific stability guidelines.
                </p>
              </div>
            )}
          </div>
        </div>
      </section>

      {/* Recommendations */}
      <section style={{ paddingTop: 80 }}>
        <div className="container">
          <SectionHeader eyebrow="Related compounds" title="You may also be researching" />
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 32 }} className="product-grid">
            {recs.map((p) => <ProductCard key={p.id} product={p} navigate={navigate} />)}
          </div>
        </div>
      </section>
    </main>
  );
}

Object.assign(window, { HomePage, ShopPage, ProductPage });
