'use strict';

var neetoCist = require('@bigbinary/neeto-cist');
var PrivateRoute = require('@bigbinary/neeto-commons-frontend/react-utils/PrivateRoute');
var reactRouterDom = require('react-router-dom');
var ErrorPage = require('./ErrorPage.js');
var classnames = require('classnames');
var Typography = require('@bigbinary/neetoui/Typography');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var Container = require('./Container.js');
var jsxRuntime = require('react/jsx-runtime');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var React = require('react');
var useBreakpoints = require('@bigbinary/neeto-commons-frontend/react-utils/useBreakpoints');
var ExternalLink = require('@bigbinary/neeto-icons/ExternalLink');
var LinkIcon = require('@bigbinary/neeto-icons/Link');
var Button = require('@bigbinary/neetoui/Button');
var CopyToClipboardButton = require('./CopyToClipboardButton.js');
var MoreDropdown = require('./MoreDropdown.js');
var formik = require('formik');
var Pane = require('@bigbinary/neetoui/Pane');
var Input = require('@bigbinary/neetoui/formik/Input');
var ActionBlock = require('@bigbinary/neetoui/formik/ActionBlock');
var i18next = require('i18next');
var constants = require('@bigbinary/neeto-commons-frontend/constants');
var Facebook = require('@bigbinary/neeto-icons/Facebook');
var Linkedin = require('@bigbinary/neeto-icons/Linkedin');
var Twitter = require('@bigbinary/neeto-icons/Twitter');
var yup = require('yup');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var general = require('@bigbinary/neeto-commons-frontend/utils/general');
var injectCss = require('./inject-css-B6qYtOJe.js');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var Help = require('@bigbinary/neeto-icons/Help');
var Modal = require('@bigbinary/neetoui/Modal');
var Input$1 = require('@bigbinary/neetoui/Input');
var Select = require('@bigbinary/neetoui/Select');
var DatePicker = require('@bigbinary/neetoui/DatePicker');
var Share = require('@bigbinary/neeto-icons/Share');
var QrCode = require('@bigbinary/neeto-icons/QrCode');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var HelpPopover = require('./HelpPopover.js');
var LeftArrow = require('@bigbinary/neeto-icons/LeftArrow');
var CardLayout = require('./CardLayout.js');
var Header$1 = require('./Header.js');
require('zustand/shallow');
require('@bigbinary/neeto-commons-frontend/react-utils/useDisplayErrorPage');
require('react-helmet');
require('./index-JY2zVpnv.js');
require('./_commonjsHelpers-BJu3ubxk.js');
require('@bigbinary/neeto-icons/Copy');
require('@bigbinary/neeto-icons/Check');
require('@bigbinary/neeto-icons/MenuHorizontal');
require('@bigbinary/neeto-icons/MenuVertical');
require('@bigbinary/neetoui/Dropdown');
require('@bigbinary/neetoui/Tooltip');
require('@bigbinary/neeto-commons-frontend/react-utils');
require('@bigbinary/neetoui/Popover');
require('./Breadcrumbs.js');
require('./Search.js');
require('@bigbinary/neeto-commons-frontend/react-utils/useFuncDebounce');
require('@bigbinary/neeto-commons-frontend/react-utils/useQueryParams');
require('@bigbinary/neeto-commons-frontend/react-utils/useUpdateEffect');
require('@bigbinary/neeto-icons/Search');

function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);

var ExpiryNotice = function ExpiryNotice(_ref) {
  var expiryConfiguration = _ref.expiryConfiguration;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var daysBeforeExpiry = expiryConfiguration.daysBeforeExpiry;
  var notice = t("neetoMolecules.shareViaLink.expiryNotice.daysRemaining", {
    count: daysBeforeExpiry
  });
  if (daysBeforeExpiry < 1) {
    notice = t("neetoMolecules.shareViaLink.expiryNotice.expiresToday");
  }
  if (daysBeforeExpiry <= 0) {
    notice = t("neetoMolecules.shareViaLink.expiryNotice.expired");
  }
  return /*#__PURE__*/jsxRuntime.jsx(Typography, {
    "data-testid": "expiry-notice",
    lineHeight: "normal",
    style: "body3",
    className: classnames("ms-1", {
      "neeto-ui-text-error-800": daysBeforeExpiry <= 1,
      "neeto-ui-text-gray-700": daysBeforeExpiry > 1
    }),
    children: notice
  });
};

function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
var facebookShareLink = function facebookShareLink(_ref) {
  var url = _ref.url;
  return general.buildUrl("https://www.facebook.com/sharer/sharer.php", {
    u: url
  });
};
var linkedInShareLink = function linkedInShareLink(_ref2) {
  var url = _ref2.url,
    title = _ref2.title;
  return general.buildUrl("https://www.linkedin.com/sharing/share-offsite", {
    mini: true,
    text: "".concat(title, " ").concat(url)
  });
};
var twitterShareLink = function twitterShareLink(_ref3) {
  var url = _ref3.url,
    title = _ref3.title;
  return general.buildUrl("http://twitter.com/share", {
    text: title,
    url: url
  });
};
var downloadCanvas = function downloadCanvas(canvas) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var _options$name = options.name,
    name = _options$name === void 0 ? "image" : _options$name,
    _options$extension = options.extension,
    extension = _options$extension === void 0 ? "png" : _options$extension;
  var canvasUrl = canvas.toDataURL("image/".concat(extension));
  var element = document.createElement("a");
  element.href = canvasUrl;
  element.download = "".concat(name, ".").concat(extension);
  element.click();
  element.remove();
};
var copyCanvasToClipboard = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(canvas, handleDownloadQRCode) {
    var blob, clipboardItem;
    return _regenerator().w(function (_context) {
      while (1) switch (_context.p = _context.n) {
        case 0:
          if (canvas) {
            _context.n = 1;
            break;
          }
          return _context.a(2);
        case 1:
          _context.p = 1;
          _context.n = 2;
          return new Promise(function (resolve) {
            return canvas.toBlob(resolve);
          });
        case 2:
          blob = _context.v;
          if (blob) {
            _context.n = 3;
            break;
          }
          return _context.a(2);
        case 3:
          clipboardItem = new ClipboardItem(_defineProperty({}, blob.type, blob));
          navigator.clipboard.write([clipboardItem]);
          _context.n = 5;
          break;
        case 4:
          _context.p = 4;
          _context.v;
          handleDownloadQRCode();
        case 5:
          return _context.a(2);
      }
    }, _callee, null, [[1, 4]]);
  }));
  return function copyCanvasToClipboard(_x, _x2) {
    return _ref4.apply(this, arguments);
  };
}();
var getPathname = function getPathname(url) {
  return new URL(url).pathname.slice(1);
};
var getPrefixFromUrl = function getPrefixFromUrl(url) {
  return "".concat(new URL(url).origin, "/");
};
var truncatePrefix = function truncatePrefix(inputElement, prefixText) {
  var parentElement = inputElement.parentElement;
  var prefixElement = parentElement.querySelector(".neeto-ui-input__prefix");
  var _getComputedStyle = getComputedStyle(inputElement),
    fontSize = _getComputedStyle.fontSize;
  var averageCharWidth = parseFloat(fontSize) * 0.6;
  var requiredInputWidth = inputElement.value.length * averageCharWidth;
  var prefixWidth = parentElement.offsetWidth - requiredInputWidth;
  var maxPrefixChars = Math.max(Math.floor(prefixWidth / averageCharWidth), 5);
  prefixElement.textContent = maxPrefixChars < prefixText.length ? "...".concat(prefixText.slice(-maxPrefixChars)) : prefixText;
};
var normalizeEditablePath = ramda.replace(/[^a-z0-9&?=._-]/gi, "");

var SOCIAL_MEDIA_OPTIONS = {
  FACEBOOK: {
    label: i18next.t("neetoMolecules.shareViaLink.socialMediaShare.facebook"),
    icon: Facebook,
    generateShareUrl: facebookShareLink
  },
  LINKEDIN: {
    label: i18next.t("neetoMolecules.shareViaLink.socialMediaShare.linkedIn"),
    icon: Linkedin,
    generateShareUrl: linkedInShareLink
  },
  TWITTER: {
    label: i18next.t("neetoMolecules.shareViaLink.socialMediaShare.twitter"),
    icon: Twitter,
    generateShareUrl: twitterShareLink
  }
};
var PATH_VALIDATION_SCHEMA = yup__namespace.object().shape({
  path: yup__namespace.string().required(i18next.t("neetoMolecules.shareViaLink.editUrl.validationError")).matches(/^[A-Za-z0-9]([\w/-])*$/, i18next.t("neetoMolecules.shareViaLink.editUrl.validationError")).test("reserved-path", i18next.t("neetoMolecules.shareViaLink.editUrl.reservedPathError"), function (value) {
    return !constants.RESERVED_PATHS.includes(value === null || value === void 0 ? void 0 : value.toLowerCase());
  })
});

var css$1 = ".no-padding .neeto-ui-input.neeto-ui-input--medium input{padding:0}.no-padding .neeto-ui-input__prefix{color:rgb(var(--neeto-ui-gray-600))!important}";
injectCss.n(css$1,{});

