"use client";

import { useMemo, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  portfolioCategories,
  portfolioItems,
  type PortfolioCategory,
} from "@/constants";

type Filter = "All" | PortfolioCategory;

function PortfolioCard({
  item,
  index,
}: {
  item: (typeof portfolioItems)[number];
  index: number;
}) {
  const [errored, setErrored] = useState(false);

  return (
    <motion.article
      className="group flex flex-col overflow-hidden rounded-xl border border-navy-100 bg-white shadow-card"
      initial={{ opacity: 0, y: 20, scale: 0.95 }}
      animate={{ opacity: 1, y: 0, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95, y: -20 }}
      transition={{ duration: 0.4, ease: [0.25, 0.1, 0.25, 1] }}
      layout
      whileHover={{
        y: -8,
        boxShadow: "0 24px 60px -16px rgba(11, 31, 69, 0.30)",
        transition: { duration: 0.3 }
      }}
    >
      {/* Media with enhanced hover effect */}
      <div className="relative aspect-[16/10] overflow-hidden">
        <motion.div
          className="absolute inset-0 z-10 bg-gradient-to-t from-navy/20 to-transparent opacity-0 transition-opacity duration-300 group-hover:opacity-100"
        />
        {!errored ? (
          <motion.img
            src={item.image}
            alt={item.title}
            loading="lazy"
            onError={() => setErrored(true)}
            className="h-full w-full object-cover"
            whileHover={{ scale: 1.1, transition: { duration: 0.25, ease: [0.25, 0.1, 0.25, 1] } }}
          />
        ) : (
          <div
            aria-hidden="true"
            className="flex h-full w-full items-center justify-center bg-gradient-to-br from-navy-800 to-navy-950"
          >
            <span className="select-none text-6xl font-extrabold tracking-tightest text-gold/20">
              {String(index + 1).padStart(2, "0")}
            </span>
          </div>
        )}
        {/* Temporarily hidden category tag */}
        {/* <motion.span
          className="absolute left-4 top-4 rounded-full bg-white/95 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-navy shadow-sm backdrop-blur-sm"
          initial={{ x: -20, opacity: 0 }}
          animate={{ x: 0, opacity: 1 }}
          transition={{ delay: 0.2, duration: 0.4 }}
        >
          {item.category}
        </motion.span> */}
      </div>

      {/* Body */}
      <div className="flex flex-1 flex-col p-6">
        <motion.h3
          className="text-lg font-bold text-navy"
          whileHover={{ x: 4, color: "#c9a24b", transition: { duration: 0.2 } }}
        >
          {item.title}
        </motion.h3>
        <p className="mt-2 flex-1 text-sm leading-relaxed text-navy-500">
          {item.description}
        </p>
      </div>
    </motion.article>
  );
}

export default function Portfolio() {
  const [filter, setFilter] = useState<Filter>("All");

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

  return (
    <section
      id="portfolio"
      // Added 'relative' and removed the solid background color so the dots show through
      className="relative scroll-mt-24 border-y border-navy-100 py-24 sm:py-28"
      style={{
        backgroundImage:
          "radial-gradient(rgba(11, 31, 69, 0.40) 1.5px, transparent 1.5px)",
        backgroundSize: "28px 28px",
      }}
    >
      {/* Soft glow so content stays readable over the dot grid */}
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-0 z-0"
        style={{
          background:
            "radial-gradient(ellipse 70% 60% at center, rgba(238, 242, 248, 0.9) 0%, rgba(238, 242, 248, 0.55) 55%, transparent 100%)",
        }}
      />

      {/* Added 'relative z-10' to ensure content sits on top of the grid and glow */}
      <div className="container-x relative z-10">
        {/* Header with reveal animation */}
        <motion.div
          className="flex flex-col gap-8 lg:flex-row lg:items-end lg:justify-between"
          initial={{ opacity: 0, y: 40 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-100px" }}
          transition={{ duration: 0.8, ease: [0.25, 0.1, 0.25, 1] }}
        >
          <div className="max-w-2xl">
            <motion.p
              className="eyebrow"
              initial={{ opacity: 0, x: -20 }}
              whileInView={{ opacity: 1, x: 0 }}
              viewport={{ once: true }}
              transition={{ delay: 0.1 }}
            >
              Capabilities &amp; portfolio
            </motion.p>
            <h2 className="mt-4 text-3xl font-extrabold leading-tight sm:text-4xl">
              Proven across the missions that matter.
            </h2>
            <motion.div
              className="heading-rule"
              initial={{ scaleX: 0 }}
              whileInView={{ scaleX: 1 }}
              viewport={{ once: true }}
              transition={{ delay: 0.3, duration: 0.6, ease: [0.25, 0.1, 0.25, 1] }}
            />
            <p className="mt-6 text-lg leading-relaxed text-navy-600">
              A selection of the work we ship — from centimeter-accurate mapping
              to beyond-visual-line-of-sight logistics. Filter by domain.
            </p>
          </div>
        </motion.div>

        {/* Filter tabs with magnetic effect */}
        <motion.div
          role="tablist"
          aria-label="Filter portfolio by category"
          className="mt-10 flex flex-wrap gap-2"
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.2 }}
        >
          {portfolioCategories.map((cat, i) => {
            const active = filter === cat;
            return (
              <motion.button
                key={cat}
                role="tab"
                aria-selected={active}
                type="button"
                onClick={() => setFilter(cat)}
                className={[
                  "rounded-full px-5 py-2 text-sm font-semibold transition-colors relative overflow-hidden",
                  active
                    ? "bg-navy text-white"
                    : "bg-white text-navy-600 ring-1 ring-navy-100 hover:text-navy hover:ring-gold-300",
                ].join(" ")}
                whileHover={{ scale: 1.05, y: -2 }}
                whileTap={{ scale: 0.95 }}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0, transition: { delay: i * 0.05 } }}
                transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
              >
                <span className="relative z-10">{cat}</span>
                {active && (
                  <motion.div
                    className="absolute inset-0 bg-navy"
                    layoutId="activeTab"
                    transition={{ type: "spring", stiffness: 300, damping: 30 }}
                  />
                )}
              </motion.button>
            );
          })}
        </motion.div>

        {/* Grid with AnimatePresence for smooth filtering */}
        <motion.div
          className="mt-10 grid gap-6 sm:grid-cols-2 lg:grid-cols-3"
          layout
        >
          <AnimatePresence mode="popLayout">
            {visible.map((item, i) => (
              <PortfolioCard key={item.title} item={item} index={i} />
            ))}
          </AnimatePresence>
        </motion.div>

        {visible.length === 0 && (
          <motion.p
            className="mt-10 text-center text-navy-500"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
          >
            No projects in this category yet.
          </motion.p>
        )}
      </div>
    </section>
  );
}
