import { _ as _asyncToGenerator, r as regenerator, a as _Promise } from './asyncToGenerator-958ef5fc.js';
import { _ as _typeof } from './typeof-e9fc0c5d.js';
import { _ as _extends } from './extends-6d8e3924.js';
import { _ as _slicedToArray } from './slicedToArray-6ebcbfea.js';
import React__default, { useState, useEffect } from 'react';
import { M as MediaSeriesCard, D as DropdownButton, a as Dropdown } from './MediaSeriesCard-96ac8ed4.js';
import './index-0ce54f8a.js';
import 'react-dom';
import Link from 'next/link';
import { B as BlockContent } from './BlockContent-1e73bd2c.js';
import MasterDeck from './MasterDeckPaginated.js';
import { g as getSerializers } from './index-076baa11.js';
import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-ea258bb1.js';
import './web.dom.iterable-ab4dea5c.js';
import './_library-528f1934.js';
import './_iter-detect-98db3b07.js';
import './_is-array-8d21b9e3.js';
import './_object-pie-133f504a.js';
import 'prop-types';
import './index-755f2cc2.js';
import './urlFor.js';
import './index-3f5c03b2.js';
import './moment-bc12cb97.js';
import './style-inject.es-1f59c1d0.js';
import './stringify-2b084bee.js';
import './toConsumableArray-f7074d7c.js';
import './inherits-a6ba2ec4.js';
import './_object-sap-7cee6f84.js';
import './define-property-5f1bda73.js';
import './index-f0fc23eb.js';
import './events-6c3a7a63.js';
import 'react-bootstrap/Container';
import 'react-bootstrap/Spinner';
import 'next/router';
import './lodash-f97fd99a.js';
import './main-9f6806ea.js';
import './ADlgInfeed-e7fd1bb6.js';
import 'react-bootstrap/Card';
import './AdSlot.js';
import './debounce-533d9748.js';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import './Beam.js';
import './Segment.js';
import './ADInfeed-777bb0b3.js';
import './Pagination-9fe9f61d.js';
import 'react-bootstrap/Button';
import './index.esm-1bd8a0a8.js';
import './iconBase-ccc56b97.js';
import 'react-bootstrap';
import './index-c7e2ac95.js';
import './empty-a8042e3c.js';
import './urlForFile-b69adffc.js';
import './brightcove-react-player-loader.es-57a70a56.js';
import 'react-bootstrap/Modal';
import 'react-bootstrap/Form';
import './index-e7075467.js';
import './GroupDeck.js';
import './smoothscroll-fa4e3f8c.js';
import './SocialShare.js';
import 'next/head';
import 'react-share';
import './_object-to-array-2300e51b.js';
import 'react-bootstrap/Pagination';
import './entities-6d9154b4.js';
import 'react-bootstrap/Row';
import 'react-bootstrap/Col';
import './index.esm-eb1e8e80.js';
import 'react-bootstrap/Figure';
import 'react-bootstrap/OverlayTrigger';
import 'react-bootstrap/Tooltip';
import 'react-bootstrap/Popover';
import './checkSisterSite-baa4fb6b.js';

var _this = undefined;

