"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { PageShell } from "@/components/layout/PageShell";
import { SafeImage } from "@/components/ui/SafeImage";
import type { Category } from "@/data/types";
import { categories as fallbackCategories } from "@/data/categories";
import { easeOut } from "@/lib/motion";

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    void fetch("/api/categories")
      .then((res) => res.json())
      .then((data: { categories?: Category[] }) => {
        if (!active) return;
        const list = data.categories?.length
          ? data.categories
          : fallbackCategories;
        setCategories(list);
      })
      .catch(() => {
        if (active) setCategories(fallbackCategories);
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, []);

  return (
    <PageShell
      crumbs={[{ label: "Home", href: "/" }, { label: "Categories" }]}
      eyebrow="Browse"
      title="Shop by category"
      description="Browse outerwear, tees, bottoms, shirts, knits, dresses, loungewear, kids, and baby."
    >
      {loading ? (
        <div className="grid grid-cols-4 gap-2 sm:grid-cols-5 lg:grid-cols-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="aspect-[3/4] animate-pulse bg-surface" />
          ))}
        </div>
      ) : categories.length === 0 ? (
        <p className="border border-border bg-card px-5 py-10 text-center text-sm text-muted">
          No categories found. Try refreshing the page.
        </p>
      ) : (
        <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-2.5 lg:grid-cols-4">
          {categories.map((category, index) => (
            <motion.div
              key={category.id || category.slug}
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.4, delay: Math.min(index * 0.04, 0.35), ease: easeOut }}
            >
              <Link
                href={`/categories/${category.slug}`}
                className="group block overflow-hidden bg-surface"
              >
                <div className="relative aspect-[3/4] bg-surface">
                  <SafeImage
                    src={category.image}
                    alt={category.name}
                    fill
                    sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
                    className="media-zoom object-cover"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/25 to-transparent" />
                  <div className="absolute bottom-0 p-3 text-white sm:p-3.5">
                    <h2 className="font-display text-xl leading-none sm:text-2xl">
                      {category.name}
                    </h2>
                    <p className="mt-1 line-clamp-2 text-[11px] text-white/75">
                      {category.description}
                    </p>
                    <p className="mt-1.5 text-[9px] uppercase tracking-[0.16em] text-white/60">
                      {category.productCount} styles
                    </p>
                  </div>
                </div>
              </Link>
            </motion.div>
          ))}
        </div>
      )}
    </PageShell>
  );
}
