/* Blog index — dinámico desde Notion */

const BlogHero = () => (
  <section className="amp-px" style={{ padding: '80px 48px 48px', background: '#F8F7F3' }}>
    <div style={{ maxWidth: 1440, margin: '0 auto' }}>
      <div style={{ fontSize: 12, color: 'rgba(26,26,24,0.5)', marginBottom: 24,
        display: 'flex', alignItems: 'center', gap: 8 }}>
        <a href="/" style={{ color: 'rgba(26,26,24,0.5)', textDecoration: 'none' }}>Ampera</a>
        <span>›</span>
        <span style={{ color: '#0F3518' }}>Blog</span>
      </div>
      <div className="amp-g2" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, alignItems: 'end' }}>
        <div>
          <Eyebrow>Recursos · Blog Ampera</Eyebrow>
          <h1 className="amp-t-xl" style={{ fontFamily: 'Inter', fontSize: 72, fontWeight: 700, color: '#0F3518',
            margin: '20px 0 24px', letterSpacing: '-.02em', lineHeight: 1.05, textWrap: 'balance' }}>
            Ideas que <span style={{ color: '#C4A84F' }}>iluminan</span> tu decisión energética
          </h1>
        </div>
        <p style={{ fontSize: 17, color: 'rgba(26,26,24,0.7)', lineHeight: 1.7, margin: 0, maxWidth: 480 }}>
          Análisis, guías técnicas y casos reales sobre energía solar, regulación colombiana y tecnología energética. Para tomar decisiones informadas.
        </p>
      </div>
    </div>
  </section>
);

const Featured = ({ a }) => (
  <section className="amp-px" style={{ padding: '32px 48px 48px', background: '#F8F7F3' }}>
    <div style={{ maxWidth: 1440, margin: '0 auto' }}>
      <a href={'/recursos/' + a.slug + '/'} style={{ textDecoration: 'none', color: 'inherit' }}>
        <div className="amp-g2" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 0,
          background: '#fff', borderRadius: 16, overflow: 'hidden',
          boxShadow: '0 8px 32px rgba(15,53,24,0.08)',
          transition: 'transform .25s, box-shadow .25s' }}
          onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 16px 48px rgba(15,53,24,0.14)'; }}
          onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = '0 8px 32px rgba(15,53,24,0.08)'; }}>
          <div className="amp-feat-img" style={{ height: 480, backgroundImage: `url(${a.image})`,
            backgroundSize: 'cover', backgroundPosition: 'center', backgroundColor: '#E9E8E4' }}/>
          <div style={{ padding: 48, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '5px 12px', borderRadius: 9999,
              background: 'rgba(196,168,79,0.14)', color: '#8B7232',
              fontSize: 11, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase',
              alignSelf: 'flex-start', marginBottom: 20 }}>★ Destacado · {a.category}</div>
            <h2 style={{ fontFamily: 'Inter', fontSize: 36, fontWeight: 600, color: '#0F3518',
              margin: '0 0 16px', letterSpacing: '-.01em', lineHeight: 1.2, textWrap: 'balance' }}>{a.title}</h2>
            <p style={{ fontSize: 16, color: 'rgba(26,26,24,0.7)', lineHeight: 1.65, margin: '0 0 24px' }}>{a.excerpt}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 13,
              color: 'rgba(26,26,24,0.55)' }}>
              <span style={{ fontWeight: 600, color: '#1B5C2C' }}>{a.author}</span>
              <span>·</span>
              <span>{a.date}</span>
              <span>·</span>
              <span>{a.readText}</span>
            </div>
            <div style={{ alignSelf: 'flex-start', marginTop: 28 }}>
              <span style={{
                display: 'inline-flex', alignItems: 'center', gap: 8,
                background: '#0F3518', color: '#fff',
                padding: '12px 24px', borderRadius: 50,
                fontFamily: 'Inter', fontWeight: 700, fontSize: 14,
                boxShadow: '0 4px 16px rgba(15,53,24,0.2)',
              }}>Leer artículo completo →</span>
            </div>
          </div>
        </div>
      </a>
    </div>
  </section>
);

