"use client";

import { useQuery } from "convex/react";
import Link from "next/link";
import { api } from "../../../../../../../../convex/_generated/api";
import { ProductCard } from "@/components/product/ProductCard";
import { SectionHeading } from "@/utils/common/heading/section_heading";
import {
  enrichedProductToCardProps,
  type EnrichedProduct,
} from "@/lib/shop/productMapper";

export function RecentlyAddedSection() {
  const products = useQuery(api.products.listRecentlyAdded, { limit: 8 });

  const isLoading = products === undefined;
  const isEmpty = Array.isArray(products) && products.length === 0;

  if (isEmpty) return null;

  return (
    <section
      aria-label="Recently added products"
      className="w-full py-10 md:py-12"
    >
      <div className="mx-auto max-w-7xl min-w-0 px-4 md:px-6">
        <div className="flex flex-row flex-wrap items-center justify-between gap-4 mb-6 md:mb-8">
          <SectionHeading title="Recently Added" />
          <Link
            href="/shop/recently-added"
            className="inline-flex items-center gap-1 font-sans text-sm font-bold text-[var(--accent)] hover:underline focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:ring-offset-2 rounded"
          >
            View All
            <span aria-hidden>→</span>
          </Link>
        </div>
        <div
          className="flex gap-6 overflow-x-auto scrollbar-hide scroll-smooth pb-2 lg:grid lg:grid-cols-5 lg:overflow-visible lg:pb-0"
          style={{ scrollSnapType: "x proximity" }}
        >
          {isLoading
            ? Array.from({ length: 5 }).map((_, i) => (
                <div
                  key={i}
                  className="min-w-[280px] shrink-1 lg:min-w-0 lg:shrink animate-pulse"
                  style={{ scrollSnapAlign: "start" }}
                >
                  <div className="rounded-xl bg-gray-200 aspect-square w-full" />
                  <div className="mt-3 space-y-2">
                    <div className="h-3 w-1/3 rounded bg-gray-200" />
                    <div className="h-4 w-3/4 rounded bg-gray-200" />
                    <div className="h-4 w-1/4 rounded bg-gray-200" />
                  </div>
                </div>
              ))
            : (products as EnrichedProduct[]).map((product) => {
                const props = enrichedProductToCardProps(product);
                return (
                  <div
                    key={product._id}
                    className="min-w-[280px] shrink-1 lg:min-w-0 lg:shrink"
                    style={{ scrollSnapAlign: "start" }}
                  >
                    <ProductCard {...props} />
                  </div>
                );
              })}
        </div>
      </div>
    </section>
  );
}
