/* ═══════════════════════════════════════════════
   AUREAL — Inner Pages
   Custom, Pricing, Community, About, Join, Contact
   ═══════════════════════════════════════════════ */

/* ═══ PRICING DATA ═══ */
/* Structure: PRICES[product][tier][ship][print][qty] */
const PRICES = {
  tee: {
    budget: {
      SL: {
        0: { 1: 9.68, 5: 6.84, 12: 6.56, 24: 6.46, 50: 6.23, 100: 5.84 },
        1: { 1: 13.22, 5: 10.38, 12: 10.10, 24: 10.00, 50: 9.76, 100: 9.37 },
        2: { 1: 16.75, 5: 13.91, 12: 13.64, 24: 13.54, 50: 13.30, 100: 12.91 }
      },
      IE: {
        0: { 1: 36.34, 5: 14.80, 12: 11.31, 24: 10.21, 50: 8.74, 100: 7.49 },
        1: { 1: 39.87, 5: 18.34, 12: 14.85, 24: 13.75, 50: 12.28, 100: 11.02 },
        2: { 1: 43.41, 5: 21.88, 12: 18.38, 24: 17.29, 50: 15.82, 100: 14.56 }
      }
    },
    standard: {
      SL: {
        0: { 1: 14.41, 5: 11.26, 12: 11.18, 24: 11.08, 50: 10.65, 100: 9.97 },
        1: { 1: 18.33, 5: 15.18, 12: 15.11, 24: 15.00, 50: 14.57, 100: 13.89 },
        2: { 1: 22.26, 5: 19.11, 12: 19.03, 24: 18.92, 50: 18.50, 100: 17.82 }
      },
      IE: {
        0: { 1: 53.89, 5: 22.36, 12: 17.76, 24: 16.15, 50: 13.83, 100: 11.68 },
        1: { 1: 57.81, 5: 26.28, 12: 21.68, 24: 20.08, 50: 17.76, 100: 15.60 },
        2: { 1: 61.74, 5: 30.21, 12: 25.61, 24: 24.00, 50: 21.68, 100: 19.53 }
      }
    },
    premium: {
      SL: {
        0: { 1: 21.11, 5: 16.89, 12: 16.88, 24: 16.73, 50: 16.04, 100: 14.77 },
        1: { 1: 26.38, 5: 22.15, 12: 22.15, 24: 22.00, 50: 21.31, 100: 20.04 },
        2: { 1: 31.65, 5: 27.42, 12: 27.41, 24: 27.27, 50: 26.57, 100: 25.31 }
      },
      IE: {
        0: { 1: 75.04, 5: 32.81, 12: 26.75, 24: 24.60, 50: 21.33, 100: 18.01 },
        1: { 1: 80.30, 5: 38.08, 12: 32.01, 24: 29.87, 50: 26.60, 100: 23.28 },
        2: { 1: 85.57, 5: 43.35, 12: 37.28, 24: 35.13, 50: 31.86, 100: 28.54 }
      }
    }
  },
  hoodie: {
    budget: {
      SL: {
        0: { 1: 25.27, 5: 22.29, 12: 21.42, 24: 21.29, 50: 20.47, 100: 19.10 },
        1: { 1: 28.99, 5: 26.01, 12: 25.13, 24: 25.00, 50: 24.18, 100: 22.82 },
        2: { 1: 32.70, 5: 29.72, 12: 28.85, 24: 28.71, 50: 27.90, 100: 26.53 }
      },
      IE: {
        0: { 1: 67.57, 5: 36.29, 12: 30.75, 24: 29.12, 50: 25.14, 100: 22.28 },
        1: { 1: 71.29, 5: 40.00, 12: 34.47, 24: 32.83, 50: 28.85, 100: 26.00 },
        2: { 1: 75.00, 5: 43.71, 12: 38.18, 24: 36.55, 50: 32.57, 100: 29.71 }
      }
    },
    standard: {
      SL: {
        0: { 1: 34.55, 5: 31.38, 12: 31.17, 24: 31.06, 50: 29.96, 100: 27.99 },
        1: { 1: 38.49, 5: 35.33, 12: 35.11, 24: 35.00, 50: 33.90, 100: 31.93 },
        2: { 1: 42.43, 5: 39.27, 12: 39.05, 24: 38.94, 50: 37.84, 100: 35.88 }
      },
      IE: {
        0: { 1: 77.18, 5: 43.88, 12: 37.98, 24: 36.25, 50: 35.06, 100: 31.33 },
        1: { 1: 81.12, 5: 47.82, 12: 41.92, 24: 40.19, 50: 39.00, 100: 35.27 },
        2: { 1: 85.06, 5: 51.76, 12: 45.87, 24: 44.13, 50: 42.94, 100: 39.21 }
      }
    },
    premium: {
      SL: {
        0: { 1: 45.01, 5: 41.77, 12: 41.07, 24: 40.96, 50: 39.29, 100: 36.18 },
        1: { 1: 49.05, 5: 45.81, 12: 45.11, 24: 45.00, 50: 43.33, 100: 40.22 },
        2: { 1: 53.10, 5: 49.85, 12: 49.15, 24: 49.04, 50: 47.37, 100: 44.26 }
      },
      IE: {
        0: { 1: 92.97, 5: 61.08, 12: 54.83, 24: 53.16, 50: 47.51, 100: 42.04 },
        1: { 1: 97.01, 5: 65.12, 12: 58.87, 24: 57.20, 50: 51.55, 100: 46.08 },
        2: { 1: 101.06, 5: 69.16, 12: 62.91, 24: 61.24, 50: 55.59, 100: 50.12 }
      }
    }
  }
};

const TIER_META = {
  budget: { label: 'Budget', color: '#cc9e04', desc: 'Events & High-Volume Orders', sub: 'One-time events, runs, and giveaways where quantity is the priority.' },
  standard: { label: 'Standard', color: '#cc9e04', desc: 'Brand Merch & Community Orders', sub: 'Student organizations, clubs, and recurring drops.' },
  premium: { label: 'Premium', color: '#cc9e04', desc: 'Corporate & Quality-Forward Orders', sub: 'Executive gifting and clients who want the best blank.' }
};

const PRODUCT_META = {
  tee: { label: 'T-Shirts', sub: 'from $9.37/unit' },
  hoodie: { label: 'Hoodies', sub: 'from $22.82/unit' }
};

