import * as React from 'react';
import React__default, { Component } from 'react';
import PropTypes from 'prop-types';
import * as icons from '@pie-lib/icons';
import Popover from '@material-ui/core/Popover';
import { withStyles, createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import classNames from 'classnames';
import green from '@material-ui/core/colors/green';
import orange from '@material-ui/core/colors/orange';
import pink from '@material-ui/core/colors/pink';
import indigo from '@material-ui/core/colors/indigo';
import red from '@material-ui/core/colors/red';
import debug from 'debug';
import { withStyles as withStyles$1 } from '@material-ui/core/styles/index';
import Collapse from '@material-ui/core/Collapse/index';
import { renderMath } from '@pie-lib/math-rendering';
import Button from '@material-ui/core/Button';
import require$$3 from '@material-ui/core/SvgIcon';
import isEmpty from 'lodash/isEmpty';
import InputLabel from '@material-ui/core/InputLabel';
import FormControl from '@material-ui/core/FormControl';

const defaults = {
  TEXT: 'black',
  DISABLED: 'grey',
  DISABLED_SECONDARY: '#ABABAB',
  CORRECT: green[500],
  CORRECT_SECONDARY: green[50],
  CORRECT_TERTIARY: '#0EA449',
  CORRECT_WITH_ICON: '#087D38',
  INCORRECT: orange[500],
  INCORRECT_SECONDARY: red[50],
  INCORRECT_WITH_ICON: '#BF0D00',
  MISSING: red[700],
  MISSING_WITH_ICON: '#6A78A1',
  PRIMARY: indigo[500],
  PRIMARY_LIGHT: indigo[200],
  PRIMARY_DARK: indigo[800],
  SECONDARY: pink.A400,
  SECONDARY_LIGHT: pink[200],
  SECONDARY_DARK: pink[900],
  TERTIARY: '#146EB3',
  TERTIARY_LIGHT: '#D0E2F0',
  BACKGROUND: 'rgba(255,255,255,0)',
  BACKGROUND_DARK: '#ECEDF1',
  DROPDOWN_BACKGROUND: '#E0E1E6',
  // this is used for inline-dropdown
  // this is only used for multi-trait-rubric, we might want to use BACKGROUND_DARK instead
  SECONDARY_BACKGROUND: 'rgba(241,241,241,1)',
  BORDER: '#9A9A9A',
  BORDER_LIGHT: '#D1D1D1',
  BORDER_DARK: '#646464',
  BORDER_GRAY: '#7E8494',
  BLACK: '#000000',
  WHITE: '#ffffff',
  TRANSPARENT: 'transparent',
  // this is used for multiple-choice accessibility
  FOCUS_CHECKED: '#BBDEFB',
  FOCUS_CHECKED_BORDER: '#1565C0',
  FOCUS_UNCHECKED: '#E0E0E0',
  FOCUS_UNCHECKED_BORDER: '#757575',
  // this is used for select text tokens
  BLUE_GREY100: '#F3F5F7',
  BLUE_GREY300: '#C0C3CF',
  BLUE_GREY600: '#7E8494',
  BLUE_GREY900: '#152452',
  // this is used for charting
  FADED_PRIMARY: '#DCDAFB'
};
Object.freeze(defaults);
const v = prefix => (...args) => {
  const fallback = args.pop();
  return args.reduceRight((acc, v) => {
    return `var(--${prefix}-${v}, ${acc})`;
  }, fallback);
};
const pv = v('pie');
const text = () => pv('text', defaults.TEXT);
const disabled = () => pv('disabled', defaults.DISABLED);
const disabledSecondary = () => pv('disabled-secondary', defaults.DISABLED_SECONDARY);
const correct = () => pv('correct', defaults.CORRECT);
const correctSecondary = () => pv('correct-secondary', defaults.CORRECT_SECONDARY);
const correctTertiary = () => pv('correct-tertiary', defaults.CORRECT_TERTIARY);
const correctWithIcon = () => pv('correct-icon', defaults.CORRECT_WITH_ICON);
const incorrect = () => pv('incorrect', defaults.INCORRECT);
const incorrectWithIcon = () => pv('incorrect-icon', defaults.INCORRECT_WITH_ICON);
const incorrectSecondary = () => pv('incorrect-secondary', defaults.INCORRECT_SECONDARY);
const missing = () => pv('missing', defaults.MISSING);
const missingWithIcon = () => pv('missing-icon', defaults.MISSING_WITH_ICON);
const primary = () => pv('primary', defaults.PRIMARY);
const primaryLight = () => pv('primary-light', defaults.PRIMARY_LIGHT);
const primaryDark = () => pv('primary-dark', defaults.PRIMARY_DARK);
const primaryText = () => pv('primary-text', 'text', defaults.TEXT);
const fadedPrimary = () => pv('faded-primary', defaults.FADED_PRIMARY);
const secondary = () => pv('secondary', defaults.SECONDARY);
const secondaryLight = () => pv('secondary-light', defaults.SECONDARY_LIGHT);
const secondaryDark = () => pv('secondary-dark', defaults.SECONDARY_DARK);
const secondaryText = () => pv('secondary-text', 'text', defaults.TEXT);
const background = () => pv('background', defaults.BACKGROUND);
const backgroundDark = () => pv('background-dark', defaults.BACKGROUND_DARK);
const secondaryBackground = () => pv('secondary-background', defaults.SECONDARY_BACKGROUND);
const dropdownBackground = () => pv('dropdown-background', defaults.DROPDOWN_BACKGROUND);
const tertiary = () => pv('tertiary', defaults.TERTIARY);
const tertiaryLight = () => pv('tertiary-light', defaults.TERTIARY_LIGHT);
const border = () => pv('border', defaults.BORDER);
const borderLight = () => pv('border-light', defaults.BORDER_LIGHT);
const borderDark = () => pv('border-dark', defaults.BORDER_DARK);
const borderGray = () => pv('border-gray', defaults.BORDER_GRAY);
const black = () => pv('black', defaults.BLACK);
const white = () => pv('white', defaults.WHITE);
const transparent = () => defaults.TRANSPARENT;
const focusChecked = () => pv('focus-checked', defaults.FOCUS_CHECKED);
const focusCheckedBorder = () => pv('focus-checked-border', defaults.FOCUS_CHECKED_BORDER);
const focusUnchecked = () => pv('focus-unchecked', defaults.FOCUS_UNCHECKED);
const focusUncheckedBorder = () => pv('focus-unchecked-border', defaults.FOCUS_UNCHECKED_BORDER);
const blueGrey100 = () => pv('blue-grey-100', defaults.BLUE_GREY100);
const blueGrey300 = () => pv('blue-grey-300', defaults.BLUE_GREY300);
const blueGrey600 = () => pv('blue-grey-600', defaults.BLUE_GREY600);
const blueGrey900 = () => pv('blue-grey-900', defaults.BLUE_GREY900);
const visualElementsColors = {
  AXIS_LINE_COLOR: '#5A53C9',
  ROLLOVER_FILL_BAR_COLOR: '#050F2D',
  GRIDLINES_COLOR: '#8E88EA',
  PLOT_FILL_COLOR: '#1463B3'
};

var color = /*#__PURE__*/Object.freeze({
  __proto__: null,
  background: background,
  backgroundDark: backgroundDark,
  black: black,
  blueGrey100: blueGrey100,
  blueGrey300: blueGrey300,
  blueGrey600: blueGrey600,
  blueGrey900: blueGrey900,
  border: border,
  borderDark: borderDark,
  borderGray: borderGray,
  borderLight: borderLight,
  correct: correct,
  correctSecondary: correctSecondary,
  correctTertiary: correctTertiary,
  correctWithIcon: correctWithIcon,
  defaults: defaults,
  disabled: disabled,
  disabledSecondary: disabledSecondary,
  dropdownBackground: dropdownBackground,
  fadedPrimary: fadedPrimary,
  focusChecked: focusChecked,
  focusCheckedBorder: focusCheckedBorder,
  focusUnchecked: focusUnchecked,
  focusUncheckedBorder: focusUncheckedBorder,
  incorrect: incorrect,
  incorrectSecondary: incorrectSecondary,
  incorrectWithIcon: incorrectWithIcon,
  missing: missing,
  missingWithIcon: missingWithIcon,
  primary: primary,
  primaryDark: primaryDark,
  primaryLight: primaryLight,
  primaryText: primaryText,
  secondary: secondary,
  secondaryBackground: secondaryBackground,
  secondaryDark: secondaryDark,
  secondaryLight: secondaryLight,
  secondaryText: secondaryText,
  tertiary: tertiary,
  tertiaryLight: tertiaryLight,
  text: text,
  transparent: transparent,
  v: v,
  visualElementsColors: visualElementsColors,
  white: white
});

/**
 * Lifted from multiple-choice - TODO: create a shared package for it.
 */
const styleSheet = {
  corespringFeedback: {
    transformOrigin: '0% 0px 0px',
    width: '100%',
    display: 'block',
    overflow: 'hidden',
    '&:.incorrect': {
      color: '#946202'
    }
  },
  content: {
    '-webkit-font-smoothing': 'antialiased',
    backgroundColor: `var(--feedback-bg-color, ${disabled()})`,
    borderRadius: '4px',
    fontFamily: '"Roboto", "Noto", sans-serif',
    lineHeight: '25px',
    margin: '0px',
    padding: '10px',
    verticalAlign: 'middle',
    color: 'var(--feedback-color, white)'
  },
  correct: {
    backgroundColor: `var(--feedback-correct-bg-color, ${correct()})`
  },
  incorrect: {
    backgroundColor: `var(--feedback-incorrect-bg-color, ${incorrect()})`
  },
  feedbackEnter: {
    height: '1px'
  },
  feedbackEnterActive: {
    height: '45px',
    transition: 'height 500ms'
  },
  feedbackLeave: {
    height: '45px'
  },
  feedbackLeaveActive: {
    height: '1px',
    transition: 'height 200ms'
  }
};
class Feedback extends React__default.Component {
  render() {
    const {
      correctness,
      feedback,
      classes
    } = this.props;

    function chooseFeedback(correctness) {
      if (correctness && feedback) {
        return /*#__PURE__*/React__default.createElement(CSSTransition, {
          classNames: {
            enter: classes.feedbackEnter,
            enterActive: classes.feedbackEnterActive,
            leave: classes.feedbackLeave,
            leaveActive: classes.feedbackLeaveActive
          },
          key: "hasFeedback",
          timeout: {
            enter: 500,
            exit: 300
          }
        }, /*#__PURE__*/React__default.createElement("div", {
          className: classes.corespringFeedback
        }, /*#__PURE__*/React__default.createElement("div", {
          className: classNames(classes.content, classes[correctness]),
          dangerouslySetInnerHTML: {
            __html: feedback
          }
        })));
      } else {
        return null;
      }
    }

    return /*#__PURE__*/React__default.createElement("div", null, /*#__PURE__*/React__default.createElement(TransitionGroup, null, chooseFeedback(correctness)));
  }

}
Feedback.propTypes = {
  correctness: PropTypes.string,
  feedback: PropTypes.string,
  classes: PropTypes.object.isRequired
};
var Feedback$1 = withStyles(styleSheet, {
  name: 'Feedback'
})(Feedback);

const log = debug('pie-libs:render-ui:response-indicators');

const styles$4 = () => ({
  responseIndicator: {
    cursor: 'pointer'
  },
  paper: {
    padding: '0',
    borderRadius: '4px'
  },
  popover: {
    cursor: 'pointer'
  },
  popperClose: {
    cursor: 'pointer'
  }
});

const BuildIndicator = (Icon, correctness) => {
  class RawIndicator extends React__default.Component {
    constructor(props) {
      super(props);

      this.handlePopoverOpen = event => {
        log('[handlePopoverOpen]', event.target);
        this.setState({
          anchorEl: event.target
        });
      };

      this.handlePopoverClose = () => {
        this.setState({
          anchorEl: null
        });
      };

      this.state = {};
    }

    render() {
      const {
        feedback,
        classes
      } = this.props;
      const {
        anchorEl
      } = this.state;
      return /*#__PURE__*/React__default.createElement("div", {
        className: feedback && classes.responseIndicator
      }, /*#__PURE__*/React__default.createElement("span", {
        ref: r => this.icon = r,
        onClick: this.handlePopoverOpen
      }, /*#__PURE__*/React__default.createElement(Icon, null)), feedback && /*#__PURE__*/React__default.createElement(Popover, {
        className: classes.popover,
        classes: {
          paper: classes.paper
        },
        open: !!anchorEl,
        anchorEl: anchorEl,
        anchorOrigin: {
          vertical: 'bottom',
          horizontal: 'left'
        },
        transformOrigin: {
          vertical: 'top',
          horizontal: 'left'
        },
        onClose: this.handlePopoverClose
      }, /*#__PURE__*/React__default.createElement(Feedback$1, {
        feedback: feedback,
        correctness: correctness
      })));
    }

  }

  RawIndicator.propTypes = {
    feedback: PropTypes.string,
    classes: PropTypes.object.isRequired
  };
  return withStyles(styles$4)(RawIndicator);
};

const Correct = BuildIndicator(icons.Correct, 'correct');
const Incorrect = BuildIndicator(icons.Incorrect, 'incorrect');
const PartiallyCorrect = BuildIndicator(icons.PartiallyCorrect, 'partially-correct');
const NothingSubmitted = BuildIndicator(icons.NothingSubmitted, 'nothing-submitted');

var responseIndicators = /*#__PURE__*/Object.freeze({
  __proto__: null,
  Correct: Correct,
  Incorrect: Incorrect,
  NothingSubmitted: NothingSubmitted,
  PartiallyCorrect: PartiallyCorrect
});

class Collapsible extends React__default.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      expanded: false
    };

    this.toggleExpanded = () => {
      this.setState(state => ({
        expanded: !state.expanded
      }));
    };
  }

  componentDidMount() {
    renderMath(this.root);
  }

  componentDidUpdate() {
    renderMath(this.root);
  }

  render() {
    const {
      classes,
      labels,
      children,
      className
    } = this.props;
    const title = this.state.expanded ? labels.visible || 'Hide' : labels.hidden || 'Show';
    return /*#__PURE__*/React__default.createElement("div", {
      className: className,
      ref: r => this.root = r
    }, /*#__PURE__*/React__default.createElement("div", {
      onClick: this.toggleExpanded
    }, /*#__PURE__*/React__default.createElement("span", {
      className: classes.title
    }, title)), /*#__PURE__*/React__default.createElement(Collapse, {
      in: this.state.expanded,
      timeout: "auto",
      unmountOnExit: true,
      className: classes.collapsible
    }, children));
  }

}
Collapsible.propTypes = {
  classes: PropTypes.object.isRequired,
  className: PropTypes.string,
  children: PropTypes.object,
  labels: PropTypes.shape({
    visible: PropTypes.string,
    hidden: PropTypes.string
  })
};
Collapsible.defaultProps = {
  labels: {}
};
var index = withStyles$1(theme => ({
  title: {
    color: theme.palette.primary.light,
    borderBottom: `1px dotted ${theme.palette.primary.light}`,
    cursor: 'pointer'
  },
  collapsible: {
    paddingTop: theme.spacing.unit * 2
  }
}))(Collapsible);

