'use strict';

var React = require('react');
var framerMotion = require('framer-motion');
var ReactDOM = require('react-dom');
var jobberHooks = require('@jobber/hooks');
var classnames = require('classnames');
var ButtonDismiss = require('./ButtonDismiss-cjs.js');
var Text = require('./Text-cjs.js');
var Button = require('./Button-cjs.js');
var Heading = require('./Heading-cjs.js');
var AtlantisThemeContext = require('./AtlantisThemeContext-cjs.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] = React.useState(imageIndex);
    const directionRef = React.useRef(0);
    const [mouseIsStationary, setMouseIsStationary] = React.useState(true);
    const lightboxRef = jobberHooks.useFocusTrap(open);
    const selectedThumbnailRef = React.useRef(null);
    const debouncedHandleNext = jobberHooks.useDebounce(handleMoveNext, BUTTON_DEBOUNCE_DELAY);
    const debouncedHandlePrevious = jobberHooks.useDebounce(handleMovePrevious, BUTTON_DEBOUNCE_DELAY);
    const mounted = jobberHooks.useIsMounted();
    const prevOpen = React.useRef(open);
    jobberHooks.useRefocusOnActivator(open);
    const handleMouseMovement = jobberHooks.useDebounce(() => {
        setMouseIsStationary(true);
    }, MOVEMENT_DEBOUNCE_DELAY);
    jobberHooks.useOnKeyDown(handleRequestClose, "Escape");
    jobberHooks.useOnKeyDown(debouncedHandlePrevious, {
        key: "ArrowLeft",
    });
    jobberHooks.useOnKeyDown(debouncedHandleNext, {
        key: "ArrowRight",
    });
    React.useEffect(() => {
        setCurrentImageIndex(imageIndex);
    }, [imageIndex, open]);
    if (prevOpen.current !== open) {
        prevOpen.current = open;
        togglePrintStyles(open);
    }
    React.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.createElement(React.Fragment, null, open && (React.createElement("div", { className: styles.lightboxWrapper, tabIndex: 0, "aria-label": "Lightbox", key: "Lightbox", ref: lightboxRef, onMouseMove: () => {
            if (mouseIsStationary) {
                setMouseIsStationary(false);
            }
            handleMouseMovement();
        } },
        React.createElement("div", { className: styles.backgroundImage, style: {
                backgroundImage: `url("${images[currentImageIndex].url}")`,
            } }),
        React.createElement("div", { className: styles.blurOverlay, onClick: handleRequestClose }),
        React.createElement(AtlantisThemeContext.AtlantisThemeContextProvider, { dangerouslyOverrideTheme: "dark" },
            React.createElement("div", { className: styles.toolbar },
                React.createElement("div", { className: styles.slideNumber },
                    React.createElement(Text.Text, null, `${currentImageIndex + 1}/${images.length}`)),
                React.createElement("div", { className: styles.closeButton },
                    React.createElement(ButtonDismiss.ButtonDismiss, { ariaLabel: "Close", onClick: handleRequestClose })))),
        React.createElement("div", { className: styles.imageArea },
            React.createElement(framerMotion.AnimatePresence, { initial: false },
                React.createElement(framerMotion.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.createElement(React.Fragment, null,
            React.createElement(PreviousButton, { onClick: debouncedHandlePrevious, hideButton: mouseIsStationary }),
            React.createElement(NextButton, { onClick: debouncedHandleNext, hideButton: mouseIsStationary }))),
        (images[currentImageIndex].title ||
            images[currentImageIndex].caption) && (React.createElement("div", { className: styles.captionWrapper },
            React.createElement(AtlantisThemeContext.AtlantisThemeContextProvider, { dangerouslyOverrideTheme: "dark" },
                images[currentImageIndex].title && (React.createElement("div", { className: styles.title },
                    React.createElement(Heading.Heading, { level: 4 }, images[currentImageIndex].title))),
                images[currentImageIndex].caption && (React.createElement(Text.Text, { size: "large" }, images[currentImageIndex].caption))))),
        images.length > 1 && (React.createElement("div", { className: styles.thumbnailBar, style: {
                "--lightbox--box-sizing": boxSizing,
            }, "data-testid": "ATL-Thumbnail-Bar" }, images.map((image, index) => (React.createElement("div", { key: index, className: classnames(styles.thumbnail, {
                [styles.selected]: index === currentImageIndex,
            }), onClick: () => handleThumbnailClick(index), ref: index === currentImageIndex ? selectedThumbnailRef : null },
            React.createElement("img", { key: index, src: image.url, alt: image.alt || image.title || "", className: styles.thumbnailImage }))))))))));
    return mounted.current
        ? ReactDOM.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 } = jobberHooks.useBreakpoints();
    return (React.createElement("div", { className: `${styles.prev} ${hideButton ? styles.buttonHidden : styles.buttonVisible}` },
        React.createElement(Button.Button, { size: mediumAndUp ? "large" : "small", variation: "subtle", type: "secondary", icon: "arrowLeft", ariaLabel: "Previous image", onClick: onClick })));
}
function NextButton({ onClick, hideButton }) {
    const { mediumAndUp } = jobberHooks.useBreakpoints();
    return (React.createElement("div", { className: `${styles.next} ${hideButton ? styles.buttonHidden : styles.buttonVisible}` },
        React.createElement(Button.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);
    }
}

exports.LightBox = LightBox;