var Header = Pane.Header,
  Body = Pane.Body,
  Footer = Pane.Footer;
var EditURL = function EditURL(_ref) {
  var editUrlProps = _ref.editUrlProps,
    isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    url = _ref.url,
    isLoading = _ref.isLoading,
    handleEdit = _ref.handleEdit;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var focusRef = React.useRef(null);
  var prevIsLoadingRef = React.useRef(isLoading);
  var prefixText = (editUrlProps === null || editUrlProps === void 0 ? void 0 : editUrlProps.prefix) || getPrefixFromUrl(url);
  var observerRef = React.useRef(new ResizeObserver(function (_ref2) {
    var _ref3 = _slicedToArray(_ref2, 1),
      entry = _ref3[0];
    return requestAnimationFrame(function () {
      return truncatePrefix(entry.target, prefixText);
    });
  }));
  var inputRef = React.useCallback(function (inputElement) {
    focusRef.current = inputElement;
    inputElement ? observerRef.current.observe(inputElement) : observerRef.current.disconnect();
  }, []);
  React.useEffect(function () {
    if (prevIsLoadingRef.current && !isLoading) onClose();
    prevIsLoadingRef.current = isLoading;
  }, [isLoading]);
  return /*#__PURE__*/jsxRuntime.jsxs(Pane, {
    isOpen: isOpen,
    onClose: onClose,
    "data-testid": "edit-url-modal",
    initialFocusRef: focusRef,
    size: "large",
    children: [/*#__PURE__*/jsxRuntime.jsx(Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
        lineHeight: "normal",
        style: "h2",
        weight: "semibold",
        children: t("neetoMolecules.shareViaLink.editUrl.title")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(formik.Formik, {
      enableReinitialize: true,
      initialValues: {
        path: (editUrlProps === null || editUrlProps === void 0 ? void 0 : editUrlProps.editablePath) || getPathname(url)
      },
      validationSchema: PATH_VALIDATION_SCHEMA,
      onSubmit: function onSubmit(_ref4) {
        var path = _ref4.path;
        return handleEdit(path);
      },
      children: function children(_ref5) {
        var isSubmitting = _ref5.isSubmitting,
          dirty = _ref5.dirty,
          setFieldValue = _ref5.setFieldValue;
        return /*#__PURE__*/jsxRuntime.jsxs(formik.Form, {
          children: [/*#__PURE__*/jsxRuntime.jsxs(Body, {
            className: "flex flex-col gap-y-6",
            children: [/*#__PURE__*/jsxRuntime.jsx(Input, {
              className: "no-padding w-full flex-grow-0",
              "data-testid": "edit-url-input",
              label: t("neetoMolecules.shareViaLink.editUrl.inputLabel"),
              maxLength: editUrlProps === null || editUrlProps === void 0 ? void 0 : editUrlProps.maxLength,
              name: "path",
              prefix: prefixText,
              ref: inputRef,
              onChange: function onChange(event) {
                return setFieldValue("path", normalizeEditablePath(event.target.value));
              }
            }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
              className: "neeto-ui-text-gray-700",
              lineHeight: "normal",
              style: "body2",
              children: t("neetoMolecules.shareViaLink.editUrl.description")
            })]
          }), /*#__PURE__*/jsxRuntime.jsx(Footer, {
            className: "flex items-center gap-x-2",
            children: /*#__PURE__*/jsxRuntime.jsx(ActionBlock, {
              className: "flex items-center gap-x-2",
              cancelButtonProps: {
                onClick: onClose,
                disabled: isSubmitting,
                "data-testid": "edit-url-cancel-button"
              },
              submitButtonProps: {
                disabled: isSubmitting || !dirty,
                loading: isLoading,
                "data-testid": "edit-url-confirm-button"
              }
            })
          })]
        });
      }
    })]
  });
};

var RegenerateURL = function RegenerateURL(_ref) {
  var _regenerateConfig$exp, _regenerateConfig$exp2, _globalProps$user$dat, _globalProps;
  var isOpen = _ref.isOpen,
    onClose = _ref.onClose,
    url = _ref.url,
    isLoading = _ref.isLoading,
    handleRegenerate = _ref.handleRegenerate,
    _ref$regenerateConfig = _ref.regenerateConfig,
    regenerateConfig = _ref$regenerateConfig === void 0 ? {
      expiresInOptions: [],
      helpUrl: null
    } : _ref$regenerateConfig;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var prevIsLoadingRef = React.useRef(isLoading);
  var regenerateStrategy = neetoCist.isPresent(regenerateConfig === null || regenerateConfig === void 0 ? void 0 : regenerateConfig.expiresInOptions) ? "expiryBased" : "basic";
  var defaultExpiresInOption = regenerateConfig === null || regenerateConfig === void 0 || (_regenerateConfig$exp = regenerateConfig.expiresInOptions) === null || _regenerateConfig$exp === void 0 || (_regenerateConfig$exp = _regenerateConfig$exp[0]) === null || _regenerateConfig$exp === void 0 ? void 0 : _regenerateConfig$exp.value;
  var _useState = React.useState(defaultExpiresInOption),
    _useState2 = _slicedToArray(_useState, 2),
    selectedExpiresInOption = _useState2[0],
    setSelectedExpiresInOption = _useState2[1];
  var defaultExpiresOnDate = utils.dayjs().add(10, "day").toDate();
  var _useState3 = React.useState(defaultExpiresOnDate),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedExpiresOnDate = _useState4[0],
    setSelectedExpiresOnDate = _useState4[1];
  var isSelectedExpiresInOptionNever = selectedExpiresInOption === "never";
  var isSelectedExpiresInOptionCustom = selectedExpiresInOption === "custom";
  var isSelectedExpiresInOptionValidNumberOfDays = neetoCist.isPresent(selectedExpiresInOption) && !isSelectedExpiresInOptionCustom && !isSelectedExpiresInOptionNever;
  var isValidExpiryConfig = isSelectedExpiresInOptionNever || isSelectedExpiresInOptionCustom && neetoCist.isPresent(selectedExpiresOnDate) || isSelectedExpiresInOptionValidNumberOfDays;
  var expiryConfigPayload = isSelectedExpiresInOptionValidNumberOfDays ? {
    expiresInDays: selectedExpiresInOption
  } : {
    expiresOnDate: selectedExpiresOnDate
  };
  var onSubmit = function onSubmit() {
    return regenerateStrategy === "basic" || isSelectedExpiresInOptionNever ? handleRegenerate() : handleRegenerate({
      payload: expiryConfigPayload
    });
  };
  React.useEffect(function () {
    if (prevIsLoadingRef.current && !isLoading) onClose();
    prevIsLoadingRef.current = isLoading;
  }, [isLoading]);
  React.useEffect(function () {
    if (!isOpen) return;
    setSelectedExpiresInOption(defaultExpiresInOption);
    setSelectedExpiresOnDate(defaultExpiresOnDate);
  }, [isOpen]);
  return /*#__PURE__*/jsxRuntime.jsxs(Modal, {
    isOpen: isOpen,
    onClose: onClose,
    "data-testid": "regenerate-url-modal",
    size: regenerateStrategy === "basic" ? "medium" : "large",
    children: [/*#__PURE__*/jsxRuntime.jsx(Modal.Header, {
      children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
        lineHeight: "normal",
        style: "h2",
        weight: "semibold",
        children: regenerateStrategy === "expiryBased" ? t("neetoMolecules.shareViaLink.regenerateUrl.titleForExpiryBasedRegeneration") : t("neetoMolecules.shareViaLink.regenerateUrl.title")
      })
    }), /*#__PURE__*/jsxRuntime.jsx(Modal.Body, {
      children: /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex w-full flex-col gap-y-6",
        children: [regenerateStrategy === "basic" && /*#__PURE__*/jsxRuntime.jsx(Input$1, {
          disabled: true,
          label: t("neetoMolecules.shareViaLink.regenerateUrl.inputLabel"),
          value: url
        }), regenerateStrategy === "expiryBased" && /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex flex-row gap-2",
          children: [/*#__PURE__*/jsxRuntime.jsx(Select, {
            "data-testid": "expires-in-select",
            defaultValue: (_regenerateConfig$exp2 = regenerateConfig.expiresInOptions) === null || _regenerateConfig$exp2 === void 0 ? void 0 : _regenerateConfig$exp2[0],
            options: regenerateConfig.expiresInOptions,
            className: classnames({
              "w-1/2": isSelectedExpiresInOptionCustom,
              "w-full": !isSelectedExpiresInOptionCustom
            }),
            label: t("neetoMolecules.shareViaLink.regenerateUrl.expiresInLabel"),
            labelProps: {
              helpIconProps: neetoCist.isPresent(regenerateConfig === null || regenerateConfig === void 0 ? void 0 : regenerateConfig.helpUrl) && {
                icon: Help,
                className: "cursor-pointer opacity-75 hover:opacity-100 transition-opacity duration-300 ease-in-out",
                popoverProps: {
                  title: t("neetoMolecules.shareViaLink.regenerateUrl.expiresInHelpTitle"),
                  helpLinkProps: {
                    label: t("neetoMolecules.shareViaLink.regenerateUrl.helpLinkLabel"),
                    href: regenerateConfig === null || regenerateConfig === void 0 ? void 0 : regenerateConfig.helpUrl,
                    target: "_blank"
                  }
                }
              }
            },
            onChange: function onChange(option) {
              return setSelectedExpiresInOption(option.value);
            }
          }), isSelectedExpiresInOptionCustom && /*#__PURE__*/jsxRuntime.jsx(DatePicker, {
            "data-testid": "expires-on-date-picker",
            dateFormat: (_globalProps$user$dat = (_globalProps = globalProps) === null || _globalProps === void 0 || (_globalProps = _globalProps.user) === null || _globalProps === void 0 ? void 0 : _globalProps.dateFormat) !== null && _globalProps$user$dat !== void 0 ? _globalProps$user$dat : undefined,
            disabledDate: function disabledDate(d) {
              return !d || d.isBefore(utils.dayjs());
            },
            getPopupContainer: ramda.prop("parentNode"),
            picker: "date",
            type: "date",
            value: selectedExpiresOnDate,
            label: t("neetoMolecules.shareViaLink.regenerateUrl.expiresOnLabel"),
            onChange: setSelectedExpiresOnDate
          })]
        }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
          className: "neeto-ui-text-gray-700",
          lineHeight: "normal",
          style: "body2",
          children: t("neetoMolecules.shareViaLink.regenerateUrl.description")
        })]
      })
    }), /*#__PURE__*/jsxRuntime.jsxs(Modal.Footer, {
      className: "flex items-center gap-x-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
        "data-cy": "regenerate-url-confirm-button",
        "data-testid": "regenerate-url-confirm-button",
        loading: isLoading,
        disabled: regenerateStrategy === "expiryBased" && !isValidExpiryConfig,
        label: t("neetoMolecules.shareViaLink.regenerateUrl.submitButtonLabel"),
        onClick: onSubmit
      }), /*#__PURE__*/jsxRuntime.jsx(Button, {
        "data-cy": "regenerate-url-cancel-button",
        "data-testid": "regenerate-url-cancel-button",
        style: "text",
        label: t("neetoMolecules.shareViaLink.regenerateUrl.cancelButtonLabel"),
        onClick: onClose
      })]
    })]
  });
};

