// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { useState, useEffect, useRef } from 'react';
import { scrollIntoView } from '../utils';
import OnDarkContext from '../OnDarkContext';
import Layer from '../Layer';
import SpotPulsar from './SpotPulsar';
import SpotPopup from './SpotPopup';
import { jsx as _jsx } from "react/jsx-runtime";
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] = useState();
  const pulsarRef = useRef(null);
  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;
            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__*/_jsx(SpotPulsar, {
    rect: rect,
    placement: placement,
    ...props,
    ref: pulsarRef
  });
  return /*#__PURE__*/_jsx(OnDarkContext.Provider, {
    value: true,
    children: /*#__PURE__*/_jsx(Layer, {
      children: popup ? /*#__PURE__*/_jsx(SpotPopup, {
        pulsar: pulsar,
        pulsarRef: pulsarRef,
        meta: meta,
        ...popup
      }) : /*#__PURE__*/_jsx("div", {
        children: pulsar
      })
    })
  });
};
export default Spot;