/* global React, Eyebrow, GlassCard, Icon, Btn, Light, Sticker */
const { useState: useStateBL, useEffect: useEffectBL, useMemo: useMemoBL } = React;

const CATEGORIES = [
  { key: 'all', label: 'Todos', color: '#F6F4F5' },
  { key: 'compliance', label: 'Compliance', color: '#A335E7' },
  { key: 'pentest', label: 'Pentesting', color: '#EC4D2A' },
  { key: 'devsecops', label: 'DevSecOps', color: '#3551E7' },
  { key: 'cloud', label: 'Cloud Security', color: '#35E7C7' },
  { key: 'awareness', label: 'Awareness', color: '#FB881D' },
  { key: 'opinion', label: 'Opinión', color: '#35E747' },
];

const POSTS = [
  {
    featured: true,
    cat: 'compliance', catLabel: 'Compliance', catColor: '#A335E7',
    title: 'ISO 27001 vs SOC 2: cuál certificar primero si vendés a EE.UU.',
    excerpt: 'Una decisión de timeline que define si cerrás el deal enterprise este trimestre o el próximo. Guía práctica para CTOs de SaaS argentinos que escalan al norte.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '28 Abr 2026', read: '12 min',
    badge: 'Guía completa',
    href: 'blog/iso-27001-vs-soc-2.html',
  },
  {
    cat: 'pentest', catLabel: 'Pentesting', catColor: '#EC4D2A',
    title: 'Anatomía de un breach: cómo un parámetro mal validado costó USD 2.1M',
    excerpt: 'Write-up técnico de un engagement reciente — cómo encontramos la cadena de explotación y qué controles habrían cortado el ataque en cualquiera de los 4 pasos.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '15 Abr 2026', read: '9 min',
    href: 'blog/anatomia-de-un-breach.html',
  },
  {
    cat: 'devsecops', catLabel: 'DevSecOps', catColor: '#3551E7',
    title: 'SAST que no rompe el pipeline: presupuesto de tiempo y false positives',
    excerpt: 'Cómo configurar Semgrep, Snyk o CodeQL sin sumar 20 minutos a cada PR ni inundar a los devs con alertas que ya saben.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '09 Abr 2026', read: '7 min',
    href: 'blog/sast-pipeline-ci-cd.html',
  },
  {
    cat: 'cloud', catLabel: 'Cloud', catColor: '#35E7C7',
    title: 'AWS hardening en 14 controles que el auditor SOC 2 va a pedir',
    excerpt: 'CloudTrail, GuardDuty, Config, IAM Access Analyzer — el orden, el costo y qué dejar para el sprint 2.',
    author: 'Gonzalo De Simone', role: 'Co-founder',
    date: '19 Mar 2026', read: '11 min',
    href: 'blog/aws-hardening-soc2.html',
  },
  {
    cat: 'compliance', catLabel: 'Compliance', catColor: '#A335E7',
    title: 'Anexo A.8: Asset Management sin morir en hojas de cálculo',
    excerpt: 'El control que más demora la primera certificación. Cómo Ariana lo automatiza tirando de tus inventarios cloud y endpoints existentes.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '06 Mar 2026', read: '7 min',
    href: 'blog/anexo-a8-asset-management.html',
  },
  {
    cat: 'awareness', catLabel: 'Awareness', catColor: '#FB881D',
    title: 'Phishing simulado: por qué el 38% nunca debería ser tu KPI',
    excerpt: 'Click-rates altos no significan que el programa falle. Datos de 14 campañas en fintechs argentinas y qué métricas sí mover.',
    author: 'Gonzalo De Simone', role: 'Co-founder',
    date: '27 Feb 2026', read: '6 min',
    href: 'blog/phishing-simulado-kpi.html',
  },
  {
    cat: 'pentest', catLabel: 'Pentesting', catColor: '#EC4D2A',
    title: 'API security: los 6 hallazgos que aparecen en cada engagement de fintech',
    excerpt: 'BOLA, mass assignment, JWT misconfig — el top de OWASP API que seguimos viendo en 2026 y cómo prevenirlos en CI.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '16 Feb 2026', read: '8 min',
    href: 'blog/api-security-fintech.html',
  },
  {
    cat: 'opinion', catLabel: 'Opinión', catColor: '#35E747',
    title: 'Por qué dejamos de vender retainers de seguridad',
    excerpt: 'La estructura comercial vieja no sirve para empresas que escalan. Lo que aprendimos al cambiar a packs por outcome.',
    author: 'Brian Suarez', role: 'Co-founder',
    date: '02 Feb 2026', read: '5 min',
    href: 'blog/retainers-vs-outcomes.html',
  },
  {
    cat: 'devsecops', catLabel: 'DevSecOps', catColor: '#3551E7',
    title: 'Threat modeling en 90 minutos: el formato que sí adoptan los devs',
    excerpt: 'STRIDE simplificado para una sesión rápida con el equipo de producto — incluye el template Miro que usamos en cada feature crítica.',
    author: 'Gonzalo De Simone', role: 'Co-founder',
    date: '16 Ene 2026', read: '6 min',
    href: 'blog/threat-modeling-90-minutos.html',
  },
];

