import React, { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import { FLIP_MODIFIER, OFFSET_MODIFIER, Popper, POPPER_PLACEMENTS_TYPES, POPPER_STRATEGY_OPTIONS } from '../react-popper';
import { TourFooter } from './components/tour-footer';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/**
 * Component to demonstrate tour onboarding information.
 * Could be attached to any component on the page by its selector.
 * @uxr-only-supported
 * @midnight-gray-supported
 * @alpine-light-supported
 * */
const Tour = ({
  step,
  setNextStep,
  setPrevStep,
  onCompleteHandler,
  showTour,
  onSkipHandler,
  stepNumber = 0,
  totalSteps = 0,
  className = ''
}) => {
  const ref = useRef(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const {
    selector,
    placement,
    content,
    imageSrc,
    altText
  } = step;
  let observer = null;
  useEffect(() => {
    let anchorElement = document.querySelector(selector);
    if (anchorElement) {
      setAnchorEl(anchorElement);
    } else {
      observer = new MutationObserver(() => {
        anchorElement = document.querySelector(selector);
        if (anchorElement) {
          observer?.disconnect();
          setAnchorEl(anchorElement);
        }
      });
      observer.observe(document.body, {
        childList: true,
        subtree: true
      });
    }
    return () => {
      if (observer) {
        observer.disconnect();
        observer = null;
      }
    };
  }, [selector]);
  if (!anchorEl) {
    return null;
  }
  return /*#__PURE__*/_jsx(Popper, {
    open: showTour,
    rootEl: ref,
    container: anchorEl,
    placement: placement || POPPER_PLACEMENTS_TYPES.BOTTOM,
    anchorEl: anchorEl,
    strategy: POPPER_STRATEGY_OPTIONS.FIXED,
    popperModifiers: [OFFSET_MODIFIER, FLIP_MODIFIER],
    children: () => /*#__PURE__*/_jsxs("div", {
      className: classNames('tour-container popout popout-transition react-tooltip', className),
      ref: ref,
      "test-id": "tour-container",
      children: [/*#__PURE__*/_jsx("img", {
        className: "tour-image",
        "test-id": "tour-img",
        src: imageSrc,
        alt: altText
      }), /*#__PURE__*/_jsx("div", {
        className: "tour-content",
        "test-id": "tour-content",
        children: typeof content === 'string' ? /*#__PURE__*/_jsx("p", {
          children: content
        }) : content
      }), /*#__PURE__*/_jsx(TourFooter, {
        stepNumber: stepNumber,
        totalSteps: totalSteps,
        onNextHandler: setNextStep,
        onPrevHandler: setPrevStep,
        onCompleteHandler: onCompleteHandler,
        onSkipHandler: onSkipHandler
      }), /*#__PURE__*/_jsx("div", {
        "data-popper-arrow": ""
      })]
    })
  });
};
export default Tour;