function _extends() {
  _extends = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  return _extends.apply(this, arguments);
}

function _objectWithoutPropertiesLoose(source, excluded) {
  if (source == null) return {};
  var target = {};
  var sourceKeys = Object.keys(source);
  var key, i;

  for (i = 0; i < sourceKeys.length; i++) {
    key = sourceKeys[i];
    if (excluded.indexOf(key) >= 0) continue;
    target[key] = source[key];
  }

  return target;
}

function getDefaultExportFromCjs (x) {
	return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}

var Restore$1 = {};

var interopRequireDefault = {exports: {}};

var hasRequiredInteropRequireDefault;

function requireInteropRequireDefault () {
	if (hasRequiredInteropRequireDefault) return interopRequireDefault.exports;
	hasRequiredInteropRequireDefault = 1;
	(function (module) {
		function _interopRequireDefault(obj) {
		  return obj && obj.__esModule ? obj : {
		    "default": obj
		  };
		}

		module.exports = _interopRequireDefault, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (interopRequireDefault));
	return interopRequireDefault.exports;
}

var createSvgIcon = {};

var pure = {};

var shouldUpdate = {};

var inheritsLoose = {exports: {}};

var setPrototypeOf = {exports: {}};

var hasRequiredSetPrototypeOf;

function requireSetPrototypeOf () {
	if (hasRequiredSetPrototypeOf) return setPrototypeOf.exports;
	hasRequiredSetPrototypeOf = 1;
	(function (module) {
		function _setPrototypeOf(o, p) {
		  module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
		    o.__proto__ = p;
		    return o;
		  }, module.exports.__esModule = true, module.exports["default"] = module.exports;
		  return _setPrototypeOf(o, p);
		}

		module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (setPrototypeOf));
	return setPrototypeOf.exports;
}

var hasRequiredInheritsLoose;

function requireInheritsLoose () {
	if (hasRequiredInheritsLoose) return inheritsLoose.exports;
	hasRequiredInheritsLoose = 1;
	(function (module) {
		var setPrototypeOf = requireSetPrototypeOf();

		function _inheritsLoose(subClass, superClass) {
		  subClass.prototype = Object.create(superClass.prototype);
		  subClass.prototype.constructor = subClass;
		  setPrototypeOf(subClass, superClass);
		}

		module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; 
	} (inheritsLoose));
	return inheritsLoose.exports;
}

var setDisplayName = {};

var setStatic = {};

var hasRequiredSetStatic;

function requireSetStatic () {
	if (hasRequiredSetStatic) return setStatic;
	hasRequiredSetStatic = 1;

	setStatic.__esModule = true;
	setStatic.default = void 0;

	var setStatic$1 = function setStatic(key, value) {
	  return function (BaseComponent) {
	    /* eslint-disable no-param-reassign */
	    BaseComponent[key] = value;
	    /* eslint-enable no-param-reassign */

	    return BaseComponent;
	  };
	};

	var _default = setStatic$1;
	setStatic.default = _default;
	return setStatic;
}

var hasRequiredSetDisplayName;

function requireSetDisplayName () {
	if (hasRequiredSetDisplayName) return setDisplayName;
	hasRequiredSetDisplayName = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	setDisplayName.__esModule = true;
	setDisplayName.default = void 0;

	var _setStatic = _interopRequireDefault(requireSetStatic());

	var setDisplayName$1 = function setDisplayName(displayName) {
	  return (0, _setStatic.default)('displayName', displayName);
	};

	var _default = setDisplayName$1;
	setDisplayName.default = _default;
	return setDisplayName;
}

var wrapDisplayName = {};

var getDisplayName = {};

var hasRequiredGetDisplayName;

function requireGetDisplayName () {
	if (hasRequiredGetDisplayName) return getDisplayName;
	hasRequiredGetDisplayName = 1;

	getDisplayName.__esModule = true;
	getDisplayName.default = void 0;

	var getDisplayName$1 = function getDisplayName(Component) {
	  if (typeof Component === 'string') {
	    return Component;
	  }

	  if (!Component) {
	    return undefined;
	  }

	  return Component.displayName || Component.name || 'Component';
	};

	var _default = getDisplayName$1;
	getDisplayName.default = _default;
	return getDisplayName;
}

var hasRequiredWrapDisplayName;

function requireWrapDisplayName () {
	if (hasRequiredWrapDisplayName) return wrapDisplayName;
	hasRequiredWrapDisplayName = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	wrapDisplayName.__esModule = true;
	wrapDisplayName.default = void 0;

	var _getDisplayName = _interopRequireDefault(requireGetDisplayName());

	var wrapDisplayName$1 = function wrapDisplayName(BaseComponent, hocName) {
	  return hocName + "(" + (0, _getDisplayName.default)(BaseComponent) + ")";
	};

	var _default = wrapDisplayName$1;
	wrapDisplayName.default = _default;
	return wrapDisplayName;
}

var hasRequiredShouldUpdate;

function requireShouldUpdate () {
	if (hasRequiredShouldUpdate) return shouldUpdate;
	hasRequiredShouldUpdate = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	shouldUpdate.__esModule = true;
	shouldUpdate.default = void 0;

	var _inheritsLoose2 = _interopRequireDefault(requireInheritsLoose());

	var _react = React__default;

	var _setDisplayName = _interopRequireDefault(requireSetDisplayName());

	var _wrapDisplayName = _interopRequireDefault(requireWrapDisplayName());

	var shouldUpdate$1 = function shouldUpdate(test) {
	  return function (BaseComponent) {
	    var factory = (0, _react.createFactory)(BaseComponent);

	    var ShouldUpdate =
	    /*#__PURE__*/
	    function (_Component) {
	      (0, _inheritsLoose2.default)(ShouldUpdate, _Component);

	      function ShouldUpdate() {
	        return _Component.apply(this, arguments) || this;
	      }

	      var _proto = ShouldUpdate.prototype;

	      _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps) {
	        return test(this.props, nextProps);
	      };

	      _proto.render = function render() {
	        return factory(this.props);
	      };

	      return ShouldUpdate;
	    }(_react.Component);

	    if (process.env.NODE_ENV !== 'production') {
	      return (0, _setDisplayName.default)((0, _wrapDisplayName.default)(BaseComponent, 'shouldUpdate'))(ShouldUpdate);
	    }

	    return ShouldUpdate;
	  };
	};

	var _default = shouldUpdate$1;
	shouldUpdate.default = _default;
	return shouldUpdate;
}