var Link = function Link(_ref) {
  var editUrlProps = _ref.editUrlProps,
    enabledOptions = _ref.enabledOptions,
    entityName = _ref.entityName,
    handleEdit = _ref.handleEdit,
    handleRegenerate = _ref.handleRegenerate,
    isLoading = _ref.isLoading,
    previewUrl = _ref.previewUrl,
    url = _ref.url;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isRegenerateURLModalOpen = _useState2[0],
    setIsRegenerateURLModalOpen = _useState2[1];
  var _useState3 = React.useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isEditURLModalOpen = _useState4[0],
    setIsEditURLModalOpen = _useState4[1];
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useBreakpoints = useBreakpoints(),
    isSize = _useBreakpoints.isSize;
  var isMobile = isSize("mobile");
  var isDropdownEnabled = enabledOptions.regenerate || enabledOptions.edit;
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "flex flex-col gap-y-4",
    "data-cy": "link-block",
    "data-testid": "link-block",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-1 sm:gap-2",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "relative flex min-w-0 flex-grow items-stretch truncate leading-none",
        "data-cy": "nui-input-field",
        children: [/*#__PURE__*/jsxRuntime.jsx("div", {
          className: "neeto-ui-rounded-md neeto-ui-border-gray-300 neeto-ui-bg-gray-50 relative flex min-w-0 flex-grow items-center truncate rounded-r-none border leading-none rtl:rounded-l-none rtl:rounded-r-md",
          children: /*#__PURE__*/jsxRuntime.jsx(Button, {
            className: "neeto-molecules-share-link-button relative min-w-0 flex-grow flex-row truncate px-2 py-1 leading-none",
            href: url,
            icon: LinkIcon,
            iconPosition: "left",
            label: url,
            style: "link",
            target: "_blank"
          })
        }), /*#__PURE__*/jsxRuntime.jsx(CopyToClipboardButton, {
          className: "rounded-l-none rtl:rounded-l-md rtl:rounded-r-none",
          "data-cy": "link-copy-button",
          "data-testid": "link-copy-button",
          label: !isMobile ? t("neetoMolecules.shareViaLink.copyLink") : null,
          value: url
        })]
      }), /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex flex-shrink-0 items-center gap-1 sm:gap-2",
        children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
          "data-cy": "preview-button",
          "data-testid": "preview-button",
          href: previewUrl || url,
          icon: ExternalLink,
          style: "secondary",
          target: "_blank",
          tooltipProps: {
            content: t("neetoMolecules.shareViaLink.view", {
              entity: entityName
            }),
            position: "top",
            touch: ["hold", 500]
          }
        }), isDropdownEnabled && /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [/*#__PURE__*/jsxRuntime.jsx(MoreDropdown, {
            menuItems: [{
              isVisible: enabledOptions.regenerate || neetoCist.isPresent(enabledOptions.regenerate),
              "data-testid": "regenerate-url-button",
              "data-cy": "regenerate-url-button",
              onClick: function onClick() {
                return setIsRegenerateURLModalOpen(true);
              },
              label: t("neetoMolecules.shareViaLink.regenerateUrl.title"),
              key: "regenerate-url-option"
            }, {
              isVisible: enabledOptions.edit,
              "data-testid": "edit-url-button",
              "data-cy": "edit-url-button",
              onClick: function onClick() {
                return setIsEditURLModalOpen(true);
              },
              label: t("neetoMolecules.shareViaLink.editUrl.title"),
              key: "edit-url-option"
            }]
          }), /*#__PURE__*/jsxRuntime.jsx(RegenerateURL, {
            handleRegenerate: handleRegenerate,
            isLoading: isLoading,
            url: url,
            isOpen: isRegenerateURLModalOpen,
            regenerateConfig: enabledOptions.regenerate,
            onClose: function onClose() {
              return setIsRegenerateURLModalOpen(false);
            }
          }), /*#__PURE__*/jsxRuntime.jsx(EditURL, {
            editUrlProps: editUrlProps,
            handleEdit: handleEdit,
            isLoading: isLoading,
            url: url,
            isOpen: isEditURLModalOpen,
            onClose: function onClose() {
              return setIsEditURLModalOpen(false);
            }
          })]
        })]
      })]
    })
  });
};

var _excluded = ["title", "link", "description", "Icon", "onClick", "helpPopoverProps"];
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 Card = function Card(_ref) {
  var title = _ref.title,
    link = _ref.link,
    description = _ref.description,
    Icon = _ref.Icon,
    _ref$onClick = _ref.onClick,
    onClick = _ref$onClick === void 0 ? neetoCist.noop : _ref$onClick,
    helpPopoverProps = _ref.helpPopoverProps,
    otherProps = _objectWithoutProperties(_ref, _excluded);
  var Component = neetoCist.isPresent(link) ? reactRouterDom.Link : "div";
  return /*#__PURE__*/jsxRuntime.jsxs(Component, _objectSpread(_objectSpread({
    onClick: onClick,
    className: "neeto-ui-border-gray-300 neeto-ui-rounded-lg neeto-molecules-share-landing__card flex cursor-pointer flex-col gap-3 border p-3",
    to: link
  }, otherProps), {}, {
    children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-2",
      children: [Icon && /*#__PURE__*/jsxRuntime.jsx(Icon, {
        className: "neeto-ui-text-gray-500 flex-shrink-0",
        size: 24
      }), /*#__PURE__*/jsxRuntime.jsxs(Typography, {
        className: "neeto-molecules-share-landing__card-title min-w-0 flex-grow break-words",
        style: "h4",
        children: [title, helpPopoverProps && /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [" ", /*#__PURE__*/jsxRuntime.jsx(HelpPopover, _objectSpread({}, helpPopoverProps))]
        })]
      })]
    }), description && /*#__PURE__*/jsxRuntime.jsx(Typography, {
      className: "neeto-molecules-share-landing__card-desc break-words",
      lineHeight: "normal",
      style: "body2",
      children: description
    })]
  }));
};

