import './_commonjsHelpers-0c4b6f40.js';
import './_to-object-ded78eb9.js';
import './es6.string.iterator-9b2af4a5.js';
import './_library-528f1934.js';
import './_iter-detect-59409a32.js';
import { _ as _toConsumableArray } from './toConsumableArray-725434a0.js';
import './core.get-iterator-method-54d2e411.js';
import './_object-pie-71ac75a4.js';
import { _ as _extends, a as _Object$assign } from './extends-cc5da797.js';
import './_object-sap-4d59d5bd.js';
import './inherits-7ee3e0c1.js';
import './define-property-de3fc946.js';
import './web.dom.iterable-8956f9a5.js';
import { _ as _typeof } from './typeof-08f2c380.js';
import './_is-array-49698029.js';
import React__default, { useState, useRef, useEffect } from 'react';
import { l as lib_3 } from './index-0e45a0b2.js';
import 'prop-types';
import 'react-bootstrap/Row';
import 'react-bootstrap/Col';
import { m as moment } from './moment-e2f9b20c.js';
import { useRouter } from 'next/router';
import './isSymbol-807e927e.js';
import './debounce-1a993acf.js';
import { I as InfiniteScroll } from './index.es-29c1cef5.js';
import 'react-dom';
import './index-73819142.js';
import './index-5f9f807a.js';
import { m as main_36 } from './main-5d1e4bd3.js';
import './entities-7cc3bf45.js';
import { _ as _JSON$stringify } from './stringify-008c8802.js';
import { a as _getIterator, _ as _slicedToArray } from './slicedToArray-7021e5df.js';
import { a as _asyncToGenerator, r as regenerator } from './asyncToGenerator-7c654f36.js';
import './_set-species-cede29f8.js';
import './Segment.js';
import './Beam.js';
import DFPAdSlot from './AdSlot.js';
import { B as BlockContent } from './BlockContent-e9b4ddcf.js';
import './smoothscroll-4b699764.js';
import './GroupDeck.js';
import 'react-bootstrap';
import './iconBase-602d52fe.js';
import Button from 'react-bootstrap/Button';
import { _ as _defineProperty } from './defineProperty-b798470d.js';
import Form from 'react-bootstrap/Form';
import { I as InscreenSensor, r as renderAuthor, g as getSerializers } from './index-4af8180e.js';
import './util-7700fc59.js';
import './brightcove-react-player-loader.es-83f53e4e.js';
import 'react-bootstrap/Pagination';
import Head from 'next/head';
import 'react-share';
import SocialShare from './SocialShare.js';
import FormControl from 'react-bootstrap/FormControl';
import { _ as _Object$keys } from './keys-fc2d4c34.js';
import 'react-bootstrap/Dropdown';
import { b as FaMinus, c as FaPlus } from './index.esm-cf08bf18.js';
import getSeriesDetail from './getSeriesDetail.js';
import './index-db3bb315.js';
import getRelatedArticle from './getRelatedArticle.js';
import getQuery from './getQuery.js';
import { g as getTargeting, a as getContentPlacementUrl } from './getTargeting-2acdec91.js';
import getKeywords from './getKeywords.js';
import urlFor from './urlFor.js';
import { s as styleInject } from './style-inject.es-1f59c1d0.js';

var getArticleSummary = function getArticleSummary(article) {
  if (article.summary && article.summary.length > 0) {
    return article.summary;
  } else {
    return false;
  }
};

var getDocumentGroupUrl = function getDocumentGroupUrl(docGroup) {
  if (!docGroup) {
    return null;
  }
  var url = void 0;
  if (docGroup.path && docGroup.path.includes('/')) {
    return "/" + docGroup.path;
  }

  if (docGroup.parent) {
    url = '/' + docGroup.parent.identifier.current;
    if (docGroup.parent.parent && docGroup.parent.parent.name) {
      url = '/' + docGroup.parent.parent.identifier.current + url;
    }
  }

  if (!docGroup.thumbnail) ;
  url = url + '/' + docGroup.path;

  return url;
};

var getDocumentGroupName = function getDocumentGroupName(docGroup) {
  var name = void 0;
  if (!docGroup) {
    return null;
  }

  if (docGroup.parent) {
    name = docGroup.parent.name;

    if (docGroup.parent.parent && docGroup.parent.parent.name) {
      name = docGroup.parent.parent.name + ' | ' + name;
    }
  }

  //if (!docGroup.thumbnail) {
  name = name + ' | <b>' + docGroup.name + '</b>';
  //}

  return name;
};

var DocumentGroup = function DocumentGroup(_ref) {
  var article = _ref.article,
      client = _ref.client;

  if (!article.documentGroup) {
    return null;
  }

  var name = getDocumentGroupName(article.documentGroup);
  var url = getDocumentGroupUrl(article.documentGroup);
  var thumbnailUrl = false;

  if (article.documentGroup.thumbnail) {
    thumbnailUrl = urlFor(client, article.documentGroup.thumbnail).url();
  }

  return React__default.createElement(
    'a',
    {
      href: url,
      className: 'doc-group',
      style: { display: 'flex', flexDirection: 'column', padding: '0 1rem', justifyContent: thumbnailUrl ? 'center' : 'flex-start', alignItems: 'center' } },
    thumbnailUrl && React__default.createElement('img', { style: { maxWidth: '220px', maxHeight: '100px', marginTop: '1rem' }, src: thumbnailUrl, alt: name }),
    !thumbnailUrl && React__default.createElement('p', {
      style: { maxWidth: '315px', margin: '0', color: 'var(--primary)', textAlign: thumbnailUrl ? 'center' : main_36 ? 'left' : 'right', marginTop: '.25rem' },
      dangerouslySetInnerHTML: { __html: name } }),
    main_36 && !thumbnailUrl && React__default.createElement(
      'style',
      { jsx: 'true' },
      '\n          a.doc-group {\n            display: block !important;\n            padding: 0!important;\n          }\n        '
    )
  );
};

var findIndex = function findIndex(arr) {
  var indexes = [];
  if ((typeof arr === 'undefined' ? 'undefined' : _typeof(arr)) === 'object') {
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = _getIterator(arr), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var ele = _step.value;

        if (ele['_type'] === 'block' && ele.children.some(function (child) {
          return child.text.trim().length > 0;
        }) && ele['listItem'] !== 'bullet' &&
        //  To skip li tags when setting contextual native ads
        ele['listItem'] !== 'number' && ele['style'] === 'normal' || ele['_type'] === 'figure') {
          indexes.push(arr.indexOf(ele));
        }
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }
  }
  return indexes;
};

