"use strict";
"use client";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var Carousel_exports = {};
__export(Carousel_exports, {
  default: () => Carousel_default
});
module.exports = __toCommonJS(Carousel_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_framer_motion = require("framer-motion");
var import_react2 = require("@use-gesture/react");
var import_controls = require("@makeswift/controls");
var import_colorToString = require("../../utils/colorToString");
var import_hooks = require("../../hooks");
var import_Image = __toESM(require("../Image"));
var import_use_style = require("../../../runtimes/react/use-style");
var import_css = require("@emotion/css");
var import_responsive_style = require("../../utils/responsive-style");
var import_use_breakpoints = require("../../../runtimes/react/hooks/use-breakpoints");
function wrap(min, max, v) {
  const rangeSize = max - min;
  return ((v - min) % rangeSize + rangeSize) % rangeSize + min;
}
const LeftChevron = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { xmlns: "http://www.w3.org/2000/svg", width: "10", height: "14", viewBox: "0 0 10 14", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
  "path",
  {
    d: "M7,13,1,7,7,1",
    fill: "none",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    strokeWidth: "2"
  }
) });
const RightChevron = () => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { xmlns: "http://www.w3.org/2000/svg", width: "10", height: "14", viewBox: "0 0 10 14", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
  "path",
  {
    d: "M3,1,9,7,3,13",
    fill: "none",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    strokeWidth: "2"
  }
) });
const SWIPE_THRESHOLD = 20;
const swipePower = (dx, velocity) => dx * (1 + velocity);
const classSelector = (classname) => `.${classname.split(" ").join(".")}`;
const Carousel = (0, import_react.forwardRef)(function Carousel2({
  images = [],
  width,
  margin,
  pageSize: responsivePageSize,
  step: responsiveStep,
  gap,
  slideAlignment,
  showDots,
  showArrows,
  arrowPosition,
  arrowColor,
  arrowBackground,
  dotColor,
  autoplay = false,
  delay = 5,
  slideBorder,
  slideBorderRadius
}, ref) {
  const breakpoints = (0, import_use_breakpoints.useBreakpoints)();
  const [index, setIndex] = (0, import_react.useState)(0);
  const swipe = (0, import_react.useRef)(0);
  const startIndex = wrap(0, images.length, index);
  const pageSize = (0, import_hooks.useMediaQuery)(responsivePageSize) || 1;
  const step = (0, import_hooks.useMediaQuery)(responsiveStep) || 1;
  const endIndex = startIndex + pageSize;
  const pageCount = Math.ceil((images.length - pageSize) / step + 1);
  const pageIndex = Math.ceil(startIndex / step);
  const isFirstPage = pageIndex === 0;
  const isLastPage = pageIndex === pageCount - 1;
  const paginate = (0, import_react.useCallback)(
    (pageDistance) => {
      if (pageDistance === 0)
        return;
      const direction = pageDistance / Math.abs(pageDistance);
      const remaining = direction > 0 ? images.slice(endIndex) : images.slice(0, startIndex);
      const distance = direction * Math.min(remaining.length, step * Math.abs(pageDistance));
      setIndex(index + distance);
    },
    [images, index, startIndex, endIndex, step]
  );
  const animation = (0, import_framer_motion.useAnimation)({ x: 0, transition: { type: "spring", stiffness: 100 } });
  const bindPage = (0, import_react2.useGesture)(
    {
      onDrag: ({ movement: [mx], delta: [dx], velocity: [vx] }) => {
        animation.start({ x: mx });
        swipe.current = swipePower(dx, vx);
      },
      onDragEnd: () => {
        animation.start({ x: 0 });
        if (swipe.current > SWIPE_THRESHOLD)
          paginate(1);
        else if (swipe.current < -SWIPE_THRESHOLD)
          paginate(-1);
      }
    },
    {
      drag: {
        axis: "x",
        bounds: { left: 0, right: 0 },
        rubberband: true
      }
    }
  );
  (0, import_react.useEffect)(() => {
    if (!autoplay || pageSize !== 0)
      setIndex(0);
  }, [autoplay, pageSize]);
  (0, import_react.useEffect)(() => {
    if (!autoplay)
      return () => {
      };
    const intervalId = setInterval(() => isLastPage ? setIndex(0) : paginate(1), delay * 1e3);
    return () => clearInterval(intervalId);
  }, [autoplay, delay, paginate, isLastPage]);
  const clipMaskClassName = (0, import_use_style.useStyle)({ overflow: "hidden" });
  const pageClassName = (0, import_use_style.useStyle)({ position: "relative", width: "100%" });
  const slideClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({ display: "flex" }),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)([responsivePageSize], ([pageSize2 = 1]) => ({
        flexBasis: `${100 / pageSize2}%`,
        maxWidth: `${100 / pageSize2}%`,
        minWidth: `${100 / pageSize2}%`
      }))
    ),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)([slideAlignment], ([alignItems = "center"]) => ({ alignItems }))
    )
  );
  const reelClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({ display: "flex", position: "relative", flexWrap: "nowrap" }),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)([gap], ([gap2 = { value: 0, unit: "px" }]) => ({
        margin: `0 ${`${-gap2.value / 2}${gap2.unit}`}`,
        [`& > ${classSelector(slideClassName)}`]: {
          padding: `0 ${`${gap2.value / 2}${gap2.unit}`}`
        }
      }))
    )
  );
  const arrowClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({
      padding: 10,
      borderRadius: "50%",
      outline: 0,
      border: 0,
      width: 40,
      height: 40,
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      cursor: "pointer",
      userSelect: "none"
    }),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)(
        [arrowBackground],
        ([background = { swatch: { hue: 0, saturation: 0, lightness: 100 }, alpha: 1 }]) => ({
          background: (0, import_colorToString.colorToString)(background)
        })
      )
    ),
    (0, import_use_style.useStyle)({ svg: { transition: "transform 0.15s", stroke: "currentcolor" } })
  );
  const slopClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({
      position: "absolute",
      top: 0,
      bottom: 0,
      display: "flex",
      "&[hidden]": {
        display: "none"
      },
      alignItems: "center",
      cursor: "pointer",
      zIndex: 2
    }),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)(
        [arrowColor],
        ([color = { swatch: { hue: 0, saturation: 0, lightness: 0 }, alpha: 1 }]) => ({
          color: (0, import_colorToString.colorToString)(color)
        })
      )
    )
  );
  const leftSlopClassName = (0, import_css.cx)(
    slopClassName,
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)([arrowPosition], ([position = "inside"]) => {
        switch (position) {
          case "inside":
            return { transform: "translateX(8px)" };
          case "outside":
            return { transform: "translateX(calc(-100% - 8px))" };
          default:
            return { transform: "translateX(calc(-50%))" };
        }
      })
    ),
    (0, import_use_style.useStyle)({
      left: 0,
      [`&:hover > ${classSelector(arrowClassName)}`]: {
        "& > svg": {
          transform: "translateX(-2px)"
        }
      }
    })
  );
  const rightSlopClassName = (0, import_css.cx)(
    slopClassName,
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)([arrowPosition], ([position = "inside"]) => {
        switch (position) {
          case "inside":
            return { transform: "translateX(-8px)" };
          case "outside":
            return { transform: "translateX(calc(100% + 8px))" };
          default:
            return { transform: "translateX(calc(50%))" };
        }
      })
    ),
    (0, import_use_style.useStyle)({
      right: 0,
      [`&:hover > ${classSelector(arrowClassName)}`]: {
        "& > svg": {
          transform: "translateX(2px)"
        }
      }
    })
  );
  const dotsClassName = (0, import_css.cx)(
    (0, import_use_style.useStyle)({ display: showDots ? "flex" : "none", justifyContent: "center", marginTop: 20 }),
    (0, import_use_style.useStyle)(
      (0, import_responsive_style.useResponsiveStyle)(
        [dotColor],
        ([color = { swatch: { hue: 0, saturation: 0, lightness: 0 }, alpha: 1 }]) => ({
          color: (0, import_colorToString.colorToString)(color)
        })
      )
    )
  );
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
    "div",
    {
      ref,
      className: (0, import_css.cx)(
        (0, import_use_style.useStyle)({ position: "relative", display: "flex", flexDirection: "column" }),
        width,
        margin,
        (0, import_use_style.useStyle)({ "&:focus": { outline: 0 } })
      ),
      tabIndex: -1,
      onKeyDown: (e) => {
        switch (e.key) {
          case "ArrowRight":
            paginate(1);
            break;
          case "ArrowLeft":
            paginate(-1);
            break;
          default:
        }
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: (0, import_use_style.useStyle)({ position: "relative", height: "100%" }), children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: clipMaskClassName, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_framer_motion.motion.div, { ...bindPage(), className: pageClassName, animate: animation, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_framer_motion.motion.div,
            {
              className: reelClassName,
              animate: { x: `${-(100 / pageSize) * startIndex}%` },
              transition: {
                x: {
                  type: "tween",
                  ease: [0.165, 0.84, 0.44, 1],
                  duration: 0.5
                }
              },
              children: images.map(({ props: imageProps, key }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                import_framer_motion.motion.div,
                {
                  className: slideClassName,
                  onMouseDown: (e) => e.preventDefault(),
                  onClick: (e) => {
                    if (swipe.current !== 0)
                      e.preventDefault();
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
                    import_Image.default,
                    {
                      width: [
                        {
                          deviceId: (0, import_controls.getBaseBreakpoint)(breakpoints).id,
                          value: { value: 100, unit: "%" }
                        }
                      ],
                      file: imageProps.file,
                      altText: imageProps.altText,
                      link: imageProps.link,
                      border: slideBorder,
                      borderRadius: slideBorderRadius
                    }
                  )
                },
                key
              ))
            }
          ) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            "div",
            {
              onClick: () => paginate(-1),
              className: leftSlopClassName,
              hidden: !showArrows || isFirstPage,
              children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: arrowClassName, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(LeftChevron, {}) })
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            "div",
            {
              onClick: () => paginate(1),
              className: rightSlopClassName,
              hidden: !showArrows || isLastPage,
              children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: arrowClassName, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(RightChevron, {}) })
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: dotsClassName, children: Array.from({ length: pageCount }).map((_, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dot, { active: i === pageIndex, onClick: () => paginate(i - pageIndex) }, i)) })
      ]
    }
  );
});
var Carousel_default = Carousel;
function Dot({ className, active, ...restOfProps }) {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    "div",
    {
      ...restOfProps,
      className: (0, import_css.cx)(
        (0, import_use_style.useStyle)({
          position: "relative",
          margin: "0 6px",
          borderRadius: "50%",
          cursor: "pointer",
          width: 16,
          height: 16,
          "&::before, &::after": {
            content: '""',
            position: "absolute",
            top: "50%",
            left: "50%",
            display: "block",
            borderRadius: "50%",
            transition: "all 0.15s cubic-bezier(0.175, 0.885, 0.32, 1.275)"
          },
          "&::before": {
            boxShadow: "0 0 0 2px currentColor",
            transform: "translate3d(-50%, -50%, 0)",
            width: active ? 16 : 10,
            height: active ? 16 : 10
          },
          "&::after": {
            background: "currentColor",
            transform: `translate3d(-50%, -50%, 0) scale(${active ? 1 : 0})`,
            width: 10,
            height: 10
          },
          "&:hover::after": {
            transform: `translate3d(-50%, -50%, 0) scale(${active ? 1 : 0})`
          }
        }),
        className
      )
    }
  );
}
//# sourceMappingURL=Carousel.js.map