var ShareBlock = function ShareBlock(_ref) {
  var moreOptions = _ref.moreOptions,
    disableShareSocialMedia = _ref.disableShareSocialMedia,
    disableQRDownload = _ref.disableQRDownload,
    socialMediaProps = _ref.socialMediaProps,
    qrCodeProps = _ref.qrCodeProps,
    entity = _ref.entity,
    urls = _ref.urls;
  var location = reactRouterDom.useLocation();
  var history = reactRouterDom.useHistory();
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var handleNavigate = function handleNavigate(subPath) {
    // eslint-disable-next-line @bigbinary/neeto/use-common-routes
    history.push("".concat(location.pathname, "/").concat(subPath));
  };
  var hasMoreOptions = neetoCist.isPresent(moreOptions);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: classnames("grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3", {
      "neeto-ui-border-gray-200 mt-8 border-t pt-8": neetoCist.isNotEmpty(urls)
    }),
    children: [hasMoreOptions && moreOptions.filter(function (_ref2) {
      var permissions = _ref2.permissions;
      return neetoCist.isNotPresent(permissions) || globalProps.permissions.some(ramda.includes(ramda.__, permissions));
    }).map(function (_ref3) {
      var title = _ref3.title,
        link = _ref3.link,
        Icon = _ref3.icon,
        onClick = _ref3.onClick,
        dataCy = _ref3.dataCy,
        description = _ref3.description,
        helpPopoverProps = _ref3.helpPopoverProps;
      return /*#__PURE__*/React.createElement(Card, {
        Icon: Icon,
        description: description,
        helpPopoverProps: helpPopoverProps,
        link: link,
        onClick: onClick,
        title: title,
        "data-cy": dataCy,
        "data-testid": dataCy,
        key: link
      });
    }), !disableShareSocialMedia && /*#__PURE__*/jsxRuntime.jsx(Card, {
      Icon: Share,
      "data-cy": "social-share-card",
      "data-testid": "social-share-card",
      description: (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.cardDescription) || t("neetoMolecules.shareViaLink.socialMediaShare.description"),
      title: (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.cardTitle) || t("neetoMolecules.shareViaLink.socialMediaShare.title"),
      onClick: function onClick() {
        return handleNavigate("social-media");
      }
    }), !disableQRDownload && entity && /*#__PURE__*/jsxRuntime.jsx(Card, {
      Icon: QrCode,
      "data-cy": "qr-code-card",
      "data-testid": "qr-code-card",
      description: (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.cardDescription) || t("neetoMolecules.shareViaLink.qrCode.description"),
      title: (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.cardTitle) || t("neetoMolecules.shareViaLink.qrCode.title"),
      onClick: function onClick() {
        return handleNavigate("qrcode");
      }
    })]
  });
};

var MainPanel = function MainPanel(_ref) {
  var _urls$;
  var title = _ref.title,
    description = _ref.description,
    qrCodeProps = _ref.qrCodeProps,
    socialMediaProps = _ref.socialMediaProps,
    _ref$isLoading = _ref.isLoading,
    isLoading = _ref$isLoading === void 0 ? false : _ref$isLoading,
    _ref$enabledOptions = _ref.enabledOptions,
    enabledOptions = _ref$enabledOptions === void 0 ? {
      regenerate: false,
      edit: false
    } : _ref$enabledOptions,
    _ref$urls = _ref.urls,
    urls = _ref$urls === void 0 ? [] : _ref$urls,
    entity = _ref.entity,
    entityName = _ref.entityName,
    _ref$handleEdit = _ref.handleEdit,
    handleEdit = _ref$handleEdit === void 0 ? neetoCist.noop : _ref$handleEdit,
    _ref$handleRegenerate = _ref.handleRegenerate,
    handleRegenerate = _ref$handleRegenerate === void 0 ? neetoCist.noop : _ref$handleRegenerate,
    moreOptions = _ref.moreOptions,
    _ref$disableShareSoci = _ref.disableShareSocialMedia,
    disableShareSocialMedia = _ref$disableShareSoci === void 0 ? false : _ref$disableShareSoci,
    _ref$disableQRDownloa = _ref.disableQRDownload,
    disableQRDownload = _ref$disableQRDownloa === void 0 ? false : _ref$disableQRDownloa,
    _ref$publicLinkExpiry = _ref.publicLinkExpiryConfiguration,
    publicLinkExpiryConfiguration = _ref$publicLinkExpiry === void 0 ? {} : _ref$publicLinkExpiry,
    customTopContent = _ref.customTopContent,
    customBottomContent = _ref.customBottomContent;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var shouldShowShareBlock = !disableQRDownload || !disableShareSocialMedia || neetoCist.isPresent(moreOptions);
  return /*#__PURE__*/jsxRuntime.jsx(Container, {
    className: "neeto-ui-bg-gray-100 neeto-molecule-share-landing-page",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "mx-auto w-full max-w-5xl py-10",
      children: [customTopContent, /*#__PURE__*/jsxRuntime.jsx(Typography, {
        "data-cy": "share-your-meeting-heading",
        lineHeight: "tight",
        style: "h2",
        className: classnames({
          "mb-2": neetoCist.isPresent(description),
          "mb-6": !neetoCist.isPresent(description)
        }),
        children: title || t("neetoMolecules.shareViaLink.title", {
          productName: globalProps.appName
        })
      }), description && /*#__PURE__*/jsxRuntime.jsx(Typography, {
        className: "mb-6",
        "data-cy": "share-your-meeting-heading",
        lineHeight: "normal",
        style: "body1",
        children: description
      }), /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "neeto-ui-rounded-lg neeto-ui-bg-white p-6 sm:p-8",
        "data-testid": "share-via-link",
        children: [neetoCist.isNotEmpty(urls) && /*#__PURE__*/jsxRuntime.jsxs("div", {
          className: "flex flex-col gap-y-1",
          children: [/*#__PURE__*/jsxRuntime.jsx("div", {
            className: "inline-flex max-w-full flex-col gap-y-4",
            children: urls === null || urls === void 0 ? void 0 : urls.map(function (urlOption) {
              return /*#__PURE__*/React.createElement(Link, {
                enabledOptions: enabledOptions,
                entityName: entityName,
                handleEdit: handleEdit,
                handleRegenerate: handleRegenerate,
                isLoading: isLoading,
                editUrlProps: ramda.omit(["url"], urlOption),
                key: urlOption.url,
                previewUrl: urlOption.previewUrl,
                url: urlOption.url
              });
            })
          }), neetoCist.isPresent(publicLinkExpiryConfiguration) && /*#__PURE__*/jsxRuntime.jsx(ExpiryNotice, {
            expiryConfiguration: publicLinkExpiryConfiguration
          })]
        }), shouldShowShareBlock && /*#__PURE__*/jsxRuntime.jsx(ShareBlock, {
          disableQRDownload: disableQRDownload,
          disableShareSocialMedia: disableShareSocialMedia,
          entity: entity,
          moreOptions: moreOptions,
          qrCodeProps: qrCodeProps,
          socialMediaProps: socialMediaProps,
          urls: urls,
          url: (_urls$ = urls[0]) === null || _urls$ === void 0 ? void 0 : _urls$.url
        })]
      }), customBottomContent]
    })
  });
};

var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};

// src/third-party/qrcodegen/index.ts
/**
 * @license QR Code generator library (TypeScript)
 * Copyright (c) Project Nayuki.
 * SPDX-License-Identifier: MIT
 */
