angular
	.module('Dating', [
		'ui.router',
		'ui.bootstrap.dropdown',
		'ct.ui.router.extras',
		'ngSanitize',
		'pascalprecht.translate',
		'monospaced.elastic',
		'rzModule',
		'pages'
	])
	.provider('globalParamsServiceProvider', function () {
		var globalParams;

		this.setGlobalParams = function (value) {
			globalParams = value;
		};

		this.$get = [
			'globalParamsService',
			function (globalParamsService) {
				if (globalParams) {
					return globalParamsService.fetchGlobalParams();
				}
				throw new Error('Global Params not set');
			}
		];
	})
	.service('authService', function ($rootScope) {
		var user = this;
		user.isAuthenticated = !!window.globalParams.userInfo.username;
		user.clearCredentials = function () {
			window.globalParams.userInfo = {};
			window.globalParams.user = {};
			user.isAuthenticated = false;
			$rootScope.$broadcast('userLoggedOut');
		};
		user.currentUser = user.isAuthenticated ? window.globalParams.userInfo : null;
	})
	.service('userAccess', function (globalParamsService) {
		var userAccess = this;
		var GLOBALS = globalParamsService.GLOBALS;

		userAccess.initialize = function () {
			userAccess.hasAccess = !!globalParamsService.GLOBALS.user;
			if (userAccess.hasAccess) {
				if (
					GLOBALS.user.justRegistered ||
					GLOBALS.user.showUploadPhotoDescriptionBox ||
					GLOBALS.user.affiliateOneClickBox ||
					GLOBALS.user.affiliateOneClickBoxStep2 ||
					GLOBALS.user.affiliateOneClickBoxStep3 ||
					GLOBALS.user.showOneClickBox
				) {
					userAccess.hasAccess = false;
				}
			}
		};

		userAccess.initialize();
	})
	.service('globalParamsService', function ($http) {
		var globalParamsService = this;
		globalParamsService.GLOBALS = window.globalParams;
		globalParamsService.COUNTRY_LIST = window.globalParams.countries;
		globalParamsService.PROFILE_SETTINGS = window.globalParams.classifiers;

		this.fetchGlobalParams = function () {
			return $http.get('/site/getParameters').then(
				function (res) {
					if (res.status === 200 && angular.isDefined(res.data)) {
						angular.copy(res.data, globalParamsService.GLOBALS);
						angular.copy(res.data.countries, globalParamsService.COUNTRY_LIST);
						angular.copy(res.data.classifiers, globalParamsService.PROFILE_SETTINGS);
						angular.copy(res.data, window.globalParams);
					}
					return res;
				},
				function (error) {
					console.error('Error fetching global params:', error);
					throw error;
				}
			);
		};
	})
	.service('RouteChangeService', function ($rootScope, $location, globalParamsService, $window) {
		var initialized = false;
		var GLOBALS = globalParamsService.GLOBALS;
		function init() {
			if (initialized) {
				return;
			}
			$rootScope.$watch(
				function () {
					return $location.path();
				},
				function (newPath, oldPath) {
					if (newPath !== oldPath) {
						$rootScope.$broadcast('routeChange', {
							newPath: newPath,
							oldPath: oldPath
						});
						if (
							$window.OneSignal &&
							!!GLOBALS.user &&
							!GLOBALS.user.justRegistered &&
							newPath !== '/signOutAd' &&
							!GLOBALS.user.affiliateOneClickBox &&
							!GLOBALS.user.affiliateOneClickBoxStep2 &&
							!GLOBALS.user.affiliateOneClickBoxStep3
						) {
							$window.OneSignal.push(function () {
								$window.OneSignal.showSlidedownPrompt();
							});
						}
					}
				}
			);
			initialized = true;
		}
		return {
			init: init
		};
	})
	.service('SearchNavigationService', function ($state, ProfilesModel) {
		function filterProfiles(currentPage, profilesFilter) {
			if (
				$state.current.name === 'dating.pages.videoProfiles' ||
				$state.current.name === 'dating.pages.videoProfilesNoParams'
			) {
				$state.go('dating.pages.videoProfiles', {
					page: currentPage,
					filter: ProfilesModel.buildSearchParams(profilesFilter)
				});
			} else {
				var targetState =
					$state.current.name === 'dating.pages.featuredProfiles' ? $state.current.name : 'dating.pages.profiles';
				$state.go(targetState, {
					page: currentPage,
					filter: ProfilesModel.buildSearchParams(profilesFilter)
				});
			}
		}
		return {
			filterProfiles: filterProfiles
		};
	})
	.config(function ($httpProvider, $locationProvider) {
		$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
		$locationProvider.html5Mode(true);
	})
	.config(function () {
		window.globalParams.isMobileScreen = !window.globalParams.mobileQuery && $('body').width() <= 768;
	})
	.config([
		'$stateProvider',
		'$urlRouterProvider',
		function ($stateProvider, $urlRouterProvider) {
			//abstract state serves as a PLACEHOLDER or NAMESPACE for application states
			$stateProvider.state('dating', {
				url: '',
				abstract: true
			});

			$urlRouterProvider.otherwise('/');
		}
	])
	.config(function ($translateProvider, globalParamsServiceProvider) {
		var GLOBALS = globalParamsServiceProvider.$get().GLOBALS;
		if (GLOBALS.isHeadless) {
			$translateProvider.useStaticFilesLoader({
				prefix: GLOBALS.i18nUrl,
				suffix: '.json'
			});
		} else {
			$translateProvider.useUrlLoader(GLOBALS.i18nUrl);
		}

		// Since you've now registered more then one translation table, angular-translate has to know which one to use.
		// This is where preferredLanguage(langKey) comes in.
		$translateProvider.preferredLanguage(GLOBALS.i18nDefaultLang);

		// Store the language in the local storage
		$translateProvider.useLocalStorage();

		// Enable sanitize
		$translateProvider.useSanitizeValueStrategy(null);

		// Log missing translations to console
		$translateProvider.useMissingTranslationHandlerLog();
	})
	.config([
		'$compileProvider',
		function ($compileProvider) {
			$compileProvider.debugInfoEnabled(false);
		}
	])
	.run(function (RouteChangeService) {
		RouteChangeService.init();
	})
	.run(function ($rootScope) {
		$rootScope.$on('$locationChangeStart', function (event) {
			if ($rootScope.preventRouteChange) {
				event.preventDefault();
			}
		});
	})
	.run(function ($rootScope, $window, ProfilesModel, globalParamsService, authService, EventsModel) {
		var GLOBALS = globalParamsService.GLOBALS;
		$rootScope.$on('ccp:onRevealLocation', function (event, args) {
			if (args.callback && typeof args.callback === 'function') {
				var data = { userId: args.profileId };
				if (
					GLOBALS.isCreditsSite &&
					authService.currentUser.membership === 'premium' &&
					GLOBALS.userInfo.hasSufficientCreditsForReveal
				) {
					ProfilesModel.sendRevealLocation(data).then(function (response) {
						args.callback(response.data.location.country + ', ' + response.data.location.city);
					});
				} else {
					EventsModel.clickRevealLocation();
					var trackingParam = '';
					if (GLOBALS.isCreditsSite) {
						trackingParam = '?revealLocationUpgrade=1';
					}
					$rootScope.$broadcast('showPurchaseModal', { trackingParam: trackingParam });
				}
			}
		});
	});
if (!window.globalParams.isHeadless) {
	// angular.module('Dating').constant('GLOBALS', window.globalParams)// We can remove this if when all sites are converted to headless since the GLOBALS is set in the index.html fetchGlobalParamsAndBootstrap() before bootstrapping AngularJS
}
