// Mobile Push Notifications with Capacitor
// This replaces browser notifications for mobile apps

class MobileNotificationManager {
    constructor() {
        this.isMobile = this.detectMobile();
        this.isCapacitor = window.Capacitor !== undefined;
        if (this.isCapacitor) {
            this.setup();
        }
    }

    detectMobile() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }

    async setup() {
        if (!this.isCapacitor) {
            return; // Not in Capacitor, use browser notifications
        }

        try {
            // Dynamically import Capacitor plugins
            const { PushNotifications } = await import('@capacitor/push-notifications');
            const { LocalNotifications } = await import('@capacitor/local-notifications');
            const { Haptics } = await import('@capacitor/haptics');

            await this.initializePushNotifications(PushNotifications, LocalNotifications, Haptics);
        } catch (error) {
            console.log('Capacitor plugins not available, using browser notifications');
        }
    }

    async initializePushNotifications(PushNotifications, LocalNotifications, Haptics) {
        // Request permission
        let permStatus = await PushNotifications.checkPermissions();
        
        if (permStatus.receive === 'prompt') {
            permStatus = await PushNotifications.requestPermissions();
        }

        if (permStatus.receive !== 'granted') {
            console.log('Push notification permission denied');
            return;
        }

        // Register for push
        await PushNotifications.register();

        // Listen for registration
        PushNotifications.addListener('registration', (token) => {
            console.log('Push registration success, token: ' + token.value);
            this.registerToken(token.value);
        });

        // Listen for registration errors
        PushNotifications.addListener('registrationError', (error) => {
            console.error('Error on registration: ' + JSON.stringify(error));
        });

        // Listen for push notifications
        PushNotifications.addListener('pushNotificationReceived', (notification) => {
            console.log('Push notification received: ', notification);
            
            // Show local notification with sound
            LocalNotifications.schedule({
                notifications: [{
                    title: notification.title || 'Assignment Reminder',
                    body: notification.body || notification.data?.message || '',
                    id: Date.now(),
                    sound: 'default', // Native sound
                    attachments: null,
                    actionTypeId: '',
                    extra: notification.data || {}
                }]
            });

            // Haptic feedback
            Haptics.vibrate({ duration: 200 });
        });

        // Listen for notification actions
        PushNotifications.addListener('pushNotificationActionPerformed', (action) => {
            console.log('Push notification action performed', action);
            
            if (action.notification.data?.url) {
                window.location.href = action.notification.data.url;
            }
        });

        // Setup local notifications
        await this.setupLocalNotifications(LocalNotifications);
    }

    async registerToken(token) {
        try {
            const platform = window.Capacitor.getPlatform() === 'ios' ? 'ios' : 'android';
            
            const response = await fetch('/api/device-tokens/register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'),
                    'Accept': 'application/json'
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    token: token,
                    platform: platform,
                    device_id: this.getDeviceId(),
                    device_name: navigator.userAgent
                })
            });

            if (response.ok) {
                console.log('Device token registered successfully');
            }
        } catch (error) {
            console.error('Error registering device token:', error);
        }
    }

    getDeviceId() {
        let deviceId = localStorage.getItem('device_id');
        if (!deviceId) {
            deviceId = 'device_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('device_id', deviceId);
        }
        return deviceId;
    }

    async setupLocalNotifications(LocalNotifications) {
        const permStatus = await LocalNotifications.requestPermissions();
        
        if (permStatus.display === 'granted') {
            console.log('Local notifications permission granted');
        }
    }
}

// Initialize mobile notifications if Capacitor is available
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        if (window.Capacitor) {
            window.mobileNotificationManager = new MobileNotificationManager();
        }
    });
} else {
    if (window.Capacitor) {
        window.mobileNotificationManager = new MobileNotificationManager();
    }
}