var shallowEqual = {};

/**
 * Copyright (c) 2013-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @typechecks
 * 
 */

var shallowEqual_1;
var hasRequiredShallowEqual$1;

function requireShallowEqual$1 () {
	if (hasRequiredShallowEqual$1) return shallowEqual_1;
	hasRequiredShallowEqual$1 = 1;

	var hasOwnProperty = Object.prototype.hasOwnProperty;

	/**
	 * inlined Object.is polyfill to avoid requiring consumers ship their own
	 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
	 */
	function is(x, y) {
	  // SameValue algorithm
	  if (x === y) {
	    // Steps 1-5, 7-10
	    // Steps 6.b-6.e: +0 != -0
	    // Added the nonzero y check to make Flow happy, but it is redundant
	    return x !== 0 || y !== 0 || 1 / x === 1 / y;
	  } else {
	    // Step 6.a: NaN == NaN
	    return x !== x && y !== y;
	  }
	}

	/**
	 * Performs equality by iterating through keys on an object and returning false
	 * when any key has values which are not strictly equal between the arguments.
	 * Returns true when the values of all keys are strictly equal.
	 */
	function shallowEqual(objA, objB) {
	  if (is(objA, objB)) {
	    return true;
	  }

	  if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
	    return false;
	  }

	  var keysA = Object.keys(objA);
	  var keysB = Object.keys(objB);

	  if (keysA.length !== keysB.length) {
	    return false;
	  }

	  // Test for A's keys different from B.
	  for (var i = 0; i < keysA.length; i++) {
	    if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
	      return false;
	    }
	  }

	  return true;
	}

	shallowEqual_1 = shallowEqual;
	return shallowEqual_1;
}

