// MendiArt — Página de producto

function ProductPage({ p, products, qty, onBack, onAdd, onRemove, onConsult, onOpenProduct, onCartClick, cartCount }) {
  const { C, Icon, ProductImage, ProductImg, MEDIA } = window;
  const [tab, setTab] = React.useState(0);
  const [fotoIdx, setFotoIdx] = React.useState(0);
  const outOfStock = !p.stock;
  const related = products.filter(x => x.id !== p.id && x.cat === p.cat).slice(0, 4);
  const compatList = p.compat.split('·').map(s => s.trim()).filter(Boolean);
  const fotos = Array.isArray(p.fotos) ? p.fotos : [];

  return (
    <div style={{
      height: '100%', display: 'flex', flexDirection: 'column',
      background: '#fff', position: 'relative', overflow: 'hidden',
    }}>
      {/* Scroll body */}
      <div style={{
        flex: 1, overflowY: 'auto', overflowX: 'hidden',
        paddingBottom: 160,
      }}>
        {/* Sticky top chrome */}
        <div style={{
          position: 'sticky', top: 0, zIndex: 5,
          padding: '16px 12px 8px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          background: 'linear-gradient(to bottom, rgba(255,255,255,0.9) 60%, rgba(255,255,255,0))',
          backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
        }}>
          <button onClick={onBack} style={chromeBtn}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M15 5l-7 7 7 7" stroke={C.text} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
          <div style={{ display: 'flex', gap: 6 }}>
            <button style={chromeBtn}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M20.8 4.6c-1.5-1.5-4-1.5-5.5 0L12 7.9 8.7 4.6c-1.5-1.5-4-1.5-5.5 0s-1.5 4 0 5.5l8.8 9 8.8-9c1.5-1.5 1.5-4 0-5.5z" stroke={C.text} strokeWidth="1.8" strokeLinejoin="round"/>
              </svg>
            </button>
            <button onClick={onCartClick} style={{ ...chromeBtn, position: 'relative' }}>
              <Icon.Cart s={20} c={C.text} />
              {cartCount > 0 && (
                <span style={{
                  position: 'absolute', top: 0, right: 0,
                  minWidth: 16, height: 16, padding: '0 4px',
                  background: C.naranja, color: '#fff',
                  borderRadius: 10, fontSize: 9, fontWeight: 800,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  border: '2px solid #fff', fontFamily: 'inherit',
                }}>{cartCount}</span>
              )}
            </button>
          </div>
        </div>

        {/* Gallery */}
        <div style={{ padding: '0 16px', marginTop: -32 }}>
          <div style={{
            width: '100%', aspectRatio: '1 / 1', borderRadius: 22,
            overflow: 'hidden', position: 'relative', background: '#f5f5f5',
          }}>
            {fotos.length > 0 ? (
              <img
                src={`${MEDIA}/${p.id}/${fotos[fotoIdx]}`}
                alt={p.name}
                style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
              />
            ) : (
              <ProductImage kind={p.kind} tone={p.tone} />
            )}
            {outOfStock && (
              <span style={{
                position: 'absolute', top: 16, left: 16,
                background: '#fff', color: C.text,
                padding: '6px 12px', borderRadius: 8, fontSize: 11, fontWeight: 700,
                fontFamily: 'inherit',
                border: `1px solid ${C.line}`, letterSpacing: 0.3,
              }}>SIN STOCK</span>
            )}
          </div>
          {/* Miniaturas si hay más de una foto */}
          {fotos.length > 1 && (
            <div style={{
              display: 'flex', gap: 8, paddingTop: 10,
              overflowX: 'auto', scrollbarWidth: 'none',
            }}>
              {fotos.map((f, i) => (
                <button key={f} onClick={() => setFotoIdx(i)} style={{
                  flexShrink: 0, width: 56, height: 56, borderRadius: 10,
                  overflow: 'hidden', border: 'none', padding: 0, cursor: 'pointer',
                  outline: i === fotoIdx ? `2.5px solid ${C.azul}` : `2px solid ${C.line}`,
                }}>
                  <img src={`${MEDIA}/${p.id}/${f}`} alt=""
                    style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
                </button>
              ))}
            </div>
          )}
          {/* dots si solo hay una foto o placeholder */}
          {fotos.length <= 1 && (
            <div style={{ display: 'flex', justifyContent: 'center', gap: 6, paddingTop: 12 }}>
              <span style={{ width: 18, height: 6, borderRadius: 6, background: C.azul }} />
            </div>
          )}
        </div>

        {/* Info */}
        <div style={{ padding: '20px 20px 8px' }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6,
          }}>
            <span style={{
              fontFamily: 'inherit', fontSize: 10.5, fontWeight: 800,
              color: C.naranja, textTransform: 'uppercase', letterSpacing: 1,
            }}>{p.cat}</span>
            {!outOfStock && (
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 5,
                fontFamily: 'inherit', fontSize: 10.5, fontWeight: 600,
                color: '#0F8B4A', letterSpacing: 0.2, whiteSpace: 'nowrap',
              }}>
                <span style={{ width: 6, height: 6, borderRadius: 6, background: '#0F8B4A' }} />
                En stock
              </span>
            )}
          </div>
          <h1 style={{
            fontFamily: 'inherit', fontSize: 24, fontWeight: 800,
            color: C.text, margin: 0, lineHeight: 1.2, letterSpacing: '-0.01em',
            textWrap: 'balance',
          }}>{p.name}</h1>
          <div style={{ marginTop: 14 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
              <span style={{
                fontFamily: 'inherit', fontSize: 30, fontWeight: 800,
                color: C.azul, letterSpacing: '-0.02em', lineHeight: 1,
              }}>${p.price.toLocaleString('es-AR')}</span>
              <span style={{
                fontFamily: 'inherit', fontSize: 11, fontWeight: 500, color: C.muted,
              }}>IVA incluido</span>
            </div>
            <div style={{
              fontFamily: 'inherit', fontSize: 12, color: C.muted, marginTop: 4,
            }}>
              Sin IVA: <strong style={{ color: C.text }}>${p.price_sin_iva.toLocaleString('es-AR')}</strong>
            </div>
          </div>
          {/* Payment hint */}
          <div style={{
            marginTop: 14, padding: '10px 12px', borderRadius: 12,
            background: '#F7F8FB', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <rect x="2.5" y="6" width="19" height="13" rx="2" stroke={C.azul} strokeWidth="1.6"/>
              <path d="M2.5 10h19" stroke={C.azul} strokeWidth="1.6"/>
            </svg>
            <div style={{ flex: 1, fontFamily: 'inherit', fontSize: 12, color: C.text, lineHeight: 1.35 }}>
              3 cuotas sin interés de <strong>${Math.round(p.price/3).toLocaleString('es-AR')}</strong>
            </div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{
          display: 'flex', gap: 0, padding: '14px 16px 0',
          borderBottom: `1px solid ${C.line}`,
        }}>
          {['Descripción', 'Compatibilidad', 'Especif.'].map((t, i) => (
            <button key={t} onClick={() => setTab(i)} style={{
              flex: 1, padding: '12px 8px', border: 'none', background: 'transparent',
              cursor: 'pointer', position: 'relative',
              fontFamily: 'inherit', fontSize: 12.5,
              fontWeight: tab === i ? 700 : 500,
              color: tab === i ? C.azul : C.muted,
              letterSpacing: 0.1,
            }}>
              {t}
              {tab === i && <div style={{
                position: 'absolute', bottom: -1, left: '15%', right: '15%',
                height: 2.5, background: C.azul, borderRadius: 4,
              }} />}
            </button>
          ))}
        </div>

        {/* Tab content */}
        <div style={{ padding: '16px 20px 24px', minHeight: 110 }}>
          {tab === 0 && (
            <p style={{
              fontFamily: 'inherit', fontSize: 13.5, lineHeight: 1.55,
              color: C.text, margin: 0, textWrap: 'pretty',
            }}>
              {p.descripcion || 'Sin descripción disponible.'}
            </p>
          )}
          {tab === 1 && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {compatList.length > 1 ? compatList.map(m => (
                <span key={m} style={{
                  padding: '6px 10px', borderRadius: 8,
                  background: '#EEF0FA', color: C.azul,
                  fontFamily: 'inherit', fontSize: 12, fontWeight: 600,
                }}>{m}</span>
              )) : (
                <span style={{
                  fontFamily: 'inherit', fontSize: 13.5, color: C.text,
                }}>{p.compat}</span>
              )}
            </div>
          )}
          {tab === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {[
                p.marca && ['Marca', p.marca],
                p.cantidad_por_unidad && ['Contenido', p.cantidad_por_unidad],
                p.calidad && ['Calidad', p.calidad],
                p.color_tinta && ['Color', p.color_tinta],
              ].filter(Boolean).map(([k, v]) => (
                <div key={k} style={{
                  display: 'flex', justifyContent: 'space-between',
                  padding: '10px 0', borderBottom: `1px solid ${C.line}`,
                  fontFamily: 'inherit', fontSize: 13,
                }}>
                  <span style={{ color: C.muted }}>{k}</span>
                  <span style={{ color: C.text, fontWeight: 600 }}>{v}</span>
                </div>
              ))}
              {!p.marca && !p.cantidad_por_unidad && !p.calidad && !p.color_tinta && (
                <span style={{ fontFamily: 'inherit', fontSize: 13, color: C.muted }}>Sin especificaciones cargadas.</span>
              )}
            </div>
          )}
        </div>

        {/* Related */}
        {related.length > 0 && (
          <div style={{ background: '#F7F8FB', padding: '20px 0 24px' }}>
            <h3 style={{
              fontFamily: 'inherit', fontSize: 14, fontWeight: 800,
              color: C.text, margin: '0 20px 12px', letterSpacing: '-0.01em',
            }}>También te puede interesar</h3>
            <div style={{
              display: 'flex', gap: 12, overflowX: 'auto',
              padding: '0 16px 4px', scrollbarWidth: 'none',
            }}>
              {related.map(r => (
                <button key={r.id} onClick={() => onOpenProduct(r.id)} style={{
                  flexShrink: 0, width: 140, background: '#fff', borderRadius: 14,
                  border: `1px solid ${C.line}`, padding: 10, cursor: 'pointer',
                  textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 8,
                }}>
                  <ProductImage kind={r.kind} tone={r.tone} />
                  <span style={{
                    fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600,
                    color: C.text, lineHeight: 1.2,
                    display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                  }}>{r.name}</span>
                  <span style={{
                    fontFamily: 'inherit', fontSize: 13, fontWeight: 800,
                    color: C.azul, letterSpacing: '-0.01em',
                  }}>{r.stock ? `$${r.price.toLocaleString('es-AR')}` : 'Sin stock'}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Sticky bottom CTA */}
      <div style={{
        position: 'absolute', bottom: 76, left: 0, right: 0, zIndex: 8,
        background: '#fff', borderTop: `1px solid ${C.line}`,
        padding: '12px 16px',
      }}>
        {!outOfStock ? (
          qty > 0 ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{
                display: 'flex', alignItems: 'center',
                background: '#F1F2F6', borderRadius: 999, padding: 4, gap: 4,
              }}>
                <button onClick={() => onRemove(p.id)} style={{
                  ...qtyBtnLg, background: '#fff',
                }}>
                  <Icon.Minus s={16} c={C.text} />
                </button>
                <span style={{
                  fontFamily: 'inherit', fontSize: 15, fontWeight: 700,
                  color: C.text, minWidth: 24, textAlign: 'center',
                }}>{qty}</span>
                <button onClick={() => onAdd(p.id)} style={{
                  ...qtyBtnLg, background: '#fff',
                }}>
                  <Icon.Plus s={16} c={C.text} />
                </button>
              </div>
              <button onClick={onCartClick} style={ctaBtn}>
                Ir al carrito · ${(p.price * qty).toLocaleString('es-AR')}
              </button>
            </div>
          ) : (
            <button onClick={() => onAdd(p.id)} style={ctaBtn}>
              <Icon.Plus s={18} c="#fff" />
              <span style={{ marginLeft: 8 }}>Agregar al carrito</span>
            </button>
          )
        ) : (
          <button onClick={() => onConsult(p)} style={{
            ...ctaBtn, background: C.verde, boxShadow: '0 6px 16px rgba(37,211,102,0.35)',
          }}>
            <svg width="18" height="18" viewBox="0 0 32 32">
              <path d="M16 3C8.8 3 3 8.8 3 16c0 2.3.6 4.5 1.7 6.4L3 29l6.8-1.8A13 13 0 0016 29c7.2 0 13-5.8 13-13S23.2 3 16 3z" fill="#fff"/>
            </svg>
            <span style={{ marginLeft: 8 }}>Consultar por WhatsApp</span>
          </button>
        )}
      </div>
    </div>
  );
}

const chromeBtn = {
  width: 40, height: 40, borderRadius: 999, border: 'none',
  background: '#fff', cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  boxShadow: '0 2px 8px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.04)',
};
const qtyBtnLg = {
  width: 32, height: 32, borderRadius: 999, border: 'none',
  cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
};
const ctaBtn = {
  flex: 1, height: 48, borderRadius: 999, border: 'none',
  background: 'linear-gradient(180deg, #F66218 0%, #E04D00 100%)',
  color: '#fff', cursor: 'pointer',
  fontFamily: 'inherit', fontSize: 14.5, fontWeight: 700,
  letterSpacing: 0.2,
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  boxShadow: '0 6px 16px rgba(240,90,10,0.35)',
};

Object.assign(window, { ProductPage });
