import { useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import cx from "../../../utils/css/cx.js";
import useIntersectionObserver from "../../../hooks/useIntersectionObserver/index.js";
import classes from './styles.module.scss';
const cls = cx.merge(classes);

/**
 * A sticky top bar that can provide some down-page navigation or whatever
 * else you might need to do in a sticky top bar. By default this component
 * will render its children in an absolutely positioned container so that
 * it doesn't take up any height on the page and it will only be visible
 * while it is actually sticky.
 */
const StickyTopBar = function StickyTopBar(props) {
  const {
    zIndex,
    intersectionRootMargin,
    alwaysVisible = false,
    disableAbsoluteContentContainer = false,
    children
  } = props;
  const [isSticky, setIsSticky] = useState(false);
  const callback = useCallback(entry => {
    const visible = !entry.isIntersecting && entry.boundingClientRect.top < 0;
    setIsSticky(visible);
  }, []);
  const ref = useIntersectionObserver({
    callback,
    rootMargin: intersectionRootMargin
  });
  const absoluteContentContainer = !disableAbsoluteContentContainer;
  return <>
      <div ref={ref} />
      <div className={cls('stickyTopBar', {
      alwaysVisible,
      isSticky
    })} style={{
      '--StickyTopBar-z-index': zIndex
    }}>
        <div className={cls({
        absoluteContentContainer
      })}>
          {children}
        </div>
      </div>
    </>;
};
StickyTopBar.defaultProps = {
  zIndex: undefined,
  intersectionRootMargin: undefined,
  alwaysVisible: false,
  disableAbsoluteContentContainer: false,
  children: undefined
};
StickyTopBar.propTypes = {
  /**
   * Set a specific z-index for the sticky bar other than the default of 10
   */
  zIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  /**
   * Customize the root margin of the intersection observer that determines
   * whether the bar is currently sticky or not
   */
  intersectionRootMargin: PropTypes.string,
  /**
   * Force the bar to always be visible rather than fading away when it's
   * not sticky.
   */
  alwaysVisible: PropTypes.bool,
  /**
   * Turn off the default `position: absolute` container that wraps the bar
   * contents.
   */
  disableAbsoluteContentContainer: PropTypes.bool,
  /**
   * What to render inside the sticky bar
   */
  children: PropTypes.node
};
export default StickyTopBar;