import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-86d4db69.js';
import './_library-528f1934.js';
import './_iter-detect-130ee549.js';
import { _ as _toConsumableArray } from './toConsumableArray-32282905.js';
import './web.dom.iterable-f8f967cd.js';
import React, { useState, useRef, useEffect } from 'react';
import { l as lib_3 } from './index-1819118a.js';
import 'prop-types';
import { useRouter } from 'next/router';
import './isSymbol-1981418f.js';
import { d as debounce_1 } from './debounce-9207d8ee.js';
import './toNumber-2f7a84cd.js';
import { I as InfiniteScroll } from './index.es-c6222053.js';
import 'react-dom';
import { V as VisibilitySensor } from './visibility-sensor-f40c2564.js';
import { _ as _slicedToArray } from './slicedToArray-67a08c9c.js';
import { m as main_40 } from './main-43ca42fe.js';
import { _ as _JSON$stringify } from './stringify-70b72959.js';
import { _ as _asyncToGenerator, r as regenerator } from './asyncToGenerator-64812e90.js';
import { Spinner, Container, Row, Col } from 'react-bootstrap';

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

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

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

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

export default CMEDeck;
