import React__default, { useState, useRef, useEffect } from 'react';
import { AnimatePresence, motion } from 'framer-motion';
import ReactDOM__default from 'react-dom';
import { useFocusTrap, useDebounce, useIsMounted, useRefocusOnActivator, useOnKeyDown, useBreakpoints } from '@jobber/hooks';
import classnames from 'classnames';
import { B as ButtonDismiss } from './ButtonDismiss-es.js';
import { T as Text } from './Text-es.js';
import { B as Button } from './Button-es.js';
import { H as Heading } from './Heading-es.js';
import { A as AtlantisThemeContextProvider } from './AtlantisThemeContext-es.js';

var styles = {"backgroundImage":"i9Tw1T65W-k-","next":"Q8amcRaTGf0-","prev":"W9FVb24yJrk-","buttonHidden":"nsN0TPWsBXI-","buttonVisible":"dkLYp7AD2jE-","lightboxWrapper":"_5p2iAj4JfoE-","toolbar":"rMK4cKdOxFw-","closeButton":"_0m6vb11DgiA-","slideNumber":"kCc68gGuTgg-","image":"yYFVVScosfQ-","imageArea":"UskuwLHR6fg-","captionWrapper":"OGjhge-r-U4-","title":"tZU2g-NYdIs-","blurOverlay":"GKIdLTmvcvQ-","thumbnailBar":"_3TfQLQEE3GQ-","thumbnailImage":"eBMzUOlcfQ4-","thumbnail":"eapm2zruLn8-","selected":"PeLn2u-QB0k-","spinning":"_8tDoqjgfLcw-"};

