const { useState, useEffect, useCallback } = React;

function fmtDate(iso) {
  if (!iso) return '';
  try { return new Date(iso).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short', year: 'numeric' }); } catch { return ''; }
}

const TIPO_PROJECT_MAP = (() => {
  const m = {};
  const defs = {
    papo:        ['Episódios Papo com Pijama','Papo com Pijama','Papo com Pijama Hot','Apresentadoras Papo com Pijama','Papo na Banheira','Papo com Requesty.me','Papo com Skokka'],
    pimentinhas: ['Pimentinhas 2026 HOT','Pimentinhas Julho 2026 HOT','Pimentinhas Julho 2026','Pimentinhas Junho 2026 HOT','Pimentinhas Junho 2026','Pimentinhas Maio 2026 HOT','Pimentinhas Maio 2026','Pimentinhas 10'],
    casapim:     ['Casa das Pimentinhas','Episódios Casa das Pimentinhas 10','Capa Casa das Pimentinhas 10','Madrinha Casa das Pimentinhas 10','Apresentadora Casa das Pimentinhas 10'],
    revista:     ['Revista Sexy'],
    sxclube:     ['Episódios California TV','California TV','Sexy Girls','Sexy Blitz','Programas Sexy Blitz','Sexy Geek','Sexy Unboxing','Caminhos do Prazer','De Frente com a Prazeróloga','Ketlen em Cena','Mentora do Homem Consciente','Matérias'],
  };
  Object.entries(defs).forEach(([proj, arr]) => arr.forEach(t => { m[t] = proj; }));
  return m;
})();

const PROJECT_CFGS = {
  revista:     { label: 'REVISTA SEXY',         color: '#C8A96E', bg: 'rgba(200,169,110,0.15)', border: 'rgba(200,169,110,0.3)' },
  sxclube:     { label: 'SXCLUBE',              color: '#9A65F5', bg: 'rgba(123,63,242,0.15)',  border: 'rgba(123,63,242,0.35)' },
  casapim:     { label: 'CASA DAS PIMENTINHAS', color: '#FF4D97', bg: 'rgba(255,22,117,0.15)',  border: 'rgba(255,22,117,0.3)' },
  pimentinhas: { label: 'PIMENTINHAS',          color: '#FF4D97', bg: 'rgba(255,22,117,0.12)',  border: 'rgba(255,22,117,0.25)' },
  papo:        { label: 'PAPO COM PIJAMA',      color: '#33CFFF', bg: 'rgba(0,194,255,0.12)',   border: 'rgba(0,194,255,0.3)' },
};

const TYPE_CORNER_CFGS = {
  video:     { bg: 'rgba(255,22,117,0.85)', color: '#fff',                   label: 'VÍDEO' },
  galeria:   { bg: 'rgba(123,63,242,0.85)', color: '#fff',                   label: 'GALERIA' },
  editorial: { bg: 'rgba(10,10,15,0.6)',    color: 'rgba(255,255,255,0.5)', label: 'EDITORIAL' },
};

function getCategory(tipo) {
  if (!tipo) return 'editorial';
  const t = tipo.toLowerCase();
  if (t.includes('episód') || t.includes('vídeo') || t.includes('programa')) return 'video';
  if (t.includes('galeria') || t.includes('fotos') || t.includes('capa')) return 'galeria';
  return 'editorial';
}

function getProject(tipo) { return TIPO_PROJECT_MAP[tipo] || null; }

function ProjectTag({ tipo }) {
  const pc = PROJECT_CFGS[getProject(tipo)];
  if (!pc) return null;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', whiteSpace: 'nowrap', fontSize: 9, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '3px 9px', borderRadius: 9999, background: pc.bg, color: pc.color, border: `1px solid ${pc.border}`, fontFamily: "'Inter', sans-serif", lineHeight: 1 }}>
      {pc.label}
    </span>
  );
}

function TypeCorner({ tipo }) {
  const c = TYPE_CORNER_CFGS[getCategory(tipo)];
  if (!c) return null;
  return (
    <div style={{ position: 'absolute', top: 10, right: 10, zIndex: 3, display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 8, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', padding: '4px 8px', borderRadius: 9999, background: c.bg, color: c.color, backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)', fontFamily: "'Inter', sans-serif", lineHeight: 1 }}>
      {c.label}
    </div>
  );
}

