// storefront-product.jsx — placeholder visual + product card

// Resolve a real product image if available for a (product, color, view) triple.
//   view ∈ 'front' (flat front, default) · 'back' · 'male' · 'maleBack'
//          · 'female' · 'femaleBack' · 'detail' · 'backLogo'
// Strict: returns null if THIS specific view isn't in imagesByColor.
// Callers handle their own fallback (e.g. ProductCard hover picks an alt view manually).
function resolveProductImage(product, color, view = 'front') {
  if (!product || !product.imagesByColor || !color) return null;
  const set = product.imagesByColor[color.name];
  if (!set) return null;
  return set[view] || null;
}

const ProductPlaceholder = ({ product, color, mobile, large = false, label, view = 'front' }) => {
  const c = color || product.colors[0];
  const img = resolveProductImage(product, c, view);

  // ── Real photo branch — neutral studio-white frame with editorial metadata corner stamps
  if (img) {
    return (
      <div style={{
        position:'relative', width:'100%', aspectRatio:'4/5',
        background:'#F4F2EC', overflow:'hidden',
      }}>
        <img src={img} alt={`${product.name} — ${c.name}`}
          loading="lazy"
          style={{
            position:'absolute', inset:0, width:'100%', height:'100%',
            objectFit:'cover', display:'block',
          }}/>
        <div style={{
          position:'absolute', top: large ? 18 : 10, left: large ? 18 : 10,
          fontFamily:'JetBrains Mono, monospace', fontSize: large ? 10 : 9,
          letterSpacing:'0.2em', textTransform:'uppercase',
          color: '#0A0A0A', opacity: 0.55, mixBlendMode:'multiply',
        }}>
          {label || `${product.id} · ${c.name}`}
        </div>
        <div style={{
          position:'absolute', bottom: large ? 18 : 10, right: large ? 18 : 10,
          fontFamily:'JetBrains Mono, monospace', fontSize: large ? 10 : 9,
          letterSpacing:'0.2em', textTransform:'uppercase',
          color: '#0A0A0A', opacity: 0.35, mixBlendMode:'multiply',
        }}>
          4:5
        </div>
      </div>
    );
  }

  // ── Placeholder branch — colored block + abstract garment silhouette + metadata
  const stripeBg = `repeating-linear-gradient(45deg, ${c.hex}00 0 12px, rgba(255,255,255,0.05) 12px 13px)`;
  return (
    <div style={{
      position:'relative', width:'100%', aspectRatio:'4/5',
      background: c.hex, overflow:'hidden',
    }}>
      <div style={{ position:'absolute', inset:0, background: stripeBg }}/>
      {/* fake garment silhouette outline */}
      <GarmentSilhouette category={product.category} colorHex={c.hex} />
      {/* monospace explainer */}
      <div style={{
        position:'absolute', top: large ? 20 : 12, left: large ? 20 : 12,
        fontFamily:'JetBrains Mono, monospace', fontSize: large ? 11 : 10,
        letterSpacing:'0.2em', textTransform:'uppercase',
        color: contrast(c.hex), opacity: 0.65,
      }}>
        {label || `${product.id} · ${c.name}`}
      </div>
      <div style={{
        position:'absolute', bottom: large ? 20 : 12, right: large ? 20 : 12,
        fontFamily:'JetBrains Mono, monospace', fontSize: large ? 11 : 10,
        letterSpacing:'0.2em', textTransform:'uppercase',
        color: contrast(c.hex), opacity: 0.45,
      }}>
        4:5 · Slot
      </div>
    </div>
  );
};

function contrast(hex) {
  const h = hex.replace('#',''); const r = parseInt(h.substring(0,2),16), g = parseInt(h.substring(2,4),16), b = parseInt(h.substring(4,6),16);
  const lum = (0.299*r + 0.587*g + 0.114*b);
  return lum > 160 ? '#0A0A0A' : '#FFFFFF';
}