/* Garment specs vary by product AND tier, so they live here (not in the
   product-agnostic TIER_META). Public-safe only — GSM/oz + fit descriptor,
   never style codes or manufacturer name. */
const TIER_SPECS = {
  tee: {
    budget: '180 GSM · 5.3 oz — midweight cotton',
    standard: '230 GSM · 6.8 oz — heavyweight cotton',
    premium: '230 GSM · 6.8 oz — heavyweight cotton'
  },
  hoodie: {
    budget: '300 GSM · 8.8 oz — relaxed fit',
    standard: '380 GSM · 11.2 oz — oversized, fleece-lined',
    premium: '430 GSM · 12.7 oz — boxy heavyweight, drop-shoulder'
  }
};

function interpolatePrice(product, tier, ship, print, qty) {
  const row = PRICES[product][tier][ship][print];
  const qtys = [1, 5, 12, 24, 50, 100];
  if (qty <= 1) return row[1];
  if (qty >= 100) return row[100];
  let lo = 1,hi = 100;
  for (let i = 0; i < qtys.length - 1; i++) {
    if (qty >= qtys[i] && qty <= qtys[i + 1]) {lo = qtys[i];hi = qtys[i + 1];break;}
  }
  const t = (qty - lo) / (hi - lo);
  return Math.round((row[lo] + t * (row[hi] - row[lo])) * 100) / 100;
}

function fmt(n) {return '$' + n.toFixed(2);}

/* ═══ PRICE TABLE COMPONENT ═══ */
function PriceTable({ product, tier, ship }) {
  const printLabels = ['Blank (no design)', 'Front print · design included', 'Front + back'];
  const qtys = [1, 5, 12, 24, 50, 100];
  return (
    <table className="au-price-table">
      <thead>
        <tr>
          <th>Print</th>
          {qtys.map((q) => <th key={q}>{q} {q === 1 ? 'unit' : 'units'}</th>)}
        </tr>
      </thead>
      <tbody>
        {[0, 1, 2].map((p) =>
        <tr key={p}>
            <td>{printLabels[p]}</td>
            {qtys.map((q) => {
            const val = PRICES[product][tier][ship][p][q];
            return <td key={q}>{fmt(val)}</td>;
          })}
          </tr>
        )}
      </tbody>
    </table>);

}

/* ═══ QUOTE CALCULATOR ═══ */
function QuoteCalc({ product, onSubmit, initialTier }) {
  const [tier, setTier] = React.useState(initialTier || 'standard');

  React.useEffect(() => {
    if (initialTier) setTier(initialTier);
  }, [initialTier]);
  const [print, setPrint] = React.useState(1);
  const [ship, setShip] = React.useState('SL');
  const [qty, setQty] = React.useState(24);

  const activeProduct = product || 'tee';
  const pu = qty > 0 ? interpolatePrice(activeProduct, tier, ship, print, qty) : 0;
  const total = pu * qty;
  const printLabels = ['no print', 'front print', 'front + back'];
  const tierLabel = TIER_META[tier].label;
  const shipLabel = ship === 'SL' ? 'standard' : 'express';
  const productLabel = PRODUCT_META[activeProduct].label;

  return (
    <div className="au-calc">
      <Eyebrow>Quote Calculator</Eyebrow>
      <div className="au-calc-grid" style={{ marginTop: '1rem' }}>
        <div>
          <label>Tier</label>
          <select value={tier} onChange={(e) => setTier(e.target.value)}>
            <option value="budget">Budget</option>
            <option value="standard">Standard</option>
            <option value="premium">Premium</option>
          </select>
        </div>
        <div>
          <label>Print</label>
          <select value={print} onChange={(e) => setPrint(+e.target.value)}>
            <option value={0}>No Print</option>
            <option value={1}>Front Print</option>
            <option value={2}>Front + Back</option>
          </select>
        </div>
        <div>
          <label>Delivery</label>
          <select value={ship} onChange={(e) => setShip(e.target.value)}>
            <option value="SL">Standard (~14 days)</option>
            <option value="IE">Express (~7 days)</option>
          </select>
        </div>
        <div>
          <label>Quantity</label>
          <input type="number" value={qty} min={1} max={9999} onChange={(e) => setQty(Math.max(0, +e.target.value))} />
        </div>
      </div>
      <div className="au-calc-result">
        <div className="au-calc-result-item">
          <div className="au-calc-result-label">Price per unit</div>
          <div className="au-calc-result-value">{qty > 0 ? fmt(pu) : '—'}</div>
          <div className="au-calc-result-sub">{qty > 0 ? `${productLabel} · ${tierLabel} · ${printLabels[print]} · ${shipLabel}` : ''}</div>
        </div>
        <div className="au-calc-result-item">
          <div className="au-calc-result-label">Total order</div>
          <div className="au-calc-result-value">{qty > 0 ? fmt(total) : '—'}</div>
          <div className="au-calc-result-sub">{qty > 0 ? `${qty} unit${qty === 1 ? '' : 's'} × ${fmt(pu)}` : ''}</div>
        </div>
      </div>
      {onSubmit && qty > 0 &&
      <div style={{ marginTop: '1.5rem', textAlign: 'center' }}>
          <Btn variant="primary" onClick={() => onSubmit({ product: activeProduct, tier, print, ship, qty, pu, total, tierLabel, shipLabel, productLabel, printLabel: printLabels[print] })}>
            Get Started with This Order →
          </Btn>
        </div>
      }
    </div>);

}

