// ─── Blog Listing App ───

function ListingHero() {
  return (
    <section className="blog-hero">
      <div className="container">
        <h1>The Long Game.</h1>
        <p className="sub">For people who did the research and stayed.</p>
      </div>
    </section>
  );
}

function FilterBar({ active, onChange, categories }) {
  return (
    <div className="filter-bar">
      <button
        className={`pill ${active === "all" ? "pill-active" : ""}`}
        onClick={() => onChange("all")}
        style={{ border: active === "all" ? undefined : undefined }}
      >
        All
      </button>
      {Object.entries(categories).map(([key, cat]) => (
        <button
          key={key}
          className={`pill ${active === key ? "pill-active" : ""}`}
          onClick={() => onChange(key)}
        >
          <span className="pill-dot" style={{
            background: active === key ? "var(--night)" : cat.dot,
            ...(cat.border && active !== key ? { border: "1px solid #ccc" } : {})
          }} />
          {cat.label}
        </button>
      ))}
    </div>
  );
}

function FeaturedPost({ post }) {
  if (!post) return null;
  return (
    <a href={`/blog/${post.slug}/`} className="featured-card" style={{ color: "inherit" }}>
      <div className="featured-text">
        <h2>{post.title}</h2>
        <p className="deck">{post.deck}</p>
        <div className="meta">{formatDate(post.date)} · {post.readingTime} min read</div>
      </div>
      {post.heroImage ? (
        <img src={post.heroImage} alt={post.heroAlt || post.title} className="featured-img" />
      ) : (
        <div className="featured-img" style={{ background: "var(--night)" }} />
      )}
    </a>
  );
}

function ListingApp() {
  const [posts, setPosts] = React.useState([]);
  const [filter, setFilter] = React.useState("all");
  const [visible, setVisible] = React.useState(6);
  const [loaded, setLoaded] = React.useState(false);

  React.useEffect(() => {
    fetch("posts.json")
      .then(r => r.json())
      .then(data => {
        // Sort newest first
        data.sort((a, b) => b.date.localeCompare(a.date));
        setPosts(data);
        setLoaded(true);
      })
      .catch(() => setLoaded(true));
  }, []);

  const filtered = filter === "all" ? posts : posts.filter(p => p.category === filter);
  const featured = posts[0];
  const gridPosts = filtered.filter(p => p !== featured).slice(0, visible);
  const hasMore = filtered.filter(p => p !== featured).length > visible;

  if (!loaded) return null;

  return (
    <>
      <BlogNav />
      <ListingHero />

      <div className="container">
        <FilterBar active={filter} onChange={(cat) => { setFilter(cat); setVisible(6); }} categories={CATEGORIES} />

        {filter === "all" && featured && <FeaturedPost post={featured} />}

        {gridPosts.length > 0 ? (
          <div className="post-grid">
            {gridPosts.map(post => <PostCard key={post.slug} post={post} />)}
          </div>
        ) : (
          <div style={{ textAlign: "center", padding: "48px 0", color: "var(--ink-3)" }}>
            <p style={{ fontFamily: "var(--font-display)", fontSize: 18 }}>No posts yet in this category.</p>
            <p style={{ fontSize: 14, marginTop: 8 }}>Check back soon.</p>
          </div>
        )}

        {hasMore && (
          <div className="load-more-wrap">
            <button className="btn btn-ghost" onClick={() => setVisible(v => v + 6)}>
              More posts
            </button>
          </div>
        )}
      </div>

      <NewsletterCTA />
      <BlogFooter />
    </>
  );
}

// ─── Mount ───
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<ListingApp />);
