'use strict';

var asyncToGenerator = require('./asyncToGenerator-77821af0.js');
var toConsumableArray = require('./toConsumableArray-d7797c2b.js');
var stringify = require('./stringify-f7a37a8d.js');
var slicedToArray = require('./slicedToArray-067dd3bc.js');
var React = require('react');
var reactBootstrap = require('react-bootstrap');
var index_es = require('./index.es-f3e47207.js');
var visibilitySensor = require('./visibility-sensor-eb2c5b69.js');
var main = require('./main-f1c77adb.js');
var debounce = require('./debounce-d4a2369b.js');
var Router = require('next/router');
var index = require('./index-fc2f1ca2.js');
require('./_commonjsHelpers-06173234.js');
require('./core.get-iterator-method-5643aa10.js');
require('./web.dom.iterable-d98303e0.js');
require('./_library-dd23b178.js');
require('./_iter-detect-b1df62f0.js');
require('react-dom');
require('./isSymbol-03abbdf0.js');
require('./toNumber-5e1fac58.js');
require('./events-1b438fe7.js');
require('prop-types');

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

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

var itemsPerPage = 12;

var CMEDeck = function CMEDeck(_ref) {
  var getData = function () {
    var _ref2 = asyncToGenerator._asyncToGenerator( /*#__PURE__*/asyncToGenerator.regenerator.mark(function _callee(params) {
      var response, newData;
      return asyncToGenerator.regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 3;
              return fetch('/api/get_activities', {
                headers: {
                  'Content-Type': 'application/json',
                  Accept: 'application/json'
                },
                method: 'post',
                credentials: 'same-origin',
                body: stringify._JSON$stringify({ params: params })
              });

            case 3:
              response = _context.sent;
              _context.next = 6;
              return response.json();

            case 6:
              newData = _context.sent;


              if (newData && newData.length > 0) {
                setIsLoading(false);
                newData.length === itemsPerPage ? setScrolling(true) : setScrolling(false);
                setData(function (prevData) {
                  return [].concat(toConsumableArray._toConsumableArray(prevData), toConsumableArray._toConsumableArray(newData));
                });
              } else {
                setScrolling(false);
              }
              _context.next = 13;
              break;

            case 10:
              _context.prev = 10;
              _context.t0 = _context['catch'](0);

              console.log(_context.t0);

            case 13:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this, [[0, 10]]);
    }));

    return function getData(_x) {
      return _ref2.apply(this, arguments);
    };
  }();

  var _ref$autoScroll = _ref.autoScroll,
      autoScroll = _ref$autoScroll === undefined ? true : _ref$autoScroll,
      _ref$variant = _ref.variant,
      variant = _ref$variant === undefined ? 'left' : _ref$variant,
      rightItems = _ref.rightItems,
      _ref$seoPaginate = _ref.seoPaginate,
      seoPaginate = _ref$seoPaginate === undefined ? true : _ref$seoPaginate,
      pageview = _ref.pageview;
      _ref.keywords;

  var router = Router.useRouter();

  var _useState = React.useState(true),
      _useState2 = slicedToArray._slicedToArray(_useState, 2),
      isLoading = _useState2[0],
      setIsLoading = _useState2[1];

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

  var _useState5 = React.useState(router && router.query && router.query.page ? parseInt(router.query.page) : 1),
      _useState6 = slicedToArray._slicedToArray(_useState5, 2),
      currentPage = _useState6[0],
      setCurrentPage = _useState6[1];

  var _useState7 = React.useState([]),
      _useState8 = slicedToArray._slicedToArray(_useState7, 2),
      data = _useState8[0],
      setData = _useState8[1];

  var _useState9 = React.useState(router && router.query && router.query.page ? (parseInt(router.query.page) - 1) * itemsPerPage : 0),
      _useState10 = slicedToArray._slicedToArray(_useState9, 2),
      from = _useState10[0],
      setFrom = _useState10[1];

  var currentPageRef = React.useRef(currentPage);
  var fromeRef = React.useRef(from);


  React.useEffect(function () {
    // load initial data
    getData({ from: from, to: itemsPerPage, itemsPerPage: itemsPerPage, currentPage: currentPage });
  }, []);

  var changePageNumber = function changePageNumber(pageNumber) {
    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 (currentPageRef.current !== pageNumber) {
        index.lib_3.refresh();

        currentPageRef.current = pageNumber;
        if (path[0] !== '/') {
          path = '/' + path;
        }
        var newPath = pageNumber === 1 ? '' + path : path + '?page=' + pageNumber;

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

  var loadMore = debounce.debounce_1(function () {
    setFrom(function (prevFrom) {
      return prevFrom + itemsPerPage;
    });
    setCurrentPage(function (prevCurrentPage) {
      return prevCurrentPage + 1;
    });
  }, 0);

  React.useEffect(function () {
    if (currentPageRef.current !== currentPage && fromeRef.current !== from) {
      fromeRef.current = from;
      getData({ from: from, limit: itemsPerPage });
    }
  }, [currentPage]);

  var cardLoader = function cardLoader() {
    var numberOfItemsBeforeAd = 6;
    return React__default['default'].createElement(
      'div',
      { id: 'ceToggles' },
      React__default['default'].createElement(
        'div',
        { style: { width: 'max-content', padding: '0.5rem' } },
        React__default['default'].createElement('img', { src: 'https://gotoper-com.s3.amazonaws.com/_media/_image/PER_Logo.svg', style: { width: '100%', maxWidth: '10rem', marginBottom: '1rem' }, alt: 'per logo' }),
        React__default['default'].createElement(
          'p',
          { style: { margin: '0', fontWeight: '700', width: '100%', textAlign: 'center', fontSize: '1rem' } },
          'Physician Education'
        )
      ),
      React__default['default'].createElement(
        reactBootstrap.Row,
        null,
        data && data.map(function (row, index) {
          var pageNumber = row.pageNumber || 1;
          return React__default['default'].createElement(
            React__default['default'].Fragment,
            { key: index },
            React__default['default'].createElement(
              visibilitySensor.VisibilitySensor,
              {
                onChange: function onChange(isVisible) {
                  isVisible && changePageNumber(pageNumber);
                } },
              variant === 'left' ? React__default['default'].createElement(
                reactBootstrap.Col,
                { xl: 12, style: { marginBottom: '1rem' } },
                React__default['default'].createElement(
                  reactBootstrap.Row,
                  null,
                  React__default['default'].createElement(
                    reactBootstrap.Col,
                    { xs: 3, sm: 4, md: 4, lg: 4, xl: 4, style: { padding: '0' } },
                    React__default['default'].createElement(
                      'a',
                      { rel: 'noopener', href: row.href, target: '_blank' },
                      React__default['default'].createElement('img', { style: { width: '100%', borderRadius: '0 0 0 10%', marginBottom: '20px', borderTop: '1px solid #EEE' }, src: row.thumbnail })
                    )
                  ),
                  React__default['default'].createElement(
                    reactBootstrap.Col,
                    { xs: 9, sm: 8, md: 8, lg: 8, xl: 8, style: { paddingTop: '10px', marginBottom: '20px', borderTop: '1px solid #EEE' } },
                    React__default['default'].createElement(
                      'a',
                      { rel: 'noopener', href: row.href, target: '_blank' },
                      React__default['default'].createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                      React__default['default'].createElement(
                        'p',
                        { className: 'mb-2' },
                        row.date
                      ),
                      React__default['default'].createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                    )
                  )
                )
              ) : React__default['default'].createElement(
                reactBootstrap.Row,
                { style: { margin: '0', padding: '0' } },
                React__default['default'].createElement(
                  reactBootstrap.Col,
                  { xs: 9, sm: 8, lg: 8, xl: 8 },
                  React__default['default'].createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default['default'].createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                    React__default['default'].createElement(
                      'p',
                      null,
                      row.date
                    ),
                    React__default['default'].createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                  )
                ),
                React__default['default'].createElement(
                  reactBootstrap.Col,
                  { xs: 3, sm: 4, lg: 4, xl: 4 },
                  React__default['default'].createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default['default'].createElement('img', { style: { width: '100%', borderRadius: '0 0 10% 0' }, src: row.thumbnail && urlFor(row.thumbnail.asset).url() })
                  )
                )
              )
            ),
            main.main_43 && rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && React__default['default'].createElement(
              'div',
              { style: { margin: '0 auto' } },
              renderMobileAd(index, numberOfItemsBeforeAd)
            )
          );
        })
      )
    );
  };

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

  var renderManualPagination = function renderManualPagination() {
    var currentPage = 1;
    return React__default['default'].createElement(
      'div',
      { className: 'd-flex justify-content-between' },
      currentPage > 1 ,
      React__default['default'].createElement(
        'a',
        { href: '?page=' + (currentPage + 1) },
        'Next >>'
      )
    );
  };

  if (isLoading) {
    return React__default['default'].createElement(
      'div',
      { style: { display: 'flex', justifyContent: 'center', marginTop: '48px' } },
      React__default['default'].createElement(
        reactBootstrap.Spinner,
        { animation: 'border', role: 'status' },
        React__default['default'].createElement(
          'span',
          { className: 'sr-only' },
          'Loading...'
        )
      )
    );
  }

  if (data.length > 0) {
    return React__default['default'].createElement(
      'div',
      { className: 'contentDeck' },
      autoScroll ? React__default['default'].createElement(
        React__default['default'].Fragment,
        null,
        React__default['default'].createElement(
          'style',
          { jsx: true },
          '\n                .infinite-scroll-component {\n                  overflow: hidden !important;\n                }\n              '
        ),
        React__default['default'].createElement(
          index_es.InfiniteScroll,
          {
            dataLength: data.length,
            next: loadMore,
            hasMore: scrolling,
            scrollThreshold: 0.9,
            loader: React__default['default'].createElement(
              'div',
              { style: { textAlign: 'center' } },
              React__default['default'].createElement(
                reactBootstrap.Spinner,
                { animation: 'border', role: 'status' },
                React__default['default'].createElement(
                  'span',
                  { className: 'sr-only' },
                  'Loading...'
                )
              )
            ),
            endMessage: React__default['default'].createElement(
              'p',
              { style: { textAlign: 'center' } },
              React__default['default'].createElement(
                'b',
                null,
                'Yay! You have seen it all'
              )
            ) },
          React__default['default'].createElement(
            reactBootstrap.Container,
            null,
            cardLoader()
          )
        ),
        React__default['default'].createElement(
          'noscript',
          null,
          renderManualPagination()
        )
      ) : React__default['default'].createElement(
        React__default['default'].Fragment,
        null,
        React__default['default'].createElement(
          reactBootstrap.Container,
          null,
          cardLoader()
        ),
        React__default['default'].createElement(
          'div',
          { style: { padding: '0px 10px' } },
          scrolling ? React__default['default'].createElement(
            'button',
            {
              style: { margin: 'auto', width: '100%' },
              onClick: function onClick(e) {
                loadMore();
              } },
            'Load More'
          ) : React__default['default'].createElement(
            'p',
            { style: { textAlign: 'center' } },
            React__default['default'].createElement(
              'b',
              null,
              'End of data'
            )
          )
        ),
        React__default['default'].createElement(
          'noscript',
          null,
          renderManualPagination()
        )
      )
    );
  } else {
    return React__default['default'].createElement(
      'div',
      null,
      React__default['default'].createElement(
        'div',
        null,
        'No data found '
      )
    );
  }
};

module.exports = CMEDeck;