/* ═══ PRICING PAGE ═══ */
function PricingPage({ navigate }) {
  const [activeProduct, setActiveProduct] = React.useState('tee');
  const [activeTier, setActiveTier] = React.useState('standard');
  const meta = TIER_META[activeTier];
  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <FadeIn>
          <Eyebrow>Pricing</Eyebrow>
          <h1>Transparent pricing.<br />No per-color fees. No surprises.</h1>
          <p style={{ maxWidth: 560, marginTop: '0.75rem' }}>
            Same rate for every client, at every quantity.
          </p>
        </FadeIn>

        <FadeIn delay={200}>
          <div className="au-delivery-row" style={{ marginTop: '2.5rem' }}>
            <div className="au-delivery-item">
              <div className="au-delivery-label">Standard Delivery</div>
              <div className="au-delivery-val">~14 business days</div>
              <div className="au-delivery-note">Production + shipping included</div>
            </div>
            <div className="au-delivery-item">
              <div className="au-delivery-label">Express Delivery</div>
              <div className="au-delivery-val">~7 business days</div>
              <div className="au-delivery-note">Priority production + expedited</div>
            </div>
            <div className="au-delivery-item">
              <div className="au-delivery-label">Minimum Order</div>
              <div className="au-delivery-val">No minimums</div>
              <div className="au-delivery-note">Order as few or as many as you need</div>
            </div>
          </div>
        </FadeIn>

        <FadeIn delay={300}>
          <div className="au-product-block">
            <div className="au-product-eyebrow">Product</div>
            <div className="au-product-selector">
              {Object.entries(PRODUCT_META).map(([key, m]) =>
              <button
                key={key}
                className={`au-product-btn ${activeProduct === key ? 'active' : ''}`}
                onClick={() => setActiveProduct(key)}>
                {m.label}
                <span className="product-sub">{m.sub}</span>
              </button>
              )}
            </div>
          </div>
        </FadeIn>

        <FadeIn delay={350} key={activeProduct + '-tabs'}>
          <div className="au-tier-tabs">
            {Object.entries(TIER_META).map(([key, m]) =>
            <button
              key={key}
              className={`au-tier-tab ${activeTier === key ? 'active' : ''}`}
              style={{ ...(activeTier === key ? { color: m.color, borderBottomColor: m.color } : {}), lineHeight: "1" }}
              onClick={() => setActiveTier(key)}>
                {m.label}
              </button>
            )}
          </div>
        </FadeIn>

        <FadeIn delay={400} key={activeProduct + '-' + activeTier}>
          <div style={{ marginBottom: '0.5rem' }}>
            <span style={{ fontSize: '0.65rem', fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase', color: meta.color, background: meta.color + '1a', padding: '3px 10px', borderRadius: 3 }}>{meta.label}</span>
          </div>
          <h3 style={{ marginBottom: '0.3rem' }}>{meta.desc}</h3>
          <p style={{ fontSize: '0.88rem', marginBottom: '0.4rem' }}>{meta.sub}</p>
          <p className="au-spec-line">{TIER_SPECS[activeProduct][activeTier]}</p>

          <div className="au-price-banner">Every price below is final. Full-color design included. No setup fees, no per-color charges.</div>

          <div style={{ marginBottom: '2.5rem' }}>
            <Eyebrow>Standard Delivery (~14 days)</Eyebrow>
            <div style={{ marginTop: '0.75rem' }}><PriceTable product={activeProduct} tier={activeTier} ship="SL" /></div>
          </div>
          <div>
            <Eyebrow>Express Delivery (~7 days)</Eyebrow>
            <div style={{ marginTop: '0.75rem' }}><PriceTable product={activeProduct} tier={activeTier} ship="IE" /></div>
          </div>
        </FadeIn>

        <FadeIn delay={200}>
          <QuoteCalc product={activeProduct} initialTier={activeTier} onSubmit={(data) => {
            window.__pricingData = data;
            navigate('contact');
          }} />
        </FadeIn>
      </Section>
    </div>);

}

/* ═══ CUSTOM ORDER MODAL ═══ */
function CustomOrderModal({ tier, productKey, catalogProduct, initialColor, onClose, navigate }) {
  const [selectedColor, setSelectedColor] = React.useState(initialColor || null);
  const [print, setPrint] = React.useState(null);
  const [ship, setShip] = React.useState(null);
  const [qty, setQty] = React.useState('');

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const tierKey = tier.key.split('-')[1] || tier.key;
  const tierLabel = TIER_META[tierKey] ? TIER_META[tierKey].label : tier.label;
  const productLabel = PRODUCT_META[productKey] ? PRODUCT_META[productKey].label : productKey;
  const printLabels = ['No Print', 'Front Print', 'Front + Back'];
  const shipLabels = { SL: 'Standard (~14 days)', IE: 'Express (~7 days)' };

  const qtyNum = parseInt(qty, 10) || 0;
  const allSelected = print !== null && ship !== null && qtyNum > 0;
  const pu = allSelected ? interpolatePrice(productKey, tierKey, ship, print, qtyNum) : 0;
  const total = pu * qtyNum;

  const activeColorObj = catalogProduct && selectedColor
    ? catalogProduct.colors.find(c => c.name === selectedColor)
    : null;
  const displayImage = (activeColorObj && activeColorObj.image)
    || (catalogProduct && catalogProduct.image)
    || null;

  const handleSubmit = () => {
    if (!allSelected) return;
    const data = {
      product: productKey,
      tier: tierKey,
      print,
      ship,
      qty: qtyNum,
      pu,
      total,
      tierLabel,
      shipLabel: ship === 'SL' ? 'standard' : 'express',
      productLabel,
      printLabel: printLabels[print].toLowerCase()
    };
    window.__pricingData = data;
    onClose();
    navigate('contact');
  };

  const optBtnStyle = (active) => ({
    fontFamily: 'var(--font-body)', fontSize: '0.75rem', fontWeight: 500,
    padding: '0.45rem 1rem', border: '1px solid',
    borderColor: 'var(--gold)',
    background: active ? 'var(--gold)' : 'transparent',
    color: active ? 'var(--dark)' : 'var(--text-muted)',
    cursor: 'pointer', transition: 'all 0.2s', borderRadius: 'var(--radius)'
  });

  const labelStyle = { fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '0.4rem' };

  return (
    <div className="au-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="au-modal">
        <button className="au-modal-close" onClick={onClose}>✕</button>
        <div className="au-modal-img">
          {displayImage
            ? <img src={displayImage} alt={productLabel + ' — ' + tierLabel} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <ImgPlaceholder aspect="4/5" label={productLabel + ' · ' + tierLabel} />
          }
        </div>
        <div className="au-modal-body">
          <span style={{ fontSize: '0.6rem', fontWeight: 700, letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--gold)', marginBottom: '0.5rem', display: 'inline-block' }}>{tierLabel} Tier</span>
          <h2 style={{ fontSize: '1.55rem', fontWeight: 400, marginBottom: '0.25rem' }}>{productLabel}</h2>
          <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: '1.25rem' }}>{tier.desc}</p>

          {catalogProduct && catalogProduct.colors && catalogProduct.colors.length > 0 && (
            <div style={{ marginBottom: '1.25rem' }}>
              <p style={labelStyle}>Color</p>
              <div style={{ display: 'flex', gap: '0.35rem', flexWrap: 'wrap', alignItems: 'center' }}>
                {selectedColor && <span style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginRight: '0.5rem' }}>{selectedColor}</span>}
                {catalogProduct.colors.map(c => {
                  const hex = window.__aurealColorToHex ? window.__aurealColorToHex(c.name) : null;
                  return (
                    <button
                      key={c.name}
                      type="button"
                      className={'au-swatch' + (selectedColor === c.name ? ' sel' : '')}
                      title={c.name}
                      aria-label={c.name}
                      style={{ background: hex || 'var(--border)' }}
                      onClick={() => setSelectedColor(c.name)}
                    />
                  );
                })}
              </div>
            </div>
          )}

          <div style={{ marginBottom: '1.25rem' }}>
            <p style={labelStyle}>Print</p>
            <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
              {[0, 1, 2].map(p => (
                <button key={p} onClick={() => setPrint(p)} style={optBtnStyle(print === p)}>{printLabels[p]}</button>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: '1.25rem' }}>
            <p style={labelStyle}>Delivery</p>
            <div style={{ display: 'flex', gap: '0.5rem' }}>
              {['SL', 'IE'].map(s => (
                <button key={s} onClick={() => setShip(s)} style={optBtnStyle(ship === s)}>{shipLabels[s]}</button>
              ))}
            </div>
          </div>

          <div style={{ marginBottom: '1.25rem' }}>
            <p style={labelStyle}>Quantity</p>
            <input
              type="number"
              value={qty}
              min={1}
              max={9999}
              placeholder="0"
              onChange={(e) => setQty(e.target.value)}
              onFocus={(e) => { e.target.style.borderColor = 'var(--gold)'; }}
              onBlur={(e) => { e.target.style.borderColor = 'var(--border)'; }}
              style={{
                fontFamily: 'var(--font-body)', fontSize: '1rem', padding: '0.5rem 0.75rem',
                background: 'var(--dark)', border: '1px solid var(--border)', borderRadius: 'var(--radius)',
                color: 'var(--white)', width: 120, outline: 'none'
              }}
            />
          </div>

          {allSelected && (
            <div style={{ border: '1px solid var(--gold)', borderRadius: 'var(--radius)', padding: '1rem', marginBottom: '1rem' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '0.35rem' }}>
                <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>Price per unit</span>
                <span style={{ fontSize: '1rem', fontWeight: 600, color: 'var(--white)' }}>{fmt(pu)}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: '0.8rem', color: 'var(--text-muted)' }}>Total ({qtyNum} units)</span>
                <span style={{ fontSize: '1rem', fontWeight: 600, color: 'var(--gold)' }}>{fmt(total)}</span>
              </div>
            </div>
          )}

          <div style={{ borderTop: '1px solid var(--border)', paddingTop: '1.25rem', marginTop: 'auto' }}>
            <Btn
              variant="primary"
              style={{ width: '100%', justifyContent: 'center', opacity: allSelected ? 1 : 0.4, transition: 'opacity 0.2s' }}
              onClick={handleSubmit}>
              Get Started with This Order →
            </Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ═══ CUSTOM ORDERS PAGE ═══ */
