import './_commonjsHelpers-0c4b6f40.js';
import './core.get-iterator-method-86d4db69.js';
import './_library-528f1934.js';
import './_iter-detect-130ee549.js';
import './toConsumableArray-32282905.js';
import './_object-pie-33c40e79.js';
import { _ as _extends } from './extends-a4230287.js';
import './_object-sap-8b8ea5a9.js';
import './inherits-91a2c374.js';
import './define-property-6d26cb48.js';
import './web.dom.iterable-f8f967cd.js';
import { _ as _typeof } from './typeof-f1b7564e.js';
import './_is-array-4df618a6.js';
import React, { useState, useEffect } from 'react';
import './index-1819118a.js';
import 'prop-types';
import 'react-bootstrap/Container';
import 'react-bootstrap/Row';
import 'react-bootstrap/Col';
import 'react-bootstrap/Card';
import './moment-b6f49411.js';
import 'next/router';
import './isSymbol-1981418f.js';
import './debounce-9207d8ee.js';
import './toNumber-2f7a84cd.js';
import './index.es-c6222053.js';
import 'react-dom';
import './visibility-sensor-f40c2564.js';
import { _ as _slicedToArray } from './slicedToArray-67a08c9c.js';
import './index-51a80699.js';
import './urlFor.js';
import './index-6c12bdd5.js';
import './main-43ca42fe.js';
import './entities-7cc3bf45.js';
import './stringify-70b72959.js';
import { _ as _asyncToGenerator, r as regenerator } from './asyncToGenerator-64812e90.js';
import './Segment.js';
import './Beam.js';
import './AdSlot.js';
import './ADInfeed-f3a93040.js';
import './lodash-ec8c6b48.js';
import './ADlgInfeed-c4814c4e.js';
import 'react-bootstrap/Button';
import { B as BlockContent } from './BlockContent-d05b5b23.js';
import './index-c7e2ac95.js';
import './smoothscroll-0cd4c7a6.js';
import './GroupDeck.js';
import 'react-bootstrap';
import './iconBase-602d52fe.js';
import './index.esm-55f22b35.js';
import { g as getSerializers } from './index-85bb0372.js';
import './util-7700fc59.js';
import './urlForFile-d2a27665.js';
import './brightcove-react-player-loader.es-4abff0b1.js';
import 'react-bootstrap/Modal';
import 'react-bootstrap/Form';
import 'next/head';
import 'react-share';
import './SocialShare.js';
import './_object-to-array-c54dd835.js';
import 'react-bootstrap/Pagination';
import 'react-bootstrap/Figure';
import 'react-bootstrap/OverlayTrigger';
import 'react-bootstrap/Tooltip';
import 'react-bootstrap/Popover';
import 'react-script-tag';
import MasterDeck from './MasterDeck.js';
import './style-inject.es-1f59c1d0.js';
import { M as MediaSeriesCard, D as DropdownButton, a as Dropdown } from './MediaSeriesCard-4ba5bde7.js';
import Link from 'next/link';

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.createElement(
    'div',
    { className: 'flex-container' },
    parentData && React.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn', title: parentData.name ? parentData.name : 'Filter By Category' },
      React.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'parent');
          } },
        'All'
      ),
      parentData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'parent');
            } },
          docGroup.name
        );
      })
    ),
    childData && childData.data && childData.data.length > 0 && React.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: childData.name ? childData.name : 'Filter By Topic' },
      React.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'child');
          } },
        'All'
      ),
      childData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'child');
            } },
          docGroup.name
        );
      })
    ),
    grandChildData && grandChildData.data && grandChildData.data.length > 0 && React.createElement(
      DropdownButton,
      { drop: 'down', style: { borderRadius: '3px' }, className: 'filter-btn ml-3', title: grandChildData.name ? grandChildData.name : 'Select Sub Topic' },
      React.createElement(
        Dropdown.Item,
        { onSelect: function onSelect() {
            return handleFilterSelect({}, 'grandchild');
          } },
        'All'
      ),
      grandChildData.data.map(function (docGroup) {
        if (!docGroup._id) return null;
        return React.createElement(
          Dropdown.Item,
          { key: docGroup._id, onSelect: function onSelect() {
              return handleFilterSelect(docGroup, 'grandchild');
            } },
          docGroup.name
        );
      })
    ),
    React.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.createElement(
      'div',
      { className: 'd-flex flex-column align-items-center mt-3' },
      React.createElement(
        'h3',
        null,
        '404: Resource not found'
      ),
      React.createElement(
        'p',
        null,
        'We seem to have misplaced the page you\'re looking for. Sorry! Please try checking the URL for errors.'
      ),
      React.createElement(
        'p',
        null,
        'Click here to',
        React.createElement(
          Link,
          { href: '/' },
          React.createElement(
            'a',
            { style: { color: 'blue', textDecoration: 'underline' } },
            ' return to homepage.'
          )
        )
      )
    );
  }

  return React.createElement(
    'div',
    { className: 'mb-5' },
    props.docGroup && props.docGroup.description && React.createElement(BlockContent, { blocks: props.docGroup.description, serializers: getSerializers(client) }),
    props.taxonomyFilter && props.taxonomyFilter && React.createElement(
      'div',
      { className: 'filter-btn-container' },
      React.createElement(Filter, { setFilterTopicID: setFilterTopicID, filterData: props.taxonomyFilter }),
      React.createElement('hr', null)
    ),
    seriesData && React.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, req, 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, req = ctx.req;
            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;
