"use client";

import { useRef } from "react";
import { ProductCard } from "@/components/store/product-card";
import type { SanityProductCard } from "@/lib/sanity/queries";

type Props = {
  products: Array<SanityProductCard | null | undefined>;
};

export function HomeProductsCarousel({ products }: Props) {
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const safeProducts = products.filter((product): product is SanityProductCard => {
    return Boolean(product && product._id && product.handle);
  });

  const scrollByAmount = (direction: "prev" | "next") => {
    const container = scrollRef.current;
    if (!container) return;

    const amount = Math.max(container.clientWidth * 0.9, 320);
    container.scrollBy({
      left: direction === "next" ? amount : -amount,
      behavior: "smooth",
    });
  };

  if (safeProducts.length === 0) {
    return null;
  }

  return (
    <div className="relative">
      <div
        ref={scrollRef}
        className="carousel-scroll overflow-x-auto pb-2 scroll-smooth"
      >
        <div className="flex snap-x snap-mandatory gap-4 px-1 pb-2 sm:px-0">
          {safeProducts.map((product, index) => (
            <div
              key={product._id}
              className="min-w-0 shrink-0 snap-center first:pl-0 last:pr-0 basis-[86%] sm:basis-[47%] lg:basis-[31.5%]"
            >
              <ProductCard product={product} index={index} />
            </div>
          ))}
        </div>
      </div>

      <button
        type="button"
        aria-label="Produits precedents"
        onClick={() => scrollByAmount("prev")}
        className="absolute left-2 top-1/2 z-10 hidden h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-[#ffe0e0] bg-white/95 text-[var(--accent-3)] shadow-[0_12px_24px_rgba(49,18,18,0.12)] transition hover:bg-white md:inline-flex"
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4">
          <path strokeLinecap="round" strokeLinejoin="round" d="m15 6-6 6 6 6" />
        </svg>
      </button>

      <button
        type="button"
        aria-label="Produits suivants"
        onClick={() => scrollByAmount("next")}
        className="absolute right-2 top-1/2 z-10 hidden h-10 w-10 -translate-y-1/2 items-center justify-center rounded-full border border-[#ffe0e0] bg-white/95 text-[var(--accent-3)] shadow-[0_12px_24px_rgba(49,18,18,0.12)] transition hover:bg-white md:inline-flex"
      >
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-4 w-4">
          <path strokeLinecap="round" strokeLinejoin="round" d="m9 6 6 6-6 6" />
        </svg>
      </button>
    </div>
  );
}