var ISI = function ISI(props) {
  var children = props.children;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      active = _useState2[0],
      setActive = _useState2[1];

  var isi = useRef();
  useEffect(function () {
    if (active) {
      var offset = '5rem';
      var nav = document.getElementsByTagName('header');
      if (nav && nav.length > 0) {
        offset = nav[0].offsetHeight + 'px';
      }
      isi.current.style.maxHeight = 'calc(100% - ' + offset + ')';
      isi.current.style.overflowY = 'scroll';
    } else {
      isi.current.style.maxHeight = '';
      isi.current.style.overflowY = '';
    }
  }, [active]);
  return React__default.createElement(
    React__default.Fragment,
    null,
    React__default.createElement(
      'div',
      { id: 'isi', ref: isi },
      React__default.createElement(
        'div',
        { id: 'isiContent' },
        React__default.createElement(
          'div',
          { onClick: function onClick() {
              return setActive(function (prev) {
                return !prev;
              });
            }, id: 'isiToggle' },
          active ? React__default.createElement(
            'p',
            null,
            'Close ',
            React__default.createElement(FaMinus, null)
          ) : React__default.createElement(
            'p',
            null,
            'See More ',
            React__default.createElement(FaPlus, null)
          )
        ),
        children
      )
    ),
    React__default.createElement(
      'style',
      { jsx: true },
      '\n        #isi {\n          position: fixed;\n          z-index: 99999;\n          bottom: 0;\n          left: 0;\n          max-height: 10rem;\n          background-color: #ffffff;\n          overflow-x: hidden;\n          overflow-y: hidden;\n          transition: max-height 0.2s;\n          width: 100%;\n          box-shadow: 0 0 1rem 0 rgba(0, 0, 0, 0.5);\n        }\n        #isiContent {\n          width: 100%;\n          max-width: 1000px;\n          margin-left: auto;\n          margin-right: auto;\n          position: relative;\n          padding: 1rem;\n          font-size: 1rem;\n        }\n        #isi::-webkit-scrollbar {\n          display: none;\n        }\n        #isiToggle {\n          position: absolute;\n          top: 0;\n          right: 0;\n          padding: 1rem;\n          font-weight: bold;\n          cursor: pointer;\n          font-size: 1rem;\n        }\n        #isiToggle p {\n          margin: 0;\n        }\n      '
    )
  );
};

var css = ".RelatedArticles-module_mediaContainer__10h9k {\r\n  display: flex;\r\n  flex-direction: row;\r\n  flex-wrap: nowrap;\r\n  margin: 0 -1rem;\r\n}\r\n.RelatedArticles-module_mediaCard__3wQbn {\r\n  margin: 0 1rem 1rem;\r\n  width: calc(33% - 1rem);\r\n  display: column;\r\n  flex-direction: row;\r\n  margin-bottom: 0.75rem;\r\n  padding-bottom: 0.75rem;\r\n  border-bottom: none;\r\n}\r\n.RelatedArticles-module_mediaCard__3wQbn:last-child {\r\n  border-bottom: none;\r\n}\r\n.RelatedArticles-module_cardTitle__3P-Ib {\r\n  font-weight: bold;\r\n  color: #252525;\r\n  margin-bottom: 0.25rem;\r\n  font-size: 15px;\r\n}\r\n.RelatedArticles-module_authorListing__1EFg4 span.RelatedArticles-module_text-muted__3b0zX {\r\n  color: #000;\r\n  font-weight: bold;\r\n}\r\n.RelatedArticles-module_cardDate__1wOR5 {\r\n  color: var(--dark);\r\n  display: block;\r\n  background: #fff !important;\r\n  margin-bottom: 0;\r\n}\r\n.RelatedArticles-module_imgWrapper__5Jx_4 {\r\n  display: block;\r\n  text-align: center;\r\n  margin-bottom: 0.5rem;\r\n}\r\n.RelatedArticles-module_imgWrapper__5Jx_4 img {\r\n  height: 135px;\r\n  width: 100%;\r\n  object-fit: cover;\r\n  object-position: center;\r\n}\r\n@media screen and (max-width: 1064px) {\r\n}\r\n@media screen and (max-width: 968px) {\r\n  .RelatedArticles-module_mediaContainer__10h9k {\r\n    flex-wrap: wrap;\r\n  }\r\n  .RelatedArticles-module_mediaCard__3wQbn {\r\n    width: 100%;\r\n  }\r\n  .RelatedArticles-module_imgWrapper__5Jx_4 img {\r\n    width: 100%;\r\n    height: auto;\r\n\r\n    max-height: 175px;\r\n    object-fit: contain;\r\n    margin-bottom: 1rem;\r\n  }\r\n}\r\n";
var styles = { "mediaContainer": "RelatedArticles-module_mediaContainer__10h9k", "mediaCard": "RelatedArticles-module_mediaCard__3wQbn", "cardTitle": "RelatedArticles-module_cardTitle__3P-Ib", "authorListing": "RelatedArticles-module_authorListing__1EFg4", "text-muted": "RelatedArticles-module_text-muted__3b0zX", "cardDate": "RelatedArticles-module_cardDate__1wOR5", "imgWrapper": "RelatedArticles-module_imgWrapper__5Jx_4" };
styleInject(css);

var RelatedArticle = function RelatedArticle(_ref) {
  var articles = _ref.articles,
      client = _ref.client;

  if (!articles || articles.length == 0 || !articles[0]) {
    return null;
  }
  return React__default.createElement(
    'div',
    { className: styles.mediaContainer },
    articles.map(function (article, index) {
      return React__default.createElement(
        'div',
        { id: 'related-card', key: index, className: styles.mediaCard },
        React__default.createElement(
          'a',
          { className: styles.imgWrapper, href: '/view/' + (article.url ? article.url.current : '') },
          article.thumbnail && React__default.createElement('img', {
            style: { objectFit: 'cover', objectPosition: 'center' },
            src: article.thumbnail && urlFor(client, article.thumbnail.asset).width(250).url(),
            alt: article.title
          })
        ),
        React__default.createElement(
          'div',
          { className: styles.mediaBody },
          React__default.createElement(
            'a',
            { href: '/view/' + (article.url ? article.url.current : '') },
            React__default.createElement(
              'h4',
              { className: styles.cardTitle },
              article.title
            )
          )
        )
      );
    })
  );
};

