/* global React */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ============ ICONS ============
const Icon = {
  search: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><circle cx="11" cy="11" r="7" /><path d="m20 20-3.5-3.5" /></svg>,
  user: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><circle cx="12" cy="8" r="4" /><path d="M4 21a8 8 0 0 1 16 0" /></svg>,
  heart: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M12 20s-7-4.5-9-9.5C1.5 6.5 4.5 3 8 3c2 0 3.2 1 4 2 .8-1 2-2 4-2 3.5 0 6.5 3.5 5 7.5-2 5-9 9.5-9 9.5Z" /></svg>,
  heartFilled: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12 20s-7-4.5-9-9.5C1.5 6.5 4.5 3 8 3c2 0 3.2 1 4 2 .8-1 2-2 4-2 3.5 0 6.5 3.5 5 7.5-2 5-9 9.5-9 9.5Z" /></svg>,
  cart: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M3 5h2l2.5 11h11L21 8H7" /><circle cx="9" cy="20" r="1.6" /><circle cx="18" cy="20" r="1.6" /></svg>,
  close: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M6 6 18 18M6 18 18 6" /></svg>,
  menu: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="M3 6h18M3 12h18M3 18h18" /></svg>,
  chev: (p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="m9 6 6 6-6 6" /></svg>,
  chevDown: (p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="m6 9 6 6 6-6" /></svg>,
  check: (p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" {...p}><path d="m4 12 5 5L20 6" /></svg>,
  filter: (p = {}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M3 5h18M6 12h12M10 19h4" /></svg>,
  grid: (p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><rect x="3" y="3" width="7" height="7" /><rect x="14" y="3" width="7" height="7" /><rect x="3" y="14" width="7" height="7" /><rect x="14" y="14" width="7" height="7" /></svg>,
  list: (p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M3 6h18M3 12h18M3 18h18" /></svg>,
  shield: (p = {}) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M12 3 4 6v6c0 5 3.5 8 8 9 4.5-1 8-4 8-9V6l-8-3Z" /></svg>,
  truck: (p = {}) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M3 7h11v9H3zM14 10h4l3 3v3h-7zM7 16a2 2 0 1 0 0 0M17 16a2 2 0 1 0 0 0" /></svg>,
  bolt: (p = {}) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M13 3 4 14h7l-1 7 9-11h-7l1-7Z" /></svg>,
  pin: (p = {}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M12 22s7-6 7-12a7 7 0 1 0-14 0c0 6 7 12 7 12Z" /><circle cx="12" cy="10" r="2.5" /></svg>,
  phone: (p = {}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M5 4h4l2 5-3 2a12 12 0 0 0 5 5l2-3 5 2v4a2 2 0 0 1-2 2A17 17 0 0 1 3 6a2 2 0 0 1 2-2Z" /></svg>,
  mail: (p = {}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><rect x="3" y="5" width="18" height="14" /><path d="m3 6 9 7 9-7" /></svg>,
  eye: (p = {}) => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12Z" /><circle cx="12" cy="12" r="3" /></svg>,
  star: (filled, p = {}) => <svg width="14" height="14" viewBox="0 0 24 24" fill={filled ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="1.5" {...p}><path d="m12 2 3 7 7 .8-5.3 4.9 1.6 7L12 18l-6.3 3.7 1.6-7L2 9.8 9 9Z" /></svg>,
  ig: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><rect x="3" y="3" width="18" height="18" rx="4" /><circle cx="12" cy="12" r="4" /><circle cx="17.5" cy="6.5" r="1" fill="currentColor" /></svg>,
  yt: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" {...p}><rect x="2" y="6" width="20" height="12" rx="3" /><path d="m10 9 5 3-5 3z" fill="currentColor" /></svg>,
  fb: (p = {}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M13 9V7c0-1 .5-1.5 1.5-1.5H17V2h-3c-3 0-5 2-5 5v2H6v4h3v9h4v-9h3l1-4z" /></svg>
};

// ============ Product imagery (SVG placeholders w/ iconography) ============
// each product gets a categorical glyph on a brand-colored panel
const PROD_GLYPHS = {
  helmet: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M40 130 Q40 50 120 50 Q200 50 200 130 L200 165 L40 165 Z" />
      <path d="M60 130 Q60 70 120 70 Q180 70 180 130" />
      <path d="M75 140 Q75 95 120 95 Q165 95 165 140 L165 155 L75 155 Z" fill={c} fillOpacity=".15" />
      <path d="M55 110 L185 110" strokeWidth="1.4" />
      <circle cx="120" cy="138" r="3" fill={c} />
    </g>,

  jacket: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M70 50 L100 40 L120 55 L140 40 L170 50 L185 80 L175 90 L175 195 L65 195 L65 90 L55 80 Z" />
      <path d="M120 55 L120 195" />
      <path d="M100 40 Q110 30 120 35 Q130 30 140 40" />
      <rect x="76" y="120" width="22" height="35" strokeWidth="2" />
      <rect x="142" y="120" width="22" height="35" strokeWidth="2" />
      <path d="M120 70 L120 110 M115 80 L125 80 M115 90 L125 90 M115 100 L125 100" strokeWidth="1.5" />
    </g>,

  glove: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M60 130 Q60 85 80 85 L85 60 Q88 50 98 50 Q108 50 110 60 L113 90 L120 90 L122 55 Q124 45 134 45 Q144 45 146 55 L148 90 L154 90 L158 70 Q162 60 172 62 Q182 64 180 75 L175 95 L182 110 Q190 130 178 145 L172 195 L72 195 L60 165 Z" fill={c} fillOpacity=".08" />
      <path d="M88 130 L88 175 M120 130 L120 175 M148 130 L148 175 M175 130 L168 175" strokeWidth="1.5" />
    </g>,

  knee: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M90 50 Q120 45 150 50 L160 100 Q175 110 175 130 Q175 160 160 175 L150 200 L90 200 L80 175 Q65 160 65 130 Q65 110 80 100 Z" fill={c} fillOpacity=".1" />
      <circle cx="120" cy="130" r="22" fill={c} />
      <path d="M85 90 L155 90 M85 175 L155 175" strokeWidth="1.5" />
    </g>,

  back: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M70 50 Q120 40 170 50 L165 200 L75 200 Z" fill={c} fillOpacity=".08" />
      <path d="M85 70 L155 70 M85 95 L155 95 M85 120 L155 120 M85 145 L155 145 M85 170 L155 170" strokeWidth="1.5" />
      <path d="M120 55 L120 195" strokeDasharray="3 4" />
    </g>,

  boot: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M90 30 L150 30 L155 130 L195 145 L195 195 L60 195 L60 145 L85 130 Z" fill={c} fillOpacity=".1" />
      <path d="M95 60 L150 60 M95 85 L150 85 M95 110 L150 110" strokeWidth="1.5" />
      <path d="M60 165 L195 165" strokeWidth="1.5" />
    </g>,

  elbow: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M80 60 L160 60 L170 100 L180 145 L165 195 L75 195 L60 145 L70 100 Z" fill={c} fillOpacity=".1" />
      <circle cx="120" cy="120" r="25" fill={c} />
      <path d="M85 80 L155 80 M85 175 L155 175" strokeWidth="1.5" />
    </g>,

  collar: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M50 110 Q50 70 120 70 Q190 70 190 110 L190 160 Q190 180 170 180 L70 180 Q50 180 50 160 Z" fill={c} fillOpacity=".08" />
      <path d="M90 140 L150 140 M90 160 L150 160" strokeWidth="1.5" />
      <circle cx="120" cy="105" r="14" />
    </g>,

  filter: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <ellipse cx="120" cy="65" rx="55" ry="14" />
      <path d="M65 65 L65 175 Q65 195 120 195 Q175 195 175 175 L175 65" />
      <path d="M80 90 L160 90 M80 115 L160 115 M80 140 L160 140 M80 165 L160 165" strokeWidth="1.4" />
    </g>,

  brake: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <circle cx="120" cy="120" r="75" fill={c} fillOpacity=".05" />
      <circle cx="120" cy="120" r="55" />
      <circle cx="120" cy="120" r="22" fill={c} />
      <path d="M120 45 L120 75 M120 165 L120 195 M45 120 L75 120 M165 120 L195 120" strokeWidth="2.5" />
      <path d="M70 70 L88 88 M150 152 L172 174 M152 88 L170 70 M70 172 L88 154" strokeWidth="1.5" />
    </g>,

  tire: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <circle cx="120" cy="120" r="80" />
      <circle cx="120" cy="120" r="45" fill={c} fillOpacity=".15" />
      <circle cx="120" cy="120" r="22" />
      {Array.from({ length: 12 }).map((_, i) => {
      const a = i * 30 * Math.PI / 180;const x1 = 120 + Math.cos(a) * 48,y1 = 120 + Math.sin(a) * 48;
      const x2 = 120 + Math.cos(a) * 78,y2 = 120 + Math.sin(a) * 78;
      return <path key={i} d={`M${x1} ${y1} L${x2} ${y2}`} strokeWidth="3" />;
    })}
    </g>,

  chain: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      {[40, 80, 120, 160].map((x, i) =>
    <g key={i}>
          <rect x={x} y="100" width="40" height="40" rx="6" />
          <circle cx={x + 10} cy="120" r="4" fill={c} />
          <circle cx={x + 30} cy="120" r="4" fill={c} />
        </g>
    )}
      <path d="M20 120 L40 120 M200 120 L220 120" strokeWidth="2" />
    </g>,

  spark: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M110 30 L130 30 L130 60 L138 65 L138 110 L102 110 L102 65 L110 60 Z" />
      <rect x="100" y="110" width="40" height="50" />
      <path d="M120 160 L120 200 M110 180 L130 180" strokeWidth="2.5" />
      <path d="M115 75 L125 75 M115 85 L125 85 M115 95 L125 95" strokeWidth="1.5" />
    </g>,

  wrench: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M55 55 L75 35 Q90 50 75 65 L95 85 L160 150 Q170 160 175 170 Q185 185 175 195 Q165 205 150 195 Q140 190 130 180 L65 115 L45 95 Q30 80 55 55 Z" fill={c} fillOpacity=".08" />
      <circle cx="155" cy="180" r="6" fill={c} />
    </g>,

  jack: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <rect x="40" y="150" width="160" height="40" rx="4" fill={c} fillOpacity=".1" />
      <path d="M60 150 L60 120 L100 100 L140 100 L180 120 L180 150" />
      <path d="M100 100 L100 70 L140 70 L140 100" />
      <circle cx="65" cy="190" r="8" /><circle cx="175" cy="190" r="8" />
    </g>,

  stand: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <path d="M40 180 L100 100 L140 100 L200 180 Z" fill={c} fillOpacity=".08" />
      <path d="M70 140 L170 140" strokeWidth="2" />
      <circle cx="120" cy="80" r="14" />
    </g>,

  torque: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <rect x="50" y="100" width="120" height="40" rx="4" />
      <rect x="170" y="90" width="40" height="60" rx="3" fill={c} fillOpacity=".15" />
      <path d="M30 100 L50 100 M30 140 L50 140" strokeWidth="2" />
      <path d="M60 120 L160 120" strokeDasharray="3 4" strokeWidth="1.5" />
    </g>,

  bike: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <circle cx="60" cy="160" r="36" />
      <circle cx="180" cy="160" r="36" />
      <path d="M60 160 L120 80 L160 160 M120 80 L150 80 L180 160 M100 130 L150 80" strokeWidth="3" />
      <path d="M150 70 L165 65 M55 155 L60 160 L70 155" strokeWidth="2" />
    </g>,

  scooter: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <circle cx="50" cy="170" r="22" />
      <circle cx="195" cy="170" r="22" />
      <path d="M50 170 L150 170 L180 80 L165 75 L160 90" />
      <path d="M150 170 L160 80" strokeWidth="2" />
      <rect x="55" y="155" width="120" height="18" fill={c} fillOpacity=".15" />
    </g>,

  gear: (c = 'currentColor') =>
  <g fill="none" stroke={c} strokeWidth="3" strokeLinejoin="round">
      <circle cx="120" cy="120" r="42" />
      <circle cx="120" cy="120" r="14" fill={c} />
      {Array.from({ length: 8 }).map((_, i) => {
      const a = i * 45 * Math.PI / 180;const x = 120 + Math.cos(a) * 60,y = 120 + Math.sin(a) * 60;
      return <rect key={i} x={x - 7} y={y - 10} width="14" height="20" transform={`rotate(${i * 45} ${x} ${y})`} fill={c} fillOpacity=".25" />;
    })}
    </g>

};

// background tint by category (subtle)
const PROD_TINT = {
  cascos: ['#F4F1EA', '#0A0A0A'],
  chamarras: ['#EAE5DA', '#0A0A0A'],
  proteccion: ['#EFEAE0', '#0A0A0A'],
  refacciones: ['#E8E2D4', '#0A0A0A'],
  herramientas: ['#E5DFD2', '#0A0A0A'],
  bicicletas: ['#EAE5DA', '#0A0A0A'],
  patines: ['#EFEAE0', '#0A0A0A']
};

function ProductArt({ product, dark, accent }) {
  const Glyph = PROD_GLYPHS[product.icon] || PROD_GLYPHS.gear;
  const tint = PROD_TINT[product.cat] || ['#F4F1EA', '#0A0A0A'];
  const bg = dark ? '#181818' : tint[0];
  const stroke = dark ? '#F4F1EA' : '#0A0A0A';
  const ac = accent || '#E60023';

  // If real product image exists, render photo with a subtle annotation overlay
  if (product.image) {
    return (
      <div style={{position:'relative', width:'100%', height:'100%', overflow:'hidden', background: dark ? '#0A0A0A' : '#1A1A1A'}}>
        <img src={product.image} alt={product.name}
          style={{width:'100%', height:'100%', objectFit:'cover', display:'block', filter: dark ? 'brightness(.95)' : 'none'}}
          onError={(e)=>{ e.currentTarget.style.display = 'none'; }}
        />
        {/* corner overlay annotations — subtle, garage spec sheet feel */}
        <div style={{
          position:'absolute', top:8, left:10, right:10,
          display:'flex', justifyContent:'space-between',
          fontFamily:'JetBrains Mono, monospace', fontSize:9,
          color:'#ffffff', letterSpacing:'.1em', opacity:.7,
          pointerEvents:'none', mixBlendMode:'difference',
        }}>
          <span>{product.id.toUpperCase()}</span>
          <span>{product.brand}</span>
        </div>
      </div>
    );
  }

  // SVG fallback (no image assigned)
  return (
    <svg viewBox="0 0 240 240" preserveAspectRatio="xMidYMid meet" style={{ width: "100%", height: "100%", display: "block" }}>
      <rect width="240" height="240" fill={bg} />
      {/* grid lines */}
      <g stroke={stroke} strokeOpacity=".05" strokeWidth="1">
        {[40, 80, 120, 160, 200].map((p) => <g key={p}><line x1={p} y1="0" x2={p} y2="240" /><line y1={p} x1="0" y2={p} x2="240" /></g>)}
      </g>
      {/* corner spec */}
      <text x="12" y="22" fontFamily="JetBrains Mono, monospace" fontSize="9" fill={stroke} opacity=".5" letterSpacing="1">{product.id.toUpperCase()}</text>
      <text x="228" y="22" textAnchor="end" fontFamily="JetBrains Mono, monospace" fontSize="9" fill={stroke} opacity=".5" letterSpacing="1">{product.brand}</text>
      {/* enso suggestion */}
      <circle cx="200" cy="210" r="14" fill="none" stroke={ac} strokeWidth="3" strokeDasharray="60 8" transform="rotate(-30 200 210)" />
      <g style={{ color: stroke }}>{Glyph(stroke)}</g>
      <text x="12" y="232" fontFamily="JetBrains Mono, monospace" fontSize="9" fill={stroke} opacity=".5" letterSpacing="1.5">MODEL · {product.tags[0]?.toUpperCase()}</text>
    </svg>);

}

// ============ Star rating ============
function Stars({ value, reviews, showCount = true }) {
  const full = Math.round(value);
  return (
    <span className="pcard-stars">
      {[1, 2, 3, 4, 5].map((i) => <span key={i} style={{ color: i <= full ? '#E60023' : 'currentColor', opacity: i <= full ? 1 : .3 }}>{Icon.star(i <= full)}</span>)}
      {showCount && <span>{value.toFixed(1)} · {reviews}</span>}
    </span>);

}

// ============ Price utils ============
const fmtMXN = (n) => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN', maximumFractionDigits: 0 }).format(n);

// ============ Product card ============
function ProductCard({ product, variant = 'default', onQuickView, onAddToCart, onToggleFav, isFav, dark, accent }) {
  const cartBtnRef = useRef(null);
  const cls = `pcard ${variant !== 'default' ? variant : ''}`;
  return (
    <article className={cls} style={{ width: "300px", height: "500px", textAlign: "left", padding: "22px", margin: "5px" }}>
      <div className="pcard-thumb">
        {product.badge &&
        <div className="pcard-badges">
            {product.badge === 'sale' && <span className="pcard-badge blood">−{Math.round((1 - product.price / product.oldPrice) * 100)}%</span>}
            {product.badge === 'new' && <span className="pcard-badge">Nuevo</span>}
            {product.badge === 'top' && <span className="pcard-badge blood">Top</span>}
          </div>
        }
        <button className={`pcard-fav ${isFav ? 'on heart-pop' : ''}`} onClick={(e) => {e.stopPropagation();onToggleFav(product.id);}} aria-label="Favorito">
          {isFav ? Icon.heartFilled() : Icon.heart()}
        </button>
        <a onClick={() => onQuickView(product, 'view')} style={{ cursor: 'pointer', display: 'block', height: '100%' }}>
          <ProductArt product={product} dark={dark} accent={accent} />
        </a>
        <div className="pcard-quick">
          <button ref={cartBtnRef} className="btn primary block sm" onClick={(e) => onAddToCart(product, e.currentTarget)}>
            <span>{Icon.cart()}</span> Agregar
          </button>
        </div>
      </div>
      <div className="pcard-meta">
        <span className="pcard-brand">{product.brand}</span>
        <a className="pcard-name" onClick={() => onQuickView(product, 'view')} style={{ cursor: 'pointer' }}>{product.name}</a>
        <Stars value={product.rating} reviews={product.reviews} />
        <div className="pcard-price">
          <span className="now">{fmtMXN(product.price)}</span>
          {product.oldPrice && <span className="was">{fmtMXN(product.oldPrice)}</span>}
        </div>
      </div>
    </article>);

}

// Export to window so other Babel scripts see them
Object.assign(window, {
  Icon, ProductArt, ProductCard, Stars, fmtMXN,
  useState, useEffect, useRef, useMemo, useCallback
});