/* ASCX — Landing: Drop 01 commerce (pre-order apparel).
   Cart store + Drop 01 grid + product modal (gallery + size) + cart drawer.
   Reads DS bundle + window.LV. Exposes window.LVD and window.ASCXCart. text/babel. */
(function () {
const NS = window.ASCXDesignSystem_77a68b;
const { Button, Eyebrow, Badge } = NS;
const LV = window.LV;
const Wrap = ({ children, style }) => <div className="lp-wrap" style={style}>{children}</div>;

const money = (n) => '$' + (Number.isInteger(n) ? n : n.toFixed(2));

/* ---------------- Cart store (shared across components) ---------------- */
const CART_KEY = 'ascx_preorder_cart_v1';
const cart = {
  items: {},          // key -> { key, kind:'box'|'merch', id, name, size, price, qty }
  drawerOpen: false,
  reserved: false,
  listeners: new Set(),
  /* Product ids that have been renamed. A cart saved under the old id would
     otherwise linger with a stale key and submit the wrong sku at checkout. */
  legacyIds: { crew: 'hood01' },
  load() {
    try {
      const s = JSON.parse(localStorage.getItem(CART_KEY));
      if (!s || typeof s !== 'object') return;
      let changed = false;
      Object.keys(s).forEach((key) => {
        const it = s[key];
        const next = it && this.legacyIds[it.id];
        if (!next) return;
        delete s[key];
        it.id = next;
        it.key = next + (it.size ? '|' + it.size : '');
        s[it.key] = it;
        changed = true;
      });
      this.items = s;
      if (changed) this.save();
    } catch (e) {}
  },
  save() { try { localStorage.setItem(CART_KEY, JSON.stringify(this.items)); } catch (e) {} },
  subscribe(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); },
  emit() { this.save(); this.listeners.forEach((fn) => fn()); },
  add(item) {
    const key = item.kind === 'box' ? 'box' : item.id + (item.size ? '|' + item.size : '');
    if (this.items[key]) this.items[key].qty += (item.qty || 1);
    else this.items[key] = Object.assign({}, item, { key, qty: item.qty || 1 });
    this.reserved = false;
    this.emit();
  },
  remove(key) { delete this.items[key]; this.emit(); },
  setQty(key, q) { const it = this.items[key]; if (!it) return; if (q <= 0) delete this.items[key]; else it.qty = q; this.reserved = false; this.emit(); },
  list() { return Object.keys(this.items).map((k) => this.items[k]); },
  /* what the same cart would cost at full price, and the difference — used for
     the struck-through figures and the "you save" line in the drawer, the
     checkout summary, and the submitted order. Items without a `list` simply
     count at their own price, so they contribute nothing to the saving. */
  listSubtotal() { return this.list().reduce((s, i) => s + (i.list || i.price) * i.qty, 0); },
  savings() { return Math.max(0, this.listSubtotal() - this.subtotal()); },
  hasBox() { return !!this.items['box']; },
  merchCount() { return this.list().filter((i) => i.kind === 'merch').reduce((s, i) => s + i.qty, 0); },
  count() { return this.list().reduce((s, i) => s + i.qty, 0); },
  subtotal() { return this.list().reduce((s, i) => s + i.price * i.qty, 0); },
  freeShip() { return this.hasBox() && this.merchCount() > 0; },
  shipFee() { return this.count() === 0 ? 0 : (this.freeShip() ? 0 : LV.SHIP.fee); },
  total() { return this.subtotal() + this.shipFee(); },
  openDrawer() { this.drawerOpen = true; this.emit(); },
  closeDrawer() { this.drawerOpen = false; this.emit(); },
  reserve() { this.reserved = true; this.emit(); },
  /* Called by the checkout sheet once an order is accepted. */
  complete() { this.items = {}; this.reserved = true; this.emit(); },
};
cart.load();
window.ASCXCart = cart;

function useCart() {
  const [, force] = React.useReducer((x) => x + 1, 0);
  React.useEffect(() => cart.subscribe(force), []);
  return cart;
}

/* ---------------- Product gallery (fillable image-slots + angle selector) ---------------- */
function Gallery({ p }) {
  const [sel, setSel] = React.useState(0);
  React.useEffect(() => { setSel(0); }, [p.id]);
  return (
    <div className="pm-gallery">
      <div className="pm-main">
        {p.angles.map((a, i) => (
          <div key={a} className="pm-slot" style={{ display: i === sel ? 'block' : 'none' }}>
            <image-slot id={'drop-' + p.id + '-' + (i + 1)} shape="rect" {...(p.photos && p.photos[i] ? { src: p.photos[i] } : {})} placeholder={'Drop the ' + a.toLowerCase() + ' photo'}></image-slot>
          </div>
        ))}
        <div className="pm-tag">{p.tag}</div>
      </div>
      <div className="pm-thumbs">
        {p.angles.map((a, i) => (
          <button key={a} type="button" className={'pm-thumb' + (i === sel ? ' on' : '')} onClick={() => setSel(i)}>
            <span className="pm-thumb-n">{i + 1}</span>
            <span className="pm-thumb-label">{a}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

/* ---------------- Product modal ---------------- */
function ProductModal({ p, onClose }) {
  const c = useCart();
  const [size, setSize] = React.useState(null);
  React.useEffect(() => { setSize(null); }, [p && p.id]);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, []);
  if (!p) return null;
  const canAdd = p.oneSize || !!size;
  const addToCart = () => {
    if (!canAdd) return;
    c.add({ kind: 'merch', id: p.id, name: p.name, size: p.oneSize ? 'OS' : size, price: p.price, list: p.list });
    onClose();
    c.openDrawer();
  };
  return (
    <div className="pm-overlay" onMouseDown={onClose}>
      <div className="pm-panel" onMouseDown={(e) => e.stopPropagation()}>
        <button className="pm-close" type="button" onClick={onClose} aria-label="Close">×</button>
        <div className="pm-body">
          <Gallery p={p} />
          <div className="pm-info">
            <div className="pm-ey">Drop 01 · {p.tag}</div>
            <div className="pm-name">{p.name}</div>
            <div className="pm-price">{money(p.price)}{p.list && <span className="pm-list">{money(p.list)}</span>}{p.list && <span className="pm-save">Save {money(p.list - p.price)}</span>}</div>
            <p className="pm-blurb">{p.blurb}</p>
            <div className="pm-size-head">
              <span>{p.oneSize ? 'Size' : 'Select size'}</span>
              {!p.oneSize && !size && <span className="pm-size-hint">Required</span>}
            </div>
            {p.oneSize ? (
              <div className="pm-onesize">One size · adjustable snap</div>
            ) : (
              <div className="pm-sizes">
                {p.sizes.map((s) => (
                  <button key={s} type="button" className={'pm-size' + (size === s ? ' on' : '')} onClick={() => setSize(s)}>{s}</button>
                ))}
              </div>
            )}
            <button className={'pm-add' + (canAdd ? '' : ' off')} type="button" onClick={addToCart}>
              {canAdd ? 'Add to pre-order · ' + money(p.price) : 'Select a size'}
            </button>
            <div className="pm-ship">
              <span className="pm-ship-dot" />
              Ships with your box before the holidays. {LV.SHIP.freeCopy}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ---------------- Drop 01 section ---------------- */
function Drop01() {
  const [open, setOpen] = React.useState(null); // product id
  const c = useCart();
  const prod = open ? LV.DROP.filter((p) => p.id === open)[0] : null;
  return (
    <section id="drop" className="lp-section" style={{ background: 'var(--surface-card)' }}>
      <Wrap>
        <div className="reveal drop-head">
          <div style={{ maxWidth: 640 }}>
            <Eyebrow>Drop 01</Eyebrow>
            <h2 className="lp-h2">Pre-order the <span className="red">first drop.</span></h2>
            <p className="lp-lead sec-lead">
              <span className="lp-strong">Drop 01</span> is our first apparel collection, open to pre-order now, separate from the earned Marks gear. Add any piece to your box and it ships together, before the holidays.
            </p>
          </div>
          <div className="drop-ship reveal">
            <div className="drop-ship-k">Free shipping</div>
            <div className="drop-ship-d">Pre-order the box + any Drop 01 piece and shipping is on us.</div>
          </div>
        </div>

        <div className="drop-grid reveal">
          {LV.DROP.map((p) => (
            <div key={p.id} className="drop-card" role="button" tabIndex={0}
              onClick={() => setOpen(p.id)}
              onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(p.id); } }}>
              <div className="dc-media">
                <image-slot id={'drop-' + p.id + '-1'} shape="rect" {...(p.photos && p.photos[0] ? { src: p.photos[0] } : {})} placeholder={'Drop the ' + p.name.toLowerCase() + ' photo'}></image-slot>
                <span className="dc-tag">{p.tag}</span>
                <span className="dc-view">View</span>
              </div>
              <div className="dc-info">
                <div className="dc-name">{p.name}</div>
                <div className="dc-meta">
                  <span className="dc-price">{money(p.price)}{p.list && <span className="dc-list">{money(p.list)}</span>}</span>
                  <span className="dc-pre">Pre-order</span>
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="reveal drop-foot">
          <Button variant="default" size="md" onClick={() => c.openDrawer()}>View pre-order cart</Button>
        </div>
      </Wrap>
      {prod && <ProductModal p={prod} onClose={() => setOpen(null)} />}
    </section>
  );
}

/* ---------------- Cart button + drawer (mounted at app root) ---------------- */
function nudge(c) {
  if (c.count() === 0) return null;
  if (c.freeShip()) return { ok: true, t: 'Free shipping unlocked. Box + Drop 01 ship together.' };
  /* `go` turns the nudge into a button that jumps to that section */
  if (c.hasBox() && c.merchCount() === 0) return { ok: false, t: 'Add any Drop 01 piece for free shipping.', go: 'drop' };
  if (!c.hasBox()) return { ok: false, t: 'Add the box to start Jan 1 with Cohort 001 and unlock free shipping.' };
  return null;
}

function CartButton() {
  const c = useCart();
  const n = c.count();
  const open = c.drawerOpen;
  const ng = nudge(c);
  const items = c.list();
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') c.closeDrawer(); };
    if (open) document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [open]);
  const goTo = (id) => { c.closeDrawer(); const el = document.getElementById(id); if (el) el.scrollIntoView({ behavior: 'smooth' }); };
  const goPricing = () => goTo('pricing');
  /* Adds the box right here rather than scrolling to pricing and asking for a
     second click. The drawer already names the price, so bouncing someone back
     to the page to press an identical button is a step that buys nothing. */
  const addBox = () => window.ASCXCart.add({
    kind: 'box', id: LV.BOX.id, name: LV.BOX.name, sub: LV.BOX.sub,
    price: LV.BOX.price, list: LV.BOX.list,
  });
  return (
    <React.Fragment>
      <button className="cart-fab" type="button" onClick={() => (open ? c.closeDrawer() : c.openDrawer())} aria-label="Pre-order cart">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="square"><path d="M4 5h2l1.5 11h10L20 8H7" /><circle cx="9" cy="20" r="1.2" fill="currentColor" stroke="none" /><circle cx="18" cy="20" r="1.2" fill="currentColor" stroke="none" /></svg>
        {n > 0 && <span className="cart-count">{n}</span>}
      </button>

      {open && <div className="cart-scrim" onClick={() => c.closeDrawer()} />}
      <aside className={'cart-drawer' + (open ? ' open' : '')} aria-hidden={!open}>
        <div className="cart-top">
          <div>
            <div className="cart-title">Pre-order cart</div>
            <div className="cart-sub">{LV.LAUNCH.cohort} · {LV.LAUNCH.shipWindow}</div>
          </div>
          <button className="cart-x" type="button" onClick={() => c.closeDrawer()} aria-label="Close">×</button>
        </div>

        {c.reserved ? (
          <div className="cart-done">
            <div className="cart-done-mark"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinecap="square"><path d="M4 12l5 5L20 6" /></svg></div>
            <div className="cart-done-t">Pre-order reserved</div>
            <p className="cart-done-d">Your place in {LV.LAUNCH.cohort} is locked. Watch your email: the confirmation carries the link that sets up your account. Your box ships before the holidays, and we begin {LV.LAUNCH.startLong}.</p>
            <Button variant="default" fullWidth onClick={() => c.closeDrawer()}>Keep exploring</Button>
          </div>
        ) : items.length === 0 ? (
          <div className="cart-empty">
            <p>Your pre-order cart is empty.</p>
            <p className="cart-empty-d">Reserve the box to lock your place in {LV.LAUNCH.cohort}, then add Drop 01 gear for free shipping.</p>
            <Button variant="primary" fullWidth onClick={addBox}>Pre-order the box · {money(LV.BOX.price)}</Button>
          </div>
        ) : (
          <React.Fragment>
            <div className="cart-items">
              {items.map((it) => (
                <div key={it.key} className="cart-item">
                  <div className="ci-main">
                    <div className="ci-name">{it.name}{it.kind === 'box' && <span className="ci-badge">Box</span>}</div>
                    <div className="ci-meta">{it.kind === 'box' ? it.sub || 'Box + platform' : (it.size === 'OS' ? 'One size' : 'Size ' + it.size)}</div>
                    <div className="ci-qty">
                      <button type="button" onClick={() => c.setQty(it.key, it.qty - 1)} aria-label="Decrease">–</button>
                      <span>{it.qty}</span>
                      <button type="button" onClick={() => c.setQty(it.key, it.qty + 1)} aria-label="Increase">+</button>
                      <button type="button" className="ci-remove" onClick={() => c.remove(it.key)}>Remove</button>
                    </div>
                  </div>
                  <div className="ci-price">
                    {money(it.price * it.qty)}
                    {it.list > it.price && <span className="ci-list">{money(it.list * it.qty)}</span>}
                  </div>
                </div>
              ))}
            </div>

            {ng && (ng.go ? (
              <button type="button" className={'cart-nudge cart-nudge-btn' + (ng.ok ? ' ok' : '')} onClick={() => goTo(ng.go)}>
                <span>{ng.t}</span><span className="cart-nudge-go" aria-hidden="true">&rarr;</span>
              </button>
            ) : (
              <div className={'cart-nudge' + (ng.ok ? ' ok' : '')}>{ng.t}</div>
            ))}

            {/* full price struck first, the saving in red, then what you
                actually pay in white — subtotal, shipping, total */}
            <div className="cart-totals">
              {c.savings() > 0 && (
                <React.Fragment>
                  <div className="ct-row ct-was"><span>Full price</span><span>{money(c.listSubtotal())}</span></div>
                  <div className="ct-row ct-save"><span>You save</span><span>&ndash;{money(c.savings())}</span></div>
                </React.Fragment>
              )}
              <div className="ct-row ct-pay"><span>Subtotal</span><span>{money(c.subtotal())}</span></div>
              <div className="ct-row"><span>Shipping</span><span>{c.shipFee() === 0 ? (c.freeShip() ? 'Free' : '—') : money(c.shipFee())}</span></div>
              <div className="ct-row ct-total"><span>Total</span><span>{money(c.total())}</span></div>
            </div>
            {!c.hasBox() && (
              <button type="button" className="cart-addbox" onClick={goPricing}>+ Add the Full Experience box · $99</button>
            )}
            <div className="cart-foot">
              <Button variant="primary" fullWidth onClick={() => { c.closeDrawer(); if (window.ASCXFlows) window.ASCXFlows.openCheckout(); }}>Pay and reserve your place</Button>
              <div className="cart-fine">Payment is taken securely by Stripe.</div>
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

window.LVD = { Drop01, CartButton };
})();
