// cart.jsx — cart.html (buy-mode line items only; partner/provider never enter a cart)

function initialCartIds() {
  const p = new URLSearchParams(location.search);
  const add = p.get("add");
  const seed = ["agent-context-engine", "skill-deep-research"];
  if (add && !seed.includes(add) && getItem(add) && getItem(add).mode === "buy") seed.push(add);
  return seed;
}

function CartLine({ item, onRemove, onSave }) {
  return (
    <article className="cart-line glass">
      <div className="cart-line-thumb"><Icon name="box" size={22} /></div>
      <div className="cart-line-body">
        <div className="label-overline fg-muted">{CATEGORIES.find((c) => c.id === item.category)?.label}</div>
        <h4 className="h4" style={{ margin: "2px 0" }}>{item.name}</h4>
        <p className="body-sm fg-muted">{item.unitPrice}</p>
      </div>
      <div className="cart-line-actions">
        <div className="price-main">${item.price}</div>
        <button type="button" className="cart-link-btn" onClick={onSave}>Save for later</button>
        <button type="button" className="cart-link-btn" onClick={onRemove}>Remove</button>
      </div>
    </article>
  );
}

function CartPage() {
  const [ids, setIds] = React.useState(initialCartIds);
  const [savedIds, setSavedIds] = React.useState([]);

  const items = ids.map(getItem).filter(Boolean);
  const saved = savedIds.map(getItem).filter(Boolean);

  const subtotal = items.reduce((s, i) => s + (i.price || 0), 0);
  const tax = Math.round(subtotal * 0.08 * 100) / 100;
  const fees = items.length ? 1.5 : 0;
  const total = Math.round((subtotal + tax + fees) * 100) / 100;

  const remove = (id) => setIds((s) => s.filter((x) => x !== id));
  const save = (id) => { setSavedIds((s) => [...s, id]); remove(id); };
  const restore = (id) => { setIds((s) => [...s, id]); setSavedIds((s) => s.filter((x) => x !== id)); };

  return (
    <Section id="cart">
      <span className="topic label-overline">Your cart</span>
      <h1 className="h1">Cart.</h1>
      <p className="lead" style={{ marginBottom: 20 }}>
        Buy-mode items only — partner and provider listings route through their own handoff, never a cart.
      </p>

      {items.length === 0 ? (
        <EmptyState
          title="Your cart is empty."
          message="Nothing buy-mode saved yet. Browse the catalog to add something."
          actionLabel="Browse catalog"
          actionHref="plp.html"
        />
      ) : (
        <div className="cart-layout">
          <div className="cart-list">
            {items.map((i) => (
              <CartLine key={i.id} item={i} onRemove={() => remove(i.id)} onSave={() => save(i.id)} />
            ))}

            {saved.length > 0 && (
              <div className="saved-later-list">
                <div className="label-overline fg-muted" style={{ marginBottom: 10 }}>Saved for later</div>
                <div className="cart-list">
                  {saved.map((i) => (
                    <article key={i.id} className="cart-line glass">
                      <div className="cart-line-thumb"><Icon name="heart" size={20} /></div>
                      <div className="cart-line-body">
                        <h4 className="h4" style={{ margin: "2px 0" }}>{i.name}</h4>
                        <p className="body-sm fg-muted">{i.unitPrice}</p>
                      </div>
                      <div className="cart-line-actions">
                        <button type="button" className="cart-link-btn" onClick={() => restore(i.id)}>Move to cart</button>
                      </div>
                    </article>
                  ))}
                </div>
              </div>
            )}
          </div>

          <aside className="order-summary glass">
            <div className="label-overline fg-muted" style={{ marginBottom: 8 }}>Order summary</div>
            <div className="summary-row body-sm"><span>Subtotal</span><span>${subtotal.toFixed(2)}</span></div>
            <div className="summary-row body-sm"><span>Est. tax</span><span>${tax.toFixed(2)}</span></div>
            <div className="summary-row body-sm"><span>Platform fee</span><span>${fees.toFixed(2)}</span></div>
            <div className="summary-row total"><span>Total</span><span>${total.toFixed(2)}</span></div>
            <a className="btn btn-primary" href="#" style={{ width: "100%", marginTop: 14 }} onClick={(e) => e.preventDefault()}>Checkout</a>
            <div className="guest-note body-sm">
              <Icon name="user-check" size={15} />
              <span>Guest checkout — an account is never required to buy.</span>
            </div>
            <ReturnsSummary item={{ returns: "14-day return on every buy-mode item in this cart, no questions asked." }} />
          </aside>
        </div>
      )}
    </Section>
  );
}

window.__PAGE__ = CartPage;
