// Página /blog/ — listado de artículos con filtros por categoría
// Composante exposé sur window.BlogIndex.
// Usa BLOG_ARTICLES + BLOG_CATEGORIES + BlogCover de blog-data.jsx.

const BlogCard = ({ article, layout = 'grid' }) => {
  const isFeatured = layout === 'featured';
  const cardCtx = (typeof useCountry === 'function') ? useCountry() : null;
  const cardCountry = (cardCtx && cardCtx.country) || 'co';
  return (
    <a
      href={`/${cardCountry}/blog/${article.slug}/`}
      className="reveal cb-blog-card"
      style={{
        display: isFeatured ? 'grid' : 'flex',
        gridTemplateColumns: isFeatured ? 'minmax(0, 1.05fr) minmax(0, 1fr)' : undefined,
        flexDirection: isFeatured ? undefined : 'column',
        gap: isFeatured ? 0 : 0,
        background: '#fff',
        border: '1px solid var(--border)',
        borderRadius: 18,
        overflow: 'hidden',
        transition: 'border-color 0.25s ease, box-shadow 0.25s ease, transform 0.25s ease',
        textDecoration: 'none',
        color: 'inherit',
        height: '100%',
      }}
    >
      <div style={{
        width: '100%',
        height: isFeatured ? '100%' : 'auto',
        minHeight: isFeatured ? 320 : 0,
      }}>
        <BlogCover
          eyebrow={article.coverEyebrow}
          title={article.title}
          variant={article.coverVariant}
          size={isFeatured ? 'lg' : 'md'}
        />
      </div>
      <div style={{
        padding: isFeatured ? '40px 44px' : '24px 26px 26px',
        display: 'flex',
        flexDirection: 'column',
        gap: isFeatured ? 16 : 12,
        flex: 1,
      }}>
        <div className="mono" style={{
          display: 'flex', alignItems: 'center', gap: 10,
          fontSize: 11, color: 'var(--fg-muted)',
          textTransform: 'uppercase', letterSpacing: '0.1em',
        }}>
          <span>{article.categoryLabel}</span>
          <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--fg-faint)' }} />
          <span>{article.dateLabel}</span>
        </div>

        <h3 style={{
          fontSize: isFeatured ? 'clamp(24px, 2.4vw, 30px)' : 20,
          fontWeight: 500,
          letterSpacing: '-0.015em',
          lineHeight: 1.22,
          textWrap: 'balance',
          color: 'var(--fg)',
        }}>
          {article.title}
        </h3>

        <p style={{
          fontSize: isFeatured ? 16 : 14.5,
          color: 'var(--fg-soft)',
          lineHeight: 1.6,
          textWrap: 'pretty',
          flex: 1,
        }}>
          {article.excerpt}
        </p>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 14, fontWeight: 500,
          marginTop: 4,
        }}>
          <span className="cb-blog-card-cta">Leer artículo</span>
          <span className="cb-blog-card-arrow" style={{ transition: 'transform 0.25s ease' }}>→</span>
        </div>
      </div>
    </a>
  );
};