const PROJETO_META = {
  revista:     { nome: 'Revista Sexy',         label: 'DESDE 1993',      accent: '#C8A96E', bg: 'linear-gradient(135deg,#1a1208,#2e2010,#0A0A0F)', desc: 'A maior publicação erótica do Brasil. Décadas de ensaios exclusivos, entrevistas e conteúdo que define a cultura nacional da sensualidade.', logo: '/assets/Logo-Sexy.svg' },
  sxclube:     { nome: 'SX Clube',             label: 'CONTEÚDO PREMIUM', accent: '#9A65F5', bg: 'linear-gradient(135deg,#14082e,#260a50,#0A0A0F)', desc: 'A plataforma de assinatura com o melhor do universo SEXY. Conteúdos exclusivos, bastidores e acesso antecipado para assinantes.', logo: '/assets/logo-sexy-clube.svg' },
  casapim:     { nome: 'Casa das Pimentinhas', label: 'REALITY',          accent: '#FF4D97', bg: 'linear-gradient(135deg,#200010,#450020,#0A0A0F)', desc: 'O reality show mais quente do Brasil. Episódios completos, bastidores e entrevistas exclusivas com as participantes.', logo: '/assets/logo-casa-pimentinhas.svg' },
  pimentinhas: { nome: 'Pimentinhas',          label: 'SÉRIE',            accent: '#FF8A80', bg: 'linear-gradient(135deg,#2a0008,#5c0020,#0A0A0F)', desc: 'A série de ensaios que mistura sensualidade, arte e personalidade. As mais picantes do Brasil em produções inéditas.', logo: '/assets/logo-pimentinhas.png' },
  papo:        { nome: 'Papo com Pijama',      label: 'PODCAST · VÍDEO',  accent: '#33CFFF', bg: 'linear-gradient(135deg,#001520,#002a40,#0A0A0F)', desc: 'O podcast mais intimista do universo SEXY. Conversas sem filtro sobre liberdade, sexualidade, relacionamentos e muito mais.', logo: '/assets/logo-papo-pijama.svg' },
};

// component: 'hero+carousel' | 'carousel' | 'grid-portrait'
const PAPO_SUB_TIPOS = [
  { tipo: 'Episódios Papo com Pijama',      label: 'Papo com Pijama',      component: 'hero+carousel' },
  { tipo: 'Papo na Banheira',               label: 'Papo na Banheira',     component: 'carousel' },
  { tipo: 'Papo com Pijama Hot',            label: 'Papo com Pijama Hot',  component: 'carousel' },
  { tipo: 'Apresentadoras Papo com Pijama', label: 'Apresentadoras',       component: 'grid-portrait' },
  { tipo: 'Papo com Requesty.me',           label: 'Papo com Requesty.me', component: 'carousel' },
  { tipo: 'Papo com Skokka',               label: 'Papo com Skokka',      component: 'carousel' },
];

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

function NavBar({ nome }) {
  return (
    <nav style={{ position: 'fixed', top: 0, left: 0, right: 0, zIndex: 200, height: 64, background: 'rgba(10,10,15,0.92)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)', borderBottom: '1px solid rgba(255,255,255,0.06)', display: 'flex', alignItems: 'center', padding: '0 24px', gap: 16 }}>
      <a href="/" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <img src="/assets/sx_fill.svg" style={{ height: 26, filter: 'brightness(0) invert(1)' }} alt="SX" />
      </a>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#55556A" strokeWidth="2" strokeLinecap="round"><path d="M9 18l6-6-6-6"/></svg>
      <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#9999B2', fontFamily: "'Inter',sans-serif" }}>{nome || 'Projeto'}</span>
      <div className="nav-links" style={{ display: 'flex', gap: 4, marginLeft: 8 }}>
        {[['Conteúdo','/conteudo'],['Modelos','/modelos']].map(([label, href]) => (
          <a key={href} href={href} style={{ fontSize: 13, fontWeight: 500, color: '#9999B2', padding: '6px 10px' }}>{label}</a>
        ))}
      </div>
      <div style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center' }}>
        <a href="/entrar" style={{ fontSize: 13, fontWeight: 500, color: '#9999B2' }}>Entrar</a>
        <a href="/assinar" style={{ background: 'linear-gradient(135deg,#7B3FF2,#FF1675)', borderRadius: 9999, color: '#fff', fontSize: 12, fontWeight: 600, padding: '7px 16px' }}>Assinar</a>
      </div>
    </nav>
  );
}

