// Cart drawer

function CartDrawer({ open, onClose, items, onQty, onRemove }) {
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  return (
    <>
      <div className={`drawer-scrim ${open ? "open" : ""}`} onClick={onClose} />
      <aside className={`drawer ${open ? "open" : ""}`} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Your cart {items.length > 0 && <span style={{ color: "var(--muted)", fontWeight: 400 }}>({items.length})</span>}</h3>
          <button className="icon-btn" onClick={onClose} aria-label="Close cart"><IconX size={16} /></button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="drawer-empty">
              <IconCart size={36} />
              <div>
                <div style={{ color: "var(--ink)", fontWeight: 500, marginBottom: 4 }}>Your cart is empty</div>
                Add Sleep Truffles to get started.
              </div>
              <button className="cta-add" style={{ height: 44, padding: "0 24px" }} onClick={onClose}>
                Continue shopping
              </button>
            </div>
          ) : items.map((it, i) => (
            <div key={i} className="cart-item">
              <div className="cart-item-img" />
              <div>
                <h6>{it.product}</h6>
                <div className="meta">{it.variant} · {it.pack}</div>
                <div className="meta" style={{ color: "var(--ink-2)", marginTop: 2 }}>{it.planLabel}</div>
                <div className="cart-item-qty">
                  <button onClick={() => onQty(i, it.qty - 1)} aria-label="Decrease">−</button>
                  <span className="v">{it.qty}</span>
                  <button onClick={() => onQty(i, it.qty + 1)} aria-label="Increase">+</button>
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                <div className="price">${it.price * it.qty}</div>
                <button className="remove" onClick={() => onRemove(i)}>Remove</button>
              </div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <div className="drawer-totals">
              <span>Subtotal</span>
              <span className="total">${subtotal}</span>
            </div>
            <button className="drawer-cta">Checkout · ${subtotal}</button>
            <div className="drawer-note">Free shipping on orders over $99 · 30-day money-back guarantee</div>
          </div>
        )}
      </aside>
    </>
  );
}

function Toast({ show, msg }) {
  return (
    <div className={`toast ${show ? "show" : ""}`}>
      <IconCheck size={14} /> {msg}
    </div>
  );
}

Object.assign(window, { CartDrawer, Toast });