var Article = function Article(props) {
  var onVote = function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(nodeKey, selectedChoice) {
      var response, result;
      return regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _context.next = 2;
              return fetch('/api/polls/vote', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: _JSON$stringify({ articleId: props.article._id, nodeKey: nodeKey, selectedChoice: selectedChoice, body: articleBody })
              });

            case 2:
              response = _context.sent;

              if (!response.ok) {
                _context.next = 11;
                break;
              }

              _context.next = 6;
              return response.json();

            case 6:
              result = _context.sent;

              setArticleBody(result.body);

              console.log('Voted successfully');
              _context.next = 12;
              break;

            case 11:
              console.log('Unable to vote!');

            case 12:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    return function onVote(_x, _x2) {
      return _ref.apply(this, arguments);
    };
  }();

  var article = props.article,
      Ads = props.Ads,
      showRelatedArticles = props.showRelatedArticles,
      _props$hideFBShare = props.hideFBShare,
      hideFBShare = _props$hideFBShare === undefined ? false : _props$hideFBShare,
      _props$hidePinterestS = props.hidePinterestShare,
      hidePinterestShare = _props$hidePinterestS === undefined ? false : _props$hidePinterestS;
  var client = props.client,
      pageview = props.pageview,
      videoAccountIDs = props.videoAccountIDs,
      drupalLeadSettings = props.drupalLeadSettings,
      currentPage = props.currentPage,
      _props$article = props.article,
      title = _props$article.title,
      _props$article$passwo = _props$article.passwordLock,
      passwordLock = _props$article$passwo === undefined ? false : _props$article$passwo,
      authorDetails = _props$article.authorDetails,
      pageNumber = _props$article.pageNumber,
      published = _props$article.published,
      _props$article$showPu = _props$article.showPublished,
      showPublished = _props$article$showPu === undefined ? true : _props$article$showPu,
      body = _props$article.body,
      thumbnail = _props$article.thumbnail,
      content_placement = _props$article.content_placement,
      _props$article$url = _props$article.url;
  _props$article$url = _props$article$url === undefined ? {
    current: ''
  } : _props$article$url;
  var url = _props$article$url.current,
      issue = _props$article.issue,
      source = _props$article.source,
      documentGroupMapping = _props$article.documentGroupMapping,
      showIsi = _props$article.showIsi,
      isi = _props$article.isi,
      regionalPages = props.regionalPages,
      nationalPage = props.nationalPage,
      ISIContent = props.ISIContent,
      shareOptions = props.shareOptions,
      cpModificationRequired = props.cpModificationRequired,
      authorPrefix = props.authorPrefix,
      _props$lgContextAd = props.lgContextAd,
      lgContextAd = _props$lgContextAd === undefined ? false : _props$lgContextAd,
      queueData = props.queueData,
      _props$sponsoredFlag = props.sponsoredFlag,
      sponsoredFlag = _props$sponsoredFlag === undefined ? false : _props$sponsoredFlag,
      _props$authorImgHeigh = props.authorImgHeight,
      authorImgHeight = _props$authorImgHeigh === undefined ? 270 : _props$authorImgHeigh;

  var targeting = getTargeting(props);
  var onChangeArticle = props.onChangeArticle;

  //If sponsored flag, disable contextual ads

  if (sponsoredFlag) {
    article.contextualVideoAD = false;
    article.contextualAD = false;
    showRelatedArticles = false;
  }
  if (article.disableRelatedContent) {
    showRelatedArticles = false;
  }
  //This was being done in ArticleQueue2 which wasnt effecting articles excluded from infinite scroll, moved inside article component
  if (!sponsoredFlag && Ads.getVideoContextualAD) {
    article.contextualVideoAD = Ads.getVideoContextualAD(getTargeting(props, 'in-context_video'));
  }
  if (!sponsoredFlag && Ads.getNativeContextualAD) {
    article.contextualAD = Ads.getNativeContextualAD(getTargeting(props, 'native-ad'));
  }

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      contextualADFlag = _useState2[0],
      setContextualADFlag = _useState2[1];
  //  Setting new Flag 'visibleFlag' to know when the article is visible so that new contextual ad can be appended into DOM.


  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      visibleFlag = _useState4[0],
      setVisibleFlag = _useState4[1];

  var summary = getArticleSummary(props.article);

  var _useState5 = useState(1),
      _useState6 = _slicedToArray(_useState5, 2),
      auth = _useState6[0],
      setAuth = _useState6[1];

  var _useState7 = useState(''),
      _useState8 = _slicedToArray(_useState7, 2),
      passwordKey = _useState8[0],
      setPasswordKey = _useState8[1];

  var _useState9 = useState(body),
      _useState10 = _slicedToArray(_useState9, 2),
      articleBody = _useState10[0],
      setArticleBody = _useState10[1];

  var _useState11 = useState(true),
      _useState12 = _slicedToArray(_useState11, 2),
      previewAd = _useState12[0],
      setPreviewAd = _useState12[1];

  useEffect(function () {
    var path = window && window.location && window.location.search;
    // Setting flag for Ad-preview URLs
    setPreviewAd(path.split('&').some(function (param) {
      return param.includes('creativeId');
    }));
  }, []);

  var isCutomPage = function isCutomPage(article) {
    var url = article.url.current;

    if (regionalPages || nationalPage) {
      return regionalPages.includes(url) || nationalPage === url;
    } else {
      return false;
    }
  };
  var renderAuthorBiography = function renderAuthorBiography(biography) {
    if (biography) {
      return React__default.createElement(BlockContent, _extends({
        serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, contextualADFlag),
        blocks: [biography]
      }, client.config()));
    }
  };
  var renderIsiContent = function renderIsiContent(article) {
    var url = article.url.current;

    if (regionalPages && ISIContent && regionalPages.includes(url)) {
      return React__default.createElement(ISIContent, null);
    } else if (nationalPage === url && ISIContent) {
      return React__default.createElement(ISIContent, { national: true });
    }
    return null;
  };

  var RelevantTopics = function RelevantTopics() {
    if (content_placement && content_placement.length > 0 || documentGroupMapping) {
      return React__default.createElement(
        'div',
        { style: { color: '#262626' } },
        React__default.createElement(
          'p',
          { className: 'mb-0' },
          React__default.createElement(
            'b',
            null,
            'Related Content:'
          )
        ),
        documentGroupMapping && documentGroupMapping.map(function (documentGroup) {
          if (!documentGroup.parent) {
            return null;
          }

          return React__default.createElement(
            React__default.Fragment,
            null,
            React__default.createElement(
              'span',
              { className: '' },
              React__default.createElement(
                'a',
                {
                  className: 'related-links',
                  style: { color: 'blue' },
                  href: cpModificationRequired ? '/' + documentGroup.parent.identifier.current + '/' + documentGroup.path : '/' + documentGroup.path },
                documentGroup.name
              )
            ),
            content_placement && content_placement.length ? ' | ' : null
          );
        }),
        content_placement && content_placement.length > 0 ? content_placement.map(function (cp, index) {
          var cp_url = cpModificationRequired ? getContentPlacementUrl(cp) : cp.path;
          var href = '/' + cp_url;
          return React__default.createElement(
            React__default.Fragment,
            { key: index },
            React__default.createElement(
              'span',
              null,
              React__default.createElement(
                'a',
                { className: 'related-links', key: index, href: href, style: { color: 'blue' } },
                cp.name
              )
            ),
            content_placement.length > index + 1 ? ' | ' : null
          );
        }) : null
      );
    }
    return null;
  };

  var form = function form() {
    return React__default.createElement(
      React__default.Fragment,
      null,
      React__default.createElement(
        Head,
        null,
        React__default.createElement('meta', { name: 'googlebot', content: 'noindex' })
      ),
      React__default.createElement(
        'div',
        { className: 'mt-5', style: { display: 'flex', justifyContent: 'center', alignItems: 'center' } },
        React__default.createElement(
          Form,
          {
            inline: true,
            onSubmit: function onSubmit(e) {
              e.preventDefault();
            } },
          React__default.createElement(FormControl, { type: 'text', className: 'mr-sm-2', value: passwordKey, onChange: function onChange(e) {
              return setPasswordKey(e.target.value);
            }, placeholder: 'Password' }),
          React__default.createElement(
            Button,
            {
              variant: 'primary',
              onClick: function onClick() {
                if (passwordKey === props.article.password) {
                  setAuth(2);
                } else {
                  alert('Incorrect Password');
                }
              } },
            'Submit'
          )
        )
      )
    );
  };

  var renderBlockContent = function renderBlockContent(payload) {
    var _payload = payload,
        body = _payload.body;


    var indexes = findIndex(body);

    if (indexes.length >= 2 && body.length > 3 && payload.contextualAD && payload.contextualVideoAD) {
      payload = _extends({}, payload, {
        contextualAD: _extends({}, payload.contextualAD, {
          slotId: (payload.contextualAD.slotId || 'contextual_ad') + '-' + payload._id
        }),
        contextualVideoAD: _extends({}, payload.contextualVideoAD, {
          slotId: (payload.contextualVideoAD.slotId || 'in-context_video') + '-' + payload._id
        })
      });
      var selectedIndex = indexes[1] + 1;

      var checkIsAdFound = function checkIsAdFound(isFound) {
        if (!isFound) {
          var parent = document.getElementById('contextual-native-ad-' + payload._id);
          parent.style.height = '0%';
          parent.style.width = '0%';
          parent.style.display = 'none';
          setContextualADFlag(false);
        } else {
          if (body[0]._type === 'figure' || body[1]._type === 'figure' || body[2]._type === 'figure' || body[3]._type === 'figure') {
            setContextualADFlag(true);
          }
        }
      };

      var checkIsVideoAdFound = function checkIsVideoAdFound(isFound) {
        if (!isFound) {
          var parent = document.getElementById('contextual-video-ad-' + payload._id);
          parent.style.height = '0%';
          parent.style.width = '0%';
          parent.style.display = 'none';
          setContextualADFlag(false);
        } else {
          setContextualADFlag(true);
        }
      };
      return React__default.createElement(
        React__default.Fragment,
        null,
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, contextualADFlag, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        React__default.createElement('span', { className: 'clearfix' }),
        React__default.createElement(
          'div',
          { id: 'contextual-native-ad-' + payload._id, className: 'contextual-native-ad' },
          React__default.createElement(DFPAdSlot, _extends({}, payload.contextualAD, { refreshFlag: false, checkIsAdFound: previewAd ? null : checkIsAdFound }))
        ),
        React__default.createElement('span', { className: 'clearfix' }),
        React__default.createElement(
          'div',
          { id: 'contextual-video-ad-' + payload._id, className: 'contextual-video-ad' },
          React__default.createElement(DFPAdSlot, _extends({}, payload.contextualVideoAD, { refreshFlag: false, checkIsAdFound: checkIsVideoAdFound }))
        ),
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, null, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config()))
      );
    } else if (indexes.length >= 2 && body.length >= 3 && payload.contextualAD && !payload.contextualVideoAD) {
      payload = _extends({}, payload, {
        contextualAD: _extends({}, payload.contextualAD, {
          slotId: (payload.contextualAD.slotId || 'contextual_ad') + '-' + payload._id,
          className: 'ADFluid',
          //  Fetching new contextual targeting based on the current active article.
          targeting: getTargeting(props, 'native-ad'),
          // Adding new ad size for large contextual ad for desktop screen width >= 1400
          sizes: lgContextAd ? [[728, 90], 'fluid', [300, 100]] : ['fluid', [300, 100]],
          sizeMapping: lgContextAd ? [{
            viewport: [1400, 0],
            sizes: [[728, 90], 'fluid', [300, 100]]
          }, { viewport: [0, 0], sizes: ['fluid', [300, 100]] }] : { viewport: [0, 0], sizes: ['fluid', [300, 100]] }
        })
      });
      var _selectedIndex = indexes[1] + 1;

      var _checkIsAdFound = function _checkIsAdFound(isFound, adData) {
        if (!isFound) {
          var parent = document.getElementById('contextual-native-ad-' + payload._id);
          parent.style.height = '0%';
          parent.style.width = '0%';
          parent.style.display = 'none';
          setContextualADFlag(false);
        } else {
          var _parent = document.getElementById('contextual-native-ad-' + payload._id);
          if (adData && adData.event && adData.event.size && _parent) {
            // Adding fix for fluid contextual ad to avoid from collapsing when size is [0,0]
            var fluidSizes = [[0, 0]];
            var checkAdSize = function checkAdSize(size) {
              return _JSON$stringify(size) === _JSON$stringify(adData.event.size);
            };
            if (!fluidSizes.some(checkAdSize)) {
              _parent.style.width = adData.event.size[0] + 'px';
              _parent.style.height = adData.event.size[1] + 'px';
            }
            _parent.style.margin = 'auto';
            //  Adding margin below to create a seperation from text.
            _parent.style.marginBottom = '15px';
          }
          if (body[0]._type === 'figure' || body[1]._type === 'figure' || body[2]._type === 'figure' || body[3]._type === 'figure') {
            setContextualADFlag(true);
          }
        }
      };

      return React__default.createElement(
        React__default.Fragment,
        null,
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, contextualADFlag, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, _selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        contextualADFlag && React__default.createElement('span', { className: 'clearfix' }),
        (visibleFlag || queueData && queueData.length === 1 || !props.infiniteScroll) && React__default.createElement(
          'div',
          { id: 'contextual-native-ad-' + payload._id, className: 'contextual-native-ad' },
          React__default.createElement(DFPAdSlot, _extends({}, payload.contextualAD, { refreshFlag: false, checkIsAdFound: previewAd ? null : _checkIsAdFound }))
        ),
        contextualADFlag && React__default.createElement('span', { className: 'clearfix' }),
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, null, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(_selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config()))
      );
    } else if (indexes.length >= 2 && body.length > 3 && payload.contextualVideoAD && !payload.contextualAD) {
      payload = _extends({}, payload, {
        contextualVideoAD: _extends({}, payload.contextualVideoAD, {
          slotId: (payload.contextualVideoAD.slotId || 'in-context_video') + '-' + payload._id
        })
      });
      var _selectedIndex2 = indexes[1] + 1;

      var _checkIsAdFound2 = function _checkIsAdFound2(isFound) {
        if (!isFound) {
          var parent = document.getElementById('contextual-video-ad-' + payload._id);
          parent.style.height = '0%';
          parent.style.width = '0%';
          parent.style.display = 'none';
          setContextualADFlag(false);
        } else {
          if (body && body[1] && body[1]._type === 'figure') {
            setContextualADFlag(true);
          }
        }
      };

      return React__default.createElement(
        React__default.Fragment,
        null,
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, contextualADFlag, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, _selectedIndex2))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        React__default.createElement('span', { className: 'clearfix' }),
        React__default.createElement(
          'div',
          { id: 'contextual-video-ad-' + payload._id, className: 'contextual-video-ad' },
          React__default.createElement(DFPAdSlot, _extends({}, payload.contextualVideoAD, { refreshFlag: false, checkIsAdFound: _checkIsAdFound2 }))
        ),
        React__default.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, null, null, null, targeting),
          blocks: [].concat(_toConsumableArray(articleBody.slice(_selectedIndex2))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config()))
      );
    } else {
      return React__default.createElement(BlockContent, _extends({
        serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, false, null, props.article.Ads, targeting),
        blocks: articleBody,
        imageOptions: { w: 320, h: 240, fit: 'max' }
      }, client.config()));
    }
  };

  var detail = function detail() {
    var shareVia = shareOptions.shareVia,
        shareSubject = shareOptions.shareSubject,
        twitterSiteName = shareOptions.twitterSiteName,
        shareImageDefault = shareOptions.shareImageDefault,
        shareBaseUrl = shareOptions.shareBaseUrl,
        shareSiteTitle = shareOptions.shareSiteTitle;

    var shareUrl = shareBaseUrl + props.article.url.current;
    var shareTitle = article.title;
    var shareSummary = article.summary;
    var shareImage = thumbnail && thumbnail.asset ? urlFor(props.client, thumbnail.asset).url() : shareImageDefault;
    var siteName = props.website && props.website.title ? props.website.title : '';
    var shareKeywords = getKeywords(props.article).join(',');

    var meta = {
      shareTitle: shareTitle,
      shareSiteName: props.cache.siteSettingCache.name,
      shareSummary: shareSummary,
      shareUrl: shareUrl,
      shareImage: shareImage,
      shareVia: props.Settings.title,
      shareKeywords: shareKeywords
    };
    if (!props.infiniteScroll) {
      onChangeArticle = function onChangeArticle() {
        return null;
      };
    }

    return React__default.createElement(
      React__default.Fragment,
      null,
      React__default.createElement(
        InscreenSensor,
        {
          offSetTop: 120,
          className: 'inscreen-wrapper',
          id: 'article-' + title,
          onChange: function onChange(visible) {
            if (visible === 'top' || visible === 'bottom' || visible === 'small-top') {
              onChangeArticle(url, visible, meta);
              //  Setting 'visibleFlag' to know that the article is visible.
              setVisibleFlag(true);
            }
          } },
        React__default.createElement(
          'div',
          null,
          React__default.createElement(
            'div',
            { className: 'video-detail', style: { marginBottom: isCutomPage(props.article) || showIsi && Array.isArray(isi) && isi.length > 0 ? '15rem' : 0 } },
            React__default.createElement(
              'h1',
              { className: 'page-title', style: { fontSize: '1.9rem' } },
              title
            ),
            React__default.createElement(
              'div',
              { className: 'mb-3 doc-group-container', style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' } },
              React__default.createElement(
                'style',
                { jsx: 'true' },
                '\n                  @media screen and (max-width: 468px) {\n                    .video-detail .doc-group-container {\n                      flex-direction: column;\n                      align-items: flex-start !important;\n                    }\n                    .video-detail .doc-group {\n                      margin-top: 2rem;\n                      width: calc(100vw - 45px);\n                      align-items: center;\n                    }\n                    .video-detail .doc-group img,\n                    .doc-group p {\n                      max-width: calc(100vw - 45px) !important;\n                    }\n                  }\n                  .author-details-img {\n                    margin-right: 10px;\n                    max-height: 250px;\n                    min-height: 150px;\n                    max-width: 250px;\n                    min-width: 150px;\n                    width: 100%;\n                    height: 100%;\n                    object-fit: contain;\n                  }\n                  .author-details-img-container {\n                    text-align: center;\n                  }\n                  .author-details-col {\n                    padding-left: 25px;\n                  }\n                '
              ),
              React__default.createElement(
                'div',
                { className: 'left-wrap' },
                showPublished && React__default.createElement(
                  'div',
                  null,
                  moment(published).format('LL')
                )
                /* Show Published date */
                ,
                React__default.createElement(
                  'div',
                  { className: 'mb-3' },
                  authorDetails && authorDetails.map(function (authorDetail, index) {
                    return React__default.createElement(
                      'span',
                      { key: index },
                      renderAuthor(authorDetail.displayName, authorDetail.url, index, authorDetails.length, authorPrefix, authorDetail.biography && renderAuthorBiography(authorDetail.biography[0]), authorDetail.profileImage && urlFor(props.client, authorDetail.profileImage).height(authorImgHeight).url())
                    );
                  }),
                  React__default.createElement(
                    'div',
                    null,
                    source && React__default.createElement(
                      'p',
                      {
                        style: {
                          display: 'inline-block',
                          padding: '0 .25rem',
                          color: 'var(--franchise-primary, #484848)',
                          borderRadius: '2px',
                          fontWeight: 'bold',
                          border: '2px solid var(--franchise-primary, #484848)'
                        },
                        className: 'source-label' },
                      source
                    )
                  ),
                  issue && React__default.createElement(
                    'div',
                    { className: 'volume-issue' },
                    issue.publication && issue.publication.name && React__default.createElement(
                      'span',
                      { className: 'mb-0' },
                      React__default.createElement(
                        'b',
                        null,
                        issue.publication.name
                      ),
                      ',',
                      ' '
                    ),
                    issue.name && React__default.createElement(
                      'span',
                      { className: 'mb-0' },
                      issue.name,
                      ', '
                    ),
                    issue.volume && React__default.createElement(
                      'span',
                      null,
                      'Volume ' + issue.volume,
                      ','
                    ),
                    issue.issueNumber && React__default.createElement(
                      'span',
                      null,
                      ' Issue ' + issue.issueNumber
                    )
                  ),
                  pageNumber && React__default.createElement(
                    'div',
                    { className: 'article-pageNumber' },
                    'Page Number: ' + pageNumber
                  )
                ),
                React__default.createElement(
                  'p',
                  null,
                  React__default.createElement(SocialShare, {
                    shareUrl: shareUrl,
                    shareTitle: shareTitle,
                    shareVia: shareVia,
                    shareSummary: shareSummary,
                    shareSubject: shareSubject,
                    shareImage: shareImage,
                    size: 32,
                    siteName: siteName,
                    twitterSiteName: twitterSiteName,
                    disableMeta: true,
                    hidePinterest: hidePinterestShare,
                    hideFacebook: hideFBShare
                  })
                )
              ),
              React__default.createElement(
                'div',
                null,
                React__default.createElement(DocumentGroup, { article: props.article, client: props.client })
              )
            ),
            summary && React__default.createElement(
              'p',
              null,
              React__default.createElement(
                'em',
                null,
                summary
              )
            ),
            React__default.createElement(
              'div',
              { className: 'ad-box', style: { textAlign: 'center' } },
              main_36 && !sponsoredFlag && props.article.Ads && props.article.Ads.length > 0 && props.article.Ads.map(function (ad, index) {
                if (index === 0) {
                  return React__default.createElement(
                    'div',
                    {
                      key: index,
                      id: 'addid-' + index,
                      style: {
                        display: 'flex',
                        flex: '1 0 auto',
                        justifyContent: 'center',
                        alignItems: 'center',
                        textAlign: 'center'
                      } },
                    ad.component
                  );
                }
              })
            ),
            React__default.createElement(
              'div',
              { className: 'block-content mt-3' },
              renderBlockContent(article),
              React__default.createElement('div', { className: 'clearfix' }),
              React__default.createElement(
                'noscript',
                null,
                React__default.createElement(
                  'div',
                  { style: { display: 'flex', justifyContent: 'center' }, className: 'series-links' },
                  props.article.seriesDetail && props.article.seriesDetail.prevUrl && React__default.createElement(
                    'a',
                    { className: 'mx-3', href: props.article.seriesDetail.prevUrl },
                    'Previous ',
                    props.article.seriesDetail.type
                  ),
                  props.article.seriesDetail && props.article.seriesDetail.nextUrl && React__default.createElement(
                    'a',
                    { className: 'mx-3', href: props.article.seriesDetail.nextUrl },
                    'Next ',
                    props.article.seriesDetail.type
                  )
                )
              ),
              issue && issue.url && React__default.createElement(
                'a',
                { rel: 'noopener', href: issue.url, target: '_blank', title: 'Download issue' },
                React__default.createElement('img', { style: { margin: '1rem', maxHeight: '40px', maxWidth: '40px' }, src: '/download.png', alt: 'download issue' }),
                'Download Issue : ',
                issue.name
              )
            ),
            React__default.createElement('div', { className: 'clearfix', style: { minHeight: '1px' } }),
            showRelatedArticles && !showIsi && React__default.createElement(
              React__default.Fragment,
              null,
              React__default.createElement(
                'div',
                null,
                React__default.createElement(RelevantTopics, null)
              ),
              React__default.createElement(
                'div',
                { className: 'pt-2' },
                React__default.createElement(RelatedArticle, { articles: article.relatedArticle, client: client })
              )
            )
          ),
          renderIsiContent(props.article)
        ),
        showIsi && Array.isArray(isi) && isi.length > 0 && React__default.createElement(
          ISI,
          null,
          React__default.createElement(BlockContent, {
            serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, false, null, props.article.Ads, targeting),
            blocks: isi
          })
        )
      ),
      main_36 && !sponsoredFlag && props.article.Ads && props.article.Ads.length > 0 && props.article.Ads.map(function (ad, index) {
        if (index > 0) {
          return React__default.createElement(
            'div',
            { key: index, id: 'addid-' + index, style: { display: 'flex', flex: '1 0 auto' } },
            ad.component
          );
        }
      }),
      React__default.createElement(
        'noscript',
        null,
        props.infiniteScroll && props.article.relatedArticle && props.article.relatedArticle[0] && props.article.relatedArticle[0].url && props.article.relatedArticle[0].url.current && React__default.createElement(
          'div',
          { style: { textAlign: 'center' } },
          React__default.createElement(
            'a',
            { href: '/view/' + props.article.relatedArticle[0].url.current },
            'Related Article ',
            '>>>'
          )
        )
      ),
      React__default.createElement('hr', { className: 'article-seperater mb-5 mt-3' })
    );
  };

  if (passwordLock) {
    if (auth === 2) {
      return detail();
    } else {
      return form();
    }
  } else {
    return detail();
  }
};

