// ============================================================
// CartDrawer — right-side drawer. Lines, subtotal, CTA to
// checkout. Includes free-ship progress.
// ============================================================

function JmCartDrawer({ open, items, lang, onClose, onRemove, onUpdateQty, onCheckout, onGoShop }) {
  const t = JM.t[lang];
  React.useEffect(() => { if (window.lucide) lucide.createIcons(); });

  const subtotal = items.reduce((s, i) => s + i.price * (i.qty || 1), 0);
  const freeShipThreshold = JM.shop.freeShipFrom;
  const shipFee = JM.shop.shipFee;
  const remaining = Math.max(0, freeShipThreshold - subtotal);
  const progress = Math.min(100, (subtotal / freeShipThreshold) * 100);
  const itemCount = items.reduce((s, i) => s + (i.qty || 1), 0);

  return (
    <>
      <div className={`jm-scrim ${open ? 'is-open' : ''}`} onClick={onClose}></div>
      <aside className={`jm-cart-drawer ${open ? 'is-open' : ''}`} aria-hidden={!open} data-screen-label="Cart drawer">
        <div className="jm-cart-drawer__top">
          <div>
            <div className="jm-label">{t['cart.title']}</div>
            <div className="jm-small" style={{ marginTop: 4 }}>
              {itemCount > 0 ? `${itemCount} ${t['cart.item']}` : ''}
            </div>
          </div>
          <button className="jm-icon-btn" onClick={onClose} aria-label="Đóng">
            <i data-lucide="x" className="jm-icon"></i>
          </button>
        </div>

        {items.length === 0 ? (
          <div className="jm-cart-empty">
            <i data-lucide="shopping-bag" className="jm-icon" style={{ width: 36, height: 36, color: 'var(--jm-muted)' }}></i>
            <p className="jm-body" style={{ margin: '20px 0 24px', maxWidth: 260 }}>{t['cart.empty']}</p>
            <button className="jm-btn jm-btn-secondary" onClick={() => { onClose(); onGoShop && onGoShop(); }}>
              {t['cart.emptyCta']}
            </button>
          </div>
        ) : (
          <>
            {/* Free-ship progress */}
            <div className="jm-cart-ship">
              {remaining > 0 ? (
                <p className="jm-small" style={{ margin: 0 }}>
                  {lang === 'vi'
                    ? <>Mua thêm <strong style={{ color: 'var(--jm-cam-dat)' }}>{JM.formatPrice(remaining)}</strong> để được miễn phí vận chuyển.</>
                    : <>Add <strong style={{ color: 'var(--jm-cam-dat)' }}>{JM.formatPrice(remaining)}</strong> more for free shipping.</>}
                </p>
              ) : (
                <p className="jm-small" style={{ margin: 0, color: 'var(--jm-cam-dat)' }}>
                  <i data-lucide="check" className="jm-icon jm-icon-sm" style={{ marginRight: 6 }}></i>
                  {lang === 'vi' ? 'Đơn hàng được miễn phí vận chuyển.' : 'Free shipping unlocked.'}
                </p>
              )}
              <div className="jm-cart-ship__bar"><div className="jm-cart-ship__fill" style={{ width: `${progress}%` }}></div></div>
            </div>

            <div className="jm-cart-drawer__body">
              {items.map((it, idx) => (
                <div className="jm-cart-line" key={idx}>
                  <div className="jm-cart-line__img">
                    <JmProductImage src={it.image || (it.images && it.images[0])} glyph={it.glyph} material={it.material} ratio="1/1"/>
                  </div>
                  <div className="jm-cart-line__info">
                    <span className="jm-title">{it.name}</span>
                    <span className="jm-small">
                      {it.variantLabel ? `${it.variantLabel} · ${it.code}` : (() => {
                        const m = JM.materials.find(mm => mm.id === it.material);
                        return (m ? (lang === 'vi' ? m.vi : m.en) : '') + (it.size && it.size !== 'std' ? ` · ${it.size}` : '');
                      })()}
                    </span>
                    <div className="jm-cart-line__bottom">
                      <div className="jm-qty jm-qty--sm">
                        <button onClick={() => onUpdateQty(idx, Math.max(1, (it.qty || 1) - 1))} aria-label="-"><i data-lucide="minus" className="jm-icon jm-icon-sm"></i></button>
                        <span className="jm-qty__n">{it.qty || 1}</span>
                        <button onClick={() => onUpdateQty(idx, (it.qty || 1) + 1)} aria-label="+"><i data-lucide="plus" className="jm-icon jm-icon-sm"></i></button>
                      </div>
                      <div className="jm-cart-line__price">
                        <strong>{JM.formatPrice(it.price * (it.qty || 1))}</strong>
                        <button className="jm-cart-line__remove" onClick={() => onRemove(idx)} aria-label="Xoá">
                          {lang === 'vi' ? 'Xoá' : 'Remove'}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div className="jm-cart-drawer__foot">
              <div className="jm-cart-drawer__row">
                <span className="jm-small">{t['cart.subtotal']}</span>
                <span className="jm-title">{JM.formatPrice(subtotal)}</span>
              </div>
              <div className="jm-cart-drawer__row" style={{ marginTop: 6 }}>
                <span className="jm-small">{t['cart.shipping']}</span>
                <span className="jm-small">{remaining > 0 ? JM.formatPrice(shipFee) : t['cart.shippingFree']}</span>
              </div>
              <hr className="jm-divider" style={{ margin: '16px 0' }}/>
              <div className="jm-cart-drawer__row">
                <span className="jm-label">{t['cart.total']}</span>
                <span className="jm-h2">{JM.formatPrice(subtotal + (remaining > 0 ? shipFee : 0))}</span>
              </div>
              <button className="jm-btn jm-btn-primary jm-btn-block" style={{ marginTop: 18 }} onClick={onCheckout}>
                {t['cta.checkout']}
              </button>
              <p className="jm-small" style={{ textAlign: 'center', marginTop: 12, color: 'var(--jm-muted)' }}>
                {lang === 'vi' ? 'Đổi mới trong 15 ngày' : '15-day exchange'}
              </p>
            </div>
          </>
        )}
      </aside>
    </>
  );
}

window.JmCartDrawer = JmCartDrawer;