const BlogIndex = () => {
  const [active, setActive] = React.useState('todos');
  const ctx = (typeof useCountry === 'function') ? useCountry() : null;
  const country = (ctx && ctx.country) || 'co';
  const articlesAll = (typeof getBlogArticles === 'function') ? getBlogArticles(country) : BLOG_ARTICLES;

  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.1, rootMargin: '0px 0px -10% 0px' });
    document.querySelectorAll('.reveal').forEach(el => obs.observe(el));
    return () => obs.disconnect();
  }, [active]);

  const articles = active === 'todos'
    ? articlesAll
    : articlesAll.filter(a => a.category === active);

  const featured = active === 'todos' ? articlesAll.find(a => a.featured) : null;
  const rest = featured ? articles.filter(a => a.slug !== featured.slug) : articles;

  // Filtres catégories : on n'affiche que celles présentes (+ "Todos")
  const presentIds = new Set(articlesAll.map(a => a.category));
  const visibleCats = BLOG_CATEGORIES.filter(c => c.id === 'todos' || presentIds.has(c.id));

  return (
    <>
      <Nav />
      <main>
        {/* Hero */}
        <section style={{ paddingTop: 140, paddingBottom: 56, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: -260, left: '20%', width: 560, height: 560, borderRadius: '50%', background: 'radial-gradient(circle, rgba(84,181,227,0.18) 0%, transparent 70%)', filter: 'blur(40px)' }} />
            <div style={{ position: 'absolute', top: -200, right: '15%', width: 480, height: 480, borderRadius: '50%', background: 'radial-gradient(circle, rgba(198,156,255,0.18) 0%, transparent 70%)', filter: 'blur(40px)' }} />
          </div>
          <div className="container" style={{ position: 'relative' }}>
            <div style={{ textAlign: 'center', maxWidth: 820, margin: '0 auto' }}>
              <div className="reveal in" style={{ marginBottom: 26 }}>
                <div className="eyebrow"><span className="eyebrow-dot" />Blog</div>
              </div>
              <h1 className="h1 reveal in reveal-delay-1" style={{ marginBottom: 22, textWrap: 'balance', fontSize: 'clamp(36px, 5.2vw, 60px)' }}>
                Ideas, guías y estrategias para{' '}
                <span className="serif" style={{ fontStyle: 'italic' }}>agencias inmobiliarias.</span>
              </h1>
              <p className="reveal in reveal-delay-2" style={{ fontSize: 18, color: 'var(--fg-soft)', textWrap: 'pretty', maxWidth: 640, margin: '0 auto' }}>
                Todo lo que aprendemos construyendo CloserBroker junto a agencias de México, Colombia y toda LATAM.
              </p>
            </div>
          </div>
        </section>

        {/* Filtros */}
        <section style={{ paddingTop: 8, paddingBottom: 40 }}>
          <div className="container">
            <div className="reveal in" style={{
              display: 'flex',
              flexWrap: 'wrap',
              justifyContent: 'center',
              gap: 8,
            }}>
              {visibleCats.map(cat => {
                const isActive = active === cat.id;
                return (
                  <button
                    key={cat.id}
                    onClick={() => setActive(cat.id)}
                    className="cb-blog-chip"
                    style={{
                      padding: '8px 16px',
                      fontSize: 13,
                      fontWeight: 500,
                      borderRadius: 999,
                      border: '1px solid',
                      borderColor: isActive ? 'transparent' : 'var(--border)',
                      background: isActive ? 'var(--fg)' : '#fff',
                      color: isActive ? '#fff' : 'var(--fg-soft)',
                      transition: 'all 0.2s ease',
                      cursor: 'pointer',
                    }}
                  >
                    {cat.label}
                  </button>
                );
              })}
            </div>
          </div>
        </section>

        {/* Featured post */}
        {featured && (
          <section style={{ paddingTop: 0, paddingBottom: 48 }}>
            <div className="container">
              <BlogCard article={featured} layout="featured" />
            </div>
          </section>
        )}

        {/* Grille articles */}
        <section style={{ paddingTop: featured ? 8 : 0, paddingBottom: 96 }}>
          <div className="container">
            {rest.length === 0 ? (
              <div className="reveal in" style={{
                textAlign: 'center', padding: '64px 32px',
                color: 'var(--fg-muted)', fontSize: 16,
              }}>
                Pronto publicaremos artículos en esta categoría.
              </div>
            ) : (
              <div style={{
                display: 'grid',
                gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))',
                gap: 28,
              }}>
                {rest.map(article => (
                  <BlogCard key={article.slug} article={article} />
                ))}
              </div>
            )}
          </div>
        </section>
      </main>
      <Footer />
      <WhatsAppButton />

      <style>{`
        .cb-blog-card { display: flex; }
        .cb-blog-card:hover {
          border-color: rgba(198,156,255,0.55) !important;
          box-shadow: 0 18px 40px -20px rgba(84,181,227,0.30);
          transform: translateY(-3px);
        }
        .cb-blog-card:hover .cb-blog-card-cta {
          background-image: var(--grad);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
        }
        .cb-blog-card:hover .cb-blog-card-arrow {
          transform: translateX(4px);
          background-image: var(--grad);
          -webkit-background-clip: text;
          background-clip: text;
          color: transparent;
        }
        .cb-blog-chip:hover {
          border-color: var(--fg) !important;
        }
        @media (max-width: 760px) {
          .cb-blog-card[style*="grid-template-columns"] {
            display: flex !important;
            flex-direction: column !important;
          }
          /* Featured card body — reduce padding from 40x44 to a comfortable mobile size */
          .cb-blog-card[style*="grid-template-columns"] > div:last-child {
            padding: 24px 22px 26px !important;
            gap: 12px !important;
          }
          /* Featured card cover — reduce minHeight on mobile */
          .cb-blog-card[style*="grid-template-columns"] > div:first-child {
            min-height: 200px !important;
          }
          /* Featured card title — slightly smaller on mobile */
          .cb-blog-card[style*="grid-template-columns"] h3 {
            font-size: 22px !important;
          }
        }
      `}</style>
    </>
  );
};

window.BlogIndex = BlogIndex;