// ── SectionHeader ─────────────────────────────────────────────────────────────

function SectionHeader({ label, count, accent, countLabel = 'episódios', linkHref }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18, paddingBottom: 12, borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 3, height: 16, background: accent, borderRadius: 9999, flexShrink: 0 }} />
        <h2 style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 15, color: '#EFEFEF', textTransform: 'uppercase', letterSpacing: '0.05em', margin: 0 }}>{label}</h2>
        {count > 0 && <span style={{ fontSize: 11, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>{count} {countLabel}</span>}
      </div>
      {linkHref && count > 8 && (
        <a href={linkHref} style={{ fontSize: 11, fontWeight: 600, color: accent, fontFamily: "'Inter',sans-serif", opacity: 0.85 }}>Ver todos →</a>
      )}
    </div>
  );
}

// ── ContentCard (3:4 portrait DS, para projetos não-Papo) ────────────────────

function ContentCard({ post, width }) {
  const [hov, setHov] = useState(false);
  const isVideo = getCategory(post.tipo) === 'video';
  const cover = post.capa || (!isVideo ? post.modelos?.[0]?.capa : null) || null;
  const wrapStyle = {
    position: 'relative', borderRadius: 16, overflow: 'hidden', aspectRatio: '3/4', cursor: 'pointer',
    border: `1px solid ${hov ? 'rgba(255,255,255,0.14)' : 'rgba(255,255,255,0.06)'}`,
    boxShadow: hov ? '0 8px 32px rgba(0,0,0,0.5), 0 0 20px rgba(123,63,242,0.2)' : '0 4px 20px rgba(0,0,0,0.45)',
    transform: hov ? 'translateY(-3px)' : 'none',
    transition: 'transform 0.25s cubic-bezier(0.16,1,0.3,1), box-shadow 0.25s, border-color 0.25s',
    background: '#14141C',
  };
  if (width) { wrapStyle.flexShrink = 0; wrapStyle.width = width; wrapStyle.aspectRatio = undefined; }
  return (
    <div className="content-card" onClick={() => window.location.href = `/conteudo/${post.slug}`}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)} style={wrapStyle}>
      <div style={{ position: 'absolute', inset: 0, background: post.gradient || 'linear-gradient(135deg,#14082e,#0A0A0F)' }} />
      {cover && <img src={cover} alt={post.title} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top' }} onError={e => e.target.style.display='none'} />}
      <TypeCorner tipo={post.tipo} />
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,15,0.95) 0%, rgba(10,10,15,0.1) 55%, transparent 100%)' }} />
      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '16px 16px 18px' }}>
        <div style={{ marginBottom: 8 }}><ProjectTag tipo={post.tipo} /></div>
        <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 13, color: '#EFEFEF', lineHeight: 1.25, textTransform: 'uppercase', letterSpacing: '0.02em' }}>{post.title}</div>
        <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.45)', marginTop: 6, fontFamily: "'Inter',sans-serif" }}>{fmtDate(post.date)}</div>
      </div>
    </div>
  );
}

// ── VideoCard (16:9, para episódios em carousel) ──────────────────────────────

