"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import Image from "next/image";
import { AnimatePresence, motion, useMotionValue, useSpring } from "framer-motion";
import { ArrowRight } from "@/components/ui/icons";
import AnimatedButton from "@/components/ui/AnimatedButton";

/**
 * Portfolio list with a cursor-trace image reveal. On desktop, hovering a
 * project row floats its image at the cursor (spring-eased) and dims the rest
 * of the list. On touch/small screens it falls back to stacked image cards so
 * every project stays visible and crawlable. Brand-strict: dark tokens,
 * Google Sans, orange/gold accents.
 */
const EASE = [0.21, 0.47, 0.32, 0.98];
const rise = {
  hidden: { opacity: 0, y: 28 },
  show: { opacity: 1, y: 0, transition: { duration: 0.6, ease: EASE } },
};

/* Filter buckets — mirror the Portfolio menu (Games / Analytics / Websites / Media). */
const FILTERS = [
  { key: "all", label: "All" },
  { key: "games", label: "Games" },
  { key: "analytics", label: "Analytics" },
  { key: "websites", label: "Websites" },
  { key: "media", label: "Media" },
];

export default function PortfolioList({ projects }) {
  const [hovered, setHovered] = useState(null);
  const [filter, setFilter] = useState("all");

  // Preselect a filter from the URL (?filter=games) — used by the nav dropdown.
  useEffect(() => {
    const p = new URLSearchParams(window.location.search).get("filter");
    if (p && FILTERS.some((f) => f.key === p)) setFilter(p);
  }, []);

  const filtered = filter === "all" ? projects : projects.filter((p) => p.group === filter);

  const selectFilter = (key) => {
    setFilter(key);
    setHovered(null);
  };

  // Cursor position (relative to the list) → spring-smoothed for a trailing feel.
  const mx = useMotionValue(0);
  const my = useMotionValue(0);
  const x = useSpring(mx, { stiffness: 260, damping: 30, mass: 0.6 });
  const y = useSpring(my, { stiffness: 260, damping: 30, mass: 0.6 });

  const onMove = (e) => {
    const r = e.currentTarget.getBoundingClientRect();
    mx.set(e.clientX - r.left);
    my.set(e.clientY - r.top);
  };

  return (
    <section className="relative overflow-hidden bg-background py-16 text-foreground md:py-24">
      <div className="pointer-events-none absolute -left-32 top-0 h-[28rem] w-[40rem] rounded-full bg-primary/[0.07] blur-[160px]" />

      <div className="container relative">
        {/* Header */}
        <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true, amount: 0.5 }} className="max-w-3xl">
          <span className="inline-flex items-center gap-2 rounded-full border border-border bg-surface/60 px-4 py-1.5 text-xs font-semibold uppercase tracking-wider text-muted-foreground backdrop-blur">
            <span className="h-1.5 w-1.5 rounded-full bg-primary" />
            Our work
          </span>
          <h1 className="mt-6 font-heading text-4xl font-bold leading-[1.08] tracking-tight sm:text-5xl md:text-6xl">
            Selected{" "}
            <span className="animate-text-shimmer bg-gradient-to-r from-primary via-accent to-primary bg-clip-text text-transparent">
              work.
            </span>
          </h1>
          <p className="mt-5 max-w-xl text-base leading-relaxed text-muted-foreground sm:text-lg">
            A few of the products we&apos;ve designed, built and scaled — across fintech,
            healthcare, AI, gaming and more.
          </p>
        </motion.div>

        {/* Filter tabs */}
        <motion.div
          variants={rise}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true }}
          className="mt-10 flex flex-wrap gap-2"
        >
          {FILTERS.map((f) => {
            const active = filter === f.key;
            return (
              <button
                key={f.key}
                onClick={() => selectFilter(f.key)}
                className={
                  "rounded-full border px-4 py-2 text-sm font-medium transition-colors duration-300 " +
                  (active
                    ? "border-primary/50 bg-primary/10 text-primary"
                    : "border-border bg-surface/60 text-muted-foreground hover:border-primary/40 hover:text-foreground")
                }
              >
                {f.label}
              </button>
            );
          })}
        </motion.div>

        {/* Empty state (e.g. a filter with no projects yet) */}
        {filtered.length === 0 && (
          <p className="mt-14 border-t border-border pt-14 text-center text-muted-foreground">
            New {FILTERS.find((f) => f.key === filter)?.label.toLowerCase()} work is on the way —{" "}
            <Link href="/contact" className="font-semibold text-primary hover:underline">
              start a project
            </Link>
            .
          </p>
        )}

        {/* Desktop — cursor-trace list */}
        <div
          onMouseMove={onMove}
          onMouseLeave={() => setHovered(null)}
          className={
            "relative mt-10 hidden border-t border-border " +
            (filtered.length ? "lg:block" : "")
          }
        >
          {/* Floating cursor image */}
          <motion.div style={{ x, y }} className="pointer-events-none absolute left-0 top-0 z-20">
            <div className="-translate-x-1/2 -translate-y-1/2">
              <AnimatePresence mode="popLayout">
                {hovered !== null && (
                  <motion.div
                    key={hovered}
                    initial={{ opacity: 0, scale: 0.85 }}
                    animate={{ opacity: 1, scale: 1 }}
                    exit={{ opacity: 0, scale: 0.85 }}
                    transition={{ duration: 0.3, ease: EASE }}
                    className="relative h-60 w-80 overflow-hidden rounded-2xl border border-primary/30 shadow-2xl shadow-black/50"
                  >
                    <Image
                      src={filtered[hovered].image}
                      alt={filtered[hovered].title}
                      fill
                      sizes="20rem"
                      className="object-cover"
                    />
                    <span className="absolute inset-0 bg-gradient-to-t from-background/60 to-transparent" />
                    <span className="absolute bottom-3 left-3 rounded-full border border-primary/40 bg-background/70 px-3 py-1 text-[11px] font-semibold text-primary backdrop-blur">
                      {filtered[hovered].category}
                    </span>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </motion.div>

          {/* Rows */}
          <ul>
            {filtered.map((p, i) => (
              <li key={p.slug}>
                <Link
                  href={`/portfolio/${p.slug}`}
                  onMouseEnter={() => setHovered(i)}
                  className={
                    "group flex items-center justify-between gap-6 border-b border-border py-8 transition-all duration-300 " +
                    (hovered === null || hovered === i ? "opacity-100" : "opacity-40")
                  }
                >
                  <div className="flex items-baseline gap-7">
                    <span className="font-heading text-sm font-semibold text-muted-foreground">
                      {String(i + 1).padStart(2, "0")}
                    </span>
                    <h2 className="font-heading text-4xl font-bold tracking-tight text-foreground transition-all duration-300 group-hover:translate-x-3 group-hover:text-primary xl:text-5xl">
                      {p.title}
                    </h2>
                  </div>

                  <div className="flex shrink-0 items-center gap-8">
                    <span className="hidden text-sm text-muted-foreground xl:block">{p.category}</span>
                    <span className="text-sm tabular-nums text-muted-foreground">{p.year}</span>
                    <span className="flex h-11 w-11 items-center justify-center rounded-full border border-border text-muted-foreground transition-all duration-300 group-hover:-rotate-45 group-hover:border-primary group-hover:bg-primary group-hover:text-primary-foreground">
                      <ArrowRight className="h-5 w-5" />
                    </span>
                  </div>
                </Link>
              </li>
            ))}
          </ul>
        </div>

        {/* Mobile — image cards */}
        <motion.div
          variants={{ show: { transition: { staggerChildren: 0.06 } } }}
          initial="hidden"
          whileInView="show"
          viewport={{ once: true, amount: 0.1 }}
          className="mt-12 grid gap-5 sm:grid-cols-2 lg:hidden"
        >
          {filtered.map((p, i) => (
            <motion.div key={p.slug} variants={rise}>
              <Link href={`/portfolio/${p.slug}`} className="group block overflow-hidden rounded-3xl border border-border bg-surface/70">
                <div className="relative aspect-[16/10] overflow-hidden">
                  <Image
                    src={p.image}
                    alt={p.title}
                    fill
                    sizes="(min-width: 640px) 50vw, 100vw"
                    className="object-cover transition-transform duration-700 group-hover:scale-105"
                  />
                  <span className="absolute inset-0 bg-gradient-to-t from-background/70 to-transparent" />
                  <span className="absolute left-4 top-4 rounded-full border border-primary/40 bg-background/70 px-3 py-1 text-[11px] font-semibold uppercase tracking-wider text-primary backdrop-blur">
                    {p.category}
                  </span>
                </div>
                <div className="flex items-center justify-between gap-3 p-5">
                  <h2 className="font-heading text-xl font-semibold">
                    <span className="mr-2 text-sm text-primary">{String(i + 1).padStart(2, "0")}</span>
                    {p.title}
                  </h2>
                  <span className="text-xs text-muted-foreground">{p.year}</span>
                </div>
              </Link>
            </motion.div>
          ))}
        </motion.div>

        {/* CTA */}
        <motion.div variants={rise} initial="hidden" whileInView="show" viewport={{ once: true }} className="mt-16 flex flex-col items-center gap-4 text-center">
          <p className="font-heading text-xl font-semibold sm:text-2xl">Have a product in mind?</p>
          <AnimatedButton href="/contact">Start a project</AnimatedButton>
        </motion.div>
      </div>
    </section>
  );
}
