import { useId } from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import customizable from "../../../utils/css/customizable.js";
import useMountOnObserved from './hooks/useMountOnObserved';
import classes from './styles.module.scss';

/**
 * Programmatic advertisements generated by our ad manager (the actual ads
 * won't show in Storybook). In general we tend to include a `leaderboard` ad
 * at the top of a story above the navigation and `supercube` ads throughout
 * the body of a story.
 *
 * ```js
 *
 * import { Ad } from '@politico/interactive-style';
 * ```
 */
const Ad = function Ad(props) {
  const {
    type,
    observationThreshold,
    rootMargin,
    rootThreshold,
    rootNode,
    alwaysDisplayPlaceholder
  } = props;
  const rId = useId();
  const id = `ad-${rId.split(':')[1]}`;
  const [ref,, mounted] = useMountOnObserved({
    observationThreshold,
    rootMargin,
    rootThreshold,
    rootNode,
    id,
    type
  });
  const placeholder = type.startsWith('leaderboard') ? 'rect' : 'box';
  const placeholderActive = alwaysDisplayPlaceholder || !mounted;
  return <div ref={ref} className={classnames(customizable('Ad'), classes.container, classes[type])}>
      <p className={classnames(customizable('Ad__disclaimer'), classes.disclaimer)}>
        Advertisement
      </p>
      <div className={classnames(customizable('Ad__placeholder'), classes.placeholder, classes[`placeholder-${placeholder}`], classes[`placeholder-${type}`], {
      [classes.active]: placeholderActive
    })} />
      <div id={id} className={classnames(customizable('Ad__mount'), classes.mount, classes[`mount-${placeholder}`], classes[`mount-${type}`], {
      [classes.active]: !placeholderActive
    })} />
    </div>;
};
Ad.defaultProps = {
  type: 'supercube',
  observationThreshold: 1,
  rootMargin: '700px',
  alwaysDisplayPlaceholder: false,
  rootNode: undefined,
  rootThreshold: 1
};
Ad.propTypes = {
  /**
   * What type of ad to call for
   */
  type: PropTypes.oneOf(['cube', 'supercube', 'leaderboard', 'leaderboard-320']),
  /**
   * How long (in ms) should the ad be in sight before loading
   */
  observationThreshold: PropTypes.number,
  /**
   * The area around the ad which counts as "being in sight"
   */
  rootMargin: PropTypes.string,
  /**
   * The element that is used as the viewport for checking
   * visibility of the target. Must be the ancestor of the
   * target. Defaults to the browser viewport if not specified
   * or if null.
   */
  rootNode: PropTypes.element,
  /**
   * Either a single number or an array of numbers which
   * indicate at what percentage of the target's visibility
   * the observer's callback should be executed.
   */
  rootThreshold: PropTypes.oneOfType([PropTypes.number, PropTypes.arrayOf(PropTypes.number)]),
  /**
   * An option to keep the placeholder even if the ad is mounted
   */
  alwaysDisplayPlaceholder: PropTypes.bool
};
export default Ad;