import { _ as _asyncToGenerator, r as regenerator } from './asyncToGenerator-1ebeb135.js';
import { _ as _toConsumableArray } from './toConsumableArray-e6f28e5c.js';
import { _ as _JSON$stringify } from './stringify-1e2a5946.js';
import { _ as _slicedToArray } from './slicedToArray-72ed566b.js';
import React__default, { useState, useRef, useEffect } from 'react';
import { Spinner, Container, Row, Col } from 'react-bootstrap';
import { I as InfiniteScroll } from './index.es-a6137319.js';
import { V as VisibilitySensor } from './visibility-sensor-72fd8f8b.js';
import { m as main_43 } from './main-dde1592e.js';
import { d as debounce_1 } from './debounce-533d9748.js';
import { useRouter } from 'next/router';
import { l as lib_3 } from './index-5cc7b406.js';
import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-95db387d.js';
import './web.dom.iterable-3fffc027.js';
import './_library-528f1934.js';
import './_set-species-7d3317b7.js';
import './_iter-detect-2f89237f.js';
import 'react-dom';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import 'prop-types';

var itemsPerPage = 12;

var CMEDeck = function CMEDeck(_ref) {
  var getData = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(params) {
      var response, newData;
      return 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: _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(prevData), _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 = useRouter();

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

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

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

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

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

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


  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) {
        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_1(function () {
    setFrom(function (prevFrom) {
      return prevFrom + itemsPerPage;
    });
    setCurrentPage(function (prevCurrentPage) {
      return prevCurrentPage + 1;
    });
  }, 0);

  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.createElement(
      'div',
      { id: 'ceToggles' },
      React__default.createElement(
        'div',
        { style: { width: 'max-content', padding: '0.5rem' } },
        React__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.createElement(
          'p',
          { style: { margin: '0', fontWeight: '700', width: '100%', textAlign: 'center', fontSize: '1rem' } },
          'Physician Education'
        )
      ),
      React__default.createElement(
        Row,
        null,
        data && data.map(function (row, index) {
          var pageNumber = row.pageNumber || 1;
          return React__default.createElement(
            React__default.Fragment,
            { key: index },
            React__default.createElement(
              VisibilitySensor,
              {
                onChange: function onChange(isVisible) {
                  isVisible && changePageNumber(pageNumber);
                } },
              variant === 'left' ? React__default.createElement(
                Col,
                { xl: 12, style: { marginBottom: '1rem' } },
                React__default.createElement(
                  Row,
                  null,
                  React__default.createElement(
                    Col,
                    { xs: 3, sm: 4, md: 4, lg: 4, xl: 4, style: { padding: '0' } },
                    React__default.createElement(
                      'a',
                      { rel: 'noopener', href: row.href, target: '_blank' },
                      React__default.createElement('img', { style: { width: '100%', borderRadius: '0 0 0 10%', marginBottom: '20px', borderTop: '1px solid #EEE' }, src: row.thumbnail })
                    )
                  ),
                  React__default.createElement(
                    Col,
                    { xs: 9, sm: 8, md: 8, lg: 8, xl: 8, style: { paddingTop: '10px', marginBottom: '20px', borderTop: '1px solid #EEE' } },
                    React__default.createElement(
                      'a',
                      { rel: 'noopener', href: row.href, target: '_blank' },
                      React__default.createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                      React__default.createElement(
                        'p',
                        { className: 'mb-2' },
                        row.date
                      ),
                      React__default.createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                    )
                  )
                )
              ) : React__default.createElement(
                Row,
                { style: { margin: '0', padding: '0' } },
                React__default.createElement(
                  Col,
                  { xs: 9, sm: 8, lg: 8, xl: 8 },
                  React__default.createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default.createElement('h4', { className: 'mb-1', style: { fontWeight: '500', fontSize: '22px' }, dangerouslySetInnerHTML: { __html: row.title } }),
                    React__default.createElement(
                      'p',
                      null,
                      row.date
                    ),
                    React__default.createElement('p', { dangerouslySetInnerHTML: { __html: row.intro } })
                  )
                ),
                React__default.createElement(
                  Col,
                  { xs: 3, sm: 4, lg: 4, xl: 4 },
                  React__default.createElement(
                    'a',
                    { rel: 'noopener', href: row.href, target: '_blank' },
                    React__default.createElement('img', { style: { width: '100%', borderRadius: '0 0 10% 0' }, src: row.thumbnail && urlFor(row.thumbnail.asset).url() })
                  )
                )
              )
            ),
            main_43 && rightItems && (index + 1) % numberOfItemsBeforeAd === 0 && React__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.createElement(
      Col,
      { md: 12, style: { display: 'flex', flex: '1 0 auto' } },
      rightItems[i].component
    );
  };

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

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

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

export { CMEDeck as default };
