// NotificationManager.jsx - Handles all notification types
const { useState, useCallback } = React;

const NotificationManager = {
    // Browser Notification
    showBrowserNotification: (title, options = {}) => {
        if (!('Notification' in window)) {
            console.log('Browser notifications not supported');
            return false;
        }

        if (Notification.permission === 'granted') {
            return new Notification(title, {
                icon: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                badge: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                ...options
            });
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    new Notification(title, {
                        icon: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                        badge: 'https://qzezgagdxaootepuykdl.supabase.co/storage/v1/object/public/favicon.png',
                        ...options
                    });
                }
            });
        }
        return false;
    },

    // Email Notification via EmailJS
    sendEmailNotification: async (enrollmentData, adminEmail = 'bappa4uall@gmail.com') => {
        const templateParams = {
            to_email: adminEmail,
            student_name: enrollmentData.name,
            student_email: enrollmentData.email,
            student_phone: enrollmentData.phone,
            class_enrolled: enrollmentData.classItem?.title || 'General Enrollment',
            experience_level: enrollmentData.experience,
            message: enrollmentData.message || 'No message provided',
            enrollment_date: new Date().toLocaleString()
        };

        // EmailJS configuration - Replace with your credentials
        const EMAILJS_CONFIG = {
            serviceId: 'YOUR_SERVICE_ID',
            templateId: 'YOUR_TEMPLATE_ID',
            publicKey: 'YOUR_PUBLIC_KEY'
        };

        // Check if EmailJS is configured
        if (window.emailjs && EMAILJS_CONFIG.serviceId !== 'YOUR_SERVICE_ID') {
            try {
                await window.emailjs.send(
                    EMAILJS_CONFIG.serviceId,
                    EMAILJS_CONFIG.templateId,
                    templateParams,
                    EMAILJS_CONFIG.publicKey
                );
                console.log('Email notification sent successfully');
                return { success: true, type: 'email' };
            } catch (error) {
                console.error('Email notification failed:', error);
                return { success: false, type: 'email', error: error.message };
            }
        } else {
            // Log notification data (for development/demo)
            console.log('📧 Email Notification (Demo):', templateParams);
            return { success: true, type: 'email', demo: true };
        }
    },

    // SMS/WhatsApp Notification via Twilio (Backend required)
    sendSMSNotification: async (enrollmentData, adminPhone = '+1234567890') => {
        const message = `🎨 New Enrollment at Arpita Art Academy!

Student: ${enrollmentData.name}
Email: ${enrollmentData.email}
Phone: ${enrollmentData.phone}
Class: ${enrollmentData.classItem?.title || 'General Enrollment'}
Experience: ${enrollmentData.experience}

Time: ${new Date().toLocaleString()}`;

        // Twilio configuration - Would need backend server
        const TWILIO_CONFIG = {
            accountSid: 'YOUR_ACCOUNT_SID',
            authToken: 'YOUR_AUTH_TOKEN',
            fromNumber: '+1234567890'
        };

        // Check if Twilio is configured
        if (TWILIO_CONFIG.accountSid !== 'YOUR_ACCOUNT_SID') {
            try {
                // This would require a backend endpoint
                const response = await fetch('/api/send-sms', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        to: adminPhone,
                        message: message,
                        from: TWILIO_CONFIG.fromNumber
                    })
                });
                console.log('SMS notification sent successfully');
                return { success: true, type: 'sms' };
            } catch (error) {
                console.error('SMS notification failed:', error);
                return { success: false, type: 'sms', error: error.message };
            }
        } else {
            // Log notification data (for development/demo)
            console.log('📱 SMS Notification (Demo):', {
                to: adminPhone,
                message: message
            });
            return { success: true, type: 'sms', demo: true };
        }
    },

    // WhatsApp Notification via Twilio
    sendWhatsAppNotification: async (enrollmentData, adminPhone = '+1234567890') => {
        const message = `🎨 *New Enrollment - Arpita Art Academy*

*Student:* ${enrollmentData.name}
*Email:* ${enrollmentData.email}
*Phone:* ${enrollmentData.phone}
*Class:* ${enrollmentData.classItem?.title || 'General Enrollment'}
*Experience:* ${enrollmentData.experience}

_Date: ${new Date().toLocaleString()}_`;

        // Twilio WhatsApp configuration
        const TWILIO_WHATSAPP_CONFIG = {
            accountSid: 'YOUR_ACCOUNT_SID',
            authToken: 'YOUR_AUTH_TOKEN',
            fromWhatsApp: 'whatsapp:+14155238886' // Twilio sandbox number
        };

        // Check if Twilio is configured
        if (TWILIO_WHATSAPP_CONFIG.accountSid !== 'YOUR_ACCOUNT_SID') {
            try {
                const response = await fetch('/api/send-whatsapp', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        to: `whatsapp:${adminPhone}`,
                        message: message,
                        from: TWILIO_WHATSAPP_CONFIG.fromWhatsApp
                    })
                });
                console.log('WhatsApp notification sent successfully');
                return { success: true, type: 'whatsapp' };
            } catch (error) {
                console.error('WhatsApp notification failed:', error);
                return { success: false, type: 'whatsapp', error: error.message };
            }
        } else {
            // Log notification data (for development/demo)
            console.log('💬 WhatsApp Notification (Demo):', {
                to: adminPhone,
                message: message
            });
            return { success: true, type: 'whatsapp', demo: true };
        }
    },

    // Send all notifications
    sendAllNotifications: async (enrollmentData, adminConfig = {}) => {
        const results = {
            browser: null,
            email: null,
            sms: null,
            whatsapp: null
        };

        const {
            enableBrowser = true,
            enableEmail = true,
            enableSMS = false,
            enableWhatsApp = false,
            adminEmail = 'admin@arpitaart.com',
            adminPhone = '+1234567890'
        } = adminConfig;

        // Browser notification (immediate)
        if (enableBrowser) {
            results.browser = NotificationManager.showBrowserNotification(
                '🎨 New Enrollment!',
                {
                    body: `${enrollmentData.name} enrolled in ${enrollmentData.classItem?.title || 'General Enrollment'}`,
                    tag: 'new-enrollment'
                }
            );
        }

        // Email notification
        if (enableEmail) {
            results.email = await NotificationManager.sendEmailNotification(
                enrollmentData,
                adminEmail
            );
        }

        // SMS notification
        if (enableSMS) {
            results.sms = await NotificationManager.sendSMSNotification(
                enrollmentData,
                adminPhone
            );
        }

        // WhatsApp notification
        if (enableWhatsApp) {
            results.whatsapp = await NotificationManager.sendWhatsAppNotification(
                enrollmentData,
                adminPhone
            );
        }

        return results;
    }
};

window.NotificationManager = NotificationManager;