import { _ as _toConsumableArray } from './toConsumableArray-f7074d7c.js';
import { a as _Promise } from './asyncToGenerator-958ef5fc.js';
import { _ as _extends } from './extends-6d8e3924.js';
import { _ as _inherits, a as _classCallCheck, b as _possibleConstructorReturn, c as _Object$getPrototypeOf, d as _createClass } from './inherits-a6ba2ec4.js';
import React__default from 'react';
import { l as lib_3 } from './index-f0fc23eb.js';
import Container from 'react-bootstrap/Container';
import 'react-bootstrap/Row';
import 'react-bootstrap/Col';
import 'react-bootstrap/Card';
import './moment-bc12cb97.js';
import { withRouter } from 'next/router';
import { l as lodash } from './lodash-f97fd99a.js';
import { d as debounce_1 } from './debounce-533d9748.js';
import { I as InfiniteScroll } from './index.es-a6137319.js';
import { V as VisibilitySensor } from './visibility-sensor-72fd8f8b.js';
import './slicedToArray-6ebcbfea.js';
import './index-3f5c03b2.js';
import { A as ADlgInfeed } from './ADlgInfeed-dc36c928.js';
import { A as ADInfeed } from './ADInfeed-6d1fc6bf.js';
import './main-1894c974.js';
import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-ea258bb1.js';
import './_iter-detect-98db3b07.js';
import './web.dom.iterable-ab4dea5c.js';
import './_library-528f1934.js';
import './_object-pie-133f504a.js';
import './_object-sap-7cee6f84.js';
import './define-property-5f1bda73.js';
import './typeof-e9fc0c5d.js';
import './_is-array-8d21b9e3.js';
import './events-6c3a7a63.js';
import 'prop-types';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import 'react-dom';
import './AdSlot.js';
import './Beam.js';
import './stringify-2b084bee.js';
import './Segment.js';

