import { _ as _toConsumableArray } from './toConsumableArray-f7074d7c.js';
import { _ as _extends } from './extends-1559c147.js';
import { _ as _inherits, a as _classCallCheck, b as _possibleConstructorReturn, c as _Object$getPrototypeOf, d as _createClass } from './inherits-d21b4ef9.js';
import React__default from 'react';
import { l as lib_3 } from './index-f0fc23eb.js';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Card from 'react-bootstrap/Card';
import { m as moment } from './moment-bc12cb97.js';
import { withRouter } from 'next/router';
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 urlFor from './urlFor.js';
import { L as LazyLoad } from './index-755f2cc2.js';
import { m as main_43 } from './main-f97773b2.js';
import { c as clean_html_1 } from './entities-6d9154b4.js';
import { A as ADInfeed } from './ADInfeed-74cc728c.js';
import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-ea258bb1.js';
import './_iter-detect-98db3b07.js';
import './_object-sap-7cee6f84.js';
import './define-property-5f1bda73.js';
import './typeof-657f25da.js';
import './web.dom.iterable-ab4dea5c.js';
import './_is-array-8d21b9e3.js';
import './_library-528f1934.js';
import './events-6c3a7a63.js';
import 'prop-types';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import 'react-dom';
import './slicedToArray-6ebcbfea.js';
import './index-3f5c03b2.js';
import './AdSlot.js';
import './Beam.js';
import './stringify-2b084bee.js';
import './asyncToGenerator-64822ccc.js';
import './_set-species-2cd9340f.js';
import './Segment.js';

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

  function DeckContent() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, DeckContent);

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

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = DeckContent.__proto__ || _Object$getPrototypeOf(DeckContent)).call.apply(_ref, [this].concat(args))), _this), _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.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: true,
      query: _this.query,
      currentPage: _this.props.currentPage || 1,
      lastDataSize: _this.data ? _this.data.length : 0,
      itemsPerPage: _this.params.itemsPerPage || 3
    }, _this.loadMore = debounce_1(function () {
      _this.setState(function (state) {
        var page = state.page,
            from = state.from,
            per = state.per,
            to = state.to;

        return {
          page: page + 1,
          from: from + per,
          to: to + per
        };
      }, _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 client = _this.props.client;


      var params = _extends({}, _this.params, { from: from, to: to
        // const queryUpdated = query.replace('$from', params.from).replace('$to', params.to)
        // const query = '*[_type == "article" && defined(title) && defined(thumbnail)][$from...$to] { title, summary, thumbnail { asset-> }, url }'
      });client.fetch(query, params).then(function (dataArr) {
        if (_this.pointer && _this.pointerArray) {
          var pointer = _this.pointer;
          dataArr = dataArr[_this.pointerArray][pointer];
        }
        dataArr = dataArr.map(function (item) {
          return _extends({}, item, {
            pageNumber: page
          });
        });

        _this.setState(function () {
          if (dataArr.length > 0) {
            return {
              data: [].concat(_toConsumableArray(data), _toConsumableArray(dataArr)),
              scrolling: true,
              lastDataSize: dataArr.length
            };
          } else {
            return {
              scrolling: false,
              lastDataSize: 0
            };
          }
        });
      });
    }, _this.renderCardImage = function (row, page) {
      if (row.thumbnail && row.thumbnail.asset) {
        var url = urlFor({
          client: _this.client,
          source: row.thumbnail,
          imageHeight: _this.props.imageHeight || null,
          imageWidth: _this.props.imageWidth || null,
          imageFit: _this.props.imageFit || null
        });
        return url;
      } else {
        return _this.defaultImage;
      }
    }, _this.changePageNumber = function (pageNumber) {
      var _this$props = _this.props,
          seoPaginate = _this$props.seoPaginate,
          pageview = _this$props.pageview,
          router = _this$props.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;

            // 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.renderAuthor = function (authorDetail, index, length) {
      if (authorDetail) {
        var _id = authorDetail._id,
            displayName = authorDetail.displayName,
            url = authorDetail.url;

        if (displayName && url && url.current) {
          return React__default.createElement(
            'div',
            { key: _id },
            index === 0 && React__default.createElement(
              'span',
              { className: 'pr-1' },
              'By'
            ),
            React__default.createElement(
              'a',
              { href: '/authors/${url.current}', className: 'text-muted' },
              displayName,
              length !== index + 1 && React__default.createElement('br', null)
            )
          );
        } else if (displayName) {
          return React__default.createElement(
            'div',
            { key: _id },
            index === 0 && React__default.createElement(
              'span',
              { className: 'pr-1' },
              'By'
            ),
            React__default.createElement(
              'span',
              { className: 'text-muted' },
              displayName,
              length !== index + 1 && React__default.createElement('br', null)
            )
          );
        }
      } else return null;
    }, _this.cardLoader = function (page, columns, variant, showBI, brandInsight) {
      var biStart = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 3;

      var mode = variant && variant === 'bottom' ? 'column-reverse' : 'column';

      var itemCounter = 0;
      var lgVar = 12;
      var numberOfItemsBeforeAd = 6;

      var insert = function insert(arr, index, newElement) {
        return [].concat(_toConsumableArray(arr.slice(0, index)), [newElement], _toConsumableArray(arr.slice(index)));
      };
      var articles = [];
      if (showBI) {
        var data = _this.state.data;
        articles = data;
        var pos = biStart;
        for (var i = 1; pos < articles.length; i++) {
          var inFeedAd = {
            adUnit: brandInsight.adUnit,
            className: brandInsight.className,
            networkID: brandInsight.networkID,
            sizes: brandInsight.sizes,
            slotId: brandInsight.slotId + '_' + i,
            targeting: {
              pos: 'infeed',
              content_placement: brandInsight.targeting.content_placement,
              document_url: brandInsight.targeting.document_url
            },
            _type: 'BrandInsight',
            /* Passing refresh flag */
            refreshFlag: brandInsight.refreshFlag ? brandInsight.refreshFlag : false
          };

          articles = insert(articles, pos, inFeedAd);
          pos += brandInsight.interval + 1;
        }
      } else {
        articles = _this.state.data;
      }

      return React__default.createElement(
        Row,
        null,
        articles && articles.map(function (row, index) {
          if (columns === 'rotate' && itemCounter % 3 === 0) {
            lgVar = 12;
          } else if (columns && columns !== 'rotate') {
            lgVar = Math.floor(12 / columns);
          } else {
            lgVar = 6;
          }
          if (row._type === 'BrandInsight' && row.adUnit) {
            return React__default.createElement(ADInfeed, { index: index, infeedAd: row });
          } else {
            var pageNumber = row.pageNumber || _this.state.page;
            var contentCategoryName = row.contentCategory && row.contentCategory.name && _this.mapping[row.contentCategory.name] ? row.contentCategory.name : 'Articles';
            return React__default.createElement(
              React__default.Fragment,
              { key: itemCounter },
              React__default.createElement(
                VisibilitySensor,
                {
                  onChange: function onChange(isVisible) {
                    isVisible && _this.changePageNumber(pageNumber);
                  } },
                React__default.createElement(
                  Col,
                  { md: 12, lg: lgVar, counter: itemCounter++, style: { display: 'flex', flex: '1 0 auto' } },
                  React__default.createElement(
                    Card,
                    { className: 'content-card', style: { flexDirection: mode } },
                    (row.thumbnail && row.thumbnail.asset || _this.props.defaultImage) && React__default.createElement(
                      'a',
                      { href: _this.mapping[contentCategoryName] + '/' + row.url.current },
                      React__default.createElement(
                        LazyLoad,
                        { height: _this.props.imageHeight },
                        React__default.createElement(Card.Img, {
                          variant: 'top',
                          src: _this.renderCardImage(row, page),
                          alt: row.thumbnail && row.thumbnail.asset ? row.thumbnail.asset.originalFilename : ''
                        })
                      )
                    ),
                    React__default.createElement(
                      Card.Body,
                      null,
                      React__default.createElement(
                        'a',
                        { href: _this.mapping[contentCategoryName] + '/' + row.url.current },
                        React__default.createElement(
                          Card.Title,
                          null,
                          row.title
                        )
                      ),
                      _this.props.showPublished && row.published && React__default.createElement(
                        Card.Subtitle,
                        null,
                        moment(row.published).format('MMMM DD, YYYY')
                      ),
                      _this.props.showAuthor && row.authorMapping && row.authorMapping.length > 0 && row.authorMapping.map(function (authorDetail, index) {
                        return _this.renderAuthor(authorDetail, index, row.authorMapping.length);
                      }),
                      React__default.createElement(
                        Card.Text,
                        null,
                        clean_html_1(row.summary)
                      )
                    )
                  )
                )
              ),
              main_43 && _this.props.rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && _this.renderMobileAd(index, numberOfItemsBeforeAd)
            );
          }
        })
      );
    }, _this.renderMobileAd = function (index, numberOfItemsBeforeAd) {
      var rightItems = _this.props.rightItems;

      var i = ((index + 1) / numberOfItemsBeforeAd - 1) % rightItems.length;
      return React__default.createElement(
        Col,
        { md: 12, style: { display: 'flex', flex: '1 0 auto' } },
        rightItems[i].component
      );
    }, _this.renderManualPagination = function (_ref2) {
      var nextPagePostsCount = _ref2.nextPagePostsCount;
      var currentPage = _this.state.currentPage;

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

  _createClass(DeckContent, [{
    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
        });
      }
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      // this.loadData();
    }
  }, {
    key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props,
          columns = _props.columns,
          variant = _props.variant,
          autoScroll = _props.autoScroll,
          page = _props.page,
          showBI = _props.showBI,
          brandInsight = _props.brandInsight,
          biStart = _props.biStart,
          _props$nextPagePostsC = _props.nextPagePostsCount,
          nextPagePostsCount = _props$nextPagePostsC === undefined ? 3 : _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, showBI, brandInsight, biStart)
            )
          ),
          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, showBI, brandInsight, biStart)
          ),
          React__default.createElement(
            'div',
            { style: { padding: '0px 10px' } },
            this.state.scrolling ? React__default.createElement(
              'button',
              {
                style: { margin: 'auto', width: '100%' },
                onClick: function onClick(e) {
                  _this2.loadMore();
                } },
              'Load More'
            ) : React__default.createElement(
              'p',
              { style: { textAlign: 'center' } },
              React__default.createElement(
                'b',
                null,
                'End of data'
              )
            )
          ),
          React__default.createElement(
            'noscript',
            null,
            this.renderManualPagination({ nextPagePostsCount: nextPagePostsCount })
          )
        )
      );
    }
  }]);

  return DeckContent;
}(React__default.Component);

var ContentCard = withRouter(DeckContent);

export { ContentCard as default };