function CustomPage({ navigate, tweaks }) {
  const [modalData, setModalData] = React.useState(null);

  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <FadeIn>
          <Eyebrow>Custom Orders</Eyebrow>
          <h1>High quality merch for your community.<br />Exactly how you imagined it.</h1>
          <p style={{ maxWidth: 600, marginTop: '0.75rem' }}>No per-color fees. No quote requests. 100% partner satisfaction.</p>
        </FadeIn>
      </Section>

      <Section bg="light">
        <FadeIn><Eyebrow>How it works</Eyebrow><h2>Just Four Simple Stages.</h2></FadeIn>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '2rem', marginTop: '2rem' }}>
          {[
          { icon:
            <svg width="44" height="44" viewBox="0 0 44 44" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M11 6 h14 l8 8 v24 H11 Z" />
                <path d="M25 6 v8 h8" />
                <line x1="16" y1="20" x2="28" y2="20" />
                <line x1="16" y1="26" x2="28" y2="26" />
                <line x1="16" y1="32" x2="22" y2="32" />
              </svg>,
            t: 'Tell us your vision', d: "Fill out the form with your organization's details, product type, and estimated quantity." },
          { icon:
            <svg width="44" height="44" viewBox="0 0 44 44" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M32 8 l4 4 -20 20 -7 2 2-7 Z" />
                <line x1="28" y1="12" x2="32" y2="16" />
              </svg>,
            t: 'Design & approve', d: "Bring your own artwork or use our design service. We'll work to ensure 100% satisfaction." },
          { icon:
            <svg width="44" height="44" viewBox="0 0 44 44" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <rect x="8" y="16" width="28" height="22" rx="1" />
                <rect x="8" y="9" width="28" height="7" />
                <line x1="22" y1="16" x2="22" y2="38" />
                <line x1="16" y1="9" x2="16" y2="16" />
                <line x1="28" y1="9" x2="28" y2="16" />
              </svg>,
            t: 'We produce & ship', d: 'Premium garments, full-color printing, delivered to anywhere in the world.' },
          { icon:
            <svg width="44" height="44" viewBox="0 0 44 44" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="4,18 9,7 35,7 40,18" />
                <path d="M4 18 Q4 24 10 24 Q16 24 16 18 Q16 24 22 24 Q28 24 28 18 Q28 24 34 24 Q40 24 40 18" />
                <polyline points="8,24 8,37 36,37 36,24" />
                <rect x="17" y="28" width="10" height="9" />
              </svg>,
            t: 'Your merch stays live', d: 'Products listed on our storefront — earning passive income on every sale.' }].
          map((s, i) =>
          <FadeIn key={i} delay={i * 100}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ color: 'var(--gold)', marginBottom: '1.25rem', display: 'flex', justifyContent: 'center' }}>{s.icon}</div>
                <h3>{s.t}</h3>
                <p style={{ fontSize: '0.88rem', marginTop: '0.4rem' }}>{s.d}</p>
              </div>
            </FadeIn>
          )}
        </div>
      </Section>

      <ProductShowcase
        navigate={navigate}
        tweaks={tweaks}
        showPricingCTA={false}
        onTierClick={(tier, productKey, catalogProduct, selectedColor) =>
          setModalData({ tier, productKey, catalogProduct, selectedColor })
        }
      />

      <Section bg="light">
        <FadeIn>
          <div style={{ textAlign: 'center', maxWidth: 680, margin: '0 auto' }}>
            <h2>Full-color printing. No extra charge.</h2>
            <GoldRule style={{ margin: '1rem auto' }} />
            <p style={{ fontSize: '1.02rem' }}>Other providers charge per-color fees that aren't in their advertised price — $90–$360 in hidden costs on a 3-color, 30-shirt run. At Aureal, every design prints in full color, no matter how many colors it uses.</p>
            <Btn variant="outline" onClick={() => navigate('pricing')} style={{ marginTop: '1.5rem' }}>See Full Pricing →</Btn>
          </div>
        </FadeIn>
      </Section>

      <GoldCTA headline="Your community deserves merch that won't end up at a thrift store." cta="Start Your Order" navigate={navigate} />

      {modalData &&
        <CustomOrderModal
          tier={modalData.tier}
          productKey={modalData.productKey}
          catalogProduct={modalData.catalogProduct}
          initialColor={modalData.selectedColor}
          onClose={() => setModalData(null)}
          navigate={navigate}
        />
      }
    </div>);

}