var _this = undefined;

var ArticleQueue = function ArticleQueue(props) {
  var _props$prevUrl = props.prevUrl,
      prevUrl = _props$prevUrl === undefined ? '/' : _props$prevUrl,
      Ads = props.Ads,
      _props$maxListLength = props.maxListLength,
      maxListLength = _props$maxListLength === undefined ? 10 : _props$maxListLength,
      _props$sponsoredTaxon = props.sponsoredTaxonomies,
      _props$cpModification = props.cpModificationRequired,
      cpModificationRequired = _props$cpModification === undefined ? false : _props$cpModification,
      _props$authorPrefix = props.authorPrefix,
      authorPrefix = _props$authorPrefix === undefined ? 'authors' : _props$authorPrefix,
      showRelatedArticles = props.showRelatedArticles,
      canonicalTag = props.canonicalTag;


  var firstArticle = function firstArticle() {
    var article = _Object$assign({}, props.article);
    var targeting = getTargeting(props);
    article.Ads = Ads.getRightItems(targeting);
    return article;
  };

  var _useState = useState([firstArticle()]),
      _useState2 = _slicedToArray(_useState, 2),
      queueData = _useState2[0],
      setQueueData = _useState2[1];

  var refreshAD = function refreshAD(path) {
    var activeArticle = queueData.find(function (item) {
      return item.url.current === path;
    });
    var targeting = getTargeting({ article: activeArticle, cpModificationRequired: cpModificationRequired, position: props.position, prevUrl: prevUrl });

    if (!main_36) {
      lib_3.getGoogletag().then(function (googletag) {
        if (window.googletag && googletag.pubadsReady) {
          var slots = googletag.pubads().getSlots();
          slots.forEach(function (slot) {
            var pos = slot.getTargeting('pos');

            slot.clearTargeting();
            _Object$keys(targeting).forEach(function (key) {
              slot.setTargeting(key, targeting[key]);
            });
            slot.setTargeting('pos', pos);
          });
          lib_3.refresh();
        }
      });
    }
    //Refresh leaderboard ad on mobile
    if (main_36) {
      var leaderboardSlotId = '';
      lib_3.getGoogletag().then(function (googletag) {
        if (window.googletag && googletag.pubadsReady) {
          var slots = googletag.pubads().getSlots();
          slots.forEach(function (slot) {
            var pos = slot.getTargeting('pos');
            if (pos == 'top-mobile') {
              //gets the slotId of the leaderboard ad to refresh
              leaderboardSlotId = slot.getSlotId().getDomId();
              slot.clearTargeting();
              _Object$keys(targeting).forEach(function (key) {
                slot.setTargeting(key, targeting[key]);
              });
              slot.setTargeting('pos', pos);
            }
          });
          lib_3.refresh(leaderboardSlotId);
        }
      });
    }
  };

  var preVscroll = 0;
  var isScrollDown = true;

  var scrollDirectionDetect = function scrollDirectionDetect(e) {
    var window = e.currentTarget;

    if (preVscroll > window.scrollY) {
      isScrollDown = false;
    } else if (preVscroll < window.scrollY) {
      isScrollDown = true;
    }
    preVscroll = window.scrollY;
  };

  useEffect(function () {
    window.addEventListener('scroll', scrollDirectionDetect);
    return function () {
      return window.removeEventListener('scroll', scrollDirectionDetect);
    };
  });

  var hasVerticalScroll = function hasVerticalScroll() {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight;
    } else {
      return document.documentElement.scrollHeight > document.documentElement.offsetHeight || document.body.scrollHeight > document.body.offsetHeight;
    }
  };

  useEffect(function () {
    // Fetching related article after component mounted if vertical scroll not found
    setTimeout(function () {
      if (!hasVerticalScroll()) {
        loadmore();
      }
    }, 1000);
  }, [queueData.length]);

  var loadmore = function loadmore() {
    var query = props.relatedArticleQuery;
    var params = props.params;
    if (queueData && queueData.length < maxListLength) {
      params.index = queueData.length - 1;
      props.client.fetch(query, params).then(function () {
        var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(article) {
          var startingIndex, endingIndex, targeting;
          return regenerator.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  if (!(article && article._id)) {
                    _context.next = 9;
                    break;
                  }

                  //query next 4 related article without repeating previous 4 related articles
                  startingIndex = queueData.length + 1;
                  endingIndex = startingIndex + 2;
                  _context.next = 5;
                  return getRelatedArticle(null, props.client, article, prevUrl, startingIndex + '..' + endingIndex);

                case 5:
                  article.relatedArticle = _context.sent;
                  targeting = getTargeting({ article: article, cpModificationRequired: cpModificationRequired, prevUrl: prevUrl });

                  article.Ads = Ads.getRightItems(targeting);
                  setQueueData([].concat(_toConsumableArray(queueData), [article]));

                case 9:
                case 'end':
                  return _context.stop();
              }
            }
          }, _callee, _this);
        }));

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

  var changeMeta = function changeMeta(meta) {
    document.title = meta.shareTitle;
    document.querySelector('meta[name="description"]').setAttribute('content', meta.shareSummary);
    document.querySelector('meta[name="keywords"]').setAttribute('content', meta.shareKeywords);
    document.querySelector('meta[property="og:url"]').setAttribute('content', meta.shareUrl);
    document.querySelector('meta[property="og:title"]').setAttribute('content', meta.shareTitle);
    document.querySelector('meta[property="og:site_name"]').setAttribute('content', meta.shareVia);
    document.querySelector('meta[property="og:description"]').setAttribute('content', meta.shareSummary);
    document.querySelector('meta[name="twitter:title"]').setAttribute('content', meta.shareTitle);
    document.querySelector('meta[name="twitter:image"]').setAttribute('content', meta.shareImage);
    document.querySelector('meta[name="twitter:site"]').setAttribute('content', meta.shareVia);
    document.querySelector('meta[name="twitter:description"]').setAttribute('content', meta.shareSummary);
    if (canonicalTag) {
      document.querySelector('link[rel="canonical"]').setAttribute('href', meta.shareUrl);
    }
  };

  var onChangeArticle = function onChangeArticle(path, visibility, meta) {
    var currentPath = window && window.location && window.location.pathname ? window.location.pathname.replace('/view/', '') : '';
    var newPath = '/view/' + path;

    // Change URL and do other changes
    var doChanges = function doChanges() {
      window.history.pushState({ page: path }, meta.shareTitle, newPath);
      changeMeta(meta);
      if (props.setCustomDimensions) {
        var activeArticle = queueData.find(function (item) {
          return item.url.current === path;
        });
        props.setCustomDimensions(activeArticle, '200', prevUrl);
      }
      if (props.pageview) props.pageview(newPath);
      refreshAD(path);
    };

    if (currentPath !== path) {
      if (isScrollDown) {
        if (visibility === 'top') {
          doChanges();
        }
      } else {
        if (visibility === 'bottom') {
          doChanges();
        }
      }
      if (visibility === 'small-top') {
        doChanges();
      }
    }
  };

  return React__default.createElement(
    InfiniteScroll,
    { dataLength: queueData.length, next: loadmore, scrollThreshold: '60%', hasMore: true, style: { overflow: 'hidden' } },
    queueData.map(function (article, index) {
      return React__default.createElement(Article, _extends({
        key: index
      }, props, {
        onChangeArticle: onChangeArticle,
        authorPrfix: authorPrefix,
        article: article,
        cpModificationRequired: cpModificationRequired
        // Passing queueData to check for single article
        , queueData: queueData,
        showRelatedArticles: showRelatedArticles
      }));
    })
  );
};

