// CartNavButton — botón de carrito para el nav (ícono + badge de cantidad).
// Expone: window.CartNavButton (componente React)
// Uso:    <CartNavButton active={bool}/>
//   active=true → resalta el botón (para la página Carrito.html)
(() => {
  const { useState, useEffect } = React;

  const CartNavButton = ({ active = false }) => {
    const [count, setCount] = useState(() =>
      window.CreartCart ? window.CreartCart.count() : 0
    );
    const [pulse, setPulse] = useState(false);

    useEffect(() => {
      const sync = () => {
        const n = window.CreartCart ? window.CreartCart.count() : 0;
        setCount(prev => {
          if (n > prev) { setPulse(true); setTimeout(() => setPulse(false), 600); }
          return n;
        });
      };
      window.addEventListener('creart-cart-changed', sync);
      return () => window.removeEventListener('creart-cart-changed', sync);
    }, []);

    return (
      <a
        href="Carrito.html"
        aria-label="Carrito"
        title="Carrito"
        style={{
          position: 'relative',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          width: 40, height: 36, marginLeft: 4,
          background: active ? 'var(--yellow)' : 'transparent',
          border: '2px solid var(--bg)',
          color: active ? 'var(--ink)' : 'var(--bg)',
          boxShadow: active ? '2px 2px 0 rgba(255,255,255,0.3)' : 'none',
          transform: pulse ? 'scale(1.15)' : 'scale(1)',
          transition: 'transform 0.2s, background 0.15s',
          flexShrink: 0,
        }}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="square" strokeLinejoin="miter">
          <circle cx="9"  cy="20" r="1.4" fill="currentColor" stroke="none"/>
          <circle cx="18" cy="20" r="1.4" fill="currentColor" stroke="none"/>
          <path d="M2.5 3.5h3l2.6 12h10.5l2.4-8.5H6.2"/>
        </svg>
        {count > 0 && (
          <span style={{
            position: 'absolute', top: -7, right: -7,
            background: 'var(--red)', color: '#fff',
            fontFamily: 'var(--fdisp2)', fontSize: 9, fontWeight: 700,
            minWidth: 17, height: 17, borderRadius: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            border: '1.5px solid var(--ink)', padding: '0 3px',
            lineHeight: 1, letterSpacing: '0.02em',
          }}>
            {count > 99 ? '99+' : count}
          </span>
        )}
      </a>
    );
  };

  window.CartNavButton = CartNavButton;
})();
