import { _ as _JSON$stringify } from './stringify-2b084bee.js';
import { _ as _asyncToGenerator, r as regenerator, a as _Promise } from './asyncToGenerator-958ef5fc.js';
import { _ as _extends } from './extends-6d8e3924.js';
import { _ as _toConsumableArray } from './toConsumableArray-f7074d7c.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 Spinner from 'react-bootstrap/Spinner';
import { withRouter } from 'next/router';
import { l as lodash } from './lodash-f97fd99a.js';
import { m as main_43 } from './main-9f6806ea.js';
import { A as ADlgInfeed } from './ADlgInfeed-e7fd1bb6.js';
import { A as ADInfeed } from './ADInfeed-777bb0b3.js';
import { P as Pagination } from './Pagination-9fe9f61d.js';
import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-ea258bb1.js';
import './web.dom.iterable-ab4dea5c.js';
import './_library-528f1934.js';
import './_iter-detect-98db3b07.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 './slicedToArray-6ebcbfea.js';
import 'react-bootstrap/Card';
import './AdSlot.js';
import './debounce-533d9748.js';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import './Beam.js';
import './Segment.js';
import 'react-bootstrap/Button';
import './index.esm-1bd8a0a8.js';
import './iconBase-ccc56b97.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.data = _this.props.dataRecord || [], _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.state = {
      isDataLoading: false,
      data: _this.data,
      prevData: _this.data,
      currentPage: _this.props.currentPage || 1,
      dataRemapped: !_this.props.showBI || !_this.props.brandInsightAd,
      itemsPerPage: _this.props.params ? _this.props.params.to - _this.props.params.from : 2,
      mobileView: false
    }, _this.seoPagination = function (pageNumber) {
      var _this$props = _this.props,
          pageview = _this$props.pageview,
          router = _this$props.router;

      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 (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 (_ref2) {
      var variant = _ref2.variant,
          brandInsightAd = _ref2.brandInsightAd,
          showBI = _ref2.showBI,
          lgInfeedAd = _ref2.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) {
          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(
              React__default.Fragment,
              { key: index },
              React__default.createElement(_this2.Deck, {
                data: row,
                currentPage: _this.state.currentPage,
                itemsPerPage: _this.state.itemsPerPage,
                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) {
          if (!row._type || !['lg-infeed', 'brandInsightAd'].includes(row._type)) {
            return React__default.createElement(
              React__default.Fragment,
              { key: index },
              React__default.createElement(_this2.Deck, {
                data: row,
                currentPage: _this.state.currentPage,
                itemsPerPage: _this.state.itemsPerPage,
                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.handlePageChange = function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(selectedPage) {
        var itemsPerPage, _this$props2, query, params, client, dataHandler, seoPaginate, start, newParams, dataHandlerPromise, newData;

        return regenerator.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                itemsPerPage = _this.state.itemsPerPage;
                _this$props2 = _this.props, query = _this$props2.query, params = _this$props2.params, client = _this$props2.client, dataHandler = _this$props2.dataHandler, seoPaginate = _this$props2.seoPaginate;

                _this.setState({ isDataLoading: true, currentPage: selectedPage });
                seoPaginate && _this.seoPagination(selectedPage);
                lib_3.refresh();
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
                start = (selectedPage - 1) * itemsPerPage;
                newParams = _extends({}, params, {
                  from: start,
                  to: start + itemsPerPage
                });
                dataHandlerPromise = null;

                if (dataHandler) {
                  dataHandlerPromise = new _Promise(function (resolve, reject) {
                    try {
                      var result = dataHandler(newParams);
                      resolve(result);
                    } catch (e) {
                      reject(e);
                    }
                  });
                }

                _context.prev = 11;

                if (!dataHandlerPromise) {
                  _context.next = 18;
                  break;
                }

                _context.next = 15;
                return dataHandlerPromise;

              case 15:
                _context.t0 = _context.sent;
                _context.next = 21;
                break;

              case 18:
                _context.next = 20;
                return client.fetch(query, newParams);

              case 20:
                _context.t0 = _context.sent;

              case 21:
                newData = _context.t0;

                if (_this.pointer && _this.pointerArray) newData = newData[_this.pointerArray][_this.pointer];
                if (newData && newData.length > 0) {
                  _this.setState({ isDataLoading: false, data: newData });
                }
                _context.next = 29;
                break;

              case 26:
                _context.prev = 26;
                _context.t1 = _context['catch'](11);

                console.error(_context.t1);

              case 29:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this2, [[11, 26]]);
      }));

      return function (_x) {
        return _ref3.apply(this, arguments);
      };
    }(), _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(MasterDeck, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps, prevState) {
      if (_JSON$stringify(this.state.prevData) !== _JSON$stringify(prevState.prevData) && this.props.seoPaginate) {
        this.seoPagination(this.state.currentPage);
      }
      // 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: 'render',
    value: function render() {
      //  Setting default value for 'showBI' and 'lgInfeedAd'
      var _props = this.props,
          variant = _props.variant,
          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,
          totalDataCount = _props.totalDataCount;
      var _state = this.state,
          data = _state.data,
          itemsPerPage = _state.itemsPerPage,
          currentPage = _state.currentPage,
          isDataLoading = _state.isDataLoading;

      return React__default.createElement(
        'div',
        { className: 'contentDeck' },
        isDataLoading ? React__default.createElement(
          'div',
          { className: 'd-flex justify-content-center', style: { marginTop: '100px' } },
          React__default.createElement(
            Spinner,
            { animation: 'border', role: 'status' },
            React__default.createElement(
              'span',
              { className: 'sr-only' },
              'Loading...'
            )
          )
        ) : data && data.length > 0 ? React__default.createElement(
          Container,
          null,
          this.cardLoader({ variant: variant, brandInsightAd: brandInsightAd, showBI: showBI, lgInfeedAd: lgInfeedAd }),
          React__default.createElement(
            'div',
            { className: 'pagination-wrapper' },
            React__default.createElement(Pagination, {
              pageCount: Math.ceil(totalDataCount / itemsPerPage),
              pageRangeDisplayed: main_43 ? 3 : 9,
              currentPage: currentPage,
              onPageChange: this.handlePageChange,
              needLargePaginateButtons: this.props.needLargePaginateButtons
            }),
            React__default.createElement(
              'style',
              { jsx: 'true' },
              '\n                .pagination-wrapper {\n                  margin: 3rem 0 100px 0;\n                }\n              '
            )
          )
        ) : null
      );
    }
  }], [{
    key: 'getDerivedStateFromProps',
    value: function getDerivedStateFromProps(props, state) {
      if (_JSON$stringify(props.dataRecord) !== _JSON$stringify(state.prevData)) {
        return {
          data: props.dataRecord,
          prevData: props.dataRecord,
          currentPage: props.currentPage
        };
      }
      return null;
    }
    //  Passing 'brandInsightAd','showBI' and 'lgInfeedAd'

  }]);

  return MasterDeck;
}(React__default.Component);

var MasterDeck$1 = withRouter(MasterDeck);

export { MasterDeck$1 as default };