var Filter = function Filter(_ref) {
  var filterData = _ref.filterData,
      setFilterTopicID = _ref.setFilterTopicID;

  if (!filterData || filterData.length == 0) return null;

  var _useState = useState(null),
      _useState2 = _slicedToArray(_useState, 2),
      parentData = _useState2[0],
      setParentData = _useState2[1];

  var _useState3 = useState(null),
      _useState4 = _slicedToArray(_useState3, 2),
      childData = _useState4[0],
      setChildData = _useState4[1];

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      grandChildData = _useState6[0],
      setGrandChildData = _useState6[1];
  /*
    {parent: showAll,
      chidlren: show selected from parent,
        grandchildren: show selected from children
    }
    */


  useEffect(function () {
    if (filterData.length < 2) {
      setChildData({ name: null, data: filterData[0].children, _id: filterData[0]._id });
    } else {
      setParentData({ name: null, data: filterData });
    }
  }, []);

  var handleFilterSelect = function handleFilterSelect(group, type) {
    if (type === 'parent') {
      setParentData(function (prevState) {
        return _extends({}, prevState, { name: group.name ? group.name : null });
      });
      if (group && group.children && group.children.length > 0) {
        setChildData({ data: group.children, _id: group._id });
        setFilterTopicID(group._id);
      } else {
        //handle filter
        setChildData(null);
        setGrandChildData(null);
        setFilterTopicID(group._id ? group._id : 'all');
      }
    }
    if (type === 'child') {
      setChildData(function (prevState) {
        return _extends({}, prevState, { name: group.name ? group.name : null, _id: group._id });
      });
      if (group && group.grandchildren && group.grandchildren.length > 0) {
        setGrandChildData({ data: group.grandchildren, _id: group._id });
        setFilterTopicID(group._id);
        var topics = [];
        topics.push(group._id);
        group.grandchildren.forEach(function (topic) {
          topics.push(topic._id);
        });
        setFilterTopicID(topics);
      } else {
        //handle filter
        setGrandChildData(null);
        setFilterTopicID(group._id ? group._id : 'all');
      }
    }
    if (type === 'grandchild') {
      setGrandChildData(function (prevState) {
        return _extends({}, prevState, { name: group.name ? group.name : 'All', _id: group._id });
      });
      //handle filter
      if (!group._id) {
        var _topics = [];
        _topics.push(childData._id);
        grandChildData.data.forEach(function (topic) {
          _topics.push(topic._id);
        });
        setFilterTopicID(_topics);
      } else {
        setFilterTopicID([group._id, childData._id]);
      }
    }
  };

  return React__default.createElement(
    'div',
    { className: 'flex-container' },
    parentData && React__default.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn', title: parentData.name ? parentData.name : 'Filter By Category' },
      React__default.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'parent');
          } },
        'All'
      ),
      parentData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'parent');
            } },
          docGroup.name
        );
      })
    ),
    childData && childData.data && childData.data.length > 0 && React__default.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: childData.name ? childData.name : 'Filter By Topic' },
      React__default.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'child');
          } },
        'All'
      ),
      childData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'child');
            } },
          docGroup.name
        );
      })
    ),
    grandChildData && grandChildData.data && grandChildData.data.length > 0 && React__default.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: grandChildData.name ? grandChildData.name : 'Select Sub Topic' },
      React__default.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'grandchild');
          } },
        'All'
      ),
      grandChildData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React__default.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'grandchild');
            } },
          docGroup.name
        );
      })
    ),
    React__default.createElement(
      'style',
      { jsx: 'true' },
      '\n        .flex-container {\n          display: flex;\n          flex-direction: row;\n          align-items: center;\n        }\n        .filter-btn button {\n          border-radius: 3px;\n          z-index: 99999;\n        }\n        .filter-btn .dropdown-menu {\n          z-index: 9999999;\n        }\n        @media (max-width: 768px) {\n          .flex-container {\n            flex-direction: column;\n            align-items: flex-start;\n          }\n        }\n      '
    )
  );
};

