/**
 * Floating Notification Bell
 * Handles push notification subscription popup
 */

(function() {
    'use strict';

    let bellButton = null;
    let popupOverlay = null;
    let isSubscribed = false;

    // Initialize bell button
    function initNotificationBell() {
        // Check if push notifications are enabled
        const pushConfig = window.PUSH_NOTIFICATION_CONFIG;
        if (!pushConfig || !pushConfig.enabled || !pushConfig.appId) {
            return;
        }

        // Create bell button
        createBellButton();
        
        // Create popup
        createPopup();
        
        // Check subscription status
        checkSubscriptionStatus();
        
        // Add event listeners
        attachEventListeners();
    }

    // Create floating bell button
    function createBellButton() {
        bellButton = document.createElement('button');
        bellButton.className = 'notification-bell-btn';
        bellButton.setAttribute('aria-label', 'Subscribe to notifications');
        bellButton.innerHTML = `
            <i class="fas fa-bell"></i>
            <span class="bell-badge"></span>
        `;
        document.body.appendChild(bellButton);
    }

    // Create notification popup
    function createPopup() {
        popupOverlay = document.createElement('div');
        popupOverlay.className = 'notification-popup-overlay';
        popupOverlay.innerHTML = `
            <div class="notification-popup">
                <button class="notification-popup-close" aria-label="Close">
                    <i class="fas fa-times"></i>
                </button>
                
                <div class="notification-popup-icon">
                    <i class="fas fa-bell"></i>
                </div>
                
                <h3>Stay Updated!</h3>
                <p>Get instant notifications about new coupons, exclusive deals, and special offers from your favorite stores.</p>
                
                <div class="notification-popup-benefits">
                    <div class="notification-popup-benefit">
                        <i class="fas fa-check-circle"></i>
                        <span>Instant alerts for new deals</span>
                    </div>
                    <div class="notification-popup-benefit">
                        <i class="fas fa-check-circle"></i>
                        <span>Exclusive coupon codes</span>
                    </div>
                    <div class="notification-popup-benefit">
                        <i class="fas fa-check-circle"></i>
                        <span>Never miss a discount</span>
                    </div>
                </div>
                
                <div class="notification-popup-actions">
                    <button class="notification-popup-btn notification-popup-btn-primary" id="notificationSubscribeBtn">
                        <i class="fas fa-bell"></i>
                        <span>Enable Notifications</span>
                    </button>
                    <button class="notification-popup-btn notification-popup-btn-secondary" id="notificationCancelBtn">
                        <span>Maybe Later</span>
                    </button>
                </div>
            </div>
        `;
        document.body.appendChild(popupOverlay);
    }

    // Check if user is already subscribed
    async function checkSubscriptionStatus() {
        if (!window.OneSignalInstance) {
            // Wait for OneSignal to initialize
            setTimeout(checkSubscriptionStatus, 1000);
            return;
        }

        try {
            const isPushEnabled = await window.OneSignalInstance.User.PushSubscription.optedIn;
            updateBellState(isPushEnabled);
        } catch (error) {
            // OneSignal not ready yet
        }
    }

    // Update bell button state
    function updateBellState(subscribed) {
        isSubscribed = subscribed;
        
        if (subscribed) {
            bellButton.classList.add('subscribed');
            bellButton.setAttribute('aria-label', 'Notifications enabled');
        } else {
            bellButton.classList.remove('subscribed');
            bellButton.setAttribute('aria-label', 'Subscribe to notifications');
        }
    }

    // Attach event listeners
    function attachEventListeners() {
        // Bell button click
        bellButton.addEventListener('click', function() {
            if (isSubscribed) {
                showSubscribedMessage();
            } else {
                showPopup();
            }
        });

        // Close popup on overlay click
        popupOverlay.addEventListener('click', function(e) {
            if (e.target === popupOverlay) {
                hidePopup();
            }
        });

        // Close button
        const closeBtn = popupOverlay.querySelector('.notification-popup-close');
        closeBtn.addEventListener('click', hidePopup);

        // Subscribe button
        const subscribeBtn = document.getElementById('notificationSubscribeBtn');
        subscribeBtn.addEventListener('click', handleSubscribe);

        // Cancel button
        const cancelBtn = document.getElementById('notificationCancelBtn');
        cancelBtn.addEventListener('click', hidePopup);

        // Listen for subscription changes
        if (window.OneSignalInstance) {
            window.OneSignalInstance.User.PushSubscription.addEventListener('change', function(event) {
                if (event.current.optedIn) {
                    updateBellState(true);
                }
            });
        }
    }

    // Show popup
    function showPopup() {
        popupOverlay.classList.add('active');
        document.body.style.overflow = 'hidden';
    }

    // Hide popup
    function hidePopup() {
        popupOverlay.classList.remove('active');
        document.body.style.overflow = '';
    }

    // Handle subscription
    async function handleSubscribe() {
        if (!window.OneSignalInstance) {
            // OneSignal not initialized - hide popup and show friendly message
            hidePopup();
            
            const notification = document.createElement('div');
            notification.className = 'push-notification push-notification-warning';
            notification.innerHTML = `
                <div class="push-notification-content">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span>Notifications are being set up. Please try again in a moment.</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            setTimeout(() => notification.classList.add('show'), 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => notification.remove(), 300);
            }, 4000);
            
            // Try to check again after a delay
            setTimeout(checkSubscriptionStatus, 2000);
            return;
        }

        const subscribeBtn = document.getElementById('notificationSubscribeBtn');
        const btnText = subscribeBtn.querySelector('span');
        const btnIcon = subscribeBtn.querySelector('i');
        
        // Show loading state
        subscribeBtn.classList.add('loading');
        btnIcon.className = 'fas fa-spinner fa-spin';
        btnText.textContent = 'Enabling...';
        subscribeBtn.disabled = true;

        try {
            // Prompt for push notification permission
            await window.OneSignalInstance.Slidedown.promptPush();
            
            // Check if permission was granted
            const isPushEnabled = await window.OneSignalInstance.User.PushSubscription.optedIn;
            
            if (isPushEnabled) {
                // Success!
                showSuccessState();
                updateBellState(true);
                
                // Hide popup after 2 seconds
                setTimeout(hidePopup, 2000);
            } else {
                // User denied permission
                resetSubscribeButton();
                hidePopup();
                
                const notification = document.createElement('div');
                notification.className = 'push-notification push-notification-info';
                notification.innerHTML = `
                    <div class="push-notification-content">
                        <i class="fas fa-info-circle"></i>
                        <span>Please allow notifications in your browser to receive updates.</span>
                    </div>
                `;
                
                document.body.appendChild(notification);
                setTimeout(() => notification.classList.add('show'), 100);
                
                setTimeout(() => {
                    notification.classList.remove('show');
                    setTimeout(() => notification.remove(), 300);
                }, 4000);
            }
        } catch (error) {
            console.error('Error subscribing to notifications:', error);
            resetSubscribeButton();
            hidePopup();
            
            const notification = document.createElement('div');
            notification.className = 'push-notification push-notification-error';
            notification.innerHTML = `
                <div class="push-notification-content">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>Unable to enable notifications. Please try again later.</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            setTimeout(() => notification.classList.add('show'), 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => notification.remove(), 300);
            }, 4000);
        }
    }

    // Show success state
    function showSuccessState() {
        const popup = popupOverlay.querySelector('.notification-popup');
        const icon = popup.querySelector('.notification-popup-icon i');
        const title = popup.querySelector('h3');
        const description = popup.querySelector('p');
        const subscribeBtn = document.getElementById('notificationSubscribeBtn');
        
        popup.classList.add('success');
        icon.className = 'fas fa-check-circle';
        title.textContent = 'You\'re All Set!';
        description.textContent = 'You\'ll now receive notifications about new deals and exclusive offers.';
        
        subscribeBtn.classList.remove('loading');
        subscribeBtn.querySelector('i').className = 'fas fa-check';
        subscribeBtn.querySelector('span').textContent = 'Subscribed';
    }

    // Reset subscribe button
    function resetSubscribeButton() {
        const subscribeBtn = document.getElementById('notificationSubscribeBtn');
        subscribeBtn.classList.remove('loading');
        subscribeBtn.disabled = false;
        subscribeBtn.querySelector('i').className = 'fas fa-bell';
        subscribeBtn.querySelector('span').textContent = 'Enable Notifications';
    }

    // Show already subscribed message
    function showSubscribedMessage() {
        const notification = document.createElement('div');
        notification.className = 'push-notification push-notification-success';
        notification.innerHTML = `
            <div class="push-notification-content">
                <i class="fas fa-check-circle"></i>
                <span>You're already subscribed to notifications! 🔔</span>
            </div>
        `;
        
        document.body.appendChild(notification);
        setTimeout(() => notification.classList.add('show'), 100);
        
        setTimeout(() => {
            notification.classList.remove('show');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    // Auto-show popup for first-time visitors (optional)
    function autoShowPopup() {
        // Check if user has seen the popup before
        const hasSeenPopup = localStorage.getItem('notification_popup_seen');
        const isSubscribed = localStorage.getItem('onesignal_player_id');
        
        if (!hasSeenPopup && !isSubscribed) {
            // Show popup after 10 seconds
            setTimeout(function() {
                showPopup();
                localStorage.setItem('notification_popup_seen', 'true');
            }, 10000);
        }
    }

    // Initialize when DOM is ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            initNotificationBell();
            // Uncomment to enable auto-popup
            // autoShowPopup();
        });
    } else {
        initNotificationBell();
        // Uncomment to enable auto-popup
        // autoShowPopup();
    }

})();
