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 Hot','Apresentadoras Papo com Pijama','Papo na Banheira','Papo com Requesty.me','Papo com Skokka'],
    pimentinhas: ['Pimentinhas 2026 HOT','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','Sexy Girls','Sexy Blitz','Programas Sexy Blitz','Sexy Unboxing','Sexy Geek','Caminhos do Prazer','De Frente com a Prazeróloga','Ketlen em Cena','Mentora do Homem Consciente','Matérias'],
    sxclube:     ['Episódios California TV','California TV'],
  };
  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 FILTERS = [
  { label: 'Todos',        projeto: '' },
  { label: 'Revista Sexy', projeto: 'revista' },
  { label: 'SX Clube',     projeto: 'sxclube' },
  { label: 'Pimentinhas',  projeto: 'pimentinhas' },
  { label: 'Casa das Pim', projeto: 'casapim' },
  { label: 'Papo',         projeto: 'papo' },
];

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

function NavBar({ title }) {
  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, flexShrink: 0 }}>
        <img src="/assets/sx_fill.svg" style={{ height: 26, filter: 'brightness(0) invert(1)' }} alt="SX" />
      </a>
      <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#7B3FF2', fontFamily: "'Inter',sans-serif" }}>{title || 'Conteúdo'}</span>
      <div className="nav-links" style={{ display: 'flex', alignItems: 'center', gap: 4, marginLeft: 8 }}>
        {[['Modelos','/modelos'],['Busca','/busca']].map(([label, href]) => (
          <a key={href} href={href} style={{ fontSize: 13, fontWeight: 500, color: '#9999B2', padding: '6px 10px', borderRadius: 8 }}>{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>
  );
}

// ── ContentCard (DS portrait) ─────────────────────────────────────────────────

function ContentCard({ post }) {
  const [hov, setHov] = useState(false);
  const isVideo = getCategory(post.tipo) === 'video';
  const cover = post.capa || (!isVideo ? post.modelos?.[0]?.capa : null) || null;
  return (
    <div className="content-card" onClick={() => window.location.href = `/conteudo/${post.slug}`}
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ 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' }}>
      <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: 14, 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>
  );
}

// ── ListaConteudo ──────────────────────────────────────────────────────────────

const SORTS = [
  { label: 'Mais recentes', value: 'recentes' },
  { label: 'Nome',          value: 'nome' },
];

function ListaConteudo() {
  const [activeFilter, setActiveFilter] = useState('');
  const [sort, setSort] = useState('recentes');
  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((projeto, sortBy, off, append) => {
    setLoading(true);
    const qs = `limit=${LIMIT}&offset=${off}&sort=${sortBy}${projeto ? `&projeto=${projeto}` : ''}`;
    fetch(`/api/content?${qs}`)
      .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));
  }, []);

  useEffect(() => {
    load(activeFilter, sort, 0, false);
  }, [activeFilter, sort, load]);

  function changeFilter(projeto) {
    setActiveFilter(projeto);
    setOffset(0);
    setItems([]);
  }

  function changeSort(value) {
    setSort(value);
    setOffset(0);
    setItems([]);
  }

  const activeLabel = FILTERS.find(f => f.projeto === activeFilter)?.label || 'Todos';

  return (
    <div style={{ background: '#0A0A0F', minHeight: '100vh' }}>
      <NavBar title={activeFilter ? activeLabel : 'Conteúdo'} />

      <div style={{ paddingTop: 64 }}>
        <div className="section-pad" style={{ maxWidth: 1400, margin: '0 auto', padding: '40px 40px 0' }}>

          {/* Header */}
          <div style={{ marginBottom: 28 }}>
            <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#7B3FF2', fontFamily: "'Inter',sans-serif", marginBottom: 6 }}>SEXY / SX</div>
            <h1 style={{ fontFamily: "'Space Grotesk',sans-serif", fontWeight: 700, fontSize: 36, color: '#EFEFEF', textTransform: 'uppercase', letterSpacing: '0.02em', marginBottom: 20 }}>
              {activeFilter ? activeLabel : 'Todo o Conteúdo'}
            </h1>

            {/* Filter pills + ordenação */}
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {FILTERS.map(f => {
                  const active = f.projeto === activeFilter;
                  return (
                    <button key={f.projeto} onClick={() => changeFilter(f.projeto)}
                      style={{ background: active ? 'rgba(123,63,242,0.15)' : 'rgba(255,255,255,0.04)', border: active ? '1px solid rgba(123,63,242,0.4)' : '1px solid rgba(255,255,255,0.08)', borderRadius: 9999, color: active ? '#9A65F5' : 'rgba(255,255,255,0.5)', fontFamily: "'Inter',sans-serif", fontSize: 12, fontWeight: 500, padding: '6px 14px', cursor: 'pointer', transition: 'all 0.15s' }}>
                      {f.label}
                    </button>
                  );
                })}
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
                <span style={{ fontSize: 11, color: '#55556A', fontFamily: "'Inter',sans-serif", textTransform: 'uppercase', letterSpacing: '0.06em' }}>Ordenar</span>
                <div style={{ display: 'flex', gap: 4, background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: 9999, padding: 3 }}>
                  {SORTS.map(s => {
                    const active = s.value === sort;
                    return (
                      <button key={s.value} onClick={() => changeSort(s.value)}
                        style={{ background: active ? 'rgba(123,63,242,0.25)' : 'transparent', border: 'none', borderRadius: 9999, color: active ? '#EFEFEF' : 'rgba(255,255,255,0.45)', fontFamily: "'Inter',sans-serif", fontSize: 12, fontWeight: 500, padding: '5px 12px', cursor: 'pointer', transition: 'all 0.15s' }}>
                        {s.label}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          </div>

          {/* Grid */}
          {items.length > 0 ? (
            <div className="grid-4" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
              {items.map(post => <ContentCard key={post.id} post={post} />)}
            </div>
          ) : !loading ? (
            <div style={{ padding: '60px 0', textAlign: 'center', color: '#55556A', fontFamily: "'Inter',sans-serif", fontSize: 14 }}>Nenhum conteúdo encontrado.</div>
          ) : null}

          {/* Loading skeleton */}
          {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: 16, overflow: 'hidden', background: '#14141C', border: '1px solid rgba(255,255,255,0.05)', aspectRatio: '3/4' }} />
              ))}
            </div>
          )}

          {/* Totais + Carregar mais */}
          {items.length > 0 && (
            <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12, paddingBottom: 48 }}>
              <span style={{ fontSize: 12, color: '#55556A', fontFamily: "'Inter',sans-serif" }}>
                Exibindo {items.length} de {total} conteúdos
              </span>
              {hasMore && (
                <button onClick={() => load(activeFilter, sort, 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>
  );
}