/* ═══ COMMUNITY STOREFRONT PAGE ═══ */

/* Fallback products for Claude Design preview (no Shopify) */
const FALLBACK_COMMUNITY_PRODUCTS = [
  { org: 'Purdue Climbing Club', name: 'Summit Hoodie', price: '$38.99' },
  { org: 'Purdue Climbing Club', name: 'Basecamp Tee', price: '$23.99' },
  { org: 'Boiler Film Society', name: "Director's Cut Hoodie", price: '$38.99' },
  { org: 'Boiler Film Society', name: 'Screenplay Tee', price: '$23.99' },
  { org: 'PSEA', name: 'Educator Quarter-Zip', price: '$43.49' },
  { org: 'IEEE Purdue', name: 'Circuit Tee', price: '$23.99' },
  { org: 'Debate Team', name: 'Opening Statement Polo', price: '$34.99' },
  { org: 'PSEA', name: 'Future Teacher Tee', price: '$23.99' }
];

function ProductModal({ product, onClose, onAddToCart }) {
  const purchaseEnabled = window.PURCHASE_ENABLED;
  const hasVariants = product.variants && product.variants.length > 0;
  const fallbackSizes = ['XS', 'S', 'M', 'L', 'XL', '2XL'];

  const availableVariants = hasVariants ? product.variants.filter(v => v.available) : [];
  const initialVariant = hasVariants ? (availableVariants[0] || product.variants[0] || null) : null;

  const [variant, setVariant] = React.useState(initialVariant);
  const [size, setSize] = React.useState(null);
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const handleAdd = () => {
    if (hasVariants) {
      if (!variant) return;
      onAddToCart({
        org: product.org || product._collectionTitle,
        name: product.name,
        price: variant.price,
        size: variant.size || variant.title,
        qty,
        variantId: variant.id,
        image: product.image
      });
    } else {
      if (!size) return;
      onAddToCart({ ...product, size, qty });
    }
    setAdded(true);
    setTimeout(() => { setAdded(false); }, 1800);
  };

  const displayPrice = hasVariants && variant ? variant.price : product.price;
  const canAdd = hasVariants ? !!variant : !!size;

  return (
    <div className="au-modal-overlay" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="au-modal">
        <button className="au-modal-close" onClick={onClose}>✕</button>
        <div className="au-modal-img">
          {product.image
            ? <img src={product.image} alt={product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <ImgPlaceholder aspect="4/5" label="Product photo" />
          }
        </div>
        <div className="au-modal-body">
          <div className="au-product-org" style={{ fontSize: '0.65rem', marginBottom: '0.5rem' }}>{product.org || product._collectionTitle}</div>
          <h2 style={{ fontSize: '1.55rem', fontWeight: 400, marginBottom: '0.25rem' }}>{product.name}</h2>
          <p style={{ color: 'var(--gold)', fontSize: '1.15rem', fontWeight: 600, marginBottom: '1.25rem' }}>{displayPrice}</p>

          {(product.descriptionHtml || product.description) && (
            <div
              className="au-product-desc"
              dangerouslySetInnerHTML={{ __html: product.descriptionHtml || product.description }}
            />
          )}

          {purchaseEnabled && hasVariants && (
            <div>
              <p style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '0.3rem' }}>Size</p>
              <div className="au-size-grid">
                {product.variants.map((v) =>
                  <button
                    key={v.id}
                    className={'au-size-btn' + (variant && variant.id === v.id ? ' sel' : '')}
                    disabled={!v.available}
                    onClick={() => setVariant(v)}
                    style={!v.available ? { opacity: 0.35, cursor: 'not-allowed' } : null}>
                    {v.size || v.title}
                  </button>
                )}
              </div>
            </div>
          )}

          {purchaseEnabled && !hasVariants && (
            <div>
              <p style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '0.3rem' }}>Size</p>
              <div className="au-size-grid">
                {fallbackSizes.map((s) =>
                  <button key={s} className={'au-size-btn' + (size === s ? ' sel' : '')} onClick={() => setSize(s)}>{s}</button>
                )}
              </div>
            </div>
          )}

          {purchaseEnabled && (
            <div>
              <p style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--text-muted)', marginBottom: '0.3rem' }}>Quantity</p>
              <div className="au-qty-row">
                <button className="au-qty-btn" onClick={() => setQty((q) => Math.max(1, q - 1))}>−</button>
                <span style={{ fontSize: '1rem', minWidth: 24, textAlign: 'center', color: 'var(--white)' }}>{qty}</span>
                <button className="au-qty-btn" onClick={() => setQty((q) => q + 1)}>+</button>
              </div>
            </div>
          )}

          <div style={{ borderTop: '1px solid var(--border)', paddingTop: '1.5rem', marginTop: 'auto' }}>
            {purchaseEnabled ? (
              <div>
                {!canAdd && <p style={{ fontSize: '0.75rem', color: 'var(--text-muted)', marginBottom: '0.75rem', fontStyle: 'italic' }}>Select a size to continue.</p>}
                <Btn
                  variant="primary"
                  style={{ width: '100%', justifyContent: 'center', opacity: canAdd ? 1 : 0.45, transition: 'opacity 0.2s' }}
                  onClick={handleAdd}>
                  {added ? '✓ Added to Cart' : 'Add to Cart'}
                </Btn>
              </div>
            ) : (
              <div style={{
                width: '100%', padding: '0.95rem 1rem', textAlign: 'center',
                fontSize: '0.72rem', fontWeight: 600, letterSpacing: '0.22em',
                textTransform: 'uppercase', color: 'var(--text-muted)',
                background: 'transparent', border: '2px solid var(--gold)',
                borderRadius: 'var(--radius)', cursor: 'default',
                userSelect: 'text', pointerEvents: 'none'
              }}>Members Only</div>
            )}
          </div>
        </div>
      </div>
    </div>);
}