function GarmentSilhouette({ category, colorHex }) {
  const stroke = contrast(colorHex);
  const op = 0.18;
  // Simple abstract garment shapes — not detailed illustration
  const common = { fill: 'none', stroke, strokeWidth: 1.2, strokeOpacity: op, strokeLinejoin: 'round' };
  return (
    <svg viewBox="0 0 200 250" preserveAspectRatio="xMidYMid meet" style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
      {category === 'hoodies' && (
        <g {...common}>
          <path d="M70 60 Q100 40 130 60 L170 90 L160 130 L150 130 L150 220 L50 220 L50 130 L40 130 L30 90 Z"/>
          <path d="M70 60 Q100 80 130 60"/>
          <path d="M85 65 Q100 110 115 65"/>
          <line x1="92" y1="100" x2="92" y2="170"/>
          <line x1="108" y1="100" x2="108" y2="170"/>
        </g>
      )}
      {category === 'crewnecks' && (
        <g {...common}>
          <path d="M70 70 L130 70 L170 100 L160 130 L150 130 L150 220 L50 220 L50 130 L40 130 L30 100 Z"/>
          <path d="M75 70 Q100 90 125 70"/>
        </g>
      )}
      {category === 'playeras' && (
        <g {...common}>
          <path d="M70 70 L130 70 L165 90 L155 110 L145 105 L145 220 L55 220 L55 105 L45 110 L35 90 Z"/>
          <path d="M78 70 Q100 92 122 70"/>
        </g>
      )}
      {category === 'bottoms' && (
        <g {...common}>
          <path d="M55 50 L145 50 L150 110 L120 230 L100 230 L96 130 L92 230 L72 230 Z"/>
          <line x1="100" y1="50" x2="100" y2="120"/>
        </g>
      )}
      {category === 'outerwear' && (
        <g {...common}>
          <path d="M65 60 L100 70 L135 60 L170 90 L160 140 L150 140 L150 225 L50 225 L50 140 L40 140 L30 90 Z"/>
          <line x1="100" y1="70" x2="100" y2="225"/>
          <rect x="60" y="160" width="22" height="28"/>
          <rect x="118" y="160" width="22" height="28"/>
        </g>
      )}
      {category === 'sets' && (
        <g {...common}>
          <path d="M75 55 L125 55 L150 80 L140 105 L130 105 L130 130 L70 130 L70 105 L60 105 L50 80 Z"/>
          <path d="M70 140 L130 140 L130 230 L110 230 L100 170 L90 230 L70 230 Z"/>
        </g>
      )}
    </svg>
  );
}

// ─── Product card ───────────────────────────────────────────────────
function ProductCard({ product, mobile, onClick, span }) {
  const [hover, setHover] = useState(false);
  const colors = product.colors;
  // Decide hover behaviour:
  //   - real photos available → flip to the studio BACK shot (or detail) — no models in catalog
  //   - else if multiple colors → flip to second color (legacy placeholder behaviour)
  const hasPhotos = !!(product.imagesByColor && product.imagesByColor[colors[0].name]);
  const flipMode = hasPhotos ? 'view' : (colors.length > 1 ? 'color' : null);
  const showSecondary = hover && !!flipMode;
  // Pick which non-model view to flip to. Back is the most informative second shot;
  // fall back to detail/backLogo for products without a back flat.
  const hoverView = (() => {
    if (!hasPhotos) return 'front';
    const set = product.imagesByColor[colors[0].name];
    if (set.back) return 'back';
    if (set.detail) return 'detail';
    if (set.backLogo) return 'backLogo';
    return 'front';
  })();
  return (
    <article
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      onClick={onClick}
      data-cursor-label="Ver"
      style={{
        position:'relative', cursor:'pointer',
        gridColumn: span,
      }}>
      <div style={{ position:'relative', overflow:'hidden' }}>
        <div style={{ opacity: showSecondary ? 0 : 1, transition:'opacity .35s ease' }}>
          <ProductPlaceholder product={product} color={colors[0]} mobile={mobile} view="front" />
        </div>
        {flipMode && (
          <div style={{ position:'absolute', inset:0, opacity: showSecondary ? 1 : 0, transition:'opacity .35s ease' }}>
            <ProductPlaceholder product={product}
              color={flipMode === 'color' ? colors[1] : colors[0]}
              view={flipMode === 'view' ? hoverView : 'front'}
              mobile={mobile} />
          </div>
        )}
        {product.isNew && (
          <div style={{
            position:'absolute', top:12, right:12,
            background: C.accent, color:'#fff',
            fontFamily:'JetBrains Mono, monospace', fontSize: 10,
            letterSpacing:'0.18em', padding:'5px 8px', textTransform:'uppercase',
          }}>NEW IN</div>
        )}
      </div>
      <div style={{
        marginTop: 12, display:'flex', justifyContent:'space-between', alignItems:'baseline',
        transform: hover && !mobile ? 'translateY(-2px)' : 'translateY(0)',
        transition:'transform .25s',
      }}>
        <div>
          <div style={{ fontFamily:'Anton, sans-serif', fontSize: mobile ? 16 : 18, textTransform:'uppercase', letterSpacing:'0.01em', lineHeight:1 }}>{product.name}</div>
          <div style={{ display:'flex', gap:6, marginTop:6 }}>
            {colors.slice(0,4).map((c,i) => (
              <span key={i} style={{
                width:10, height:10, borderRadius:'50%', background: c.hex,
                boxShadow:`inset 0 0 0 1px rgba(0,0,0,0.15)`,
              }}/>
            ))}
            {colors.length > 4 && <span style={{ fontFamily:'JetBrains Mono, monospace', fontSize:10, color: C.fgMuted }}>+{colors.length - 4}</span>}
          </div>
        </div>
        <div style={{ fontFamily:'JetBrains Mono, monospace', fontSize: mobile ? 12 : 13, textAlign:'right' }}>
          ${product.price.toLocaleString('es-MX')}
          <div style={{ fontSize:9, color: C.fgMuted, letterSpacing:'0.18em', textTransform:'uppercase' }}>MXN</div>
        </div>
      </div>
    </article>
  );
}

Object.assign(window, { ProductPlaceholder, GarmentSilhouette, ProductCard, contrast, resolveProductImage });
