"use client";

import Link from "next/link";
import { useRef } from "react";
import { ArrowUpRight, ChevronLeft, ChevronRight } from "lucide-react";
import type { Product } from "@/data/types";
import { GroceryTile } from "./GroceryTile";

export function ProductRail({
  title,
  kicker = "From the crib",
  href,
  hrefLabel = "View all",
  products,
}: {
  title: string;
  kicker?: string;
  href?: string;
  hrefLabel?: string;
  products: Product[];
}) {
  const scroller = useRef<HTMLDivElement>(null);
  const scroll = (dir: number) => {
    scroller.current?.scrollBy({ left: dir * 320, behavior: "smooth" });
  };

  return (
    <section className="mx-auto w-full max-w-[1280px] px-4 py-10 sm:px-6 lg:px-8">
      <div className="mb-6 flex items-end justify-between gap-4">
        <div>
          <p className="text-[11px] font-bold uppercase tracking-[0.2em] text-[var(--straw)]">
            {kicker}
          </p>
          <h2 className="mt-1 font-serif text-3xl font-semibold tracking-tight text-foreground">
            {title}
          </h2>
        </div>
        <div className="flex items-center gap-2">
          {href ? (
            <Link
              href={href}
              className="mr-1 hidden items-center gap-1 text-sm font-semibold text-[var(--spruce-ink)] sm:inline-flex"
            >
              {hrefLabel}
              <ArrowUpRight className="h-3.5 w-3.5" />
            </Link>
          ) : null}
          <button type="button" aria-label="Previous" onClick={() => scroll(-1)} className="rail-btn">
            <ChevronLeft className="h-4 w-4" />
          </button>
          <button type="button" aria-label="Next" onClick={() => scroll(1)} className="rail-btn">
            <ChevronRight className="h-4 w-4" />
          </button>
        </div>
      </div>
      <div
        ref={scroller}
        className="hide-scrollbar -mx-1 flex snap-x snap-mandatory gap-4 overflow-x-auto px-1 pb-4"
      >
        {products.map((product) => (
          <div key={product.id} className="snap-start">
            <GroceryTile product={product} />
          </div>
        ))}
      </div>
    </section>
  );
}
