'use client';

import { useRef } from 'react';
import Link from 'next/link';
import { Icon } from './icons';
import { ProductCard, type ProductCardItem } from './product-card';
import { SectionHead } from './category-grid';

export function FeaturedProducts({ products }: { products: ProductCardItem[] }) {
    const ref = useRef<HTMLDivElement>(null);
    if (!products?.length) return null;

    const scrollBy = (dir: 1 | -1) => {
        const el = ref.current;
        if (!el) return;
        const card = el.querySelector('article');
        const step = card ? (card.clientWidth + 20) * 1.5 : el.clientWidth * 0.8;
        el.scrollBy({ left: step * dir, behavior: 'smooth' });
    };

    return (
        <section className="section-pad bg-ink-950 relative">
            <div className="container-jt">
                <div className="flex items-end justify-between gap-4 mb-10 flex-wrap">
                    <SectionHead align="left" eyebrow="In stock now" title="Featured Products" sub="Hand-picked machines &mdash; ready to dispatch from our Industrial Area yard." />
                    <div className="flex items-center gap-2 shrink-0">
                        <button
                            onClick={() => scrollBy(-1)}
                            aria-label="Previous"
                            className="w-10 h-10 rounded-md border border-white/10 text-steel-300 hover:bg-orange-600 hover:text-white hover:border-orange-600 transition-all"
                        >
                            <Icon.ArrowLeft className="w-4 h-4 mx-auto" />
                        </button>
                        <button
                            onClick={() => scrollBy(1)}
                            aria-label="Next"
                            className="w-10 h-10 rounded-md border border-white/10 text-steel-300 hover:bg-orange-600 hover:text-white hover:border-orange-600 transition-all"
                        >
                            <Icon.ArrowRight className="w-4 h-4 mx-auto" />
                        </button>
                        <Link href="/products" className="ml-3 hidden sm:inline-flex font-mono text-xs uppercase tracking-widest text-orange-500 hover:text-orange-400 items-center gap-1">
                            View all <Icon.ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>
                </div>

                <div
                    ref={ref}
                    className="flex gap-4 sm:gap-5 lg:gap-6 overflow-x-auto no-scrollbar snap-x snap-mandatory pb-4 -mx-4 sm:-mx-5 px-4 sm:px-5"
                >
                    {products.map((p, i) => (
                        <div key={p.slug} className="snap-start shrink-0 w-[80vw] sm:w-[46vw] md:w-[32vw] lg:w-[24vw] xl:w-[22vw] 2xl:w-[18vw]">
                            <ProductCard p={p} eager={i < 4} />
                        </div>
                    ))}
                </div>
            </div>
        </section>
    );
}
