import { a as _asyncToGenerator, r as regenerator } from './asyncToGenerator-7f8f9219.js';
import { _ as _extends, a as _Object$assign } from './extends-60e0e1c6.js';
import { a as _getIterator, _ as _slicedToArray } from './slicedToArray-be2f7a22.js';
import React, { useState, useRef, useEffect, forwardRef } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { _ as _JSON$stringify } from './stringify-59c8f690.js';
import { _ as _toConsumableArray } from './toConsumableArray-6d9a4616.js';
import { m as moment } from './moment-bc12cb97.js';
import { B as BlockContent } from './BlockContent-52cf21c5.js';
import { m as main_43 } from './main-b5c5aac1.js';
import 'react-bootstrap/Dropdown';
import Form from 'react-bootstrap/Form';
import FormControl from 'react-bootstrap/FormControl';
import Button from 'react-bootstrap/Button';
import { V as VisibilitySensor } from './visibility-sensor-f40c2564.js';
import SocialShare from './SocialShare.js';
import { r as renderAuthor, g as getSerializers } from './index-c1bcae0f.js';
import DFPAdSlot from './AdSlot.js';
import { S as SeriesSlider } from './SeriesSlider-38cca5eb.js';
import { g as getTargeting, a as getContentPlacementUrl } from './getTargeting-68291ce9.js';
import getKeywords from './getKeywords.js';
import urlFor from './urlFor.js';
import { _ as _typeof } from './typeof-a286cf0c.js';
import { b as FaMinus, c as FaPlus } from './index.esm-a8ff922c.js';
import { s as styleInject } from './style-inject.es-1f59c1d0.js';
import './index-35bdcc81.js';
import { DiscussionEmbed } from 'disqus-react';
import { _ as _Object$keys } from './keys-7a3adabf.js';
import { I as InfiniteScroll } from './index.es-c6222053.js';
import { l as lib_3 } from './index-2446af28.js';
import getRelatedArticle from './getRelatedArticle.js';
import getQuery from './getQuery.js';
import getSeriesDetail from './getSeriesDetail.js';
import './_commonjsHelpers-0c4b6f40.js';
import './es6.string.iterator-bc33758b.js';
import './_to-object-b50e61c3.js';
import './web.dom.iterable-4109ff68.js';
import './_library-528f1934.js';
import './core.get-iterator-method-133dfacd.js';
import './_iter-detect-7e5e5ce2.js';
import './_object-pie-133f504a.js';
import 'prop-types';
import './index-0dbff1d1.js';
import 'react-dom';
import 'react-share';
import 'react-bootstrap';
import './index-c7e2ac95.js';
import './util-3ab476bf.js';
import './Beam.js';
import './Segment.js';
import './brightcove-react-player-loader.es-b43c695a.js';
import './GroupDeck.js';
import './smoothscroll-fa4e3f8c.js';
import './_is-array-3e99e06e.js';
import './_object-to-array-0f197f89.js';
import 'react-bootstrap/Pagination';
import './entities-932b50cf.js';
import 'react-bootstrap/Row';
import 'react-bootstrap/Col';
import './inherits-a41fe93f.js';
import './_object-sap-f353c2a9.js';
import './define-property-fe54dc9f.js';
import './index.esm-3fdda599.js';
import './iconBase-602d52fe.js';
import 'react-bootstrap/Figure';
import './debounce-533d9748.js';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import './events-6c3a7a63.js';
import './index-db3bb315.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('/') && (!docGroup.parent || !docGroup.parent.parent)) {
    return '/' + docGroup.path;
  }
  // Checking if Parent has Parent
  if (docGroup.path && docGroup.path.includes('/') && docGroup.parent && docGroup.parent.parent) {
    if (docGroup.path.includes(docGroup.parent.identifier.current)) {
      return '/' + docGroup.parent.parent.identifier.current + '/' + docGroup.path;
    } else {
      return '/' + docGroup.parent.parent.identifier.current + '/' + docGroup.parent.identifier.current + '/' + 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 || article.documentGroup.isShow === false || article.documentGroup.isSeries) {
    return null;
  }

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

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

  return React.createElement(
    'a',
    {
      href: url,
      className: 'doc-group',
      style: { display: 'flex', flexDirection: 'column', padding: '0 1rem', justifyContent: thumbnailUrl ? 'center' : 'flex-start', alignItems: 'center' } },
    thumbnailUrl && React.createElement('img', { style: { maxWidth: '220px', maxHeight: '100px', marginTop: '1rem' }, src: thumbnailUrl, alt: name }),
    !thumbnailUrl && React.createElement('p', {
      style: { maxWidth: '315px', margin: '0', color: 'var(--primary)', textAlign: thumbnailUrl ? 'center' : main_43 ? 'left' : 'right', marginTop: '.25rem' },
      dangerouslySetInnerHTML: { __html: name } }),
    main_43 && !thumbnailUrl && React.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 _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      bottomOfArticle = _useState4[0],
      setbottomOfArticle = _useState4[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]);
  useEffect(function () {
    var detectBottomOfArticle = function detectBottomOfArticle() {
      var article_body = document.getElementById('article__block');
      var isi = document.getElementById('isi');
      var articleBottomPosition = article_body.getBoundingClientRect().bottom - window.innerHeight;
      console.log(articleBottomPosition, bottomOfArticle);
      if (articleBottomPosition < 30 && !isi.classList.contains('in-view')) {
        setbottomOfArticle(true);
      }
      if (articleBottomPosition > 60 && isi.classList.contains('in-view')) {
        setbottomOfArticle(false);
      }
    };
    window.addEventListener('scroll', detectBottomOfArticle);
    return function () {
      return window.removeEventListener('scroll', detectBottomOfArticle);
    };
  }, []);

  useEffect(function () {
    var isi = document.getElementById('isi');
    if (bottomOfArticle) {
      toggleSticky(true);
      isi.classList.add('in-view');
      if (active) {
        setActive(false);
      }
    }
    if (!bottomOfArticle) {
      toggleSticky(false);
      isi.classList.remove('in-view');
    }
  }, [bottomOfArticle]);

  var toggleSticky = function toggleSticky(sticky) {
    var isiToggle = document.getElementById('isiToggle');
    var isiContent = document.getElementById('isiContent');
    var isi = document.getElementById('isi');
    if (sticky) {
      isi.style.bottom = '-200px';
      setTimeout(function () {
        isi.style.maxHeight = 'unset';
        isi.style.position = 'relative';
        isi.style.boxShadow = 'none';
        isi.style.zIndex = '1';
        isi.style.marginTop = '-25rem';
        isi.style.marginBottom = '15rem';
        isiToggle.style.display = 'none';
        isiContent.style.padding = '0';
      }, 300);
    } else if (!sticky) {

      isi.style.marginBottom = '0';
      isi.style.maxHeight = '12rem';
      isi.style.position = 'fixed';
      isi.style.boxShadow = '0 0 1rem 0 rgba(0, 0, 0, 0.5)';
      isi.style.zIndex = '99999';

      isiToggle.style.display = 'block';
      isiContent.style.padding = '1rem';
      setTimeout(function () {
        isi.style.bottom = '0';
        isi.style.marginTop = '0';
      }, 300);
    }
  };
  return React.createElement(
    React.Fragment,
    null,
    React.createElement(
      'div',
      { id: 'isi', ref: isi },
      React.createElement(
        'div',
        { id: 'isiContent' },
        React.createElement(
          'div',
          { onClick: function onClick() {
              return setActive(function (prev) {
                return !prev;
              });
            }, id: 'isiToggle' },
          active ? React.createElement(
            'p',
            null,
            'Close ',
            React.createElement(FaMinus, null)
          ) : React.createElement(
            'p',
            null,
            'See More ',
            React.createElement(FaPlus, null)
          )
        ),
        children
      )
    ),
    React.createElement(
      'style',
      { jsx: true },
      '\n        #isi {\n          position: fixed;\n          z-index: 9999999;\n          bottom: 0;\n          left: 0;\n          max-height: 12rem;\n          background-color: #ffffff;\n          overflow-x: hidden;\n          overflow-y: hidden;\n          width: 100%;\n          box-shadow: 0 0 1rem 0 rgba(0, 0, 0, 0.5);\n          transition: bottom .5s ease , margin-top .3s, max-height .2s;\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 {\n  display: flex;\n  flex-direction: row;\n  flex-wrap: nowrap;\n  margin: 0 -1rem;\n}\n.RelatedArticles-module_mediaCard__3wQbn {\n  margin: 0 1rem 1rem;\n  width: calc(33% - 1rem);\n  display: column;\n  flex-direction: row;\n  margin-bottom: 0.75rem;\n  padding-bottom: 0.75rem;\n  border-bottom: none;\n}\n.RelatedArticles-module_mediaCard__3wQbn:last-child {\n  border-bottom: none;\n}\n.RelatedArticles-module_cardTitle__3P-Ib {\n  font-weight: bold;\n  color: #252525;\n  margin-bottom: 0.25rem;\n  font-size: 15px;\n}\n.RelatedArticles-module_authorListing__1EFg4 span.RelatedArticles-module_text-muted__3b0zX {\n  color: #000;\n  font-weight: bold;\n}\n.RelatedArticles-module_cardDate__1wOR5 {\n  color: var(--dark);\n  display: block;\n  background: #fff !important;\n  margin-bottom: 0;\n}\n.RelatedArticles-module_imgWrapper__5Jx_4 {\n  display: block;\n  text-align: center;\n  margin-bottom: 0.5rem;\n}\n.RelatedArticles-module_imgWrapper__5Jx_4 img {\n  height: 135px;\n  width: 100%;\n  object-fit: cover;\n  object-position: center;\n}\n@media screen and (max-width: 1064px) {\n}\n@media screen and (max-width: 968px) {\n  .RelatedArticles-module_mediaContainer__10h9k {\n    flex-wrap: wrap;\n  }\n  .RelatedArticles-module_imgWrapper__5Jx_4 {\n    display: none;\n  }\n  .RelatedArticles-module_mediaCard__3wQbn {\n    width: 100%;\n    margin-bottom: 0.5rem;\n    padding: 0;\n  }\n  .RelatedArticles-module_cardTitle__3P-Ib {\n    font-size: 0.75rem;\n    margin-bottom: 0;\n  }\n}\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,
      fallbackImage = _ref.fallbackImage,
      _ref$showRelatedArtic = _ref.showRelatedArticleFallbackImage,
      showRelatedArticleFallbackImage = _ref$showRelatedArtic === undefined ? true : _ref$showRelatedArtic;

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

var getSocialShareDisableFlag = function getSocialShareDisableFlag(article) {
  //Need to check Taxonomy, DocumentGroup, and Authors for showSocialShare
  var showSocialShare = true;

  if (article.content_placement && article.content_placement.length > 0) {
    //loop through each
    article.content_placement.forEach(function (category) {
      if (category.showSocialShare === false) {
        showSocialShare = false;
      }
    });
  }
  if (article.authorDetails && article.authorDetails.length > 0) {
    article.authorDetails.forEach(function (author) {
      if (author.showSocialShare === false) {
        showSocialShare = false;
      }
    });
  }
  if (article.documentGroup && article.documentGroup.length > 0) {
    article.documentGroup.forEach(function (docGroup) {
      if (docGroup.showSocialShare === false) {
        showSocialShare = false;
      }
    });
  }
  if (article.documentGroupMapping && article.documentGroupMapping.length > 0) {
    article.documentGroupMapping.forEach(function (docGroup) {
      if (docGroup.showSocialShare === false) {
        showSocialShare = false;
      }
    });
  }

  return showSocialShare;
};

var Article = forwardRef(function (props, ref) {
  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,
      onChangeArticle = props.onChangeArticle,
      _props$showSocialShar = props.showSocialShare,
      showSocialShare = _props$showSocialShar === undefined ? true : _props$showSocialShar;
  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,
      issueGroup = _props$article.issueGroup,
      showIsi = _props$article.showIsi,
      isi = _props$article.isi,
      _props$article$displa = _props$article.display_summary,
      display_summary = _props$article$displa === undefined ? true : _props$article$displa,
      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;
      props.active;
      var containerHeight = props.containerHeight,
      _props$refreshFlag = props.refreshFlag,
      refreshFlag = _props$refreshFlag === undefined ? false : _props$refreshFlag,
      disqusConfig = props.disqusConfig,
      showDisqus = props.showDisqus;

  var targeting = getTargeting(props);

  //if showSocialShare is not disabled for entire site, check article taxonomy, docgroup, authors for showSocialShare === false
  if (showSocialShare) {
    showSocialShare = getSocialShareDisableFlag(props.article);
  }

  //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);
      _useState12[0];
      var 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.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.createElement(ISIContent, null);
    } else if (nationalPage === url && ISIContent) {
      return React.createElement(ISIContent, { national: true });
    }
    return null;
  };

  var RelevantTopics = function RelevantTopics() {
    if (content_placement && content_placement.length > 0 || documentGroupMapping && documentGroupMapping.length > 0) {
      var relatedLinks = [];
      if (documentGroupMapping && documentGroupMapping.length > 0) {
        documentGroupMapping.forEach(function (documentGroup) {
          if (documentGroup.parent) {
            relatedLinks = [].concat(_toConsumableArray(relatedLinks), [{ label: documentGroup.name, href: cpModificationRequired ? getDocumentGroupUrl(documentGroup) : '/' + documentGroup.path }]);
          }
        });
      }
      if (content_placement && content_placement.length > 0) {
        content_placement.filter(function (item) {
          return item.path !== 'news';
        }).forEach(function (cp) {
          var cp_url = cpModificationRequired ? getContentPlacementUrl(cp) : cp.path;
          var href = '/' + cp_url;
          relatedLinks = [].concat(_toConsumableArray(relatedLinks), [{ label: cp.name, href: href }]);
        });
      }
      if (issueGroup && issueGroup.name && issueGroup.identifier && issueGroup.identifier.current && issueGroup.parent && issueGroup.parent.identifier && issueGroup.parent.identifier.current) {
        var _props$Settings$issue = props.Settings.issueMapping,
            issueMapping = _props$Settings$issue === undefined ? '/publications' : _props$Settings$issue;

        relatedLinks = [].concat(_toConsumableArray(relatedLinks), [{ label: issueGroup.name, href: issueMapping + '/' + issueGroup.parent.identifier.current + '/' + issueGroup.identifier.current }]);
      }
      if (relatedLinks && relatedLinks.length > 0) {
        return React.createElement(
          'div',
          null,
          relatedLinks.map(function (relatedLink, index) {
            return React.createElement(
              'span',
              { key: index, className: 'related-link' },
              React.createElement(
                'a',
                { className: 'related-links', style: { color: 'blue' }, href: relatedLink.href },
                relatedLink.label
              ),
              React.createElement(
                'style',
                { jsx: 'true' },
                '\n                      .related-link:not(:first-child):before {\n                        content: \' | \';\n                      }\n                    '
              )
            );
          })
        );
      }
      return null;
    }
    return null;
  };

  var RelatedContent = function RelatedContent() {
    return React.createElement(
      'section',
      { id: 'related-content-section', className: 'my-1' },
      (article.relatedArticle || RelevantTopics()) && React.createElement(
        'p',
        { className: 'mb-0' },
        React.createElement(
          'b',
          null,
          'Related Content:'
        )
      ),
      React.createElement(RelevantTopics, null),
      React.createElement(
        'div',
        { className: 'pt-2' },
        React.createElement(RelatedArticle, {
          articles: article.relatedArticle,
          client: client,
          fallbackImage: props.Settings.logo,
          showRelatedArticleFallbackImage: props.showRelatedArticleFallbackImage
        })
      )
    );
  };

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

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

    var indexes = findIndex(body);
    var seriesInfo = checkIfMediaSeriesHasVideo(article);
    var isMediaSeries = article.documentGroup && article.documentGroup.isSeries ? true : false;
    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;
      if (seriesInfo.hasVideo) {
        selectedIndex = seriesInfo.videoIndex;
      }

      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.createElement(
        React.Fragment,
        null,
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, contextualADFlag, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        React.createElement('span', { className: 'clearfix' }),
        article.documentGroup && article.documentGroup.isSeries && props.sliderData && seriesInfo.hasVideo && React.createElement(SeriesSlider, { dataset: props.sliderData, client: client, nowPlaying: article.title, displayEpisodeNumber: true }),
        React.createElement(
          'div',
          { id: 'contextual-native-ad-' + payload._id, className: 'contextual-native-ad' },
          React.createElement(DFPAdSlot, _extends({}, payload.contextualAD, {
            refreshFlag: refreshFlag
            // checkIsAdFound={previewAd ? null : checkIsAdFound}
          }))
        ),
        React.createElement('span', { className: 'clearfix' }),
        React.createElement(
          'div',
          { id: 'contextual-video-ad-' + payload._id, className: 'contextual-video-ad' },
          React.createElement(DFPAdSlot, _extends({}, payload.contextualVideoAD, { refreshFlag: refreshFlag, checkIsAdFound: checkIsVideoAdFound }))
        ),
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, null, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          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;
      if (seriesInfo.hasVideo) {
        _selectedIndex = seriesInfo.videoIndex;
      }
      return React.createElement(
        React.Fragment,
        null,
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, contextualADFlag, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, _selectedIndex))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        contextualADFlag && React.createElement('span', { className: 'clearfix' }),
        article.documentGroup && article.documentGroup.isSeries && props.sliderData && seriesInfo.hasVideo && React.createElement(SeriesSlider, { dataset: props.sliderData, client: client, nowPlaying: article.title, displayEpisodeNumber: true }),
        (visibleFlag || queueData && queueData.length === 1 || !props.infiniteScroll) && React.createElement(
          'div',
          { id: 'contextual-native-ad-' + payload._id, className: 'contextual-native-ad' },
          React.createElement(DFPAdSlot, _extends({}, payload.contextualAD, {
            refreshFlag: refreshFlag
            // checkIsAdFound={previewAd ? null : checkIsAdFound}
          }))
        ),
        contextualADFlag && React.createElement('span', { className: 'clearfix' }),
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, null, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          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;
      if (seriesInfo.hasVideo) {
        _selectedIndex2 = seriesInfo.videoIndex;
      }
      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.createElement(
        React.Fragment,
        null,
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, contextualADFlag, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: [].concat(_toConsumableArray(articleBody.slice(0, _selectedIndex2))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        React.createElement('span', { className: 'clearfix' }),
        article.documentGroup && article.documentGroup.isSeries && props.sliderData && seriesInfo.hasVideo && React.createElement(SeriesSlider, { dataset: props.sliderData, client: client, nowPlaying: article.title, displayEpisodeNumber: true }),
        React.createElement(
          'div',
          { id: 'contextual-video-ad-' + payload._id, className: 'contextual-video-ad' },
          React.createElement(DFPAdSlot, _extends({}, payload.contextualVideoAD, { refreshFlag: refreshFlag, checkIsAdFound: _checkIsAdFound2 }))
        ),
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, null, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: [].concat(_toConsumableArray(articleBody.slice(_selectedIndex2))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config()))
      );
    } else {
      var _selectedIndex3 = indexes[1] + 1;
      if (seriesInfo.hasVideo) {
        _selectedIndex3 = seriesInfo.videoIndex;
      }

      return React.createElement(
        'div',
        null,
        React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, false, null, props.article.Ads, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: article.documentGroup && article.documentGroup.isSeries ? [].concat(_toConsumableArray(articleBody.slice(0, _selectedIndex3))) : articleBody,
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config())),
        article.documentGroup && article.documentGroup.isSeries && props.sliderData && seriesInfo.hasVideo && React.createElement(SeriesSlider, { dataset: props.sliderData, client: client, nowPlaying: article.title, displayEpisodeNumber: true }),
        article.documentGroup && article.documentGroup.isSeries && React.createElement(BlockContent, _extends({
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, isMediaSeries, null, null, null, targeting, article, meta, authorPrefix, authorImgHeight),
          blocks: [].concat(_toConsumableArray(articleBody.slice(_selectedIndex3))),
          imageOptions: { w: 320, h: 240, fit: 'max' }
        }, client.config()))
      );
    }
  };

  var checkIfVideoSeries = function checkIfVideoSeries(article) {
    if (!article || !article.body) {
      return false;
    }

    for (var i = 0; i < article.body.length; i++) {
      var block = article.body[i];
      if (block._type === 'youtubeGallery') {
        return true;
      }
    }

    return false;
  };
  var checkIfMediaSeriesHasVideo = function checkIfMediaSeriesHasVideo(article) {
    var seriesInfo = { hasVideo: false, videoIndex: 0 };
    if (!article || !article.body) {
      return false;
    }

    for (var i = 0; i < article.body.length; i++) {
      var block = article.body[i];
      if (block._type == 'video' || block._type == 'youtube' || block._type == 'audio') {
        seriesInfo.hasVideo = true;
        seriesInfo.videoIndex = i + 1;
      }
    }

    return seriesInfo;
  };

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

    var shareUrl = shareBaseUrl + props.article.url.current;
    var shareTitle = article.title;
    var shareSummary = article.summary;
    var shareImage = thumbnail && thumbnail.asset ? urlFor({ client: props.client, source: thumbnail.asset }) : 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;
      };
    }
    var fetchCurrentEpisode = function fetchCurrentEpisode(sliderData, article) {
      if (!sliderData) return null;
      var episode = null;
      sliderData.forEach(function (seriesArticle, index) {
        if (seriesArticle.title === article.title) {
          episode = index + 1;
        }
      });
      return episode;
    };
    // pixels from bottom of window to change trigger visibility change
    var triggerOffset = 10;
    var isVideoSeries = checkIfVideoSeries(article);
    var episodeNumber = fetchCurrentEpisode(props.sliderData, props.article);
    var isMediaSeries = article.documentGroup && article.documentGroup.isSeries ? true : false;
    var seriesInfo = checkIfMediaSeriesHasVideo(article);

    return React.createElement(
      React.Fragment,
      null,
      React.createElement(
        VisibilitySensor,
        {
          partialVisibility: true,
          offset: { bottom: triggerOffset, top: containerHeight - 80 },
          onChange: function onChange(isVisible) {
            if (isVisible && queueData && queueData.length > 1) {
              onChangeArticle(url, meta);
              setVisibleFlag(function () {
                return true;
              });
            }
          } },
        React.createElement(
          'div',
          { id: 'article__block', ref: ref },
          React.createElement(
            'div',
            { className: 'video-detail', style: { marginBottom: isCutomPage(props.article) || showIsi && Array.isArray(isi) && isi.length > 0 ? '15rem' : 0 } },
            isVideoSeries && renderBlockContent(article, meta, authorImgHeight),
            !isVideoSeries && React.createElement(
              'div',
              null,
              isMediaSeries && article.documentGroup && article.documentGroup.name && React.createElement(
                'p',
                { style: { fontSize: '14px' } },
                article.documentGroup.name,
                ' - Episode ',
                episodeNumber
              ),
              React.createElement(
                'h1',
                { className: 'page-title', style: { fontSize: '1.9rem' } },
                title
              )
            ),
            React.createElement(
              'div',
              { className: 'mb-3 doc-group-container', style: { display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' } },
              React.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.createElement(
                'div',
                { className: 'left-wrap' },
                !isVideoSeries && showPublished && React.createElement(
                  'div',
                  null,
                  moment(published).format('LL')
                )
                /* Show Published date */
                ,
                React.createElement(
                  'div',
                  { className: 'mb-3' },
                  !isVideoSeries && authorDetails && authorDetails.map(function (authorDetail, index) {
                    return React.createElement(
                      'span',
                      { key: index },
                      renderAuthor(authorDetail.displayName, authorDetail.url, index, authorDetails.length, authorPrefix, authorDetail.biography && renderAuthorBiography(authorDetail.biography[0]), authorDetail.profileImage && urlFor({ client: props.client, source: authorDetail.profileImage, imageHeight: authorImgHeight }))
                    );
                  }),
                  React.createElement(
                    'div',
                    null,
                    source && React.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.createElement(
                    'div',
                    { className: 'volume-issue' },
                    issue.publication && issue.publication.name && React.createElement(
                      'span',
                      { className: 'mb-0' },
                      React.createElement(
                        'b',
                        null,
                        issue.publication.name
                      ),
                      ',',
                      ' '
                    ),
                    issue.name && React.createElement(
                      'span',
                      { className: 'mb-0' },
                      issue.name,
                      ', '
                    ),
                    issue.volume && React.createElement(
                      'span',
                      null,
                      'Volume ' + issue.volume,
                      ','
                    ),
                    issue.issueNumber && React.createElement(
                      'span',
                      null,
                      ' Issue ' + issue.issueNumber
                    )
                  ),
                  pageNumber && React.createElement(
                    'div',
                    { className: 'article-pageNumber' },
                    'Pages: ' + pageNumber
                  )
                ),
                !isVideoSeries && showSocialShare && React.createElement(
                  'p',
                  null,
                  React.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.createElement(
                'div',
                null,
                React.createElement(DocumentGroup, { article: props.article, client: props.client })
              )
            ),
            !isVideoSeries && summary && display_summary && React.createElement(
              'p',
              null,
              React.createElement(
                'em',
                null,
                summary
              )
            ),
            React.createElement(
              'div',
              { className: 'ad-box', style: { textAlign: 'center' } },
              main_43 && !sponsoredFlag && props.article.Ads && props.article.Ads.length > 0 && props.article.Ads.map(function (ad, index) {
                if (index === 0) {
                  return React.createElement(
                    'div',
                    {
                      key: index,
                      id: 'addid-' + index,
                      style: {
                        display: 'flex',
                        flex: '1 0 auto',
                        justifyContent: 'center',
                        alignItems: 'center',
                        textAlign: 'center'
                      } },
                    ad.component
                  );
                }
              })
            ),
            React.createElement(
              'div',
              { className: 'block-content mt-3' },
              !isVideoSeries && renderBlockContent(article, meta),
              React.createElement('div', { className: 'clearfix' }),
              React.createElement(
                'noscript',
                null,
                React.createElement(
                  'div',
                  { style: { display: 'flex', justifyContent: 'center' }, className: 'series-links' },
                  props.article.seriesDetail && props.article.seriesDetail.prevUrl && React.createElement(
                    'a',
                    { className: 'mx-3', href: props.article.seriesDetail.prevUrl },
                    'Previous ',
                    props.article.seriesDetail.type
                  ),
                  props.article.seriesDetail && props.article.seriesDetail.nextUrl && React.createElement(
                    'a',
                    { className: 'mx-3', href: props.article.seriesDetail.nextUrl },
                    'Next ',
                    props.article.seriesDetail.type
                  )
                )
              ),
              issue && issue.url && React.createElement(
                'a',
                { rel: 'noopener', href: issue.url, target: '_blank', title: 'Download issue' },
                React.createElement('img', { style: { margin: '1rem', maxHeight: '40px', maxWidth: '40px' }, src: '/download.png', alt: 'download issue' }),
                'Download Issue : ',
                issue.name
              )
            ),
            React.createElement('div', { className: 'clearfix', style: { minHeight: '1px' } }),
            article.documentGroup && article.documentGroup.isSeries && props.sliderData && !seriesInfo.hasVideo && React.createElement(
              'div',
              null,
              false ,
              React.createElement(SeriesSlider, { dataset: props.sliderData, client: client, nowPlaying: article.title, displayEpisodeNumber: true })
            ),
            showRelatedArticles && !showIsi && React.createElement(RelatedContent, null),
            disqusConfig && showDisqus && React.createElement(
              'div',
              { id: 'disqusContainer' },
              React.createElement(DiscussionEmbed, {
                shortname: disqusConfig.shortname,
                config: {
                  url: disqusConfig.url,
                  identifier: disqusConfig.identifier,
                  title: disqusConfig.title
                }
              })
            )
          ),
          renderIsiContent(props.article)
        )
      ),
      showIsi && Array.isArray(isi) && isi.length > 0 && React.createElement(
        ISI,
        null,
        React.createElement(BlockContent, {
          serializers: getSerializers(client, pageview, videoAccountIDs, onVote, true, drupalLeadSettings, currentPage, false, false, null, props.article.Ads, targeting),
          blocks: isi
        })
      ),
      main_43 && !sponsoredFlag && props.article.Ads && props.article.Ads.length > 0 && props.article.Ads.map(function (ad, index) {
        if (index > 0) {
          return React.createElement(
            'div',
            { key: index, id: 'addid-' + index, style: { display: 'flex', flex: '1 0 auto' } },
            ad.component
          );
        }
      }),
      React.createElement(
        'noscript',
        null,
        props.infiniteScroll && props.article.relatedArticle && props.article.relatedArticle[0] && props.article.relatedArticle[0].url && props.article.relatedArticle[0].url.current && React.createElement(
          'div',
          { style: { textAlign: 'center' } },
          React.createElement(
            'a',
            { href: '/view/' + props.article.relatedArticle[0].url.current },
            'Related Article ',
            '>>>'
          )
        )
      ),
      props.infiniteScroll && React.createElement('hr', { className: 'article-seperater mb-5 mt-3' })
    );
  };

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

var _this$1 = 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.sponsoredTaxonomies;
      var _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 _useState = useState(0),
      _useState2 = _slicedToArray(_useState, 2),
      containerHeight = _useState2[0],
      setContainerHeight = _useState2[1];

  useEffect(function () {
    setContainerHeight(function () {
      return window.innerHeight;
    });
    var handleResize = function handleResize() {
      return setContainerHeight(function () {
        return window.innerHeight;
      });
    };
    window.addEventListener('resize', handleResize);
    return function () {
      return window.removeEventListener('resize', handleResize);
    };
  }, []);

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

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

  var _useState5 = useState(queueData[0]._id),
      _useState6 = _slicedToArray(_useState5, 2),
      active = _useState6[0],
      setActive = _useState6[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_43) {
      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_43) {
      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 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 () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
      var index, article, startingIndex, endingIndex, targeting;
      return regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!(queueData && queueData.length < maxListLength)) {
                _context.next = 27;
                break;
              }

              index = queueData.length - 1;
              article = null;
              _context.prev = 3;
              _context.next = 6;
              return getRelatedArticle(null, props.client, props.article, prevUrl, index);

            case 6:
              article = _context.sent;
              _context.next = 12;
              break;

            case 9:
              _context.prev = 9;
              _context.t0 = _context['catch'](3);

              console.error(_context.t0);

            case 12:
              if (!(article && article._id)) {
                _context.next = 27;
                break;
              }

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

            case 18:
              article.relatedArticle = _context.sent;
              _context.next = 24;
              break;

            case 21:
              _context.prev = 21;
              _context.t1 = _context['catch'](15);

              console.error(_context.t1);

            case 24:
              targeting = getTargeting({ article: article, cpModificationRequired: cpModificationRequired, prevUrl: prevUrl });

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

            case 27:
            case 'end':
              return _context.stop();
          }
        }
      }, _callee, _this$1, [[3, 9], [15, 21]]);
    }));

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

  var changeMeta = function changeMeta(meta) {
    document.title = meta.shareTitle;
    //this was throwing an error if there was no description, doing a check for the description meta
    if (document.querySelector('meta[name="description"]')) 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);
    //this was throwing an error if there was no description, doing a check for the description meta
    if (document.querySelector('meta[name="twitter:description"]')) 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, meta) {
    var newPath = '/view/' + path;
    var activeArticle = queueData.find(function (item) {
      return item.url.current === path;
    });
    setActive(function () {
      return activeArticle._id;
    });
    // Change URL and do other changes
    window.history.pushState({ page: path }, meta.shareTitle, newPath);
    changeMeta(meta);
    if (props.setCustomDimensions) {
      props.setCustomDimensions(activeArticle, '200', prevUrl);
    }
    if (props.pageview) props.pageview(newPath);
    refreshAD(path);
  };

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