var MediaSeriesLanding = function MediaSeriesLanding(props) {
  var client = props.client,
      pageview = props.pageview;

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      filterTopicID = _useState8[0],
      setFilterTopicID = _useState8[1];

  var _useState9 = useState(props.seriesData),
      _useState10 = _slicedToArray(_useState9, 2),
      seriesData = _useState10[0],
      setSeriesData = _useState10[1];

  var _useState11 = useState(props.totalSeriesCount),
      _useState12 = _slicedToArray(_useState11, 2),
      totalSeriesCount = _useState12[0],
      setTotalSeriesCount = _useState12[1];

  var _useState13 = useState(props.params),
      _useState14 = _slicedToArray(_useState13, 2),
      params = _useState14[0],
      setParams = _useState14[1];

  var _useState15 = useState(props.query),
      _useState16 = _slicedToArray(_useState15, 2),
      query = _useState16[0],
      setQuery = _useState16[1];

  var _useState17 = useState(props.currentPage),
      _useState18 = _slicedToArray(_useState17, 2),
      currentPage = _useState18[0],
      setCurrentPage = _useState18[1];

  useEffect(function () {
    if (filterTopicID) {
      fetchFilteredData();
    }
  }, [filterTopicID]);

  var fetchFilteredData = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
      var newParams, filterQuery, x, seriesQuerySorts, seriesQueryProjection, seriesQueryFilters, seriesQuery, totalSeriesCountQuery, _ref3, _ref4, newData, newDataCount;

      return regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              newParams = _extends({}, params, { from: 0, to: 30 });
              filterQuery = void 0;

              if ((typeof filterTopicID === 'undefined' ? 'undefined' : _typeof(filterTopicID)) === 'object') {
                filterQuery = '[';
                for (x = 0; x < filterTopicID.length; x++) {
                  filterQuery = filterQuery + (' references(\'' + filterTopicID[x] + '\') ');
                  if (x === filterTopicID.length - 1) {
                    filterQuery = filterQuery + ']';
                  } else {
                    filterQuery = filterQuery + ' || ';
                  }
                }
              } else {
                filterQuery = filterTopicID !== 'all' ? '[references(\'' + filterTopicID + '\')]' : '';
              }

              seriesQuerySorts = props.seriesQuerySorts, seriesQueryProjection = props.seriesQueryProjection;
              seriesQueryFilters = props.seriesQueryFilters;

              seriesQueryFilters = filterQuery ? [seriesQueryFilters, filterQuery] : seriesQueryFilters;
              seriesQuery = ['*'].concat(seriesQueryFilters).concat(seriesQuerySorts).concat(seriesQueryProjection).join('|');
              totalSeriesCountQuery = 'count(' + ['*'].concat(seriesQueryFilters).join('|') + ')';
              _context.next = 10;
              return _Promise.all([client.fetch(seriesQuery, newParams), client.fetch(totalSeriesCountQuery)]);

            case 10:
              _ref3 = _context.sent;
              _ref4 = _slicedToArray(_ref3, 2);
              newData = _ref4[0];
              newDataCount = _ref4[1];


              setParams(newParams);
              setQuery(seriesQuery);
              setSeriesData(newData);
              setTotalSeriesCount(newDataCount);
              setCurrentPage(1);

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

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

  if (props.statusCode === 404) {
    return React__default.createElement(
      'div',
      { className: 'd-flex flex-column align-items-center mt-3' },
      React__default.createElement(
        'h3',
        null,
        '404: Resource not found'
      ),
      React__default.createElement(
        'p',
        null,
        'We seem to have misplaced the page you\'re looking for. Sorry! Please try checking the URL for errors.'
      ),
      React__default.createElement(
        'p',
        null,
        'Click here to',
        React__default.createElement(
          Link,
          { href: '/' },
          React__default.createElement(
            'a',
            { style: { color: 'blue', textDecoration: 'underline' } },
            ' return to homepage.'
          )
        )
      )
    );
  }

  return React__default.createElement(
    'div',
    { className: 'mb-5' },
    props.docGroup && props.docGroup.description && React__default.createElement(BlockContent, { blocks: props.docGroup.description, serializers: getSerializers(client) }),
    props.taxonomyFilter && props.taxonomyFilter && React__default.createElement(
      'div',
      { className: 'filter-btn-container' },
      React__default.createElement(Filter, { setFilterTopicID: setFilterTopicID, filterData: props.taxonomyFilter }),
      React__default.createElement('hr', null)
    ),
    seriesData && React__default.createElement(MasterDeck, {
      deck: MediaSeriesCard,
      variant: 'left',
      defaultImage: '/placeholder.jpg',
      client: client,
      dataRecord: seriesData,
      totalDataCount: totalSeriesCount,
      query: query && query,
      params: params && params,
      currentPage: currentPage,
      pageview: pageview,
      needLargePaginateButtons: props.needLargePaginateButtons,
      seoPaginate: true
    })
  );
};

