"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _reactNativeGestureHandler = require("react-native-gesture-handler");
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _reactNativeKeyboardController = require("react-native-keyboard-controller");
var _OxyContext = require("../context/OxyContext");
var _reactQuery = require("@tanstack/react-query");
var _FontLoader = require("./FontLoader");
var _BottomSheetRouter = _interopRequireDefault(require("./BottomSheetRouter"));
var _sonner = require("../../lib/sonner");
var _queryClient = require("../hooks/queryClient");
var _useStorage = require("../hooks/useStorage");
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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); } // Initialize fonts automatically
(0, _FontLoader.setupFonts)();

/**
 * OxyProvider component
 *
 * Provides the authentication/session context used across the app.
 * UI composition (e.g. OxyRouter inside a bottom sheet) can be added externally.
 */
const OxyProvider = ({
  oxyServices,
  children,
  contextOnly = false,
  onAuthStateChange,
  storageKeyPrefix,
  baseURL,
  queryClient: providedQueryClient
}) => {
  // contextOnly is retained for backwards compatibility while the UI-only
  // bottom sheet experience is removed. At the moment both modes behave the same.
  void contextOnly;

  // Get storage for query persistence
  const {
    storage,
    isReady: isStorageReady
  } = (0, _useStorage.useStorage)();

  // Initialize React Query Client with persistence
  const queryClientRef = (0, _react.useRef)(null);
  const [queryClient, setQueryClient] = (0, _react.useState)(null);
  (0, _react.useEffect)(() => {
    if (providedQueryClient) {
      queryClientRef.current = providedQueryClient;
      setQueryClient(providedQueryClient);
    } else if (isStorageReady) {
      // Create query client with persistence once storage is ready
      if (!queryClientRef.current) {
        const client = (0, _queryClient.createQueryClient)(storage);
        queryClientRef.current = client;
        setQueryClient(client);
      }
    }
  }, [providedQueryClient, isStorageReady, storage]);

  // Hook React Query focus manager into React Native AppState
  (0, _react.useEffect)(() => {
    const subscription = _reactNative.AppState.addEventListener('change', state => {
      _reactQuery.focusManager.setFocused(state === 'active');
    });
    return () => {
      subscription.remove();
    };
  }, []);

  // Setup network status monitoring for offline detection
  (0, _react.useEffect)(() => {
    let cleanup;
    const setupNetworkMonitoring = async () => {
      try {
        // For React Native, try to use NetInfo
        if (typeof window === 'undefined' || typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
          try {
            const NetInfo = await Promise.resolve().then(() => _interopRequireWildcard(require('@react-native-community/netinfo')));
            const state = await NetInfo.default.fetch();
            _reactQuery.onlineManager.setOnline(state.isConnected ?? true);
            const unsubscribe = NetInfo.default.addEventListener(state => {
              _reactQuery.onlineManager.setOnline(state.isConnected ?? true);
            });
            cleanup = () => unsubscribe();
          } catch {
            // NetInfo not available, default to online
            _reactQuery.onlineManager.setOnline(true);
          }
        } else {
          // For web, use navigator.onLine
          _reactQuery.onlineManager.setOnline(navigator.onLine);
          const handleOnline = () => _reactQuery.onlineManager.setOnline(true);
          const handleOffline = () => _reactQuery.onlineManager.setOnline(false);
          window.addEventListener('online', handleOnline);
          window.addEventListener('offline', handleOffline);
          cleanup = () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
          };
        }
      } catch (error) {
        // Default to online if detection fails
        _reactQuery.onlineManager.setOnline(true);
      }
    };
    setupNetworkMonitoring();
    return () => {
      cleanup?.();
    };
  }, []);

  // Ensure we have a valid QueryClient
  if (!queryClient) {
    // Return loading state or fallback
    return null;
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeSafeAreaContext.SafeAreaProvider, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeGestureHandler.GestureHandlerRootView, {
      style: {
        flex: 1
      },
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNativeKeyboardController.KeyboardProvider, {
        children: queryClient && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactQuery.QueryClientProvider, {
          client: queryClient,
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_OxyContext.OxyContextProvider, {
            oxyServices: oxyServices,
            baseURL: baseURL,
            storageKeyPrefix: storageKeyPrefix,
            onAuthStateChange: onAuthStateChange,
            children: [children, /*#__PURE__*/(0, _jsxRuntime.jsx)(_BottomSheetRouter.default, {}), /*#__PURE__*/(0, _jsxRuntime.jsx)(_sonner.Toaster, {})]
          })
        })
      })
    })
  });
};
var _default = exports.default = OxyProvider;
//# sourceMappingURL=OxyProvider.js.map