var qrcodegen;
((qrcodegen2) => {
  const _QrCode = class {
    constructor(version, errorCorrectionLevel, dataCodewords, msk) {
      this.version = version;
      this.errorCorrectionLevel = errorCorrectionLevel;
      this.modules = [];
      this.isFunction = [];
      if (version < _QrCode.MIN_VERSION || version > _QrCode.MAX_VERSION)
        throw new RangeError("Version value out of range");
      if (msk < -1 || msk > 7)
        throw new RangeError("Mask value out of range");
      this.size = version * 4 + 17;
      let row = [];
      for (let i = 0; i < this.size; i++)
        row.push(false);
      for (let i = 0; i < this.size; i++) {
        this.modules.push(row.slice());
        this.isFunction.push(row.slice());
      }
      this.drawFunctionPatterns();
      const allCodewords = this.addEccAndInterleave(dataCodewords);
      this.drawCodewords(allCodewords);
      if (msk == -1) {
        let minPenalty = 1e9;
        for (let i = 0; i < 8; i++) {
          this.applyMask(i);
          this.drawFormatBits(i);
          const penalty = this.getPenaltyScore();
          if (penalty < minPenalty) {
            msk = i;
            minPenalty = penalty;
          }
          this.applyMask(i);
        }
      }
      assert(0 <= msk && msk <= 7);
      this.mask = msk;
      this.applyMask(msk);
      this.drawFormatBits(msk);
      this.isFunction = [];
    }
    static encodeText(text, ecl) {
      const segs = qrcodegen2.QrSegment.makeSegments(text);
      return _QrCode.encodeSegments(segs, ecl);
    }
    static encodeBinary(data, ecl) {
      const seg = qrcodegen2.QrSegment.makeBytes(data);
      return _QrCode.encodeSegments([seg], ecl);
    }
    static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
      if (!(_QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= _QrCode.MAX_VERSION) || mask < -1 || mask > 7)
        throw new RangeError("Invalid value");
      let version;
      let dataUsedBits;
      for (version = minVersion; ; version++) {
        const dataCapacityBits2 = _QrCode.getNumDataCodewords(version, ecl) * 8;
        const usedBits = QrSegment.getTotalBits(segs, version);
        if (usedBits <= dataCapacityBits2) {
          dataUsedBits = usedBits;
          break;
        }
        if (version >= maxVersion)
          throw new RangeError("Data too long");
      }
      for (const newEcl of [_QrCode.Ecc.MEDIUM, _QrCode.Ecc.QUARTILE, _QrCode.Ecc.HIGH]) {
        if (boostEcl && dataUsedBits <= _QrCode.getNumDataCodewords(version, newEcl) * 8)
          ecl = newEcl;
      }
      let bb = [];
      for (const seg of segs) {
        appendBits(seg.mode.modeBits, 4, bb);
        appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
        for (const b of seg.getData())
          bb.push(b);
      }
      assert(bb.length == dataUsedBits);
      const dataCapacityBits = _QrCode.getNumDataCodewords(version, ecl) * 8;
      assert(bb.length <= dataCapacityBits);
      appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
      appendBits(0, (8 - bb.length % 8) % 8, bb);
      assert(bb.length % 8 == 0);
      for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 236 ^ 17)
        appendBits(padByte, 8, bb);
      let dataCodewords = [];
      while (dataCodewords.length * 8 < bb.length)
        dataCodewords.push(0);
      bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7));
      return new _QrCode(version, ecl, dataCodewords, mask);
    }
    getModule(x, y) {
      return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
    }
    getModules() {
      return this.modules;
    }
    drawFunctionPatterns() {
      for (let i = 0; i < this.size; i++) {
        this.setFunctionModule(6, i, i % 2 == 0);
        this.setFunctionModule(i, 6, i % 2 == 0);
      }
      this.drawFinderPattern(3, 3);
      this.drawFinderPattern(this.size - 4, 3);
      this.drawFinderPattern(3, this.size - 4);
      const alignPatPos = this.getAlignmentPatternPositions();
      const numAlign = alignPatPos.length;
      for (let i = 0; i < numAlign; i++) {
        for (let j = 0; j < numAlign; j++) {
          if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
            this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
        }
      }
      this.drawFormatBits(0);
      this.drawVersion();
    }
    drawFormatBits(mask) {
      const data = this.errorCorrectionLevel.formatBits << 3 | mask;
      let rem = data;
      for (let i = 0; i < 10; i++)
        rem = rem << 1 ^ (rem >>> 9) * 1335;
      const bits = (data << 10 | rem) ^ 21522;
      assert(bits >>> 15 == 0);
      for (let i = 0; i <= 5; i++)
        this.setFunctionModule(8, i, getBit(bits, i));
      this.setFunctionModule(8, 7, getBit(bits, 6));
      this.setFunctionModule(8, 8, getBit(bits, 7));
      this.setFunctionModule(7, 8, getBit(bits, 8));
      for (let i = 9; i < 15; i++)
        this.setFunctionModule(14 - i, 8, getBit(bits, i));
      for (let i = 0; i < 8; i++)
        this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
      for (let i = 8; i < 15; i++)
        this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
      this.setFunctionModule(8, this.size - 8, true);
    }
    drawVersion() {
      if (this.version < 7)
        return;
      let rem = this.version;
      for (let i = 0; i < 12; i++)
        rem = rem << 1 ^ (rem >>> 11) * 7973;
      const bits = this.version << 12 | rem;
      assert(bits >>> 18 == 0);
      for (let i = 0; i < 18; i++) {
        const color = getBit(bits, i);
        const a = this.size - 11 + i % 3;
        const b = Math.floor(i / 3);
        this.setFunctionModule(a, b, color);
        this.setFunctionModule(b, a, color);
      }
    }
    drawFinderPattern(x, y) {
      for (let dy = -4; dy <= 4; dy++) {
        for (let dx = -4; dx <= 4; dx++) {
          const dist = Math.max(Math.abs(dx), Math.abs(dy));
          const xx = x + dx;
          const yy = y + dy;
          if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
            this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
        }
      }
    }
    drawAlignmentPattern(x, y) {
      for (let dy = -2; dy <= 2; dy++) {
        for (let dx = -2; dx <= 2; dx++)
          this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
      }
    }
    setFunctionModule(x, y, isDark) {
      this.modules[y][x] = isDark;
      this.isFunction[y][x] = true;
    }
    addEccAndInterleave(data) {
      const ver = this.version;
      const ecl = this.errorCorrectionLevel;
      if (data.length != _QrCode.getNumDataCodewords(ver, ecl))
        throw new RangeError("Invalid argument");
      const numBlocks = _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
      const blockEccLen = _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
      const rawCodewords = Math.floor(_QrCode.getNumRawDataModules(ver) / 8);
      const numShortBlocks = numBlocks - rawCodewords % numBlocks;
      const shortBlockLen = Math.floor(rawCodewords / numBlocks);
      let blocks = [];
      const rsDiv = _QrCode.reedSolomonComputeDivisor(blockEccLen);
      for (let i = 0, k = 0; i < numBlocks; i++) {
        let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
        k += dat.length;
        const ecc = _QrCode.reedSolomonComputeRemainder(dat, rsDiv);
        if (i < numShortBlocks)
          dat.push(0);
        blocks.push(dat.concat(ecc));
      }
      let result = [];
      for (let i = 0; i < blocks[0].length; i++) {
        blocks.forEach((block, j) => {
          if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
            result.push(block[i]);
        });
      }
      assert(result.length == rawCodewords);
      return result;
    }
    drawCodewords(data) {
      if (data.length != Math.floor(_QrCode.getNumRawDataModules(this.version) / 8))
        throw new RangeError("Invalid argument");
      let i = 0;
      for (let right = this.size - 1; right >= 1; right -= 2) {
        if (right == 6)
          right = 5;
        for (let vert = 0; vert < this.size; vert++) {
          for (let j = 0; j < 2; j++) {
            const x = right - j;
            const upward = (right + 1 & 2) == 0;
            const y = upward ? this.size - 1 - vert : vert;
            if (!this.isFunction[y][x] && i < data.length * 8) {
              this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
              i++;
            }
          }
        }
      }
      assert(i == data.length * 8);
    }
    applyMask(mask) {
      if (mask < 0 || mask > 7)
        throw new RangeError("Mask value out of range");
      for (let y = 0; y < this.size; y++) {
        for (let x = 0; x < this.size; x++) {
          let invert;
          switch (mask) {
            case 0:
              invert = (x + y) % 2 == 0;
              break;
            case 1:
              invert = y % 2 == 0;
              break;
            case 2:
              invert = x % 3 == 0;
              break;
            case 3:
              invert = (x + y) % 3 == 0;
              break;
            case 4:
              invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
              break;
            case 5:
              invert = x * y % 2 + x * y % 3 == 0;
              break;
            case 6:
              invert = (x * y % 2 + x * y % 3) % 2 == 0;
              break;
            case 7:
              invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
              break;
            default:
              throw new Error("Unreachable");
          }
          if (!this.isFunction[y][x] && invert)
            this.modules[y][x] = !this.modules[y][x];
        }
      }
    }
    getPenaltyScore() {
      let result = 0;
      for (let y = 0; y < this.size; y++) {
        let runColor = false;
        let runX = 0;
        let runHistory = [0, 0, 0, 0, 0, 0, 0];
        for (let x = 0; x < this.size; x++) {
          if (this.modules[y][x] == runColor) {
            runX++;
            if (runX == 5)
              result += _QrCode.PENALTY_N1;
            else if (runX > 5)
              result++;
          } else {
            this.finderPenaltyAddHistory(runX, runHistory);
            if (!runColor)
              result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3;
            runColor = this.modules[y][x];
            runX = 1;
          }
        }
        result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * _QrCode.PENALTY_N3;
      }
      for (let x = 0; x < this.size; x++) {
        let runColor = false;
        let runY = 0;
        let runHistory = [0, 0, 0, 0, 0, 0, 0];
        for (let y = 0; y < this.size; y++) {
          if (this.modules[y][x] == runColor) {
            runY++;
            if (runY == 5)
              result += _QrCode.PENALTY_N1;
            else if (runY > 5)
              result++;
          } else {
            this.finderPenaltyAddHistory(runY, runHistory);
            if (!runColor)
              result += this.finderPenaltyCountPatterns(runHistory) * _QrCode.PENALTY_N3;
            runColor = this.modules[y][x];
            runY = 1;
          }
        }
        result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * _QrCode.PENALTY_N3;
      }
      for (let y = 0; y < this.size - 1; y++) {
        for (let x = 0; x < this.size - 1; x++) {
          const color = this.modules[y][x];
          if (color == this.modules[y][x + 1] && color == this.modules[y + 1][x] && color == this.modules[y + 1][x + 1])
            result += _QrCode.PENALTY_N2;
        }
      }
      let dark = 0;
      for (const row of this.modules)
        dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
      const total = this.size * this.size;
      const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
      assert(0 <= k && k <= 9);
      result += k * _QrCode.PENALTY_N4;
      assert(0 <= result && result <= 2568888);
      return result;
    }
    getAlignmentPatternPositions() {
      if (this.version == 1)
        return [];
      else {
        const numAlign = Math.floor(this.version / 7) + 2;
        const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
        let result = [6];
        for (let pos = this.size - 7; result.length < numAlign; pos -= step)
          result.splice(1, 0, pos);
        return result;
      }
    }
    static getNumRawDataModules(ver) {
      if (ver < _QrCode.MIN_VERSION || ver > _QrCode.MAX_VERSION)
        throw new RangeError("Version number out of range");
      let result = (16 * ver + 128) * ver + 64;
      if (ver >= 2) {
        const numAlign = Math.floor(ver / 7) + 2;
        result -= (25 * numAlign - 10) * numAlign - 55;
        if (ver >= 7)
          result -= 36;
      }
      assert(208 <= result && result <= 29648);
      return result;
    }
    static getNumDataCodewords(ver, ecl) {
      return Math.floor(_QrCode.getNumRawDataModules(ver) / 8) - _QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * _QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
    }
    static reedSolomonComputeDivisor(degree) {
      if (degree < 1 || degree > 255)
        throw new RangeError("Degree out of range");
      let result = [];
      for (let i = 0; i < degree - 1; i++)
        result.push(0);
      result.push(1);
      let root = 1;
      for (let i = 0; i < degree; i++) {
        for (let j = 0; j < result.length; j++) {
          result[j] = _QrCode.reedSolomonMultiply(result[j], root);
          if (j + 1 < result.length)
            result[j] ^= result[j + 1];
        }
        root = _QrCode.reedSolomonMultiply(root, 2);
      }
      return result;
    }
    static reedSolomonComputeRemainder(data, divisor) {
      let result = divisor.map((_) => 0);
      for (const b of data) {
        const factor = b ^ result.shift();
        result.push(0);
        divisor.forEach((coef, i) => result[i] ^= _QrCode.reedSolomonMultiply(coef, factor));
      }
      return result;
    }
    static reedSolomonMultiply(x, y) {
      if (x >>> 8 != 0 || y >>> 8 != 0)
        throw new RangeError("Byte out of range");
      let z = 0;
      for (let i = 7; i >= 0; i--) {
        z = z << 1 ^ (z >>> 7) * 285;
        z ^= (y >>> i & 1) * x;
      }
      assert(z >>> 8 == 0);
      return z;
    }
    finderPenaltyCountPatterns(runHistory) {
      const n = runHistory[1];
      assert(n <= this.size * 3);
      const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
      return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
    }
    finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {
      if (currentRunColor) {
        this.finderPenaltyAddHistory(currentRunLength, runHistory);
        currentRunLength = 0;
      }
      currentRunLength += this.size;
      this.finderPenaltyAddHistory(currentRunLength, runHistory);
      return this.finderPenaltyCountPatterns(runHistory);
    }
    finderPenaltyAddHistory(currentRunLength, runHistory) {
      if (runHistory[0] == 0)
        currentRunLength += this.size;
      runHistory.pop();
      runHistory.unshift(currentRunLength);
    }
  };
  let QrCode = _QrCode;
  QrCode.MIN_VERSION = 1;
  QrCode.MAX_VERSION = 40;
  QrCode.PENALTY_N1 = 3;
  QrCode.PENALTY_N2 = 3;
  QrCode.PENALTY_N3 = 40;
  QrCode.PENALTY_N4 = 10;
  QrCode.ECC_CODEWORDS_PER_BLOCK = [
    [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
    [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
    [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
    [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
  ];
  QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
    [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
    [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
    [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
    [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81]
  ];
  qrcodegen2.QrCode = QrCode;
  function appendBits(val, len, bb) {
    if (len < 0 || len > 31 || val >>> len != 0)
      throw new RangeError("Value out of range");
    for (let i = len - 1; i >= 0; i--)
      bb.push(val >>> i & 1);
  }
  function getBit(x, i) {
    return (x >>> i & 1) != 0;
  }
  function assert(cond) {
    if (!cond)
      throw new Error("Assertion error");
  }
  const _QrSegment = class {
    constructor(mode, numChars, bitData) {
      this.mode = mode;
      this.numChars = numChars;
      this.bitData = bitData;
      if (numChars < 0)
        throw new RangeError("Invalid argument");
      this.bitData = bitData.slice();
    }
    static makeBytes(data) {
      let bb = [];
      for (const b of data)
        appendBits(b, 8, bb);
      return new _QrSegment(_QrSegment.Mode.BYTE, data.length, bb);
    }
    static makeNumeric(digits) {
      if (!_QrSegment.isNumeric(digits))
        throw new RangeError("String contains non-numeric characters");
      let bb = [];
      for (let i = 0; i < digits.length; ) {
        const n = Math.min(digits.length - i, 3);
        appendBits(parseInt(digits.substr(i, n), 10), n * 3 + 1, bb);
        i += n;
      }
      return new _QrSegment(_QrSegment.Mode.NUMERIC, digits.length, bb);
    }
    static makeAlphanumeric(text) {
      if (!_QrSegment.isAlphanumeric(text))
        throw new RangeError("String contains unencodable characters in alphanumeric mode");
      let bb = [];
      let i;
      for (i = 0; i + 2 <= text.length; i += 2) {
        let temp = _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
        temp += _QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
        appendBits(temp, 11, bb);
      }
      if (i < text.length)
        appendBits(_QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
      return new _QrSegment(_QrSegment.Mode.ALPHANUMERIC, text.length, bb);
    }
    static makeSegments(text) {
      if (text == "")
        return [];
      else if (_QrSegment.isNumeric(text))
        return [_QrSegment.makeNumeric(text)];
      else if (_QrSegment.isAlphanumeric(text))
        return [_QrSegment.makeAlphanumeric(text)];
      else
        return [_QrSegment.makeBytes(_QrSegment.toUtf8ByteArray(text))];
    }
    static makeEci(assignVal) {
      let bb = [];
      if (assignVal < 0)
        throw new RangeError("ECI assignment value out of range");
      else if (assignVal < 1 << 7)
        appendBits(assignVal, 8, bb);
      else if (assignVal < 1 << 14) {
        appendBits(2, 2, bb);
        appendBits(assignVal, 14, bb);
      } else if (assignVal < 1e6) {
        appendBits(6, 3, bb);
        appendBits(assignVal, 21, bb);
      } else
        throw new RangeError("ECI assignment value out of range");
      return new _QrSegment(_QrSegment.Mode.ECI, 0, bb);
    }
    static isNumeric(text) {
      return _QrSegment.NUMERIC_REGEX.test(text);
    }
    static isAlphanumeric(text) {
      return _QrSegment.ALPHANUMERIC_REGEX.test(text);
    }
    getData() {
      return this.bitData.slice();
    }
    static getTotalBits(segs, version) {
      let result = 0;
      for (const seg of segs) {
        const ccbits = seg.mode.numCharCountBits(version);
        if (seg.numChars >= 1 << ccbits)
          return Infinity;
        result += 4 + ccbits + seg.bitData.length;
      }
      return result;
    }
    static toUtf8ByteArray(str) {
      str = encodeURI(str);
      let result = [];
      for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) != "%")
          result.push(str.charCodeAt(i));
        else {
          result.push(parseInt(str.substr(i + 1, 2), 16));
          i += 2;
        }
      }
      return result;
    }
  };
  let QrSegment = _QrSegment;
  QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
  QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
  QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
  qrcodegen2.QrSegment = QrSegment;
})(qrcodegen || (qrcodegen = {}));
((qrcodegen2) => {
  ((QrCode2) => {
    const _Ecc = class {
      constructor(ordinal, formatBits) {
        this.ordinal = ordinal;
        this.formatBits = formatBits;
      }
    };
    let Ecc = _Ecc;
    Ecc.LOW = new _Ecc(0, 1);
    Ecc.MEDIUM = new _Ecc(1, 0);
    Ecc.QUARTILE = new _Ecc(2, 3);
    Ecc.HIGH = new _Ecc(3, 2);
    QrCode2.Ecc = Ecc;
  })(qrcodegen2.QrCode || (qrcodegen2.QrCode = {}));
})(qrcodegen || (qrcodegen = {}));
((qrcodegen2) => {
  ((QrSegment2) => {
    const _Mode = class {
      constructor(modeBits, numBitsCharCount) {
        this.modeBits = modeBits;
        this.numBitsCharCount = numBitsCharCount;
      }
      numCharCountBits(ver) {
        return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
      }
    };
    let Mode = _Mode;
    Mode.NUMERIC = new _Mode(1, [10, 12, 14]);
    Mode.ALPHANUMERIC = new _Mode(2, [9, 11, 13]);
    Mode.BYTE = new _Mode(4, [8, 16, 16]);
    Mode.KANJI = new _Mode(8, [8, 10, 12]);
    Mode.ECI = new _Mode(7, [0, 0, 0]);
    QrSegment2.Mode = Mode;
  })(qrcodegen2.QrSegment || (qrcodegen2.QrSegment = {}));
})(qrcodegen || (qrcodegen = {}));
var qrcodegen_default = qrcodegen;

// src/index.tsx
/**
 * @license qrcode.react
 * Copyright (c) Paul O'Shannessy
 * SPDX-License-Identifier: ISC
 */
var ERROR_LEVEL_MAP = {
  L: qrcodegen_default.QrCode.Ecc.LOW,
  M: qrcodegen_default.QrCode.Ecc.MEDIUM,
  Q: qrcodegen_default.QrCode.Ecc.QUARTILE,
  H: qrcodegen_default.QrCode.Ecc.HIGH
};
var DEFAULT_SIZE = 128;
var DEFAULT_LEVEL = "L";
var DEFAULT_BGCOLOR = "#FFFFFF";
var DEFAULT_FGCOLOR = "#000000";
var DEFAULT_INCLUDEMARGIN = false;
var MARGIN_SIZE = 4;
var DEFAULT_IMG_SCALE = 0.1;
function generatePath(modules, margin = 0) {
  const ops = [];
  modules.forEach(function(row, y) {
    let start = null;
    row.forEach(function(cell, x) {
      if (!cell && start !== null) {
        ops.push(`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`);
        start = null;
        return;
      }
      if (x === row.length - 1) {
        if (!cell) {
          return;
        }
        if (start === null) {
          ops.push(`M${x + margin},${y + margin} h1v1H${x + margin}z`);
        } else {
          ops.push(`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z`);
        }
        return;
      }
      if (cell && start === null) {
        start = x;
      }
    });
  });
  return ops.join("");
}
function excavateModules(modules, excavation) {
  return modules.slice().map((row, y) => {
    if (y < excavation.y || y >= excavation.y + excavation.h) {
      return row;
    }
    return row.map((cell, x) => {
      if (x < excavation.x || x >= excavation.x + excavation.w) {
        return cell;
      }
      return false;
    });
  });
}
function getImageSettings(cells, size, includeMargin, imageSettings) {
  if (imageSettings == null) {
    return null;
  }
  const margin = includeMargin ? MARGIN_SIZE : 0;
  const numCells = cells.length + margin * 2;
  const defaultSize = Math.floor(size * DEFAULT_IMG_SCALE);
  const scale = numCells / size;
  const w = (imageSettings.width || defaultSize) * scale;
  const h = (imageSettings.height || defaultSize) * scale;
  const x = imageSettings.x == null ? cells.length / 2 - w / 2 : imageSettings.x * scale;
  const y = imageSettings.y == null ? cells.length / 2 - h / 2 : imageSettings.y * scale;
  let excavation = null;
  if (imageSettings.excavate) {
    let floorX = Math.floor(x);
    let floorY = Math.floor(y);
    let ceilW = Math.ceil(w + x - floorX);
    let ceilH = Math.ceil(h + y - floorY);
    excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };
  }
  return { x, y, h, w, excavation };
}
var SUPPORTS_PATH2D = function() {
  try {
    new Path2D().addPath(new Path2D());
  } catch (e) {
    return false;
  }
  return true;
}();
function QRCodeCanvas(props) {
  const _a = props, {
    value,
    size = DEFAULT_SIZE,
    level = DEFAULT_LEVEL,
    bgColor = DEFAULT_BGCOLOR,
    fgColor = DEFAULT_FGCOLOR,
    includeMargin = DEFAULT_INCLUDEMARGIN,
    style,
    imageSettings
  } = _a, otherProps = __objRest(_a, [
    "value",
    "size",
    "level",
    "bgColor",
    "fgColor",
    "includeMargin",
    "style",
    "imageSettings"
  ]);
  const imgSrc = imageSettings == null ? void 0 : imageSettings.src;
  const _canvas = React.useRef(null);
  const _image = React.useRef(null);
  const [isImgLoaded, setIsImageLoaded] = React.useState(false);
  React.useEffect(() => {
    if (_canvas.current != null) {
      const canvas = _canvas.current;
      const ctx = canvas.getContext("2d");
      if (!ctx) {
        return;
      }
      let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
      const margin = includeMargin ? MARGIN_SIZE : 0;
      const numCells = cells.length + margin * 2;
      const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
      const image = _image.current;
      const haveImageToRender = calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0;
      if (haveImageToRender) {
        if (calculatedImageSettings.excavation != null) {
          cells = excavateModules(cells, calculatedImageSettings.excavation);
        }
      }
      const pixelRatio = window.devicePixelRatio || 1;
      canvas.height = canvas.width = size * pixelRatio;
      const scale = size / numCells * pixelRatio;
      ctx.scale(scale, scale);
      ctx.fillStyle = bgColor;
      ctx.fillRect(0, 0, numCells, numCells);
      ctx.fillStyle = fgColor;
      if (SUPPORTS_PATH2D) {
        ctx.fill(new Path2D(generatePath(cells, margin)));
      } else {
        cells.forEach(function(row, rdx) {
          row.forEach(function(cell, cdx) {
            if (cell) {
              ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
            }
          });
        });
      }
      if (haveImageToRender) {
        ctx.drawImage(image, calculatedImageSettings.x + margin, calculatedImageSettings.y + margin, calculatedImageSettings.w, calculatedImageSettings.h);
      }
    }
  });
  React.useEffect(() => {
    setIsImageLoaded(false);
  }, [imgSrc]);
  const canvasStyle = __spreadValues({ height: size, width: size }, style);
  let img = null;
  if (imgSrc != null) {
    img = /* @__PURE__ */ React.createElement("img", {
      src: imgSrc,
      key: imgSrc,
      style: { display: "none" },
      onLoad: () => {
        setIsImageLoaded(true);
      },
      ref: _image
    });
  }
  return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("canvas", __spreadValues({
    style: canvasStyle,
    height: size,
    width: size,
    ref: _canvas
  }, otherProps)), img);
}
function QRCodeSVG(props) {
  const _a = props, {
    value,
    size = DEFAULT_SIZE,
    level = DEFAULT_LEVEL,
    bgColor = DEFAULT_BGCOLOR,
    fgColor = DEFAULT_FGCOLOR,
    includeMargin = DEFAULT_INCLUDEMARGIN,
    imageSettings
  } = _a, otherProps = __objRest(_a, [
    "value",
    "size",
    "level",
    "bgColor",
    "fgColor",
    "includeMargin",
    "imageSettings"
  ]);
  let cells = qrcodegen_default.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
  const margin = includeMargin ? MARGIN_SIZE : 0;
  const numCells = cells.length + margin * 2;
  const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
  let image = null;
  if (imageSettings != null && calculatedImageSettings != null) {
    if (calculatedImageSettings.excavation != null) {
      cells = excavateModules(cells, calculatedImageSettings.excavation);
    }
    image = /* @__PURE__ */ React.createElement("image", {
      xlinkHref: imageSettings.src,
      height: calculatedImageSettings.h,
      width: calculatedImageSettings.w,
      x: calculatedImageSettings.x + margin,
      y: calculatedImageSettings.y + margin,
      preserveAspectRatio: "none"
    });
  }
  const fgPath = generatePath(cells, margin);
  return /* @__PURE__ */ React.createElement("svg", __spreadValues({
    height: size,
    width: size,
    viewBox: `0 0 ${numCells} ${numCells}`
  }, otherProps), /* @__PURE__ */ React.createElement("path", {
    fill: bgColor,
    d: `M0,0 h${numCells}v${numCells}H0z`,
    shapeRendering: "crispEdges"
  }), /* @__PURE__ */ React.createElement("path", {
    fill: fgColor,
    d: fgPath,
    shapeRendering: "crispEdges"
  }), image);
}
var QRCode$1 = (props) => {
  const _a = props, { renderAs } = _a, otherProps = __objRest(_a, ["renderAs"]);
  if (renderAs === "svg") {
    return /* @__PURE__ */ React.createElement(QRCodeSVG, __spreadValues({}, otherProps));
  }
  return /* @__PURE__ */ React.createElement(QRCodeCanvas, __spreadValues({}, otherProps));
};

