'use client';

import { useGetPublicTrustedClientsQuery } from '@/store/slice/publicApi';
import { motion } from 'framer-motion';
import { useEffect, useRef, useState } from 'react';
import { Skeleton } from './ui/skeleton';
import Link from 'next/link';

const TrustedClients = () => {
	const scrollContainerRef = useRef<HTMLDivElement | null>(null);
	const { data: clientData, isLoading } = useGetPublicTrustedClientsQuery();
	const clients = clientData?.filter((c) => c.isActive) ?? [];

	const [isHovering, setIsHovering] = useState(false);

	// If you have few clients, duplicate enough times to make the loop feel full.
	// We'll duplicate exactly once for a seamless loop (render clients twice).
	const loopItems = clients.length ? [...clients, ...clients] : [];

	useEffect(() => {
		const el = scrollContainerRef.current;
		if (!el || loopItems.length === 0) return;

		let reqId = 0;
		const speed = 0.6; // px per frame — tweak to taste
		// let rafScroll = 0;

		const step = () => {
			if (!isHovering) {
				// move forward
				el.scrollLeft += speed;

				// When we've scrolled past half the scrollWidth (the first set),
				// subtract half so we appear seamless.
				const half = el.scrollWidth / 2;
				if (el.scrollLeft >= half) {
					// subtract half — keeps visual continuity
					el.scrollLeft = el.scrollLeft - half;
				}
			}

			reqId = requestAnimationFrame(step);
		};

		reqId = requestAnimationFrame(step);

		return () => cancelAnimationFrame(reqId);
	}, [isHovering, loopItems.length]);

	return (
		<section className="py-24 lg:py-32 bg-[#110D09]">
			<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
				{/* Header */}
				<motion.div
					initial={{ opacity: 0, y: 20 }}
					whileInView={{ opacity: 1, y: 0 }}
					transition={{ duration: 0.8 }}
					viewport={{ once: true }}
					className="text-center mb-16"
				>
					<h2 className="font-serif text-4xl sm:text-5xl font-bold text-white mb-4">
						Our Trusted Clients
					</h2>
					<div className="w-16 h-0.5 mx-auto mt-6 bg-[#CBB26A]" />
				</motion.div>

				{/* Carousel */}
				<div className="relative">
					<div
						ref={scrollContainerRef}
						onMouseEnter={() => setIsHovering(true)}
						onMouseLeave={() => setIsHovering(false)}
						className="flex gap-6 overflow-x-auto scrollbar-hide py-4"
						style={{ scrollBehavior: 'smooth' }}
						role="list"
						aria-label="Trusted clients carousel"
					>
						{/* Loading skeletons */}
						{isLoading &&
							Array.from({ length: 8 }).map((_, i) => (
								<Skeleton
									key={i}
									className="shrink-0 w-72 h-72 flex items-center justify-center rounded-xl border border-white/10"
									aria-hidden="true"
								/>
							))}

						{/* If we have clients, render duplicated list to form an infinite loop */}
						{!isLoading &&
							loopItems.map((client, idx) => {
								// For accessibility: mark duplicate items (the second batch) as aria-hidden to avoid screen reader duplication
								const isDuplicate = idx >= clients.length;
								return (
									<Link
										key={`${client.id}-${idx}`}
										href={client.link ?? '/'}
										target="_blank"
										rel="noopener noreferrer"
										className="shrink-0 w-60 h-60 flex items-center justify-center rounded-xl border border-white/10 bg-card/20 hover:border-[#CBB26A] hover:bg-card/50 transition-all duration-300"
										role="listitem"
										aria-hidden={isDuplicate ? true : undefined}
									>
										<img
											src={client.logo}
											alt={client.name}
											className="w-full h-full object-contain px-3 rounded-lg transition-all duration-300 filter grayscale hover:grayscale-0 hover:drop-shadow-[0_0_12px_rgba(203,178,106,0.5)]"
										/>
									</Link>
								);
							})}

						{/* If no clients and not loading, show an empty state */}
						{!isLoading && clients.length === 0 && (
							<div className="shrink-0 w-full py-12 text-center text-foreground/60">
								No trusted clients yet.
							</div>
						)}
					</div>
				</div>
			</div>
		</section>
	);
};

export default TrustedClients;
