// CART PAGE — mobile ready
function CartPage({ lang, cart, setCart, setPage, session }) {
  const settings = Store.getSettings();

  const t = lang === 'pt' ? {
    title: 'Carrinho', empty: 'O seu carrinho está vazio.',
    shopNow: 'Ir às Compras', subtotal: 'Subtotal', delivery: 'Entrega',
    free: 'Grátis', total: 'Total', checkout: 'Finalizar Encomenda',
    freeOver: `Portes grátis acima de ${settings.freeDeliveryOver}€`,
    loginRequired: 'Entrar para finalizar'
  } : {
    title: 'Cart', empty: 'Your cart is empty.',
    shopNow: 'Go Shopping', subtotal: 'Subtotal', delivery: 'Delivery',
    free: 'Free', total: 'Total', checkout: 'Checkout',
    freeOver: `Free delivery over €${settings.freeDeliveryOver}`,
    loginRequired: 'Sign in to checkout'
  };

  const updateQty = (id, delta) => {
    const updated = cart.map(item =>
      item.id === id ? { ...item, qty: Math.max(1, item.qty + delta) } : item
    );
    setCart(updated); Store.saveCart(updated);
  };

  const removeItem = (id) => {
    const updated = cart.filter(item => item.id !== id);
    setCart(updated); Store.saveCart(updated);
  };

  const subtotal = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const deliveryFee = subtotal >= settings.freeDeliveryOver ? 0 : settings.deliveryFee;
  const total = subtotal + deliveryFee;

  if (cart.length === 0) return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 20, padding: '90px 20px 40px' }}>
      <div style={{ fontSize: 64 }}>🛒</div>
      <h2 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', margin: 0, textAlign: 'center' }}>{t.empty}</h2>
      <BtnPrimary onClick={() => setPage('shop')}>{t.shopNow}</BtnPrimary>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: 'var(--bg)', paddingTop: 70 }}>
      <div style={{ maxWidth: 1000, margin: '0 auto', padding: 'clamp(24px,5vw,50px) clamp(16px,4vw,40px)' }}>
        <SectionTitle center={false}>{t.title}</SectionTitle>

        {/* Responsive grid: items + summary */}
        <div className="cart-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 28, alignItems: 'start' }}>
          {/* Items list */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {cart.map(item => (
              <div key={item.id} style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: '16px', display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
                <div style={{ flexShrink: 0, borderRadius: 6, overflow: 'hidden' }}>
                  <ProductImage type={item.image} size={72} />
                </div>
                <div style={{ flex: 1, minWidth: 120 }}>
                  <h3 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 16, margin: '0 0 4px' }}>{item.name}</h3>
                  <div style={{ fontFamily: 'Lato, sans-serif', color: 'var(--gold)', fontSize: 15, fontWeight: 700 }}>{item.price.toFixed(2)}€</div>
                </div>
                {/* Qty */}
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <button onClick={() => updateQty(item.id, -1)} style={{ width: 34, height: 34, borderRadius: 5, background: 'rgba(212,153,58,0.12)', border: '1px solid var(--border)', color: 'var(--gold)', fontSize: 20, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>−</button>
                  <span style={{ fontFamily: 'Lato, sans-serif', color: 'var(--cream)', fontSize: 16, minWidth: 22, textAlign: 'center', fontWeight: 700 }}>{item.qty}</span>
                  <button onClick={() => updateQty(item.id, 1)} style={{ width: 34, height: 34, borderRadius: 5, background: 'rgba(212,153,58,0.12)', border: '1px solid var(--border)', color: 'var(--gold)', fontSize: 20, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>+</button>
                </div>
                <div style={{ fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 17, fontWeight: 700, minWidth: 64, textAlign: 'right' }}>
                  {(item.price * item.qty).toFixed(2)}€
                </div>
                <button onClick={() => removeItem(item.id)} style={{ background: 'none', border: 'none', color: 'var(--dim)', cursor: 'pointer', fontSize: 22, lineHeight: 1, padding: 4 }}
                  onMouseEnter={e => e.currentTarget.style.color = '#d04040'}
                  onMouseLeave={e => e.currentTarget.style.color = 'var(--dim)'}>×</button>
              </div>
            ))}
          </div>

          {/* Summary card */}
          <div style={{ background: 'var(--card)', border: '1px solid var(--border)', borderRadius: 10, padding: '24px', position: 'sticky', top: 80 }}>
            <h3 style={{ fontFamily: "'Playfair Display', serif", color: 'var(--cream)', fontSize: 20, margin: '0 0 20px' }}>
              {lang === 'pt' ? 'Resumo' : 'Summary'}
            </h3>
            {[[t.subtotal, `${subtotal.toFixed(2)}€`], [t.delivery, deliveryFee === 0 ? t.free : `${deliveryFee.toFixed(2)}€`]].map(([label, val]) => (
              <div key={label} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10, fontFamily: 'Lato, sans-serif', color: 'var(--muted)', fontSize: 14 }}>
                <span>{label}</span><span style={{ color: 'var(--cream)' }}>{val}</span>
              </div>
            ))}
            <div style={{ borderTop: '1px solid var(--border)', paddingTop: 14, marginTop: 6, display: 'flex', justifyContent: 'space-between', fontFamily: "'Playfair Display', serif", color: 'var(--gold)', fontSize: 22, fontWeight: 700 }}>
              <span>{t.total}</span><span>{total.toFixed(2)}€</span>
            </div>
            <div style={{ fontFamily: 'Lato, sans-serif', color: '#6a8a40', fontSize: 11, marginTop: 8, marginBottom: 18 }}>{t.freeOver}</div>
            {session ? (
              <BtnPrimary onClick={() => setPage('checkout')} full>{t.checkout}</BtnPrimary>
            ) : (
              <BtnPrimary onClick={() => setPage('auth')} full>{t.loginRequired}</BtnPrimary>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartPage });
