/* global React */
const { useState, useEffect, useRef } = React;

function useReveal() {
  const ioRef = useRef(null);
  if (!ioRef.current && typeof IntersectionObserver !== "undefined") {
    ioRef.current = new IntersectionObserver((es) => {
      es.forEach((e) => {
        if (e.isIntersecting) { e.target.dataset.rv = "1"; ioRef.current.unobserve(e.target); }
      });
    }, { threshold: 0.12 });
  }
  React.useLayoutEffect(() => {
    document.querySelectorAll(".reveal:not([data-rv])").forEach((el) => {
      if (ioRef.current) ioRef.current.observe(el);
      else el.dataset.rv = "1";
    });
  });
}

const LANGUAGE_LABELS = {
  'all': 'All',
  'en': '🇺🇸 English',
  'es': '🇦🇷 Español'
};

function BlogList() {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [language, setLanguage] = useState('all');
  useReveal();

  useEffect(() => {
    fetch('/blog/manifest.json')
      .then(r => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then(data => {
        const arr = Array.isArray(data) ? data : (data.articles || []);
        setPosts(arr.sort((a, b) => new Date(b.date) - new Date(a.date)));
        setLoading(false);
      })
      .catch(err => {
        console.error('Error loading posts:', err);
        setLoading(false);
      });
  }, []);

  const filteredPosts = language === 'all'
    ? posts
    : posts.filter(post => post.language === language);

  if (loading) {
    return (
      <div className="wrap" style={{ minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <p>Loading posts...</p>
      </div>
    );
  }

  return (
    <section className="blog-section">
      <div className="wrap">
        <div className="blog-header">
          <p className="eyebrow">Blog</p>
          <h1>Articles & Stories</h1>
          <p className="blog-intro" style={{ color: 'var(--fog)' }}>Documenting our journey building products.</p>
        </div>

        <div className="language-filter">
          {['all', 'en', 'es'].map(lang => (
            <button
              key={lang}
              className={`filter-btn ${language === lang ? 'active' : ''}`}
              onClick={() => setLanguage(lang)}
            >
              {LANGUAGE_LABELS[lang]}
            </button>
          ))}
        </div>

        {filteredPosts.length === 0 ? (
          <div style={{ textAlign: 'center', padding: '60px 0' }}>
            <p style={{ color: 'var(--ash)' }}>No posts in this language. Check back soon.</p>
          </div>
        ) : (
          <div className="posts-grid">
            {filteredPosts.map((post) => (
              <article
                key={post.slug}
                className="post-card"
                onClick={() => {
                  window.location.hash = `#${post.slug}`;
                }}
                style={{ cursor: 'pointer' }}
              >
                <div className="post-card-content">
                  <div className="post-card-header">
                    <h2 className="post-title">{post.title}</h2>
                    {post.language && (
                      <span className="language-badge">
                        {LANGUAGE_LABELS[post.language]}
                      </span>
                    )}
                  </div>
                  <p className="post-excerpt" style={{ color: 'var(--fog)' }}>{post.excerpt}</p>
                  {post.tags && post.tags.length > 0 && (
                    <div className="post-tags">
                      {post.tags.slice(0, 3).map(tag => (
                        <span key={tag} className="post-tag">{tag}</span>
                      ))}
                      {post.tags.length > 3 && <span className="post-tag-more">+{post.tags.length - 3}</span>}
                    </div>
                  )}
                  <div className="post-meta">
                    <time dateTime={post.date}>
                      {new Date(post.date).toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric',
                      })}
                    </time>
                    {post.author && <span className="post-author">{post.author}</span>}
                  </div>
                </div>
                <div className="post-arrow">→</div>
              </article>
            ))}
          </div>
        )}

      </div>
    </section>
  );
}

window.BlogList = BlogList;