var Articles = function Articles(props) {
  var _extends2;

  var videoAccountIDs = props.videoAccountIDs,
      Ads = props.Ads,
      cpModificationRequired = props.cpModificationRequired,
      Settings = props.Settings,
      ISIContent = props.ISIContent,
      prevUrl = props.prevUrl,
      setActiveArticle = props.setActiveArticle,
      article = props.article,
      client = props.client,
      relatedArticleQuery = props.relatedArticleQuery,
      Website = props.Website,
      pageview = props.pageview,
      shareOptions = props.shareOptions,
      WAds = props.WAds,
      regionalPages = props.regionalPages,
      nationalPage = props.nationalPage,
      canonicalTag = props.canonicalTag;
  var taxonomyMapping = article.taxonomyMapping,
      _article$url = article.url;
  _article$url = _article$url === undefined ? {
    current: null
  } : _article$url;
  var url = _article$url.current,
      content_placement = article.content_placement;


  var taxonomy = [];
  content_placement.forEach(function (_ref2) {
    var path = _ref2.path,
        _id = _ref2._id;

    var prev_url_to_check = prevUrl;
    if (prev_url_to_check.includes('?')) {
      prev_url_to_check = prev_url_to_check.split('?')[0];
    }
    if (prev_url_to_check.endsWith(path)) taxonomy.push(_id);
  });

  if (taxonomy.length === 0) {
    taxonomy = taxonomyMapping.map(function (_ref3) {
      var _ref = _ref3._ref;
      return _ref;
    });
  }

  var params = {
    url: url,
    taxonomy: taxonomy,
    index: 0
  };

  return React__default.createElement(ArticleQueue, _extends((_extends2 = {
    client: client,
    params: params,
    relatedArticleQuery: relatedArticleQuery,
    website: Website,
    checkSponsered: true,
    pageview: pageview,
    shareOptions: shareOptions,
    Ads: WAds,
    regionalPages: regionalPages,
    nationalPage: nationalPage
  }, _defineProperty(_extends2, 'pageview', pageview), _defineProperty(_extends2, 'onVote', function onVote() {}), _defineProperty(_extends2, 'ISIContent', ISIContent), _defineProperty(_extends2, 'videoAccountIDs', videoAccountIDs), _defineProperty(_extends2, 'sponsoredTaxonomies', []), _defineProperty(_extends2, 'cpModificationRequired', cpModificationRequired), _defineProperty(_extends2, 'Settings', Settings), _defineProperty(_extends2, 'canonicalTag', canonicalTag), _extends2), props));
};

