import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import { isNotEmpty } from '@bigbinary/neeto-cist';
import Pane from '@bigbinary/neetoui/Pane';
import Typography from '@bigbinary/neetoui/Typography';
import Spinner from '@bigbinary/neetoui/Spinner';
import { useTranslation } from 'react-i18next';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState, useCallback, useEffect } from 'react';
import { buildUrl } from '@bigbinary/neeto-commons-frontend/utils';
import Label from '@bigbinary/neetoui/Label';
import Input from '@bigbinary/neetoui/Input';
import Switch from '@bigbinary/neetoui/Switch';
import Button from '@bigbinary/neetoui/Button';
import { not, assoc } from 'ramda';
import CardLayout from './CardLayout.js';
import CopyToClipboardButton from './CopyToClipboardButton.js';
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import 'classnames';
import '@bigbinary/neeto-commons-frontend/utils/general';
import '@bigbinary/neeto-icons/Copy';
import '@bigbinary/neeto-icons/Check';
import './inject-css-C2dztUxs.js';

var ONE_SECOND = 1;
var ONE_MINUTE = 60 * ONE_SECOND;
var ONE_HOUR = 60 * ONE_MINUTE;

var padZero = function padZero(number) {
  var length = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  var string = String(number);
  var threshold = Math.pow(10, length - 1);
  if (number < threshold) {
    while (String(threshold).length > string.length) {
      string = "0".concat(number);
    }
  }
  return string;
};
var shouldRenderHoursInput = function shouldRenderHoursInput(duration) {
  var hours = Math.floor(duration / ONE_HOUR);
  return hours > 0;
};
var formatTime = function formatTime(timeInSeconds, showHours) {
  var hours = Math.floor(timeInSeconds / ONE_HOUR);
  var minutes = Math.floor(timeInSeconds % ONE_HOUR / ONE_MINUTE);
  var seconds = timeInSeconds % ONE_MINUTE;
  return showHours ? "".concat(padZero(hours), ":").concat(padZero(minutes), ":").concat(padZero(seconds)) : "".concat(padZero(minutes), ":").concat(padZero(seconds));
};
var parseTime = function parseTime(timeString) {
  var parts = timeString.split(":").map(function (part) {
    return part === "" ? NaN : parseInt(part, 10);
  });
  if (parts.some(isNaN) || parts.length > 3) {
    return 0;
  }
  if (parts.length === 1) {
    return parts[0];
  } else if (parts.length === 2) {
    return parts[0] * ONE_MINUTE + parts[1];
  } else if (parts.length === 3) {
    return parts[0] * ONE_HOUR + parts[1] * ONE_MINUTE + parts[2];
  }
  return 0;
};
var validateInput = function validateInput(input) {
  var regex = /^[0-9:]{0,8}$/;
  var colons = (input.match(/:/g) || []).length;
  return regex.test(input) && colons <= 2;
};

