"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _useThemeStyles = require("../hooks/useThemeStyles");
var _useColorScheme = require("../hooks/use-color-scheme");
var _themeUtils = require("../utils/themeUtils");
var _vectorIcons = require("@expo/vector-icons");
var _sonner = require("../../lib/sonner");
var _components = require("../components");
var _useI18n = require("../hooks/useI18n");
var _languageUtils = require("../../utils/languageUtils");
var _OxyContext = require("../context/OxyContext");
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); }
/**
 * LanguageSelectorScreen - Optimized for performance
 * 
 * Performance optimizations:
 * - useMemo for language items to prevent recreation on every render
 * - useCallback for handlers to prevent unnecessary re-renders
 * - Memoized current language section
 */
const LanguageSelectorScreen = ({
  goBack,
  onClose,
  theme
}) => {
  // Use useOxy() hook for OxyContext values
  const {
    user,
    currentLanguage,
    setLanguage,
    oxyServices,
    isAuthenticated
  } = (0, _OxyContext.useOxy)();
  const {
    t
  } = (0, _useI18n.useI18n)();
  const colorScheme = (0, _useColorScheme.useColorScheme)();
  const normalizedTheme = (0, _themeUtils.normalizeTheme)(theme);
  const themeStyles = (0, _useThemeStyles.useThemeStyles)(normalizedTheme, colorScheme);
  const themeColors = themeStyles.colors;
  const [isLoading, setIsLoading] = (0, _react.useState)(false);

  // Memoize the language select handler to prevent recreation on every render
  const handleLanguageSelect = (0, _react.useCallback)(async languageId => {
    if (languageId === currentLanguage || isLoading) {
      return; // Already selected or loading
    }
    setIsLoading(true);
    try {
      let serverSyncFailed = false;

      // If signed in, persist preference to backend user settings
      if (isAuthenticated && user?.id) {
        try {
          await oxyServices.updateProfile({
            language: languageId
          });
        } catch (e) {
          // Server sync failed, but we'll save locally anyway
          serverSyncFailed = true;
          if (__DEV__) {
            console.warn('Failed to sync language to server (will save locally only):', e?.message || e);
          }
        }
      }

      // Always persist locally for immediate UX and for guests
      await setLanguage(languageId);
      const selectedLang = _languageUtils.SUPPORTED_LANGUAGES.find(lang => lang.id === languageId);

      // Show success message (language is saved locally regardless of server sync)
      _sonner.toast.success(t('language.changed', {
        lang: selectedLang?.name || languageId
      }));

      // Log server sync failure only in dev mode (user experience is still good - saved locally)
      if (serverSyncFailed && __DEV__) {
        console.warn('Language saved locally but server sync failed');
      }
      setIsLoading(false);
      // Close the bottom sheet if possible; otherwise, go back
      if (onClose) onClose();else goBack?.();
    } catch (error) {
      // Only show error if local storage also failed
      console.error('Error saving language preference:', error);
      _sonner.toast.error('Failed to save language preference');
      setIsLoading(false);
    }
  }, [currentLanguage, isLoading, isAuthenticated, user?.id, oxyServices, setLanguage, t, onClose, goBack]);

  // Memoize language items to prevent recreation on every render
  const languageItems = (0, _react.useMemo)(() => _languageUtils.SUPPORTED_LANGUAGES.map(language => {
    const isSelected = currentLanguage === language.id;
    return {
      id: language.id,
      title: language.name,
      subtitle: language.nativeName,
      customIcon: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: [styles.languageFlag, {
          backgroundColor: `${language.color}15`
        }],
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: styles.flagEmoji,
          children: language.flag
        })
      }),
      iconColor: language.color,
      selected: isSelected,
      onPress: () => handleLanguageSelect(language.id),
      customContent: isSelected ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_vectorIcons.Ionicons, {
        name: "checkmark-circle",
        size: 24,
        color: themeColors.tint
      }) : undefined
    };
  }), [currentLanguage, handleLanguageSelect, themeColors]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
    style: [styles.container, {
      backgroundColor: theme === 'dark' ? '#000000' : '#F5F5F5'
    }],
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Header, {
      title: "",
      subtitle: "",
      theme: normalizedTheme,
      onBack: onClose || goBack,
      variant: "minimal",
      elevation: "none"
    }), /*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.ScrollView, {
      style: styles.content,
      contentContainerStyle: styles.contentContainer,
      showsVerticalScrollIndicator: false,
      removeClippedSubviews: true,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)(_reactNative.View, {
        style: styles.titleContainer,
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: [styles.bigTitle, {
            color: themeColors.text
          }],
          children: t('language.title')
        }), t('language.subtitle') && /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.Text, {
          style: [styles.bigSubtitle, {
            color: themeColors.secondaryText
          }],
          children: t('language.subtitle')
        })]
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
        style: styles.sectionContainer,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactNative.View, {
          style: [styles.materialCard, {
            backgroundColor: themeColors.card
          }],
          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.GroupedSection, {
            items: languageItems
          })
        })
      })]
    })]
  });
};
const styles = _reactNative.StyleSheet.create({
  container: {
    flex: 1
  },
  content: {
    flex: 1
  },
  contentContainer: {
    padding: 16,
    paddingTop: 24
  },
  titleContainer: {
    marginBottom: 32,
    paddingTop: 0
  },
  bigTitle: {
    fontSize: 34,
    fontWeight: '700',
    lineHeight: 40,
    marginBottom: 8,
    letterSpacing: -0.5
  },
  bigSubtitle: {
    fontSize: 16,
    lineHeight: 22,
    opacity: 0.7,
    marginTop: 4
  },
  sectionContainer: {
    marginBottom: 8
  },
  materialCard: {
    borderRadius: 12,
    overflow: 'hidden'
  },
  languageFlag: {
    width: 40,
    height: 40,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center'
  },
  flagEmoji: {
    fontSize: 20
  }
});

// Export memoized component to prevent unnecessary re-renders
var _default = exports.default = /*#__PURE__*/_react.default.memo(LanguageSelectorScreen);
//# sourceMappingURL=LanguageSelectorScreen.js.map