var _this$1 = undefined;

var View = function View(props) {
  var router = useRouter();
  var shareOptions = props.shareOptions,
      article = props.article,
      _props$sponsoredFlag = props.sponsoredFlag,
      sponsoredFlag = _props$sponsoredFlag === undefined ? false : _props$sponsoredFlag,
      _props$sponsoredTaxon = props.sponsoredTaxonomies,
      Ads = props.Ads,
      setCustomDimensions = props.setCustomDimensions,
      statusCode = props.statusCode,
      prevUrl = props.prevUrl,
      pageview = props.pageview,
      _props$showRelatedArt = props.showRelatedArticles,
      showRelatedArticles = _props$showRelatedArt === undefined ? false : _props$showRelatedArt,
      _props$canonicalTag = props.canonicalTag,
      canonicalTag = _props$canonicalTag === undefined ? true : _props$canonicalTag,
      _props$infiniteScroll = props.infiniteScrollFlag,
      infiniteScrollFlag = _props$infiniteScroll === undefined ? true : _props$infiniteScroll;
  var _props$article = props.article,
      _props$article$passwo = _props$article.passwordLock,
      passwordLock = _props$article$passwo === undefined ? false : _props$article$passwo,
      description = _props$article.description,
      title = _props$article.title,
      seriesShareOptions = _props$article.seriesShareOptions;

  var _useState = useState(0),
      _useState2 = _slicedToArray(_useState, 2),
      currentPage = _useState2[0],
      setCurrentPage = _useState2[1];
  // Logging GA pageview for the initial article with custom dimensions


  useEffect(function () {
    if (pageview && setCustomDimensions) {
      var timer = void 0;
      var waitAndExicute = function waitAndExicute() {
        if (typeof window.GA_INITIALIZED !== 'undefined') {
          setCustomDimensions(article, statusCode, prevUrl);
          pageview(router.asPath);
        } else timer = setTimeout(waitAndExicute, 1000);
      };
      waitAndExicute();
      return function () {
        clearTimeout(timer);
      };
    }
  }, []);

  //disable infinite scroll
  var checkVideoSeries = function checkVideoSeries(article) {
    if (!article || !article.body) {
      return false;
    }
    for (var i = 0; i < article.body.length; i++) {
      var row = article.body[i];
      if (typeof row.videos !== 'undefined') {
        return true;
      }
    }
    return false;
  };

  var checkArticleSeries = function checkArticleSeries(article) {
    if (!article || !article.body) {
      return false;
    }
    for (var i = 0; i < article.body.length; i++) {
      if (article.body[i]._type === 'articleSeries') {
        return true;
      }
    }
    return false;
  };

  var isVideoSeries = checkVideoSeries(props.article);
  var isArticleSeries = checkArticleSeries(props.article);
  var needInfiniteScroll = ['Articles', 'Videos', 'Podcasts'].includes(article.category.name) && article.taxonomyMapping && article.passwordLock !== true && !isVideoSeries && !isArticleSeries && !article.ExcludeFromInfiniteScroll && !sponsoredFlag && infiniteScrollFlag && !article.showIsi;

  if (['Articles', 'Videos', 'Podcasts'].includes(article.category.name)) {
    description = null;
    title = null;
  }

  if (!needInfiniteScroll && !title) {
    title = props.article ? props.article.title : '';
  }
  //add mobile ads to articles not using infinite scroll
  if (!needInfiniteScroll) {
    var targeting = getTargeting(props);
    article.Ads = Ads.getRightItems(targeting);
    if (!sponsoredFlag && Ads.getVideoContextualAD) {
      article.contextualVideoAD = Ads.getVideoContextualAD(getTargeting(props, 'in-context_video'));
    }
    if (!sponsoredFlag && Ads.getNativeContextualAD) {
      article.contextualAD = Ads.getNativeContextualAD(getTargeting(props, 'native-ad'));
    }
  }
  useEffect(function () {
    router.asPath && router.asPath.length > 0 && router.asPath.includes('?') && router.asPath.split('?')[1].split('&').forEach(function (item) {
      if (item.includes('page=')) {
        setCurrentPage(item.split('=')[1]);
      } else {
        setCurrentPage(0);
      }
    });
    if (!router.asPath.includes('page=') && currentPage !== 0) {
      setCurrentPage(0);
    }
  }, [router]);
  return React__default.createElement(
    React__default.Fragment,
    null,
    React__default.createElement(
      Head,
      null,
      React__default.createElement(
        'title',
        { key: 'title' },
        seriesShareOptions && seriesShareOptions.seriesTitle ? '' + seriesShareOptions.seriesTitle + (currentPage > 0 ? ' | Page ' + currentPage : '') : article && article.seo && article.seo.seo_title ? '' + article.seo.seo_title + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + article.title + (currentPage > 0 ? ' | Page ' + currentPage : '') + ' | ' + props.cache.siteSettingCache.name
      ),
      shareOptions.shareSummary && React__default.createElement('meta', {
        name: 'description',
        key: 'description',
        content: seriesShareOptions && seriesShareOptions.seriesSummary ? '' + seriesShareOptions.seriesSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : article.seo && article.seo.meta_description ? '' + article.seo.meta_description + (currentPage > 0 ? ' | Page ' + currentPage : '') : shareOptions.shareSummary ? '' + shareOptions.shareSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + (currentPage > 0 ? 'Page ' + currentPage : '') }),
      React__default.createElement('meta', { name: 'keywords', content: getKeywords(article).join(','), key: 'keywords' }),
      passwordLock && React__default.createElement('meta', { name: 'robots', content: 'noindex, nofollow' }),
      React__default.createElement('meta', {
        property: 'og:url',
        content: seriesShareOptions && seriesShareOptions.seriesUrl ? shareOptions.shareUrl + seriesShareOptions.seriesUrl : shareOptions.shareUrl,
        key: 'og:url'
      }),
      React__default.createElement('meta', {
        property: 'og:title',
        content: seriesShareOptions && seriesShareOptions.seriesTitle ? '' + seriesShareOptions.seriesTitle + (currentPage > 0 ? ' | Page ' + currentPage : '') : article.seo && article.seo.seo_title ? '' + article.seo.seo_title + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + shareOptions.shareTitle + (currentPage > 0 ? ' | Page ' + currentPage : ''),
        key: 'og:title'
      }),
      React__default.createElement('meta', {
        property: 'og:image',
        content: seriesShareOptions && seriesShareOptions.seriesThumbnail ? seriesShareOptions.seriesThumbnail : shareOptions.shareImage,
        key: 'og:image'
      }),
      React__default.createElement('meta', { property: 'og:site_name', content: props.Settings.title, key: 'og:site_name' }),
      React__default.createElement('meta', {
        property: 'og:description',
        content: seriesShareOptions && seriesShareOptions.seriesSummary ? '' + seriesShareOptions.seriesSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : shareOptions.shareSummary ? '' + shareOptions.shareSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + (currentPage > 0 ? ' | Page ' + currentPage : ''),
        key: 'og:description'
      }),
      React__default.createElement('meta', { name: 'twitter:card', content: 'summary', key: 'twitter:card' }),
      React__default.createElement('meta', {
        name: 'twitter:title',
        content: seriesShareOptions && seriesShareOptions.seriesTitle ? '' + seriesShareOptions.seriesTitle + (currentPage > 0 ? ' | Page ' + currentPage : '') : article.seo && article.seo.seo_title ? '' + article.seo.seo_title + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + shareOptions.shareTitle + (currentPage > 0 ? ' | Page ' + currentPage : ''),
        key: 'twitter:title'
      }),
      React__default.createElement('meta', {
        name: 'twitter:image',
        content: seriesShareOptions && seriesShareOptions.seriesThumbnail ? seriesShareOptions.seriesThumbnail : shareOptions.shareImage,
        key: 'twitter:image'
      }),
      React__default.createElement('meta', { name: 'twitter:site', content: '@' + props.Settings.title, key: 'twitter:site' }),
      React__default.createElement('meta', {
        name: 'twitter:description',
        content: seriesShareOptions && seriesShareOptions.seriesSummary ? '' + seriesShareOptions.seriesSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : shareOptions.shareSummary ? '' + shareOptions.shareSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : '' + (currentPage > 0 ? ' | Page ' + currentPage : ''),
        key: 'twitter:description'
      }),
      canonicalTag && React__default.createElement('link', {
        rel: 'canonical',
        href: seriesShareOptions && seriesShareOptions.seriesUrl ? shareOptions.shareUrl + seriesShareOptions.seriesUrl : shareOptions.shareUrl,
        key: 'canonical'
      }),
      React__default.createElement(
        'noscript',
        null,
        props.article.seriesDetail && props.article.seriesDetail.prevUrl && React__default.createElement('link', { rel: 'prev', href: props.article.seriesDetail.prevUrl }),
        props.article.seriesDetail && props.article.seriesDetail.nextUrl && React__default.createElement('link', { rel: 'next', href: props.article.seriesDetail.nextUrl })
      )
    ),
    !needInfiniteScroll ? React__default.createElement(Article, _extends({ infiniteScroll: false, showRelatedArticles: showRelatedArticles }, props)) : React__default.createElement(Articles, _extends({ infiniteScroll: true, showRelatedArticles: showRelatedArticles, canonicalTag: canonicalTag }, props))
  );
};

