// PiBead — Cart drawer
//
// Global slide-in cart, summons via window event 'pibead:open-cart'.
// Items shape:
//   { id, type, title, patternId?, previewImageUrl?, brand?, gridSize?,
//     totalBeads?, colorCount?, beadCounts?, estimatedPrice, qty }

const { useState, useEffect, useMemo } = React;

function CartDrawer({ items, setItems, open, setOpen }) {
  useEffect(() => {
    const handler = () => setOpen(true);
    window.addEventListener('pibead:open-cart', handler);
    return () => window.removeEventListener('pibead:open-cart', handler);
  }, []);

  useEffect(() => {
    const onEsc = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', onEsc);
    return () => window.removeEventListener('keydown', onEsc);
  }, []);

  const total = items.reduce((s, it) => s + (it.estimatedPrice || it.price || 0) * (it.qty || 1), 0);
  const shippingThreshold = 40;
  const remaining = Math.max(0, shippingThreshold - total);
  const progress = Math.min(100, (total / shippingThreshold) * 100);

  function updateQty(idx, delta) {
    setItems(items => items.map((it, i) => i === idx ? { ...it, qty: Math.max(1, (it.qty || 1) + delta) } : it));
  }
  function remove(idx) {
    setItems(items => items.filter((_, i) => i !== idx));
  }

  return (
    <>
      {/* Backdrop */}
      <div
        style={{
          position: 'fixed', inset: 0, zIndex: 80,
          background: 'rgba(17,17,17,0.45)',
          backdropFilter: 'blur(4px)',
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity .25s ease',
        }}
        onClick={() => setOpen(false)}
      />
      {/* Drawer */}
      <aside
        style={{
          position: 'fixed', top: 0, right: 0, bottom: 0, zIndex: 90,
          width: 'min(440px, 100vw)',
          background: 'var(--lt2)',
          borderLeft: '3px solid var(--ink)',
          boxShadow: '-8px 0 0 0 var(--v)',
          transform: open ? 'translateX(0)' : 'translateX(110%)',
          transition: 'transform .35s cubic-bezier(.2,.7,.2,1)',
          display: 'flex', flexDirection: 'column',
        }}
        aria-hidden={!open}
      >
        {/* Header */}
        <div className="flex items-center justify-between" style={{ padding: '18px 20px', borderBottom: '3px solid var(--ink)' }}>
          <div>
            <div className="px" style={{ fontSize: 14, color: 'var(--ink)' }}>YOUR CART</div>
            <div className="px" style={{ fontSize: 8, color: 'var(--ink2)', marginTop: 8 }}>{items.length} {items.length === 1 ? 'ITEM' : 'ITEMS'}</div>
          </div>
          <button onClick={() => setOpen(false)} style={{ width: 38, height: 38, border: '3px solid var(--ink)', background: 'var(--lt2)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon.Close size={16}/></button>
        </div>

        {/* Free-ship progress */}
        <div style={{ padding: '14px 20px', borderBottom: '3px solid var(--lt3)' }}>
          {remaining > 0 ? (
            <div className="px" style={{ fontSize: 8, color: 'var(--ink2)', lineHeight: 1.6 }}>
              ADD <span style={{ color: 'var(--v)' }}>${remaining.toFixed(2)}</span> FOR FREE SHIP
            </div>
          ) : (
            <div className="px" style={{ fontSize: 8, color: 'var(--ink)', display: 'flex', alignItems: 'center', gap: 6 }}>
              ★ FREE SHIPPING UNLOCKED
            </div>
          )}
          <div style={{ marginTop: 10, height: 12, background: 'var(--lt3)', border: '2px solid var(--ink)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${progress}%`, background: 'repeating-linear-gradient(90deg, var(--ylw) 0 6px, #FFDD6B 6px 12px)', transition: 'width .4s ease' }}/>
          </div>
        </div>

        {/* Items */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '14px 16px' }}>
          {items.length === 0 ? (
            <EmptyCart/>
          ) : (
            items.map((it, i) => <CartItemCard key={it.id + ':' + i} item={it} onInc={() => updateQty(i, +1)} onDec={() => updateQty(i, -1)} onRemove={() => remove(i)}/>)
          )}
        </div>

        {/* Footer */}
        {items.length > 0 && (
          <div style={{ padding: 18, borderTop: '3px solid var(--ink)', background: 'var(--lt)' }}>
            <div className="flex items-center justify-between" style={{ marginBottom: 12 }}>
              <span className="px" style={{ fontSize: 9, color: 'var(--ink2)' }}>SUBTOTAL</span>
              <span className="px" style={{ fontSize: 16, color: 'var(--ink)' }}>${total.toFixed(2)}</span>
            </div>
            <button className="pbtn pbtn-ylw" style={{ width: '100%' }}>
              <window.Icon.Bolt size={14}/> CHECKOUT
            </button>
            <div className="px" style={{ fontSize: 7, color: 'var(--ink2)', textAlign: 'center', marginTop: 12, lineHeight: 1.8 }}>
              SHOP PAY · APPLE PAY · AFFIRM
            </div>
          </div>
        )}
      </aside>
    </>
  );
}
window.CartDrawer = CartDrawer;

function EmptyCart() {
  return (
    <div className="flex flex-col items-center justify-center text-center" style={{ padding: '60px 24px' }}>
      <div style={{ width: 72, height: 72, background: 'var(--bk)', border: '3px solid var(--v)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--v)' }}>
        <window.Icon.Cart size={32}/>
      </div>
      <div className="px mt-5" style={{ fontSize: 12, color: 'var(--ink)', marginTop: 20 }}>CART EMPTY</div>
      <p className="aw-disp" style={{ marginTop: 12, fontSize: 14, color: 'var(--ink2)', maxWidth: 260 }}>
        Pick a mode and start a bead build.
      </p>
      <a href="#/create" onClick={() => window.dispatchEvent(new CustomEvent('pibead:close-cart'))} className="pbtn pbtn-ylw pbtn-sm" style={{ marginTop: 20 }}>
        <window.Icon.Sparkle size={14}/> DESIGN A KIT
      </a>
    </div>
  );
}

function CartItemCard({ item, onInc, onDec, onRemove }) {
  const isCustom = item.type === 'custom-kit';
  return (
    <div style={{ padding: 12, marginBottom: 10, display: 'flex', gap: 12, background: 'var(--lt2)', border: '3px solid var(--ink)', boxShadow: '4px 4px 0 var(--v)' }}>
      {/* Preview */}
      <div style={{ width: 84, height: 84, flexShrink: 0, overflow: 'hidden', border: '3px solid var(--ink)', background: '#05050F', display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', color: 'var(--v)' }}>
        {item.previewImageUrl ? (
          <img src={item.previewImageUrl} style={{ width: '100%', height: '100%', objectFit: 'cover', imageRendering: 'pixelated' }}/>
        ) : (
          <window.Icon.Layers size={26}/>
        )}
        {isCustom && (
          <span className="px" style={{ position: 'absolute', top: 3, left: 3, background: 'var(--ylw)', color: 'var(--ink)', fontSize: 6, padding: '2px 3px', border: '1px solid var(--ink)' }}>YOU</span>
        )}
      </div>
      {/* Detail */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div className="flex items-start justify-between gap-2">
          <div style={{ minWidth: 0 }}>
            <div className="px" style={{ fontSize: 9, color: 'var(--ink)', lineHeight: 1.5 }}>{item.title}</div>
            {isCustom ? (
              <div className="px" style={{ fontSize: 7, color: 'var(--ink2)', marginTop: 6 }}>
                {item.brand} · {item.gridSize}×{item.gridSize} · {item.totalBeads?.toLocaleString()} beads
              </div>
            ) : (
              <div className="px" style={{ fontSize: 7, color: 'var(--ink2)', marginTop: 6 }}>
                KIT #{(item.id || 'stock').toString().slice(0,6)}
              </div>
            )}
          </div>
          <button onClick={onRemove} style={{ width: 24, height: 24, flexShrink: 0, border: '2px solid var(--ink)', background: 'var(--lt2)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon.Close size={11}/></button>
        </div>

        {/* Top bead colors */}
        {isCustom && item.beadCounts && (
          <div className="flex items-center gap-1 mt-2">
            {Object.entries(item.beadCounts).sort((a,b) => b[1] - a[1]).slice(0, 7).map(([id, n]) => {
              const b = window.BEAD_BY_ID[id];
              if (!b) return null;
              return <div key={id} title={`${b.code} · ${b.name} · ×${n}`} style={{ width: 13, height: 13, background: b.hex, border: '1px solid var(--ink)' }}/>;
            })}
          </div>
        )}

        {/* Qty + price row */}
        <div className="flex items-center justify-between" style={{ marginTop: 12 }}>
          <div className="flex items-center" style={{ border: '2px solid var(--ink)' }}>
            <button onClick={onDec} style={{ width: 26, height: 26, background: 'var(--lt2)', color: 'var(--ink)', border: 'none', borderRight: '2px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon.Minus size={11}/></button>
            <span className="px" style={{ width: 26, textAlign: 'center', fontSize: 9 }}>{item.qty || 1}</span>
            <button onClick={onInc} style={{ width: 26, height: 26, background: 'var(--lt2)', color: 'var(--ink)', border: 'none', borderLeft: '2px solid var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><window.Icon.Plus size={11}/></button>
          </div>
          <div className="px" style={{ fontSize: 11, color: 'var(--v)' }}>
            ${((item.estimatedPrice || item.price || 0) * (item.qty || 1)).toFixed(2)}
          </div>
        </div>
      </div>
    </div>
  );
}
