// PDP — Product Detail Page
function PdpScreen({ navigate, addToCart, isMobile, route, user }) {
  const P = window.POP;
  const raw = window.POP_PROD_MAP[route?.id] || window.POP_PRODUCTS[0];

  // Normalize product — fill in safe defaults for fields the schema may not have
  const product = Object.assign({
    sku: raw?.id || '',
    tone: P.cream,
    colors: null,
    specs: null,
    rating: 4.8,
    ratingCount: 0,
    desc: null,
    tag: null,
    stock: null,
    discount: null,
    oldPrice: null,
  }, raw);

  const [qty, setQty] = React.useState(1);
  const [tab, setTab] = React.useState('desc');
  const [imgIdx, setImgIdx] = React.useState(0);
  const [tilt, setTilt] = React.useState({ x: 0, y: 0 });

  // ── Reviews state ─────────────────────────────────────────
  const [reviews, setReviews]         = React.useState(null);   // null = loading
  const [myReview, setMyReview]       = React.useState(undefined);
  const [reviewDraft, setReviewDraft] = React.useState({ rating: 5, comment: '' });
  const [submitting, setSubmitting]   = React.useState(false);
  const [reviewErr, setReviewErr]     = React.useState('');
  const [isVerified, setIsVerified]   = React.useState(false);
  const [editMode, setEditMode]       = React.useState(false);

  const imgRef = React.useRef(null);
  const fmt = n => n.toLocaleString('es-MX');

  // ── Load reviews from Supabase ────────────────────────────
  const loadReviews = React.useCallback(async () => {
    if (!window.sb || !product.id) return;
    const { data } = await window.sb
      .from('reviews')
      .select('id, rating, comment, verified, created_at, user_id, profiles(name)')
      .eq('product_id', product.id)
      .order('created_at', { ascending: false });
    const list = data || [];
    setReviews(list);
    setMyReview(user?.id ? (list.find(r => r.user_id === user.id) || null) : null);
  }, [product.id, user?.id]);

  React.useEffect(() => {
    let alive = true;
    if (!window.sb || !product.id) { setReviews([]); return; }
    window.sb
      .from('reviews')
      .select('id, rating, comment, verified, created_at, user_id, profiles(name)')
      .eq('product_id', product.id)
      .order('created_at', { ascending: false })
      .then(({ data }) => {
        if (!alive) return;
        const list = data || [];
        setReviews(list);
        setMyReview(user?.id ? (list.find(r => r.user_id === user.id) || null) : null);
      });
    return () => { alive = false; };
  }, [product.id, user?.id]);

  // ── Check verified purchase ───────────────────────────────
  React.useEffect(() => {
    if (!window.sb || !user?.id || !product.id) { setIsVerified(false); return; }
    window.sb
      .from('order_items')
      .select('id, orders!inner(status)')
      .eq('product_id', product.id)
      .in('orders.status', ['paid', 'shipped', 'delivered'])
      .limit(1)
      .then(({ data }) => setIsVerified(!!(data?.length)));
  }, [product.id, user?.id]);

  // ── Review submit / delete ────────────────────────────────
  const submitReview = async () => {
    if (!user || submitting) return;
    setSubmitting(true);
    setReviewErr('');
    const { error } = await window.sb.from('reviews').upsert(
      {
        product_id: product.id,
        user_id:    user.id,
        rating:     reviewDraft.rating,
        comment:    reviewDraft.comment.trim() || null,
        verified:   isVerified,
      },
      { onConflict: 'user_id,product_id' }
    );
    setSubmitting(false);
    if (error) { setReviewErr(error.message); return; }
    setEditMode(false);
    await loadReviews();
  };

  const deleteReview = async () => {
    if (!user || !myReview) return;
    await window.sb.from('reviews').delete().eq('id', myReview.id);
    setMyReview(null);
    setReviews(prev => (prev || []).filter(r => r.id !== myReview.id));
  };

  // ── Derived review stats ──────────────────────────────────
  const relativeDate = d => {
    const days = Math.floor((Date.now() - new Date(d).getTime()) / 86400000);
    if (days === 0) return 'Hoy';
    if (days === 1) return 'Ayer';
    if (days < 30)  return `Hace ${days} días`;
    const mo = Math.floor(days / 30);
    if (days < 365) return `Hace ${mo} mes${mo !== 1 ? 'es' : ''}`;
    const yr = Math.floor(days / 365);
    return `Hace ${yr} año${yr !== 1 ? 's' : ''}`;
  };

  const avgRating = reviews?.length
    ? Number(reviews.reduce((s, r) => s + r.rating, 0) / reviews.length).toFixed(1)
    : null;

  const ratingCount = reviews ? reviews.length : (product.ratingCount || 0);

  const distribution = [5, 4, 3, 2, 1].map(s => ({
    stars: s,
    count: reviews?.filter(r => r.rating === s).length ?? 0,
    pct:   reviews?.length
      ? Math.round((reviews.filter(r => r.rating === s).length / reviews.length) * 100)
      : 0,
  }));

  // ── Gallery ───────────────────────────────────────────────
  const realImages = [product.image_url, product.image_url_2].filter(Boolean);
  const swatchColors = [P.cream, P.cream2, P.pink, P.purple];
  const galleryItems = realImages.length > 0
    ? realImages.map(url => ({ type: 'img', url })).concat(
        swatchColors.slice(0, Math.max(0, 4 - realImages.length)).map(c => ({ type: 'swatch', color: c }))
      )
    : swatchColors.map(c => ({ type: 'swatch', color: c }));

  const currentBg = galleryItems[imgIdx]?.type === 'swatch' ? galleryItems[imgIdx].color : P.card;

  const handleMouseMove = (e) => {
    if (isMobile || !imgRef.current) return;
    const r = imgRef.current.getBoundingClientRect();
    const x = ((e.clientX - r.left) / r.width - 0.5) * 8;
    const y = ((e.clientY - r.top) / r.height - 0.5) * -8;
    setTilt({ x: y, y: x });
  };

  const handleAdd = () => {
    const imgEl = imgRef.current;
    const cartEl = document.querySelector('[data-cart-target]');
    if (imgEl && cartEl) window.flyToCart && window.flyToCart(imgEl, cartEl, product.tone);
    for (let i = 0; i < qty; i++) addToCart(product);
  };

  const all = window.POP_PRODUCTS || [];
  const related = all.filter(p => p.category === product.category && p.id !== product.id).slice(0, 4);
  if (related.length < 4) {
    all.filter(p => p.id !== product.id && !related.find(r => r.id === p.id))
      .slice(0, 4 - related.length).forEach(p => related.push(p));
  }

  const derivedSpecs = [
    ['Marca', product.brand || '—'],
    ['Categoría', product.category || '—'],
    ['SKU / ID', product.sku || product.id || '—'],
    ['Precio', `$${fmt(product.price)} ${product.currency || 'MXN'}`],
    ['Disponibilidad', product.in_stock ? 'En stock' : 'Sin stock'],
  ];
  const specs = (product.specs && product.specs.length > 0) ? product.specs : derivedSpecs;

  const tabs = [
    ['desc',    'Descripción'],
    ['specs',   'Specs'],
    ['reviews', `Reseñas${ratingCount > 0 ? ` (${ratingCount})` : ''}`],
    ['ship',    'Envío'],
  ];

  const filledStars = s => Math.round(+(avgRating || 0)) >= s ? '★' : '☆';

  return (
    <div className="pop-page-in" style={{ padding: isMobile ? 16 : 32, overflow: 'hidden' }}>
      {/* Breadcrumb */}
      <div style={{ fontSize: 11, color: P.dim, letterSpacing: 0.5, marginBottom: isMobile ? 14 : 20,
        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
        <span onClick={() => navigate('home')} style={{ cursor: 'pointer', textDecoration: 'underline' }}>Inicio</span>
        {' › '}
        <span onClick={() => navigate('listing', { category: product.category })} style={{ cursor: 'pointer', textDecoration: 'underline' }}>{product.category}</span>
        {' › '}
        <span>{product.name}</span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr', gap: isMobile ? 20 : 40 }}>
        {/* Gallery */}
        <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row-reverse', gap: isMobile ? 12 : 16 }}>
          {/* Main image */}
          <div ref={imgRef} onMouseMove={handleMouseMove} onMouseLeave={() => setTilt({ x: 0, y: 0 })}
            style={{
              flex: 1, position: 'relative', aspectRatio: '1 / 1',
              background: currentBg, borderRadius: isMobile ? 16 : 20,
              border: `3px solid ${P.ink}`, boxShadow: `6px 6px 0 ${P.ink}`,
              overflow: 'hidden',
              transform: `perspective(900px) rotateX(${tilt.x}deg) rotateY(${tilt.y}deg)`,
              transition: 'transform .15s ease-out',
            }}>
            {galleryItems[imgIdx]?.type === 'img' ? (
              <img src={galleryItems[imgIdx].url} alt={product.name}
                style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 20, position: 'absolute', inset: 0 }}
                onError={e => { e.currentTarget.style.display = 'none'; }}
              />
            ) : (
              <>
                <div className="pop-stripes" style={{ position: 'absolute', inset: 0 }}></div>
                <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.4 }}></div>
                <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <div style={{ background: P.card, padding: '10px 16px', borderRadius: 8, border: `2px solid ${P.ink}`,
                    fontFamily: 'ui-monospace, monospace', fontSize: 14, color: P.dim, letterSpacing: 1 }}>{product.sku || product.id}</div>
                </div>
              </>
            )}
            {product.discount > 0 && (
              <div style={{ position: 'absolute', top: isMobile ? 16 : 24, left: isMobile ? 16 : 24 }}>
                <StarBurst size={isMobile ? 72 : 96} fill={P.red} text={`-${product.discount}%`} rotate={-10} />
              </div>
            )}
            <div style={{ position: 'absolute', top: isMobile ? 16 : 24, right: isMobile ? 16 : 24, display: 'flex', gap: 8 }}>
              <div className="pop-press" style={{ width: 40, height: 40, borderRadius: 10, background: P.card,
                border: `2px solid ${P.ink}`, boxShadow: `2px 2px 0 ${P.ink}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>♡</div>
              <div className="pop-press" style={{ width: 40, height: 40, borderRadius: 10, background: P.card,
                border: `2px solid ${P.ink}`, boxShadow: `2px 2px 0 ${P.ink}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center' }}>↗</div>
            </div>
            <div style={{ position: 'absolute', bottom: 16, right: 16, background: P.ink, color: '#ffffff',
              fontFamily: 'ui-monospace, monospace', fontSize: 10, padding: '4px 8px', borderRadius: 4, letterSpacing: 0.5 }}>
              {imgIdx + 1} / {galleryItems.length}
            </div>
          </div>

          {/* Thumbnails */}
          <div style={{ display: 'flex', flexDirection: isMobile ? 'row' : 'column', gap: isMobile ? 8 : 12, overflowX: isMobile ? 'auto' : 'visible' }}>
            {galleryItems.map((item, i) => (
              <div key={i} onClick={() => setImgIdx(i)} className="pop-press"
                style={{
                  width: isMobile ? 60 : 80, height: isMobile ? 60 : 80, borderRadius: 10,
                  background: item.type === 'swatch' ? item.color : P.card,
                  border: `2px solid ${P.ink}`,
                  boxShadow: i === imgIdx ? `inset 3px 3px 0 ${P.ink}80, 3px 3px 0 ${P.ink}` : `3px 3px 0 ${P.ink}`,
                  cursor: 'pointer', flexShrink: 0, position: 'relative', overflow: 'hidden',
                }}>
                {item.type === 'img' ? (
                  <img src={item.url} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 6 }}
                    onError={e => { e.currentTarget.style.display = 'none'; }} />
                ) : (
                  <>
                    <div className="pop-stripes" style={{ position: 'absolute', inset: 0 }}></div>
                    <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'ui-monospace, monospace', fontSize: 8, color: P.dim }}>{`0${i + 1}`}</div>
                  </>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Info */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
            {product.brand && <PopChip color={P.blueLight} size="sm">{product.brand}</PopChip>}
            {product.tag && <PopChip color={P.green} size="sm" style={{ color: P.card }}>{product.tag}</PopChip>}
            {product.discount > 0 && <PopChip color={P.red} size="sm" style={{ color: P.card }}>-{product.discount}%</PopChip>}
            {product.stock > 0 && product.stock < 20 && <PopChip color={P.orange} size="sm" style={{ color: P.card }}>¡SOLO QUEDAN {product.stock}!</PopChip>}
          </div>

          <h1 style={{ fontFamily: P.display, fontSize: isMobile ? 24 : 40, letterSpacing: -1.5, lineHeight: 1.05, margin: 0, wordBreak: 'break-word' }}>{product.name}</h1>

          <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 8 : 14, flexWrap: 'wrap' }}>
            {ratingCount > 0 ? (
              <button onClick={() => setTab('reviews')} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
                <PopRating rating={+avgRating} count={ratingCount} size={14} />
              </button>
            ) : reviews !== null && (
              <button onClick={() => setTab('reviews')} style={{ background: 'none', border: 'none', padding: 0, cursor: 'pointer',
                fontSize: 12, color: P.dim, textDecoration: 'underline', textUnderlineOffset: 3 }}>
                Sin reseñas · Sé el primero
              </button>
            )}
            {product.sku && <>
              <span style={{ fontSize: 12, color: P.dim }}>•</span>
              <span style={{ fontSize: 11, color: P.dim, fontFamily: 'ui-monospace, monospace' }}>{product.sku}</span>
            </>}
            <span style={{ fontSize: 12, color: P.dim }}>•</span>
            <span style={{ fontSize: 12, color: P.green, fontWeight: 700 }}>● En stock</span>
          </div>

          {/* Price block */}
          <div style={{ background: P.yellow, border: `3px solid ${P.ink}`, borderRadius: 16, padding: isMobile ? 16 : 20,
            boxShadow: `5px 5px 0 ${P.ink}`, display: 'flex', alignItems: 'center', gap: 16, flexWrap: 'wrap', minWidth: 0 }}>
            <div style={{ minWidth: 0, flex: '1 1 auto' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
                <div style={{ fontFamily: P.display, fontSize: isMobile ? 32 : 48, letterSpacing: -2, lineHeight: 1, wordBreak: 'break-word' }}>${fmt(product.price)}</div>
                {product.oldPrice && <div style={{ fontSize: 16, color: P.ink2, textDecoration: 'line-through' }}>${fmt(product.oldPrice)}</div>}
              </div>
              <div style={{ fontSize: 11, color: P.ink2, marginTop: 4, fontWeight: 600 }}>
                💳 Hasta 12 cuotas · ${fmt(Math.round(product.price / 12))} / mes
              </div>
            </div>
            {product.discount > 0 && product.oldPrice && (
              <div style={{ background: P.red, color: P.card, padding: '8px 14px', borderRadius: 10,
                border: `2px solid ${P.ink}`, fontFamily: P.display, fontSize: isMobile ? 12 : 14, letterSpacing: 0.5, whiteSpace: 'nowrap' }}>
                AHORRAS ${fmt(product.oldPrice - product.price)}
              </div>
            )}
          </div>

          {/* Quantity + Add */}
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', marginTop: 6 }}>
            <QtyStepper qty={qty} setQty={setQty} size="lg" />
            <PopButton variant="dark" size="lg" onClick={handleAdd} style={{ flex: '1 1 0', minWidth: isMobile ? 180 : 200 }}>
              🛒 Agregar · ${fmt(product.price * qty)}
            </PopButton>
          </div>

          <PopButton variant="primary" size="md" full onClick={() => {
            for (let i = 0; i < qty; i++) addToCart(product);
            navigate('checkout');
          }}>
            ⚡ COMPRAR AHORA
          </PopButton>

          {/* Trust strip */}
          <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 12, padding: 14,
            display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3,1fr)', gap: isMobile ? 10 : 14,
            boxShadow: `3px 3px 0 ${P.ink}` }}>
            {[
              ['🚚', 'Envío gratis', 'Sobre $99K · 24h'],
              ['↩️', 'Devolución', '30 días sin preguntas'],
              ['🛡', 'Garantía', '2 años oficial'],
            ].map(([e, t, s]) => (
              <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{ fontSize: 22 }}>{e}</div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 700 }}>{t}</div>
                  <div style={{ fontSize: 10, color: P.dim }}>{s}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div style={{ marginTop: isMobile ? 32 : 48 }}>
        <div style={{ display: 'flex', gap: 0, borderBottom: `3px solid ${P.ink}`, overflowX: 'auto', scrollbarWidth: 'none' }}>
          {tabs.map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              padding: isMobile ? '10px 12px' : '14px 22px',
              background: tab === k ? P.ink : 'transparent',
              color: tab === k ? '#ffffff' : P.ink,
              fontFamily: P.display, fontSize: isMobile ? 11 : 14, letterSpacing: 0.5,
              cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0,
              borderTopLeftRadius: tab === k ? 10 : 0, borderTopRightRadius: tab === k ? 10 : 0,
              border: tab === k ? `2px solid ${P.ink}` : '2px solid transparent',
              borderBottom: 'none', marginBottom: -3,
            }}>{l}</button>
          ))}
        </div>

        <div style={{ padding: isMobile ? '20px 4px' : '28px 4px', fontSize: 14, lineHeight: 1.7, color: P.ink2, minHeight: 200 }}>

          {/* ── Descripción ── */}
          {tab === 'desc' && (
            <div className="pop-page-in">
              <p style={{ margin: 0, maxWidth: 720 }}>
                {product.desc || `${product.name} — ${product.brand ? product.brand + ' · ' : ''}${product.category}. Producto original con garantía oficial del fabricante. Incluye caja, accesorios y manual.`}
              </p>
              <ul style={{ marginTop: 18, maxWidth: 720, paddingLeft: 18, lineHeight: 1.9 }}>
                <li>Producto original con garantía oficial.</li>
                <li>Compatible con los principales sistemas operativos y estándares del mercado.</li>
                <li>Caja incluye: producto + accesorios + manual + garantía 2 años.</li>
                <li>Despacho en 24h hábiles desde nuestro depósito en Montevideo.</li>
              </ul>
            </div>
          )}

          {/* ── Specs ── */}
          {tab === 'specs' && (
            <div className="pop-page-in" style={{ maxWidth: 720 }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
                <tbody>
                  {specs.map(([k, v]) => (
                    <tr key={k} style={{ borderBottom: `1px dashed ${P.line2}` }}>
                      <td style={{ padding: '12px 8px 12px 0', fontFamily: P.display, fontSize: isMobile ? 10 : 12, letterSpacing: 1,
                        width: isMobile ? '40%' : 200, verticalAlign: 'top', wordBreak: 'break-word' }}>{k.toUpperCase()}</td>
                      <td style={{ padding: '12px 0', fontWeight: 500, color: P.ink, wordBreak: 'break-word', fontSize: isMobile ? 13 : 14 }}>{v}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {/* ── Reseñas ── */}
          {tab === 'reviews' && (
            <div className="pop-page-in" style={{ maxWidth: 900 }}>

              {/* Top row: stats + write form */}
              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '200px 1fr', gap: 24, marginBottom: 28 }}>

                {/* Stats card */}
                <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14,
                  padding: '20px 18px', boxShadow: `3px 3px 0 ${P.ink}`, textAlign: 'center', height: 'fit-content' }}>
                  {reviews === null ? (
                    <div style={{ color: P.dim, fontSize: 13 }}>Cargando...</div>
                  ) : (
                    <>
                      <div style={{ fontFamily: P.display, fontSize: 64, letterSpacing: -3, lineHeight: 1, color: P.ink }}>
                        {ratingCount > 0 ? avgRating : '—'}
                      </div>
                      <div style={{ color: '#f5a200', fontSize: 22, marginTop: 4, letterSpacing: 2 }}>
                        {[1,2,3,4,5].map(s => filledStars(s)).join('')}
                      </div>
                      <div style={{ fontSize: 12, color: P.dim, marginTop: 8 }}>
                        {ratingCount > 0
                          ? `${ratingCount} reseña${ratingCount !== 1 ? 's' : ''}`
                          : 'Sin reseñas aún'}
                      </div>
                      {ratingCount > 0 && (
                        <div style={{ marginTop: 14, textAlign: 'left' }}>
                          {distribution.map(({ stars, count, pct }) => (
                            <div key={stars} style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5, fontSize: 11 }}>
                              <span style={{ width: 8, color: P.dim }}>{stars}</span>
                              <span style={{ color: '#f5a200' }}>★</span>
                              <div style={{ flex: 1, height: 6, background: P.line, borderRadius: 999,
                                border: `1px solid ${P.line2}`, overflow: 'hidden' }}>
                                <div style={{
                                  height: '100%',
                                  background: stars >= 4 ? P.green : stars >= 3 ? P.yellow : P.red,
                                  width: `${pct}%`,
                                  transition: 'width .5s ease',
                                }} />
                              </div>
                              <span style={{ width: 18, textAlign: 'right', color: P.dim }}>{count}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </>
                  )}
                </div>

                {/* Write review / own review */}
                <div>
                  {!user ? (
                    /* Not logged in */
                    <div style={{ background: P.cream, border: `2px solid ${P.ink}`, borderRadius: 14,
                      padding: 24, textAlign: 'center', boxShadow: `3px 3px 0 ${P.ink}` }}>
                      <div style={{ fontSize: 36 }}>✍️</div>
                      <div style={{ fontFamily: P.display, fontSize: 18, marginTop: 10, letterSpacing: -0.5 }}>¿Ya lo compraste?</div>
                      <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>Inicia sesión para dejar tu reseña y ayudar a otros compradores.</div>
                    </div>

                  ) : myReview && !editMode ? (
                    /* User has already reviewed — show it */
                    <div style={{ background: P.yellow, border: `2px solid ${P.ink}`, borderRadius: 14,
                      padding: 20, boxShadow: `3px 3px 0 ${P.ink}` }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                        <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1 }}>TU RESEÑA</div>
                        <div style={{ display: 'flex', gap: 8 }}>
                          <PopButton variant="secondary" size="sm" onClick={() => {
                            setReviewDraft({ rating: myReview.rating, comment: myReview.comment || '' });
                            setEditMode(true);
                          }}>✏ Editar</PopButton>
                          <PopButton variant="danger" size="sm" onClick={deleteReview}>🗑</PopButton>
                        </div>
                      </div>
                      <div style={{ color: '#f5a200', fontSize: 18 }}>
                        {'★'.repeat(myReview.rating)}{'☆'.repeat(5 - myReview.rating)}
                      </div>
                      {myReview.comment && (
                        <div style={{ fontSize: 13, color: P.ink2, marginTop: 10, lineHeight: 1.6 }}>{myReview.comment}</div>
                      )}
                      {myReview.verified && (
                        <div style={{ fontSize: 10, color: P.green, marginTop: 10, fontWeight: 700 }}>✓ Compra verificada</div>
                      )}
                    </div>

                  ) : (
                    /* Review form (new or edit) */
                    <div style={{ background: P.cream, border: `2px solid ${P.ink}`, borderRadius: 14,
                      padding: 20, boxShadow: `3px 3px 0 ${P.ink}` }}>
                      <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5, marginBottom: 16 }}>
                        {editMode ? '✏ EDITAR TU RESEÑA' : '✍️ ESCRIBIR RESEÑA'}
                      </div>

                      {/* Star picker */}
                      <div style={{ marginBottom: 16 }}>
                        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, color: P.dim, marginBottom: 8 }}>CALIFICACIÓN</div>
                        <div style={{ display: 'flex', gap: 2 }}>
                          {[1, 2, 3, 4, 5].map(s => (
                            <button key={s}
                              onClick={() => setReviewDraft(d => ({ ...d, rating: s }))}
                              onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.2)'}
                              onMouseLeave={e => e.currentTarget.style.transform = 'scale(1)'}
                              style={{
                                fontSize: 32, background: 'none', border: 'none', cursor: 'pointer', padding: '0 3px',
                                color: s <= reviewDraft.rating ? '#f5a200' : P.line2,
                                transform: 'scale(1)', transition: 'all .1s',
                              }}>★</button>
                          ))}
                          <span style={{ alignSelf: 'center', marginLeft: 8, fontSize: 13, fontWeight: 700 }}>
                            {['', 'Malo', 'Regular', 'Bueno', 'Muy bueno', 'Excelente'][reviewDraft.rating]}
                          </span>
                        </div>
                      </div>

                      {/* Comment textarea */}
                      <div style={{ marginBottom: 16 }}>
                        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1, color: P.dim, marginBottom: 8 }}>COMENTARIO <span style={{ fontWeight: 400 }}>(opcional)</span></div>
                        <textarea
                          value={reviewDraft.comment}
                          onChange={e => setReviewDraft(d => ({ ...d, comment: e.target.value }))}
                          placeholder="¿Qué te pareció el producto? ¿Lo recomendarías?"
                          rows={4}
                          style={{
                            width: '100%', boxSizing: 'border-box', padding: '10px 12px',
                            border: `2px solid ${P.ink}`, borderRadius: 10,
                            fontFamily: P.font, fontSize: 13, lineHeight: 1.6, resize: 'vertical',
                            background: P.card, outline: 'none', color: P.ink,
                          }}
                        />
                      </div>

                      {isVerified && (
                        <div style={{ fontSize: 11, color: P.green, fontWeight: 700, marginBottom: 12 }}>
                          ✓ Tu reseña se publicará como compra verificada
                        </div>
                      )}
                      {reviewErr && (
                        <div style={{ fontSize: 12, color: P.red, marginBottom: 12, padding: '8px 12px',
                          background: '#fff0f0', border: `1px solid ${P.red}`, borderRadius: 8 }}>{reviewErr}</div>
                      )}

                      <div style={{ display: 'flex', gap: 10 }}>
                        <PopButton variant="dark" size="md" onClick={submitReview}
                          style={{ flex: 1, opacity: submitting ? 0.6 : 1, pointerEvents: submitting ? 'none' : 'auto' }}>
                          {submitting ? '⏳ Publicando...' : (editMode ? '💾 Guardar cambios' : '🚀 Publicar reseña')}
                        </PopButton>
                        {editMode && (
                          <PopButton variant="secondary" size="md" onClick={() => setEditMode(false)}>Cancelar</PopButton>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Reviews list */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {reviews === null ? (
                  /* Loading skeleton */
                  [1, 2, 3].map(i => (
                    <div key={i} style={{ background: P.card, border: `2px solid ${P.line}`, borderRadius: 12,
                      padding: 18, opacity: 0.5 + i * 0.15 }}>
                      <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 12 }}>
                        <div style={{ width: 34, height: 34, borderRadius: '50%', background: P.line }} />
                        <div>
                          <div style={{ height: 12, width: 90, background: P.line, borderRadius: 4, marginBottom: 6 }} />
                          <div style={{ height: 10, width: 60, background: P.line, borderRadius: 4 }} />
                        </div>
                      </div>
                      <div style={{ height: 12, width: '85%', background: P.line, borderRadius: 4, marginBottom: 6 }} />
                      <div style={{ height: 12, width: '65%', background: P.line, borderRadius: 4 }} />
                    </div>
                  ))
                ) : reviews.filter(r => r.user_id !== user?.id).length === 0 ? (
                  <div style={{ textAlign: 'center', padding: '40px 16px', color: P.dim,
                    background: P.card, border: `2px dashed ${P.line2}`, borderRadius: 14 }}>
                    <div style={{ fontSize: 40 }}>💬</div>
                    <div style={{ fontFamily: P.display, fontSize: 20, marginTop: 12, color: P.ink }}>
                      {user ? (myReview ? '¡Gracias por tu reseña!' : 'Sé el primero en reseñar') : 'Sin reseñas aún'}
                    </div>
                    <div style={{ fontSize: 13, marginTop: 6 }}>
                      {user && !myReview ? 'Comparte tu experiencia con este producto.' : 'Este producto aún no tiene reseñas de otros usuarios.'}
                    </div>
                  </div>
                ) : (
                  reviews.filter(r => r.user_id !== user?.id).map(r => {
                    const name = r.profiles?.name || 'Usuario';
                    const initial = name[0].toUpperCase();
                    const avatarColors = [P.pink, P.blueLight, P.purple, P.green, P.orange];
                    const avatarColor = avatarColors[initial.charCodeAt(0) % avatarColors.length];
                    return (
                      <div key={r.id} style={{ background: P.card, border: `2px solid ${P.ink}`,
                        borderRadius: 12, padding: 18, boxShadow: `3px 3px 0 ${P.ink}` }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 10 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <div style={{ width: 34, height: 34, borderRadius: '50%', background: avatarColor,
                              border: `2px solid ${P.ink}`, display: 'flex', alignItems: 'center',
                              justifyContent: 'center', fontWeight: 900, fontSize: 14, flexShrink: 0 }}>
                              {initial}
                            </div>
                            <div>
                              <div style={{ fontWeight: 700, fontSize: 13 }}>{name}</div>
                              <div style={{ fontSize: 10, color: P.dim }}>{relativeDate(r.created_at)}</div>
                            </div>
                          </div>
                          <div style={{ color: '#f5a200', fontSize: 14, letterSpacing: 1 }}>
                            {'★'.repeat(r.rating)}{'☆'.repeat(5 - r.rating)}
                          </div>
                        </div>
                        {r.comment && (
                          <div style={{ fontSize: 13, color: P.ink2, lineHeight: 1.65 }}>{r.comment}</div>
                        )}
                        {r.verified && (
                          <div style={{ fontSize: 10, color: P.green, marginTop: 10, fontWeight: 700,
                            display: 'flex', alignItems: 'center', gap: 4 }}>
                            <span>✓</span> Compra verificada
                          </div>
                        )}
                      </div>
                    );
                  })
                )}
              </div>
            </div>
          )}

          {/* ── Envío ── */}
          {tab === 'ship' && (
            <div className="pop-page-in" style={{ maxWidth: 720, display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5, marginBottom: 6 }}>🚚 ENVÍO</div>
                <div>Envío gratis en compras sobre $99.000. Despacho en 24h hábiles.</div>
                <ul style={{ marginTop: 8, paddingLeft: 18, lineHeight: 1.8 }}>
                  <li>Montevideo: 24–48h</li>
                  <li>Interior del país: 2–4 días</li>
                  <li>Internacional: 5–7 días</li>
                </ul>
              </div>
              <div>
                <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5, marginBottom: 6 }}>↩️ DEVOLUCIONES</div>
                <div>Tienes 30 días desde la entrega para devolver el producto sin preguntas. Reembolso al mismo método de pago en 5 días hábiles.</div>
              </div>
              <div>
                <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5, marginBottom: 6 }}>🛡 GARANTÍA</div>
                <div>2 años de garantía oficial del fabricante. MAGIC CELL PRO extiende a 3 años.</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Related */}
      {related.length > 0 && (
        <div style={{ marginTop: isMobile ? 32 : 48 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18, flexWrap: 'wrap' }}>
            <div className="pop-press" style={{ background: P.pink, border: `2px solid ${P.ink}`, padding: '6px 12px', borderRadius: 8,
              fontFamily: P.display, fontSize: 12, letterSpacing: 1, boxShadow: `2px 2px 0 ${P.ink}` }}>👀 TAMBIÉN TE GUSTARÍA</div>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 22 : 28, letterSpacing: -1 }}>Productos similares</div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(5,1fr)', gap: isMobile ? 12 : 12 }}>
            {related.map(p => (
              <ProductCard key={p.id} product={p} onClick={() => { navigate('pdp', { id: p.id }); setQty(1); }} onAddToCart={addToCart} />
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.PdpScreen = PdpScreen;
