// 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

// app-layout.component.ts
import { Component, inject, effect, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { LayoutService } from '../../providers/layout.service';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { IonicModule, PopoverController } from '@ionic/angular';
import { UserMenuComponent } from '../user-menu/user-menu.component';
import { ConfigService } from 'src/app/providers/config.service';
import { MessagingService } from 'src/app/providers/messaging.service';
import { App } from '@capacitor/app';

@Component({
	selector: 'app-layout',
	template: `
		<!-- ═══ HEADER ═══ -->
		@if (layoutService.showHeader()) {
		<ion-header class="app-header ion-no-border">
			<ion-toolbar>
				<ion-buttons slot="start">
					@if (layoutService.showBackButton()) {
					<ion-back-button class="back-btn" [defaultHref]="layoutService.backButtonHref()" text=""></ion-back-button>
					} @else {
					<ion-menu-button class="menu-btn"></ion-menu-button>
					}
				</ion-buttons>

				<ion-title>
					<div class="title-wrap" [class.has-subtitle]="!!layoutService.pageSubtitle()">
						<span class="page-title">{{ layoutService.pageTitle() }}</span>
						@if (layoutService.pageSubtitle()) {
						<span class="page-subtitle">{{ layoutService.pageSubtitle() }}</span>
						}
					</div>
				</ion-title>

				@if (layoutService.headerRightButton()) {
				<ion-buttons slot="end">
					<ion-button class="icon-btn" (click)="navigateRight()">
						<ion-icon [name]="layoutService.headerRightButton()!.icon" slot="icon-only"></ion-icon>
					</ion-button>
				</ion-buttons>
				}
			</ion-toolbar>
		</ion-header>
		}

		<!-- Router outlet -->
		<ion-content>
			<ion-router-outlet></ion-router-outlet>
		</ion-content>

		<!-- ═══ FOOTER TAB BAR ═══ -->
		@if (layoutService.showTabBar()) {
		<ion-footer class="ion-no-border tab-footer">
			<ion-tab-bar mode="md" class="main-tab-bar">
				@for (tab of tabs; track tab.value) {
				<ion-tab-button (click)="navigateToTab(tab.value)" [selected]="layoutService.selectedTab() === tab.value" [class.is-active]="layoutService.selectedTab() === tab.value">
					<div class="tab-pip">
						<ion-icon [name]="layoutService.selectedTab() === tab.value ? tab.icon : tab.iconOutline" class="tab-icon"></ion-icon>
					</div>
					<span class="tab-label">{{ tab.label }}</span>
					@if (getTabBadgeCount(tab.value) > 0) {
					<span class="tab-badge">{{ getTabBadgeCount(tab.value) > 99 ? '99+' : getTabBadgeCount(tab.value) }}</span>
					}
				</ion-tab-button>
				}
			</ion-tab-bar>
		</ion-footer>
		} @else {
		<ion-footer class="ion-no-border bare-footer">
			<div class="footer-line"></div>
		</ion-footer>
		}
	`,
	styles: [
		`
			/* ─── HEADER ─────────────────────────────────────── */

			ion-header.app-header ion-toolbar {
				--background: var(--app-brand);
				--color: var(--app-on-brand);
				--border-width: 0;
				--padding-start: 4px;
				--padding-end: 6px;
				--min-height: 54px;
			}

			.title-wrap {
				display: flex;
				flex-direction: column;
				justify-content: center;
				line-height: 1.15;
				min-width: 0;
			}

			.title-wrap.has-subtitle .page-title {
				font-size: 15.5px;
			}

			.page-title {
				font-size: 17px;
				font-weight: 700;
				letter-spacing: 0.2px;
				color: var(--app-on-brand);
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.page-subtitle {
				display: block;
				font-size: 11px;
				font-weight: 500;
				letter-spacing: 0.15px;
				color: rgba(var(--app-on-brand-rgb), 0.85);
				margin-top: 2px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 100%;
			}

			.back-btn {
				--color: rgba(var(--app-on-brand-rgb), 0.9);
				--icon-font-size: 22px;
			}

			.menu-btn {
				--color: rgba(var(--app-on-brand-rgb), 0.9);
			}

			.icon-btn {
				--color: rgba(var(--app-on-brand-rgb), 0.9);
				--background: transparent;
				--background-activated: rgba(var(--app-on-brand-rgb), 0.12);
				--border-radius: 50%;
				--padding-start: 8px;
				--padding-end: 8px;
			}

			/* Notification bell + badge */
			.notif-wrap {
				position: relative;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 30px;
				height: 30px;
			}

			.header-icon {
				font-size: 22px;
			}

			.notif-dot {
				position: absolute;
				top: -1px;
				right: -3px;
				background: #ef4444;
				color: #fff;
				font-size: 8px;
				font-weight: 800;
				min-width: 14px;
				height: 14px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 3px;
				border: 1.5px solid var(--app-brand);
				line-height: 1;
				letter-spacing: -0.2px;
			}

			/* Avatar button */
			.avatar-btn {
				--background: transparent;
				--background-activated: rgba(var(--app-on-brand-rgb), 0.08);
				--padding-start: 6px;
				--padding-end: 8px;
			}

			.avatar-wrap {
				position: relative;
				width: 34px;
				height: 34px;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.avatar-ring {
				position: absolute;
				inset: 0;
				border-radius: 50%;
				border: 2px solid rgba(var(--app-on-brand-rgb), 0.35);
			}

			.avatar-inner {
				width: 28px;
				height: 28px;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 11px;
				font-weight: 800;
				color: var(--app-on-brand);
				letter-spacing: 0.5px;
			}

			/* ─── FOOTER TAB BAR ──────────────────────────────── */

			.tab-footer {
				background: transparent;
				--border-width: 0;
			}

			.main-tab-bar {
				--background: #ffffff;
				--border: 0 none transparent;
				--color: #94a3b8;
				--color-selected: var(--app-brand-2);
				height: 50px;
				border-radius: 20px 20px 0 0;
				box-shadow: 0 -6px 32px rgba(var(--app-brand-rgb), 0.08), 0 -1px 0 rgba(0, 0, 0, 0.05);
				padding: 0;
			}

			/* Tab button base */
			.main-tab-bar ion-tab-button {
				--color: #94a3b8;
				--color-selected: var(--app-brand-2);
				--padding-top: 0px;
				--padding-bottom: 0px;
				--ripple-color: rgba(var(--app-brand-rgb), 0.1);
				max-width: none;
				text-align: center;
			}

			/* Icon pip container */
			.tab-pip {
				width: 36px;
				height: 28px;
				border-radius: 10px;
				display: flex;
				align-items: center;
				justify-content: center;
				background: transparent;
				transition: background 0.22s cubic-bezier(0.4, 0, 0.2, 1);
				margin: 0 auto 4px auto;
				overflow: hidden;
			}

			.tab-icon {
				font-size: 20px !important;
				width: 20px !important;
				height: 20px !important;
				display: flex !important;
				align-items: center;
				justify-content: center;
				flex-shrink: 0;
				transition: transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
			}

			/* Active tab — pill highlight + icon bounce */
			.main-tab-bar ion-tab-button.is-active .tab-pip {
				background: rgba(var(--app-brand-rgb), 0.18);
			}

			.main-tab-bar ion-tab-button.is-active .tab-icon {
				transform: translateY(-2px) scale(1.08);
			}

			/* Label */
			.tab-label {
				font-size: 9px !important;
				font-weight: 500;
				display: block !important;
				text-align: center;
				letter-spacing: 0;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				max-width: 100%;
				line-height: 1;
				/* color inherited from ion-tab-button --color / --color-selected */
			}

			.main-tab-bar ion-tab-button.is-active .tab-label {
				font-weight: 700;
			}

			/* Badge on tab */
			.tab-badge {
				position: absolute;
				top: 4px;
				right: 6px;
				background: #ef4444;
				color: #fff;
				font-size: 8px;
				font-weight: 800;
				min-width: 14px;
				height: 14px;
				border-radius: 7px;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0 3px;
				border: 1.5px solid #fff;
			}

			/* Bare footer (when tab bar hidden) */
			.bare-footer {
				background: transparent;
			}

			.footer-line {
				height: 1px;
				background: rgba(83, 104, 120, 0.3);
			}
		`,
	],
	imports: [FormsModule, IonicModule, ReactiveFormsModule],
})
export class AppLayoutComponent implements OnInit, OnDestroy {
	layoutService = inject(LayoutService);
	private router = inject(Router);
	private http = inject(HttpClient);
	private messagingService = inject(MessagingService);

	unreadCount = 0;
	unreadMessages = 0;
	private unreadInterval: any;
	private appStateListener: any;

	private allTabs = [
		{ value: 'bakeka', icon: 'book', iconOutline: 'bookmark-outline', label: 'Bacheca' },
		{ value: 'services', icon: 'pricetags', iconOutline: 'pricetags-outline', label: 'Servizi' },
		{ value: 'categories', icon: 'grid', iconOutline: 'grid-outline', label: 'Categorie' },
		{ value: 'messaging', icon: 'chatbubble-ellipses', iconOutline: 'chatbubble-ellipses-outline', label: 'Chat' },
		{ value: 'notifications', icon: 'notifications', iconOutline: 'notifications-outline', label: 'Notifiche' },
		{ value: 'profile', icon: 'person', iconOutline: 'person-outline', label: 'Profilo' },
	];

	get tabs() {
		const logged = this.config.isLogged();
		return this.allTabs
			.filter((t) => {
				// Chat: nascosta agli utenti non registrati (app pubblica).
				if (t.value === 'messaging' && !logged) return false;
				// Notifiche: solo utenti registrati (funzione personale, rotta protetta).
				if (t.value === 'notifications' && !logged) return false;
				return true;
			})
			.map((t) => {
				// Profilo: per i non registrati diventa "Accedi" e porta direttamente al login.
				if (t.value === 'profile' && !logged) {
					return { ...t, icon: 'log-in', iconOutline: 'log-in-outline', label: 'Accedi' };
				}
				return t;
			});
	}

	currentRoute = toSignal(this.router.events.pipe(filter((event) => event instanceof NavigationEnd)));

	constructor(private popoverController: PopoverController, public config: ConfigService) {
		effect(() => {
			const navEvent = this.currentRoute();
			if (navEvent) {
				this.updateSelectedTabFromRoute();
				this.layoutService.pushToHistory(this.router.url);
			}
		});
	}

	ngOnInit() {
		this.updateSelectedTabFromRoute();
		if (this.config.isLogged()) {
			this.loadUnreadCount();
			this.startUnreadInterval();
			this.appStateListener = App.addListener('appStateChange', ({ isActive }) => {
				if (isActive) {
					// App tornata in foreground: aspetta 1.5s per rete ristabilita poi aggiorna
					setTimeout(() => {
						this.loadUnreadCount();
						this.startUnreadInterval();
					}, 1500);
				} else {
					// App in background: ferma l'intervallo
					this.stopUnreadInterval();
				}
			});
		}
	}

	ngOnDestroy() {
		this.stopUnreadInterval();
		if (this.appStateListener) this.appStateListener.remove();
	}

	private startUnreadInterval() {
		this.stopUnreadInterval();
		this.unreadInterval = setInterval(() => this.loadUnreadCount(), 60000);
	}

	private stopUnreadInterval() {
		if (this.unreadInterval) {
			clearInterval(this.unreadInterval);
			this.unreadInterval = null;
		}
	}

	loadUnreadCount() {
		/*this.http.get(this.config.serviceUrl_PortalManager + 'notify/unread-count').subscribe({
			next: (count: any) => (this.unreadCount = count),
			error: () => {},
		});*/
		// Badge messaggi: solo quando il tab Chat esiste (utente loggato)
		if (!this.config.isLogged()) return;
		this.messagingService.getUnreadCount().subscribe({
			next: (count) => (this.unreadMessages = Number(count) || 0),
			error: () => {},
		});
	}

	navigateToTab(tab: string) {
		if (tab === 'services' || tab === 'categories') {
			this.layoutService.homeView.set(tab as 'services' | 'categories');
			this.layoutService.selectedTab.set(tab);
			this.router.navigate(['/servizi']);
		} else if (tab === 'messaging') {
			this.layoutService.selectedTab.set('messaging');
			this.router.navigate(['/messaging']);
		} else if (tab === 'notifications') {
			this.layoutService.selectedTab.set('notifications');
			this.router.navigate(['/notifications']);
		} else if (tab === 'profile') {
			// Non registrato: il tab "Accedi" porta direttamente al login.
			if (!this.config.isLogged()) {
				this.router.navigate(['/login']);
				return;
			}
			this.layoutService.selectedTab.set('profile');
			this.router.navigate(['/profile']);
		} else if (tab === 'bakeka') {
			this.layoutService.selectedTab.set('bakeka');
			this.router.navigate(['/bakeka']);
		}
	}

	getTabBadgeCount(tab: string): number {
		if (tab === 'notifications') return this.unreadCount;
		if (tab === 'messaging') return this.unreadMessages;
		return this.layoutService.getTabBadge(tab);
	}

	private updateSelectedTabFromRoute() {
		const url = this.router.url;
		const segments = url.split('/').filter((s) => s);
		// Rimuove eventuali matrix param (es. /home;refresh=true dopo il login) e query
		// dal primo segmento, altrimenti 'home;refresh=true' non matcha mainRoutes e la tab bar resta nascosta.
		const firstSegment = (segments[0] || 'servizi').split(';')[0].split('?')[0];

		const mainRoutes = ['bakeka', 'servizi', 'messaging', 'notifications', 'profile'];
		this.layoutService.showTabBar.set(mainRoutes.includes(firstSegment));

		if (firstSegment === 'messaging') {
			this.layoutService.selectedTab.set('messaging');
		} else if (firstSegment === 'notifications') {
			this.layoutService.selectedTab.set('notifications');
		} else if (firstSegment === 'profile') {
			this.layoutService.selectedTab.set('profile');
		} else if (firstSegment === 'servizi') {
			this.layoutService.selectedTab.set(this.layoutService.homeView());
		} else if (firstSegment === 'bakeka') {
			this.layoutService.selectedTab.set('bakeka');
		}
	}

	navigateRight() {
		const btn = this.layoutService.headerRightButton();
		if (btn) this.router.navigate([btn.route]);
	}

	async presentUserMenu(event: any) {
		const popover = await this.popoverController.create({
			component: UserMenuComponent,
			event: event,
			translucent: true,
			cssClass: 'user-menu-popover-wrapper',
		});
		await popover.present();
	}

	getAvatarColor(): string {
		return this.config.getColorFromDisplayName();
	}

	getUserInitials(): string {
		return this.config.getUsernameInitials();
	}
}
