// Home Blog section — đọc danh sách bài viết từ <script id="cnv-recent-posts">
// (Statamic Antlers inject JSON vào HTML lúc server render).

// Read posts NGAY khi script chạy (chứ không trong useEffect) — tránh trường hợp
// component nhận posts=[] ở render đầu rồi user không thấy gì nếu state update bị skip.
function readInitialPosts() {
  if (typeof document === 'undefined') return [];
  const node = document.getElementById('cnv-recent-posts');
  if (!node) return [];
  try {
    const data = JSON.parse(node.textContent || '[]');
    return Array.isArray(data) ? data : [];
  } catch (_) {
    return [];
  }
}

const HomeBlog = () => {
  const [posts] = React.useState(readInitialPosts);

  // Render section luôn (kể cả khi posts rỗng) — empty state hiện link tới /blog

  return (
    <section style={{ background: '#FAF7F4', padding: '110px 64px', color: '#0A0E1A' }}>
      <div style={{ maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 32, marginBottom: 48, flexWrap: 'wrap' }}>
          <div style={{ maxWidth: 640 }}>
            <PinkEyebrow style={{ marginBottom: 16 }}>BLOG · KINH NGHIỆM</PinkEyebrow>
            <h2 style={{ fontFamily: 'Inter, sans-serif', fontWeight: 800, fontSize: 'clamp(28px, 4vw, 44px)', letterSpacing: '-0.03em', lineHeight: 1.1, margin: '0 0 12px' }}>
              Đúc kết từ <PinkGradientText gradient={PINK_CYAN_GRAD}>3,000+ doanh nghiệp Việt</PinkGradientText>
            </h2>
            <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 16, color: 'rgba(10,14,26,0.6)', lineHeight: 1.55, margin: 0 }}>
              Chiến lược CRM, Private Domain Traffic, case study triển khai — góc nhìn thực chiến từ đội ngũ CNV.
            </p>
          </div>
          <a href="/blog" style={{
            display: 'inline-flex', alignItems: 'center', gap: 6,
            padding: '12px 22px', borderRadius: 999,
            border: '1px solid rgba(10,14,26,0.18)', color: '#0A0E1A',
            fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 600,
            textDecoration: 'none', transition: 'all .15s',
          }}
            onMouseEnter={(e) => { e.currentTarget.style.borderColor = '#FF688E'; e.currentTarget.style.color = '#D0336A'; }}
            onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'rgba(10,14,26,0.18)'; e.currentTarget.style.color = '#0A0E1A'; }}>
            Xem tất cả bài viết
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M5 12h14m-6-6l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </a>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          {posts.map((p, i) => (
            <a key={p.url || i} href={p.url} style={{
              background: '#fff', borderRadius: 16, padding: '28px 26px',
              border: '1px solid rgba(10,14,26,0.08)',
              display: 'flex', flexDirection: 'column',
              textDecoration: 'none', color: 'inherit',
              transition: 'transform .2s, box-shadow .2s, border-color .2s',
            }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateY(-4px)';
                e.currentTarget.style.boxShadow = `0 16px 40px ${PINK[400]}26`;
                e.currentTarget.style.borderColor = `${PINK[400]}66`;
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateY(0)';
                e.currentTarget.style.boxShadow = 'none';
                e.currentTarget.style.borderColor = 'rgba(10,14,26,0.08)';
              }}>
              {p.category && (
                <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: PINK[600], marginBottom: 10 }}>{p.category}</div>
              )}
              <h3 style={{ fontFamily: 'Inter, sans-serif', fontSize: 19, fontWeight: 800, letterSpacing: '-0.02em', lineHeight: 1.25, margin: '0 0 10px', color: '#0A0E1A' }}>{p.title}</h3>
              {p.excerpt && (
                <p style={{ fontFamily: 'Inter, sans-serif', fontSize: 14, color: 'rgba(10,14,26,0.6)', lineHeight: 1.6, margin: '0 0 18px', flex: 1 }}>{p.excerpt}</p>
              )}
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 12.5, color: 'rgba(10,14,26,0.45)', display: 'flex', gap: 10, paddingTop: 14, borderTop: '1px solid rgba(10,14,26,0.06)' }}>
                {p.date && <span>{p.date}</span>}
                {p.read_time && <span>· {p.read_time} phút</span>}
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

Object.assign(window, { HomeBlog });
