"use client";

import { useState, useMemo } from "react";
import type { BlogCategory } from "@/data/blog-posts";
import { CATEGORIES, POSTS } from "@/data/blog-posts";
import { BlogCard } from "./BlogCard";
import { BlogFilterBar } from "./BlogFilterBar";
import { BlogFeatured } from "./BlogFeatured";
import { BlogSmiley } from "./BlogSmiley";

const PAGE_SIZE = 6;

export function BlogGrid() {
  const [cat, setCat] = useState<BlogCategory>("All");
  const [query, setQuery] = useState("");
  const [limit, setLimit] = useState(PAGE_SIZE);

  const featured = POSTS.find((p) => p.featured);

  const counts = useMemo(() => {
    const c: Record<string, number> = { All: POSTS.length };
    CATEGORIES.slice(1).forEach((k) => {
      c[k] = POSTS.filter((p) => p.cat === k).length;
    });
    return c;
  }, []);

  const filtered = useMemo(() => {
    const ql = query.trim().toLowerCase();
    return POSTS.filter(
      (p) =>
        (cat === "All" || p.cat === cat) &&
        (!ql || (p.title + " " + p.excerpt).toLowerCase().includes(ql)),
    );
  }, [cat, query]);

  const isDefault = cat === "All" && !query.trim();
  const gridPosts = isDefault ? filtered.filter((p) => !p.featured) : filtered;
  const shown = gridPosts.slice(0, limit);

  const handleCatChange = (c: BlogCategory) => {
    setCat(c);
    setLimit(PAGE_SIZE);
  };
  const handleQueryChange = (q: string) => {
    setQuery(q);
    setLimit(PAGE_SIZE);
  };

  return (
    <>
      {/* Featured post (only in default view) */}
      {isDefault && featured && <BlogFeatured post={featured} />}

      {/* Filter bar */}
      <BlogFilterBar
        categories={CATEGORIES}
        activeCat={cat}
        onCatChange={handleCatChange}
        query={query}
        onQueryChange={handleQueryChange}
        counts={counts}
      />

      {/* Grid */}
      <div
        className="b-wrap"
        style={{ paddingTop: 36, paddingBottom: 24, minHeight: 320 }}
      >
        {gridPosts.length === 0 ? (
          <div className="b-empty">
            <BlogSmiley
              size={56}
              bg="rgba(21,21,25,.06)"
              face="var(--b-ink-faint)"
            />
            <h3>
              Nothing here{" "}
              <span className="b-serif" style={{ fontWeight: 500 }}>
                yet.
              </span>
            </h3>
            <p>
              No articles match &ldquo;{query}&rdquo;. Try another search or
              category.
            </p>
            <button
              className="b-btn b-btn-ghost"
              style={{ marginTop: 18 }}
              onClick={() => {
                setQuery("");
                setCat("All");
              }}
            >
              Clear filters
            </button>
          </div>
        ) : (
          <>
            <div
              style={{
                display: "flex",
                alignItems: "baseline",
                gap: 12,
                marginBottom: 22,
              }}
            >
              <h2 className="b-grid-label">
                {isDefault
                  ? "Latest articles"
                  : cat === "All"
                    ? "Results"
                    : cat}
              </h2>
              <span className="b-grid-count">
                {gridPosts.length}{" "}
                {gridPosts.length === 1 ? "article" : "articles"}
              </span>
            </div>

            <div className="b-grid">
              {shown.map((post) => (
                <BlogCard key={post.id} post={post} />
              ))}
            </div>

            {shown.length < gridPosts.length && (
              <div style={{ textAlign: "center", marginTop: 48 }}>
                <button
                  className="b-btn b-btn-dark"
                  onClick={() => setLimit((l) => l + PAGE_SIZE)}
                >
                  Load more articles
                </button>
                <div
                  style={{
                    marginTop: 14,
                    fontSize: 14,
                    color: "var(--b-ink-soft)",
                  }}
                >
                  Showing {shown.length} of {gridPosts.length}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
