import { useState, useEffect } from 'react'

const CMS = 'https://cms.bayerl.cloud/api/buenas'

function normalizePost(p) {
  const meta = p.meta ?? {}
  const ts = Number(p.published_at ?? p.created_at)
  const date = isNaN(ts) ? '' : new Date(ts).toLocaleDateString('pt-BR', {
    day: '2-digit', month: 'long', year: 'numeric'
  })
  return { id: p.id, slug: p.slug, title: p.title, date, excerpt: meta.excerpt ?? '', image: meta.featured_image ?? '' }
}

export default function HomeBlogSection() {
  const [posts, setPosts] = useState([])

  useEffect(() => {
    fetch(`${CMS}/posts?limit=3`)
      .then(r => r.json())
      .then(({ data }) => setPosts(data.map(normalizePost)))
      .catch(() => {})
  }, [])

  if (posts.length === 0) return null

  const [featured, ...secondary] = posts

  return (
    <section className="hbs-section">
      <div className="hbs-inner">
        {/* header */}
        <div className="hbs-header">
          <div>
            <h2 className="hbs-title">Blog</h2>
            <div className="hbs-line" />
          </div>
          <a href="/blog/" className="hbs-ver-tudo">
            VER TUDO
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M9 6L15 12L9 18" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </a>
        </div>

        {/* grid */}
        <div className="hbs-grid">
          {/* card destaque (metade esquerda) */}
          <a href={`/${featured.slug}/`} className="hbs-card hbs-card--featured">
            <div className="hbs-card-img" style={{ backgroundImage: featured.image ? `url("${featured.image}")` : undefined }} />
            <div className="hbs-card-overlay" />
            <div className="hbs-card-content">
              {featured.date && <span className="hbs-card-date">{featured.date}</span>}
              <h3 className="hbs-card-title">{featured.title}</h3>
              {featured.excerpt && <p className="hbs-card-excerpt">{featured.excerpt}</p>}
              <span className="hbs-card-cta">Ler artigo →</span>
            </div>
          </a>

          {/* coluna direita: 2 cards menores empilhados */}
          <div className="hbs-secondary">
            {secondary.map(p => (
              <a key={p.slug} href={`/${p.slug}/`} className="hbs-card hbs-card--secondary">
                <div className="hbs-card-img" style={{ backgroundImage: p.image ? `url("${p.image}")` : undefined }} />
                <div className="hbs-card-overlay" />
                <div className="hbs-card-content">
                  {p.date && <span className="hbs-card-date">{p.date}</span>}
                  <h3 className="hbs-card-title">{p.title}</h3>
                  <span className="hbs-card-cta">Ler artigo →</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      </div>
    </section>
  )
}
