/* =========================================================
   Catalog, Product Detail, About, Research, Contact — retail
   ========================================================= */

function CatalogPage({ go, onAddToCart }) {
  const [filter, setFilter] = React.useState('All');
  const [sort, setSort] = React.useState('popular');
  // Popularity = Jan 2026 US Google monthly search volume (DataForSEO).
  // Tirzepatide tops with ~1M/mo, Semaglutide ~700K, Retatrutide ~500K,
  // BPC-157 ~165K (most-searched non-GLP-1), GHK-Cu fastest-growing (+1,016% YoY).
  const POPULAR_ORDER = [
    'tirzepatide',    // 1
    'semaglutide',    // 2
    'retatrutide',    // 3
    'bpc-157',        // 4
    'ghk-cu',         // 5 (fastest-growing)
    'tb-500',         // 6
    'nad-plus',       // 7
    'ipamorelin',     // 8
    'cjc-1295-dac',   // 9
    'sermorelin',     // 10
    'tesamorelin',    // 11
    'pt-141',         // 12
    'mots-c',         // 13
    'bpc-tb-combo',   // 14
  ];
  const popIdx = (slug) => { const i = POPULAR_ORDER.indexOf(slug); return i === -1 ? 999 : i; };
  let filtered = filter === 'All' ? [...PRODUCTS] : PRODUCTS.filter(p => p.series === filter);
  if (sort === 'popular') filtered.sort((a,b) => popIdx(a.slug) - popIdx(b.slug));
  if (sort === 'price-asc') filtered.sort((a,b) => a.price - b.price);
  if (sort === 'price-desc') filtered.sort((a,b) => b.price - a.price);
  if (sort === 'az') filtered.sort((a,b) => a.code.localeCompare(b.code));
  return (
    <>
      <section style={{ background: 'var(--clarion-frost)', padding: '64px 0 48px' }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 14 }}>SHOP</div>
          <h1 style={{ fontSize: 48, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 16px' }}>Research compounds</h1>
          <p style={{ fontSize: 16, color: 'var(--fg1)', lineHeight: 1.6, maxWidth: 620, margin: 0 }}>
            All SKUs ship with a lot‑specific certificate of analysis. Free standard shipping over {fmt(FREE_SHIPPING_THRESHOLD)}.
          </p>
        </div>
      </section>
      <section style={{ paddingTop: 40 }}>
        <div className="container">
          <div className="catalog-toolbar">
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {SERIES.map(s => (
                <button key={s} className="btn" onClick={() => setFilter(s)}
                  style={{
                    background: filter === s ? 'var(--clarion-forest)' : '#fff',
                    color: filter === s ? '#fff' : 'var(--fg-brand)',
                    border: '1px solid ' + (filter === s ? 'var(--clarion-forest)' : 'var(--border-strong)')
                  }}>{s}</button>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em', color: 'var(--fg2)' }}>SORT</span>
              <select value={sort} onChange={e => setSort(e.target.value)} style={{ padding: '8px 12px', border: '1px solid var(--border-strong)', borderRadius: 8, fontSize: 13, background: '#fff', color: 'var(--fg-brand)' }}>
                <option value="popular">Popular</option>
                <option value="default">Featured</option>
                <option value="price-asc">Price: low → high</option>
                <option value="price-desc">Price: high → low</option>
                <option value="az">A → Z</option>
              </select>
            </div>
          </div>
          <div className="product-grid">
            {filtered.map(p => <ProductCard key={p.slug} p={p} onClick={() => go('product', p.slug)} onAddToCart={onAddToCart} />)}
          </div>
        </div>
      </section>
    </>
  );
}

function ProductDetailPage({ slug, go, onAddToCart, showUrgency, showRecentlyViewed }) {
  const p = PRODUCTS.find(x => x.slug === slug) || PRODUCTS[0];
  const cart = useCart();
  const [qty, setQty] = React.useState(1);
  const [justAdded, setJustAdded] = React.useState(false);

  React.useEffect(() => { trackRecentlyViewed(p.slug); setQty(1); }, [p.slug]);

  const [stockTick, setStockTick] = React.useState(0);
  React.useEffect(() => {
    const sync = () => setStockTick(t => t + 1);
    window.addEventListener('clarion-stock-change', sync);
    return () => window.removeEventListener('clarion-stock-change', sync);
  }, []);
  const viewers = viewersFor(p.slug);
  const recent = showRecentlyViewed ? getRecentlyViewed(p.slug).slice(0, 4) : [];
  const lowStock = p.stock < 10;
  const outOfStock = p.stock <= 0;

  const handleAdd = () => {
    if (outOfStock) return;
    const capped = Math.min(qty, p.stock);
    cart.add(p.slug, capped);
    setJustAdded(true);
    setTimeout(() => setJustAdded(false), 1500);
    if (onAddToCart) onAddToCart();
  };

  return (
    <>
      <section style={{ padding: '32px 0 0' }}>
        <div className="container">
          <button className="btn-link" onClick={() => go('catalog')}>← Shop</button>
        </div>
      </section>
      <section style={{ padding: '40px 0 64px' }}>
        <div className="container" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'flex-start' }}>
          <div style={{ background: 'linear-gradient(180deg, var(--clarion-frost) 0%, #fff 100%)', borderRadius: 16, padding: 40, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 520, border: '1px solid var(--border-strong)', position: 'sticky', top: 100 }}>
            <img src="./assets/vial-photo.webp" alt={p.code} style={{ height: 440, filter: 'drop-shadow(0 20px 30px rgba(8,80,65,.25))' }} />
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 14 }}>{p.category}</div>
            <h1 style={{ fontSize: 52, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 16px', lineHeight: 1 }}>{p.code}</h1>
            <p style={{ fontSize: 16, lineHeight: 1.65, color: 'var(--fg1)', margin: '0 0 24px' }}>{p.blurb}</p>

            <div className="pdp-price-row">
              <div className="pdp-price">{fmt(p.price)}</div>
              <div className="pdp-price-meta">per {p.weight} vial · COA included</div>
            </div>

            {showUrgency && (
              <div className="pdp-urgency">
                <span className="pdp-urgency-pulse" /> <strong>{viewers}</strong> people viewing · {outOfStock ? <strong style={{ color: '#8B2E10' }}>Out of stock</strong> : lowStock ? <><strong>Only {p.stock} left</strong> in stock</> : <>In stock — ships same day</>}
              </div>
            )}

            <div className="pdp-buy">
              <div className="pdp-qty">
                <div className="checkout-field-label" style={{ marginBottom: 6 }}>QUANTITY</div>
                <div className="qty-stepper qty-stepper-lg">
                  <button onClick={() => setQty(q => Math.max(1, q - 1))} aria-label="Decrease">−</button>
                  <span>{qty}</span>
                  <button onClick={() => setQty(q => Math.min(99, q + 1))} aria-label="Increase">+</button>
                </div>
              </div>
              <button className={"btn btn-primary pdp-add" + (justAdded ? ' is-added' : '')} onClick={handleAdd} disabled={outOfStock} style={outOfStock ? { opacity: .45, cursor: 'not-allowed' } : {}}>
                {outOfStock ? 'Sold out' : justAdded ? '✓ Added to cart' : `Add to cart · ${fmt(p.price * qty)}`}
              </button>
            </div>

            <div className="pdp-reassurance">
              <div><span>→</span> Ships within 1 business day</div>
              <div><span>✓</span> COA with every vial</div>
              <div><span>⟲</span> Free returns on sealed vials</div>
            </div>

            <div className="data-row" style={{ gridTemplateColumns: 'repeat(3,1fr)', gap: 16, marginBottom: 24, marginTop: 32 }}>
              {[['NET WT', p.weight], ['PURITY', p.purity], ['STORE', '−20°C']].map(([k, v]) => (
                <div className="data-cell" key={k} style={{ background: 'var(--clarion-frost)', border: '1px solid var(--border-strong)', borderRadius: 10, padding: '14px 16px' }}>
                  <div className="k">{k}</div>
                  <div className="v" style={{ fontSize: 22, marginTop: 4 }}>{v}</div>
                </div>
              ))}
            </div>

            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13, marginBottom: 20 }}>
              <tbody>
                {[
                  ['Molecular formula', p.molecular],
                  ['Molecular mass',    p.mass],
                  ['Sequence',          p.sequence],
                  ['Current lot',       p.lot],
                  ['Expiry',            '04/2028'],
                  ['COA',               'Emailed 24h before dispatch'],
                ].map(([k, v], i) => (
                  <tr key={k} style={{ background: i % 2 ? 'var(--clarion-surface)' : '#fff' }}>
                    <td style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', color: 'var(--fg2)', fontSize: 12, letterSpacing: '.04em' }}>{k}</td>
                    <td style={{ padding: '10px 14px', borderBottom: '1px solid var(--border)', fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg-brand)' }}>{v}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            <div style={{ marginTop: 20, padding: 14, background: 'var(--warn-bg)', border: '1px solid var(--warn-border)', borderRadius: 8, fontSize: 11, color: 'var(--warn-fg)', lineHeight: 1.6 }}>
              <strong>⚠ FOR RESEARCH USE ONLY.</strong> Not for human consumption, diagnosis, or therapeutic use.
            </div>
          </div>
        </div>
      </section>

      {recent.length > 0 && (
        <section style={{ padding: '0 0 96px', background: 'var(--clarion-frost)', marginTop: -40, paddingTop: 56 }}>
          <div className="container">
            <div className="eyebrow" style={{ marginBottom: 14 }}>RECENTLY VIEWED</div>
            <div className="product-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
              {recent.map(rp => <ProductCard key={rp.slug} p={rp} onClick={() => go('product', rp.slug)} onAddToCart={onAddToCart} />)}
            </div>
          </div>
        </section>
      )}
    </>
  );
}

function AboutPage({ go }) {
  return (
    <>
      <section className="hero-forest" style={{ padding: '96px 0' }}>
        <div className="container-narrow">
          <div className="eyebrow eyebrow-mint" style={{ marginBottom: 18 }}>ABOUT</div>
          <h1 style={{ fontSize: 60, fontWeight: 900, color: '#fff', letterSpacing: '-0.02em', margin: '0 0 24px', lineHeight: 1 }}>
            We supply <span style={{ fontFamily: 'var(--font-serif)', fontStyle: 'italic', fontWeight: 400, color: 'var(--clarion-mint)' }}>the compound</span>. The lab supplies the rigor.
          </h1>
          <p style={{ fontSize: 18, lineHeight: 1.65, color: 'rgba(255,255,255,.78)', maxWidth: 620, margin: 0 }}>
            Clarion Peptides exists to make a narrow promise: the vial you open in the lab is exactly what the certificate says. Nothing more, nothing less.
          </p>
        </div>
      </section>
      <section>
        <div className="container-narrow">
          <div className="pull-quote">Trust isn't claimed — it's traceable.</div>
          <div className="editorial-block">
            <p>Founded in 2026 by a team drawn from contract manufacturing, analytical chemistry, and logistics, Clarion operates on a single principle: every research compound we release is assayed independently before it leaves the manufacturing floor.</p>
            <p>We ship direct to qualified researchers — no pharmacy, no middleman. Our product is a material, and our customer is a researcher running real experiments. That directness keeps the chain of custody tight and the pricing honest.</p>
            <p>The founders operate the business with an auditor's mindset. Every lot, every temperature excursion, every analytical release is logged, timestamped, and made available to the receiving lab. A certificate of analysis is the contract.</p>
          </div>
        </div>
      </section>
      <section style={{ background: 'var(--clarion-frost)' }}>
        <div className="container">
          <div className="eyebrow" style={{ marginBottom: 14 }}>THE TEAM</div>
          <h2 className="section-title" style={{ marginBottom: 40 }}>Operators, chemists, auditors.</h2>
          <div className="data-row">
            {[
              ['Zavdiel Ocampo', 'FOUNDER',       'Former contract-manufacturing lead.'],
              ['Analytical',    'CHEMISTRY',     'Independent release per USP <1226>.'],
              ['Logistics',     'FULFILLMENT',   'Fast, tracked dispatch from our facility.'],
              ['Compliance',    'REGULATORY',    'Research-use labeling and documentation.'],
            ].map(([n, k, note]) => (
              <div className="data-cell" key={k}>
                <div className="k">{k}</div>
                <div className="v" style={{ fontSize: 18, fontFamily: 'var(--font-sans)', fontWeight: 800 }}>{n}</div>
                <div className="n">{note}</div>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

function ResearchPage() {
  return (
    <section>
      <div className="container-narrow">
        <div className="eyebrow" style={{ marginBottom: 14 }}>METHODOLOGY</div>
        <h1 style={{ fontSize: 48, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 16px' }}>Quality methodology</h1>
        <p style={{ fontSize: 16, color: 'var(--fg2)', lineHeight: 1.6, marginBottom: 48, maxWidth: 620 }}>
          A plain-language walkthrough of how each Clarion lot is released. For the full protocol, request the SOP bundle from our analytical team.
        </p>
        <div className="editorial-block">
          <p>Every released lot passes an eight-assay panel: identity by HPLC, purity by HPLC, net peptide content, water content by Karl Fischer, acetate content, sterility over a 14-day growth window, and LAL endotoxin. Acceptance criteria follow USP &lt;1226&gt;.</p>
        </div>
        <div style={{ marginTop: 40, display: 'flex', flexDirection: 'column', gap: 0, borderTop: '1px solid var(--border)' }}>
          {[
            ['01', 'Identity — HPLC',       'Retention time matches reference standard within tolerance.'],
            ['02', 'Purity — HPLC',         'Main peak area ≥ 99.0%. Impurity peaks individually < 0.5%.'],
            ['03', 'Peptide content',       'Amino-acid analysis confirms net peptide content ≥ 85%.'],
            ['04', 'Water content (KF)',    'Karl Fischer coulometric titration, typical range 2–6%.'],
            ['05', 'Acetate',               'Quantified via ion chromatography. Typical 6–10%.'],
            ['06', 'Sterility',             'No microbial growth across 14-day fluid thioglycollate + SCD broth.'],
            ['07', 'Endotoxin',             'LAL gel-clot assay. Acceptance < 0.5 EU/mg.'],
            ['08', 'Release & COA',         'Certificate generated, signed, archived, published to lot URL.'],
          ].map(([n, title, body]) => (
            <div key={n} style={{ display: 'grid', gridTemplateColumns: '60px 1fr', padding: '24px 0', borderBottom: '1px solid var(--border)' }}>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 600, color: 'var(--fg-accent)', letterSpacing: '.1em' }}>{n}</div>
              <div>
                <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--fg-brand)', marginBottom: 4 }}>{title}</div>
                <div style={{ fontSize: 14, color: 'var(--fg1)', lineHeight: 1.6 }}>{body}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ContactPage() {
  const [sent, setSent] = React.useState(false);
  if (sent) {
    return (
      <section style={{ padding: '120px 0' }}>
        <div className="container-narrow" style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 60, color: 'var(--clarion-teal)', marginBottom: 12 }}>✓</div>
          <h1 style={{ fontSize: 36, fontWeight: 900, color: 'var(--fg-brand)', marginBottom: 14 }}>Message received.</h1>
          <p style={{ fontSize: 15, color: 'var(--fg2)', lineHeight: 1.6 }}>Our support team typically responds within one business day. A confirmation was sent to your inbox.</p>
          <button className="btn btn-ghost" style={{ marginTop: 24 }} onClick={() => setSent(false)}>Send another</button>
        </div>
      </section>
    );
  }
  const Field = ({ label, children }) => (
    <label style={{ display: 'block', marginBottom: 18 }}>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, fontWeight: 700, letterSpacing: '.14em', color: 'var(--fg-accent)', marginBottom: 6 }}>{label}</div>
      {children}
    </label>
  );
  const inputStyle = { width: '100%', padding: '10px 14px', border: '1px solid var(--border-strong)', borderRadius: 8, fontSize: 14, fontFamily: 'var(--font-sans)', color: 'var(--fg-brand)', background: '#fff' };
  return (
    <section style={{ padding: '72px 0' }}>
      <div className="container" style={{ display: 'grid', gridTemplateColumns: '1.2fr .8fr', gap: 56, alignItems: 'flex-start' }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>SUPPORT</div>
          <h1 style={{ fontSize: 44, fontWeight: 900, color: 'var(--fg-brand)', letterSpacing: '-0.02em', margin: '0 0 16px' }}>How can we help?</h1>
          <p style={{ fontSize: 15, color: 'var(--fg1)', lineHeight: 1.65, marginBottom: 40, maxWidth: 560 }}>
            Questions about an order, a COA, or a specific compound? Our team typically responds within one business day.
          </p>
          <form onSubmit={e => { e.preventDefault(); setSent(true); }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
              <Field label="FULL NAME"><input style={inputStyle} required placeholder="Dr. Jane Researcher" /></Field>
              <Field label="EMAIL"><input type="email" style={inputStyle} required placeholder="you@institution.edu" /></Field>
              <Field label="ORDER # (OPTIONAL)"><input style={inputStyle} placeholder="CP123456" /></Field>
              <Field label="TOPIC">
                <select style={inputStyle} required>
                  <option value="">Select one…</option>
                  <option>Order status</option>
                  <option>COA / lot documentation</option>
                  <option>Product question</option>
                  <option>Shipping & delivery</option>
                  <option>Returns</option>
                  <option>Bulk / wholesale</option>
                </select>
              </Field>
            </div>
            <Field label="MESSAGE">
              <textarea style={{ ...inputStyle, minHeight: 140, resize: 'vertical' }} required placeholder="Tell us what you need." />
            </Field>
            <button type="submit" className="btn btn-primary">Send message →</button>
          </form>
        </div>
        <aside style={{ background: 'var(--clarion-frost)', border: '1px solid var(--border-strong)', borderRadius: 12, padding: 28 }}>
          <div className="eyebrow" style={{ marginBottom: 14 }}>DIRECT LINES</div>
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.14em', color: 'var(--fg2)', marginBottom: 4 }}>ORDER SUPPORT</div>
            <div style={{ fontSize: 15, color: 'var(--fg-brand)', fontWeight: 600 }}>orders@clarionpeptides.com</div>
          </div>
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.14em', color: 'var(--fg2)', marginBottom: 4 }}>ANALYTICAL / COA</div>
            <div style={{ fontSize: 15, color: 'var(--fg-brand)', fontWeight: 600 }}>analytical@clarionpeptides.com</div>
          </div>
          <div style={{ marginBottom: 24 }}>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.14em', color: 'var(--fg2)', marginBottom: 4 }}>BULK / WHOLESALE</div>
            <div style={{ fontSize: 15, color: 'var(--fg-brand)', fontWeight: 600 }}>bulk@clarionpeptides.com</div>
          </div>
          <div style={{ padding: 14, background: '#fff', border: '1px solid var(--border-strong)', borderRadius: 8, fontSize: 12, lineHeight: 1.6, color: 'var(--fg1)' }}>
            <strong style={{ color: 'var(--fg-brand)' }}>Hours:</strong> Mon–Fri, 9 AM – 6 PM ET. COA requests answered within 24 hours.
          </div>
        </aside>
      </div>
    </section>
  );
}

Object.assign(window, { CatalogPage, ProductDetailPage, AboutPage, ResearchPage, ContactPage });
