'use client';

import { cn } from "../../utils/cn.mjs";
import { Button, ButtonColor, ButtonSize, ButtonVariant } from "../Button/Button.mjs";
import { KeyboardShortcut } from "../KeyboardShortcut/KeyboardShortcut.mjs";
import { Popover } from "../Popover/dynamic.mjs";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { Children, createContext, isValidElement, useContext, useEffect, useRef, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
import { useIntlayer } from "react-intlayer";

//#region src/components/Carousel/index.tsx
const SWIPE_THRESHOLD_DIVISOR = 5;
const TRANSITION_DELAY_MS = 50;
const CarouselContext = createContext(null);
const useCarousel = () => {
	const context = useContext(CarouselContext);
	if (!context) throw new Error("useCarousel must be used within a Carousel");
	return context;
};
const getCardStyle = (index, displayedIndex) => {
	switch (Math.abs(index - displayedIndex)) {
		case 0: return "opacity-100 z-40";
		case 1: return "opacity-75 z-30 cursor-pointer";
		case 2: return "opacity-50 z-20 pointer-events-none";
		default: return "opacity-0 z-10 pointer-events-none";
	}
};
const getCardScale = (index, displayedIndex) => {
	switch (Math.abs(index - displayedIndex)) {
		case 0: return 1;
		case 1: return .9;
		case 2: return .8;
		default: return .7;
	}
};
const getCardPositionX = (index, displayedIndex) => {
	return `${(index - displayedIndex) * 30}vw`;
};
const CarouselItem = ({ children, className, ...props }) => {
	return /* @__PURE__ */ jsx("div", {
		className: cn("h-full w-full", className),
		...props,
		children
	});
};
const CarouselIndicators = ({ className, disableKeyboardShortcuts = false, ...props }) => {
	const { selectedIndex, setSelectedIndex, totalItems, handlePrev, handleNext } = useCarousel();
	const { goToSlide, previousSlide, nextSlide } = useIntlayer("carousel");
	if (totalItems <= 1) return null;
	return /* @__PURE__ */ jsxs("div", {
		className: cn("absolute bottom-4 left-1/2 z-50 flex -translate-x-1/2 flex-row items-center gap-2", className),
		...props,
		children: [
			/* @__PURE__ */ jsxs(Popover, {
				identifier: "carousel-prev",
				children: [/* @__PURE__ */ jsx(Button, {
					variant: ButtonVariant.HOVERABLE,
					color: ButtonColor.NEUTRAL,
					label: previousSlide.value,
					roundedSize: "full",
					onClick: (e) => {
						e.stopPropagation();
						handlePrev();
					},
					Icon: ChevronLeft,
					size: ButtonSize.ICON_MD,
					disabled: selectedIndex === 0
				}), /* @__PURE__ */ jsx(Popover.Detail, {
					identifier: "carousel-prev",
					children: /* @__PURE__ */ jsxs("div", {
						className: "flex items-center gap-2 p-2",
						children: [/* @__PURE__ */ jsx("span", {
							className: "whitespace-nowrap text-neutral text-xs",
							children: previousSlide.value
						}), /* @__PURE__ */ jsx(KeyboardShortcut, {
							shortcut: "ArrowLeft",
							disabled: disableKeyboardShortcuts,
							size: "sm",
							onTriggered: handlePrev
						})]
					})
				})]
			}),
			Array.from({ length: totalItems }).map((_, index) => {
				const isActive = index === selectedIndex;
				return /* @__PURE__ */ jsx("button", {
					type: "button",
					onClick: (e) => {
						e.stopPropagation();
						setSelectedIndex(index);
					},
					"aria-label": goToSlide({ index: index + 1 }).value,
					className: cn("h-2.5 w-2.5 rounded-full transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-neutral-400 focus:ring-offset-2", isActive ? "scale-110 bg-text" : "bg-text/20 hover:bg-text/40")
				}, index);
			}),
			/* @__PURE__ */ jsxs(Popover, {
				identifier: "carousel-next",
				children: [/* @__PURE__ */ jsx(Button, {
					variant: ButtonVariant.HOVERABLE,
					color: ButtonColor.NEUTRAL,
					roundedSize: "full",
					label: nextSlide.value,
					onClick: (e) => {
						e.stopPropagation();
						handleNext();
					},
					Icon: ChevronRight,
					size: ButtonSize.ICON_MD,
					disabled: selectedIndex === totalItems - 1
				}), /* @__PURE__ */ jsx(Popover.Detail, {
					identifier: "carousel-next",
					children: /* @__PURE__ */ jsxs("div", {
						className: "flex items-center gap-2 p-2",
						children: [/* @__PURE__ */ jsx("span", {
							className: "whitespace-nowrap text-neutral text-xs",
							children: nextSlide.value
						}), /* @__PURE__ */ jsx(KeyboardShortcut, {
							shortcut: "ArrowRight",
							size: "sm",
							onTriggered: handleNext,
							disabled: disableKeyboardShortcuts
						})]
					})
				})]
			})
		]
	});
};
const partitionCarouselChildren = (children) => {
	const slides = [];
	const others = [];
	children.forEach((child) => {
		if (isValidElement(child) && child.type === CarouselItem) slides.push(child);
		else others.push(child);
	});
	return [slides, others];
};
const CarouselRoot = ({ children, className, initialIndex = 0, onIndexChange, ...props }) => {
	const [slides, others] = partitionCarouselChildren(Children.toArray(children));
	const totalItems = slides.length;
	const [selectedIndex, setSelectedIndex] = useState(initialIndex);
	const [displayedIndex, setDisplayedIndex] = useState(initialIndex);
	const [containerHeight, setContainerHeight] = useState(0);
	const [startX, setStartX] = useState(0);
	const [isDragging, setIsDragging] = useState(false);
	const containerRef = useRef(null);
	const itemsRef = useRef([]);
	const handleSwitchItem = (diff) => {
		if (typeof window === "undefined") return;
		const swipeStep = window.innerWidth / SWIPE_THRESHOLD_DIVISOR;
		const numSwipe = Math.round(diff / swipeStep);
		if (Math.abs(numSwipe) >= 1) {
			const newIndex = displayedIndex - numSwipe;
			const clampedIndex = Math.max(0, Math.min(newIndex, totalItems - 1));
			if (clampedIndex !== selectedIndex) {
				setSelectedIndex(clampedIndex);
				setStartX((prev) => prev + diff);
			}
		}
	};
	const handleNext = () => {
		setSelectedIndex((prev) => Math.min(prev + 1, totalItems - 1));
	};
	const handlePrev = () => {
		setSelectedIndex((prev) => Math.max(prev - 1, 0));
	};
	const handleMouseDown = (e) => {
		setIsDragging(true);
		setStartX(e.clientX);
	};
	const handleMouseMove = (e) => {
		if (isDragging) handleSwitchItem(e.clientX - startX);
	};
	const handleDragEnd = () => setIsDragging(false);
	const handleTouchStart = (e) => {
		setIsDragging(true);
		setStartX(e.touches[0].clientX);
	};
	const handleTouchMove = (e) => {
		if (isDragging) handleSwitchItem(e.touches[0].clientX - startX);
	};
	useEffect(() => {
		if (selectedIndex) onIndexChange?.(selectedIndex);
	}, [selectedIndex, onIndexChange]);
	useEffect(() => {
		let interval;
		if (selectedIndex !== displayedIndex) interval = setInterval(() => {
			setDisplayedIndex((prev) => {
				if (prev === selectedIndex) {
					clearInterval(interval);
					return prev;
				}
				return prev < selectedIndex ? prev + 1 : prev - 1;
			});
		}, TRANSITION_DELAY_MS);
		return () => clearInterval(interval);
	}, [selectedIndex, displayedIndex]);
	useEffect(() => {
		const calculateMaxHeight = () => {
			const heights = itemsRef.current.map((item) => item?.offsetHeight || 0);
			const maxHeight = Math.max(0, ...heights);
			if (maxHeight > 0) setContainerHeight(maxHeight + 40);
		};
		calculateMaxHeight();
		const observer = new ResizeObserver(() => {
			calculateMaxHeight();
		});
		itemsRef.current.forEach((item) => {
			if (item) observer.observe(item);
		});
		return () => observer.disconnect();
	}, [totalItems]);
	return /* @__PURE__ */ jsx(CarouselContext.Provider, {
		value: {
			selectedIndex,
			setSelectedIndex,
			totalItems,
			handlePrev,
			handleNext
		},
		children: /* @__PURE__ */ jsxs("div", {
			ref: containerRef,
			className: cn("relative w-full cursor-grab select-none outline-none transition-[height] duration-300 ease-in-out focus:outline-none focus:outline-none focus:ring-0 active:cursor-grabbing", className),
			style: {
				height: containerHeight > 0 ? containerHeight : "auto",
				minHeight: "400px"
			},
			onMouseDown: handleMouseDown,
			onMouseMove: handleMouseMove,
			onMouseUp: handleDragEnd,
			onMouseLeave: handleDragEnd,
			onTouchStart: handleTouchStart,
			onTouchMove: handleTouchMove,
			onTouchEnd: handleDragEnd,
			role: "region",
			"aria-label": "Carousel",
			...props,
			children: [slides.map((child, index) => {
				return /* @__PURE__ */ jsx("div", {
					role: "button",
					tabIndex: 0,
					ref: (el) => {
						itemsRef.current[index] = el;
					},
					className: cn("absolute left-1/2 -translate-x-1/2 transition-all duration-300 ease-in-out", "outline-none ring-0 focus:outline-none focus:ring-0 focus:ring-offset-0 focus-visible:outline-none focus-visible:ring-0 focus-visible:ring-offset-0", getCardStyle(index, displayedIndex)),
					onClick: (e) => {
						e.stopPropagation();
						setSelectedIndex(index);
					},
					onKeyDown: (e) => {
						if (e.key === "Enter" || e.key === " ") setSelectedIndex(index);
					},
					style: { transform: `
                  translateX(${getCardPositionX(index, displayedIndex)}) 
                  scale(${getCardScale(index, displayedIndex)})
                ` },
					children: child
				}, index);
			}), others]
		})
	});
};
const Carousel = Object.assign(CarouselRoot, {
	Item: CarouselItem,
	Indicators: CarouselIndicators
});

//#endregion
export { Carousel };
//# sourceMappingURL=index.mjs.map