/* PLP, PDP, Cart, Checkout (personal + corporate), Confirmation, Survey, Access code, ERG, Exec */
/* globals React, Icon, ProductImage, UberMark */

// ——————— Shared product card ———————
const ProductCard = ({ product, onOpen }) => {
  return (
    <button onClick={() => onOpen(product)} style={{ background: 'transparent', border: 0, padding: 0, textAlign: 'left', cursor: 'pointer' }}>
      <div style={{ position: 'relative' }}>
        <ProductImage product={product}/>
        {product.tier === 'premium' && (
          <div style={{ position: 'absolute', top: 10, right: 10 }}>
            <span className="chip chip-gold"><Icon name="sparkle" size={12}/> Presentation</span>
          </div>
        )}
      </div>
      <div style={{ padding: '12px 2px 0' }}>
        <div style={{ fontSize: 11, color: 'var(--u-text-3)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 4 }}>{product.cat} · {product.sub}</div>
        <div style={{ fontSize: 15, fontWeight: 500, marginBottom: 4 }}>{product.name}</div>
        <div style={{ fontSize: 14, fontWeight: 600 }}>${product.price}</div>
      </div>
    </button>
  );
};
window.ProductCard = ProductCard;

// ——————— PLP ———————
const isEatsProduct = (p) => p.color === 'eats' || /uber eats/i.test(p.name);
const CATEGORY_MAP = { 'Apparel':'Apparel', 'Accessories':'Accessories', 'Drinkware':'Drinkware', 'Tech':'Tech', 'Gift kits':'Gift Kits' };
const PLP = ({ filter, onOpen, onNav }) => {
  const all = window.CATALOG;
  const [brand, setBrand] = React.useState('all'); // 'all' | 'uber' | 'eats'
  const [cats, setCats] = React.useState(new Set()); // multi-select; empty = All
  const [tiers, setTiers] = React.useState(new Set()); // 'standard' | 'premium'
  const [sizes, setSizes] = React.useState(new Set());
  const [sort, setSort] = React.useState('featured');

  const toggleSet = (setter, set, value) => {
    const next = new Set(set);
    if (next.has(value)) next.delete(value); else next.add(value);
    setter(next);
  };

  let items = all;
  let title = 'Shop all';
  let sub = 'Every item, approved by Brand Desk.';
  if (filter === 'apparel') { items = all.filter(p => p.cat === 'Apparel'); title = 'Apparel'; sub = 'T-shirts, sweatshirts, outerwear.'; }
  else if (filter === 'accessories') { items = all.filter(p => p.cat === 'Accessories'); title = 'Accessories'; sub = 'Bags, hats, lanyards, pens, notebooks.'; }
  else if (filter === 'drinkware') { items = all.filter(p => p.cat === 'Drinkware'); title = 'Drinkware'; sub = 'Tumblers, bottles, mugs.'; }
  else if (filter === 'tech') { items = all.filter(p => p.cat === 'Tech'); title = 'Tech accessories'; sub = 'Charging, audio, bags, and on-the-go essentials.'; }
  else if (filter === 'kits') { items = all.filter(p => p.cat === 'Gift Kits'); title = 'Gift kits'; sub = 'Pre-curated kits for onboarding, milestones, and teams.'; }

  // Apply sidebar filters
  if (brand === 'uber') items = items.filter(p => !isEatsProduct(p));
  else if (brand === 'eats') items = items.filter(p => isEatsProduct(p));
  if (cats.size > 0) items = items.filter(p => [...cats].some(c => CATEGORY_MAP[c] === p.cat));
  if (tiers.size > 0) items = items.filter(p => tiers.has(p.tier));
  if (sizes.size > 0) items = items.filter(p => p.sizes && p.sizes.some(s => sizes.has(s)));

  // Sorting
  items = [...items];
  if (sort === 'newest') items.reverse();
  else if (sort === 'price-low') items.sort((a,b) => a.price - b.price);
  else if (sort === 'price-high') items.sort((a,b) => b.price - a.price);

  const activeCount = (brand !== 'all' ? 1 : 0) + cats.size + tiers.size + sizes.size;

  return (
    <div style={{ maxWidth: 1440, margin: '0 auto', padding: '32px 32px 64px' }}>
      <div style={{ fontSize: 12, color: 'var(--u-text-3)', marginBottom: 12 }}>
        <button onClick={() => onNav('landing')} style={{ background:'transparent', border:0, cursor:'pointer', padding:0, color:'var(--u-text-3)', fontSize: 12 }}>Home</button> <span style={{ margin: '0 8px' }}>/</span> {title}
      </div>
      <CategoryChips current={filter || 'browse'} onNav={onNav}/>
      <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 32 }}>
        <div>
          <h1 className="u-h2" style={{ margin: 0 }}>{title}</h1>
          <p style={{ margin: '6px 0 0', color: 'var(--u-text-2)' }}>{sub}</p>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {activeCount > 0 && (
            <button onClick={() => { setBrand('all'); setCats(new Set()); setTiers(new Set()); setSizes(new Set()); }} className="btn btn-sm" style={{ background: 'transparent', color: 'var(--u-text-2)', textDecoration: 'underline', padding: '9px 8px' }}>Clear all</button>
          )}
          <select className="input" value={sort} onChange={e => setSort(e.target.value)} style={{ width: 200, padding: '10px 12px', fontSize: 14 }}>
            <option value="featured">Sort: Featured</option>
            <option value="newest">Newest</option>
            <option value="price-low">Price — low to high</option>
            <option value="price-high">Price — high to low</option>
          </select>
        </div>
      </div>

      {/* Filter toolbar + grid (full-width grid, filters as dropdowns) */}
      <FilterToolbar
        brand={brand} setBrand={setBrand}
        tiers={tiers} setTiers={setTiers}
        sizes={sizes} setSizes={setSizes}
        toggleSet={toggleSet}
        itemCount={items.length}
      />
      <div>
        {items.length > 0 ? (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24 }}>
            {items.map(p => <ProductCard key={p.id} product={p} onOpen={onOpen}/>)}
          </div>
        ) : (
          <div style={{ padding: '64px 24px', textAlign: 'center', border: '1px dashed var(--u-line-strong)', borderRadius: 8 }}>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>No items match your filters.</div>
            <div style={{ fontSize: 14, color: 'var(--u-text-2)', marginBottom: 16 }}>Try removing a filter to see more products.</div>
            <button onClick={() => { setBrand('all'); setCats(new Set()); setTiers(new Set()); setSizes(new Set()); }} className="btn btn-sm btn-outline">Clear all filters</button>
          </div>
        )}
      </div>
    </div>
  );
};
window.PLP = PLP;

