"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useChatRoomFocus = exports.default = void 0;
var _react = require("react");
var _reactRedux = require("react-redux");
var _roomsSlice = require("../roomStore/roomsSlice");
var _roomStore = require("../roomStore");
/**
 * Public hook for consumers embedding `<ChatRoom>` inside a tab-based
 * navigator. Mirrors the mount/unmount unread-tracking that ChatRoom
 * does internally — but driven by an explicit focus signal so the
 * unread counter behaves correctly when the chat tab is not focused
 * but the component is still mounted.
 *
 * Without this hook, `useUnread()` will always return 0 for the chat
 * room because the SDK assumes "mounted == active". With this hook,
 * focus marks the room visible (clearing the badge) and blur stamps
 * `lastViewedTimestamp = Date.now()` so future messages count as unread.
 *
 * Usage with React Navigation:
 *
 * ```tsx
 * import { useIsFocused } from '@react-navigation/native';
 *
 * function ChatTab() {
 *   const isFocused = useIsFocused();
 *   useChatRoomFocus({ roomJID: 'general@conference.host', isFocused });
 *   return <Chat config={...} />;
 * }
 * ```
 *
 * Bug #18-adjacent / unread-tracking bug from sdk-bug-tracker.md.
 */
const useChatRoomFocus = ({
  roomJID,
  isFocused
}) => {
  const dispatch = (0, _reactRedux.useDispatch)();
  const prevRef = (0, _react.useRef)({
    roomJID: null,
    isFocused: false
  });
  const leaveRoom = jid => {
    const timestamp = Date.now();
    dispatch((0, _roomsSlice.setLastViewedTimestamp)({
      chatJID: jid,
      timestamp
    }));
    dispatch((0, _roomsSlice.clearVisibleRoom)());
    const rooms = _roomStore.store.getState().rooms?.rooms;
    _roomStore.store.getState().chatSettingStore?.client?.flushLastViewedToPrivateStoreStanza(rooms, {
      visibleRoomJID: jid
    }).catch(() => {});
  };
  (0, _react.useEffect)(() => {
    const prev = prevRef.current;
    if (prev.isFocused && prev.roomJID && (prev.roomJID !== roomJID || !isFocused)) {
      leaveRoom(prev.roomJID);
    }
    if (roomJID && isFocused) {
      dispatch((0, _roomsSlice.setCurrentRoom)({
        roomJID
      }));
      dispatch((0, _roomsSlice.setVisibleRoom)({
        roomJID
      }));
    }
    prevRef.current = {
      roomJID: roomJID || null,
      isFocused
    };
  }, [roomJID, isFocused, dispatch]);
  (0, _react.useEffect)(() => {
    return () => {
      const prev = prevRef.current;
      if (prev.isFocused && prev.roomJID) {
        leaveRoom(prev.roomJID);
      }
    };
  }, []);
};
exports.useChatRoomFocus = useChatRoomFocus;
var _default = exports.default = useChatRoomFocus;
//# sourceMappingURL=useChatRoomFocus.js.map