var QRCode = function QRCode(_ref) {
  var entity = _ref.entity,
    qrCodeProps = _ref.qrCodeProps,
    url = _ref.url,
    shareUrl = _ref.shareUrl;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  if (!entity) return null;
  var id = entity.id,
    name = entity.name;
  var canvasId = "qrcode-share-".concat(id);
  var handleDownloadQRCode = function handleDownloadQRCode() {
    var canvas = document.getElementById(canvasId);
    if (canvas) downloadCanvas(canvas, {
      name: neetoCist.slugify(name)
    });
  };
  var handleCopyQRCode = function handleCopyQRCode() {
    var canvas = document.getElementById(canvasId);
    if (canvas) copyCanvasToClipboard(canvas, handleDownloadQRCode);
  };
  var title = (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.pageTitle) || (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.cardTitle) || t("neetoMolecules.shareViaLink.qrCode.title");
  var description = (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.pageDescription) || (qrCodeProps === null || qrCodeProps === void 0 ? void 0 : qrCodeProps.cardDescription) || t("neetoMolecules.shareViaLink.qrCode.description");
  return /*#__PURE__*/jsxRuntime.jsxs(Container, {
    className: "neeto-molecules-embed-qr-code-landing-page py-8",
    children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
      className: "mb-4",
      "data-cy": "back-button",
      "data-testid": "back-button",
      icon: LeftArrow,
      iconPosition: "left",
      label: t("neetoMolecules.productEmbed.backToShare"),
      size: "small",
      style: "link",
      to: shareUrl
    }), /*#__PURE__*/jsxRuntime.jsx(Header$1, {
      className: "py-0",
      title: t("neetoMolecules.shareViaLink.qrCode.title")
    }), /*#__PURE__*/jsxRuntime.jsx(CardLayout, {
      description: description,
      title: title,
      actionBlock: /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "flex flex-wrap items-center gap-3",
        children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
          "data-cy": "qr-code-download-button",
          "data-testid": "qr-code-download-button",
          label: t("neetoMolecules.shareViaLink.qrCode.download"),
          style: "primary",
          onClick: handleDownloadQRCode
        }), /*#__PURE__*/jsxRuntime.jsx(CopyToClipboardButton, {
          "data-cy": "qr-code-copy-button",
          "data-testid": "qr-code-copy-button",
          label: t("neetoMolecules.shareViaLink.qrCode.copy"),
          style: "secondary",
          onClick: handleCopyQRCode
        })]
      }),
      children: /*#__PURE__*/jsxRuntime.jsx(QRCode$1, {
        className: "mt-6 cursor-pointer",
        "data-cy": "qr-code-image",
        "data-testid": "qr-code-image",
        id: canvasId,
        size: 160,
        style: {
          width: 160,
          height: 160
        },
        value: url,
        onClick: handleDownloadQRCode
      })
    })]
  });
};