var hasRequiredShallowEqual;

function requireShallowEqual () {
	if (hasRequiredShallowEqual) return shallowEqual;
	hasRequiredShallowEqual = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	shallowEqual.__esModule = true;
	shallowEqual.default = void 0;

	var _shallowEqual = _interopRequireDefault(requireShallowEqual$1());

	var _default = _shallowEqual.default;
	shallowEqual.default = _default;
	return shallowEqual;
}

var hasRequiredPure;

function requirePure () {
	if (hasRequiredPure) return pure;
	hasRequiredPure = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	pure.__esModule = true;
	pure.default = void 0;

	var _shouldUpdate = _interopRequireDefault(requireShouldUpdate());

	var _shallowEqual = _interopRequireDefault(requireShallowEqual());

	var _setDisplayName = _interopRequireDefault(requireSetDisplayName());

	var _wrapDisplayName = _interopRequireDefault(requireWrapDisplayName());

	var pure$1 = function pure(BaseComponent) {
	  var hoc = (0, _shouldUpdate.default)(function (props, nextProps) {
	    return !(0, _shallowEqual.default)(props, nextProps);
	  });

	  if (process.env.NODE_ENV !== 'production') {
	    return (0, _setDisplayName.default)((0, _wrapDisplayName.default)(BaseComponent, 'pure'))(hoc(BaseComponent));
	  }

	  return hoc(BaseComponent);
	};

	var _default = pure$1;
	pure.default = _default;
	return pure;
}

