"use client";

import { AnimatePresence, motion } from "framer-motion";
import Image from "next/image";
import { useMemo, useState } from "react";
import { ArrowUpRight, AwardIcon } from "@/components/icons";
import { Reveal, SectionLabel } from "@/components/motion";
import { aspectOf } from "@/lib/content";
import type { Project } from "@/lib/data";

export default function Work({
  projects,
  onOpen,
}: {
  projects: Project[];
  onOpen: (slug: string) => void;
}) {
  const [filter, setFilter] = useState("All");

  const categories = useMemo(() => {
    const set = new Set(projects.map((p) => p.category));
    return ["All", ...Array.from(set)];
  }, [projects]);

  const visible = useMemo(
    () => (filter === "All" ? projects : projects.filter((p) => p.category === filter)),
    [projects, filter],
  );

  return (
    <section id="work" className="relative py-24 md:py-36">
      <div className="mx-auto max-w-[1600px] px-5 md:px-10">
        <Reveal className="flex flex-col gap-8 md:flex-row md:items-end md:justify-between">
          <div>
            <SectionLabel>Selected Work</SectionLabel>
            <h2 className="mt-6 max-w-[18ch] text-[clamp(2rem,4.4vw,3.8rem)] font-medium leading-[1.02] tracking-display text-balance">
              Six projects, built around a single idea of flexibility.
            </h2>
          </div>

          <div
            className="flex flex-wrap gap-2"
            role="tablist"
            aria-label="Filter projects by category"
          >
            {categories.map((cat) => {
              const isActive = cat === filter;
              return (
                <button
                  key={cat}
                  type="button"
                  role="tab"
                  aria-selected={isActive}
                  onClick={() => setFilter(cat)}
                  className="relative rounded-full border px-5 py-2.5 text-[11px] uppercase tracking-[0.18em] transition-colors duration-300"
                  style={{
                    borderColor: isActive ? "#0a0a0a" : "#e6e6e6",
                    color: isActive ? "#0a0a0a" : "#9c9c9c",
                  }}
                >
                  {cat}
                  <span className="ml-2 tabular-nums opacity-50">
                    {cat === "All"
                      ? projects.length
                      : projects.filter((p) => p.category === cat).length}
                  </span>
                </button>
              );
            })}
          </div>
        </Reveal>

        <motion.div layout className="mt-14 grid grid-cols-1 items-start gap-5 md:grid-cols-2 xl:grid-cols-3">
          <AnimatePresence mode="popLayout">
            {visible.map((project, i) => (
              <motion.article
                key={project.slug}
                layout
                initial={{ opacity: 0, y: 34 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -18 }}
                transition={{
                  duration: 0.65,
                  delay: Math.min(i * 0.07, 0.4),
                  ease: [0.16, 1, 0.3, 1],
                }}
                className={`group relative flex flex-col ${i % 5 === 0 ? "md:col-span-2 xl:col-span-1" : ""}`}
              >
                <button
                  type="button"
                  onClick={() => onOpen(project.slug)}
                  className="flex w-full flex-col text-left"
                  aria-label={`Open ${project.title} project slideshow`}
                >
                  <div
                    className="relative w-full shrink-0 overflow-hidden bg-white"
                    style={{ aspectRatio: String(aspectOf(project.cover)) }}
                  >
                    <Image
                      src={project.cover}
                      alt={`${project.title} — ${project.category} designed by Florian Gross`}
                      fill
                      sizes="(max-width: 768px) 100vw, (max-width: 1280px) 50vw, 33vw"
                      quality={88}
                      className="object-contain transition-transform duration-[1100ms] ease-[cubic-bezier(0.16,1,0.3,1)] group-hover:scale-[1.03]"
                    />

                    <span className="pointer-events-none absolute left-4 top-4 flex items-center gap-2 rounded-full bg-white/90 px-3 py-1.5 text-[9.5px] uppercase tracking-[0.2em] text-ink-soft opacity-0 shadow-sm backdrop-blur transition-all duration-500 group-hover:opacity-100">
                      <AwardIcon className="h-3 w-3 text-[#b5b5b5]" />
                      {project.awards.length
                        ? `${project.awards.length} award${project.awards.length > 1 ? "s" : ""}`
                        : "View project"}
                    </span>

                    <span className="pointer-events-none absolute bottom-4 right-4 flex h-11 w-11 translate-y-3 items-center justify-center rounded-full bg-white text-ink opacity-0 shadow-sm transition-all duration-500 group-hover:translate-y-0 group-hover:opacity-100">
                      <ArrowUpRight className="h-4.5 w-4.5" />
                    </span>
                  </div>

                  <div className="mt-4 flex items-start justify-between gap-6 border-t border-[#efefef] pt-4">
                    <div className="min-w-0">
                      <h3 className="truncate text-[17px] font-medium tracking-tight transition-opacity duration-300 group-hover:opacity-60">
                        {project.title}
                      </h3>
                      <p className="mt-1 line-clamp-2 max-w-[46ch] text-[13px] leading-relaxed text-mute">
                        {project.summary}
                      </p>
                    </div>
                    <span className="shrink-0 text-[11px] uppercase tracking-[0.2em] text-faint">
                      {project.year}
                    </span>
                  </div>
                </button>

                {project.buyUrl && (
                  <a
                    href={project.buyUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-3 inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-ink-soft transition-colors hover:text-mute"
                  >
                    {project.buyLabel ?? "Buy now"}
                    <span className="text-faint">→</span>
                  </a>
                )}
              </motion.article>
            ))}
          </AnimatePresence>
        </motion.div>

        <Reveal delay={0.1}>
          <p className="mt-12 text-[12px] text-faint">
            Click any project to open a full-screen slideshow with specifications,
            awards and credits.
          </p>
        </Reveal>
      </div>
    </section>
  );
}