var MasterDeck = function (_React$Component) {
  _inherits(MasterDeck, _React$Component);

  function MasterDeck() {
    var _ref,
        _this2 = this;

    var _temp, _this, _ret;

    _classCallCheck(this, MasterDeck);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = MasterDeck.__proto__ || _Object$getPrototypeOf(MasterDeck)).call.apply(_ref, [this].concat(args))), _this), _this.Deck = _this.props.deck, _this.variant = _this.props.variant, _this.mapping = _this.props.mapping, _this.data = _this.props.dataRecord || [], _this.query = _this.props.query, _this.params = _this.props.params, _this.pointer = _this.props.pointer ? _this.props.pointer : false, _this.pointerArray = _this.props.pointerArray ? _this.props.pointerArray : false, _this.defaultImage = _this.props.defaultImage ? _this.props.defaultImage : '/placeholder.jpg', _this.rightItems = _this.props.rightItems ? _this.props.rightItems : false, _this.isSeriesLanding = _this.props.isSeriesLanding ? _this.props.isSeriesLanding : false, _this.client = _this.props.client, _this.state = {
      data: _this.data,
      dataKeptToCompareNewDatarecord: _this.data,
      per: _this.params ? _this.params.to : 2,
      page: _this.props.currentPage || 1,
      from: _this.params ? _this.params.from : 0,
      to: _this.params ? _this.params.to : 2,
      total_pages: null,
      scrolling: false,
      query: _this.query,
      currentPage: _this.props.currentPage || 1,
      dataRemapped: !_this.props.showBI || !_this.props.brandInsightAd,
      lastDataSize: _this.data ? _this.data.length : 0,
      itemsPerPage: _this.params ? _this.params.to - _this.params.from : 2,
      mobileView: false
    }, _this.loadMore = debounce_1(function () {
      _this.setState(function (state) {
        var page = state.page,
            from = state.from,
            to = state.to,
            itemsPerPage = state.itemsPerPage;

        return {
          page: page + 1,
          from: from + itemsPerPage,
          to: to + itemsPerPage
        };
      }, _this.loadData);
    }, 0), _this.loadData = function () {
      var _this$state = _this.state,
          from = _this$state.from,
          to = _this$state.to,
          data = _this$state.data,
          query = _this$state.query,
          page = _this$state.page;
      var _this$props = _this.props,
          client = _this$props.client,
          dataHandler = _this$props.dataHandler;


      var params = _extends({}, _this.props.params, { from: from, to: to + 1 });

      if (dataHandler) {
        var dataHandlerPromise = new _Promise(function (resolve, reject) {
          try {
            var result = dataHandler(params);
            resolve(result);
          } catch (e) {
            reject(e);
          }
        });
        dataHandlerPromise.then(function (dataArr) {
          _this.loadDataFinished(data, dataArr, page);
        });
      } else {
        client.fetch(query, params).then(function (dataArr) {
          _this.loadDataFinished(data, dataArr, page);
        });
      }
    }, _this.loadDataFinished = function (data, dataArr, page) {
      if (_this.pointer && _this.pointerArray) {
        var pointer = _this.pointer;
        dataArr = dataArr[_this.pointerArray][pointer];
      }

      if (dataArr && dataArr.length > 0) {
        var itemsPerPage = _this.state.itemsPerPage;

        var scrolling = dataArr.length === itemsPerPage + 1;
        dataArr = dataArr.slice(0, itemsPerPage).map(function (item) {
          return _extends({}, item, {
            pageNumber: page
          });
        });

        _this.setState({
          data: [].concat(_toConsumableArray(data), _toConsumableArray(dataArr)),
          lastDataSize: dataArr.length,
          scrolling: scrolling
        });
      } else {
        _this.setState({
          scrolling: false,
          lastDataSize: 0
        });
      }
    }, _this.checkMoreDataAvailable = function () {
      var _this$state2 = _this.state,
          from = _this$state2.from,
          itemsPerPage = _this$state2.itemsPerPage,
          query = _this$state2.query;
      var _this$props2 = _this.props,
          client = _this$props2.client,
          dataHandler = _this$props2.dataHandler;

      var params = _extends({}, _this.props.params, { from: from + itemsPerPage, to: from + itemsPerPage + 1 });
      if (dataHandler) {
        var dataHandlerPromise = new _Promise(function (resolve, reject) {
          try {
            var result = dataHandler(params);
            resolve(result);
          } catch (e) {
            reject(e);
          }
        });
        dataHandlerPromise.then(function (dataArr) {
          if (dataArr && dataArr.length > 0) _this.setState({ scrolling: true });else _this.setState({ scrolling: false });
        });
      } else {
        client.fetch(query, params).then(function (dataArr) {
          if (dataArr && dataArr.length > 0) _this.setState({ scrolling: true });else _this.setState({ scrolling: false });
        });
      }
    }, _this.changePageNumber = function (pageNumber) {
      var _this$props3 = _this.props,
          seoPaginate = _this$props3.seoPaginate,
          pageview = _this$props3.pageview,
          router = _this$props3.router;
      var currentPage = _this.state.currentPage;

      if (seoPaginate) {
        var path = router.asPath;
        var qrIndex = path.indexOf('?');
        var pathname = router.pathname;
        var queryString = '';

        if (qrIndex > 0) {
          path = path.substring(1, qrIndex);

          var partialQS = router.asPath.substring(qrIndex + 1);
          var partialQSArr = partialQS.split('&');

          // exclude page=xxx from query string
          partialQSArr.map(function (item) {
            var itemArr = item.split('=');
            var key = itemArr[0];
            var val = itemArr[1];

            if (key !== 'page') {
              queryString += (queryString.length === 0 ? '' : '&') + key + '=' + val;
            }
          });
        }

        if (queryString.length > 0) {
          path += '?' + queryString;
        }

        pageNumber = parseInt(pageNumber);

        if (currentPage !== pageNumber) {
          lib_3.refresh();

          _this.setState({
            currentPage: pageNumber
          }, function () {
            if (path[0] !== '/') {
              path = '/' + path;
            }
            var newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;
            if (window.location.href.includes('?')) {
              if (window.location.href.includes('?page')) {
                newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;
              } else {
                newPath = pageNumber === 1 ? '' + path : path + '&page=' + pageNumber;
              }
            }

            // please leave this for later debug purpose : Yong Jun.
            /* console.log('page change reported', {
              currentPage: currentPage,
              pageNumber: pageNumber,
              pathname: pathname,
              path: path,
              newPath: newPath,
              firstPage: pageNumber === 1,
              queryString: queryString
            }) */

            if (pageview) {
              pageview(newPath);
            }

            router.push(pathname, newPath, {
              shallow: true
            });
          });
        }
      }
    }, _this.cardLoader = function (page, columns, variant, brandInsightAd, showBI, lgInfeedAd) {
      var numberOfItemsBeforeAd = 6;
      var data = _this.state.data;
      var insertBrandInsightAd = function insertBrandInsightAd(arr, index, newElement) {
        return [].concat(_toConsumableArray(arr.slice(0, index)), [newElement], _toConsumableArray(arr.slice(index)));
      };
      //  Need to pass flag "lgInfeedAd={true}" along with brandInsightAd from site level for large infeed-ad to render
      //  Checking lgInfeedAd flag in desktop view ( window >= 1400px ).
      //  Integrating large infeed AD
      if (lgInfeedAd && brandInsightAd && typeof window !== 'undefined' && window.innerWidth >= 1400) {
        var lgInfeed = {
          _type: 'lg-infeed',
          adUnit: brandInsightAd.adUnit,
          className: 'lg-infeed',
          networkID: brandInsightAd.networkID,
          sizes: [728, 90],
          sizeMapping: [{
            viewport: [1400, 0],
            sizes: [[728, 90]]
          }, { viewport: [0, 0], sizes: [] }],
          targeting: {
            content_placement: brandInsightAd.targeting.content_placement,
            document_url: brandInsightAd.targeting.document_url,
            document_group: brandInsightAd.targeting.document_group,
            rootDocumentGroup: brandInsightAd.targeting.rootDocumentGroup
          },
          /* Passing refresh flag */
          refreshFlag: brandInsightAd.refreshFlag ? brandInsightAd.refreshFlag : false
        };

        var chunks = lodash.chunk(data, 6).map(function (chunk) {
          var set = lodash.chunk(chunk, 2);
          for (var i = 0; i < set.length; i++) {
            if (i !== set.length - 1) {
              set[i].push(lgInfeed);
            }
          }
          return lodash.flattenDeep(set);
        });
        data = lodash.flatten(chunks);
        !_this.state.dataRemapped && _this.setState({ dataRemapped: true }); // To detect if appending of insights ads are completed
      }

      //  Integrating infeed AD
      if (showBI && brandInsightAd) {
        //  Checking lgInfeedAd flag in desktop view ( window >= 1400px ).
        if (lgInfeedAd && typeof window !== 'undefined' && window.innerWidth >= 1400) brandInsightAd.interval = 8;
        var pos = 0;
        for (var i = 1; pos < data.length; i++) {
          var inFeedAd = {
            adUnit: brandInsightAd.adUnit,
            className: brandInsightAd.className,
            networkID: brandInsightAd.networkID,
            sizes: brandInsightAd.sizes,
            slotId: brandInsightAd.slotId + '_' + i,
            targeting: {
              pos: 'infeed',
              content_placement: brandInsightAd.targeting.content_placement,
              document_url: brandInsightAd.targeting.document_url,
              document_group: brandInsightAd.targeting.document_group,
              rootDocumentGroup: brandInsightAd.targeting.rootDocumentGroup
            },
            _type: 'brandInsightAd',
            /* Passing refresh flag */
            refreshFlag: brandInsightAd.refreshFlag ? brandInsightAd.refreshFlag : false
          };

          data = insertBrandInsightAd(data, pos, inFeedAd);
          pos += brandInsightAd.interval + 1;
        }
      }

      // 'index' was including the indexes for infeed ads along with article count making the page number change before it reaches last article.
      data = data.map(function (ele, i) {
        if (ele._type === 'lg-infeed') {
          //  Setting pos as top2 for the first occurence of large infeed ad
          // const pos = data.indexOf(data.find((d) => d._type === 'lg-infeed')) === i ? 'top2' : `lg-infeed_${i}`
          return _extends({}, ele, { slotId: 'lg-infeed_' + i, targeting: _extends({}, ele.targeting, { pos: 'lg-infeed' }) });
        } else {
          return ele;
        }
      });

      return React__default.createElement(
        'div',
        null,
        data && _this.state.dataRemapped && data.length > 0 ? // If JS enabled and Data remapped with ads
        data.map(function (row, index) {
          var pageNumber = row.pageNumber || _this.state.page;

          if (row._type === 'lg-infeed' && row.adUnit) {
            return React__default.createElement(ADlgInfeed, _extends({ index: index }, row));
            //  Returning view for infeed Ad
          } else if (row._type === 'brandInsightAd' && row.adUnit) {
            return React__default.createElement(ADInfeed, { index: index, infeedAd: row });
          } else if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            //  Returning view for articles
            return React__default.createElement(
              VisibilitySensor,
              {
                key: row._id ? row._id : index,
                onChange: function onChange(isVisible) {
                  isVisible && _this.changePageNumber(pageNumber);
                } },
              React__default.createElement(
                React__default.Fragment,
                { key: index },
                React__default.createElement(_this2.Deck, { data: row, variant: variant, index: index, client: _this.props.client, defaultImage: _this.defaultImage, isSeriesLanding: _this.isSeriesLanding }),
                _this.state.mobileView && _this.rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && React__default.createElement(
                  'div',
                  { className: 'ad-container', style: { margin: '0 auto' } },
                  _this.renderMobileAd(index, numberOfItemsBeforeAd, _this.rightItems)
                )
              )
            );
          } else {
            return null;
          }
        }) : data && data.length > 0 ? //For Javascript Disabled Cases. data is not remapped if JS is disabled.
        data.map(function (row, index) {
          var pageNumber = row.pageNumber || _this.state.page;
          if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            return React__default.createElement(
              VisibilitySensor,
              {
                key: row._id ? row._id : index,
                onChange: function onChange(isVisible) {
                  isVisible && _this.changePageNumber(pageNumber);
                } },
              React__default.createElement(
                React__default.Fragment,
                { key: index },
                React__default.createElement(_this2.Deck, { data: row, variant: variant, index: index, client: _this.props.client, defaultImage: _this.defaultImage, isSeriesLanding: _this.isSeriesLanding })
              )
            );
          }
        }) : React__default.createElement(
          'div',
          null,
          React__default.createElement(
            'em',
            null,
            'New content coming soon, please check back later.'
          )
        )
      );
    }, _this.renderMobileAd = function (index, numberOfItemsBeforeAd, rightItems) {
      var i = ((index + 1) / numberOfItemsBeforeAd - 1) % rightItems.length;
      return React__default.createElement(
        'div',
        { className: 'ad-container', style: { display: 'flex', flex: '1 0 auto', width: '100%', textAlign: 'center', marginBottom: '2rem' } },
        rightItems[i].component
      );
    }, _this.renderManualPagination = function (_ref2) {
      var nextPagePostsCount = _ref2.nextPagePostsCount;
      var _this$state3 = _this.state,
          currentPage = _this$state3.currentPage,
          itemsPerPage = _this$state3.itemsPerPage,
          lastDataSize = _this$state3.lastDataSize;

      console.log('lastDataSize:', lastDataSize);
      console.log('itemsPerPage:', itemsPerPage);
      console.log('nextPagePostsCount:', nextPagePostsCount);
      return React__default.createElement(
        'div',
        { className: 'd-flex justify-content-between' },
        currentPage && currentPage > 1 && React__default.createElement(
          'a',
          { href: '?page=' + (currentPage - 1) },
          '<< Previous'
        ),
        !(lastDataSize < itemsPerPage) && nextPagePostsCount > 0 && React__default.createElement(
          'a',
          { href: '?page=' + (currentPage + 1) },
          'Next >>'
        )
      );
    }, _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(MasterDeck, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (this.state.dataKeptToCompareNewDatarecord !== this.props.dataRecord) {
        // eslint-disable-next-line react/no-did-update-set-state
        this.setState({
          data: this.props.dataRecord,
          dataKeptToCompareNewDatarecord: this.props.dataRecord,
          per: this.props.params ? this.props.params.to : 2,
          page: 1,
          from: this.props.params ? this.props.params.from : 0,
          to: this.props.params ? this.props.params.to : 2,
          total_pages: null,
          scrolling: true,
          query: this.props.query,
          lastDataSize: this.props.dataRecord ? this.props.dataRecord.length : 0
        });
      }
      // set dataRemap to true as there are no infeed or BI ads or window width is less than limit
      if (typeof window !== 'undefined' && (!this.props.lgInfeedAd || !this.props.brandInsightAd || window.innerWidth < 1400) && !this.state.dataRemapped) {
        !this.state.dataRemapped && this.setState({ dataRemapped: true });
      }

      if (typeof window !== 'undefined' && window.innerWidth <= 1191) {
        !this.state.mobileView && this.setState({ mobileView: true });
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _state = this.state,
          data = _state.data,
          itemsPerPage = _state.itemsPerPage;

      if (!(data.length < itemsPerPage)) this.checkMoreDataAvailable();
    }
    //  Passing 'brandInsightAd','showBI' and 'lgInfeedAd'

  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      //  Setting default value for 'showBI' and 'lgInfeedAd'
      var _props = this.props,
          columns = _props.columns,
          variant = _props.variant,
          autoScroll = _props.autoScroll,
          page = _props.page,
          brandInsightAd = _props.brandInsightAd,
          _props$showBI = _props.showBI,
          showBI = _props$showBI === undefined ? false : _props$showBI,
          _props$lgInfeedAd = _props.lgInfeedAd,
          lgInfeedAd = _props$lgInfeedAd === undefined ? false : _props$lgInfeedAd,
          _props$nextPagePostsC = _props.nextPagePostsCount,
          nextPagePostsCount = _props$nextPagePostsC === undefined ? 2 : _props$nextPagePostsC;

      return React__default.createElement(
        'div',
        { className: 'contentDeck' },
        autoScroll ? React__default.createElement(
          React__default.Fragment,
          null,
          React__default.createElement(
            InfiniteScroll,
            { dataLength: this.state.data.length, next: this.loadMore, hasMore: this.state.scrolling, scrollThreshold: 0.9 },
            React__default.createElement(
              Container,
              null,
              this.cardLoader(page, columns, variant, brandInsightAd, showBI, lgInfeedAd)
            )
          ),
          React__default.createElement(
            'noscript',
            null,
            this.renderManualPagination({ nextPagePostsCount: nextPagePostsCount })
          )
        ) : React__default.createElement(
          React__default.Fragment,
          null,
          React__default.createElement(
            Container,
            null,
            this.cardLoader(page, columns, variant, brandInsightAd, showBI, lgInfeedAd)
          ),
          React__default.createElement(
            'div',
            { style: { padding: '0px 10px' } },
            this.state.scrolling && React__default.createElement(
              'button',
              {
                className: 'btn',
                style: {
                  margin: '0 auto 2rem',
                  display: 'block',
                  fontSize: '18px',
                  padding: '.5rem 1.5rem',
                  boxShadow: '1px 2px 4px 4px rgba(0,0,0,.15)',
                  background: 'var(--primary)',
                  color: '#fff',
                  borderRadius: '5px'
                },
                onClick: function onClick(e) {
                  _this3.loadMore();
                } },
              'Load More'
            )
          ),
          React__default.createElement(
            'noscript',
            null,
            this.renderManualPagination({ nextPagePostsCount: nextPagePostsCount })
          )
        )
      );
    }
  }]);

  return MasterDeck;
}(React__default.Component);

var MasterDeck$1 = withRouter(MasterDeck);

export default MasterDeck$1;