var css = ".neeto-molecules-share-landing__card{outline:1px solid rgb(var(--neeto-ui-white))!important;transition:all .3s!important}.neeto-molecules-share-landing__card:hover{border-color:rgb(var(--neeto-ui-primary-500))!important;outline:1px solid rgb(var(--neeto-ui-primary-500))!important}.neeto-molecules-share-landing__card-title .neeto-molecule-help-popover-trigger{display:inline-block!important;vertical-align:middle}.neeto-molecules-share-link-button .neeto-ui-btn__icon{flex-shrink:0;order:-1}.neeto-molecules-share-link-button .neeto-ui-btn__label{flex-grow:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}";
injectCss.n(css,{});

var SocialMedia = function SocialMedia(_ref) {
  var socialMediaProps = _ref.socialMediaProps,
    url = _ref.url,
    shareUrl = _ref.shareUrl;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var title = (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.pageTitle) || (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.cardTitle) || t("neetoMolecules.shareViaLink.socialMediaShare.title");
  var description = (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.pageDescription) || (socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.cardDescription) || t("neetoMolecules.shareViaLink.socialMediaShare.description");
  return /*#__PURE__*/jsxRuntime.jsxs(Container, {
    className: "neeto-molecules-social-share-landing-page py-8",
    children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
      className: "mb-4",
      "data-cy": "back-button",
      "data-testid": "back-button",
      icon: LeftArrow,
      iconPosition: "left",
      label: t("neetoMolecules.productEmbed.backToShare"),
      size: "small",
      style: "link",
      to: shareUrl
    }), /*#__PURE__*/jsxRuntime.jsx(Header$1, {
      className: "py-0",
      title: t("neetoMolecules.shareViaLink.socialMediaShare.title")
    }), /*#__PURE__*/jsxRuntime.jsx(CardLayout, {
      description: description,
      title: title,
      actionBlock: /*#__PURE__*/jsxRuntime.jsx("div", {
        className: "flex flex-wrap items-center gap-3",
        children: Object.entries(SOCIAL_MEDIA_OPTIONS).map(function (_ref2) {
          var _ref3 = _slicedToArray(_ref2, 2),
            key = _ref3[0],
            _ref3$ = _ref3[1],
            label = _ref3$.label,
            Icon = _ref3$.icon,
            generateShareUrl = _ref3$.generateShareUrl;
          return /*#__PURE__*/React.createElement(Button, {
            label: label,
            "data-cy": "social-media-button-".concat(key),
            "data-testid": "social-media-button-".concat(key),
            icon: Icon,
            iconPosition: "right",
            key: key,
            rel: "noopener noreferrer",
            style: "tertiary",
            target: "_blank",
            href: generateShareUrl({
              url: url,
              title: socialMediaProps === null || socialMediaProps === void 0 ? void 0 : socialMediaProps.postTitle
            })
          }, /*#__PURE__*/jsxRuntime.jsx(Icon, {
            size: 24
          }));
        })
      })
    })]
  });
};

