import { useMemo, useState } from "react";
import { motion } from "framer-motion";
import { projects, featuredProject } from "../data/projects";
import SectionHeading from "../components/SectionHeading";
import ProjectCard from "../components/ProjectCard";
import FeaturedProject from "../components/FeaturedProject";
import ProjectModal from "../components/ProjectModal";
import Reveal from "../components/Reveal";

export default function Projects() {
  const categories = useMemo(() => {
    const set = new Set(["Todos"]);
    projects.forEach((p) => p.categories.forEach((c) => set.add(c)));
    return Array.from(set);
  }, []);

  const [active, setActive] = useState("Todos");
  const [selected, setSelected] = useState(null);

  const rest = projects.filter((p) => p.id !== featuredProject.id);
  const filtered =
    active === "Todos" ? rest : rest.filter((p) => p.categories.includes(active));

  return (
    <section id="proyectos" className="container-px py-28 md:py-36">
      <div className="mx-auto max-w-6xl flex flex-col gap-14">
        <SectionHeading
          eyebrow="Lo que he construido"
          title="Cada proyecto es una idea convertida en solución"
          subtitle="Sistemas reales, con base de datos, roles de usuario y problemas de negocio de verdad detrás — no plantillas de práctica."
        />

        <FeaturedProject project={featuredProject} onOpen={setSelected} />

        {categories.length > 2 && (
          <Reveal className="flex flex-wrap gap-2">
            {categories.map((cat) => (
              <button
                key={cat}
                onClick={() => setActive(cat)}
                className={`text-sm px-4 py-2 rounded-full border transition-colors ${
                  active === cat
                    ? "border-[color:var(--color-accent)] text-[color:var(--color-accent)] bg-[color:var(--color-accent)]/10"
                    : "border-[color:var(--color-border)] text-[color:var(--color-muted)] hover:text-[color:var(--color-ink)]"
                }`}
              >
                {cat}
              </button>
            ))}
          </Reveal>
        )}

        <motion.div layout className="grid gap-6 md:grid-cols-2">
          {filtered.map((project, i) => (
            <motion.div
              key={project.id}
              layout
              initial={{ opacity: 0, y: 20 }}
              whileInView={{ opacity: 1, y: 0 }}
              viewport={{ once: true, margin: "-60px" }}
              transition={{ duration: 0.5, delay: i * 0.05 }}
            >
              <ProjectCard project={project} onOpen={setSelected} />
            </motion.div>
          ))}
        </motion.div>
      </div>

      <ProjectModal project={selected} onClose={() => setSelected(null)} />
    </section>
  );
}