MediaSeriesLanding.getInitialData = function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(ctx, client, cache, parameters) {
    var urlQuery, pathname, identifier, itemsPerPage, currentPage, start, statusCode, params, docGroupID, seriesQueryFilters, seriesQuerySorts, seriesQueryProjection, seriesQuery, totalSeriesCountQuery, _ref6, _ref7, seriesData, totalSeriesCount, allSeries, buildUsedTopicsArray, usedTopics, taxonomyFilter;

    return regenerator.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            urlQuery = ctx.query, pathname = ctx.pathname;
            identifier = pathname.replace('/', '');
            itemsPerPage = parameters && parameters.itemsPerPage ? parameters.itemsPerPage : 30;
            currentPage = urlQuery.page ? parseInt(urlQuery.page) : 1;
            start = (currentPage - 1) * itemsPerPage;
            statusCode = 200;
            params = {
              count: itemsPerPage,
              from: start,
              to: start + itemsPerPage,
              url: pathname,
              itemsPerPage: itemsPerPage
            };
            _context2.next = 9;
            return client.fetch('*[_type == \'documentGroup\' && identifier.current == \'' + identifier + '\'][0]{\n    _id, \n    isGated,\n    name,\n    description,\n    pixelTrackingCode->\n  }');

          case 9:
            docGroupID = _context2.sent;
            seriesQueryFilters = '[\n    _type == \'documentGroup\' \n    && references(\'' + docGroupID._id + '\') \n    && isSeries != false \n    && isShow != false \n    && defined(published) \n    && published <= now()\n  ]';
            seriesQuerySorts = 'order(published desc) [$from...$to]';
            seriesQueryProjection = '{\n    _id,\n    name,\n    identifier,\n    published,\n    thumbnail{ ..., asset-> },\n    description,\n    topicMapping[]->,\n    isGated,\n    \'parentUrl\': \'' + identifier + '\'\n  }';
            seriesQuery = ['*'].concat(seriesQueryFilters).concat(seriesQuerySorts).concat(seriesQueryProjection).join('|');
            totalSeriesCountQuery = 'count(' + ['*'].concat(seriesQueryFilters).join('|') + ')';
            _context2.next = 17;
            return _Promise.all([client.fetch(seriesQuery, params), client.fetch(totalSeriesCountQuery)]);

          case 17:
            _ref6 = _context2.sent;
            _ref7 = _slicedToArray(_ref6, 2);
            seriesData = _ref7[0];
            totalSeriesCount = _ref7[1];
            _context2.next = 23;
            return client.fetch('*[_type == \'documentGroup\' && references(\'' + docGroupID._id + '\') && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now()) ]  {\n    topicMapping[]->\n  }');

          case 23:
            allSeries = _context2.sent;

            //Take all series topicMapping and put in an array
            buildUsedTopicsArray = function buildUsedTopicsArray(seriesArray) {
              var usedTopics = [];
              for (var x = 0; x < seriesArray.length; x++) {
                if (seriesArray[x].topicMapping && seriesArray[x].topicMapping.length > 0) {
                  seriesArray[x].topicMapping.forEach(function (topic) {
                    if (topic && topic._id) {
                      if (!usedTopics.includes(topic._id)) {
                        usedTopics.push(topic._id);
                      }
                    }
                  });
                }
              }
              return usedTopics;
            };

            usedTopics = buildUsedTopicsArray(allSeries);
            _context2.next = 28;
            return client.fetch('\n  *[_type == \'taxonomy\' && !defined(parent) && isMainTopic]  | order(name asc) {\n    _id,\n    identifier,\n    name,\n    "children": *[_type == \'taxonomy\' && references(^._id)]  | order(name asc) {\n        _id,\n        name,\n        identifier,\n        "grandchildren": *[_type == \'taxonomy\' && references(^._id)] | order(name asc){...}\n      }\t\n    }');

          case 28:
            taxonomyFilter = _context2.sent;


            taxonomyFilter.forEach(function (topic) {
              if (topic.children) {
                topic.children.forEach(function (child) {
                  if (child.grandchildren) {
                    child.grandchildren = child.grandchildren.filter(function (grandchild) {
                      if (!usedTopics.includes(grandchild._id)) {
                        return false;
                      }
                      return true;
                    });
                  }
                  if (!usedTopics.includes(child._id) || !child.grandchildren) {
                    child._id = null;
                    child.name = null;
                  }
                });

                topic.children = topic.children.filter(function (child) {
                  return child._id !== null;
                });
              }
            });

            if (currentPage > 1 && seriesData.length === 0) {
              statusCode = 404;
            }

            return _context2.abrupt('return', {
              seriesData: seriesData,
              totalSeriesCount: totalSeriesCount,
              query: seriesQuery,
              seriesQueryFilters: seriesQueryFilters,
              seriesQuerySorts: seriesQuerySorts,
              seriesQueryProjection: seriesQueryProjection,
              params: params,
              currentPage: currentPage,
              taxonomyFilter: taxonomyFilter,
              identifier: identifier,
              docGroupID: docGroupID._id,
              parentUrl: identifier,
              statusCode: statusCode,
              docGroup: docGroupID
            });

          case 32:
          case 'end':
            return _context2.stop();
        }
      }
    }, _callee2, _this);
  }));

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

export { MediaSeriesLanding as default };
