"use client";

import { useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import type { PostMeta } from "@/app/lib/blog-types";
import { BlogCard } from "../BlogCard/BlogCard";
import { FadeUp } from "../Motion/Motion";
import styles from "./BlogList.module.css";

const ALL = "All";

export function BlogList({
  posts,
  categories,
}: {
  posts: PostMeta[];
  categories: string[];
}) {
  const [active, setActive] = useState(ALL);

  const filtered =
    active === ALL ? posts : posts.filter((p) => p.category === active);

  return (
    <>
      <FadeUp delay={0.15}>
        <div className={styles.filters}>
          {[ALL, ...categories].map((cat) => (
            <button
              key={cat}
              className={`${styles.filterBtn} ${active === cat ? styles.filterBtnActive : ""}`}
              onClick={() => setActive(cat)}
            >
              {cat}
            </button>
          ))}
        </div>
      </FadeUp>

      {filtered.length === 0 ? (
        <p className={styles.empty}>No posts in this category yet.</p>
      ) : (
        <div className={styles.grid}>
          <AnimatePresence mode="popLayout">
            {filtered.map((post) => (
              <motion.div
                key={post.slug}
                layout
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95 }}
                transition={{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }}
              >
                <BlogCard post={post} />
              </motion.div>
            ))}
          </AnimatePresence>
        </div>
      )}
    </>
  );
}