var _this = undefined;

var View = function View(props) {
  var router = useRouter();
  var shareOptions = props.shareOptions,
      article = props.article,
      _props$article = props.article,
      hideComments = _props$article.hideComments,
      content_placement = _props$article.content_placement,
      _props$sponsoredFlag = props.sponsoredFlag,
      sponsoredFlag = _props$sponsoredFlag === undefined ? false : _props$sponsoredFlag;
      props.sponsoredTaxonomies;
      var 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$article2 = props.article,
      _props$article2$passw = _props$article2.passwordLock,
      passwordLock = _props$article2$passw === undefined ? false : _props$article2$passw;
      _props$article2.description;
      var title = _props$article2.title,
      seriesShareOptions = _props$article2.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 commentsEnabledInTaxonomy = Array.isArray(content_placement) && content_placement.some(function (t) {
    return t.showComments === true;
  });
  var showDisqus = commentsEnabledInTaxonomy || hideComments === false;
  var needInfiniteScroll = ['Articles', 'Videos', 'Podcasts'].includes(article.category.name) && article.taxonomyMapping && article.passwordLock !== true && !isVideoSeries && !isArticleSeries && !article.ExcludeFromInfiniteScroll && !sponsoredFlag && infiniteScrollFlag && !article.showIsi && (!article.documentGroup || !article.documentGroup.isSeries) && !showDisqus;

  if (['Articles', 'Videos', 'Podcasts'].includes(article.category.name)) {
    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]);

  var meta_description = 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 : '');

  if (isVideoSeries) {
    meta_description = seriesShareOptions && seriesShareOptions.seriesSummary ? '' + seriesShareOptions.seriesSummary + (currentPage > 0 ? ' | Page ' + currentPage : '') : '';
  }

  return React.createElement(
    React.Fragment,
    null,
    React.createElement(
      Head,
      null,
      React.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 : '')
      ),
      meta_description && React.createElement('meta', { name: 'description', key: 'description', content: meta_description }),
      React.createElement('meta', { name: 'keywords', content: getKeywords(article).join(','), key: 'keywords' }),
      passwordLock && React.createElement('meta', { name: 'robots', content: 'noindex, nofollow' }),
      React.createElement('meta', {
        property: 'og:url',
        content: seriesShareOptions && seriesShareOptions.seriesUrl ? shareOptions.shareUrl + seriesShareOptions.seriesUrl : shareOptions.shareUrl,
        key: 'og:url'
      }),
      React.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.createElement('meta', {
        property: 'og:image',
        content: seriesShareOptions && seriesShareOptions.seriesThumbnail ? seriesShareOptions.seriesThumbnail : shareOptions.shareImage,
        key: 'og:image'
      }),
      React.createElement('meta', { property: 'og:site_name', content: props.Settings.title, key: 'og:site_name' }),
      React.createElement('meta', { property: 'og:description', content: meta_description, key: 'og:description' }),
      React.createElement('meta', { name: 'twitter:card', content: 'summary', key: 'twitter:card' }),
      React.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.createElement('meta', {
        name: 'twitter:image',
        content: seriesShareOptions && seriesShareOptions.seriesThumbnail ? seriesShareOptions.seriesThumbnail : shareOptions.shareImage,
        key: 'twitter:image'
      }),
      React.createElement('meta', { name: 'twitter:site', content: '@' + props.Settings.title, key: 'twitter:site' }),
      React.createElement('meta', { name: 'twitter:description', content: meta_description, key: 'twitter:description' }),
      canonicalTag && React.createElement('link', {
        rel: 'canonical',
        href: seriesShareOptions && seriesShareOptions.seriesUrl ? shareOptions.shareUrl + seriesShareOptions.seriesUrl : shareOptions.shareUrl,
        key: 'canonical'
      }),
      React.createElement(
        'noscript',
        null,
        props.article.seriesDetail && props.article.seriesDetail.prevUrl && React.createElement('link', { rel: 'prev', href: props.article.seriesDetail.prevUrl }),
        props.article.seriesDetail && props.article.seriesDetail.nextUrl && React.createElement('link', { rel: 'next', href: props.article.seriesDetail.nextUrl })
      )
    ),
    !needInfiniteScroll ? React.createElement(Article, _extends({ infiniteScroll: false, showRelatedArticles: showRelatedArticles, showDisqus: showDisqus }, props)) : React.createElement(ArticleQueue, _extends({
      infiniteScroll: true,
      showRelatedArticles: showRelatedArticles,
      canonicalTag: canonicalTag,
      checkSponsered: true,
      Ads: props.WAds,
      onVote: function onVote() {},
      sponsoredTaxonomies: []
    }, 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, sliderData, statusCode, sliderArticles, _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);
            sliderData = [];
            statusCode = 200;

            if (!article || !article._id || !article.body) {
              statusCode = 404;
            }

            if (!(article.documentGroup && article.documentGroup.isSeries)) {
              _context.next = 13;
              break;
            }

            _context.next = 11;
            return client.fetch('*[!(_id in path("drafts.**")) \n    && _type == "article"\n    && defined(title)\n    && references(\'' + article.documentGroup._id + '\')\n    && is_visible == true\n    && defined(published)\n    && dateTime(published) <= dateTime(now())\n  ] | order(published asc)  {\n      title,\n      thumbnail,\n      url,\n      published\n    }');

          case 11:
            sliderArticles = _context.sent;

            sliderData = sliderArticles;

          case 13:
            _context$query$series = context.query.seriesArticle, seriesArticle = _context$query$series === undefined ? false : _context$query$series;

            if ((seriesArticle || seriesVid) && article.body) {
              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: client, source: subArticle.thumbnail.asset }) : 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: client, source: video.thumbnail.asset }) : 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 = 23;
              break;
            }

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

          case 23:
            if (!article) {
              _context.next = 27;
              break;
            }

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

          case 26:
            article.relatedArticle = _context.sent;

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

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

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

export default View;
