import { _ as _toConsumableArray } from './toConsumableArray-6d9a4616.js';
import { _ as _extends } from './extends-60e0e1c6.js';
import { _ as _slicedToArray } from './slicedToArray-be2f7a22.js';
import React, { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/router';
import { l as lib_3 } from './index-2446af28.js';
import { I as InfiniteScroll } from './index.es-c6222053.js';
import { S as SeriesSlider } from './SeriesSlider-f9325e75.js';
import { V as VisibilitySensor } from './visibility-sensor-f40c2564.js';
import './_commonjsHelpers-0c4b6f40.js';
import './es6.string.iterator-bc33758b.js';
import './_to-object-b50e61c3.js';
import './_iter-detect-7e5e5ce2.js';
import './core.get-iterator-method-133dfacd.js';
import './_object-pie-133f504a.js';
import './web.dom.iterable-4109ff68.js';
import './events-6c3a7a63.js';
import 'prop-types';
import './index-c7e2ac95.js';
import './index-35bdcc81.js';
import 'react-dom';
import './smoothscroll-fa4e3f8c.js';
import './urlFor.js';
import './index-0dbff1d1.js';
import './main-b5c5aac1.js';

var usePrevious = function usePrevious(value) {
  var ref = useRef();
  useEffect(function () {
    ref.current = value;
  });
  return ref.current;
};

var SeriesListingDeck = function SeriesListingDeck(props) {
  var data = props.data,
      client = props.client,
      query = props.query,
      params = props.params,
      parentIdentifier = props.identifier,
      initialCurrentPage = props.currentPage,
      pageview = props.pageview;

  var _useState = useState(params ? params.count : 0),
      _useState2 = _slicedToArray(_useState, 1),
      count = _useState2[0];

  var _useState3 = useState(true),
      _useState4 = _slicedToArray(_useState3, 2),
      scrolling = _useState4[0],
      setScrolling = _useState4[1];

  var _useState5 = useState(data.series),
      _useState6 = _slicedToArray(_useState5, 2),
      seriesData = _useState6[0],
      setSeriesData = _useState6[1];

  var _useState7 = useState(initialCurrentPage || 1),
      _useState8 = _slicedToArray(_useState7, 2),
      currentPage = _useState8[0],
      setCurrentPage = _useState8[1];

  var _useState9 = useState({
    from: params ? params.from : 0,
    to: params ? params.to : 0,
    page: 1
  }),
      _useState10 = _slicedToArray(_useState9, 2),
      values = _useState10[0],
      setValues = _useState10[1];

  var prevValues = usePrevious(values);

  var router = useRouter();

  var loadMore = function loadMore() {
    setValues({
      page: values.page + 1,
      from: parseInt(values.from) + parseInt(count),
      to: parseInt(values.to) + parseInt(count)
    });
  };

  var changePageNumber = function changePageNumber(pageNumber, arrIndex, pageview) {
    if (pageNumber) {
      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)
      var index = Number(arrIndex);
      var perPage = 6;

      pageNumber = Math.ceil((index + 1) / perPage);

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

        setCurrentPage(pageNumber);
        if (path[0] !== '/') {
          path = '/' + path;
        }

        var newPath = pageNumber === 1 ? '' + path : '' + path + (queryString.length > 0 ? '&' : '?') + 'page=' + pageNumber;

        if (pageview) {
          pageview(newPath);
        }

        router.push(pathname, newPath, {
          shallow: true
        });
      }
    }
  };

  var loadData = function loadData(values, query, client, params, setSeriesData, setScrolling) {
    params = _extends({}, params, {
      from: values.from,
      to: values.to
    });

    client.fetch(query, params).then(function (dataArr) {
      if (!dataArr.series) {
        dataArr.series = [];
      }

      dataArr.series = dataArr.series.map(function (item) {
        return _extends({}, item, {
          pageNumber: values.page
        });
      });

      if (dataArr.series.length > 0) {
        setSeriesData(function (prevData) {
          var newArr = [].concat(_toConsumableArray(prevData), _toConsumableArray(dataArr.series));
          return newArr;
        });
        setScrolling(true);
      } else {
        var parentScroll = document.getElementsByClassName('infinite-scroll-component')[0];
        parentScroll.style.overflow = 'hidden';
        setScrolling(false);
      }
    });
  };

  useEffect(function () {
    if (prevValues) {
      if (values.page !== prevValues.page && values.from !== prevValues.from && values.to !== prevValues.from) {
        loadData(values, query, client, params, setSeriesData, setScrolling);
      }
    }
  }, [values, prevValues, query, client, params, setSeriesData, setScrolling]);

  useEffect(function () {
    if (seriesData.length < count) {
      var parentScroll = document.getElementsByClassName('infinite-scroll-component')[0];
      parentScroll.style.overflow = 'hidden';
      setScrolling(false);
    }
  }, [seriesData, setScrolling, count]);

  return React.createElement(
    InfiniteScroll,
    { dataLength: seriesData && seriesData.length, next: function next() {
        return loadMore();
      }, hasMore: scrolling, scrollThreshold: 0.9 },
    React.createElement(
      'div',
      null,
      seriesData && seriesData.length ? React.createElement(
        'div',
        null,
        seriesData.map(function (series, index) {
          return React.createElement(
            VisibilitySensor,
            {
              key: series._id ? series._id : index,
              partialVisibility: true,
              onChange: function onChange(isVisible) {
                isVisible && changePageNumber(currentPage, index, pageview);
              } },
            React.createElement(
              'div',
              { className: 'mb-5', key: series.name },
              React.createElement(
                'div',
                { style: { fontSize: '20px', fontWeight: 'bold', borderBottom: '1px solid #eee', margin: '0 .5rem', color: '373a3c' } },
                React.createElement(
                  'a',
                  { href: '/' + parentIdentifier + '/' + series.identifier.current },
                  series.name
                )
              ),
              series.articles && series.articles.length == 0 && React.createElement(
                'p',
                { className: 'mt-2 ml-2' },
                'Please check back for more content.'
              ),
              series.articles && series.articles.length > 0 && React.createElement(SeriesSlider, _extends({}, props, { dataset: series.articles, client: client }))
            )
          );
        })
      ) : React.createElement(
        'div',
        null,
        React.createElement(
          'h5',
          null,
          React.createElement(
            'em',
            { className: 'pl-3' },
            'New content coming soon, please check back later.'
          )
        )
      )
    )
  );
};

export default SeriesListingDeck;