var hasRequiredCreateSvgIcon;

function requireCreateSvgIcon () {
	if (hasRequiredCreateSvgIcon) return createSvgIcon;
	hasRequiredCreateSvgIcon = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	Object.defineProperty(createSvgIcon, "__esModule", {
	  value: true
	});
	createSvgIcon.default = void 0;

	var _react = _interopRequireDefault(React__default);

	var _pure = _interopRequireDefault(requirePure());

	var _SvgIcon = _interopRequireDefault(require$$3);

	function createSvgIcon$1(path, displayName) {
	  var Icon = function Icon(props) {
	    return _react.default.createElement(_SvgIcon.default, props, path);
	  };

	  Icon.displayName = "".concat(displayName, "Icon");
	  Icon = (0, _pure.default)(Icon);
	  Icon.muiName = 'SvgIcon';
	  return Icon;
	}
	var _default = createSvgIcon$1;
	createSvgIcon.default = _default;
	return createSvgIcon;
}

var hasRequiredRestore;

function requireRestore () {
	if (hasRequiredRestore) return Restore$1;
	hasRequiredRestore = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	Object.defineProperty(Restore$1, "__esModule", {
	  value: true
	});
	Restore$1.default = void 0;

	var _react = _interopRequireDefault(React__default);

	var _createSvgIcon = _interopRequireDefault(/*@__PURE__*/ requireCreateSvgIcon());

	var _default = (0, _createSvgIcon.default)(_react.default.createElement(_react.default.Fragment, null, _react.default.createElement("path", {
	  fill: "none",
	  d: "M0 0h24v24H0z"
	}), _react.default.createElement("path", {
	  d: "M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"
	})), 'Restore');

	Restore$1.default = _default;
	return Restore$1;
}

var RestoreExports = /*@__PURE__*/ requireRestore();
var Restore = /*@__PURE__*/getDefaultExportFromCjs(RestoreExports);

var Undo$1 = {};

var hasRequiredUndo;

function requireUndo () {
	if (hasRequiredUndo) return Undo$1;
	hasRequiredUndo = 1;

	var _interopRequireDefault = requireInteropRequireDefault();

	Object.defineProperty(Undo$1, "__esModule", {
	  value: true
	});
	Undo$1.default = void 0;

	var _react = _interopRequireDefault(React__default);

	var _createSvgIcon = _interopRequireDefault(/*@__PURE__*/ requireCreateSvgIcon());

	var _default = (0, _createSvgIcon.default)(_react.default.createElement(_react.default.Fragment, null, _react.default.createElement("path", {
	  fill: "none",
	  d: "M0 0h24v24H0z"
	}), _react.default.createElement("path", {
	  d: "M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"
	})), 'Undo');

	Undo$1.default = _default;
	return Undo$1;
}

var UndoExports = /*@__PURE__*/ requireUndo();
var Undo = /*@__PURE__*/getDefaultExportFromCjs(UndoExports);

const _excluded$1 = ["classes"];

const styles$3 = theme => ({
  wrapper: {
    display: 'flex',
    flexDirection: 'column'
  },
  resetUndoContainer: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  },
  icon: {
    width: '24px',
    height: '24px',
    color: 'gray',
    marginRight: theme.spacing.unit
  },
  buttonContainer: {
    display: 'flex',
    alignItems: 'center',
    marginLeft: theme.spacing.unit * 3,
    marginRight: theme.spacing.unit * 3
  }
});
/**
 * HOC that adds undo and reset functionality for session values
 */


