// post.jsx — Página de Conteúdo Individual SX
const { useState, useEffect, useCallback } = React;

const CHECKOUT_URL = '/';

// ─── Utilitários ─────────────────────────────────────────────────────────────

function fmtDate(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  if (isNaN(d.getTime())) return '';
  return d.toLocaleDateString('pt-BR', { day: 'numeric', month: 'long', year: 'numeric' });
}

function extractMediaId(html) {
  const m = (html || '').match(/mediaId=(\d+)/);
  return m ? m[1] : null;
}

function stripHtml(html) {
  return (html || '').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').trim();
}

const TIPO_COLORS = {
  'Sexy Girls':              { bg: 'rgba(255,22,117,0.12)',  color: '#FF1675', border: 'rgba(255,22,117,0.3)' },
  'Revista Sexy':            { bg: 'rgba(255,22,117,0.12)',  color: '#FF1675', border: 'rgba(255,22,117,0.3)' },
  'Episódios Papo com Pijama':{ bg: 'rgba(123,63,242,0.12)', color: '#9A65F5', border: 'rgba(123,63,242,0.3)' },
  'Papo com Pijama Hot':     { bg: 'rgba(255,138,0,0.12)',   color: '#FF8A00', border: 'rgba(255,138,0,0.3)' },
  'Papo na Banheira':        { bg: 'rgba(0,194,255,0.12)',   color: '#00C2FF', border: 'rgba(0,194,255,0.3)' },
  'Episódios Casa das Pimentinhas 10': { bg: 'rgba(255,22,117,0.12)', color: '#FF1675', border: 'rgba(255,22,117,0.3)' },
};

function tipoBadgeStyle(tipo) {
  return TIPO_COLORS[tipo] || { bg: 'rgba(255,255,255,0.06)', color: '#9999B2', border: 'rgba(255,255,255,0.1)' };
}

// ─── NavBar ───────────────────────────────────────────────────────────────────

function NavBar({ tipo }) {
  return (
    <div className="nav-back">
      <a
        href="/"
        style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#9999B2', fontSize: '13px', fontWeight: 500, transition: 'color 0.15s' }}
        onMouseOver={e => e.currentTarget.style.color = '#EFEFEF'}
        onMouseOut={e => e.currentTarget.style.color = '#9999B2'}
      >
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M19 12H5M12 5l-7 7 7 7"/>
        </svg>
        Voltar
      </a>
      <span style={{ width: '1px', height: '16px', background: 'rgba(255,255,255,0.1)' }}/>
      <span style={{ fontSize: '13px', color: '#55556A' }}>
        <span style={{ color: '#7B3FF2' }}>SX</span>
        {tipo ? ` · ${tipo}` : ''}
      </span>
    </div>
  );
}

// ─── Hero ─────────────────────────────────────────────────────────────────────