// ——————— Filter toolbar (horizontal, above grid) ———————
const FilterToolbar = ({ brand, setBrand, tiers, setTiers, sizes, setSizes, toggleSet, itemCount }) => {
  const [open, setOpen] = React.useState(null); // 'brand' | 'tier' | 'size' | null
  const ref = React.useRef(null);
  React.useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(null); };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);
  const brandLabel = brand === 'all' ? 'All brands' : brand === 'uber' ? 'Uber' : 'Uber Eats';
  const tierLabel = tiers.size === 0 ? 'All tiers' : tiers.size === 1 ? (tiers.has('premium') ? 'Presentation-grade' : 'Standard swag') : `${tiers.size} tiers`;
  const sizeLabel = sizes.size === 0 ? 'All sizes' : [...sizes].join(', ');

  const Chip = ({ id, label, active, hasValue }) => (
    <button onClick={() => setOpen(open === id ? null : id)} style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '9px 14px',
      background: hasValue ? '#000' : '#fff',
      color: hasValue ? '#fff' : 'var(--u-text)',
      border: '1px solid ' + (hasValue ? '#000' : 'var(--u-line-strong)'),
      borderRadius: 999,
      fontSize: 13,
      fontWeight: 500,
      cursor: 'pointer',
      whiteSpace: 'nowrap',
    }}>
      {label}
      <svg width="10" height="10" viewBox="0 0 10 10" fill="none" style={{ opacity: 0.6 }}><path d="M2 3.5L5 6.5L8 3.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
    </button>
  );

  return (
    <div ref={ref} style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24, flexWrap: 'wrap', position: 'relative' }}>
      <span style={{ fontSize: 13, color: 'var(--u-text-2)', marginRight: 4 }}>{itemCount} {itemCount === 1 ? 'item' : 'items'}</span>
      <span style={{ width: 1, height: 20, background: 'var(--u-line)', margin: '0 6px' }}/>

      {/* Brand */}
      <div style={{ position: 'relative' }}>
        <Chip id="brand" label={brandLabel} hasValue={brand !== 'all'}/>
        {open === 'brand' && (
          <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, background:'#fff', border:'1px solid var(--u-line)', borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.12)', padding: 12, minWidth: 180, zIndex: 20 }}>
            {[{v:'all',l:'All brands'},{v:'uber',l:'Uber'},{v:'eats',l:'Uber Eats'}].map(o => (
              <label key={o.v} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 4px', fontSize: 13, fontWeight: brand === o.v ? 600 : 400, cursor: 'pointer' }}>
                <input type="radio" name="brand-top" checked={brand === o.v} onChange={() => { setBrand(o.v); setOpen(null); }} style={{ accentColor: '#000' }}/> {o.l}
              </label>
            ))}
          </div>
        )}
      </div>

      {/* Tier */}
      <div style={{ position: 'relative' }}>
        <Chip id="tier" label={tierLabel} hasValue={tiers.size > 0}/>
        {open === 'tier' && (
          <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, background:'#fff', border:'1px solid var(--u-line)', borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.12)', padding: 12, minWidth: 220, zIndex: 20 }}>
            {[{v:'standard',l:'Standard swag'},{v:'premium',l:'Presentation-grade'}].map(o => (
              <label key={o.v} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 4px', fontSize: 13, fontWeight: tiers.has(o.v) ? 600 : 400, cursor: 'pointer' }}>
                <input type="checkbox" checked={tiers.has(o.v)} onChange={() => toggleSet(setTiers, tiers, o.v)} style={{ accentColor: '#000' }}/> {o.l}
              </label>
            ))}
          </div>
        )}
      </div>

      {/* Size */}
      <div style={{ position: 'relative' }}>
        <Chip id="size" label={sizeLabel} hasValue={sizes.size > 0}/>
        {open === 'size' && (
          <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, background:'#fff', border:'1px solid var(--u-line)', borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.12)', padding: 12, minWidth: 220, zIndex: 20 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
              {['XS','S','M','L','XL','XXL'].map(o => (
                <button key={o} onClick={() => toggleSet(setSizes, sizes, o)} style={{
                  padding: '8px 0', fontSize: 13, fontWeight: sizes.has(o) ? 600 : 500,
                  background: sizes.has(o) ? '#000' : '#fff',
                  color: sizes.has(o) ? '#fff' : 'var(--u-text)',
                  border: '1px solid ' + (sizes.has(o) ? '#000' : 'var(--u-line-strong)'),
                  borderRadius: 6, cursor: 'pointer',
                }}>{o}</button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
window.FilterToolbar = FilterToolbar;

// ——————— PDP ———————
const PDP = ({ product, onAdd, onNav }) => {
  const [size, setSize] = React.useState(product.sizes ? 'M' : null);
  const [qty, setQty] = React.useState(1);
  const [added, setAdded] = React.useState(false);
  return (
    <div style={{ maxWidth: 1440, margin: '0 auto', padding: '32px 32px 64px' }}>
      <div style={{ fontSize: 12, color: 'var(--u-text-3)', marginBottom: 24 }}>
        <button onClick={() => onNav('landing')} style={{ background:'transparent', border:0, cursor:'pointer', padding:0, color:'var(--u-text-3)', fontSize: 12 }}>Home</button>
        <span style={{ margin: '0 8px' }}>/</span>
        <button onClick={() => onNav(product.cat.toLowerCase())} style={{ background:'transparent', border:0, cursor:'pointer', padding:0, color:'var(--u-text-3)', fontSize: 12 }}>{product.cat}</button>
        <span style={{ margin: '0 8px' }}>/</span>
        <span style={{ color: 'var(--u-text)' }}>{product.name}</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 64 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr', gap: 12 }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[0,1,2,3].map(i => (
              <div key={i} className={`img-ph ${product.color === 'eats' ? 'is-eats' : product.color === 'black' ? 'is-black' : product.color === 'premium' ? 'is-premium' : ''}`} style={{ aspectRatio: '1/1', borderRadius: 14 }}>
                <div className="ph-label" style={{ fontSize: 9 }}>view {i+1}</div>
              </div>
            ))}
          </div>
          <div><ProductImage product={product}/></div>
        </div>
        <div style={{ paddingTop: 8 }}>
          <div style={{ fontSize: 12, color: 'var(--u-text-3)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 10 }}>
            {product.cat} · {product.sub} · SKU {product.sku}
          </div>
          <h1 className="u-h2" style={{ margin: 0, marginBottom: 12 }}>{product.name}</h1>
          <div style={{ fontSize: 24, fontWeight: 600, marginBottom: 20 }}>${product.price}</div>
          {product.tier === 'premium' && (
            <div style={{ padding: 16, background: '#FAF5EA', border: '1px solid #E8D9B8', borderRadius: 8, marginBottom: 20, display:'flex', gap: 12, alignItems: 'start' }}>
              <Icon name="sparkle" size={18} style={{ color: '#8a6b2d', marginTop: 1 }}/>
              <div>
                <div style={{ fontWeight: 600, fontSize: 14 }}>Presentation-grade</div>
                <div style={{ fontSize: 13, color: 'var(--u-text-2)', marginTop: 2 }}>Premium materials, gift packaging, hand-inspected. For executive and client-facing use.</div>
              </div>
            </div>
          )}
          <p style={{ color: 'var(--u-text-2)', fontSize: 15, lineHeight: 1.6, marginBottom: 28 }}>{product.desc}</p>

          {product.sizes && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 10 }}>
                <span style={{ fontSize: 13, fontWeight: 600 }}>Size</span>
                <a style={{ fontSize: 12, color: 'var(--u-text-2)', textDecoration: 'underline' }}>Size guide</a>
              </div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {product.sizes.map(s => (
                  <button key={s} onClick={() => setSize(s)} style={{
                    minWidth: 52, padding: '12px 14px', fontSize: 14, fontWeight: 500,
                    background: size === s ? '#000' : '#fff',
                    color: size === s ? '#fff' : '#000',
                    border: '1px solid ' + (size === s ? '#000' : 'var(--u-line-strong)'),
                    borderRadius: 4, cursor: 'pointer',
                  }}>{s}</button>
                ))}
              </div>
            </div>
          )}

          <div style={{ marginBottom: 20 }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 10 }}>Quantity</div>
            <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--u-line-strong)', borderRadius: 4 }}>
              <button onClick={() => setQty(Math.max(1, qty - 1))} style={{ background:'transparent', border: 0, padding: '12px 16px', cursor:'pointer' }}><Icon name="minus" size={16}/></button>
              <span style={{ minWidth: 32, textAlign: 'center', fontWeight: 600 }}>{qty}</span>
              <button onClick={() => setQty(qty + 1)} style={{ background:'transparent', border: 0, padding: '12px 16px', cursor:'pointer' }}><Icon name="plus" size={16}/></button>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 10, marginBottom: 20 }}>
            <button onClick={() => { onAdd({ ...product, size, qty }); setAdded(true); setTimeout(() => setAdded(false), 1500); }} className="btn btn-primary btn-lg" style={{ flex: 1 }}>
              {added ? <><Icon name="check" size={18}/>Added to cart</> : 'Add to cart'}
            </button>
            <button className="btn btn-outline btn-lg" style={{ padding: '18px 20px' }}><Icon name="heart" size={18}/></button>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, fontSize: 13, color: 'var(--u-text-2)' }}>
            <div style={{ display:'flex', gap: 8, alignItems:'center' }}><Icon name="truck" size={16}/> Ships in 5–7 days</div>
            <div style={{ display:'flex', gap: 8, alignItems:'center' }}><Icon name="shield" size={16}/> Brand Desk approved</div>
            <div style={{ display:'flex', gap: 8, alignItems:'center' }}><Icon name="globe" size={16}/> Global fulfillment</div>
            <div style={{ display:'flex', gap: 8, alignItems:'center' }}><Icon name="doc" size={16}/> Auto PO + receipt</div>
          </div>
        </div>
      </div>
    </div>
  );
};
window.PDP = PDP;

