"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useXmppInitialization = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _xmppProvider = require("../context/xmppProvider");
var _apiClient = require("../networking/apiClient");
var _auth = require("../networking/api-requests/auth.api");
var _walletUsername = require("../helpers/walletUsername");
var _hooks = require("./hooks");
var _chatSettingsSlice = require("../roomStore/chatSettingsSlice");
/** @format */

/**
 * Hook for initializing XMPP client via JWT token
 * Used for preloading chat before opening workspace
 */
const useXmppInitialization = (options = {}) => {
  const {
    chatToken,
    xmppSettings = {
      devServer: 'wss://xmpp.ethoradev.com/ws',
      host: 'xmpp.ethoradev.com',
      conference: 'conference.xmpp.ethoradev.com'
    },
    baseURL = 'https://api.ethoradev.com/v1',
    enabled = true
  } = options;
  const {
    client,
    initializeClient
  } = (0, _xmppProvider.useXmppClient)();
  const dispatch = (0, _hooks.useAppDispatch)();
  const [isInitializing, setIsInitializing] = (0, _react.useState)(false);
  const [initializationError, setInitializationError] = (0, _react.useState)(null);
  const isMountedRef = (0, _react.useRef)(true);
  (0, _react.useEffect)(() => {
    if (baseURL) {
      (0, _apiClient.setBaseURL)(baseURL, undefined);
      console.log('🚀 useXmppInitialization: Base URL set for chat', baseURL);
    }
  }, [baseURL]);
  (0, _react.useEffect)(() => {
    if (!enabled) {
      return;
    }
    const initXmppClient = async () => {
      if (client) {
        console.log('useXmppInitialization: Client already initialized');
        return;
      }
      if (!chatToken) {
        console.log('useXmppInitialization: Waiting for chatToken...');
        return;
      }
      if (isInitializing) {
        console.log('useXmppInitialization: Initialization in progress...');
        return;
      }
      if (_reactNative.AppState.currentState !== 'active') {
        console.log('useXmppInitialization: App not active, skip init');
        return;
      }
      try {
        setIsInitializing(true);
        setInitializationError(null);
        console.log('useXmppInitialization: Starting XMPP client initialization...');
        const user = await (0, _auth.loginViaJwt)(chatToken);
        console.log('useXmppInitialization: User data received', {
          hasXmppUsername: !!user.xmppUsername,
          hasXmppPassword: !!user.xmppPassword
        });
        dispatch((0, _chatSettingsSlice.setUser)(user));
        console.log('useXmppInitialization: User saved to store');
        const xmppUsername = user.xmppUsername || (0, _walletUsername.walletToUsername)(user.defaultWallet?.walletAddress || '');
        if (!xmppUsername || !user.xmppPassword) {
          throw new Error('Missing XMPP credentials (username or password)');
        }
        console.log('useXmppInitialization: Initializing XMPP client...');
        const initializedClient = await initializeClient(xmppUsername, user.xmppPassword, xmppSettings);
        console.log('useXmppInitialization: XMPP client initialized successfully', {
          status: initializedClient.status
        });
      } catch (error) {
        console.error('useXmppInitialization: Failed to initialize XMPP client', error);
        if (isMountedRef.current) {
          setInitializationError(error?.message || 'Unknown error');
        }
      } finally {
        if (isMountedRef.current) {
          setIsInitializing(false);
        }
      }
    };
    initXmppClient();
  }, [chatToken, client, initializeClient, isInitializing, enabled, xmppSettings]);
  (0, _react.useEffect)(() => {
    return () => {
      isMountedRef.current = false;
    };
  }, []);
  return {
    isInitializing,
    initializationError,
    isInitialized: !!client && client.status === 'online'
  };
};
exports.useXmppInitialization = useXmppInitialization;
//# sourceMappingURL=useXmppInitialization.js.map