const PostCard = ({ post, featured }) => {
  const [hover, setHover] = useStateBL(false);

  if (featured) {
    return (
      <a href={post.href || '#'} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
        style={{ textDecoration: 'none', color: 'inherit', display: 'block' }}>
        <GlassCard radius={32} hover={false} style={{
          padding: 0, overflow: 'hidden', position: 'relative',
          border: `1px solid rgba(255,255,255,${hover ? .18 : .10})`,
          transition: 'all .3s cubic-bezier(.16,1,.3,1)',
        }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', minHeight: 420 }}>
            {/* Visual side */}
            <div style={{
              position: 'relative', overflow: 'hidden',
              background: `radial-gradient(circle at 30% 70%, ${post.catColor}88 0%, transparent 60%), radial-gradient(circle at 80% 20%, #EC008C66 0%, transparent 50%), #1A1A1A`,
              padding: 48,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {/* concentric rings */}
              <div aria-hidden style={{
                position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)',
                width: 360, height: 360, borderRadius: '50%', border: '1px solid rgba(255,255,255,.06)',
              }}>
                <div style={{ position: 'absolute', inset: 50, borderRadius: '50%', border: '1px solid rgba(255,255,255,.05)' }}>
                  <div style={{ position: 'absolute', inset: 50, borderRadius: '50%', border: '1px solid rgba(255,255,255,.04)' }}/>
                </div>
              </div>
              {/* sticker decoration */}
              <div style={{ position: 'relative', zIndex: 2, transform: hover ? 'rotate(-8deg) scale(1.04)' : 'rotate(-12deg)', transition: 'transform .4s cubic-bezier(.16,1,.3,1)' }}>
                <Sticker color={post.catColor} label="ISO 27001" sublabel="GUIDE·01" rotate={0} size={160}/>
              </div>
              <div style={{
                position: 'absolute', top: 20, left: 20,
                fontFamily: 'var(--font-mono)', fontSize: 11, color: 'rgba(255,255,255,.5)',
                letterSpacing: '.10em', textTransform: 'uppercase',
              }}>FEATURED · {post.badge}</div>
            </div>

            {/* Copy side */}
            <div style={{ padding: 48, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
              <div>
                <div style={{
                  fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 11,
                  letterSpacing: '0.18em', textTransform: 'uppercase', color: post.catColor, marginBottom: 16,
                }}>{post.catLabel}</div>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontWeight: 600,
                  fontSize: 'clamp(24px, 2.4vw, 34px)', lineHeight: 1.1,
                  letterSpacing: '-0.025em', color: 'var(--fg)', marginBottom: 20,
                }}>{post.title}</h2>
                <p style={{ fontSize: 16, color: 'var(--fg-muted)', lineHeight: 1.6, marginBottom: 28 }}>
                  {post.excerpt}
                </p>
              </div>

              <div style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                paddingTop: 24, borderTop: '1px solid rgba(255,255,255,.08)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{
                    width: 36, height: 36, borderRadius: '50%',
                    background: `linear-gradient(135deg, ${post.catColor}, ${post.catColor}55)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: 'var(--font-display)', fontWeight: 600, color: '#fff', fontSize: 12,
                    border: '1px solid rgba(255,255,255,.15)',
                  }}>{post.author.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
                  <div>
                    <div style={{ fontSize: 13, color: 'var(--fg)', fontFamily: 'var(--font-display)', fontWeight: 500 }}>{post.author}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-subtle)', letterSpacing: '.06em', textTransform: 'uppercase' }}>{post.role}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)', letterSpacing: '.06em', textTransform: 'uppercase' }}>
                  <span>{post.date}</span>
                  <span>·</span>
                  <span>{post.read}</span>
                  <span style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    width: 36, height: 36, borderRadius: '50%',
                    background: hover ? 'var(--brotek-magenta)' : 'rgba(255,255,255,.06)',
                    border: '1px solid rgba(255,255,255,.10)',
                    color: '#fff', transition: 'all .2s',
                    transform: hover ? 'translateX(4px)' : 'none',
                  }}>
                    <Icon name="arrow-up-right" size={14}/>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </GlassCard>
      </a>
    );
  }

  return (
    <a href={post.href || '#'} onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{ textDecoration: 'none', color: 'inherit', display: 'block' }}>
      <GlassCard radius={20} hover={false} style={{
        padding: 0, overflow: 'hidden', height: '100%',
        display: 'flex', flexDirection: 'column',
        border: `1px solid rgba(255,255,255,${hover ? .18 : .08})`,
        transform: hover ? 'translateY(-3px)' : 'none',
        transition: 'all .3s cubic-bezier(.16,1,.3,1)',
      }}>
        {/* visual block */}
        <div style={{
          position: 'relative', height: 160, overflow: 'hidden',
          background: `linear-gradient(135deg, ${post.catColor}33 0%, transparent 60%), #131313`,
          borderBottom: '1px solid rgba(255,255,255,.06)',
        }}>
          {/* decorative grid */}
          <div aria-hidden style={{
            position: 'absolute', inset: 0,
            backgroundImage: 'linear-gradient(rgba(255,255,255,.04) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,.04) 1px, transparent 1px)',
            backgroundSize: '32px 32px',
            maskImage: 'radial-gradient(ellipse at center, black 30%, transparent 75%)',
          }}/>
          <div aria-hidden style={{
            position: 'absolute', top: -60, right: -60, width: 200, height: 200, borderRadius: '50%',
            background: `radial-gradient(circle, ${post.catColor}66 0%, transparent 70%)`,
            filter: 'blur(20px)',
          }}/>
          {/* glyph */}
          <div style={{
            position: 'absolute', bottom: 16, left: 20,
            fontFamily: 'var(--font-display)', fontWeight: 700,
            fontSize: 64, lineHeight: 1, color: 'var(--fg)', letterSpacing: '-0.04em',
            opacity: 0.12,
          }}>{post.catLabel.charAt(0)}</div>
          <div style={{
            position: 'absolute', top: 16, left: 20,
            fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 10,
            letterSpacing: '0.18em', textTransform: 'uppercase', color: post.catColor,
            padding: '5px 10px', borderRadius: 999,
            background: `${post.catColor}22`, border: `1px solid ${post.catColor}55`,
          }}>{post.catLabel}</div>
        </div>

        <div style={{ padding: 24, display: 'flex', flexDirection: 'column', flex: 1, gap: 14 }}>
          <h3 style={{
            fontFamily: 'var(--font-display)', fontWeight: 600,
            fontSize: 18, lineHeight: 1.25,
            letterSpacing: '-0.015em', color: 'var(--fg)',
          }}>{post.title}</h3>
          <p style={{ fontSize: 13.5, color: 'var(--fg-muted)', lineHeight: 1.55, flex: 1 }}>
            {post.excerpt}
          </p>

          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            paddingTop: 14, borderTop: '1px solid rgba(255,255,255,.06)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                width: 26, height: 26, borderRadius: '50%',
                background: `linear-gradient(135deg, ${post.catColor}, ${post.catColor}55)`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-display)', fontWeight: 600, color: '#fff', fontSize: 10,
                border: '1px solid rgba(255,255,255,.15)',
              }}>{post.author.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
              <div style={{ fontSize: 12, color: 'var(--fg-muted)' }}>{post.author}</div>
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-subtle)', letterSpacing: '.06em', textTransform: 'uppercase' }}>
              {post.read}
            </div>
          </div>
        </div>
      </GlassCard>
    </a>
  );
};

