const { useState, useEffect, useMemo, useRef } = React;

function CartDrawer({ open, onClose, cart, setCart, onCheckout }) {
  const products = window.PRODUCTS;
  const total = cart.reduce((s, it) => s + it.qty * it.unitPrice, 0);
  const count = cart.reduce((s, it) => s + it.qty, 0);

  const updateQty = (idx, q) => {
    const next = [...cart];
    if (q <= 0) next.splice(idx, 1);
    else next[idx] = { ...next[idx], qty: q };
    setCart(next);
  };
  const remove = (idx) => {
    const next = [...cart];
    next.splice(idx, 1);
    setCart(next);
  };

  return (
    <>
      <div className={`cart-backdrop ${open ? 'open' : ''}`} onClick={onClose} />
      <aside className={`cart-drawer ${open ? 'open' : ''}`}>
        <header className="cart-head">
          <div>
            <div className="cart-eyebrow">YOUR CART</div>
            <h2>カート <span className="cart-count">{count}点</span></h2>
          </div>
          <button className="icon-btn" onClick={onClose} aria-label="閉じる">✕</button>
        </header>

        {cart.length === 0 ? (
          <div className="cart-empty">
            <div className="empty-mark">
              <svg viewBox="0 0 60 60" width="72" height="72">
                <circle cx="30" cy="30" r="28" fill="none" stroke="currentColor" strokeWidth="1.2" opacity="0.3"/>
                <path d="M18 22 L42 22 L39 44 L21 44 Z" fill="none" stroke="currentColor" strokeWidth="1.5"/>
                <path d="M23 22 Q23 15 30 15 Q37 15 37 22" fill="none" stroke="currentColor" strokeWidth="1.5"/>
              </svg>
            </div>
            <p>カートは空です</p>
            <span className="muted-small">お気に入りの商品を選んでみてください</span>
          </div>
        ) : (
          <>
            <div className="cart-list">
              {cart.map((it, idx) => {
                const p = products.find(x => x.id === it.productId);
                return (
                  <div className="cart-item" key={idx}>
                    <div className="ci-thumb" style={{ background: p.color === '#FFFFFF' ? '#F7F3EB' : 'transparent' }}>
                      <ProductVisual product={p} size={84} colorKey={it.color} />
                    </div>
                    <div className="ci-body">
                      <div className="ci-name">{p.code} {p.name}</div>
                      <div className="ci-meta">
                        {window.VARIANT_LABELS[it.variant] && p.variants.length > 1 && (
                          <span>{window.VARIANT_LABELS[it.variant]}</span>
                        )}
                        {it.color && <span>{window.VARIANT_LABELS[it.color]}</span>}
                        <span>
                          サイズ {it.size}
                          {(() => {
                            const KID = ['100','110','120','130','140','150','160'];
                            const ADULT = ['S','M','L','XL','XXL','XXXL'];
                            if (KID.includes(it.size)) return <span className="size-age-tag tag tag-kid">キッズ</span>;
                            if (ADULT.includes(it.size)) return <span className="size-age-tag tag tag-adult">大人</span>;
                            return null;
                          })()}
                        </span>
                      </div>
                      <div className="ci-foot">
                        <div className="qty-stepper small">
                          <button onClick={() => updateQty(idx, it.qty - 1)}>−</button>
                          <span>{it.qty}</span>
                          <button onClick={() => updateQty(idx, it.qty + 1)}>+</button>
                        </div>
                        <div className="ci-price">¥{(it.qty * it.unitPrice).toLocaleString()}</div>
                        <button className="ci-remove" onClick={() => remove(idx)}>削除</button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            <footer className="cart-foot">
              <div className="cart-totals">
                <div className="total-row"><span>点数</span><span>{count}点</span></div>
                <div className="total-row big"><span>合計</span><span>¥{total.toLocaleString()}</span></div>
              </div>
              <button className="checkout-btn" onClick={onCheckout}>
                ご注文手続きへ進む →
              </button>
              <div className="cart-note">お支払いは商品お受け取り時に現金またはPayPayでお願いします</div>
            </footer>
          </>
        )}
      </aside>
    </>
  );
}

window.CartDrawer = CartDrawer;