var SharePaneBody = function SharePaneBody(_ref) {
  var recordingUrls = _ref.recordingUrls,
    totalDuration = _ref.totalDuration,
    getCurrentTimestamp = _ref.getCurrentTimestamp,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    Preview = _ref.preview,
    enableAutoplayAndMuteFlags = _ref.enableAutoplayAndMuteFlags;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var currentTimestamp = getCurrentTimestamp();
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    shareLinks = _useState2[0],
    setShareLinks = _useState2[1];
  var _useState3 = useState(currentTimestamp),
    _useState4 = _slicedToArray(_useState3, 2),
    currentPlaybackTime = _useState4[0],
    setCurrentPlaybackTime = _useState4[1];
  var _useState5 = useState({
      muted: false,
      autoplay: false
    }),
    _useState6 = _slicedToArray(_useState5, 2),
    params = _useState6[0],
    setParams = _useState6[1];
  var muted = params.muted,
    autoplay = params.autoplay;
  var _useState7 = useState(""),
    _useState8 = _slicedToArray(_useState7, 2),
    rawInput = _useState8[0],
    setRawInput = _useState8[1];
  var showHours = shouldRenderHoursInput(totalDuration);
  var handlePlaybackTimestampChange = function handlePlaybackTimestampChange(e) {
    var input = e.target.value;
    if (validateInput(input)) {
      setRawInput(input);
    }
  };
  var handleFlagsChange = function handleFlagsChange(key, value) {
    return setParams(assoc(key, value));
  };
  var formatAndSetTime = function formatAndSetTime() {
    var timeInSeconds = parseTime(rawInput);
    if (timeInSeconds > totalDuration) {
      timeInSeconds = totalDuration;
    }
    setRawInput(formatTime(timeInSeconds, showHours));
  };
  var handleKeyDown = function handleKeyDown(e) {
    if (e.key !== "Enter") return;
    formatAndSetTime();
  };
  var generateUrls = useCallback(function (timeInSeconds, urlParams) {
    var playbackUrls = recordingUrls.map(function (recordingUrl) {
      return buildUrl(recordingUrl, {
        time: timeInSeconds,
        muted: urlParams.muted ? 1 : undefined,
        autoplay: urlParams.autoplay ? 1 : undefined
      });
    });
    setShareLinks(playbackUrls);
  }, [recordingUrls]);
  var handleRegenerateUrl = function handleRegenerateUrl() {
    var timeInSeconds = parseTime(rawInput);
    if (timeInSeconds > totalDuration) {
      timeInSeconds = totalDuration;
    }
    setCurrentPlaybackTime(timeInSeconds);
    generateUrls(timeInSeconds, params);
  };
  useEffect(function () {
    if (not(isOpen)) return;
    var initialTime = currentTimestamp > 0 ? currentTimestamp : 0;
    var initialParams = {
      muted: false,
      autoplay: false
    };
    setCurrentPlaybackTime(initialTime);
    setRawInput(formatTime(initialTime, showHours));
    setParams(initialParams);
    generateUrls(initialTime, initialParams);
  }, [isOpen, showHours, currentTimestamp, generateUrls]);
  return /*#__PURE__*/jsxs("div", {
    className: "flex w-full flex-col gap-y-6",
    children: [/*#__PURE__*/jsx(CardLayout, {
      title: t("neetoMolecules.shareRecording.configureUrlParameters"),
      actionBlock: /*#__PURE__*/jsxs("div", {
        className: "flex items-center gap-x-2",
        children: [/*#__PURE__*/jsx(Button, {
          "data-testid": "regenerate-url-button",
          label: t("neetoMolecules.shareRecording.regenerateUrl"),
          onClick: handleRegenerateUrl
        }), /*#__PURE__*/jsx(Button, {
          "data-testid": "cancel-button",
          label: t("neetoMolecules.shareRecording.cancel"),
          style: "secondary",
          onClick: onClose
        })]
      }),
      description: t("neetoMolecules.shareRecording.configureUrlParametersDescription"),
      children: /*#__PURE__*/jsxs("div", {
        className: "flex flex-col gap-y-4",
        children: [/*#__PURE__*/jsxs("div", {
          className: "flex items-center gap-x-2",
          children: [/*#__PURE__*/jsx(Label, {
            children: t("neetoMolecules.shareRecording.startVideoAt")
          }), /*#__PURE__*/jsx(Input, {
            unlimitedChars: true,
            className: "w-40",
            "data-testid": "time-input",
            placeholder: showHours ? "HH:MM:SS" : "MM:SS",
            value: rawInput,
            onBlur: formatAndSetTime,
            onChange: handlePlaybackTimestampChange,
            onKeyDown: handleKeyDown
          })]
        }), enableAutoplayAndMuteFlags && /*#__PURE__*/jsxs(Fragment, {
          children: [/*#__PURE__*/jsx(Switch, {
            checked: muted,
            "data-testid": "muted-checkbox",
            id: "muted",
            label: t("neetoMolecules.shareRecording.muted"),
            name: "muted",
            onChange: function onChange(e) {
              return handleFlagsChange("muted", e.target.checked);
            }
          }), /*#__PURE__*/jsx(Switch, {
            checked: autoplay,
            "data-testid": "autoplay-checkbox",
            id: "autoplay",
            label: t("neetoMolecules.shareRecording.autoplay"),
            name: "autoplay",
            onChange: function onChange(e) {
              return handleFlagsChange("autoplay", e.target.checked);
            }
          })]
        })]
      })
    }), /*#__PURE__*/jsxs("div", {
      className: "flex flex-col gap-y-2",
      children: [/*#__PURE__*/jsx(Typography, {
        style: "h3",
        children: t("neetoMolecules.shareRecording.generatedUrls")
      }), shareLinks.map(function (shareLink, index) {
        return /*#__PURE__*/jsxs("div", {
          className: "neeto-ui-bg-gray-100 neeto-ui-rounded-lg flex w-full items-center justify-between gap-1 p-2",
          children: [/*#__PURE__*/jsx(Typography, {
            className: "min-w-0 flex-1 break-words",
            style: "body2",
            children: shareLink
          }), /*#__PURE__*/jsx(CopyToClipboardButton, {
            className: "flex-shrink-0",
            style: "secondary",
            value: shareLink
          })]
        }, index);
      })]
    }), Preview && /*#__PURE__*/jsxs("div", {
      className: "flex flex-col gap-y-2 pt-2",
      children: [/*#__PURE__*/jsx(Label, {
        children: t("neetoMolecules.shareRecording.preview")
      }), /*#__PURE__*/jsx(Preview, {
        currentPlaybackTime: currentPlaybackTime
      })]
    })]
  });
};

