// Questo file fa parte di MyTown.
// MyTown è software libero: puoi ridistribuirlo e/o modificarlo secondo
// i termini della GNU Affero General Public License come pubblicata dalla
// Free Software Foundation, versione 3.
// Distribuito senza ALCUNA GARANZIA; vedi la GNU AGPL v3 per i dettagli.
// Copyright (C) Kondor Consulting & Services S.r.l.
// SPDX-License-Identifier: AGPL-3.0-or-later

import { Component } from '@angular/core';
import { AlertController, Platform } from '@ionic/angular';
import { PrimeNG } from 'primeng/config';
import { BehaviorSubject, Observable } from 'rxjs';
import { TranslateService } from '@ngx-translate/core';
import { LoginService } from './providers/login.service';
import { ConfigService } from './providers/config.service';
import { PushService } from './providers/push.service';
import { ContactsService } from './providers/contacts.service';
import { Router } from '@angular/router';
import { register } from 'swiper/element/bundle';
@Component({
	selector: 'app-root',
	templateUrl: 'app.component.html',
	styleUrls: ['app.component.scss'],
	standalone: false,
})
export class AppComponent {
	private stateParamsSubject = new BehaviorSubject<any>({});
	stateParams$: Observable<any> = this.stateParamsSubject.asObservable();
	constructor(
		private platform: Platform,
		private login: LoginService,
		public config: ConfigService,
		private pushService: PushService,
		private contactsService: ContactsService,
		private router: Router,
		private alertCtrl: AlertController,
		private translate: TranslateService,
		private primeng: PrimeNG,
	) {}
	SupportedLanguages: string[] = ['en', 'it'];

	/** Pagina di ingresso per gli utenti NON autenticati: app pubblica, '/bakeka'. */
	private entryRoute(): string {
		return '/bakeka';
	}

