/* global React, ReactDOM */
const { useState, useEffect } = React;
const { BlogHeader, BlogFooter, formatDate, fetchJSON } = window.BlogParts;

function BlogIndex() {
  const [state, setState] = useState({ status: 'loading', posts: [], error: null });
  const activeTag = new URLSearchParams(window.location.search).get('tag');

  useEffect(() => {
    const url = activeTag ? `/api/posts?tag=${encodeURIComponent(activeTag)}` : '/api/posts';
    fetchJSON(url)
      .then((data) => setState({ status: 'ready', posts: data.posts || [], error: null }))
      .catch((err) => setState({ status: 'error', posts: [], error: err.message }));
  }, [activeTag]);

  useEffect(() => { if (window.lucide) window.lucide.createIcons(); });

  return (
    <div className="site">
      <BlogHeader />
      <main>
        <section className="hero hero--blog">
          <div className="hero__grid" />
          <div className="container hero__inner" style={{ paddingBlock: 'clamp(56px,8vw,96px)' }}>
            <span className="eyebrow eyebrow--dark"><span className="cds-tick" /> Insights</span>
            <h1 style={{ marginTop: 'var(--space-4)' }}>The Blog</h1>
            <p className="hero__lede">Notes on data, AI, and value creation across the investment lifecycle.</p>
          </div>
        </section>

        <section className="section">
          <div className="container">
            {activeTag && (
              <div className="tag-filter">
                Filtering by <span className="post-tag post-tag--active">{activeTag}</span>
                <a className="tag-filter__clear" href="/blog.html">Clear ✕</a>
              </div>
            )}
            {state.status === 'loading' && <p className="blog-muted">Loading posts…</p>}
            {state.status === 'error' && <p className="blog-muted">Couldn’t load posts: {state.error}</p>}
            {state.status === 'ready' && state.posts.length === 0 && (
              <p className="blog-muted">{activeTag ? `No posts tagged “${activeTag}”.` : 'No posts yet — check back soon.'}</p>
            )}
            <div className="post-list">
              {state.posts.map((p) => (
                <a className="post-card" key={p.slug} href={`/post.html?slug=${encodeURIComponent(p.slug)}`}>
                  {p.cover_image && <img className="post-card__cover" src={p.cover_image} alt="" loading="lazy" />}
                  <div className="post-card__body">
                    <div className="post-card__date">{formatDate(p.published_at)}</div>
                    <h2 className="post-card__title">{p.title}</h2>
                    {p.excerpt && <p className="post-card__excerpt">{p.excerpt}</p>}
                    {Array.isArray(p.tags) && p.tags.length > 0 && (
                      <div className="post-tags">{p.tags.map((t) => <span className="post-tag" key={t}>{t}</span>)}</div>
                    )}
                    <span className="post-card__more">Read article <i data-lucide="arrow-right" style={{ width: 14, height: 14 }} /></span>
                  </div>
                </a>
              ))}
            </div>
          </div>
        </section>
      </main>
      <BlogFooter />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<BlogIndex />);
