"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;
    }
});
var _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
var _reactdom = require("react-dom");
var _reactdom1 = require("@floating-ui/react-dom");
var _utils = require("../../utils");
var _utils1 = require("./utils");
var _Tourstyles = require("./Tour.styles");
var _base = require("./variatoins/_view/base");
var _base1 = require("./variatoins/_size/base");
var _Tourtokens = require("./Tour.tokens");
function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
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;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
var tourRoot = function tourRoot(Root) {
    return /*#__PURE__*/ (0, _react.forwardRef)(function(_0, _1) {
        var _ref = [
            _0,
            _1
        ], _ref1 = _to_array(_ref), _ref2 = _ref1[0], _rest = _ref1.slice(1), steps = _ref2.steps, current = _ref2.current, _ref_defaultCurrent = _ref2.defaultCurrent, defaultCurrent = _ref_defaultCurrent === void 0 ? 0 : _ref_defaultCurrent, open = _ref2.open, _ref_defaultOpen = _ref2.defaultOpen, defaultOpen = _ref_defaultOpen === void 0 ? false : _ref_defaultOpen, onClose = _ref2.onClose, _ref_withOverlay = _ref2.withOverlay, withOverlay = _ref_withOverlay === void 0 ? true : _ref_withOverlay, overlayColor = _ref2.overlayColor, _ref_zIndex = _ref2.zIndex, zIndex = _ref_zIndex === void 0 ? 9000 : _ref_zIndex, view = _ref2.view, size = _ref2.size, tmp = _ref2.offset, offsetProp = tmp === void 0 ? [
            12,
            12
        ] : tmp, _ref_highlightOffset = _ref2.highlightOffset, highlightOffset = _ref_highlightOffset === void 0 ? 4 : _ref_highlightOffset, renderStep = _ref2.renderStep, rest = _object_without_properties(_ref2, [
            "steps",
            "current",
            "defaultCurrent",
            "open",
            "defaultOpen",
            "onClose",
            "withOverlay",
            "overlayColor",
            "zIndex",
            "view",
            "size",
            "offset",
            "highlightOffset",
            "renderStep"
        ]), _rest1 = _sliced_to_array(_rest, 1), outerRef = _rest1[0];
        var _ref3, _ref4, _ref5, _ref6;
        var TOUR_PORTAL_ID = "plasma-tour-portal-".concat(Date.now());
        var isCurrentControlled = typeof current === 'number';
        var isOpenControlled = typeof open === 'boolean';
        var _useState = _sliced_to_array((0, _react.useState)(defaultCurrent), 2), innerCurrent = _useState[0], setInnerCurrent = _useState[1];
        var _useState1 = _sliced_to_array((0, _react.useState)(defaultOpen), 2), innerOpen = _useState1[0], setInnerOpen = _useState1[1];
        var _useState2 = _sliced_to_array((0, _react.useState)(null), 2), highlightRect = _useState2[0], setHighlightRect = _useState2[1];
        var _useState3 = _sliced_to_array((0, _react.useState)(null), 2), highlightBorderRadius = _useState3[0], setHighlightBorderRadius = _useState3[1];
        var _useState4 = _sliced_to_array((0, _react.useState)(null), 2), targetElement = _useState4[0], setTargetElement = _useState4[1];
        var portalRef = (0, _react.useRef)(null);
        var active = isCurrentControlled ? current : innerCurrent;
        var isOpen = isOpenControlled ? open : innerOpen;
        var currentStep = steps[active];
        var rawPlacement = currentStep === null || currentStep === void 0 ? void 0 : currentStep.placement;
        var placement = (Array.isArray(rawPlacement) ? rawPlacement[0] : rawPlacement) || 'bottom';
        var middleware = [
            (0, _reactdom1.offset)(offsetProp[0]),
            (0, _reactdom1.flip)({
                fallbackPlacements: Array.isArray(currentStep === null || currentStep === void 0 ? void 0 : currentStep.placement) ? currentStep.placement : undefined
            }),
            (0, _reactdom1.shift)({
                padding: offsetProp[1]
            })
        ];
        var _useFloating = (0, _reactdom1.useFloating)({
            placement: placement,
            middleware: middleware,
            whileElementsMounted: _reactdom1.autoUpdate
        }), refs = _useFloating.refs, floatingStyles = _useFloating.floatingStyles, calculatedPlacement = _useFloating.placement;
        var handleSetOpen = function handleSetOpen(value) {
            if (!isOpenControlled) {
                setInnerOpen(value);
            }
            if (!value) {
                onClose === null || onClose === void 0 ? void 0 : onClose();
                setInnerCurrent(0);
                setHighlightRect(null);
                setTargetElement(null);
            }
        };
        var handleClose = function handleClose() {
            handleSetOpen(false);
        };
        var updateHighlight = function updateHighlight() {
            if (!isOpen || !currentStep) {
                return;
            }
            var rootItem = (0, _utils1.findRootElement)(currentStep.target);
            var highlightElement = (0, _utils1.getHTMLElement)(rootItem);
            if (highlightElement) {
                var _ref;
                var rect = highlightElement.getBoundingClientRect();
                setHighlightRect(rect);
                setTargetElement(highlightElement);
                var borderRadius = currentStep.borderRadius === 'auto' || currentStep.borderRadius === undefined || currentStep.borderRadius === null ? (0, _utils1.getIncreasedRadius)(rootItem, highlightOffset) : (_ref = currentStep === null || currentStep === void 0 ? void 0 : currentStep.borderRadius) !== null && _ref !== void 0 ? _ref : '0px';
                setHighlightBorderRadius(borderRadius);
            } else {
                setHighlightRect(null);
                setTargetElement(null);
            }
        };
        (0, _react.useEffect)(function() {
            refs.setReference(targetElement);
        }, [
            refs,
            targetElement
        ]);
        (0, _react.useEffect)(function() {
            if (!_utils.canUseDOM) {
                return;
            }
            var portal = document.getElementById(TOUR_PORTAL_ID);
            if (!portal) {
                portal = document.createElement('div');
                portal.setAttribute('id', TOUR_PORTAL_ID);
                document.body.appendChild(portal);
            }
            portalRef.current = portal;
            return function() {
                if (portal) {
                    portal.remove();
                }
            };
        }, []);
        (0, _react.useEffect)(function() {
            updateHighlight();
            window.addEventListener('resize', updateHighlight);
            window.addEventListener('scroll', updateHighlight, true);
            return function() {
                window.removeEventListener('resize', updateHighlight);
                window.removeEventListener('scroll', updateHighlight, true);
            };
        }, [
            currentStep
        ]);
        (0, _react.useEffect)(function() {
            if (isOpen && targetElement) {
                targetElement.scrollIntoView({
                    block: 'center',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, [
            isOpen,
            active,
            targetElement
        ]);
        (0, _react.useEffect)(function() {
            var handleKeyDown = function handleKeyDown(e) {
                if (e.key === 'Escape') {
                    handleClose();
                }
            };
            if (isOpen) {
                window.addEventListener('keydown', handleKeyDown);
            }
            return function() {
                window.removeEventListener('keydown', handleKeyDown);
            };
        }, [
            isOpen,
            handleClose
        ]);
        if (!currentStep || !_utils.canUseDOM || !portalRef.current) {
            return null;
        }
        var tourContent = /*#__PURE__*/ _react.default.createElement(Root, _object_spread({
            renderStep: renderStep,
            steps: steps,
            ref: outerRef,
            view: view,
            size: size
        }, rest), isOpen && withOverlay && /*#__PURE__*/ _react.default.createElement(_Tourstyles.MaskContainer, {
            className: _Tourtokens.classes.mask,
            zIndex: zIndex
        }, /*#__PURE__*/ _react.default.createElement(_Tourstyles.Mask, null), Boolean(highlightRect) && /*#__PURE__*/ _react.default.createElement(_Tourstyles.Highlight, {
            overlayColor: overlayColor,
            borderRadius: highlightBorderRadius,
            style: {
                left: ((_ref3 = highlightRect === null || highlightRect === void 0 ? void 0 : highlightRect.left) !== null && _ref3 !== void 0 ? _ref3 : 0) - highlightOffset,
                top: ((_ref4 = highlightRect === null || highlightRect === void 0 ? void 0 : highlightRect.top) !== null && _ref4 !== void 0 ? _ref4 : 0) - highlightOffset,
                width: ((_ref5 = highlightRect === null || highlightRect === void 0 ? void 0 : highlightRect.width) !== null && _ref5 !== void 0 ? _ref5 : 0) + highlightOffset * 2,
                height: ((_ref6 = highlightRect === null || highlightRect === void 0 ? void 0 : highlightRect.height) !== null && _ref6 !== void 0 ? _ref6 : 0) + highlightOffset * 2
            }
        })), isOpen && Boolean(targetElement) && /*#__PURE__*/ _react.default.createElement(_Tourstyles.TourPortal, {
            ref: refs.setFloating,
            style: _object_spread_props(_object_spread({}, floatingStyles), {
                zIndex: Number(zIndex)
            }),
            "data-placement": calculatedPlacement
        }, renderStep && renderStep(active, steps.length, active === steps.length - 1, steps[active])));
        return /*#__PURE__*/ (0, _reactdom.createPortal)(tourContent, portalRef.current);
    });
};
var tourConfig = {
    name: 'Tour',
    tag: 'div',
    layout: tourRoot,
    base: '',
    variations: {
        view: {
            css: _base.base
        },
        size: {
            css: _base1.base
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