function FilterPill({ filterKey, active, onClick, label }) {
  return (
    <button
      onClick={onClick}
      style={{
        fontFamily: 'var(--font-body)', fontSize: '0.75rem', fontWeight: 500,
        padding: '0.4rem 1rem', border: '1px solid',
        borderColor: 'var(--gold)',
        background: active ? 'var(--gold)' : 'transparent',
        color: active ? 'var(--dark)' : 'var(--text-muted)',
        cursor: 'pointer', transition: 'all 0.2s', borderRadius: 'var(--radius)'
      }}>
      {label}
    </button>
  );
}

function CommunityPage({ navigate, addToCart }) {
  const [collections, setCollections] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [selectedProduct, setSelectedProduct] = React.useState(null);

  /* Deep-link: consume __aurealInitialOrg (set by integration's URL normalization),
     or parse org from hash, or default to 'all'. */
  const initialOrg = React.useMemo(() => {
    if (window.__aurealInitialOrg) {
      const v = window.__aurealInitialOrg;
      window.__aurealInitialOrg = null;
      return v;
    }
    const hash = window.location.hash || '';
    const m = hash.match(/[?&]org=([^&]+)/);
    return m ? decodeURIComponent(m[1]) : 'all';
  }, []);
  const [filter, setFilter] = React.useState(initialOrg);

  /* Fetch from Shopify if integration is loaded, otherwise use fallback data */
  React.useEffect(() => {
    if (window.__aurealFetchCollections) {
      let cancelled = false;
      window.__aurealFetchCollections().then(cols => {
        if (cancelled) return;
        if (!cols.length) setError('No collections loaded.');
        setCollections(cols);
        if (initialOrg !== 'all' && !cols.find(c => c.handle === initialOrg)) {
          setFilter('all');
        }
      }).catch(e => { if (!cancelled) setError(String(e)); });
      return () => { cancelled = true; };
    } else {
      /* Claude Design fallback: build pseudo-collections from hardcoded products */
      const orgMap = {};
      FALLBACK_COMMUNITY_PRODUCTS.forEach(p => {
        if (!orgMap[p.org]) orgMap[p.org] = { handle: p.org, title: p.org, products: [] };
        orgMap[p.org].products.push(p);
      });
      setCollections(Object.values(orgMap));
    }
  }, []);

  /* Sync filter to URL so storefront links are shareable */
  React.useEffect(() => {
    const base = '#/community';
    const target = filter === 'all' ? base : base + '?org=' + encodeURIComponent(filter);
    if (window.location.hash !== target) {
      history.replaceState(null, '', target);
    }
  }, [filter]);

  const copyStorefrontLink = () => {
    const url = window.location.origin + window.location.pathname + '#/community?org=' + encodeURIComponent(filter);
    navigator.clipboard && navigator.clipboard.writeText(url);
  };

  const allProducts = React.useMemo(() => {
    if (!collections) return [];
    return collections.flatMap(c => c.products.map(p => ({ ...p, _collectionHandle: c.handle, _collectionTitle: c.title })));
  }, [collections]);

  const shown = React.useMemo(() => {
    if (!collections) return [];
    if (filter === 'all') return allProducts;
    const col = collections.find(c => c.handle === filter);
    return col ? col.products.map(p => ({ ...p, _collectionHandle: col.handle, _collectionTitle: col.title })) : [];
  }, [collections, filter, allProducts]);

  const isLoading = collections === null;

  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <FadeIn>
          <Eyebrow>Community Storefront</Eyebrow>
          <h1>Made by communities.<br />Available to everyone.</h1>
          <p style={{ maxWidth: 560, marginTop: '0.75rem', marginBottom: '2rem' }}>
            Every partner organization's merch lives here. Browse by community, discover new orgs, and support the ones you care about.
          </p>
        </FadeIn>

        <FadeIn delay={200}>
          <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', marginBottom: '1rem' }}>
            <FilterPill filterKey="all" active={filter === 'all'} onClick={() => setFilter('all')} label="All Communities" />
            {(collections || []).map(c =>
              <FilterPill key={c.handle} filterKey={c.handle} active={filter === c.handle} onClick={() => setFilter(c.handle)} label={c.title} />
            )}
          </div>

          {filter !== 'all' && (
            <button
              onClick={copyStorefrontLink}
              style={{
                fontFamily: 'var(--font-body)', fontSize: '0.75rem', fontWeight: 500,
                padding: '0.4rem 1rem', border: '1px dashed var(--gold)',
                background: 'transparent', color: 'var(--gold)',
                cursor: 'pointer', borderRadius: 'var(--radius)', marginBottom: '2rem'
              }}>
              Copy storefront link →
            </button>
          )}
        </FadeIn>

        {isLoading && (
          <div style={{ color: 'var(--text-muted)', padding: '2rem 0' }}>Loading products…</div>
        )}

        {error && (
          <div style={{ color: '#c44', padding: '2rem 0' }}>{error}</div>
        )}

        {!isLoading && !error && shown.length === 0 && (
          <div style={{ color: 'var(--text-muted)', padding: '2rem 0' }}>No products in this collection yet.</div>
        )}

        {!isLoading && shown.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '1.5rem' }}>
            {shown.map((p, i) =>
              <FadeIn key={p.shopifyId || (p.org + '-' + p.name)} delay={i * 60}>
                <div className="au-product-card" onClick={() => setSelectedProduct(p)}>
                  {p.image
                    ? <img src={p.image} alt={p.name} style={{ width: '100%', aspectRatio: '4/5', objectFit: 'cover', borderRadius: 8, marginBottom: '0.75rem', display: 'block' }} />
                    : <ImgPlaceholder aspect="4/5" label="Product photo" style={{ marginBottom: '0.75rem' }} />
                  }
                  <div className="au-product-org">{p.org || p._collectionTitle}</div>
                  <div className="au-product-name">{p.name}</div>
                  <div className="au-product-price">{p.price}</div>
                </div>
              </FadeIn>
            )}
          </div>
        )}
      </Section>

      <GoldCTA headline="Want your community on this page?" cta="Start a Partnership" navigate={navigate} />

      {selectedProduct &&
        <ProductModal
          product={selectedProduct}
          onClose={() => setSelectedProduct(null)}
          onAddToCart={(item) => { addToCart(item); setSelectedProduct(null); navigate('cart'); }} />
      }
    </div>);
}