// ——————— Cart ———————
const Cart = ({ items, setItems, mode, onNav }) => {
  const sub = items.reduce((s, i) => s + i.price * i.qty, 0);
  const tax = sub * 0.085;
  const ship = sub > 75 ? 0 : 9.5;
  const total = sub + tax + ship;
  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: '32px 32px 64px' }}>
      <h1 className="u-h2" style={{ margin: 0, marginBottom: 24 }}>Cart</h1>
      {items.length === 0 ? (
        <div style={{ padding: 80, textAlign: 'center', border: '1px dashed var(--u-line-strong)', borderRadius: 12 }}>
          <div style={{ fontSize: 17, fontWeight: 500, marginBottom: 8 }}>Your cart is empty.</div>
          <button className="btn btn-primary" onClick={() => onNav('browse')}>Browse the store</button>
        </div>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 32 }}>
          <div>
            {items.map((it, idx) => (
              <div key={idx} style={{ display: 'grid', gridTemplateColumns: '100px 1fr auto', gap: 20, padding: '20px 0', borderTop: idx === 0 ? '1px solid var(--u-line)' : 0, borderBottom: '1px solid var(--u-line)', alignItems: 'center' }}>
                <div style={{ width: 100 }}><ProductImage product={it} showLabel={false}/></div>
                <div>
                  <div style={{ fontSize: 12, color: 'var(--u-text-3)', textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 4 }}>{it.cat}</div>
                  <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>{it.name}</div>
                  <div style={{ fontSize: 13, color: 'var(--u-text-2)', marginBottom: 10 }}>
                    {it.size && <span>Size {it.size} · </span>}SKU {it.sku}
                  </div>
                  <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
                    <div style={{ display: 'inline-flex', alignItems: 'center', border: '1px solid var(--u-line-strong)', borderRadius: 4 }}>
                      <button onClick={() => setItems(items.map((x,i) => i === idx ? { ...x, qty: Math.max(1, x.qty - 1) } : x))} style={{ background:'transparent', border: 0, padding: '8px 10px', cursor:'pointer' }}><Icon name="minus" size={14}/></button>
                      <span style={{ minWidth: 28, textAlign: 'center', fontSize: 13, fontWeight: 600 }}>{it.qty}</span>
                      <button onClick={() => setItems(items.map((x,i) => i === idx ? { ...x, qty: x.qty + 1 } : x))} style={{ background:'transparent', border: 0, padding: '8px 10px', cursor:'pointer' }}><Icon name="plus" size={14}/></button>
                    </div>
                    <button onClick={() => setItems(items.filter((_,i) => i !== idx))} style={{ background:'transparent', border: 0, cursor:'pointer', fontSize: 13, color:'var(--u-text-2)', display:'flex', alignItems:'center', gap: 6 }}>
                      <Icon name="trash" size={14}/> Remove
                    </button>
                  </div>
                </div>
                <div style={{ fontWeight: 600, fontSize: 16 }}>${(it.price * it.qty).toFixed(2)}</div>
              </div>
            ))}
          </div>
          <aside>
            <div style={{ background: '#F6F6F6', padding: 24, borderRadius: 12, position: 'sticky', top: 120 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
                <Icon name={mode === 'corporate' ? 'building' : 'user'} size={16}/>
                <span className="chip" style={{ background: mode === 'corporate' ? '#000' : 'var(--u-eats)', color: mode === 'corporate' ? '#fff' : '#000' }}>{mode === 'corporate' ? 'Corporate order' : 'Personal order'}</span>
              </div>
              <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 16 }}>Order summary</div>
              {[
                { l: 'Subtotal', v: `$${sub.toFixed(2)}` },
                { l: 'Shipping', v: ship === 0 ? 'Free' : `$${ship.toFixed(2)}` },
                { l: 'Estimated tax', v: `$${tax.toFixed(2)}` },
              ].map(r => (
                <div key={r.l} style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', fontSize: 14 }}>
                  <span style={{ color: 'var(--u-text-2)' }}>{r.l}</span><span>{r.v}</span>
                </div>
              ))}
              <div style={{ borderTop: '1px solid var(--u-line)', margin: '12px 0', paddingTop: 12, display: 'flex', justifyContent: 'space-between', fontSize: 16, fontWeight: 700 }}>
                <span>Total</span><span>${total.toFixed(2)}</span>
              </div>
              <button onClick={() => onNav('checkout')} className="btn btn-primary btn-lg btn-block" style={{ marginTop: 16 }}>
                {mode === 'corporate' ? 'Continue to PO workflow' : 'Checkout'} <Icon name="arrow-right" size={16}/>
              </button>
              <div style={{ fontSize: 12, color: 'var(--u-text-2)', marginTop: 12, display:'flex', gap: 6, alignItems:'center', justifyContent:'center' }}>
                <Icon name="lock" size={12}/> {mode === 'corporate' ? 'Routed through Coupa / Zip' : 'Secure checkout'}
              </div>
            </div>
          </aside>
        </div>
      )}
    </div>
  );
};
window.Cart = Cart;
