'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _rollupPluginBabelHelpers = require('../../_virtual/_rollupPluginBabelHelpers.js');
var React = require('react');
var ReactDOM = require('react-dom');
var react$1 = require('@floating-ui/react');
var Popover = require('../_beta/Popover/Popover.js');
var index = require('./utils/index.js');
var Tour_styles = require('./Tour.styles.js');
var base = require('./variatoins/_view/base.js');
var base$1 = require('./variatoins/_size/base.js');
var Tour_tokens = require('./Tour.tokens.js');
var react = require('../../utils/react.js');
var canUseDOM = require('../../utils/canUseDOM.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var React__default = /*#__PURE__*/_interopDefault(React);

var _Mask;
var _excluded = ["steps", "current", "defaultCurrent", "open", "defaultOpen", "withOverlay", "overlayColor", "zIndex", "view", "size", "offset", "highlightOffset", "highlightBorderRadius", "hasTail", "tailColor", "tailWidth", "tailHeight", "renderStep", "renderHighlight", "onChange", "onClose"];
var tourRoot = function tourRoot(Root) {
  return /*#__PURE__*/React.forwardRef(function (_ref, outerRef) {
    var _ref2, _currentStep$highligh;
    var steps = _ref.steps,
      current = _ref.current,
      _ref$defaultCurrent = _ref.defaultCurrent,
      defaultCurrent = _ref$defaultCurrent === void 0 ? 0 : _ref$defaultCurrent,
      open = _ref.open,
      _ref$defaultOpen = _ref.defaultOpen,
      defaultOpen = _ref$defaultOpen === void 0 ? false : _ref$defaultOpen,
      _ref$withOverlay = _ref.withOverlay,
      withOverlay = _ref$withOverlay === void 0 ? true : _ref$withOverlay,
      overlayColor = _ref.overlayColor,
      _ref$zIndex = _ref.zIndex,
      zIndex = _ref$zIndex === void 0 ? 9000 : _ref$zIndex,
      view = _ref.view,
      size = _ref.size,
      _ref$offset = _ref.offset,
      offsetProp = _ref$offset === void 0 ? [12, 12] : _ref$offset,
      _ref$highlightOffset = _ref.highlightOffset,
      highlightOffset = _ref$highlightOffset === void 0 ? 4 : _ref$highlightOffset,
      highlightBorderRadius = _ref.highlightBorderRadius,
      _ref$hasTail = _ref.hasTail,
      hasTail = _ref$hasTail === void 0 ? false : _ref$hasTail,
      tailColor = _ref.tailColor,
      _ref$tailWidth = _ref.tailWidth,
      tailWidth = _ref$tailWidth === void 0 ? Popover.ARROW_WIDTH : _ref$tailWidth,
      _ref$tailHeight = _ref.tailHeight,
      tailHeight = _ref$tailHeight === void 0 ? Popover.ARROW_HEIGHT : _ref$tailHeight,
      renderStep = _ref.renderStep,
      renderHighlight = _ref.renderHighlight,
      onChange = _ref.onChange,
      onClose = _ref.onClose,
      rest = _rollupPluginBabelHelpers.objectWithoutProperties(_ref, _excluded);
    var portalId = react.safeUseId();
    var isCurrentControlled = typeof current === 'number';
    var isOpenControlled = typeof open === 'boolean';
    var _useState = React.useState(defaultCurrent),
      _useState2 = _rollupPluginBabelHelpers.slicedToArray(_useState, 2),
      innerCurrent = _useState2[0],
      setInnerCurrent = _useState2[1];
    var _useState3 = React.useState(defaultOpen),
      _useState4 = _rollupPluginBabelHelpers.slicedToArray(_useState3, 2),
      innerOpen = _useState4[0],
      setInnerOpen = _useState4[1];
    var _useState5 = React.useState(null),
      _useState6 = _rollupPluginBabelHelpers.slicedToArray(_useState5, 2),
      highlightRect = _useState6[0],
      setHighlightRect = _useState6[1];
    var _useState7 = React.useState(null),
      _useState8 = _rollupPluginBabelHelpers.slicedToArray(_useState7, 2),
      targetElement = _useState8[0],
      setTargetElement = _useState8[1];
    var portalRef = React.useRef(null);
    var dialogRef = React.useRef(null);
    var arrowRef = React.useRef(null);
    var hasHighlightedRef = React.useRef(false);
    var active = isCurrentControlled ? current : innerCurrent;
    var isOpen = isOpenControlled ? open : innerOpen;
    var isFirstHighlight = !hasHighlightedRef.current && highlightRect !== null;
    if (isFirstHighlight) {
      hasHighlightedRef.current = true;
    }
    var currentStep = steps[active];
    var placement = (currentStep === null || currentStep === void 0 ? void 0 : currentStep.placement) || 'bottom';
    var middleware = [react$1.offset((hasTail ? tailHeight : 0) + offsetProp[0] + highlightOffset), react$1.flip(), react$1.shift({
      padding: offsetProp[1]
    }), hasTail && react$1.arrow({
      element: arrowRef,
      padding: Popover.ARROW_PADDING
    })];
    var _useFloating = react$1.useFloating({
        placement: placement,
        middleware: middleware,
        whileElementsMounted: react$1.autoUpdate
      }),
      refs = _useFloating.refs,
      floatingStyles = _useFloating.floatingStyles,
      calculatedPlacement = _useFloating.placement,
      context = _useFloating.context;
    var setFloatingRef = function setFloatingRef(el) {
      dialogRef.current = el;
      refs.setFloating(el);
    };
    var handleSetOpen = function handleSetOpen(value) {
      if (!isOpenControlled) {
        setInnerOpen(value);
      }
      if (!value) {
        onClose === null || onClose === void 0 || onClose();
        setInnerCurrent(0);
        setHighlightRect(null);
        setTargetElement(null);
      }
    };
    var handleSetCurrent = function handleSetCurrent(index) {
      if (!isCurrentControlled) {
        setInnerCurrent(index);
      }
      onChange === null || onChange === void 0 || onChange(index);
    };
    var handleClose = function handleClose() {
      handleSetOpen(false);
    };
    var updateHighlight = React.useCallback(function () {
      if (!isOpen || !currentStep) {
        return;
      }
      var highlightElement = index.getHTMLElement(currentStep.target);
      if (!highlightElement) {
        setHighlightRect(null);
        setTargetElement(null);
        return;
      }
      var rect = highlightElement.getBoundingClientRect();
      setHighlightRect(rect);
      setTargetElement(highlightElement);
    }, [isOpen, currentStep]);
    React.useEffect(function () {
      refs.setReference(targetElement);
    }, [refs, targetElement]);
    React.useEffect(function () {
      if (isOpen) {
        if (targetElement) {
          var rect = targetElement.getBoundingClientRect();
          var 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]);
    React.useEffect(function () {
      if (!canUseDOM.canUseDOM) {
        return;
      }
      var portal = document.getElementById(portalId);
      if (!portal) {
        portal = document.createElement('div');
        portal.setAttribute('id', portalId);
        document.body.appendChild(portal);
      }
      portalRef.current = portal;
      return function () {
        var _portal;
        (_portal = portal) === null || _portal === void 0 || _portal.remove();
      };
    }, []);
    React.useEffect(function () {
      if (!isOpen) {
        return;
      }
      updateHighlight();
      window.addEventListener('resize', updateHighlight);
      window.addEventListener('scroll', updateHighlight, true);
      return function () {
        window.removeEventListener('resize', updateHighlight);
        window.removeEventListener('scroll', updateHighlight, true);
      };
    }, [isOpen, updateHighlight]);
    React.useEffect(function () {
      if (!isOpen) {
        return;
      }
      var handleKeyDown = function handleKeyDown(e) {
        if (e.key === 'Escape') {
          handleClose();
        }
      };
      window.addEventListener('keydown', handleKeyDown);
      return function () {
        window.removeEventListener('keydown', handleKeyDown);
      };
    }, [isOpen, handleClose]);
    React.useEffect(function () {
      if (!isOpen) {
        hasHighlightedRef.current = false;
        setHighlightRect(null);
      }
    }, [isOpen]);
    if (!currentStep || !canUseDOM.canUseDOM || !portalRef.current) {
      return null;
    }
    var arrowFill = tailColor || "var(".concat(Tour_tokens.tokens.tailColor, ")");
    var preparedHighlightBorderRadius = (_ref2 = (_currentStep$highligh = currentStep === null || currentStep === void 0 ? void 0 : currentStep.highlightBorderRadius) !== null && _currentStep$highligh !== void 0 ? _currentStep$highligh : highlightBorderRadius) !== null && _ref2 !== void 0 ? _ref2 : undefined;
    var preparedHighlightOffset = (currentStep === null || currentStep === void 0 ? void 0 : currentStep.highlightOffset) || highlightOffset;
    var 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;
    var highlightNode = highlightProps && (renderHighlight ? renderHighlight(highlightProps) : /*#__PURE__*/React__default.default.createElement(Tour_styles.Highlight, {
      withOverlay: withOverlay,
      overlayColor: overlayColor,
      borderRadius: preparedHighlightBorderRadius,
      disableTransition: isFirstHighlight,
      style: {
        left: highlightProps.left,
        top: highlightProps.top,
        width: highlightProps.width,
        height: highlightProps.height
      }
    }));
    var tourContent = /*#__PURE__*/React__default.default.createElement(Root, _rollupPluginBabelHelpers.extends({
      ref: outerRef,
      view: view,
      size: size
    }, rest), isOpen && Boolean(targetElement) && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(Tour_styles.MaskContainer, {
      className: Tour_tokens.classes.mask,
      zIndex: zIndex
    }, withOverlay ? _Mask || (_Mask = /*#__PURE__*/React__default.default.createElement(Tour_styles.Mask, null)) : null, highlightNode), /*#__PURE__*/React__default.default.createElement(Tour_styles.TourPortal, {
      ref: setFloatingRef,
      role: "dialog",
      "aria-modal": "true",
      tabIndex: -1,
      style: _rollupPluginBabelHelpers.objectSpread2(_rollupPluginBabelHelpers.objectSpread2({}, floatingStyles), {}, {
        zIndex: Number(zIndex)
      }),
      "data-placement": calculatedPlacement
    }, renderStep(active, steps.length, active === steps.length - 1, steps[active], handleSetCurrent), hasTail && /*#__PURE__*/React__default.default.createElement(react$1.FloatingArrow, {
      ref: arrowRef,
      context: context,
      width: tailWidth,
      height: tailHeight,
      fill: arrowFill,
      d: Popover.ARROW_POLYGON
    }))));
    return /*#__PURE__*/ReactDOM.createPortal(tourContent, portalRef.current);
  });
};
var tourConfig = {
  name: 'Tour',
  tag: 'div',
  layout: tourRoot,
  base: '',
  variations: {
    view: {
      css: base.base
    },
    size: {
      css: base$1.base
    }
  },
  defaults: {
    view: 'default',
    size: 'm'
  }
};

exports.tourConfig = tourConfig;
exports.tourRoot = tourRoot;
