"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get tourConfig () {
        return tourConfig;
    },
    get tourRoot () {
        return tourRoot;
    }
});
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _reactdom = require("react-dom");
const _react1 = require("@floating-ui/react");
const _utils = require("../../utils");
const _Popover = require("../_beta/Popover/Popover");
const _utils1 = require("./utils");
const _Tourstyles = require("./Tour.styles");
const _base = require("./variatoins/_view/base");
const _base1 = require("./variatoins/_size/base");
const _Tourtokens = require("./Tour.tokens");
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const tourRoot = (Root)=>/*#__PURE__*/ (0, _react.forwardRef)(({ steps, current, defaultCurrent = 0, open, defaultOpen = false, withOverlay = true, overlayColor, zIndex = 9000, view, size, offset: offsetProp = [
        12,
        12
    ], highlightOffset = 4, highlightBorderRadius, hasTail = false, tailColor, tailWidth = _Popover.ARROW_WIDTH, tailHeight = _Popover.ARROW_HEIGHT, renderStep, renderHighlight, onChange, onClose, ...rest }, outerRef)=>{
        const portalId = (0, _utils.safeUseId)();
        const isCurrentControlled = typeof current === 'number';
        const isOpenControlled = typeof open === 'boolean';
        const [innerCurrent, setInnerCurrent] = (0, _react.useState)(defaultCurrent);
        const [innerOpen, setInnerOpen] = (0, _react.useState)(defaultOpen);
        const [highlightRect, setHighlightRect] = (0, _react.useState)(null);
        const [targetElement, setTargetElement] = (0, _react.useState)(null);
        const portalRef = (0, _react.useRef)(null);
        const dialogRef = (0, _react.useRef)(null);
        const arrowRef = (0, _react.useRef)(null);
        const hasHighlightedRef = (0, _react.useRef)(false);
        const active = isCurrentControlled ? current : innerCurrent;
        const isOpen = isOpenControlled ? open : innerOpen;
        const isFirstHighlight = !hasHighlightedRef.current && highlightRect !== null;
        if (isFirstHighlight) {
            hasHighlightedRef.current = true;
        }
        const currentStep = steps[active];
        const placement = currentStep?.placement || 'bottom';
        const middleware = [
            (0, _react1.offset)((hasTail ? tailHeight : 0) + offsetProp[0] + highlightOffset),
            (0, _react1.flip)(),
            (0, _react1.shift)({
                padding: offsetProp[1]
            }),
            hasTail && (0, _react1.arrow)({
                element: arrowRef,
                padding: _Popover.ARROW_PADDING
            })
        ];
        const { refs, floatingStyles, placement: calculatedPlacement, context } = (0, _react1.useFloating)({
            placement,
            middleware,
            whileElementsMounted: _react1.autoUpdate
        });
        const setFloatingRef = (el)=>{
            dialogRef.current = el;
            refs.setFloating(el);
        };
        const handleSetOpen = (value)=>{
            if (!isOpenControlled) {
                setInnerOpen(value);
            }
            if (!value) {
                onClose?.();
                setInnerCurrent(0);
                setHighlightRect(null);
                setTargetElement(null);
            }
        };
        const handleSetCurrent = (index)=>{
            if (!isCurrentControlled) {
                setInnerCurrent(index);
            }
            onChange?.(index);
        };
        const handleClose = ()=>{
            handleSetOpen(false);
        };
        const updateHighlight = (0, _react.useCallback)(()=>{
            if (!isOpen || !currentStep) {
                return;
            }
            const highlightElement = (0, _utils1.getHTMLElement)(currentStep.target);
            if (!highlightElement) {
                setHighlightRect(null);
                setTargetElement(null);
                return;
            }
            const rect = highlightElement.getBoundingClientRect();
            setHighlightRect(rect);
            setTargetElement(highlightElement);
        }, [
            isOpen,
            currentStep
        ]);
        (0, _react.useEffect)(()=>{
            refs.setReference(targetElement);
        }, [
            refs,
            targetElement
        ]);
        (0, _react.useEffect)(()=>{
            if (isOpen) {
                if (targetElement) {
                    const rect = targetElement.getBoundingClientRect();
                    const isInViewport = rect.top >= 0 && rect.left >= 0 && rect.bottom <= window.innerHeight && rect.right <= window.innerWidth;
                    if (!isInViewport) {
                        targetElement.scrollIntoView({
                            block: 'center',
                            inline: 'center',
                            behavior: 'smooth'
                        });
                    }
                }
                if (dialogRef.current) {
                    dialogRef.current.focus({
                        preventScroll: true
                    });
                }
            }
        }, [
            isOpen,
            targetElement
        ]);
        (0, _react.useEffect)(()=>{
            if (!_utils.canUseDOM) {
                return;
            }
            let portal = document.getElementById(portalId);
            if (!portal) {
                portal = document.createElement('div');
                portal.setAttribute('id', portalId);
                document.body.appendChild(portal);
            }
            portalRef.current = portal;
            return ()=>{
                portal?.remove();
            };
        }, []);
        (0, _react.useEffect)(()=>{
            if (!isOpen) {
                return;
            }
            updateHighlight();
            window.addEventListener('resize', updateHighlight);
            window.addEventListener('scroll', updateHighlight, true);
            return ()=>{
                window.removeEventListener('resize', updateHighlight);
                window.removeEventListener('scroll', updateHighlight, true);
            };
        }, [
            isOpen,
            updateHighlight
        ]);
        (0, _react.useEffect)(()=>{
            if (!isOpen) {
                return;
            }
            const handleKeyDown = (e)=>{
                if (e.key === 'Escape') {
                    handleClose();
                }
            };
            window.addEventListener('keydown', handleKeyDown);
            return ()=>{
                window.removeEventListener('keydown', handleKeyDown);
            };
        }, [
            isOpen,
            handleClose
        ]);
        (0, _react.useEffect)(()=>{
            if (!isOpen) {
                hasHighlightedRef.current = false;
                setHighlightRect(null);
            }
        }, [
            isOpen
        ]);
        if (!currentStep || !_utils.canUseDOM || !portalRef.current) {
            return null;
        }
        const arrowFill = tailColor || `var(${_Tourtokens.tokens.tailColor})`;
        const preparedHighlightBorderRadius = currentStep?.highlightBorderRadius ?? highlightBorderRadius ?? undefined;
        const preparedHighlightOffset = currentStep?.highlightOffset || highlightOffset;
        const highlightProps = highlightRect ? {
            left: highlightRect.left - preparedHighlightOffset,
            top: highlightRect.top - preparedHighlightOffset,
            width: highlightRect.width + preparedHighlightOffset * 2,
            height: highlightRect.height + preparedHighlightOffset * 2,
            borderRadius: preparedHighlightBorderRadius,
            highlightOffset: preparedHighlightOffset
        } : null;
        const highlightNode = highlightProps && (renderHighlight ? renderHighlight(highlightProps) : /*#__PURE__*/ _react.default.createElement(_Tourstyles.Highlight, {
            withOverlay: withOverlay,
            overlayColor: overlayColor,
            borderRadius: preparedHighlightBorderRadius,
            disableTransition: isFirstHighlight,
            style: {
                left: highlightProps.left,
                top: highlightProps.top,
                width: highlightProps.width,
                height: highlightProps.height
            }
        }));
        const tourContent = /*#__PURE__*/ _react.default.createElement(Root, {
            ref: outerRef,
            view: view,
            size: size,
            ...rest
        }, isOpen && Boolean(targetElement) && /*#__PURE__*/ _react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/ _react.default.createElement(_Tourstyles.MaskContainer, {
            className: _Tourtokens.classes.mask,
            zIndex: zIndex
        }, withOverlay ? /*#__PURE__*/ _react.default.createElement(_Tourstyles.Mask, null) : null, highlightNode), /*#__PURE__*/ _react.default.createElement(_Tourstyles.TourPortal, {
            ref: setFloatingRef,
            role: "dialog",
            "aria-modal": "true",
            tabIndex: -1,
            style: {
                ...floatingStyles,
                zIndex: Number(zIndex)
            },
            "data-placement": calculatedPlacement
        }, renderStep(active, steps.length, active === steps.length - 1, steps[active], handleSetCurrent), hasTail && /*#__PURE__*/ _react.default.createElement(_react1.FloatingArrow, {
            ref: arrowRef,
            context: context,
            width: tailWidth,
            height: tailHeight,
            fill: arrowFill,
            d: _Popover.ARROW_POLYGON
        }))));
        return /*#__PURE__*/ (0, _reactdom.createPortal)(tourContent, portalRef.current);
    });
const tourConfig = {
    name: 'Tour',
    tag: 'div',
    layout: tourRoot,
    base: '',
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
