"use client"

import { useState, useEffect, useRef } from "react"
import ProductCard from "@/components/ProductCard"
import { Loader2 } from "lucide-react"

interface ShopProductListProps {
  initialProducts: any[]
}

export default function ShopProductList({ initialProducts }: ShopProductListProps) {
  const [visibleCount, setVisibleCount] = useState(8)
  const [loading, setLoading] = useState(false)
  const observerRef = useRef<HTMLDivElement | null>(null)

  const visibleProducts = initialProducts.slice(0, visibleCount)
  const hasMore = visibleCount < initialProducts.length

  // Reset pagination if initialProducts changes (e.g. active filter/category changed!)
  useEffect(() => {
    setVisibleCount(8)
  }, [initialProducts])

  // Load next batch function
  const loadNextBatch = () => {
    if (loading || !hasMore) return
    setLoading(true)
    setTimeout(() => {
      setVisibleCount((prev) => Math.min(prev + 8, initialProducts.length))
      setLoading(false)
    }, 600) // Sleek premium delay for tactile load indicator
  }

  // Setup intersection observer for infinite scroll
  useEffect(() => {
    if (!hasMore || loading) return

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          loadNextBatch()
        }
      },
      { threshold: 0.05, rootMargin: "150px" } // Trigger 150px before reaching bottom
    )

    const currentRef = observerRef.current
    if (currentRef) {
      observer.observe(currentRef)
    }

    return () => {
      if (currentRef) {
        observer.unobserve(currentRef)
      }
    }
  }, [hasMore, visibleCount, loading, initialProducts])

  return (
    <div className="space-y-12">
      {/* Products Grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-6">
        {visibleProducts.map((product, idx) => (
          <div
            key={product.id}
            className="transition-all duration-500 ease-out"
            style={{
              animation: "fadeIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) both",
              animationDelay: `${Math.min((idx % 8) * 60, 450)}ms`
            }}
          >
            <ProductCard product={product} idPrefix="shop" />
          </div>
        ))}
      </div>

      {/* Dynamic Keyframes Inline Style for FadeIn */}
      <style dangerouslySetInnerHTML={{ __html: `
        @keyframes fadeIn {
          from {
            opacity: 0;
            transform: translateY(12px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}} />

      {/* Loading & Trigger Area */}
      {hasMore && (
        <div ref={observerRef} className="flex flex-col items-center justify-center py-10 border-t border-zinc-100 mt-12">
          {loading ? (
            <div className="flex items-center gap-2 text-zinc-500 py-3">
              <Loader2 className="w-5 h-5 animate-spin text-zinc-950" />
              <span className="text-[10px] font-black uppercase tracking-widest text-zinc-900">Loading next fits...</span>
            </div>
          ) : (
            <button
              type="button"
              onClick={loadNextBatch}
              className="px-10 py-4 bg-zinc-950 text-white text-[10px] font-black uppercase tracking-widest hover:bg-zinc-800 transition-all shadow-sm rounded-sm cursor-pointer"
            >
              Load More
            </button>
          )}
        </div>
      )}
    </div>
  )
}