/* eslint-disable @bigbinary/neeto/use-common-routes */
var ShareViaLink = function ShareViaLink(_ref) {
  var title = _ref.title,
    description = _ref.description,
    _ref$isLoading = _ref.isLoading,
    isLoading = _ref$isLoading === void 0 ? false : _ref$isLoading,
    _ref$enabledOptions = _ref.enabledOptions,
    enabledOptions = _ref$enabledOptions === void 0 ? {
      regenerate: false,
      edit: false
    } : _ref$enabledOptions,
    _ref$urls = _ref.urls,
    urls = _ref$urls === void 0 ? [] : _ref$urls,
    entity = _ref.entity,
    entityName = _ref.entityName,
    _ref$handleEdit = _ref.handleEdit,
    handleEdit = _ref$handleEdit === void 0 ? neetoCist.noop : _ref$handleEdit,
    _ref$handleRegenerate = _ref.handleRegenerate,
    handleRegenerate = _ref$handleRegenerate === void 0 ? neetoCist.noop : _ref$handleRegenerate,
    _ref$disableShareSoci = _ref.disableShareSocialMedia,
    disableShareSocialMedia = _ref$disableShareSoci === void 0 ? false : _ref$disableShareSoci,
    _ref$disableQRDownloa = _ref.disableQRDownload,
    disableQRDownload = _ref$disableQRDownloa === void 0 ? false : _ref$disableQRDownloa,
    socialMediaProps = _ref.socialMediaProps,
    qrCodeProps = _ref.qrCodeProps,
    moreOptions = _ref.moreOptions,
    _ref$publicLinkExpiry = _ref.publicLinkExpiryConfiguration,
    publicLinkExpiryConfiguration = _ref$publicLinkExpiry === void 0 ? {} : _ref$publicLinkExpiry,
    customTopContent = _ref.customTopContent,
    customBottomContent = _ref.customBottomContent;
  var _useRouteMatch = reactRouterDom.useRouteMatch(),
    sharePath = _useRouteMatch.path,
    shareUrl = _useRouteMatch.url;
  return /*#__PURE__*/jsxRuntime.jsxs(reactRouterDom.Switch, {
    children: [/*#__PURE__*/jsxRuntime.jsx(reactRouterDom.Route, {
      exact: true,
      path: sharePath,
      render: function render() {
        return /*#__PURE__*/jsxRuntime.jsx(MainPanel, {
          customBottomContent: customBottomContent,
          customTopContent: customTopContent,
          description: description,
          disableQRDownload: disableQRDownload,
          disableShareSocialMedia: disableShareSocialMedia,
          enabledOptions: enabledOptions,
          entity: entity,
          entityName: entityName,
          handleEdit: handleEdit,
          handleRegenerate: handleRegenerate,
          isLoading: isLoading,
          moreOptions: moreOptions,
          publicLinkExpiryConfiguration: publicLinkExpiryConfiguration,
          qrCodeProps: qrCodeProps,
          socialMediaProps: socialMediaProps,
          title: title,
          urls: urls
        });
      }
    }), /*#__PURE__*/jsxRuntime.jsx(reactRouterDom.Route, {
      exact: true,
      path: "".concat(sharePath, "/qrcode"),
      render: function render() {
        var _urls$;
        return /*#__PURE__*/jsxRuntime.jsx(QRCode, {
          entity: entity,
          qrCodeProps: qrCodeProps,
          shareUrl: shareUrl,
          url: (_urls$ = urls[0]) === null || _urls$ === void 0 ? void 0 : _urls$.url
        });
      }
    }), /*#__PURE__*/jsxRuntime.jsx(reactRouterDom.Route, {
      exact: true,
      path: "".concat(sharePath, "/social-media"),
      render: function render() {
        var _urls$2;
        return /*#__PURE__*/jsxRuntime.jsx(SocialMedia, {
          shareUrl: shareUrl,
          socialMediaProps: socialMediaProps,
          url: (_urls$2 = urls[0]) === null || _urls$2 === void 0 ? void 0 : _urls$2.url
        });
      }
    }), neetoCist.isPresent(moreOptions) && moreOptions.map(function (_ref2) {
      var link = _ref2.link,
        element = _ref2.element,
        path = _ref2.path,
        permissions = _ref2.permissions;
      if (!link && !path) return null;
      return /*#__PURE__*/React.createElement(PrivateRoute, {
        permissions: permissions,
        exact: true,
        component: function component() {
          return element;
        },
        key: link,
        path: path || link
      });
    }), /*#__PURE__*/jsxRuntime.jsx(reactRouterDom.Route, {
      component: ErrorPage,
      path: "*"
    })]
  });
};

module.exports = ShareViaLink;
//# sourceMappingURL=ShareViaLink.js.map
