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 _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);
}
import React, { forwardRef, useEffect, useState, useRef } from "react";
import { createPortal } from "react-dom";
import { useFloating, offset, flip, shift, autoUpdate } from "@floating-ui/react-dom";
import { canUseDOM } from "../../utils";
import { getHTMLElement, getIncreasedRadius, findRootElement } from "./utils";
import { MaskContainer, Mask, Highlight, TourPortal } from "./Tour.styles";
import { base as viewCSS } from "./variatoins/_view/base";
import { base as sizeCSS } from "./variatoins/_size/base";
import { classes } from "./Tour.tokens";
export var tourRoot = function tourRoot(Root) {
    return /*#__PURE__*/ 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(useState(defaultCurrent), 2), innerCurrent = _useState[0], setInnerCurrent = _useState[1];
        var _useState1 = _sliced_to_array(useState(defaultOpen), 2), innerOpen = _useState1[0], setInnerOpen = _useState1[1];
        var _useState2 = _sliced_to_array(useState(null), 2), highlightRect = _useState2[0], setHighlightRect = _useState2[1];
        var _useState3 = _sliced_to_array(useState(null), 2), highlightBorderRadius = _useState3[0], setHighlightBorderRadius = _useState3[1];
        var _useState4 = _sliced_to_array(useState(null), 2), targetElement = _useState4[0], setTargetElement = _useState4[1];
        var portalRef = 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 = [
            offset(offsetProp[0]),
            flip({
                fallbackPlacements: Array.isArray(currentStep === null || currentStep === void 0 ? void 0 : currentStep.placement) ? currentStep.placement : undefined
            }),
            shift({
                padding: offsetProp[1]
            })
        ];
        var _useFloating = useFloating({
            placement: placement,
            middleware: middleware,
            whileElementsMounted: 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 = findRootElement(currentStep.target);
            var highlightElement = 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 ? 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);
            }
        };
        useEffect(function() {
            refs.setReference(targetElement);
        }, [
            refs,
            targetElement
        ]);
        useEffect(function() {
            if (!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();
                }
            };
        }, []);
        useEffect(function() {
            updateHighlight();
            window.addEventListener('resize', updateHighlight);
            window.addEventListener('scroll', updateHighlight, true);
            return function() {
                window.removeEventListener('resize', updateHighlight);
                window.removeEventListener('scroll', updateHighlight, true);
            };
        }, [
            currentStep
        ]);
        useEffect(function() {
            if (isOpen && targetElement) {
                targetElement.scrollIntoView({
                    block: 'center',
                    inline: 'center',
                    behavior: 'smooth'
                });
            }
        }, [
            isOpen,
            active,
            targetElement
        ]);
        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 || !canUseDOM || !portalRef.current) {
            return null;
        }
        var tourContent = /*#__PURE__*/ React.createElement(Root, _object_spread({
            renderStep: renderStep,
            steps: steps,
            ref: outerRef,
            view: view,
            size: size
        }, rest), isOpen && withOverlay && /*#__PURE__*/ React.createElement(MaskContainer, {
            className: classes.mask,
            zIndex: zIndex
        }, /*#__PURE__*/ React.createElement(Mask, null), Boolean(highlightRect) && /*#__PURE__*/ React.createElement(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.createElement(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__*/ createPortal(tourContent, portalRef.current);
    });
};
export var tourConfig = {
    name: 'Tour',
    tag: 'div',
    layout: tourRoot,
    base: '',
    variations: {
        view: {
            css: viewCSS
        },
        size: {
            css: sizeCSS
        }
    },
    defaults: {
        view: 'default',
        size: 'm'
    }
};