//This should be called in /view/[url] getInitialProps to fetch the article data and related articles.  This will also set the sponsoredFlag to true if any taxonomies have disabled ads.
View.returnGetInitialProps = function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(url, prevUrl, seriesVid, client, sao) {
    var context = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;

    var article, relatedArticleQuery, statusCode, _context$query$series, seriesArticle, sponsoredFlag;

    return regenerator.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return client.fetch(getQuery('article'), { url: url });

          case 2:
            article = _context.sent;
            relatedArticleQuery = getQuery('related');

            article.seriesDetail = getSeriesDetail(article, seriesVid);
            statusCode = 200;

            if (!article || !article._id) {
              statusCode = 404;
            }
            _context$query$series = context.query.seriesArticle, seriesArticle = _context$query$series === undefined ? false : _context$query$series;

            if (seriesArticle || seriesVid) {
              article.body.map(function (block) {
                if (block._type === 'articleSeries' && block.articles && block.articles.length > 0) {
                  block.articles.map(function (subArticle) {
                    if (subArticle.param.current === seriesArticle) {
                      var seriesShareOptions = {
                        seriesUrl: '?seriesArticle=' + seriesArticle,
                        seriesTitle: subArticle.title,
                        seriesSummary: subArticle.summary,
                        seriesThumbnail: subArticle.thumbnail && subArticle.thumbnail.asset ? urlFor(client, subArticle.thumbnail.asset).url() : null
                      };
                      article.seriesShareOptions = seriesShareOptions;
                    }
                  });
                }
                if (block._type === 'youtubeGallery' && block.videos && block.videos.length > 0) {
                  block.videos.map(function (video, index) {
                    if (index + 1 === Number(seriesVid)) {
                      var seriesShareOptions = {
                        seriesUrl: '?seriesVid=' + seriesVid,
                        seriesTitle: video.title,
                        seriesSummary: video.intro,
                        seriesThumbnail: video.thumbnail && video.thumbnail.asset ? urlFor(client, video.thumbnail.asset).url() : null
                      };
                      article.seriesShareOptions = seriesShareOptions;
                    }
                  });
                }
              });
            }
            sponsoredFlag = false;
            //check for disableAds flag on each taxonomoy

            if (article && article.content_placement) {
              article.content_placement.forEach(function (x) {
                if (x.disableAds) {
                  sponsoredFlag = true;
                }
              });
            }
            //check for disableAds flag on content category
            if (article.category && article.category.disableAds) {
              sponsoredFlag = true;
            }

            if (!article.disableRelatedContent) {
              _context.next = 16;
              break;
            }

            article.relatedArticle = null;
            _context.next = 20;
            break;

          case 16:
            if (!article) {
              _context.next = 20;
              break;
            }

            _context.next = 19;
            return getRelatedArticle(context, client, article, prevUrl, '0..2');

          case 19:
            article.relatedArticle = _context.sent;

          case 20:
            return _context.abrupt('return', {
              url: url,
              sao: sao,
              statusCode: statusCode,
              prevUrl: prevUrl,
              relatedArticleQuery: relatedArticleQuery,
              article: article,
              sponsoredFlag: sponsoredFlag
            });

          case 21:
          case 'end':
            return _context.stop();
        }
      }
    }, _callee, _this$1);
  }));

  return function (_x, _x2, _x3, _x4, _x5) {
    return _ref.apply(this, arguments);
  };
}();

export default View;