const BlogList = () => {
  const [activeCat, setActiveCat] = useStateBL('all');
  const [search, setSearch] = useStateBL('');
  const [visible, setVisible] = useStateBL(8);

  useEffectBL(() => {
    const onSearch = (e) => { setSearch(e.detail || ''); setVisible(8); };
    window.addEventListener('brotek-search', onSearch);
    return () => window.removeEventListener('brotek-search', onSearch);
  }, []);

  const filtered = useMemoBL(() => {
    const q = search.trim().toLowerCase();
    return POSTS.filter(p => {
      if (activeCat !== 'all' && p.cat !== activeCat) return false;
      if (!q) return true;
      return (p.title + ' ' + p.excerpt + ' ' + p.catLabel).toLowerCase().includes(q);
    });
  }, [activeCat, search]);

  const featured = filtered.find(p => p.featured) || filtered[0];
  const rest = filtered.filter(p => p !== featured).slice(0, visible);

  return (
    <section id="blog-list" data-screen-label="02 Blog grid" style={{ padding: '40px 5vw 80px', position: 'relative' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>

        {/* Filter chips */}
        <div style={{
          display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 48,
          paddingBottom: 24, borderBottom: '1px solid rgba(255,255,255,.06)',
          alignItems: 'center', justifyContent: 'space-between',
        }}>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {CATEGORIES.map(c => {
              const sel = c.key === activeCat;
              return (
                <button key={c.key} onClick={() => { setActiveCat(c.key); setVisible(8); }} style={{
                  background: sel ? c.color : 'rgba(255,255,255,.04)',
                  color: sel ? (c.key === 'all' ? '#171717' : '#fff') : 'var(--fg-muted)',
                  border: `1px solid ${sel ? c.color : 'rgba(255,255,255,.10)'}`,
                  borderRadius: 999, padding: '8px 16px', cursor: 'pointer',
                  fontFamily: 'var(--font-display)', fontWeight: 500, fontSize: 13,
                  transition: 'all .15s',
                  boxShadow: sel && c.key !== 'all' ? `0 0 24px ${c.color}55` : 'none',
                }}>{c.label}</button>
              );
            })}
          </div>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg-subtle)', letterSpacing: '.10em', textTransform: 'uppercase' }}>
            {filtered.length} {filtered.length === 1 ? 'artículo' : 'artículos'}
          </div>
        </div>

        {/* Empty state */}
        {filtered.length === 0 && (
          <GlassCard radius={24} hover={false} style={{ padding: 64, textAlign: 'center' }}>
            <div style={{
              width: 64, height: 64, margin: '0 auto 20px', borderRadius: '50%',
              background: 'rgba(255,255,255,.04)', border: '1px solid rgba(255,255,255,.08)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--fg-muted)',
            }}>
              <Icon name="search" size={24}/>
            </div>
            <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 20, color: 'var(--fg)', marginBottom: 8 }}>
              No encontramos resultados
            </h3>
            <p style={{ color: 'var(--fg-muted)', fontSize: 14 }}>
              Probá otra categoría o quitá la búsqueda.
            </p>
          </GlassCard>
        )}

        {/* Featured */}
        {featured && (
          <div style={{ marginBottom: 32 }}>
            <PostCard post={featured} featured/>
          </div>
        )}

        {/* Grid */}
        {rest.length > 0 && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
            {rest.map((p, i) => <PostCard key={p.title + i} post={p}/>)}
          </div>
        )}

        {/* Load more */}
        {rest.length < filtered.filter(p => p !== featured).length && (
          <div style={{ marginTop: 56, display: 'flex', justifyContent: 'center' }}>
            <Btn variant="ghost" size="lg" icon="plus" onClick={() => setVisible(v => v + 6)}>Cargar más artículos</Btn>
          </div>
        )}
      </div>
    </section>
  );
};

window.BlogList = BlogList;