const withUndoReset = WrappedComponent => {
  class WithUndoReset extends React.Component {
    constructor(props) {
      super(props);

      this.onSessionChange = session => {
        this.setState(state => ({
          session,
          changes: [...state.changes, session]
        }), () => this.props.onSessionChange(session));
      };

      this.onUndo = () => {
        this.setState(state => {
          const newChanges = [...state.changes];
          newChanges.pop();
          return {
            changes: newChanges,
            session: newChanges.length ? newChanges[newChanges.length - 1] : state.sessionInitialValues
          };
        }, () => this.props.onSessionChange(this.state.session));
      };

      this.onReset = () => {
        this.setState(state => ({
          session: state.sessionInitialValues,
          changes: []
        }), () => this.props.onSessionChange(this.state.sessionInitialValues));
      };

      this.state = {
        sessionInitialValues: JSON.parse(JSON.stringify(props.session)),
        session: props.session,
        changes: []
      };
    }

    render() {
      const _this$props = this.props,
            {
        classes
      } = _this$props,
            rest = _objectWithoutPropertiesLoose(_this$props, _excluded$1);

      const {
        changes,
        session
      } = this.state;
      return /*#__PURE__*/React.createElement("div", {
        className: classes.wrapper
      }, /*#__PURE__*/React.createElement("div", {
        className: classes.resetUndoContainer
      }, /*#__PURE__*/React.createElement(Button, {
        className: classes.buttonContainer,
        color: "primary",
        disabled: changes.length === 0,
        onClick: this.onUndo
      }, /*#__PURE__*/React.createElement(Undo, {
        className: classes.icon
      }), " Undo"), /*#__PURE__*/React.createElement(Button, {
        className: classes.buttonContainer,
        color: "primary",
        disabled: changes.length === 0,
        onClick: this.onReset
      }, /*#__PURE__*/React.createElement(Restore, {
        className: classes.icon
      }), " Start Over")), /*#__PURE__*/React.createElement(WrappedComponent, _extends({}, rest, {
        session: session,
        onSessionChange: this.onSessionChange
      })));
    }

  }

  WithUndoReset.propTypes = {
    classes: PropTypes.object,
    session: PropTypes.object,
    onSessionChange: PropTypes.func
  };
  return withStyles(styles$3)(WithUndoReset);
};

class ExtraCSSRulesMixin extends React__default.Component {
  constructor(props) {
    super(props);

    this.appendExtraStyles = () => {
      if (isEmpty(this.props.extraCSSRules) || !this.classesSheet) {
        return;
      }

      const headElement = document.head || document.getElementsByTagName('head')[0];

      if (!headElement) {
        return;
      }

      if (!this.classesSheet.parentElement) {
        headElement.appendChild(this.classesSheet);
      }

      const {
        extraCSSRules,
        classes
      } = this.props;
      this.classesSheet.innerHTML = `
      .${classes.extraCSSRules} {
        ${extraCSSRules.rules}
      }
    `;
    };

    this.classesSheet = document.createElement('style');
  }

  componentDidMount() {
    this.appendExtraStyles();
  }

}

ExtraCSSRulesMixin.propTypes = {
  extraCSSRules: PropTypes.shape({
    names: PropTypes.arrayOf(PropTypes.string),
    rules: PropTypes.string
  })
};
ExtraCSSRulesMixin.defaultProps = {
  extraCSSRules: {}
};

const _excluded = ["children", "className", "classes", "fontSizeFactor"],
      _excluded2 = ["extraCSSRules"];

class UiLayout extends ExtraCSSRulesMixin {
  constructor(props) {
    super(props);
    this.classesSheet = document.createElement('style');
  }

  computeStyle(fontSizeFactor) {
    const getFontSize = element => parseFloat(getComputedStyle(element).fontSize);

    const rootFontSize = getFontSize(document.documentElement);
    const bodyFontSize = getFontSize(document.body);
    const effectiveFontSize = Math.max(rootFontSize, bodyFontSize);
    return fontSizeFactor !== 1 ? {
      fontSize: `${effectiveFontSize * fontSizeFactor}px`
    } : null;
  }

  render() {
    const _this$props = this.props,
          {
      children,
      className,
      classes,
      fontSizeFactor
    } = _this$props,
          rest = _objectWithoutPropertiesLoose(_this$props, _excluded);

    const finalClass = classNames(className, classes.extraCSSRules, classes.uiLayoutContainer);

    const restProps = _objectWithoutPropertiesLoose(rest, _excluded2);

    const style = this.computeStyle(fontSizeFactor);
    return /*#__PURE__*/React__default.createElement("div", _extends({
      className: finalClass
    }, restProps, style && {
      style
    }), children);
  }

}

UiLayout.propTypes = {
  classes: PropTypes.object,
  className: PropTypes.string,
  children: PropTypes.array,
  extraCSSRules: PropTypes.shape({
    names: PropTypes.arrayOf(PropTypes.string),
    rules: PropTypes.string
  }),
  fontSizeFactor: PropTypes.number
};
UiLayout.defaultProps = {
  extraCSSRules: {},
  fontSizeFactor: 1
};
const styles$2 = {
  extraCSSRules: {},
  // need this because some browsers set their own style on table
  uiLayoutContainer: {
    '& table, th, td': {
      fontSize: 'inherit'
      /* Ensure table elements inherit font size */

    }
  }
};
const Styled$1 = withStyles(styles$2)(UiLayout);

class PreviewLayout extends React__default.Component {
  render() {
    const {
      children,
      classes,
      ariaLabel,
      role,
      extraCSSRules,
      fontSizeFactor
    } = this.props;
    const accessibility = ariaLabel ? {
      'aria-label': ariaLabel,
      role
    } : {};
    return /*#__PURE__*/React__default.createElement(Styled$1, _extends({
      className: classes.container
    }, accessibility, {
      extraCSSRules: extraCSSRules,
      fontSizeFactor: fontSizeFactor
    }), children);
  }

}

PreviewLayout.propTypes = {
  ariaLabel: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
  classes: PropTypes.object,
  role: PropTypes.string,
  extraCSSRules: PropTypes.shape({
    names: PropTypes.arrayOf(PropTypes.string),
    rules: PropTypes.string
  }),
  fontSizeFactor: PropTypes.number
};