function PostHero({ post }) {
  const badge = tipoBadgeStyle(post.tipo);
  return (
    <div style={{ position: 'relative', minHeight: '520px', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', inset: 0, background: post.gradient }}/>
      {post.capa && (
        <img
          src={post.capa}
          alt={post.title}
          onError={e => e.target.style.display = 'none'}
          style={{
            position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', objectPosition: 'center 20%',
          }}
        />
      )}

      {/* Overlay */}
      <div style={{
        position: 'absolute', inset: 0,
        background: post.capa
          ? 'linear-gradient(to top, rgba(10,10,15,1) 0%, rgba(10,10,15,0.7) 40%, rgba(10,10,15,0.2) 100%)'
          : 'linear-gradient(to top, rgba(10,10,15,0.98) 0%, rgba(10,10,15,0.5) 100%)',
      }}/>

      {/* Grid overlay */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'linear-gradient(rgba(255,255,255,0.02) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.02) 1px, transparent 1px)',
        backgroundSize: '40px 40px',
      }}/>

      {/* Conteúdo */}
      <div style={{
        position: 'relative', zIndex: 1,
        padding: '120px 40px 48px',
        maxWidth: '900px',
      }}>
        {/* Tipo badge */}
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: '6px',
          fontSize: '10px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase',
          padding: '4px 12px', borderRadius: '9999px', marginBottom: '16px',
          background: badge.bg, color: badge.color, border: `1px solid ${badge.border}`,
        }}>
          {post.tipo || 'Conteúdo'}
        </div>

        {/* Título */}
        <h1 className="hero-title" style={{
          fontFamily: "'Space Grotesk', sans-serif", fontWeight: 700,
          fontSize: 'clamp(28px, 4vw, 56px)', color: '#EFEFEF', lineHeight: 1.1,
          letterSpacing: '-0.02em', marginBottom: '16px',
        }}>
          {stripHtml(post.title)}
        </h1>

        {/* Meta */}
        <div style={{ display: 'flex', gap: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
          {post.date && (
            <span style={{ fontSize: '13px', color: '#55556A' }}>{fmtDate(post.date)}</span>
          )}
          {post.modelos && post.modelos.length > 0 && (
            <>
              <span style={{ width: '3px', height: '3px', borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'inline-block' }}/>
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {post.modelos.map(m => (
                  <a
                    key={m.slug}
                    href={`/modelos/${m.slug}`}
                    style={{
                      fontSize: '12px', fontWeight: 500, color: '#9A65F5',
                      padding: '3px 10px', borderRadius: '9999px',
                      background: 'rgba(123,63,242,0.12)', border: '1px solid rgba(123,63,242,0.25)',
                      transition: 'all 0.15s',
                    }}
                    onMouseOver={e => { e.currentTarget.style.background = 'rgba(123,63,242,0.25)'; e.currentTarget.style.color = '#EFEFEF'; }}
                    onMouseOut={e => { e.currentTarget.style.background = 'rgba(123,63,242,0.12)'; e.currentTarget.style.color = '#9A65F5'; }}
                  >
                    {m.nome}
                  </a>
                ))}
              </div>
            </>
          )}
          {post.n_membros > 0 && (
            <>
              <span style={{ width: '3px', height: '3px', borderRadius: '50%', background: 'rgba(255,255,255,0.2)', display: 'inline-block' }}/>
              <span style={{ fontSize: '12px', color: '#FF8A00' }}>
                +{post.n_membros} fotos exclusivas
              </span>
            </>
          )}
        </div>

        {/* Descrição */}
        {post.desc && (
          <p style={{
            marginTop: '16px', fontSize: '15px', lineHeight: 1.6, color: '#9999B2',
            maxWidth: '600px',
          }}>
            {post.desc}
          </p>
        )}
      </div>
    </div>
  );
}

// ─── Lightbox ─────────────────────────────────────────────────────────────────

function Lightbox({ images, index, onClose, onPrev, onNext }) {
  useEffect(() => {
    function handleKey(e) {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') onPrev();
      if (e.key === 'ArrowRight') onNext();
    }
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [onClose, onPrev, onNext]);

  return (
    <div className="lightbox-overlay" onClick={onClose}>
      {/* Prev */}
      <button
        onClick={e => { e.stopPropagation(); onPrev(); }}
        style={{
          position: 'absolute', left: '16px', top: '50%', transform: 'translateY(-50%)',
          background: 'rgba(255,255,255,0.08)', border: 'none', borderRadius: '50%',
          width: '44px', height: '44px', cursor: 'pointer', color: '#EFEFEF',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M15 18l-6-6 6-6"/></svg>
      </button>

      <img src={images[index]} alt="" onClick={e => e.stopPropagation()}/>

      {/* Next */}
      <button
        onClick={e => { e.stopPropagation(); onNext(); }}
        style={{
          position: 'absolute', right: '16px', top: '50%', transform: 'translateY(-50%)',
          background: 'rgba(255,255,255,0.08)', border: 'none', borderRadius: '50%',
          width: '44px', height: '44px', cursor: 'pointer', color: '#EFEFEF',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M9 18l6-6-6-6"/></svg>
      </button>

      {/* Counter */}
      <div style={{
        position: 'absolute', bottom: '20px', left: '50%', transform: 'translateX(-50%)',
        fontSize: '12px', color: 'rgba(255,255,255,0.5)',
      }}>
        {index + 1} / {images.length}
      </div>

      {/* Close */}
      <button
        onClick={onClose}
        style={{
          position: 'absolute', top: '16px', right: '16px',
          background: 'rgba(255,255,255,0.08)', border: 'none', borderRadius: '50%',
          width: '40px', height: '40px', cursor: 'pointer', color: '#EFEFEF',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}
      >
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
      </button>
    </div>
  );
}

// ─── Galeria de Fotos ─────────────────────────────────────────────────────────

const PHANTOM_GRADIENTS = [
  'linear-gradient(160deg, #2a0040 0%, #0a0015 100%)',
  'linear-gradient(160deg, #200030 0%, #0a0010 100%)',
  'linear-gradient(160deg, #1a0028 0%, #050010 100%)',
];

const INPUT_STYLE = {
  width: '100%', boxSizing: 'border-box',
  background: 'rgba(255,255,255,0.05)',
  border: '1px solid rgba(255,255,255,0.1)',
  borderRadius: '8px', padding: '10px 14px',
  color: '#EFEFEF', fontSize: '14px', fontFamily: "'Inter', sans-serif",
  outline: 'none', transition: 'border-color 0.15s',
};

function PhotoGallery({ images, membrosImages, nMembros, nVip, leadState, onShowForm, onLeadSubmit, leadForm, setLeadForm, leadLoading, leadError, onSubscribe, isSubscriber, onGoToWp, projeto }) {
  const [lightboxIdx, setLightboxIdx] = useState(null);
  const freeImages = images.slice(0, 3);
  const extraImages = (membrosImages || []).slice(0, 3);
  const totalExclusive = (nMembros || 0) + (nVip || 0);
  const remainingExclusive = nVip || 0;
  const unlockedWithExtras = leadState === 'unlocked' && extraImages.length > 0;
  const allImages = unlockedWithExtras ? [...freeImages, ...extraImages] : freeImages;
  const badgeCount = unlockedWithExtras ? remainingExclusive : totalExclusive;

  const openLightbox = useCallback((i) => setLightboxIdx(i), []);
  const closeLightbox = useCallback(() => setLightboxIdx(null), []);
  const prevImg = useCallback(() => setLightboxIdx(i => (i - 1 + allImages.length) % allImages.length), [allImages.length]);
  const nextImg = useCallback(() => setLightboxIdx(i => (i + 1) % allImages.length), [allImages.length]);

  return (
    <div>
      {/* Label */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
        <div style={{ fontSize: '11px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#55556A' }}>
          PRÉVIA GRATUITA — {freeImages.length} {freeImages.length === 1 ? 'FOTO' : 'FOTOS'}
        </div>
        {badgeCount > 0 && (
          <div style={{
            fontSize: '11px', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
            color: '#9A65F5', display: 'flex', alignItems: 'center', gap: '5px',
          }}>
            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <rect x="3" y="11" width="18" height="11" rx="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
            +{badgeCount} EXCLUSIVAS
          </div>
        )}
      </div>

      {/* Grid de fotos livres */}
      <div className="gallery-grid" style={{ gap: '3px' }}>
        {freeImages.map((src, i) => (
          <div
            key={i}
            className="gallery-item"
            onClick={() => openLightbox(i)}
            style={{ aspectRatio: '4/3', cursor: 'zoom-in' }}
          >
            <img src={src} alt={`Foto ${i + 1}`} loading="lazy"/>
            <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0)', transition: 'background 0.2s' }}
              onMouseOver={e => e.currentTarget.style.background = 'rgba(123,63,242,0.12)'}
              onMouseOut={e => e.currentTarget.style.background = 'rgba(0,0,0,0)'}
            />
          </div>
        ))}
      </div>

      {/* Funil de lead + upsell */}
      {leadState === 'unlocked' ? (
        /* ── Estado desbloqueado: sucesso + upsell de assinatura ── */
        <div style={{ marginTop: '12px' }}>
          {/* Banner de sucesso */}
          <div style={{
            display: 'flex', alignItems: 'center', gap: '10px',
            padding: '12px 16px', borderRadius: '10px', marginBottom: '12px',
            background: 'rgba(0,200,100,0.07)', border: '1px solid rgba(0,200,100,0.2)',
          }}>
            <div style={{
              width: '28px', height: '28px', borderRadius: '50%', flexShrink: 0,
              background: 'rgba(0,200,100,0.15)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#00C864" strokeWidth="3">
                <path d="M20 6L9 17l-5-5"/>
              </svg>
            </div>
            <div style={{ fontSize: '13px', color: '#9999B2' }}>
              <span style={{ color: '#EFEFEF', fontWeight: 600 }}>Prévia desbloqueada!</span>
              {' '}{extraImages.length > 0 ? `Confira as +${extraImages.length} fotos liberadas abaixo.` : 'Confira o ensaio completo sendo assinante.'}
            </div>
          </div>

          {/* Grid das fotos extra liberadas pelo cadastro */}
          {extraImages.length > 0 && (
            <div className="gallery-grid" style={{ gap: '3px', marginBottom: '12px' }}>
              {extraImages.map((src, i) => (
                <div
                  key={i}
                  className="gallery-item"
                  onClick={() => openLightbox(freeImages.length + i)}
                  style={{ aspectRatio: '4/3', cursor: 'zoom-in' }}
                >
                  <img src={src} alt={`Foto ${freeImages.length + i + 1}`} loading="lazy"/>
                  <div style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0)', transition: 'background 0.2s' }}
                    onMouseOver={e => e.currentTarget.style.background = 'rgba(123,63,242,0.12)'}
                    onMouseOut={e => e.currentTarget.style.background = 'rgba(0,0,0,0)'}
                  />
                </div>
              ))}
            </div>
          )}

          {/* Upsell exclusivo — usa apenas VIP quando as fotos de membros já foram liberadas acima; cai no total (fallback) se este post não tiver membros_images cadastrado */}
          {(extraImages.length > 0 ? remainingExclusive : totalExclusive) > 0 && (
            <div style={{
              borderRadius: '12px', overflow: 'hidden',
              border: '1px solid rgba(123,63,242,0.35)',
              boxShadow: '0 0 30px rgba(123,63,242,0.08)',
            }}>
              {/* Mini grade fantasma desfocada */}
              <div className="gallery-grid" style={{ gap: '2px', filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none' }}>
                {[0,1,2].map(i => (
                  <div key={i} style={{ aspectRatio: '4/3', background: PHANTOM_GRADIENTS[i], position: 'relative', overflow: 'hidden' }}>
                    <div style={{ position: 'absolute', inset: 0, backgroundImage: 'radial-gradient(ellipse at 50% 30%, rgba(123,63,242,0.2) 0%, transparent 70%)' }}/>
                  </div>
                ))}
              </div>
              {/* CTA de assinatura */}
              <div style={{
                padding: '20px 24px', background: '#0A0A0F',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', flexWrap: 'wrap',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                  <div style={{
                    width: '36px', height: '36px', borderRadius: '50%', flexShrink: 0,
                    background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                      <rect x="3" y="11" width="18" height="11" rx="2"/>
                      <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                    </svg>
                  </div>
                  <div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: '#EFEFEF', fontFamily: "'Space Grotesk', sans-serif" }}>
                      {isSubscriber ? 'Você já é um assinante SX' : `+${extraImages.length > 0 ? remainingExclusive : totalExclusive} fotos exclusivas`}
                    </div>
                    <div style={{ fontSize: '12px', color: '#9999B2', marginTop: '2px' }}>
                      {isSubscriber ? 'Veja esse conteúdo completo' : 'Ensaio completo disponível para assinantes'}
                    </div>
                  </div>
                </div>
                {isSubscriber && (
                  <button
                    onClick={onGoToWp}
                    style={{
                      background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                      border: 'none', borderRadius: '9999px', color: '#fff',
                      fontSize: '13px', fontWeight: 600, fontFamily: "'Inter', sans-serif",
                      padding: '10px 20px', cursor: 'pointer', whiteSpace: 'nowrap',
                      boxShadow: '0 0 16px rgba(123,63,242,0.4)',
                    }}
                  >
                    Ver conteúdo completo
                  </button>
                )}
              </div>
            </div>
          )}
        </div>
      ) : (
        /* ── Estado locked / form: grade fantasma com overlay ── */
        <div style={{ position: 'relative', marginTop: '3px' }}>
          {/* Cards fantasma desfocados */}
          <div className="gallery-grid" style={{ gap: '3px', filter: 'blur(3px)', pointerEvents: 'none', userSelect: 'none' }}>
            {[0,1,2].map(i => (
              <div key={i} style={{ aspectRatio: '4/3', background: PHANTOM_GRADIENTS[i], position: 'relative', overflow: 'hidden' }}>
                <div style={{ position: 'absolute', inset: 0, backgroundImage: 'radial-gradient(ellipse at 50% 30%, rgba(123,63,242,0.15) 0%, transparent 70%)' }}/>
              </div>
            ))}
          </div>

          {/* Overlay gradiente */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(to bottom, rgba(10,10,15,0.1) 0%, rgba(10,10,15,0.6) 35%, rgba(10,10,15,0.97) 70%)',
            pointerEvents: 'none',
          }}/>

          {/* Conteúdo sobre o overlay */}
          <div style={{
            position: 'absolute', inset: 0,
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end',
            padding: '16px', paddingBottom: '20px',
          }}>
            {leadState === 'locked' ? (
              /* ── CTA para abrir formulário ── */
              <div style={{ textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '8px' }}>
                <div style={{
                  width: '40px', height: '40px', borderRadius: '50%',
                  background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  boxShadow: '0 0 20px rgba(123,63,242,0.5)',
                }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
                    <rect x="3" y="11" width="18" height="11" rx="2"/>
                    <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                  </svg>
                </div>
                <div style={{ fontSize: '18px', fontWeight: 700, fontFamily: "'Space Grotesk', sans-serif", color: '#EFEFEF' }}>
                  +{nMembros || totalExclusive} fotos de prévia grátis
                </div>
                <div style={{ fontSize: '12px', color: '#9999B2' }}>
                  Cadastre-se gratuitamente para desbloquear
                </div>
                <button
                  onClick={onShowForm}
                  style={{
                    background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                    border: 'none', borderRadius: '9999px', color: '#fff',
                    fontSize: '13px', fontWeight: 600, fontFamily: "'Inter', sans-serif",
                    padding: '10px 24px', cursor: 'pointer',
                    boxShadow: '0 0 16px rgba(123,63,242,0.4)',
                    marginTop: '4px',
                  }}
                >
                  Desbloquear grátis
                </button>
              </div>
            ) : (
              /* ── Formulário de lead ── */
              <form
                onSubmit={onLeadSubmit}
                style={{
                  width: '100%', maxWidth: '360px',
                  background: 'rgba(10,10,15,0.92)',
                  border: '1px solid rgba(123,63,242,0.3)',
                  borderRadius: '14px', padding: '20px',
                  backdropFilter: 'blur(12px)',
                  display: 'flex', flexDirection: 'column', gap: '10px',
                }}
              >
                <div style={{ textAlign: 'center', marginBottom: '4px' }}>
                  <div style={{ fontSize: '15px', fontWeight: 700, color: '#EFEFEF', fontFamily: "'Space Grotesk', sans-serif" }}>
                    Desbloquear fotos de prévia
                  </div>
                  <div style={{ fontSize: '12px', color: '#9999B2', marginTop: '4px' }}>
                    Grátis — sem cartão de crédito
                  </div>
                </div>
                <input
                  type="text" placeholder="Seu nome" required
                  value={leadForm.nome}
                  onChange={e => setLeadForm({ ...leadForm, nome: e.target.value })}
                  style={INPUT_STYLE}
                  onFocus={e => e.target.style.borderColor = 'rgba(123,63,242,0.6)'}
                  onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.1)'}
                />
                <input
                  type="email" placeholder="E-mail" required
                  value={leadForm.email}
                  onChange={e => setLeadForm({ ...leadForm, email: e.target.value })}
                  style={INPUT_STYLE}
                  onFocus={e => e.target.style.borderColor = 'rgba(123,63,242,0.6)'}
                  onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.1)'}
                />
                <input
                  type="tel" placeholder="WhatsApp (ex: 11 91234-5678)" required
                  value={leadForm.whatsapp}
                  onChange={e => setLeadForm({ ...leadForm, whatsapp: e.target.value })}
                  style={INPUT_STYLE}
                  onFocus={e => e.target.style.borderColor = 'rgba(123,63,242,0.6)'}
                  onBlur={e => e.target.style.borderColor = 'rgba(255,255,255,0.1)'}
                />
                {leadError && (
                  <div style={{ fontSize: '12px', color: '#FF6B6B', textAlign: 'center' }}>{leadError}</div>
                )}
                <button
                  type="submit"
                  disabled={leadLoading}
                  style={{
                    background: leadLoading ? 'rgba(123,63,242,0.5)' : 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                    border: 'none', borderRadius: '9999px', color: '#fff',
                    fontSize: '13px', fontWeight: 600, fontFamily: "'Inter', sans-serif",
                    padding: '11px 24px', cursor: leadLoading ? 'not-allowed' : 'pointer',
                    boxShadow: '0 0 16px rgba(123,63,242,0.4)',
                    transition: 'opacity 0.15s',
                  }}
                >
                  {leadLoading ? 'Desbloqueando...' : 'Desbloquear agora →'}
                </button>
              </form>
            )}
          </div>
        </div>
      )}

      {!isSubscriber && (
        <DualPlanCard individualSlug={projeto} title={null} />
      )}

      {lightboxIdx !== null && (
        <Lightbox
          images={allImages}
          index={lightboxIdx}
          onClose={closeLightbox}
          onPrev={prevImg}
          onNext={nextImg}
        />
      )}
    </div>
  );
}

// ─── Player de Vídeo ─────────────────────────────────────────────────────────

function VideoPlayer({ videoHtml, onSubscribe, isSubscriber, onGoToWp, projeto }) {
  const mediaId = extractMediaId(videoHtml);
  if (!mediaId) return null;

  const src = `https://player.mais.uol.com.br/?related=false&autoplay=false&startHd=1080p&mediaId=${mediaId}`;

  return (
    <div>
      {/* Label com indicação de prévia */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
        <div style={{ fontSize: '11px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#55556A' }}>
          PRÉVIA GRATUITA
        </div>
        <div style={{
          fontSize: '11px', fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase',
          color: '#9A65F5', display: 'flex', alignItems: 'center', gap: '5px',
        }}>
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
            <rect x="3" y="11" width="18" height="11" rx="2"/>
            <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
          </svg>
          VERSÃO COMPLETA EXCLUSIVA
        </div>
      </div>

      {/* Player */}
      <div className="uol-player">
        <iframe src={src} allowFullScreen title="Vídeo gratuito"/>
      </div>

      {/* Teaser de vídeo completo — sempre exibido */}
      <LockedVideoTeaser onSubscribe={onSubscribe} isSubscriber={isSubscriber} onGoToWp={onGoToWp} projeto={projeto} />
    </div>
  );
}

// Teaser visual após vídeo gratuito
function LockedVideoTeaser({ onSubscribe, isSubscriber, onGoToWp, projeto }) {
  return (
    <div style={{ position: 'relative', marginTop: '3px' }}>
      {/* Background: simula tela de vídeo bloqueada */}
      <div style={{
        width: '100%', aspectRatio: '16/9', borderRadius: '0 0 12px 12px',
        background: 'linear-gradient(160deg, #1a0030 0%, #0a000f 60%, #050008 100%)',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Scan lines decorativas */}
        <div style={{
          position: 'absolute', inset: 0,
          backgroundImage: 'repeating-linear-gradient(0deg, transparent, transparent 2px, rgba(255,255,255,0.015) 2px, rgba(255,255,255,0.015) 4px)',
        }}/>
        {/* Radial glow */}
        <div style={{
          position: 'absolute', inset: 0,
          background: 'radial-gradient(ellipse at 50% 50%, rgba(123,63,242,0.2) 0%, transparent 65%)',
        }}/>

        {/* Conteúdo central */}
        <div style={{
          position: 'absolute', inset: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
          gap: '12px', textAlign: 'center', padding: '20px',
        }}>
          {/* Ícone play locked */}
          <div style={{ position: 'relative' }}>
            <div style={{
              width: '56px', height: '56px', borderRadius: '50%',
              background: 'rgba(255,255,255,0.06)', border: '2px solid rgba(255,255,255,0.12)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#9999B2" strokeWidth="1.5">
                <polygon points="5 3 19 12 5 21 5 3"/>
              </svg>
            </div>
            {/* Lock badge */}
            <div style={{
              position: 'absolute', bottom: '-4px', right: '-4px',
              width: '22px', height: '22px', borderRadius: '50%',
              background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3">
                <rect x="3" y="11" width="18" height="11" rx="2"/>
                <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
              </svg>
            </div>
          </div>

          <div>
            <div style={{ fontSize: '16px', fontWeight: 700, fontFamily: "'Space Grotesk', sans-serif", color: '#EFEFEF', marginBottom: '4px' }}>
              {isSubscriber ? 'Você já é um assinante SX' : 'Versão Completa — Exclusiva SX'}
            </div>
            <div style={{ fontSize: '12px', color: '#9999B2' }}>
              {isSubscriber ? 'Veja esse conteúdo completo' : 'Conteúdo completo disponível apenas para assinantes'}
            </div>
          </div>

          {isSubscriber && (
            <button
              onClick={onGoToWp}
              style={{
                background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
                border: 'none', borderRadius: '9999px', color: '#fff',
                fontSize: '13px', fontWeight: 600, fontFamily: "'Inter', sans-serif",
                padding: '10px 24px', cursor: 'pointer',
                boxShadow: '0 0 20px rgba(123,63,242,0.4)',
              }}
            >
              Ver conteúdo completo
            </button>
          )}
        </div>
      </div>
      {!isSubscriber && (
        <DualPlanCard individualSlug={projeto} title={null} />
      )}
    </div>
  );
}

// ─── Conteúdo Bloqueado (sem preview) ────────────────────────────────────────

function LockedContent({ count, onSubscribe, tipo, isSubscriber, onGoToWp, projeto }) {
  const msg = isSubscriber
    ? 'Veja esse conteúdo completo'
    : tipo === 'video'
      ? 'Este episódio completo está disponível apenas para assinantes SX.'
      : count
        ? `${count} ${count === 1 ? 'foto exclusiva' : 'fotos exclusivas'} disponíveis para assinantes.`
        : 'Conteúdo exclusivo disponível para assinantes SX.';

  return (
    <div style={{ marginTop: '4px' }}>
      <div style={{
        borderRadius: '12px', padding: '24px',
        background: '#0A0A0F', border: '1px solid rgba(123,63,242,0.35)',
        boxShadow: '0 0 30px rgba(123,63,242,0.08)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '20px',
        flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '14px' }}>
          <div style={{
            width: '40px', height: '40px', borderRadius: '50%', flexShrink: 0,
            background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5">
              <rect x="3" y="11" width="18" height="11" rx="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
          </div>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 600, color: '#EFEFEF', marginBottom: '2px' }}>
              {isSubscriber ? 'Você já é um assinante SX' : 'Conteúdo Exclusivo SX'}
            </div>
            <div style={{ fontSize: '12px', color: '#9999B2' }}>{msg}</div>
          </div>
        </div>
        {isSubscriber && (
          <button
            onClick={onGoToWp}
            style={{
              background: 'linear-gradient(135deg, #7B3FF2, #FF1675)',
              border: 'none', borderRadius: '9999px', color: '#fff',
              fontSize: '13px', fontWeight: 600, fontFamily: "'Inter', sans-serif",
              padding: '10px 24px', cursor: 'pointer', whiteSpace: 'nowrap',
              boxShadow: '0 0 16px rgba(123,63,242,0.35)',
              transition: 'opacity 0.15s',
            }}
            onMouseOver={e => e.currentTarget.style.opacity = '0.9'}
            onMouseOut={e => e.currentTarget.style.opacity = '1'}
          >
            Ver conteúdo completo
          </button>
        )}
      </div>
      {!isSubscriber && (
        <DualPlanCard individualSlug={projeto} title={null} />
      )}
    </div>
  );
}

// ─── Créditos ─────────────────────────────────────────────────────────────────

function Creditos({ text }) {
  if (!text) return null;
  const clean = stripHtml(text).replace(/\n+/g, '\n').trim();
  if (!clean) return null;
  return (
    <div style={{
      borderTop: '1px solid rgba(255,255,255,0.06)',
      paddingTop: '20px', marginTop: '20px',
    }}>
      <div style={{ fontSize: '11px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#55556A', marginBottom: '8px' }}>
        CRÉDITOS
      </div>
      <pre style={{
        fontSize: '12px', color: '#55556A', lineHeight: 1.7,
        fontFamily: "'Inter', sans-serif", whiteSpace: 'pre-wrap', wordBreak: 'break-word',
      }}>
        {clean}
      </pre>
    </div>
  );
}

// ─── Modelos no Conteúdo ──────────────────────────────────────────────────────

function ModelosNoConteudo({ modelos }) {
  if (!modelos || modelos.length === 0) return null;
  return (
    <div style={{ marginTop: '32px' }}>
      <div style={{ fontSize: '11px', fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#55556A', marginBottom: '12px' }}>
        {modelos.length === 1 ? 'MODELO NESTE CONTEÚDO' : 'MODELOS NESTE CONTEÚDO'}
      </div>
      <div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
        {modelos.map(m => (
          <a
            key={m.slug}
            href={`/modelos/${m.slug}`}
            style={{
              display: 'flex', alignItems: 'center', gap: '10px',
              padding: '8px 16px 8px 8px',
              background: '#14141C', borderRadius: '9999px',
              border: '1px solid rgba(255,255,255,0.06)',
              transition: 'all 0.15s', textDecoration: 'none',
            }}
            onMouseOver={e => { e.currentTarget.style.borderColor = 'rgba(123,63,242,0.3)'; e.currentTarget.style.background = '#1B1B26'; }}
            onMouseOut={e => { e.currentTarget.style.borderColor = 'rgba(255,255,255,0.06)'; e.currentTarget.style.background = '#14141C'; }}
          >
            {m.capa ? (
              <img
                src={m.capa}
                alt={m.nome}
                style={{ width: '32px', height: '32px', borderRadius: '50%', objectFit: 'cover', objectPosition: 'center top' }}
              />
            ) : (
              <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: 'linear-gradient(135deg, #7B3FF2, #FF1675)' }}/>
            )}
            <span style={{ fontSize: '13px', fontWeight: 500, color: '#EFEFEF' }}>{m.nome}</span>
          </a>
        ))}
      </div>
    </div>
  );
}

// ─── Conteúdos Relacionados ───────────────────────────────────────────────────

const GRAD = [
  'linear-gradient(135deg, #1a0532 0%, #3d0f60 100%)',
  'linear-gradient(135deg, #1a0020 0%, #4c0050 100%)',
  'linear-gradient(135deg, #2a0018 0%, #5c0040 100%)',
  'linear-gradient(135deg, #001a2e 0%, #003d5c 100%)',
];

function RelatedContent({ items }) {
  if (!items || items.length === 0) return null;
  const show = items.slice(0, 4);
  return (
    <div style={{ marginTop: '48px', paddingTop: '32px', borderTop: '1px solid rgba(255,255,255,0.06)' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
        <h2 style={{ fontFamily: "'Space Grotesk', sans-serif", fontWeight: 700, fontSize: '18px', color: '#EFEFEF' }}>
          Mais Conteúdo
        </h2>
      </div>
      <div className="related-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px' }}>
        {show.map((c, i) => {
          const badge = tipoBadgeStyle(c.tipo);
          return (
            <a
              key={c.slug}
              href={`/conteudo/${c.slug}`}
              className="related-card"
              style={{
                display: 'block', borderRadius: '12px', overflow: 'hidden',
                position: 'relative', aspectRatio: '3/4', textDecoration: 'none',
                background: '#14141C', border: '1px solid rgba(255,255,255,0.06)',
              }}
            >
              {c.capa ? (
                <img src={c.capa} alt={c.title} style={{
                  position: 'absolute', inset: 0, width: '100%', height: '100%',
                  objectFit: 'cover', objectPosition: 'center top',
                }}/>
              ) : (
                <div style={{ position: 'absolute', inset: 0, background: GRAD[i % GRAD.length] }}/>
              )}
              <div style={{
                position: 'absolute', inset: 0,
                background: 'linear-gradient(to top, rgba(10,10,15,0.95) 0%, transparent 55%)',
              }}/>
              {c.n_membros > 0 && (
                <div style={{
                  position: 'absolute', top: '8px', right: '8px',
                  background: 'rgba(123,63,242,0.2)', borderRadius: '9999px',
                  padding: '2px 7px', fontSize: '10px', color: '#9A65F5',
                  border: '1px solid rgba(123,63,242,0.3)',
                }}>
                  +{c.n_membros}
                </div>
              )}
              <div style={{ position: 'absolute', bottom: '10px', left: '10px', right: '10px' }}>
                <div style={{
                  fontSize: '10px', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: badge.color, marginBottom: '4px',
                }}>{c.tipo}</div>
                <div style={{ fontSize: '12px', fontWeight: 600, color: '#EFEFEF', lineHeight: 1.3 }}>
                  {stripHtml(c.title).slice(0, 50)}
                </div>
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}

// ─── Página principal ─────────────────────────────────────────────────────────

function ConteudoPost({ slug }) {
  const [post, setPost] = useState(null);
  const [error, setError] = useState(null);

  // Funil de lead
  const [leadState, setLeadState] = useState(() =>
    localStorage.getItem('sx_lead_unlocked') ? 'unlocked' : 'locked'
  );
  const [leadForm, setLeadForm] = useState({ nome: '', email: '', whatsapp: '' });
  const [leadLoading, setLeadLoading] = useState(false);
  const [leadError, setLeadError] = useState('');

  // Assinante logado: troca os CTAs de "Assinar" por "Ver conteúdo completo" (auto-login no WP)
  const [sxUser, setSxUser] = useState(null);
  useEffect(() => {
    try {
      const cached = localStorage.getItem('sx_user');
      if (cached) setSxUser(JSON.parse(cached));
    } catch {}
  }, []);
  const isSubscriber = sxUser?.subscription_status === 'active';

  useEffect(() => {
    fetch(`/api/content/${slug}`)
      .then(r => {
        if (!r.ok) throw new Error('Conteúdo não encontrado');
        return r.json();
      })
      .then(data => {
        setPost(data);
        document.title = `${data.title} — SX Plataforma`;
      })
      .catch(e => setError(e.message));
  }, [slug]);

  function handleShowForm() {
    setLeadState('form');
    setLeadError('');
  }

  async function handleLeadSubmit(e) {
    e.preventDefault();
    const { nome, email, whatsapp } = leadForm;
    if (!nome.trim() || !email.trim() || !whatsapp.trim()) {
      setLeadError('Preencha todos os campos.');
      return;
    }
    setLeadLoading(true);
    setLeadError('');
    try {
      const res = await fetch('/api/leads', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ nome, email, whatsapp, source: `post:${slug}` }),
      });
      if (!res.ok) throw new Error('Erro ao salvar.');
      localStorage.setItem('sx_lead_unlocked', '1');
      setLeadState('unlocked');
    } catch {
      setLeadError('Ops, tente novamente.');
    } finally {
      setLeadLoading(false);
    }
  }

  function handleSubscribe() {
    const produto = post?.projeto || 'combo';
    window.location.href = `/assinar?produto=${produto}&utm_source=conteudo&utm_post=${slug}`;
  }

  async function goToWpContent() {
    const wpUrl = post?.wp_link || `https://sexyclube.uol.com.br/conteudo/${slug}/`;
    if (!sxUser?.email) { window.location.href = wpUrl; return; }
    try {
      const r = await fetch(`/api/checkout/wp-login-url?email=${encodeURIComponent(sxUser.email)}&redirect=${encodeURIComponent(wpUrl)}`);
      const { url } = await r.json();
      if (url) { window.location.href = url; return; }
    } catch { /* cai no fallback abaixo */ }
    window.location.href = wpUrl;
  }

  if (error) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100vh', gap: '16px' }}>
        <div style={{ fontSize: '48px', color: '#55556A' }}>404</div>
        <div style={{ color: '#9999B2' }}>{error}</div>
        <a href="/" style={{ color: '#7B3FF2', fontSize: '13px' }}>Voltar ao início</a>
      </div>
    );
  }

  if (!post) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>
        <div style={{
          width: '32px', height: '32px', borderRadius: '50%',
          border: '2px solid rgba(123,63,242,0.3)', borderTopColor: '#7B3FF2',
          animation: 'spin 0.8s linear infinite',
        }}/>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  const hasVideo = !!post.video;
  const hasFreeImgs = post.free_images && post.free_images.length > 0;

  return (
    <div style={{ minHeight: '100vh', background: '#0A0A0F' }}>
      <NavBar tipo={post.tipo} />

      <div style={{ paddingTop: '64px' }}>
        <PostHero post={post} />

        <div className="content-body" style={{ maxWidth: '900px', margin: '0 auto', padding: '40px 40px' }}>

          {/* Vídeo gratuito — sempre exibe teaser de versão completa abaixo */}
          {hasVideo && (
            <div style={{ marginBottom: '32px' }}>
              <VideoPlayer
                videoHtml={post.video}
                onSubscribe={handleSubscribe}
                isSubscriber={isSubscriber}
                onGoToWp={goToWpContent}
                projeto={post.projeto}
              />
            </div>
          )}

          {/* Galeria: funil de lead integrado */}
          {hasFreeImgs && (
            <div style={{ marginBottom: '32px' }}>
              <PhotoGallery
                images={post.free_images}
                membrosImages={post.membros_images}
                nMembros={post.n_membros}
                nVip={post.n_vip}
                leadState={leadState}
                onShowForm={handleShowForm}
                onLeadSubmit={handleLeadSubmit}
                leadForm={leadForm}
                setLeadForm={setLeadForm}
                leadLoading={leadLoading}
                leadError={leadError}
                onSubscribe={handleSubscribe}
                isSubscriber={isSubscriber}
                onGoToWp={goToWpContent}
                projeto={post.projeto}
              />
            </div>
          )}

          {/* Sem conteúdo gratuito: mostra só o lock */}
          {!hasVideo && !hasFreeImgs && (
            <div style={{ marginBottom: '32px' }}>
              <LockedContent count={post.n_membros || null} onSubscribe={handleSubscribe} tipo={post.n_membros > 0 ? 'fotos' : 'video'} isSubscriber={isSubscriber} onGoToWp={goToWpContent} projeto={post.projeto} />
            </div>
          )}

          {/* Créditos */}
          {post.creditos && <Creditos text={post.creditos} />}

          {/* Modelos */}
          <ModelosNoConteudo modelos={post.modelos} />

          {/* Relacionados */}
          <RelatedContent items={post.related} />
        </div>
      </div>
    </div>
  );
}

window.ConteudoPost = ConteudoPost;
