"use strict";

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

var _preact = require("preact");

var _classnames = _interopRequireDefault(require("classnames"));

var _getColorForIndex = require("./utils/get-color-for-index");

var _emptyMessage = require("./empty-message");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @typedef BarGraphData
 * @property {number} value
 * @property {string} label
 * @property {string} [href]
 * @property {string} [color] Color will be assigned if not passed
 */

/**
 * @typedef BarGraphProps
 * @property {BarGraphData[]} data
 * @property {boolean} [showTotal=true] Default is `true`
 * @property {boolean} [sort=true] Default is `true`
 */

/**
 * Card
 *
 * @type {import('preact').FunctionComponent}
 * @param {BarGraphProps} props
 */
const BarGraph = ({
  data,
  showTotal = true,
  sort = true
}) => {
  const sorted = sort ? data.slice().sort((a, b) => b.value - a.value) : data;
  const max = sorted.reduce((max, item) => Math.max(item.value, max), 0);
  const total = sorted.reduce((sum, item) => sum + item.value, 0);
  return (0, _preact.h)("div", null, sorted.length === 0 && (0, _preact.h)(_emptyMessage.EmptyMessage, {
    message: "no data"
  }), sorted.map((item, index) => {
    const isLast = index === sorted.length - 1;
    const contents = (0, _preact.h)(_preact.Fragment, null, (0, _preact.h)("div", {
      className: "w4 truncate flex-shrink-0 pr2"
    }, item.label), (0, _preact.h)("div", {
      className: "w-100 flex items-center"
    }, (0, _preact.h)("div", {
      className: "relative w-100"
    }, (0, _preact.h)("div", {
      key: item.label,
      className: (0, _classnames.default)('br1 flex-shrink-0 flex-grow-0', "bg-".concat(item.color || (0, _getColorForIndex.getColorForIndex)(index))),
      style: {
        height: '16px',
        width: "".concat(item.value / max * 100, "%")
      }
    })), (0, _preact.h)("div", {
      className: "ml2"
    }, item.value)));
    const baseClasses = 'flex items-center' + (isLast ? '' : ' mb2');

    if (item.href) {
      return (0, _preact.h)("a", {
        href: item.href,
        className: baseClasses + ' no-underline color-inherit'
      }, contents);
    }

    return (0, _preact.h)("div", {
      key: item.label,
      className: baseClasses
    }, contents);
  }), sorted.length > 0 && showTotal && (0, _preact.h)("div", {
    className: "tr mt2"
  }, "Total: ", total));
};

exports.BarGraph = BarGraph;