'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import ProductCard from '@/components/product/ProductCard';
import { products } from '@/lib/products';
import Button from '@/components/ui/Button';
import { ArrowRight, ChevronLeft, ChevronRight } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { localizeProduct } from '@/lib/product-i18n';
import { isRtl } from '@/i18n';
import { cn } from '@/lib/utils';

const AUTO_SCROLL_MS = 4500;

export default function FeaturedProducts() {
  const { t, locale } = useTranslation();
  const rtl = isRtl(locale);
  const trackRef = useRef<HTMLDivElement>(null);
  const [paused, setPaused] = useState(false);

  const allProducts = products.map((p) => localizeProduct(p, t));

  const getScrollStep = useCallback(() => {
    const track = trackRef.current;
    if (!track) return 320;
    const card = track.querySelector<HTMLElement>('[data-slide]');
    if (!card) return 320;
    const gap = 24;
    return card.offsetWidth + gap;
  }, []);

  const scroll = useCallback(
    (direction: 'next' | 'prev') => {
      const track = trackRef.current;
      if (!track) return;

      const step = getScrollStep();
      const forward = direction === 'next';
      const delta = forward ? step : -step;
      const scrollDelta = rtl ? -delta : delta;

      const maxScroll = track.scrollWidth - track.clientWidth;
      const atEnd = track.scrollLeft >= maxScroll - 8;
      const atStart = track.scrollLeft <= 8;

      if (forward && atEnd) {
        track.scrollTo({ left: rtl ? maxScroll : 0, behavior: 'smooth' });
        return;
      }
      if (!forward && atStart) {
        track.scrollTo({ left: rtl ? 0 : maxScroll, behavior: 'smooth' });
        return;
      }

      track.scrollBy({ left: scrollDelta, behavior: 'smooth' });
    },
    [getScrollStep, rtl]
  );

  useEffect(() => {
    if (paused) return;
    const id = window.setInterval(() => scroll('next'), AUTO_SCROLL_MS);
    return () => window.clearInterval(id);
  }, [paused, scroll]);

  return (
    <section className="overflow-hidden bg-white py-16 sm:py-20">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="mb-10 flex flex-col items-start justify-between gap-4 sm:mb-12 sm:flex-row sm:items-end">
          <div>
            <span className="mb-2 inline-block text-sm font-semibold uppercase tracking-wider text-gold-600">
              {t('featured.label')}
            </span>
            <h2 className="section-heading">{t('featured.title')}</h2>
            <p className="mt-2 max-w-lg text-gray-500">{t('featured.subtitle')}</p>
          </div>
          <Button href="/shop" variant="secondary">
            {t('featured.viewAll')}
            <ArrowRight className="h-4 w-4 rtl:rotate-180" />
          </Button>
        </div>

        <div
          className="relative"
          onMouseEnter={() => setPaused(true)}
          onMouseLeave={() => setPaused(false)}
          onFocus={() => setPaused(true)}
          onBlur={() => setPaused(false)}
        >
          <div className="pointer-events-none absolute inset-y-0 start-0 z-10 w-8 bg-gradient-to-r from-white to-transparent sm:w-16" />
          <div className="pointer-events-none absolute inset-y-0 end-0 z-10 w-8 bg-gradient-to-l from-white to-transparent sm:w-16" />

          <div
            ref={trackRef}
            className="scrollbar-hide flex snap-x snap-mandatory gap-6 overflow-x-auto scroll-smooth pb-2"
          >
            {allProducts.map((product) => (
              <div
                key={product.id}
                data-slide
                className="w-[min(85vw,280px)] shrink-0 snap-start sm:w-[300px]"
              >
                <ProductCard product={product} />
              </div>
            ))}
          </div>

          <div className="mt-6 flex items-center justify-center gap-3">
            <button
              type="button"
              onClick={() => scroll('prev')}
              aria-label={t('featured.title')}
              className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-cream-300 bg-white text-brand-800 shadow-premium transition-colors hover:border-brand-300 hover:bg-brand-50"
            >
              <ChevronLeft className={cn('h-5 w-5', rtl && 'rotate-180')} />
            </button>
            <button
              type="button"
              onClick={() => scroll('next')}
              aria-label={t('featured.title')}
              className="inline-flex h-10 w-10 items-center justify-center rounded-full border border-cream-300 bg-white text-brand-800 shadow-premium transition-colors hover:border-brand-300 hover:bg-brand-50"
            >
              <ChevronRight className={cn('h-5 w-5', rtl && 'rotate-180')} />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}