const ArticleCard = ({ a }) => (
  <a href={'/recursos/' + a.slug + '/'} style={{ textDecoration: 'none', color: 'inherit' }}>
    <article style={{ background: '#fff', borderRadius: 16, overflow: 'hidden',
      transition: 'transform .2s, box-shadow .2s', cursor: 'pointer', height: '100%',
      display: 'flex', flexDirection: 'column' }}
      onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-4px)'; e.currentTarget.style.boxShadow = '0 12px 32px rgba(15,53,24,0.12)'; }}
      onMouseLeave={e => { e.currentTarget.style.transform = 'translateY(0)'; e.currentTarget.style.boxShadow = 'none'; }}>
      <div style={{ height: 220, backgroundImage: `url(${a.image})`,
        backgroundSize: 'cover', backgroundPosition: 'center', backgroundColor: '#E9E8E4' }}/>
      <div style={{ padding: 28, flex: 1, display: 'flex', flexDirection: 'column' }}>
        <div style={{ display: 'inline-flex', alignSelf: 'flex-start',
          padding: '4px 10px', borderRadius: 9999,
          background: 'rgba(27,92,44,0.10)', color: '#1B5C2C',
          fontSize: 10, fontWeight: 700, letterSpacing: '.12em', textTransform: 'uppercase',
          marginBottom: 16 }}>{a.category}</div>
        <h3 style={{ fontFamily: 'Inter', fontSize: 20, fontWeight: 600, color: '#0F3518',
          margin: '0 0 12px', lineHeight: 1.3, textWrap: 'balance', flex: 1 }}>{a.title}</h3>
        <p style={{ fontSize: 14, color: 'rgba(26,26,24,0.65)', lineHeight: 1.6, margin: '0 0 16px' }}>{a.excerpt}</p>
        <div style={{ marginTop: 'auto', paddingTop: 16,
          borderTop: '1px solid rgba(15,53,24,0.07)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontSize: 12, color: 'rgba(26,26,24,0.48)' }}>
            <span>{a.date}</span>
            <span style={{ margin: '0 6px' }}>·</span>
            <span>{a.readText}</span>
          </div>
          <span style={{ fontSize: 13, fontWeight: 700, color: '#1B5C2C',
            display: 'flex', alignItems: 'center', gap: 4 }}>
            Leer <span style={{ fontSize: 16 }}>→</span>
          </span>
        </div>
      </div>
    </article>
  </a>
);

const BlogPage = () => {
  const [articles, setArticles] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [activeCategory, setActiveCategory] = React.useState('Todos');
  const [search, setSearch] = React.useState('');

  React.useEffect(() => {
    fetch('/get-blog-posts')
      .then(r => r.json())
      .then(data => {
        if (data.articles) setArticles(data.articles);
        else setError(data.error || 'Error cargando artículos');
        setLoading(false);
      })
      .catch(e => { setError(e.message); setLoading(false); });
  }, []);

  const categories = ['Todos', ...new Set(articles.map(a => a.category).filter(Boolean))];
  const filtered = articles.filter(a => {
    const matchCat = activeCategory === 'Todos' || a.category === activeCategory;
    const matchSearch = !search || a.title.toLowerCase().includes(search.toLowerCase()) || a.excerpt.toLowerCase().includes(search.toLowerCase());
    return matchCat && matchSearch;
  });
  const featured = filtered.find(a => a.featured) || filtered[0];
  const rest = filtered.filter(a => a !== featured);

  return (
    <>
      <BlogHero/>

      <div className="amp-px" style={{ padding: '24px 48px 0', background: '#F8F7F3' }}>
        <div style={{ maxWidth: 1440, margin: '0 auto' }}>
          <div className="amp-filter-bar" style={{ display: 'flex', gap: 8,
            alignItems: 'center', flexWrap: 'wrap', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {categories.map(c => {
                const isActive = activeCategory === c;
                return (
                  <button key={c} onClick={() => setActiveCategory(c)} style={{
                    padding: '8px 16px', borderRadius: 9999,
                    fontFamily: 'Inter', fontSize: 13, fontWeight: 600,
                    border: '1px solid',
                    borderColor: isActive ? '#C4A84F' : 'rgba(15,53,24,0.12)',
                    background: isActive ? '#C4A84F' : 'transparent',
                    color: isActive ? '#0F3518' : 'rgba(26,26,24,0.7)',
                    cursor: 'pointer', transition: 'all .2s',
                  }}>{c}</button>
                );
              })}
            </div>
            <div className="amp-filter-search" style={{ position: 'relative' }}>
              <Icon name="search" size={18} color="rgba(26,26,24,0.45)" style={{
                position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)'
              }}/>
              <input value={search} onChange={e => setSearch(e.target.value)}
                placeholder="Buscar artículos…" style={{
                fontFamily: 'Inter', fontSize: 14, padding: '10px 16px 10px 40px',
                border: '1px solid rgba(15,53,24,0.12)', borderRadius: 9999,
                background: '#fff', width: 260, outline: 'none', color: '#1A1A18',
              }}/>
            </div>
          </div>
        </div>
      </div>

      {loading && (
        <section style={{ padding: '80px 48px', background: '#F8F7F3', textAlign: 'center' }}>
          <p style={{ color: 'rgba(26,26,24,0.5)' }}>Cargando artículos…</p>
        </section>
      )}

      {error && (
        <section style={{ padding: '80px 48px', background: '#F8F7F3', textAlign: 'center' }}>
          <p style={{ color: '#B33' }}>Error: {error}</p>
        </section>
      )}

      {!loading && !error && filtered.length === 0 && (
        <section style={{ padding: '80px 48px', background: '#F8F7F3', textAlign: 'center' }}>
          <p style={{ color: 'rgba(26,26,24,0.5)' }}>No hay artículos publicados aún.</p>
        </section>
      )}

      {!loading && featured && <Featured a={featured}/>}

      {rest.length > 0 && (
        <section className="amp-px" style={{ padding: '0 48px 96px', background: '#F8F7F3' }}>
          <div style={{ maxWidth: 1440, margin: '0 auto' }}>
            <div className="amp-g3" style={{
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
              {rest.map(a => <ArticleCard key={a.slug} a={a}/>)}
            </div>
          </div>
        </section>
      )}
    </>
  );
};

window.BlogPage = BlogPage;
