'use strict';

var _extends = require('./extends-29bdbc6d.js');
var slicedToArray = require('./slicedToArray-5d1bc3b3.js');
var React = require('react');
var PropTypes = require('prop-types');
var index = require('./index-fc2f1ca2.js');
var debounce = require('./debounce-d4a2369b.js');
var Beam = require('./Beam.js');
var Segment = require('./Segment.js');
var main = require('./main-025fdc78.js');
require('./_commonjsHelpers-06173234.js');
require('./_to-object-6de10e57.js');
require('./_object-pie-083f2dd6.js');
require('./web.dom.iterable-46657b5c.js');
require('./es6.string.iterator-c2573ffd.js');
require('./core.get-iterator-method-f474eacc.js');
require('./events-1b438fe7.js');
require('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.js');
require('./stringify-c9ac1214.js');
require('./asyncToGenerator-58c289d9.js');
require('./_library-dd23b178.js');
require('./_iter-detect-55a5657a.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var PropTypes__default = /*#__PURE__*/_interopDefaultLegacy(PropTypes);

var initialLoadIsDone = false;
var initialLoadInProgress = false;

function runOnce(fn) {
  var called = false;
  return function () {
    if (called) {
      return;
    }
    called = true;
    fn.apply(this, arguments);
  };
}

var getSignalsAndRefreshAds = function getSignalsAndRefreshAds(slotId) {
  index.lib_3.getGoogletag().then(function (googletag) {
    googletag.cmd.push(function () {
      if (!initialLoadIsDone && !initialLoadInProgress && googletag.pubads().getSlots().length > 0) {
        // trigger ads refresh within googletag
        var refreshAds = function refreshAds() {
          googletag.cmd.push(function () {
            googletag.pubads().refresh();
            initialLoadIsDone = true;
          });
        };
        // wrap to make sure it's called once


        initialLoadInProgress = true;var refreshAdsOnce = runOnce(refreshAds);
        // trigger signals request and refresh ads when it's ready
        window.PQ.cmd.push(function () {
          PQ.loadSignals(['ids', 'bsc', 'vlp'], refreshAdsOnce);
        });
        // just in case something go wrong ads will be refreshed anyway after specified timeout
        var timeout = 1000;
        setTimeout(refreshAdsOnce, timeout);
      }
      if (initialLoadIsDone) {
        googletag.cmd.push(function () {
          var slots = googletag.pubads().getSlots();
          // find new slot within googletag
          var newSlot = slots.find(function (slot) {
            return slot.getSlotElementId() === slotId;
          });
          // refresh single slot which was added
          function refreshAd() {
            googletag.cmd.push(function () {
              googletag.pubads().refresh([newSlot]);
            });
          }
          var refreshAdOnce = runOnce(refreshAd);
          // get VLP signal value only for the added slot; IDS and BSC signals are global for the whole page so no need to refetch
          window.PQ.cmd.push(function () {
            PQ.loadSignalsForSlots([newSlot], refreshAdOnce);
          });
          var timeout = 1000;
          setTimeout(refreshAdOnce, timeout);
        });
      }
    });
  });
};

var DFPAdSlot = function DFPAdSlot(_ref) {
  var adUnit = _ref.adUnit,
      sizeMapping = _ref.sizeMapping,
      className = _ref.className,
      slotId = _ref.slotId,
      sizes = _ref.sizes,
      _ref$targeting = _ref.targeting,
      targeting = _ref$targeting === undefined ? {} : _ref$targeting,
      _ref$refreshFlag = _ref.refreshFlag,
      refreshFlag = _ref$refreshFlag === undefined ? true : _ref$refreshFlag,
      checkIsAdFound = _ref.checkIsAdFound,
      _ref$setStickyAd = _ref.setStickyAd,
      setStickyAd = _ref$setStickyAd === undefined ? function () {} : _ref$setStickyAd;

  var _useState = React.useState(false),
      _useState2 = slicedToArray._slicedToArray(_useState, 2),
      adRendered = _useState2[0],
      setAdRendered = _useState2[1];

  var _useState3 = React.useState(false),
      _useState4 = slicedToArray._slicedToArray(_useState3, 2),
      adRefreshable = _useState4[0],
      setAdRefreshable = _useState4[1];

  var _useState5 = React.useState(false),
      _useState6 = slicedToArray._slicedToArray(_useState5, 2);
      _useState6[0];
      _useState6[1];

  targeting.ksg = typeof window !== 'undefined' && window.Krux ? window.Krux.segments : null;
  targeting.kuid = typeof window !== 'undefined' && window.Krux ? window.Krux.user : null;

  var adTargeting = _extends._extends({}, targeting, { hostname: typeof window !== 'undefined' ? window.location.hostname : null });

  var handleVisibilityChange = debounce.debounce_1(function (_ref2) {
    var event = _ref2.event;

    if (event.inViewPercentage <= 0) {
      setAdRefreshable(false);
    } else {
      setAdRefreshable(true);
    }
  }, 500);

  React.useEffect(function () {
    // Setting hostname into AD targetting
    if (window && window.location && window.location.hostname) {
      adTargeting.hostname = window.location.hostname;
    }
  }, [adTargeting]);

  var _useState7 = React.useState(null),
      _useState8 = slicedToArray._slicedToArray(_useState7, 2),
      eventData = _useState8[0],
      setEventData = _useState8[1];

  return React__default['default'].createElement(
    'div',
    { className: className, style: { textAlign: 'center' } },
    React__default['default'].createElement(index.lib_2, {
      style: { marginBottom: '1rem' },
      slotId: slotId,
      sizes: sizes,
      adUnit: adUnit,
      sizeMapping: sizeMapping,
      targetingArguments: adTargeting,
      onSlotIsViewable: function onSlotIsViewable(e) {
        setStickyAd(true);
        Beam.report_beam_ad('Impression', main.main_18, eventData.cID, eventData.lID, eventData.campID, eventData.adSize, eventData.slot_id);
        Segment.adViewed(eventData.domain, eventData.advertiserId, eventData.campID, eventData.cID, eventData.lID, eventData.adSize, eventData.isEmpty, eventData.sourceAgnosticCreativeId, eventData.sourceAgnosticLineItemId);
      },
      onSlotRender: function onSlotRender(eventData) {
        // Updating the condition to remove the dependency on static slotId.
        if (eventData && eventData.event && checkIsAdFound && checkIsAdFound !== null) {
          if (eventData.event.size !== null && eventData.event.size.length) {
            checkIsAdFound(true, eventData);
          } else {
            checkIsAdFound(false, eventData);
          }
        }

        setAdRendered(true);
        if (eventData && eventData.event) {
          var cID = eventData.event.creativeId;
          var lID = eventData.event.lineItemId;
          var campID = eventData.event.campaignId;
          var adSize = eventData.event.size && eventData.event.size.length > 1 ? eventData.event.size[0] + 'x' + eventData.event.size[1] : '';
          var slot_id = eventData.slotId ? eventData.slotId : '';
          var isEmpty = eventData.event.isEmpty;
          var sourceAgnosticCreativeId = eventData.event.sourceAgnosticCreativeId;
          var sourceAgnosticLineItemId = eventData.event.sourceAgnosticLineItemId;
          var advertiserId = eventData.event.advertiserId;
          var domain = typeof window !== 'undefined' && window.location ? window.location.hostname : '';

          setEventData({
            cID: cID,
            lID: lID,
            campID: campID,
            adSize: adSize,
            slot_id: slot_id,
            isEmpty: isEmpty,
            sourceAgnosticCreativeId: sourceAgnosticCreativeId,
            sourceAgnosticLineItemId: sourceAgnosticLineItemId,
            advertiserId: advertiserId,
            domain: domain
          });

          var slot_div = document.getElementById(eventData.slotId);
          if (slot_div) {
            slot_div.addEventListener('mouseenter', function () {
              var timeoutId = slot_div.getAttribute('timeoutId');
              clearTimeout(timeoutId);
              slot_div.setAttribute('hasFocus', 'yes');
            });

            slot_div.addEventListener('mouseleave', function () {
              var timeoutId = setTimeout(function () {
                slot_div.setAttribute('hasFocus', 'no');
              }, 60);
              slot_div.setAttribute('timeoutId', timeoutId);
            });

            document.addEventListener('visibilitychange', function () {
              if (!document.hidden) {
                return;
              }

              var hasFocus = slot_div.getAttribute('hasFocus');
              if (hasFocus == 'yes' && document.hidden) {
                slot_div.setAttribute('hasFocus', 'no');
                Beam.report_beam_ad('Click', main.main_18, cID, lID, campID, adSize, slotId);
                Segment.adClicked(domain, advertiserId, campID, cID, lID, adSize, isEmpty, sourceAgnosticCreativeId, sourceAgnosticLineItemId);
              }
            });
          } else {
            console.error('slot div not found:', slotId);
          }
        }
      },
      onSlotVisibilityChanged: handleVisibilityChange,
      shouldRefresh: function shouldRefresh(event) {
        if (adRendered && adRefreshable && refreshFlag) return true;else return false;
      },
      onSlotRegister: function onSlotRegister(e) {
        window.PQ && setTimeout(function () {
          getSignalsAndRefreshAds(e && e.slotId);
        }, 0);
      }
    })
  );
};

DFPAdSlot.propTypes = {
  adUnit: PropTypes__default['default'].string.isRequired,
  slotId: PropTypes__default['default'].string,
  className: PropTypes__default['default'].string,
  sizeMapping: PropTypes__default['default'].array,
  sizes: PropTypes__default['default'].array
};

module.exports = DFPAdSlot;