const styles$1 = () => ({
  container: {
    display: 'flex',
    flexDirection: 'column',
    position: 'relative'
  }
});

const theme = createMuiTheme({
  typography: {
    useNextVariants: true
  },
  palette: {
    action: {
      disabled: 'rgba(0, 0, 0, 0.54);'
    }
  },
  overrides: {
    MuiRadio: {
      root: {
        '&$checked': {
          color: '#3f51b5 !important'
        }
      }
    },
    MuiCheckbox: {
      root: {
        '&$checked': {
          color: '#3f51b5 !important'
        }
      }
    },
    MuiTabs: {
      root: {
        borderBottom: '1px solid #eee'
      }
    },
    MuiSwitch: {
      root: {
        '&$checked': {
          color: '#3f51b5 !important',
          '& + $bar': {
            backgroundColor: '#3f51b5 !important',
            opacity: 0.5
          }
        }
      }
    }
  }
});
const Styled = withStyles(styles$1)(PreviewLayout);

const RootElem = props => /*#__PURE__*/React__default.createElement(MuiThemeProvider, {
  theme: theme
}, /*#__PURE__*/React__default.createElement(Styled, props));

class HtmlAndMath extends React__default.Component {
  render() {
    const {
      tag,
      className,
      html
    } = this.props;
    const Tag = tag || 'div';
    return /*#__PURE__*/React__default.createElement(Tag, {
      ref: r => this.node = r,
      className: className,
      dangerouslySetInnerHTML: {
        __html: html
      }
    });
  }

}
HtmlAndMath.propTypes = {
  tag: PropTypes.string,
  className: PropTypes.string,
  html: PropTypes.string
};
HtmlAndMath.defaultProps = {
  tag: 'div',
  html: ''
};

const RawInputContainer = props => {
  const {
    label,
    className,
    children,
    classes
  } = props;
  const names = classNames(classes.formControl, className);
  return /*#__PURE__*/React__default.createElement(FormControl, {
    className: names
  }, /*#__PURE__*/React__default.createElement(InputLabel, {
    className: classes.label,
    shrink: true
  }, label), children);
};

RawInputContainer.propTypes = {
  label: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
  className: PropTypes.string,
  children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]).isRequired,
  classes: PropTypes.object.isRequired
};
var inputContainer = withStyles(theme => ({
  formControl: {
    marginLeft: 0,
    marginRight: 0,
    paddingBottom: theme.spacing.unit,
    flex: '1 0 auto',
    minWidth: theme.spacing.unit * 4
  },
  label: {
    fontSize: 'inherit',
    whiteSpace: 'nowrap'
  }
}))(RawInputContainer);

const NEWLINE_BLOCK_REGEX = /\\embed\{newLine\}\[\]/g;
const NEWLINE_LATEX = '\\newline ';
class PreviewPrompt extends Component {
  constructor(...args) {
    super(...args);

    this.parsedText = text => {
      const {
        customAudioButton
      } = this.props;
      const div = document.createElement('div');
      div.innerHTML = text;
      const audio = div.querySelector('audio');

      if (audio) {
        const source = document.createElement('source');
        source.setAttribute('type', 'audio/mp3');
        source.setAttribute('src', audio.getAttribute('src'));
        audio.removeAttribute('src');
        audio.setAttribute('id', 'pie-prompt-audio-player');
        audio.appendChild(source);

        if (customAudioButton) {
          audio.style.display = 'none';
          const playButton = document.createElement('div');
          playButton.id = 'play-audio-button';
          Object.assign(playButton.style, {
            cursor: 'pointer',
            display: 'block',
            width: '128px',
            height: '128px',
            backgroundImage: `url(${customAudioButton.pauseImage})`,
            backgroundSize: 'cover',
            borderRadius: '50%',
            border: '1px solid #326295'
          });
          audio.parentNode.insertBefore(playButton, audio);
        }
      }

      return div.innerHTML;
    };
  }

  addCustomAudioButtonControls() {
    const {
      autoplayAudioEnabled,
      customAudioButton
    } = this.props;
    const playButton = document.getElementById('play-audio-button');
    const audio = document.getElementById('pie-prompt-audio-player');

    if (autoplayAudioEnabled && audio) {
      audio.play().then(() => {
        if (playButton && customAudioButton) {
          audio.addEventListener('ended', handleAudioEnded);
        }
      }).catch(error => {
        console.error('Error playing audio', error);
      });
    }

    if (!playButton || !audio || !customAudioButton) return;

    const handlePlayClick = () => {
      // if already playing, don't play again
      if (!audio.paused) return;
      if (playButton.style.backgroundImage.includes(customAudioButton.pauseImage)) return;
      audio.play();
    };

    const handleAudioEnded = () => {
      playButton.style.backgroundImage = `url(${customAudioButton.playImage})`;
    };

    const handleAudioPlay = () => {
      Object.assign(playButton.style, {
        backgroundImage: `url(${customAudioButton.pauseImage})`,
        border: '1px solid #ccc'
      });
    };

    const handleAudioPause = () => {
      Object.assign(playButton.style, {
        backgroundImage: `url(${customAudioButton.playImage})`,
        border: '1px solid #326295'
      });
    };

    playButton.addEventListener('click', handlePlayClick);
    audio.addEventListener('play', handleAudioPlay);
    audio.addEventListener('pause', handleAudioPause);
    audio.addEventListener('ended', handleAudioEnded); // store event handler references so they can be removed later

    this._handlePlayClick = handlePlayClick;
    this._handleAudioPlay = handleAudioPlay;
    this._handleAudioPause = handleAudioPause;
    this._handleAudioEnded = handleAudioEnded;
  }

