"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _ContextMenuComponents = require("../ContextMenu/ContextMenuComponents");
var _reactRedux = require("react-redux");
var _MESSAGE_INTERACTIONS = require("../../helpers/constants/MESSAGE_INTERACTIONS");
var _reactNative = require("react-native");
var Clipboard = _interopRequireWildcard(require("expo-clipboard"));
var _ToastContext = require("../../context/ToastContext");
var _InteractionsOverlay = require("./InteractionsOverlay");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const MessageInteractions = ({
  isReply,
  isUser,
  message,
  closeMenu,
  position,
  handleReplyMessage: replyMessage,
  handleDeleteMessage,
  handleEditMessage
}) => {
  const {
    showToast
  } = (0, _ToastContext.useToast)();
  const {
    present,
    dismiss,
    originX,
    originY
  } = (0, _InteractionsOverlay.useInteractionsOverlay)();
  const overlayId = (0, _react.useId)();
  const config = (0, _reactRedux.useSelector)(state => state.chatSettingStore.config);
  const [menuSize, setMenuSize] = (0, _react.useState)({
    width: 0,
    height: 0
  });
  const handleMenuLayout = e => {
    const {
      width,
      height
    } = e.nativeEvent.layout;
    if (width && height && (width !== menuSize.width || height !== menuSize.height)) {
      setMenuSize({
        width,
        height
      });
    }
  };
  const handleCopyMessage = async text => {
    try {
      await Clipboard.setStringAsync(text);
      showToast({
        id: Date.now().toString(),
        title: 'Success',
        message: 'Copied to clipboard!',
        type: 'success'
      });
    } catch (err) {
      console.log(err);
      showToast({
        id: Date.now().toString(),
        title: 'Copy failed',
        message: err?.message || 'Unknown error',
        type: 'error'
      });
    }
    closeMenu();
  };
  const handleReplyMessage = () => {
    replyMessage();
  };
  const memoPosition = (0, _react.useMemo)(() => {
    if (!position) {
      return undefined;
    }
    if (!menuSize.width || !menuSize.height) {
      return {
        top: position.bottom,
        left: position.left,
        opacity: 0
      };
    }
    const {
      width: screenWidth,
      height: screenHeight
    } = _reactNative.Dimensions.get('window');
    const bottomReserve = (config?.keyboardVerticalOffset ?? 0) + 24;
    const topReserve = 16;
    const sideMargin = 8;
    const spaceBelow = screenHeight - position.bottom - bottomReserve;
    const spaceAbove = position.top - topReserve;
    let top;
    if (spaceBelow >= menuSize.height) {
      top = position.bottom;
    } else if (spaceAbove >= menuSize.height) {
      top = position.top - menuSize.height;
    } else {
      top = Math.max(topReserve, screenHeight - menuSize.height - bottomReserve);
    }
    const leftMargin = position.left;
    const rightMargin = screenWidth - position.right;
    const rightAligned = rightMargin < leftMargin;
    let left = rightAligned ? position.right - menuSize.width : position.left;
    left = Math.max(sideMargin, Math.min(left, screenWidth - menuSize.width - sideMargin));
    return {
      top,
      left
    };
  }, [position, menuSize, config?.keyboardVerticalOffset]);

  // Window coords (memoPosition) → host-local coords. The overlay host
  // sits below the status bar / header, so subtract its measured origin.
  const localPosition = (0, _react.useMemo)(() => {
    if (!memoPosition) {
      return undefined;
    }
    return {
      ...memoPosition,
      top: memoPosition.top - originY,
      left: memoPosition.left - originX
    };
  }, [memoPosition, originX, originY]);
  const content = config?.disableInteractions || message.isDeleted ? null : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
    style: styles.overlayFill,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable, {
      style: _reactNative.StyleSheet.absoluteFill,
      onPress: closeMenu
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
      style: [styles.contextMenu, localPosition],
      onLayout: handleMenuLayout,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_ContextMenuComponents.MenuItem, {
        onPress: () => handleCopyMessage(message.body),
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: styles.menuText,
          children: _MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS.COPY
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS_ICONS.COPY, {})]
      }), isUser && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
        children: [message?.isMediafile !== 'true' && /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_ContextMenuComponents.Delimeter, {}), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_ContextMenuComponents.MenuItem, {
            onPress: handleEditMessage,
            children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
              style: styles.menuText,
              children: _MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS.EDIT
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS_ICONS.EDIT, {})]
          })]
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_ContextMenuComponents.Delimeter, {}), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_ContextMenuComponents.MenuItem, {
          onPress: handleDeleteMessage,
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
            style: styles.menuText,
            children: _MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS.DELETE
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_MESSAGE_INTERACTIONS.MESSAGE_INTERACTIONS_ICONS.DELETE, {})]
        })]
      })]
    })]
  });

  // Render the menu in the in-tree overlay host instead of a React Native
  // <Modal>. A Modal opens its own window on Android, which steals focus
  // from the chat input and dismisses the keyboard when the menu opens;
  // hosting it in the same view tree keeps the keyboard up. Re-run every
  // render so menuSize/position updates refresh the hosted node.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  (0, _react.useEffect)(() => {
    if (content) {
      present(overlayId, content);
    } else {
      dismiss(overlayId);
    }
  });
  (0, _react.useEffect)(() => () => dismiss(overlayId), [dismiss, overlayId]);
  return null;
};
var _default = exports.default = MessageInteractions;
const styles = _reactNative.StyleSheet.create({
  overlayFill: {
    ..._reactNative.StyleSheet.absoluteFillObject,
    backgroundColor: 'transparent'
  },
  contextMenu: {
    position: 'absolute',
    backgroundColor: 'white',
    paddingVertical: 4,
    paddingHorizontal: 8,
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowOpacity: 0.18,
    shadowRadius: 8,
    elevation: 6,
    minWidth: 180,
    // Clip the children to the rounded corners (the hairline dividers
    // run full width; without this they'd poke past the rounding on
    // Android).
    overflow: 'hidden'
  },
  // Explicit label styling so rows are the same height on both platforms
  // — Android's default includeFontPadding made the menu rows taller and
  // misaligned vs iOS. marginRight keeps the label off the trailing icon.
  menuText: {
    fontSize: 16,
    color: '#141414',
    includeFontPadding: false,
    textAlignVertical: 'center',
    marginRight: 16
  }
});
//# sourceMappingURL=MessageInteractions.js.map