import { jsx, jsxs } from "react/jsx-runtime";
import React__default, { forwardRef, useState, useRef, useCallback, useEffect } from "react";
import { S as StChevronLeft } from "../../StChevronLeft-D60BtMQy.js";
import { S as StChevronRight } from "../../StChevronRight-BuahImu8.js";
import { cn } from "../utils/cn.js";
import { Image as Image$1 } from "../image/image.js";
import { ScrollArea, ScrollBar } from "../scroll-area/scroll-area.js";
import { c as createLucideIcon } from "../../createLucideIcon-Bni0WIE-.js";
/**
 * @license lucide-react v0.540.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode = [
  ["rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2", key: "1m3agn" }],
  ["circle", { cx: "9", cy: "9", r: "2", key: "af1f0g" }],
  ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21", key: "1xmnt7" }]
];
const Image = createLucideIcon("image", __iconNode);
const EmptyGallery = () => /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center p-8 text-center", children: [
  /* @__PURE__ */ jsx("div", { className: "mb-4 flex h-20 w-20 items-center justify-center rounded-lg bg-muted", children: /* @__PURE__ */ jsx(Image, { className: "h-10 w-10 text-muted-foreground" }) }),
  /* @__PURE__ */ jsx("p", { className: "text-secondary", "aria-label": "No images available", children: "No images to display" })
] });
const MIN_TOUCH_TARGET_SIZE = 44;
const THUMBNAIL_GAP = 8;
const ImageGallery = forwardRef(
  ({
    images = [],
    selectedIndex: controlledIndex,
    defaultSelectedIndex = 0,
    onImageChange,
    onImageError,
    aspectRatio = "1",
    thumbnailsPerView = 6,
    imageFallback,
    disabled = false,
    className
  }, ref) => {
    const isControlled = controlledIndex !== void 0;
    const [internalIndex, setInternalIndex] = useState(defaultSelectedIndex);
    const thumbnailRefs = useRef([]);
    const scrollAreaRef = useRef(null);
    const [canScrollLeft, setCanScrollLeft] = useState(false);
    const [canScrollRight, setCanScrollRight] = useState(false);
    const clampIndex = useCallback(
      (index) => {
        if (images.length === 0) return 0;
        return Math.max(0, Math.min(index, images.length - 1));
      },
      [images.length]
    );
    const selectedIndex = isControlled ? clampIndex(controlledIndex) : clampIndex(internalIndex);
    const handleImageSelect = useCallback(
      (index) => {
        if (disabled) return;
        const newIndex = clampIndex(index);
        if (!isControlled) {
          setInternalIndex(newIndex);
        }
        onImageChange?.(newIndex);
        requestAnimationFrame(() => {
          thumbnailRefs.current[newIndex]?.scrollIntoView({
            behavior: "smooth",
            block: "nearest",
            inline: "center"
          });
        });
      },
      [disabled, isControlled, clampIndex, onImageChange]
    );
    const handleKeyDown = useCallback(
      (e) => {
        if (disabled || images.length === 0) return;
        switch (e.key) {
          case "ArrowLeft": {
            e.preventDefault();
            const prevIndex = selectedIndex === 0 ? images.length - 1 : selectedIndex - 1;
            handleImageSelect(prevIndex);
            break;
          }
          case "ArrowRight": {
            e.preventDefault();
            const nextIndex = selectedIndex === images.length - 1 ? 0 : selectedIndex + 1;
            handleImageSelect(nextIndex);
            break;
          }
        }
      },
      [disabled, images.length, selectedIndex, handleImageSelect]
    );
    const handleThumbnailKeyDown = useCallback(
      (e, index) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          handleImageSelect(index);
        }
      },
      [handleImageSelect]
    );
    const handleImageError = useCallback(
      (index) => (error) => {
        onImageError?.(index, error);
      },
      [onImageError]
    );
    const updateScrollArrows = useCallback(() => {
      const scrollContainer = scrollAreaRef.current?.querySelector(
        '[data-slot="scroll-area-viewport"]'
      );
      if (!scrollContainer) return;
      const { scrollLeft: scrollLeft2, scrollWidth, clientWidth } = scrollContainer;
      setCanScrollLeft(scrollLeft2 > 0);
      setCanScrollRight(scrollLeft2 < scrollWidth - clientWidth - 1);
    }, []);
    useEffect(() => {
      const scrollContainer = scrollAreaRef.current?.querySelector(
        '[data-slot="scroll-area-viewport"]'
      );
      if (!scrollContainer) return;
      updateScrollArrows();
      const handleScroll = () => {
        updateScrollArrows();
      };
      scrollContainer.addEventListener("scroll", handleScroll);
      return () => {
        scrollContainer.removeEventListener("scroll", handleScroll);
      };
    }, [images.length, updateScrollArrows]);
    const scrollLeft = useCallback(() => {
      const scrollContainer = scrollAreaRef.current?.querySelector(
        '[data-slot="scroll-area-viewport"]'
      );
      if (scrollContainer) {
        const containerWidth = scrollContainer.clientWidth;
        scrollContainer.scrollBy({
          left: -containerWidth,
          behavior: "smooth"
        });
      }
    }, []);
    const scrollRight = useCallback(() => {
      const scrollContainer = scrollAreaRef.current?.querySelector(
        '[data-slot="scroll-area-viewport"]'
      );
      if (scrollContainer) {
        const containerWidth = scrollContainer.clientWidth;
        scrollContainer.scrollBy({
          left: containerWidth,
          behavior: "smooth"
        });
      }
    }, []);
    const thumbnailStyle = React__default.useMemo(() => {
      const totalGaps = (thumbnailsPerView - 1) * THUMBNAIL_GAP;
      const widthFraction = 1 / thumbnailsPerView;
      const width = `calc(${widthFraction} * (100% - ${totalGaps}px))`;
      const minWidth = `${MIN_TOUCH_TARGET_SIZE}px`;
      return {
        width,
        minWidth,
        aspectRatio: "1"
        // Keep thumbnails square
      };
    }, [thumbnailsPerView]);
    if (images.length === 0) {
      return /* @__PURE__ */ jsx("div", { className: cn("w-full", className), children: /* @__PURE__ */ jsx(EmptyGallery, {}) });
    }
    const currentImage = images[selectedIndex];
    const showThumbnails = images.length > 1;
    return /* @__PURE__ */ jsxs(
      "div",
      {
        ref,
        className: cn("w-full space-y-4", className),
        role: "region",
        "aria-label": "Image gallery",
        "aria-description": "Use arrow keys to navigate between images",
        tabIndex: 0,
        onKeyDown: handleKeyDown,
        children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              role: "status",
              "aria-live": "polite",
              "aria-atomic": "true",
              className: "sr-only",
              children: `Showing image ${selectedIndex + 1} of ${images.length}`
            }
          ),
          /* @__PURE__ */ jsx(
            "div",
            {
              className: "overflow-hidden rounded-lg bg-gray-100",
              "data-testid": "main-image-container",
              style: { aspectRatio },
              children: /* @__PURE__ */ jsx(
                Image$1,
                {
                  src: currentImage.src,
                  alt: currentImage.alt || `Image ${selectedIndex + 1}`,
                  containerClassName: "w-full h-full",
                  className: "select-none",
                  draggable: false,
                  showLoading: true,
                  fallback: imageFallback,
                  onError: handleImageError(selectedIndex),
                  role: "img"
                }
              )
            }
          ),
          showThumbnails && /* @__PURE__ */ jsxs("div", { className: "relative", children: [
            canScrollLeft && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: scrollLeft,
                className: "absolute left-2 top-1/2 z-10 -translate-y-1/2 flex h-8 w-8 items-center justify-center rounded-full bg-white/90 shadow-md transition-all cursor-pointer hover:bg-white hover:shadow-lg hover:scale-105 focus:outline-none disabled:opacity-50",
                "aria-label": "Scroll thumbnails left",
                children: /* @__PURE__ */ jsx(StChevronLeft, { className: "h-4 w-4 text-gray-700" })
              }
            ),
            canScrollRight && /* @__PURE__ */ jsx(
              "button",
              {
                onClick: scrollRight,
                className: "absolute right-2 top-1/2 z-10 -translate-y-1/2 flex h-8 w-8 items-center justify-center rounded-full bg-white/90 shadow-md transition-all cursor-pointer hover:bg-white hover:shadow-lg hover:scale-105 focus:outline-none disabled:opacity-50",
                "aria-label": "Scroll thumbnails right",
                children: /* @__PURE__ */ jsx(StChevronRight, { className: "h-4 w-4 text-gray-700" })
              }
            ),
            /* @__PURE__ */ jsxs(ScrollArea, { ref: scrollAreaRef, className: "w-full", children: [
              /* @__PURE__ */ jsx(
                "div",
                {
                  className: "flex gap-2 pb-2",
                  "data-testid": "thumbnail-container",
                  role: "listbox",
                  "aria-label": "Thumbnail navigation",
                  "aria-orientation": "horizontal",
                  children: images.map((image, index) => {
                    const isSelected = index === selectedIndex;
                    const label = image.alt || `Image ${index + 1}`;
                    return /* @__PURE__ */ jsx(
                      "button",
                      {
                        ref: (el) => {
                          thumbnailRefs.current[index] = el;
                        },
                        onClick: () => !isSelected && handleImageSelect(index),
                        onKeyDown: (e) => !isSelected && handleThumbnailKeyDown(e, index),
                        disabled,
                        style: thumbnailStyle,
                        className: cn(
                          "relative flex-shrink-0 overflow-hidden rounded-lg border-2 transition-all",
                          "disabled:cursor-not-allowed disabled:opacity-50",
                          isSelected ? "border-accent [&_img]:opacity-50" : "border-transparent bg-gray-100 cursor-pointer hover:[&_img]:opacity-80 focus:outline-none focus:border-primary"
                        ),
                        "aria-label": `View ${label}`,
                        "aria-current": isSelected ? "true" : "false",
                        "aria-selected": isSelected,
                        role: "option",
                        tabIndex: isSelected ? 0 : -1,
                        children: /* @__PURE__ */ jsx(
                          Image$1,
                          {
                            src: image.src,
                            alt: label,
                            containerClassName: "w-full h-full",
                            className: "select-none object-cover",
                            draggable: false,
                            showLoading: true,
                            fallback: imageFallback,
                            onError: handleImageError(index)
                          }
                        )
                      },
                      index
                    );
                  })
                }
              ),
              /* @__PURE__ */ jsx(ScrollBar, { orientation: "horizontal" })
            ] })
          ] })
        ]
      }
    );
  }
);
ImageGallery.displayName = "ImageGallery";
export {
  ImageGallery
};
