import { _ as _asyncToGenerator, r as regenerator } 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-06c6251a.js';
import './index-98ca9cec.js';
import 'react-dom';
import Link from 'next/link';
import MasterDeck from './MasterDeck.js';
import { B as BlockContent } from './BlockContent-1e73bd2c.js';
import { g as getSerializers } from './index-6dc67bdb.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 './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/Row';
import 'react-bootstrap/Col';
import 'react-bootstrap/Card';
import 'next/router';
import './lodash-f97fd99a.js';
import './debounce-533d9748.js';
import './isSymbol-a7e9aafe.js';
import './toNumber-5aeba6e7.js';
import './index.es-a6137319.js';
import './visibility-sensor-72fd8f8b.js';
import './ADlgInfeed-ebcafb85.js';
import './AdSlot.js';
import './Beam.js';
import './stringify-2b084bee.js';
import './Segment.js';
import './main-1894c974.js';
import './ADInfeed-7af1f934.js';
import 'react-bootstrap';
import './index-c7e2ac95.js';
import './util-8ed16d48.js';
import './urlForFile-b69adffc.js';
import './brightcove-react-player-loader.es-57a70a56.js';
import 'react-bootstrap/Modal';
import 'react-bootstrap/Button';
import 'react-bootstrap/Form';
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 './index.esm-eb1e8e80.js';
import './iconBase-ccc56b97.js';
import 'react-bootstrap/Figure';
import 'react-bootstrap/OverlayTrigger';
import 'react-bootstrap/Tooltip';
import 'react-bootstrap/Popover';

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,
      currentPage = props.currentPage,
      docGroupID = props.docGroupID,
      parentUrl = props.parentUrl;

  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.params),
      _useState12 = _slicedToArray(_useState11, 2),
      params = _useState12[0],
      setParams = _useState12[1];

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

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

  var fetchFilteredData = function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
      var newParams, filterQuery, x, seriesQuery, newData;
      return regenerator.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              newParams = _extends({}, params, { from: 0, to: 10 });
              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 + '\')' : '';
              }

              seriesQuery = '*[_type == \'documentGroup\' && references(\'' + docGroupID + '\') ' + filterQuery + ' && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now())] | order(published desc) [$from...$to] {\n      _id,\n      name,\n      identifier,\n      published,\n      thumbnail{..., asset-> },\n      description,\n      topicMapping[]->,\n      \'pageNumber\': ' + currentPage + ',\n      \'parentUrl\': \'' + parentUrl + '\'\n  }';
              _context.next = 6;
              return client.fetch(seriesQuery, newParams);

            case 6:
              newData = _context.sent;

              setParams(newParams);
              setQuery(seriesQuery);
              setSeriesData(newData);

            case 10:
            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,
      query: query && query,
      params: params && params,
      currentPage: currentPage,
      pageview: pageview,
      autoScroll: true,
      seoPaginate: true
    })
  );
};

MediaSeriesLanding.getInitialData = function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(ctx, client, cache) {
    var urlQuery, pathname, identifier, itemsPerPage, currentPage, start, statusCode, params, docGroupID, seriesQuery, seriesData, 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 = 10;
            currentPage = urlQuery.page ? parseInt(urlQuery.page) : 1;
            start = (currentPage - 1) * itemsPerPage;
            statusCode = 200;
            params = {
              count: itemsPerPage,
              from: start,
              to: start + itemsPerPage,
              url: pathname
            };
            _context2.next = 9;
            return client.fetch('*[_type == \'documentGroup\' && identifier.current == \'' + identifier + '\'][0]{\n    _id, \n    isGated,\n    name,\n    description\n  }');

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

          case 13:
            seriesData = _context2.sent;
            _context2.next = 16;
            return client.fetch('*[_type == \'documentGroup\' && references(\'' + docGroupID._id + '\') && isSeries != false && isShow != false && defined(published) && dateTime(published) <= dateTime(now()) ]  {\n    topicMapping[]->\n  }');

          case 16:
            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.forEach(function (topic) {
                    if (!usedTopics.includes(topic._id)) {
                      usedTopics.push(topic._id);
                    }
                  });
                }
              }
              return usedTopics;
            };

            usedTopics = buildUsedTopicsArray(allSeries);
            _context2.next = 21;
            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 21:
            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,
              query: seriesQuery,
              params: params,
              currentPage: currentPage,
              taxonomyFilter: taxonomyFilter,
              identifier: identifier,
              docGroupID: docGroupID._id,
              parentUrl: identifier,
              statusCode: statusCode,
              docGroup: docGroupID
            });

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

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

export default MediaSeriesLanding;