/* ═══ CART PAGE ═══ */
function CartPage({ cart, removeFromCart, updateQty, navigate }) {
  const parsePrice = (str) => parseFloat((str || '0').replace('$', ''));
  const subtotal = (cart || []).reduce((sum, item) => sum + parsePrice(item.price) * item.qty, 0);
  const totalQty = (cart || []).reduce((s, i) => s + i.qty, 0);

  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <FadeIn>
          <Eyebrow>Cart</Eyebrow>
          <h1>{!cart || cart.length === 0 ?
            'Your cart is empty.' :
            `${totalQty} item${totalQty === 1 ? '' : 's'} ready to order.`}
          </h1>
          <GoldRule />
        </FadeIn>

        {!cart || cart.length === 0 ?
        <FadeIn delay={100}>
            <div style={{ textAlign: 'center', padding: '4rem 0' }}>
              <p style={{ color: 'var(--text-muted)', marginBottom: '2rem' }}>Browse the Community Storefront to find something worth wearing.</p>
              <Btn variant="outline" onClick={() => navigate('community')}>Browse Storefront →</Btn>
            </div>
          </FadeIn> :

        <FadeIn delay={100}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem', marginTop: '2rem' }}>
              {cart.map((item) =>
            <div key={item.key} className="au-cart-item">
                  <ImgPlaceholder aspect="1/1" label="" style={{ borderRadius: 8, minWidth: 72 }} />
                  <div>
                    <div className="au-product-org" style={{ marginBottom: '0.2rem' }}>{item.org}</div>
                    <p style={{ fontWeight: 600, color: 'var(--white)', marginBottom: '0.2rem' }}>{item.name}</p>
                    <p style={{ fontSize: '0.78rem', color: 'var(--text-muted)' }}>Size: {item.size}</p>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '0.6rem' }}>
                    <p style={{ color: 'var(--gold)', fontWeight: 600 }}>{item.price}</p>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                      <button className="au-qty-btn" onClick={() => updateQty(item.key, -1)}>−</button>
                      <span style={{ minWidth: 20, textAlign: 'center', fontSize: '0.9rem', color: 'var(--white)' }}>{item.qty}</span>
                      <button className="au-qty-btn" onClick={() => updateQty(item.key, 1)}>+</button>
                    </div>
                    <button onClick={() => removeFromCart(item.key)} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: '0.72rem', cursor: 'pointer', textDecoration: 'underline', padding: 0 }}>Remove</button>
                  </div>
                </div>
            )}
            </div>

            <div className="au-cart-summary">
              <div className="au-cart-totals">
                <div className="au-cart-row">
                  <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Subtotal</span>
                  <span style={{ color: 'var(--white)' }}>${subtotal.toFixed(2)}</span>
                </div>
                <div className="au-cart-row" style={{ paddingBottom: '1rem', borderBottom: '1px solid var(--border)', marginBottom: '0.75rem' }}>
                  <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Shipping</span>
                  <span style={{ color: 'var(--text-muted)', fontSize: '0.82rem', fontStyle: 'italic' }}>Calculated at checkout</span>
                </div>
                <div className="au-cart-row" style={{ marginBottom: '1.75rem' }}>
                  <span style={{ fontWeight: 700, fontSize: '1.05rem' }}>Total</span>
                  <span style={{ color: 'var(--gold)', fontWeight: 700, fontSize: '1.1rem' }}>${subtotal.toFixed(2)}</span>
                </div>
                <Btn variant="primary" style={{ width: '100%', justifyContent: 'center', fontSize: '0.95rem' }} onClick={() => {}}>
                  Proceed to Checkout →
                </Btn>
                <button onClick={() => navigate('community')} style={{ display: 'block', width: '100%', textAlign: 'center', marginTop: '1rem', background: 'none', border: 'none', color: 'var(--text-muted)', fontSize: '0.78rem', cursor: 'pointer', textDecoration: 'underline' }}>
                  Continue Shopping
                </button>
              </div>
            </div>
          </FadeIn>
        }
      </Section>
    </div>);

}

/* ═══ ABOUT PAGE ═══ */
function AboutPage({ navigate, tweaks, setTweak }) {
  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4rem', alignItems: 'center' }}>
          <FadeIn>
            <Eyebrow>Our Story</Eyebrow>
            <h1>It started with a choir hoodie.</h1>
            <GoldRule />
            <p style={{ marginBottom: '1rem' }}>I didn't start a company because I had a business plan. I started one because I was tired of walking out of malls empty handed and dissatisfied.

            </p>
            <p style={{ marginBottom: '1rem' }}>Later on, my choir class needed hoodies, so I designed and supplied them. People kept asking who made them. Then another class needed merch. And then another.

            </p>
            <p>That's how Aureal started. Today, we've delivered thousands of T-shirts and hoodies — none of it possible without the support of people like you.</p>
          </FadeIn>
          <FadeIn delay={150}>
            <CropImage src="assets/founder.jpg" tweaks={tweaks} setTweak={setTweak} keyPrefix="founder" defaultAspect="3/4" />
          </FadeIn>
        </div>
      </Section>

      <Section bg="light">
        <FadeIn><Eyebrow>Our Mission</Eyebrow><h2>Build a network of communities that use fashion as a tool for fundraising, creative opportunity, and connection.</h2></FadeIn>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '1.5rem', marginTop: '2rem' }}>
          {[{ t: 'Community First', d: 'Every business decision is evaluated through the lens of whether it strengthens community bonds. ' }, { t: 'Quality > Quantity', d: 'We compete on product quality, not price. Everything we do is held to the highest standard. ' },
          { t: 'Creative Empowerment', d: 'Designers, communities, and individuals are given pathways to create, earn, and grow through the platform.' },
          { t: 'Transparency', d: 'Published pricing replaces quotes. What you see is what you get. If you ever have any questions, never hesitate to reach out.' }].
          map((p, i) =>
          <FadeIn key={i} delay={i * 80}>
              <div style={{ padding: '1.5rem', background: '#f2ece4', border: '1.5px solid var(--gold)', borderRadius: '24px', boxShadow: '0 2px 12px rgba(36,36,36,0.09), 0 1px 3px rgba(36,36,36,0.05)' }}>
                <h3 style={{ marginBottom: '0.4rem' }}>{p.t}</h3>
                <p style={{ fontSize: '0.9rem' }}>{p.d}</p>
              </div>
            </FadeIn>
          )}
        </div>
      </Section>

      <GoldCTA headline="Do you see the vision?" navigate={navigate} />
    </div>);

}

