/**
 * Notification Manager
 * Handles FCM registration and real-time notifications via Firebase RTDB
 */

const NotificationManager = {
    userType: 'customer',
    userId: null,
    database: null,
    messaging: null,

    init(userId, userType = 'customer') {
        this.userId = userId;
        this.userType = userType;

        if (typeof firebase === 'undefined') {
            console.error("Firebase SDK not loaded");
            return;
        }

        // If firebase is already initialized, start immediately
        if (firebase.apps.length > 0) {
            this.start();
        } else {
            // Otherwise wait for the custom event from firebase_config.js
            document.addEventListener('firebase-ready', (e) => {
                this.config = e.detail;
                this.start();
            }, { once: true });

            // Fallback: fetch it ourselves if the event doesn't fire soon enough
            setTimeout(() => {
                if (firebase.apps.length === 0) {
                    this.fetchConfigAndStart();
                }
            }, 2000);
        }
    },

    fetchConfigAndStart() {
        let apiPath = '../api/get_firebase_config.php';
        fetch(apiPath)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    this.config = data.config;
                    if (!firebase.apps.length) {
                        firebase.initializeApp(this.config);
                    }
                    this.start();
                }
            })
            .catch(err => console.error("NotificationManager: Error fetching fallback config", err));
    },

    start() {
        try {
            this.database = firebase.database();

            // Initialize Messaging if supported
            if (firebase.messaging.isSupported()) {
                this.messaging = firebase.messaging();
                this.setupFCM();
            }
        } catch (e) {
            console.warn("Firebase services initialization error:", e.message);
        }

        this.setupRealtimeListeners();
    },

    setupFCM() {
        // Request permission
        Notification.requestPermission().then((permission) => {
            if (permission === 'granted') {
                const vapidKey = this.config ? this.config.vapidKey : '';
                this.messaging.getToken({
                    vapidKey: vapidKey
                }).then((currentToken) => {
                    if (currentToken) {
                        this.saveTokenToServer(currentToken);
                    }
                }).catch((err) => {
                    console.error('An error occurred while retrieving token. ', err);
                });
            }
        });

        // Listen for token refresh
        this.messaging.onTokenRefresh(() => {
            this.messaging.getToken().then((refreshedToken) => {
                this.saveTokenToServer(refreshedToken);
            });
        });

        // Handle foreground messages
        this.messaging.onMessage((payload) => {
            console.log('Message received. ', payload);
            this.showToast(payload.notification.title, payload.notification.body, payload.data.link);
        });
    },

    saveTokenToServer(token) {
        const apiUrl = this.userType === 'admin' ? '../api/register_fcm_token.php' : '../api/register_fcm_token.php';

        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                fcm_token: token,
                user_type: this.userType
            }),
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('FCM token registered successfully');
            }
        })
        .catch((error) => {
            console.error('Error registering FCM token:', error);
        });
    },

    setupRealtimeListeners() {
        if (!this.userId) return;

        const notifRef = this.database.ref(`notifications/${this.userType}_${this.userId}`);

        // Listen for new notifications added to RTDB
        notifRef.limitToLast(1).on('child_added', (snapshot) => {
            const notif = snapshot.val();
            // Only show if it's within the last 30 seconds to avoid showing old ones on load
            if (notif && notif.timestamp > (Date.now() - 30000)) {
                this.showToast(notif.title, notif.message, notif.link);
                this.updateNotificationUI(notif);
            }
        });
    },

    showToast(title, message, link = '') {
        // Simple toast implementation
        const toast = document.createElement('div');
        toast.className = 'fixed bottom-20 right-4 z-[9999] bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-2xl p-4 max-w-sm animate-bounce-in cursor-pointer hover:scale-105 transition-transform';
        toast.style.animation = 'slideIn 0.5s ease-out';

        toast.innerHTML = `
            <div class="flex items-start gap-3">
                <div class="bg-primary/10 p-2 rounded-full">
                    <span class="material-symbols-outlined text-primary">notifications</span>
                </div>
                <div class="flex-1">
                    <h4 class="font-bold text-sm">${title}</h4>
                    <p class="text-xs text-slate-500 dark:text-slate-400 mt-1">${message}</p>
                </div>
                <button onclick="this.parentElement.parentElement.remove()" class="text-slate-400 hover:text-slate-600">
                    <span class="material-symbols-outlined text-sm">close</span>
                </button>
            </div>
        `;

        toast.onclick = (e) => {
            if (e.target.closest('button')) return;
            if (link) window.location.href = link;
            toast.remove();
        };

        document.body.appendChild(toast);

        // Auto remove
        setTimeout(() => {
            if (toast.parentElement) {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(100%)';
                toast.style.transition = 'all 0.5s ease-in';
                setTimeout(() => toast.remove(), 500);
            }
        }, 8000);
    },

    updateNotificationUI(notif) {
        // This can be used to update a notification bell badge or list
        const badge = document.getElementById('notification-badge');
        if (badge) {
            const count = parseInt(badge.textContent || '0') + 1;
            badge.textContent = count;
            badge.classList.remove('hidden');
        }
    }
};

// CSS for the toast animation
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
`;
document.head.appendChild(style);
