import { useMemo } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import useResizeObserver from "../../../hooks/useResizeObserver/index.js";
import useBreakpointName from "../../../hooks/breakpoint/useBreakpointName/index.js";
import IfActive from "../../application/IfActive/index.js";
import Ad from "../../brand/Ad/index.js";
import classes from './styles.module.scss';
const adTypeRemap = {
  leaderboard: 'banner_btf',
  periodic: 'mrec-small_btf',
  'page-end': 'banner_btf'
};

/**
 * An ad to be sprinkled in alongside elections content.
 */
const ElectionAd = function ElectionAd(props) {
  const {
    adType,
    breakpoints,
    periodicPixelsPerAd
  } = props;
  const breakpoint = useBreakpointName();
  const [ref, [width, height]] = useResizeObserver();
  const baseAdType = adTypeRemap[adType] || adType;
  const numAds = adType === 'periodic' ? Math.max(1, Math.floor(height / periodicPixelsPerAd)) : 1;
  const adKeys = useMemo(() => [...Array(numAds)].map((_, i) => i), [numAds]);
  if (breakpoints && !breakpoints.includes(breakpoint)) return null;
  return <div ref={ref} className={classnames(classes.root, classes[adType])}>
      <IfActive active={width > 300}>
        {adKeys.map(key => <div key={key} className={classnames(classes.container, classes[adType])}>
            <Ad type={baseAdType} />
          </div>)}
      </IfActive>
    </div>;
};
ElectionAd.defaultProps = {
  breakpoints: undefined,
  periodicPixelsPerAd: 1300
};
ElectionAd.propTypes = {
  /**
   * The type of ad to render. Cube ads should be slotted in body content while
   * supercube ads act as section breaks and go end-to-end.
   */
  adType: PropTypes.oneOf(['cube', 'supercube', 'leaderboard', 'periodic', 'page-end']).isRequired,
  /**
   * The set of breakpoints at which this ad should be visible.
   */
  breakpoints: PropTypes.arrayOf(PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl'])),
  /**
   * The number of pixels per ad for periodic ads
   */
  periodicPixelsPerAd: PropTypes.number
};
export default ElectionAd;