"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useMessageNotification = exports.MessageNotificationProvider = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _reactRedux = require("react-redux");
var _messageNotificationManager = require("../utils/messageNotificationManager");
var _roomsSlice = require("../roomStore/roomsSlice");
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); }
// RN port of the web MessageNotificationProvider. Renders Telegram-style
// in-app toasts when a new message arrives in a room that is NOT the
// currently visible room. Backed by the global messageNotificationManager,
// which means non-React code (stanza handlers) can push notifications.

const MessageNotificationContext = /*#__PURE__*/(0, _react.createContext)(null);
const DEFAULT_MAX = 3;
const DEFAULT_DURATION_MS = 30000;
const MessageNotificationProvider = ({
  children,
  config: propConfig
}) => {
  const dispatch = (0, _reactRedux.useDispatch)();
  const contextConfig = (0, _reactRedux.useSelector)(state => state.chatSettingStore?.config);
  const visibleRoomJID = (0, _reactRedux.useSelector)(state => state.rooms.visibleRoomJID);
  const config = propConfig || contextConfig;
  const notificationConfig = config?.inAppNotifications;
  const isEnabled = notificationConfig?.enabled === true;
  const maxNotifications = notificationConfig?.maxNotifications ?? DEFAULT_MAX;
  const duration = notificationConfig?.duration ?? DEFAULT_DURATION_MS;
  const [toasts, setToasts] = (0, _react.useState)([]);
  const appActiveRef = (0, _react.useRef)(_reactNative.AppState.currentState === 'active');

  // Track AppState — when backgrounded, hold toasts longer; when
  // foregrounded, prune expired.
  (0, _react.useEffect)(() => {
    const sub = _reactNative.AppState.addEventListener('change', next => {
      appActiveRef.current = next === 'active';
      if (next === 'active') {
        const now = Date.now();
        setToasts(prev => prev.filter(t => now - t.timestamp < duration));
      }
    });
    return () => sub.remove();
  }, [duration]);

  // Periodic prune when active.
  (0, _react.useEffect)(() => {
    const interval = setInterval(() => {
      if (!appActiveRef.current) {
        return;
      }
      const now = Date.now();
      setToasts(prev => prev.filter(t => now - t.timestamp < duration));
    }, 1000);
    return () => clearInterval(interval);
  }, [duration]);

  // Clear toasts when their room becomes active.
  (0, _react.useEffect)(() => {
    if (!visibleRoomJID) {
      return;
    }
    setToasts(prev => prev.filter(t => t.roomJID !== visibleRoomJID));
  }, [visibleRoomJID]);
  const dismiss = (0, _react.useCallback)(id => {
    setToasts(prev => prev.filter(t => t.id !== id));
  }, []);
  const navigateToMessage = (0, _react.useCallback)((roomJID, messageId, message, roomName, senderName) => {
    setToasts(prev => prev.filter(t => t.roomJID !== roomJID));
    const customOnClick = notificationConfig?.onClick;
    if (customOnClick) {
      Promise.resolve(customOnClick({
        roomJID,
        messageId,
        message,
        roomName,
        senderName
      })).catch(e => console.error('onClick handler error', e));
      return;
    }
    if (roomJID) {
      dispatch((0, _roomsSlice.setCurrentRoom)({
        roomJID
      }));
    }
  }, [dispatch, notificationConfig]);
  const showMessageNotification = (0, _react.useCallback)((message, roomName, senderName, roomJID) => {
    if (!isEnabled) {
      return;
    }
    // Don't toast for the currently active room.
    if (visibleRoomJID && visibleRoomJID === roomJID) {
      return;
    }
    const id = `msg-notification-${message.id}-${Date.now()}`;
    const item = {
      id,
      message,
      roomName,
      senderName,
      roomJID,
      timestamp: Date.now()
    };
    setToasts(prev => {
      const next = [...prev, item];
      return next.length > maxNotifications ? next.slice(-maxNotifications) : next;
    });
  }, [isEnabled, visibleRoomJID, maxNotifications]);

  // Register with the global manager.
  (0, _react.useEffect)(() => {
    if (!isEnabled) {
      return;
    }
    const unsubscribe = _messageNotificationManager.messageNotificationManager.addCallback(showMessageNotification);
    return unsubscribe;
  }, [isEnabled, showMessageNotification]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(MessageNotificationContext.Provider, {
    value: {
      showMessageNotification
    },
    children: [children, isEnabled && toasts.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
      pointerEvents: "box-none",
      style: [styles.container, positionToStyle(notificationConfig?.position)],
      children: toasts.map(t => {
        const Custom = notificationConfig?.customComponent;
        if (Custom) {
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(Custom, {
            id: t.id,
            message: t.message,
            roomName: t.roomName,
            senderName: t.senderName,
            roomJID: t.roomJID,
            timestamp: t.timestamp,
            onClose: () => dismiss(t.id),
            onNavigateToMessage: navigateToMessage,
            duration: duration
          }, t.id);
        }
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(ToastRow, {
          item: t,
          onPress: () => navigateToMessage(t.roomJID, t.message.id, t.message, t.roomName, t.senderName),
          onDismiss: () => dismiss(t.id)
        }, t.id);
      })
    })]
  });
};
exports.MessageNotificationProvider = MessageNotificationProvider;
const ToastRow = ({
  item,
  onPress,
  onDismiss
}) => {
  const fade = (0, _react.useRef)(new _reactNative.Animated.Value(0)).current;
  (0, _react.useEffect)(() => {
    _reactNative.Animated.timing(fade, {
      toValue: 1,
      duration: 180,
      useNativeDriver: true
    }).start();
  }, [fade]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Animated.View, {
    style: [styles.toast, {
      opacity: fade
    }],
    children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Pressable, {
      style: styles.toastBody,
      onPress: onPress,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.toastTitle,
        numberOfLines: 1,
        children: item.roomName
      }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.Text, {
        style: styles.toastSubtitle,
        numberOfLines: 2,
        children: [item.senderName, ": ", item.message?.body || '']
      })]
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Pressable, {
      onPress: onDismiss,
      style: styles.dismiss,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
        style: styles.dismissText,
        children: "\xD7"
      })
    })]
  });
};
const positionToStyle = position => {
  const horizontal = position?.horizontal || 'left';
  const vertical = position?.vertical || 'bottom';
  const offset = position?.offset || {};
  const out = {};
  if (vertical === 'top') {
    out.top = offset.top ?? 20;
  } else {
    out.bottom = offset.bottom ?? 20;
  }
  if (horizontal === 'right') {
    out.right = offset.right ?? 20;
    out.alignItems = 'flex-end';
  } else if (horizontal === 'center') {
    out.left = 0;
    out.right = 0;
    out.alignItems = 'center';
  } else {
    out.left = offset.left ?? 20;
    out.alignItems = 'flex-start';
  }
  return out;
};
const styles = _reactNative.StyleSheet.create({
  container: {
    position: 'absolute',
    zIndex: 10000,
    elevation: 10000
  },
  toast: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    paddingVertical: 10,
    paddingHorizontal: 14,
    marginVertical: 4,
    borderRadius: 12,
    minWidth: 240,
    maxWidth: 340,
    shadowColor: '#000',
    shadowOpacity: 0.15,
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowRadius: 6
  },
  toastBody: {
    flex: 1
  },
  toastTitle: {
    fontWeight: '600',
    fontSize: 14,
    color: '#222',
    marginBottom: 2
  },
  toastSubtitle: {
    fontSize: 12,
    color: '#555'
  },
  dismiss: {
    paddingHorizontal: 8,
    paddingVertical: 4
  },
  dismissText: {
    fontSize: 18,
    color: '#777'
  }
});
const useMessageNotification = () => {
  const ctx = (0, _react.useContext)(MessageNotificationContext);
  if (!ctx) {
    throw new Error('useMessageNotification must be used within a MessageNotificationProvider');
  }
  return ctx;
};
exports.useMessageNotification = useMessageNotification;
//# sourceMappingURL=MessageNotificationContext.js.map