"use strict";

import React, { useEffect, useId, useMemo, useState } from 'react';
import { Delimeter, MenuItem } from '../ContextMenu/ContextMenuComponents';
import { useSelector } from 'react-redux';
import { MESSAGE_INTERACTIONS, MESSAGE_INTERACTIONS_ICONS } from '../../helpers/constants/MESSAGE_INTERACTIONS';
import { Text, StyleSheet, View, Pressable, Dimensions } from 'react-native';
import * as Clipboard from 'expo-clipboard';
import { useToast } from '../../context/ToastContext';
import { useInteractionsOverlay } from './InteractionsOverlay';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
const MessageInteractions = ({
  isReply,
  isUser,
  message,
  closeMenu,
  position,
  handleReplyMessage: replyMessage,
  handleDeleteMessage,
  handleEditMessage
}) => {
  const {
    showToast
  } = useToast();
  const {
    present,
    dismiss,
    originX,
    originY
  } = useInteractionsOverlay();
  const overlayId = useId();
  const config = useSelector(state => state.chatSettingStore.config);
  const [menuSize, setMenuSize] = 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 = useMemo(() => {
    if (!position) {
      return undefined;
    }
    if (!menuSize.width || !menuSize.height) {
      return {
        top: position.bottom,
        left: position.left,
        opacity: 0
      };
    }
    const {
      width: screenWidth,
      height: screenHeight
    } = 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 = 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__*/_jsxs(View, {
    style: styles.overlayFill,
    children: [/*#__PURE__*/_jsx(Pressable, {
      style: StyleSheet.absoluteFill,
      onPress: closeMenu
    }), /*#__PURE__*/_jsxs(View, {
      style: [styles.contextMenu, localPosition],
      onLayout: handleMenuLayout,
      children: [/*#__PURE__*/_jsxs(MenuItem, {
        onPress: () => handleCopyMessage(message.body),
        children: [/*#__PURE__*/_jsx(Text, {
          style: styles.menuText,
          children: MESSAGE_INTERACTIONS.COPY
        }), /*#__PURE__*/_jsx(MESSAGE_INTERACTIONS_ICONS.COPY, {})]
      }), isUser && /*#__PURE__*/_jsxs(_Fragment, {
        children: [message?.isMediafile !== 'true' && /*#__PURE__*/_jsxs(_Fragment, {
          children: [/*#__PURE__*/_jsx(Delimeter, {}), /*#__PURE__*/_jsxs(MenuItem, {
            onPress: handleEditMessage,
            children: [/*#__PURE__*/_jsx(Text, {
              style: styles.menuText,
              children: MESSAGE_INTERACTIONS.EDIT
            }), /*#__PURE__*/_jsx(MESSAGE_INTERACTIONS_ICONS.EDIT, {})]
          })]
        }), /*#__PURE__*/_jsx(Delimeter, {}), /*#__PURE__*/_jsxs(MenuItem, {
          onPress: handleDeleteMessage,
          children: [/*#__PURE__*/_jsx(Text, {
            style: styles.menuText,
            children: MESSAGE_INTERACTIONS.DELETE
          }), /*#__PURE__*/_jsx(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
  useEffect(() => {
    if (content) {
      present(overlayId, content);
    } else {
      dismiss(overlayId);
    }
  });
  useEffect(() => () => dismiss(overlayId), [dismiss, overlayId]);
  return null;
};
export default MessageInteractions;
const styles = StyleSheet.create({
  overlayFill: {
    ...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