var _excluded = ["recordingUrl", "recordingUrls", "totalDuration", "getCurrentTimestamp", "isOpen", "onClose", "isLoading", "preview", "enableAutoplayAndMuteFlags", "size"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var ShareRecordingPane = function ShareRecordingPane(_ref) {
  var _ref$recordingUrl = _ref.recordingUrl,
    recordingUrl = _ref$recordingUrl === void 0 ? null : _ref$recordingUrl,
    _ref$recordingUrls = _ref.recordingUrls,
    recordingUrls = _ref$recordingUrls === void 0 ? [] : _ref$recordingUrls,
    totalDuration = _ref.totalDuration,
    getCurrentTimestamp = _ref.getCurrentTimestamp,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    _ref$isLoading = _ref.isLoading,
    isLoading = _ref$isLoading === void 0 ? false : _ref$isLoading,
    preview = _ref.preview,
    _ref$enableAutoplayAn = _ref.enableAutoplayAndMuteFlags,
    enableAutoplayAndMuteFlags = _ref$enableAutoplayAn === void 0 ? false : _ref$enableAutoplayAn,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? "large" : _ref$size,
    otherProps = _objectWithoutProperties(_ref, _excluded);
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var recordingUrlsToShare = isNotEmpty(recordingUrls) ? recordingUrls : [recordingUrl];
  return /*#__PURE__*/jsxs(Pane, _objectSpread(_objectSpread({}, _objectSpread({
    isOpen: isOpen,
    onClose: onClose,
    size: size
  }, otherProps)), {}, {
    "data-testid": "share-pane",
    children: [/*#__PURE__*/jsx(Pane.Header, {
      children: /*#__PURE__*/jsx(Typography, {
        style: "h2",
        children: t("neetoMolecules.shareRecording.title")
      })
    }), /*#__PURE__*/jsx(Pane.Body, {
      className: "flex flex-col gap-y-2",
      children: isLoading ? /*#__PURE__*/jsx(Spinner, {
        className: "mx-auto"
      }) : /*#__PURE__*/jsx(SharePaneBody, {
        enableAutoplayAndMuteFlags: enableAutoplayAndMuteFlags,
        getCurrentTimestamp: getCurrentTimestamp,
        isOpen: isOpen,
        onClose: onClose,
        preview: preview,
        totalDuration: totalDuration,
        recordingUrls: recordingUrlsToShare
      })
    })]
  }));
};

export { ShareRecordingPane as default };
//# sourceMappingURL=ShareRecordingPane.js.map
