/* ─────────────────────────────────────────────────────────────────
   CrossSellSheet — cross-sell superpuesto DENTRO del panel del carrito,
   ancho completo, con fondo oscuro que deja ver parte del carrito arriba.
   Se desliza de abajo hacia arriba y se puede ARRASTRAR hacia abajo
   (drag en el header) para ocultarlo. Cada producto se puede agregar y
   deseleccionar (toggle). Máx. 4 productos.
   Props: open, cart, onAdd, onRemove, onNavigate, onClose, onContinue
   ───────────────────────────────────────────────────────────────── */
function CrossSellSheet({ open, cart, onAdd, onRemove, onNavigate, onClose, onContinue }) {
  const { PRODUCTS, ARS } = window.RC_DATA;

  const MAX = 4;
  const [picks, setPicks] = React.useState([]);
  const [justAdded, setJustAdded] = React.useState({});
  const [drag, setDrag] = React.useState(0);     // px arrastrados hacia abajo (para render)
  const [animate, setAnimate] = React.useState(true);
  const [topOffset, setTopOffset] = React.useState(120); // se mide al abrir: justo debajo del 1er producto del carrito
  const dragStart = React.useRef(null);
  const dragRef = React.useRef(0);               // valor actual del drag (lectura en touchend)
  const sheetRef = React.useRef(null);

  // Candidatos: se calculan al ABRIR (no en cada add). También resetea el drag.
  React.useEffect(() => {
    setDrag(0);
    setAnimate(true);
    if (!open) return;
    const inCart = new Set(cart.map((it) => it.id));
    const accessories = PRODUCTS.filter((p) => p.cat === 'rep' && !inCart.has(p.id));
    const ranked = [...accessories].sort((a, b) => (b.rating || 0) - (a.rating || 0) || a.price - b.price);
    let result = ranked.slice(0, MAX);
    if (result.length < MAX) {
      result = result.concat(
        PRODUCTS.filter((p) => !inCart.has(p.id) && !result.find((x) => x.id === p.id)).slice(0, MAX - result.length)
      );
    }
    setPicks(result);
    setJustAdded({});
    // Posicionar la card justo debajo del primer producto del carrito,
    // para que ese producto quede visible (atenuado) en el fondo.
    requestAnimationFrame(() => {
      const panel = sheetRef.current && sheetRef.current.parentElement;
      if (!panel) return;
      const scroll = [...panel.children].find((c) => c.tagName === 'DIV' && getComputedStyle(c).overflowY === 'auto');
      const firstItem = scroll && scroll.firstElementChild;
      if (firstItem) {
        const panelTop = panel.getBoundingClientRect().top;
        setTopOffset(Math.round(firstItem.getBoundingClientRect().bottom - panelTop));
      }
    });
  }, [open]);

  const addedIds = new Set(cart.map((it) => it.id));
  const anySelected = picks.some((p) => addedIds.has(p.id)); // ¿se agregó algún artículo del cross-sell?
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const cartTotal = cart.reduce((s, i) => s + i.price * i.qty, 0);

  const handleAdd = (p) => {
    onAdd(p);
    setJustAdded((s) => ({ ...s, [p.id]: true }));
    setTimeout(() => setJustAdded((s) => { const { [p.id]: _, ...rest } = s; return rest; }), 1600);
  };
  const handleRemove = (p) => {
    onRemove(p.id);
    setJustAdded((s) => { const { [p.id]: _, ...rest } = s; return rest; });
  };

  // Drag para ocultar hacia abajo (touch). Se lee el valor desde un ref en
  // touchend (el estado podría estar desactualizado por el timing de render).
  const onDragStart = (e) => { dragStart.current = e.touches[0].clientY; dragRef.current = 0; setAnimate(false); };
  const onDragMove = (e) => {
    if (dragStart.current == null) return;
    const dy = Math.max(0, e.touches[0].clientY - dragStart.current);
    dragRef.current = dy;
    setDrag(dy);
  };
  const onDragEnd = () => {
    setAnimate(true);
    const d = dragRef.current;
    dragStart.current = null;
    if (d > 100) onClose();   // pasó el umbral → ocultar
    else setDrag(0);          // volver arriba
  };

  return (
    <div ref={sheetRef} style={{ position: 'absolute', inset: 0, zIndex: 5, pointerEvents: open ? 'auto' : 'none' }}>
      {/* Fondo oscuro: deja ver (atenuado) el primer producto del carrito arriba */}
      <div onClick={onClose} style={{
        position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)',
        opacity: open ? 1 : 0, transition: 'opacity .3s ease'
      }} />

      {/* Card del cross-sell — ancho completo, arranca debajo del 1er producto */}
      <div
        role="dialog" aria-modal="true" aria-label="Agregá a tu compra"
        style={{
          position: 'absolute', top: topOffset, left: 0, right: 0, bottom: 0,
          background: 'var(--surface)',
          borderRadius: '16px 16px 0 0',
          boxShadow: '0 -10px 30px rgba(11,18,32,0.22)',
          display: 'flex', flexDirection: 'column', overflow: 'hidden',
          transform: open ? `translateY(${drag}px)` : 'translateY(100%)',
          transition: animate ? 'transform .32s cubic-bezier(.22,1,.36,1)' : 'none'
        }}>
        {/* Header = zona de arrastre (sin padding superior) */}
        <div
          onTouchStart={onDragStart} onTouchMove={onDragMove} onTouchEnd={onDragEnd}
          style={{ padding: '0 16px 12px', borderBottom: '1px solid var(--line)', flexShrink: 0, cursor: 'grab', touchAction: 'none' }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--line-2)', margin: '8px auto 10px' }} />
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <h3 style={{ fontSize: 17, fontWeight: 500, letterSpacing: '-0.01em', color: 'var(--ink)', minWidth: 0 }}>Agregá a tu compra</h3>
            <button onClick={onClose} aria-label="Cerrar" style={{ flexShrink: 0, width: 32, height: 32, borderRadius: 16, background: 'var(--bg-2)', color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', border: 'none' }}>
              <Icon name="close" size={16} />
            </button>
          </div>
        </div>

        {/* Lista scrollable — sin box por producto */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '4px 16px' }}>
          {picks.map((p, i) => {
            const added = !!justAdded[p.id] || addedIds.has(p.id);
            return (
              <div key={p.id} style={{
                display: 'grid', gridTemplateColumns: '60px 1fr', gap: 12, alignItems: 'center',
                padding: '14px 0',
                borderBottom: i < picks.length - 1 ? '1px solid var(--line)' : 'none'
              }}>
                <button onClick={() => onNavigate(`/producto/${p.id}`)} style={{ width: 60, height: 60, background: '#FFF', border: '1px solid var(--line)', borderRadius: 8, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0 }}>
                  {p.image
                    ? <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 5 }} />
                    : <span className="mono t-xs" style={{ fontSize: 9 }}>{p.brand}</span>}
                </button>
                <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 5 }}>
                  <button onClick={() => onNavigate(`/producto/${p.id}`)} style={{ textAlign: 'left', fontSize: 13, fontWeight: 500, lineHeight: 1.3, color: 'var(--ink)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                    {p.name}
                  </button>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--ink)' }}>{ARS(p.price)}</div>
                    <button onClick={() => (added ? handleRemove(p) : handleAdd(p))} style={{
                      padding: '6px 11px', borderRadius: 999, fontSize: 12, fontWeight: 700,
                      background: added ? '#0F8A5B' : '#B30F0D', color: '#fff', border: 'none',
                      display: 'inline-flex', alignItems: 'center', gap: 5, cursor: 'pointer', transition: 'background .15s'
                    }}>
                      {added
                        ? <React.Fragment><Icon name="check" size={12} strokeWidth={3} /> Agregado</React.Fragment>
                        : <React.Fragment><Icon name="plus" size={12} strokeWidth={3} /> Agregar</React.Fragment>}
                    </button>
                  </div>
                </div>
              </div>);
          })}
        </div>

        {/* Footer */}
        <div style={{ borderTop: '1px solid var(--line)', padding: '14px 16px', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
              Total · {cartCount} {cartCount === 1 ? 'producto' : 'productos'}
            </span>
            <span style={{ fontSize: 20, fontWeight: 800, color: 'var(--ink)' }}>{ARS(cartTotal)}</span>
          </div>
          <button className="btn btn-primary" style={{ width: '100%', padding: '14px', justifyContent: 'center' }} onClick={onContinue}>
            Continuar al checkout <Icon name="arrowRight" size={14} />
          </button>
          {!anySelected &&
          <button onClick={onContinue} style={{ width: '100%', marginTop: 8, background: 'transparent', color: 'var(--ink-3)', padding: '8px', fontSize: 13, fontWeight: 600, textDecoration: 'underline', textUnderlineOffset: 4, border: 'none', cursor: 'pointer' }}>
            Saltar este paso
          </button>}
        </div>
      </div>
    </div>);
}

window.CrossSellSheet = CrossSellSheet;