function VideoCard({ post, width = 288 }) {
  const [hov, setHov] = useState(false);
  return (
    <div onClick={() => window.location.href = `/conteudo/${post.slug}`}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ flexShrink: 0, width, borderRadius: 16, overflow: 'hidden', background: post.gradient || '#14141C',
        border: `1px solid ${hov ? 'rgba(255,255,255,0.14)' : 'rgba(255,255,255,0.06)'}`,
        cursor: 'pointer',
        boxShadow: hov ? '0 4px 24px rgba(0,0,0,0.5), 0 0 20px rgba(123,63,242,0.3)' : '0 4px 24px rgba(0,0,0,0.4)',
        transform: hov ? 'scale(1.02)' : 'scale(1)',
        transition: 'transform 0.2s cubic-bezier(0.16,1,0.3,1), box-shadow 0.2s, border-color 0.2s' }}>
      <div style={{ aspectRatio: '16/9', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, background: post.gradient || '#14141C', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'rgba(255,22,117,0.2)', border: '1.5px solid rgba(255,22,117,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 0 20px rgba(255,22,117,0.35)' }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="#FF1675"><polygon points="6 3 20 12 6 21 6 3"/></svg>
          </div>
        </div>
        {post.capa && <img src={post.capa} alt={post.title} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} onError={e => e.target.style.display='none'} />}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,15,0.75) 0%, transparent 60%)' }} />
        <TypeCorner tipo={post.tipo} />
      </div>
      <div style={{ padding: '10px 12px 14px' }}>
        <div style={{ marginBottom: 6 }}><ProjectTag tipo={post.tipo} /></div>
        <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 12, color: '#EFEFEF', lineHeight: 1.3, textTransform: 'uppercase', letterSpacing: '0.02em', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', marginBottom: 4 }}>{post.title}</div>
        <div style={{ fontSize: 10, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>{fmtDate(post.date)}</div>
      </div>
    </div>
  );
}

// ── HeroEpisode (destaque do episódio mais recente) ───────────────────────────

function HeroEpisode({ post, accent }) {
  if (!post) return null;
  return (
    <div onClick={() => window.location.href = `/conteudo/${post.slug}`}
      style={{ borderRadius: 16, overflow: 'hidden', position: 'relative', aspectRatio: '21/9', background: post.gradient || '#14141C', cursor: 'pointer', marginBottom: 14 }}>
      {post.capa && (
        <img src={post.capa} alt={post.title} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }} onError={e => e.target.style.display='none'} />
      )}
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,15,0.97) 0%, rgba(10,10,15,0.35) 55%, transparent 100%)' }} />

      {/* Play button center */}
      <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ width: 56, height: 56, borderRadius: '50%', background: 'rgba(255,255,255,0.1)', border: '2px solid rgba(255,255,255,0.2)', backdropFilter: 'blur(8px)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><polygon points="5,3 19,12 5,21"/></svg>
        </div>
      </div>

      <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '28px 32px' }}>
        <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: accent, fontFamily: "'Inter',sans-serif", marginBottom: 10 }}>ÚLTIMO EPISÓDIO</div>
        <h3 style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 22, color: '#EFEFEF', textTransform: 'uppercase', letterSpacing: '0.02em', lineHeight: 1.2, marginBottom: 8, maxWidth: 640 }}>{post.title}</h3>
        <div style={{ fontSize: 11, color: '#9999B2', fontFamily: "'Inter',sans-serif" }}>{fmtDate(post.date)}</div>
      </div>
    </div>
  );
}

// ── PresenterGrid (grid de apresentadoras) ────────────────────────────────────

function PresenterGrid({ items, loading, accent }) {
  if (!loading && items.length === 0) return null;
  const skelCount = 5;
  return (
    <div style={{ display: 'flex', gap: 12 }}>
      {loading
        ? Array.from({length: skelCount}).map((_,i) => (
            <div key={i} style={{ flex: 1, borderRadius: 16, background: '#14141C', border: '1px solid rgba(255,255,255,0.05)', aspectRatio: '3/4' }} />
          ))
        : items.map(post => {
            const cover = post.capa || post.modelos?.[0]?.capa || null;
            const modelSlug = post.modelos?.[0]?.slug;
            const modelName = post.modelos?.[0]?.nome;
            const href = modelSlug ? `/modelos/${modelSlug}` : `/conteudo/${post.slug}`;
            return (
              <div key={post.id} onClick={() => window.location.href = href}
                style={{ flex: 1, minWidth: 120, borderRadius: 16, overflow: 'hidden', position: 'relative', aspectRatio: '3/4', background: post.gradient || '#14141C', border: '1px solid rgba(255,255,255,0.06)', cursor: 'pointer' }}>
                {cover && (
                  <img src={cover} alt={modelName || post.title} style={{ width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center top', display: 'block' }} onError={e => e.target.style.display='none'} />
                )}
                <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(10,10,15,0.92) 0%, rgba(10,10,15,0.3) 45%, transparent 100%)' }} />
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '16px 14px' }}>
                  {modelName && (
                    <div style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 12, color: '#EFEFEF', textTransform: 'uppercase', letterSpacing: '0.04em', lineHeight: 1.2 }}>{modelName}</div>
                  )}
                  <div style={{ fontFamily: "'Inter',sans-serif", fontWeight: 600, fontSize: 9, color: accent, textTransform: 'uppercase', letterSpacing: '0.1em', marginTop: 4 }}>Apresentadora</div>
                </div>
              </div>
            );
          })
      }
    </div>
  );
}

