angular.module('edecApp', ['ngRoute'])
	.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
		
		$locationProvider.html5Mode({
			enabled: true,
			requireBase: true
		});

		$routeProvider
		.when('/', {
			templateUrl: 'views/home.html',
			controller: 'HomeController'
		})
		.when('/import', {
			templateUrl: 'views/import.html',
			controller: 'ImportController'
		})
		.when('/payment-success', {
			template: `
				<div class="container" style="text-align: center; padding: 4rem 2rem;">
					<div class="success-icon" style="font-size: 4rem; color: #28a745;">✅</div>
					<h1>Paiement réussi !</h1>
					<p ng-if="!verifying">Vérification du paiement en cours...</p>
					<p ng-if="verifying">Lancement de la soumission...</p>
					<div class="spinner" ng-if="!error"></div>
					<p class="error" ng-if="error" style="color: red; margin-top: 2rem;">{{ error }}</p>
				</div>
			`,
			controller: ['$scope', '$location', '$timeout', '$http', '$rootScope', '$window', function($scope, $location, $timeout, $http, $rootScope, $window) {
				$scope.verifying = false;
				$scope.error = null;

				const urlParams = new URLSearchParams($window.location.search);
				const stripeSessionId = urlParams.get('session_id');

				if (!stripeSessionId) {
					$scope.error = 'Session ID manquant. Retour à l\'accueil...';
					$timeout(() => $location.path('/'), 3000);
					return;
				}

				const importData = sessionStorage.getItem('edec_import_form');
				const exportData = sessionStorage.getItem('edec_export_form');
				
				let sessionToken = null;
				let destinationType = 'import';

				if (importData) {
					const parsed = JSON.parse(importData);
					sessionToken = parsed.sessionToken;
					destinationType = 'import';
				} else if (exportData) {
					const parsed = JSON.parse(exportData);
					sessionToken = parsed.sessionToken;
					destinationType = 'export';
				}

				if (!sessionToken) {
					$scope.error = 'Déclaration non trouvée. Retour à l\'accueil...';
					$timeout(() => $location.path('/'), 3000);
					return;
				}

				$scope.verifying = true;

				$http.post('/api/verify-checkout-session', {
					sessionToken: sessionToken,
					stripeSessionId: stripeSessionId
				})
				.then(function(response) {
					if (response.data.success) {
						sessionStorage.setItem('stripe_payment_return', JSON.stringify({
							sessionToken: sessionToken,
							verified: true
						}));
						
						$timeout(() => {
							$location.path('/' + destinationType);
						}, 1500);
					} else {
						$scope.error = response.data.message || 'Erreur de vérification du paiement';
					}
				})
				.catch(function(error) {
					$scope.error = error.data?.message || 'Erreur réseau';
				});
			}]
		})
		.when('/export', {
			templateUrl: 'views/export.html',
			controller: 'ExportController'
		})
		.when('/payment', {
			templateUrl: '/views/payment.html',
			controller: 'PaymentController'
		})
		.when('/submission-error', {
			templateUrl: 'views/submission-error.html',
			controller: 'SubmissionErrorController'
		})
		.otherwise({
			redirectTo: '/'
		});
	}])

	.controller('MainController', ['$scope', '$location', '$window', '$timeout', '$rootScope', 'ConfigService', function($scope, $location, $window, $timeout, $rootScope, ConfigService) {
		// Gestion de la langue
		$scope.currentLang = 'fr'; // Langue par défaut
		
		// Fonction d'initialisation de la langue
		$scope.initLanguage = function() {
			// 1. Vérifier le paramètre URL ?lang=xx
			var urlParams = new URLSearchParams($window.location.search);
			var langParam = urlParams.get('lang');
			const SUPPORTED_LANGS = ['fr', 'de', 'it', 'en'];
			
			if (langParam && SUPPORTED_LANGS.includes(langParam)) {
				$scope.currentLang = langParam;
				localStorage.setItem('myAutoImportLang', langParam);
			}
			// 2. Sinon vérifier le localStorage
			else if (localStorage.getItem('myAutoImportLang')) {
				const storedLang = localStorage.getItem('myAutoImportLang');
				if (SUPPORTED_LANGS.includes(storedLang)) {
					$scope.currentLang = storedLang;
				}
			}
			// 3. Sinon détecter la langue du navigateur
			else {
				var browserLang = navigator.language || navigator.userLanguage;
				if (browserLang.startsWith('de')) $scope.currentLang = 'de';
				else if (browserLang.startsWith('it')) $scope.currentLang = 'it';
				else if (browserLang.startsWith('en')) $scope.currentLang = 'en';
				else $scope.currentLang = 'fr';
				
				localStorage.setItem('myAutoImportLang', $scope.currentLang);
			}
			
			// Synchroniser avec $rootScope
			$rootScope.lang = $scope.currentLang;
		};
		
		
		$scope.toggleMobileMenu = function() {
			var menu = document.querySelector('.nav-menu');
			menu.classList.toggle('active');
		};

		// Fermer le menu si on clique ailleurs
		document.addEventListener('click', function(event) {
			var menu = document.querySelector('.nav-menu');
			var burger = document.querySelector('.mobile-menu-toggle');
			
			if (menu && burger && !menu.contains(event.target) && !burger.contains(event.target)) {
				menu.classList.remove('active');
			}
		});

		// Initialiser la langue au chargement
		$scope.initLanguage();
		
		// 🌍 NOUVEAU : Charger les pays une seule fois
		ConfigService.getCountries().then(function(data) {
			$rootScope.allCountries = data;
			$rootScope.countries = data[$scope.currentLang] || data['fr'] || {};
			console.log('🌍 [MainController] Pays chargés pour langue:', $scope.currentLang);
		});
		
		// Fonction de traduction
		$scope.t = function(key) {
			// Utilise directement $rootScope.t si disponible
			if ($rootScope.t && typeof $rootScope.t === 'function') {
				return $rootScope.t(key);
			}
			// Sinon retourne la clé (fallback)
			return key;
		};
		
		// CORRECTION: Fonction pour changer de langue SANS RECHARGER LA PAGE
		$scope.setLang = function(lang) {
			$scope.currentLang = lang;
			$rootScope.lang = lang;
			localStorage.setItem('myAutoImportLang', lang);
			
			// 🌍 NOUVEAU : Mettre à jour les pays selon la nouvelle langue
			if ($rootScope.allCountries && $rootScope.allCountries[lang]) {
				$rootScope.countries = $rootScope.allCountries[lang];
				console.log('🔄 [MainController] Pays mis à jour pour langue:', lang);
			}
			
			// Forcer la mise à jour de la vue Angular
			$timeout(function() {
				$scope.$apply();
			});
		};
		
		// Fonction pour vérifier la langue active
		$scope.isLang = function(lang) {
			return $scope.currentLang === lang;
		};
		
		// Fonction pour obtenir le chemin actuel
		$scope.currentPath = function() {
			return $location.path();
		};
		
		$scope.$watch('currentLang', function(newLang) {
			var titles = {
				'fr': 'Importer & Exporter Voiture en Suisse - Déclaration Douanière Simplifiée | MyAutoImport.ch',
				'de': 'Auto Import & Export Schweiz - Vereinfachte Zollanmeldung | MyAutoImport.ch',
				'it': 'Importare & Esportare Auto in Svizzera - Dichiarazione Semplificata | MyAutoImport.ch',
				'en': 'Import & Export Car in Switzerland - Simplified Declaration | MyAutoImport.ch'
			};
			$window.document.title = titles[newLang] || titles['fr'];
		});
	}])

	.factory('ConfigService', ['$http', '$q', function($http, $q) {
		const cache = {};

		function getCached(key, apiUrl) {
			if (cache[key]) {
				return $q.resolve(cache[key]);
			}
			const dataFromSession = sessionStorage.getItem(key);
			if (dataFromSession) {
				cache[key] = JSON.parse(dataFromSession);
				return $q.resolve(cache[key]);
			}
			return $http.get(apiUrl).then(function(response) {
				cache[key] = response.data;
				sessionStorage.setItem(key, JSON.stringify(response.data));
				return response.data;
			});
		}

		return {
			getCountries: () => getCached('countries', '/api/countries'),
			getCurrencies: () => getCached('currencies', '/api/currencies'),
			getExchangeRates: () => getCached('exchange_rates', '/api/exchange-rates')
		};
	}])

	.factory('TranslationService', ['$http', '$q', function($http, $q) {
		let translations = {};
		const promise = $http.get('/translations/strings.json').then(function(response) {
			translations = response.data;
			return translations;
		});

		return {
			getPromise: promise,
			get: function(key, lang) {
				if (translations[key] && translations[key][lang]) {
					return translations[key][lang];
				}
				return key;
			}
		};
	}])

	.run(['$rootScope', '$location', 'TranslationService', function($rootScope, $location, TranslationService) {
		
		// Supprime l'ancienne logique de gestion de la langue
		delete $rootScope.lang;
		delete $rootScope.setLang;
		delete $rootScope.isLang;
		
		// Assurer que $rootScope.t utilise la traduction fournie par TranslationService
		TranslationService.getPromise.then(function() {
			$rootScope.t = function(key) {
				// Récupère la langue depuis le scope parent (MainController)
				const lang = $rootScope.currentLang || localStorage.getItem('myAutoImportLang') || 'fr';
				return TranslationService.get(key, lang);
			};
		});

		$rootScope.setErrorContext = function(token) {
			sessionStorage.setItem('error_session_token', token);
			$location.path('/submission-error');
		};

		$rootScope.notifications = [];

		$rootScope.showNotification = function(message, type, duration) {
			type = type || 'info';
			duration = duration || 5000;

			const notification = {
				id: Date.now(),
				message: message,
				type: type,
				visible: true
			};

			$rootScope.notifications.push(notification);

			if (duration > 0) {
				setTimeout(() => {
					$rootScope.$apply(() => {
						notification.visible = false;
						setTimeout(() => {
							$rootScope.$apply(() => {
								const index = $rootScope.notifications.indexOf(notification);
								if (index > -1) {
									$rootScope.notifications.splice(index, 1);
								}
							});
						}, 300);
					});
				}, duration);
			}

			return notification.id;
		};

		$rootScope.hideNotification = function(id) {
			const notification = $rootScope.notifications.find(n => n.id === id);
			if (notification) {
				notification.visible = false;
				setTimeout(() => {
					$rootScope.$apply(() => {
						const index = $rootScope.notifications.indexOf(notification);
						if (index > -1) {
							$rootScope.notifications.splice(index, 1);
						}
					});
				}, 300);
			}
		};
	}]);