const swipeConfidenceThreshold = 10000;
const swipePower = (offset, velocity) => {
    return Math.abs(offset) * velocity;
};
const slideVariants = {
    enter: (directionRef) => ({
        x: directionRef.current > 0 ? "150%" : "-150%",
    }),
    center: {
        x: 0,
    },
    exit: (directionRef) => ({
        x: directionRef.current < 0 ? "150%" : "-150%",
    }),
};
const imageTransition = {
    x: { duration: 0.65, ease: [0.42, 0, 0, 1.03] },
};
// A little bit more than the transition's duration
// We're doing this to prevent a bug from framer-motion
// https://github.com/framer/motion/issues/1769
const BUTTON_DEBOUNCE_DELAY = 250;
const MOVEMENT_DEBOUNCE_DELAY = 1000;
function LightBox({ boxSizing = "content-box", open, images, imageIndex = 0, onRequestClose, }) {
    const [currentImageIndex, setCurrentImageIndex] = useState(imageIndex);
    const directionRef = useRef(0);
    const [mouseIsStationary, setMouseIsStationary] = useState(true);
    const lightboxRef = useFocusTrap(open);
    const selectedThumbnailRef = useRef(null);
    const debouncedHandleNext = useDebounce(handleMoveNext, BUTTON_DEBOUNCE_DELAY);
    const debouncedHandlePrevious = useDebounce(handleMovePrevious, BUTTON_DEBOUNCE_DELAY);
    const mounted = useIsMounted();
    const prevOpen = useRef(open);
    useRefocusOnActivator(open);
    const handleMouseMovement = useDebounce(() => {
        setMouseIsStationary(true);
    }, MOVEMENT_DEBOUNCE_DELAY);
    useOnKeyDown(handleRequestClose, "Escape");
    useOnKeyDown(debouncedHandlePrevious, {
        key: "ArrowLeft",
    });
    useOnKeyDown(debouncedHandleNext, {
        key: "ArrowRight",
    });
    useEffect(() => {
        setCurrentImageIndex(imageIndex);
    }, [imageIndex, open]);
    if (prevOpen.current !== open) {
        prevOpen.current = open;
        togglePrintStyles(open);
    }
    useEffect(() => {
        var _a;
        (_a = selectedThumbnailRef === null || selectedThumbnailRef === void 0 ? void 0 : selectedThumbnailRef.current) === null || _a === void 0 ? void 0 : _a.scrollIntoView({
            behavior: "smooth",
            block: "nearest",
            inline: "center",
        });
    }, [currentImageIndex]);
    const template = (React__default.createElement(React__default.Fragment, null, open && (React__default.createElement("div", { className: styles.lightboxWrapper, tabIndex: 0, "aria-label": "Lightbox", key: "Lightbox", ref: lightboxRef, onMouseMove: () => {
            if (mouseIsStationary) {
                setMouseIsStationary(false);
            }
            handleMouseMovement();
        } },
        React__default.createElement("div", { className: styles.backgroundImage, style: {
                backgroundImage: `url("${images[currentImageIndex].url}")`,
            } }),
        React__default.createElement("div", { className: styles.blurOverlay, onClick: handleRequestClose }),
        React__default.createElement(AtlantisThemeContextProvider, { dangerouslyOverrideTheme: "dark" },
            React__default.createElement("div", { className: styles.toolbar },
                React__default.createElement("div", { className: styles.slideNumber },
                    React__default.createElement(Text, null, `${currentImageIndex + 1}/${images.length}`)),
                React__default.createElement("div", { className: styles.closeButton },
                    React__default.createElement(ButtonDismiss, { ariaLabel: "Close", onClick: handleRequestClose })))),
        React__default.createElement("div", { className: styles.imageArea },
            React__default.createElement(AnimatePresence, { initial: false },
                React__default.createElement(motion.img, { key: currentImageIndex, variants: slideVariants, src: images[currentImageIndex].url, custom: directionRef, className: styles.image, initial: "enter", alt: images[currentImageIndex].alt ||
                        images[currentImageIndex].title ||
                        "", animate: "center", exit: "exit", transition: imageTransition, drag: "x", dragConstraints: { left: 0, right: 0 }, dragElastic: 1, onDragEnd: handleOnDragEnd }))),
        images.length > 1 && (React__default.createElement(React__default.Fragment, null,
            React__default.createElement(PreviousButton, { onClick: debouncedHandlePrevious, hideButton: mouseIsStationary }),
            React__default.createElement(NextButton, { onClick: debouncedHandleNext, hideButton: mouseIsStationary }))),
        (images[currentImageIndex].title ||
            images[currentImageIndex].caption) && (React__default.createElement("div", { className: styles.captionWrapper },
            React__default.createElement(AtlantisThemeContextProvider, { dangerouslyOverrideTheme: "dark" },
                images[currentImageIndex].title && (React__default.createElement("div", { className: styles.title },
                    React__default.createElement(Heading, { level: 4 }, images[currentImageIndex].title))),
                images[currentImageIndex].caption && (React__default.createElement(Text, { size: "large" }, images[currentImageIndex].caption))))),
        images.length > 1 && (React__default.createElement("div", { className: styles.thumbnailBar, style: {
                "--lightbox--box-sizing": boxSizing,
            }, "data-testid": "ATL-Thumbnail-Bar" }, images.map((image, index) => (React__default.createElement("div", { key: index, className: classnames(styles.thumbnail, {
                [styles.selected]: index === currentImageIndex,
            }), onClick: () => handleThumbnailClick(index), ref: index === currentImageIndex ? selectedThumbnailRef : null },
            React__default.createElement("img", { key: index, src: image.url, alt: image.alt || image.title || "", className: styles.thumbnailImage }))))))))));
    return mounted.current
        ? ReactDOM__default.createPortal(template, document.body)
        : template;
    function handleMovePrevious() {
        directionRef.current = -1;
        setCurrentImageIndex((currentImageIndex + images.length - 1) % images.length);
    }
    function handleMoveNext() {
        directionRef.current = 1;
        setCurrentImageIndex((currentImageIndex + 1) % images.length);
    }
    function handleRequestClose() {
        onRequestClose({ lastPosition: currentImageIndex });
    }
    function handleOnDragEnd(event, { offset, velocity }) {
        const swipe = swipePower(offset.x, velocity.x);
        if (swipe < -swipeConfidenceThreshold) {
            handleMoveNext();
        }
        else if (swipe > swipeConfidenceThreshold) {
            handleMovePrevious();
        }
    }
    function handleThumbnailClick(index) {
        if (index < currentImageIndex) {
            directionRef.current = -1;
        }
        else {
            directionRef.current = 1;
        }
        setCurrentImageIndex(index);
    }
}
function PreviousButton({ onClick, hideButton }) {
    const { mediumAndUp } = useBreakpoints();
    return (React__default.createElement("div", { className: `${styles.prev} ${hideButton ? styles.buttonHidden : styles.buttonVisible}` },
        React__default.createElement(Button, { size: mediumAndUp ? "large" : "small", variation: "subtle", type: "secondary", icon: "arrowLeft", ariaLabel: "Previous image", onClick: onClick })));
}
function NextButton({ onClick, hideButton }) {
    const { mediumAndUp } = useBreakpoints();
    return (React__default.createElement("div", { className: `${styles.next} ${hideButton ? styles.buttonHidden : styles.buttonVisible}` },
        React__default.createElement(Button, { size: mediumAndUp ? "large" : "small", variation: "subtle", type: "secondary", icon: "arrowRight", ariaLabel: "Next image", onClick: onClick })));
}
function togglePrintStyles(open) {
    try {
        if (open) {
            document.documentElement.classList.add("atlantisLightBoxActive");
        }
        else {
            document.documentElement.classList.remove("atlantisLightBoxActive");
        }
    }
    catch (error) {
        console.error(error);
    }
}

export { LightBox as L };