/* ═══ JOIN PAGE ═══ */
function JoinPage({ navigate }) {
  const roles = [
  { type: 'Contract', title: 'Designer', desc: 'Create original artwork for community merch orders.', comp: '$40 / $60 / $80 / $100 per design · $10 Aureal fee' },
  { type: 'Independent', title: 'Ambassador', desc: 'Bring organizations to Aureal and promote through your network with a unique ambassador code.', comp: '15% / 20% / 25% GP commission · Tiered by unit count' }];

  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <FadeIn>
          <Eyebrow>Join Aureal</Eyebrow>
          <h1>There are only two things we are looking for: Passion &amp; Potential</h1>
          <p style={{ maxWidth: 600, marginTop: '1rem', fontSize: '1.02rem' }}>Every role is tied to contribution. You earn from the value you create. 

          </p>
        </FadeIn>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '1.5rem', marginTop: '2.5rem' }}>
          {roles.map((r, i) =>
          <FadeIn key={i} delay={i * 100}>
              <div className="au-role-card">
                <div className="au-role-type">{r.type}</div>
                <h3 style={{ marginBottom: '0.5rem', fontStyle: 'italic', fontFamily: "'Rubik', sans-serif", fontWeight: 400 }}>{r.title}</h3>
                <p style={{ fontSize: '0.88rem', marginBottom: '0.75rem' }}>{r.desc}</p>
                <div className="au-role-comp">{r.comp}</div>
                <span className="au-role-apply" onClick={(e) => e.stopPropagation()}>Apply <span>→</span></span>
              </div>
            </FadeIn>
          )}
        </div>
      </Section>


    </div>);

}

/* ═══ CONTACT PAGE ═══ */
function ContactPage({ navigate }) {
  const [submitted, setSubmitted] = React.useState(false);
  const pricingData = React.useRef(window.__pricingData || null);

  React.useEffect(() => {
    // Clear after reading so it doesn't persist across navigations
    window.__pricingData = null;
  }, []);

  // Map pricing data to form defaults
  const pd = pricingData.current;
  const defaultProduct = pd ? pd.tier === 'premium' ? 'Quarter-Zips' : 'T-Shirts' : '';
  const defaultQty = pd ? `${pd.qty} units` : '';
  const defaultVision = pd ? `Interested in ${pd.tierLabel} tier, ${pd.printLabel}, ${pd.shipLabel} delivery. Estimated ${pd.qty} units at ${fmt(pd.pu)}/unit (${fmt(pd.total)} total).` : '';

  return (
    <div>
      <Section bg="dark" padTop="9rem">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4rem', alignItems: 'start' }}>
          <FadeIn>
            <Eyebrow>GET STARTED</Eyebrow>
            <h1 style={{ fontWeight: 300 }}>Let's make something worth wearing.</h1>

            <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', margin: '2rem 0 2.5rem' }}>
              {[
              { t: 'Response within 24 hours', d: null },
              { t: 'This starts a conversation, not a contract.', d: null },
              { t: 'First-time clients get a free design consultation.', d: null },
              { t: 'Secret catalog on request', d: null }].
              map((s, i) =>
              <div key={i} style={{ display: 'flex', gap: '1rem', alignItems: 'flex-start', paddingBottom: '1rem', borderBottom: i < 3 ? '1px solid var(--border)' : 'none' }}>
                  <div>
                    {s.t && <p style={{ fontWeight: 600, color: 'var(--white)', marginBottom: '0.15rem' }}>{s.t}</p>}
                    {s.d && <p style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{s.d}</p>}
                  </div>
                </div>
              )}
            </div>

            <Btn variant="primary" style={{ fontSize: '1rem', padding: '0.85rem 2rem', letterSpacing: '0.04em' }} onClick={() => window.open('mailto:aurealapparel@gmail.com?subject=Project%20Inquiry', '_blank')}>Start Your Project →</Btn>
          </FadeIn>

          <FadeIn delay={200} style={{ paddingTop: '3rem' }}>
            <div style={{
              maxWidth: 480,
              padding: '2.5rem',
              background: 'var(--white)',
              border: '1.5px solid var(--gold)',
              borderRadius: 24,
              boxShadow: '0 2px 12px rgba(36,36,36,0.09), 0 1px 3px rgba(36,36,36,0.05)',
              display: 'flex', flexDirection: 'column', justifyContent: 'center'
            }}>
              <p style={{ fontSize: '0.7rem', fontWeight: 700, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--gold)', marginBottom: '1.75rem', textAlign: "left" }}>Trusted by communities at</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '1.5rem' }}>
                {['Purdue University', 'Dougherty Valley High School', 'American Cancer Society', 'UC San Diego'].map((org, i) =>
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '1rem', paddingBottom: '1.5rem', borderBottom: i < 3 ? '1px solid rgba(36,36,36,0.1)' : 'none' }}>
                    <p style={{ fontFamily: 'var(--font-display)', fontSize: '1.05rem', color: '#242424', fontWeight: 400 }}>{org}</p>
                  </div>
                )}
              </div>
              <p style={{ fontSize: '0.78rem', fontStyle: 'italic', color: '#242424', opacity: 0.5, marginTop: '2rem' }}>More partners coming soon.</p>
            </div>
          </FadeIn>
        </div>
      </Section>
    </div>);

}

Object.assign(window, {
  PricingPage, CustomPage, CommunityPage, AboutPage, JoinPage, ContactPage, CartPage,
  PRICES, TIER_META, PRODUCT_META, interpolatePrice, QuoteCalc
});