  removeCustomAudioButtonListeners() {
    const playButton = document.getElementById('play-audio-button');
    const audio = document.querySelector('audio');
    if (!playButton || !audio) return; // remove event listeners using stored references

    playButton.removeEventListener('click', this._handlePlayClick);
    audio.removeEventListener('play', this._handleAudioPlay);
    audio.removeEventListener('pause', this._handleAudioPause);
    audio.removeEventListener('ended', this._handleAudioEnded);
  }

  componentDidMount() {
    this.alignImages();
    this.addCustomAudioButtonControls();
  }

  componentDidUpdate() {
    this.alignImages();
  }

  componentWillUnmount() {
    this.removeCustomAudioButtonListeners();
  }

  alignImages() {
    const previewPrompts = document.querySelectorAll('#preview-prompt');
    previewPrompts.forEach(previewPrompt => {
      const images = previewPrompt.getElementsByTagName('img');

      if (images && images.length) {
        for (let image of images) {
          // check if alignment property was set
          if (image.attributes && image.attributes.alignment && image.attributes.alignment.value) {
            const parentNode = image.parentElement; // check if div is not already added to dom and replace current image with wrapped image

            if (!(parentNode.tagName === 'DIV' && parentNode.style.display === 'flex' && parentNode.style.width === '100%')) {
              const div = document.createElement('div');
              div.style.display = 'flex';
              div.style.width = '100%';
              const copyImage = image.cloneNode(true);
              div.appendChild(copyImage);
              parentNode.replaceChild(div, image);
            }
          }
        }
      }
    });
  }

  render() {
    const {
      prompt,
      classes,
      tagName,
      className,
      onClick,
      defaultClassName
    } = this.props;
    const CustomTag = tagName || 'div'; // legend tag was added once with accessibility tasks, wee need extra style to make it work with images alignment

    const legendClass = tagName === 'legend' ? 'legend' : '';
    const customClasses = `${classes.promptTable} ${classes[className] || ''} ${defaultClassName || ''} ${classes[legendClass] || ''}`;
    return /*#__PURE__*/React__default.createElement(CustomTag, {
      id: 'preview-prompt',
      onClick: onClick,
      className: customClasses,
      dangerouslySetInnerHTML: {
        __html: this.parsedText(prompt || '').replace(NEWLINE_BLOCK_REGEX, NEWLINE_LATEX)
      }
    });
  }

}
PreviewPrompt.propTypes = {
  classes: PropTypes.object,
  prompt: PropTypes.string,
  tagName: PropTypes.string,
  className: PropTypes.string,
  onClick: PropTypes.func,
  defaultClassName: PropTypes.string,
  autoplayAudioEnabled: PropTypes.bool,
  customAudioButton: {
    playImage: PropTypes.string,
    pauseImage: PropTypes.string
  }
};
PreviewPrompt.defaultProps = {
  onClick: () => {}
};

const styles = theme => ({
  prompt: {
    verticalAlign: 'middle',
    color: text()
  },
  legend: {
    width: '100%',
    fontSize: 'inherit  !important'
  },
  rationale: {
    paddingLeft: theme.spacing.unit * 4,
    paddingBottom: theme.spacing.unit
  },
  label: {
    color: `${text()} !important`,
    //'var(--choice-input-color, black)',
    display: 'flex',
    flexDirection: 'column',
    verticalAlign: 'middle',
    cursor: 'pointer',
    '& > p': {
      margin: '0 0 0 0 !important'
    }
  },
  promptTable: {
    '&:not(.MathJax) > table': {
      borderCollapse: 'collapse'
    },
    '&:not(.MathJax) > table tr': {
      '&:nth-child(2n)': {
        backgroundColor: '#f6f8fa',
        color: theme.palette.common.black
      }
    },
    // align table content to left as per STAR requirement PD-3687
    '&:not(.MathJax) table td, &:not(.MathJax) table th': {
      padding: '.6em 1em',
      textAlign: 'left'
    },
    // added this to fix alignment of text in prompt imported from studio (PD-3423)
    '&:not(.MathJax) > table td > p.kds-indent': {
      textAlign: 'initial'
    }
  }
});

var previewPrompt = withStyles(styles)(PreviewPrompt);

const Readable = props => {
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, React__default.Children.map(props.children, child => /*#__PURE__*/React__default.cloneElement(child, {
    'data-pie-readable': props.false === undefined
  })));
};

Readable.propTypes = {
  children: PropTypes.node,
  false: PropTypes.bool
};

const Purpose = props => {
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, React__default.Children.map(props.children, child => /*#__PURE__*/React__default.cloneElement(child, {
    'data-pie-purpose': props.purpose
  })));
};

Purpose.propTypes = {
  children: PropTypes.node,
  purpose: PropTypes.string
};

let parser$1;

if (typeof window !== 'undefined') {
  parser$1 = new DOMParser();
}

const markupToText = s => {
  const root = parser$1.parseFromString(s, 'text/html');
  return root.body.textContent;
};

const hasText = s => {
  if (!s) {
    return false;
  }

  const tc = markupToText(s);
  return !!(tc && tc.trim());
};

let parser;

if (typeof window !== 'undefined') {
  parser = new DOMParser();
}
/*
 * Check if the string contains at least one media element.
 */


const hasMedia = s => {
  if (!s) {
    return false;
  }

  const root = parser.parseFromString(s, 'text/html');
  return !!root.body.querySelector('img') || !!root.body.querySelector('video') || !!root.body.querySelector('audio');
};

var enableAudioAutoplayImage = 'data:image/jpeg;base64, ';

export { ExtraCSSRulesMixin as AppendCSSRules, index as Collapsible, enableAudioAutoplayImage as EnableAudioAutoplayImage, Feedback$1 as Feedback, HtmlAndMath, inputContainer as InputContainer, RootElem as PreviewLayout, previewPrompt as PreviewPrompt, Purpose, Readable, Styled$1 as UiLayout, color, hasMedia, hasText, responseIndicators as indicators, withUndoReset };
//# sourceMappingURL=index.js.map