// ── SubSection (Papo) ─────────────────────────────────────────────────────────

function SubSection({ tipo, label, accent, component = 'carousel' }) {
  const [items, setItems] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);

  const limit = component === 'hero+carousel' ? 9 : component === 'grid-portrait' ? 12 : 8;

  useEffect(() => {
    fetch(`/api/content?tipo=${encodeURIComponent(tipo)}&limit=${limit}`)
      .then(r => r.json())
      .then(data => {
        setItems(Array.isArray(data?.items) ? data.items : []);
        setTotal(data?.total || 0);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [tipo]);

  if (!loading && items.length === 0) return null;

  const header = (
    <SectionHeader label={label} count={!loading ? total : 0} accent={accent} linkHref="/conteudo?projeto=papo" />
  );

  // Hero + carousel: primeiro item em destaque, restantes em scroll horizontal
  if (component === 'hero+carousel') {
    const hero = items[0];
    const rest = items.slice(1);
    return (
      <div style={{ marginBottom: 56 }}>
        {header}
        {loading
          ? <div style={{ borderRadius: 16, background: '#14141C', border: '1px solid rgba(255,255,255,0.05)', aspectRatio: '21/9', marginBottom: 14 }} />
          : <HeroEpisode post={hero} accent={accent} />
        }
        <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 8, scrollbarWidth: 'thin', scrollbarColor: 'rgba(255,255,255,0.08) transparent' }}>
          {loading
            ? Array.from({length: 5}).map((_,i) => <div key={i} style={{ flexShrink: 0, width: 288, borderRadius: 12, background: '#14141C', aspectRatio: '16/9' }} />)
            : rest.map(post => <VideoCard key={post.id} post={post} />)
          }
        </div>
      </div>
    );
  }

  // Grid de retratos: apresentadoras
  if (component === 'grid-portrait') {
    return (
      <div style={{ marginBottom: 56 }}>
        {header}
        <PresenterGrid items={items} loading={loading} accent={accent} />
      </div>
    );
  }

  // Carousel padrão 16:9
  return (
    <div style={{ marginBottom: 48 }}>
      {header}
      <div style={{ display: 'flex', gap: 10, overflowX: 'auto', paddingBottom: 8, scrollbarWidth: 'thin', scrollbarColor: 'rgba(255,255,255,0.08) transparent' }}>
        {loading
          ? Array.from({length: 5}).map((_,i) => <div key={i} style={{ flexShrink: 0, width: 288, borderRadius: 12, background: '#14141C', aspectRatio: '16/9' }} />)
          : items.map(post => <VideoCard key={post.id} post={post} />)
        }
      </div>
    </div>
  );
}

// ── PapoContent ────────────────────────────────────────────────────────────────

function PapoContent({ meta }) {
  return (
    <div className="section-pad" style={{ maxWidth: 1400, margin: '0 auto', padding: '40px 40px 48px' }}>
      {PAPO_SUB_TIPOS.map(({ tipo, label, component }) => (
        <SubSection key={tipo} tipo={tipo} label={label} accent={meta.accent} component={component} />
      ))}
    </div>
  );
}

// ── ProjetoPage ───────────────────────────────────────────────────────────────