	ngOnInit() {
		this.primeng.ripple.set(true);
		this.platform.ready().then(async () => {
			await this.pushService.initialize();
			this.setupPushListeners();
			this.configAPIGoolge();
			// Carica contatti silenziosamente se il permesso è già stato concesso.
			this.contactsService.loadIfPermitted();
			if (this.config.getUser()) {
				if (this.config.getUser().token) {
					let token = this.config.getUser().token;
					let token_will_exipre = new Date(parseInt(JSON.parse(atob(token.substring(token.indexOf('.') + 1, token.lastIndexOf('.')))).exp + '000'));
					if (token_will_exipre.getTime() - new Date().getTime() < 0 && this.config.getUser()?.usr_id != 0) {
						localStorage.clear();
						this.login.set_reload(false);
						this.router.navigate([this.entryRoute()]);
					} else {
						this.login.set_reload(true);
						this.pushService.subscribeToBackend();
						const params = new URLSearchParams(window.location.search);
						let link = params.get('link');
						let folder_id = params.get('folder_id');
						if (link == 'sezione_documentale') {
							this.router.navigate(['/sezione_documentale/' + folder_id]);
						} else {
							this.router.navigate([this.config.getLandingRoute()]);
						}
					}
				} else {
					localStorage.clear();
					this.login.set_reload(false);
					this.router.navigate([this.entryRoute()]);
				}
			} else {
				localStorage.clear();
				//MI INIZIO gestione registrazione tramite link
				const params = new URLSearchParams(window.location.search);
				let guid = params.get('guid');
				let type = params.get('type');
				if (guid && type) {
					localStorage.setItem('guid', guid);
					localStorage.setItem('type', type);
				}
				//MI FINE gestione registrazione tramite link
				this.login.set_reload(false);
				// Deep-link di registrazione (guid+type) → sempre al login.
				// Altrimenti landing in base al brand (MyTown pubblica = bacheca).
				this.router.navigate([guid && type ? '/login' : this.entryRoute()]);
			}
		});
		this.setLanguage();
	}
	private setupPushListeners() {
		this.pushService.notificationAction$.subscribe((action) => {
			const data = action.notification.data;
			if (data && data.tipo) {
				if (data.tipo === 'LOGIN') {
					this.presentAlertLogin('Conferma Login', 'KO', 'OK', data.id);
				} else if (data.tipo?.startsWith('MESSAGE:')) {
					const convId = parseInt(data.tipo.split(':')[1], 10);
					if (!isNaN(convId) && convId > 0) {
						this.router.navigate(['/messaging/chat', convId], {
							state: {
								chatWith: action.notification.title || 'Chat',
								isCompany: true,
							},
						});
					}
				} else if (data.tipo?.startsWith('APPOINTMENT:')) {
					const aptId = parseInt(data.tipo.split(':')[1], 10);
					if (!isNaN(aptId) && aptId > 0) {
						this.router.navigate(['/biz-appointments/detail', aptId]);
					}
				} else {
					// Tipi senza deep-link (es. BOOKING:/ORDER:/PLACE: delle recensioni,
					// che richiederebbero prt_id/cmp_id): apri l'elenco notifiche
					this.router.navigate(['/notifications']);
				}
			}
		});
	}
	configAPIGoolge() {
		const apiKey = this.config.apiGoogleMapsKey;
		const script = document.createElement('script');
		script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places`;
		script.async = true;
		script.defer = true;
		document.head.appendChild(script);
	}
	async presentAlertLogin(msg: string, msgKoBtn: string, msgOkBtn: string, id: number) {
		const alert = await this.alertCtrl.create({
			header: 'Login',
			message: msg,
			buttons: [
				{
					text: msgKoBtn,
					cssClass: 'alert-button-cancel',
					handler: () => {
						this.login.confirm_app(id, 'KO').subscribe();
					},
				},
				{
					text: msgOkBtn,
					cssClass: 'alert-button-confirm',
					handler: () => {
						this.login.confirm_app(id, 'OK').subscribe();
					},
				},
			],
		});
		await alert.present();
	}
	private getResponsePreview(response: any): string {
		if (typeof response === 'string') {
			return response.length > 50 ? response.substring(0, 50) + '...' : response;
		} else if (Array.isArray(response)) {
			return `Array with ${response.length} item(s)`;
		} else if (typeof response === 'object' && response !== null) {
			const keys = Object.keys(response);
			return `Object with keys: ${keys.slice(0, 3).join(', ')}${keys.length > 3 ? '...' : ''}`;
		}
		return String(response);
	}
	setLanguage() {
		this.translate.addLangs(this.SupportedLanguages);
		if (this.config.getLocalStorageLanguage() != 'KO') {
			this.config.language = this.config.getLocalStorageLanguage();
		} else if (this.config.getUser()) {
			this.config.language = this.config.getLanguage();
		} else {
			this.config.language = 'it';
		}
		this.translate.use(this.config.language);
		this.setLocale(this.primeng, this.config.language);
		setTimeout(() => {
			//this.spinner.hide('app');
		}, 1000);
	}
	setLocale(config: PrimeNG, locale: string): void {
		const normalizedLocale = locale.trim().toLowerCase();
		switch (normalizedLocale) {
			case 'en': {
				const dow: string[] = config.getTranslation('dayNames');
				if (dow[0] !== 'Sunday') {
					console.warn('Default locale is not English. Setting English translations.');
				}
				config.setTranslation({
					startsWith: 'Starts with',
					contains: 'Contains',
					notContains: 'Does not contain',
					endsWith: 'Ends with',
					equals: 'Equals',
					notEquals: 'Does not equal',
					noFilter: 'No Filter',
					lt: 'Less than',
					lte: 'Less than or equal to',
					gt: 'Greater than',
					gte: 'Greater than or equal to',
					is: 'Is',
					isNot: 'Is not',
					before: 'Before',
					after: 'After',
					apply: 'Apply',
					matchAll: 'Match All',
					matchAny: 'Match Any',
					addRule: 'Add Rule',
					removeRule: 'Remove Rule',
					accept: 'Yes',
					reject: 'No',
					choose: 'Choose',
					upload: 'Upload',
					cancel: 'Cancel',
					dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
					dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
					dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
					monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
					monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
					today: 'Today',
					clear: 'Clear',
					weekHeader: 'Wk',
				});
				break;
			}
			case 'it': {
				config.setTranslation({
					startsWith: 'Inizia con',
					contains: 'Contiene',
					notContains: 'Non contiene',
					endsWith: 'Finisce con',
					equals: 'Uguale',
					notEquals: 'Non uguale',
					noFilter: 'Nessun filtro',
					lt: 'Minore di',
					lte: 'Minore o uguale a',
					gt: 'Maggiore di',
					gte: 'Maggiore o uguale a',
					is: 'È',
					isNot: 'Non è',
					before: 'Prima',
					after: 'Dopo',
					apply: 'Applica',
					matchAll: 'Corrispondi a tutti',
					matchAny: 'Corrispondi a qualsiasi',
					addRule: 'Aggiungi regola',
					removeRule: 'Rimuovi regola',
					accept: 'Sì',
					reject: 'No',
					choose: 'Scegli',
					upload: 'Carica',
					cancel: 'Annulla',
					dayNames: ['Domenica', 'Lunedì', 'Martedì', 'Mercoledì', 'Giovedì', 'Venerdì', 'Sabato'],
					dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab'],
					dayNamesMin: ['Do', 'Lu', 'Ma', 'Me', 'Gi', 'Ve', 'Sa'],
					monthNames: ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'],
					monthNamesShort: ['Gen', 'Feb', 'Mar', 'Apr', 'Mag', 'Giu', 'Lug', 'Ago', 'Set', 'Ott', 'Nov', 'Dic'],
					today: 'Oggi',
					clear: 'Cancella',
					weekHeader: 'Sett',
				});
				break;
			}
			case 'de': {
				console.warn('German locale not implemented yet.');
				break;
			}
			default: {
				console.error(`Locale '${locale}' not available. Falling back to English.`);
				config.setTranslation({
					startsWith: 'Starts with',
					contains: 'Contains',
					notContains: 'Does not contain',
					endsWith: 'Ends with',
					equals: 'Equals',
					notEquals: 'Does not equal',
					noFilter: 'No Filter',
					lt: 'Less than',
					lte: 'Less than or equal to',
					gt: 'Greater than',
					gte: 'Greater than or equal to',
					is: 'Is',
					isNot: 'Is not',
					before: 'Before',
					after: 'After',
					apply: 'Apply',
					matchAll: 'Match All',
					matchAny: 'Match Any',
					addRule: 'Add Rule',
					removeRule: 'Remove Rule',
					accept: 'Yes',
					reject: 'No',
					choose: 'Choose',
					upload: 'Upload',
					cancel: 'Cancel',
					dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
					dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
					dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
					monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
					monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
					today: 'Today',
					clear: 'Clear',
					weekHeader: 'Wk',
				});
				break;
			}
		}
	}
}
//Swiper's register function to globally register Swiper's custom elements
register();
