"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _utils = require("../utils");
var _OnDarkContext = _interopRequireDefault(require("../OnDarkContext"));
var _Layer = _interopRequireDefault(require("../Layer"));
var _SpotPulsar = _interopRequireDefault(require("./SpotPulsar"));
var _SpotPopup = _interopRequireDefault(require("./SpotPopup"));
var _jsxRuntime = require("react/jsx-runtime");
// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

const isEqual = (a, b) => a.top === b.top && a.left === b.left && a.right === b.right && a.bottom === b.bottom && a.width === b.width && a.height === b.height;

/**
 * The component can be used to attract the user's attention to a specific element on the page.
 * @since 3.0.1
 */
const Spot = _ref => {
  let {
    selector,
    popup,
    meta,
    placement,
    ...props
  } = _ref;
  const [rect, setRect] = (0, _react.useState)();
  const pulsarRef = (0, _react.useRef)(null);
  (0, _react.useEffect)(() => {
    let lastRect;
    let lastPageYOffset = window.pageYOffset;
    let isMoving = false;
    let needUpdate = false;
    let needScrollIntoView = true;
    const check = () => {
      const node = document.querySelector(selector);
      if (node) {
        const nextRect = node.getBoundingClientRect();
        if (!lastRect) {
          isMoving = true;
          lastRect = nextRect;
        } else if (!isEqual(nextRect, lastRect) || window.pageYOffset !== lastPageYOffset) {
          isMoving = true;
          lastPageYOffset = window.pageYOffset;
          lastRect = nextRect;
        } else if (isMoving) {
          isMoving = false;
          needUpdate = true;
        }
        if (needUpdate) {
          setRect(nextRect);
          needUpdate = false;
          if (needScrollIntoView) {
            needScrollIntoView = false;
            (0, _utils.scrollIntoView)(node, {
              scrollMode: 'if-needed'
            });
          }
        }
      } else {
        setRect(undefined);
      }
    };
    check();
    const retryId = window.setInterval(check, 125);
    return () => {
      window.clearInterval(retryId);
    };
  }, [selector]);
  if (!rect) {
    return null;
  }
  const pulsar = /*#__PURE__*/(0, _jsxRuntime.jsx)(_SpotPulsar.default, {
    rect: rect,
    placement: placement,
    ...props,
    ref: pulsarRef
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_OnDarkContext.default.Provider, {
    value: true,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_Layer.default, {
      children: popup ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_SpotPopup.default, {
        pulsar: pulsar,
        pulsarRef: pulsarRef,
        meta: meta,
        ...popup
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        children: pulsar
      })
    })
  });
};
var _default = exports.default = Spot;