function ProjetoPage({ slug }) {
  const meta = PROJETO_META[slug];
  const [items, setItems]   = useState([]);
  const [total, setTotal]   = useState(0);
  const [offset, setOffset] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(false);
  const LIMIT = 24;

  const load = useCallback((off, append) => {
    if (!slug || slug === 'papo') return;
    setLoading(true);
    fetch(`/api/content?projeto=${slug}&limit=${LIMIT}&offset=${off}`)
      .then(r => r.json())
      .then(data => {
        const newItems = Array.isArray(data?.items) ? data.items : [];
        setItems(prev => append ? [...prev, ...newItems] : newItems);
        setTotal(data?.total || 0);
        setHasMore(off + LIMIT < (data?.total || 0));
        setOffset(off + LIMIT);
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [slug]);

  useEffect(() => {
    if (slug !== 'papo') load(0, false);
  }, [load, slug]);

  if (!meta) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100vh', color: '#55556A', fontFamily: 'Inter,sans-serif', flexDirection: 'column', gap: 16 }}>
      <div>Projeto não encontrado.</div>
      <a href="/conteudo" style={{ color: '#7B3FF2', fontWeight: 600 }}>Ver todo o conteúdo</a>
    </div>
  );

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

      <div style={{ paddingTop: 64 }}>

        {/* Hero do projeto */}
        <div style={{ background: meta.bg, borderBottom: '1px solid rgba(255,255,255,0.05)', padding: '48px 40px' }}>
          <div style={{ maxWidth: 1400, margin: '0 auto' }}>
            <img src={meta.logo} alt={meta.nome} style={{ height: 40, width: 'auto', maxWidth: 280, filter: 'brightness(0) invert(1)', opacity: 0.9, marginBottom: 20, display: 'block' }}
              onError={e => { e.target.style.display='none'; }} />
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: meta.accent, fontFamily: "'Inter',sans-serif", marginBottom: 10 }}>{meta.label}</div>
            <p style={{ fontSize: 15, color: '#9999B2', lineHeight: 1.7, maxWidth: 600, fontFamily: "'Inter',sans-serif" }}>{meta.desc}</p>
            {slug !== 'papo' && total > 0 && <div style={{ marginTop: 16, fontSize: 12, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>{total} conteúdos disponíveis</div>}
          </div>
        </div>

        {/* Comparativo: assinatura individual do projeto x Combo Premium */}
        <div style={{ maxWidth: 1400, margin: '0 auto', padding: '0 40px' }}>
          <DualPlanCard individualSlug={slug} title="Assine este acesso" />
        </div>

        {/* Papo: layout editorial | Outros: flat grid */}
        {slug === 'papo' ? (
          <PapoContent meta={meta} />
        ) : (
          <div className="section-pad" style={{ maxWidth: 1400, margin: '0 auto', padding: '40px 40px 48px' }}>

            {loading && items.length === 0 ? (
              <div className="grid-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
                {Array.from({length: 8}).map((_,i) => <div key={i} style={{ borderRadius: 12, background: '#14141C', border: '1px solid rgba(255,255,255,0.05)', aspectRatio: '4/5' }} />)}
              </div>
            ) : items.length === 0 ? (
              <div style={{ padding: '60px 0', textAlign: 'center', color: '#55556A', fontFamily: "'Inter',sans-serif", fontSize: 14 }}>Nenhum conteúdo encontrado para este projeto.</div>
            ) : (
              <div className="grid-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
                {items.map(post => <ContentCard key={post.id} post={post} />)}
              </div>
            )}

            {items.length > 0 && (
              <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
                <span style={{ fontSize: 12, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>Exibindo {items.length} de {total}</span>
                {hasMore && (
                  <button onClick={() => load(offset, true)} disabled={loading}
                    style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: 9999, color: '#EFEFEF', fontFamily: "'Inter',sans-serif", fontSize: 13, fontWeight: 600, padding: '10px 24px', cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.5 : 1 }}>
                    {loading ? 'Carregando…' : 'Carregar mais'}
                  </button>
                )}
              </div>
            )}

          </div>
        )}

      </div>
    </div>
  );
}
