/**
 * Push Notification System with OneSignal
 * Handles store following and push notification subscriptions
 */

// Make OneSignalInstance globally accessible for notification bell
window.OneSignalInstance = null;
let currentPlayerId = null;

// Initialize OneSignal
function initializePushNotifications(appId, safariWebId) {
    if (!appId) {
        console.error('OneSignal App ID not provided');
        return;
    }

    window.OneSignalDeferred = window.OneSignalDeferred || [];
    
    OneSignalDeferred.push(async function(OneSignal) {
        try {
            // Make OneSignal globally accessible
            window.OneSignalInstance = OneSignal;
            
            await OneSignal.init({
                appId: appId,
                safari_web_id: safariWebId || undefined,
                notifyButton: {
                    enable: false, // We'll use custom bell buttons
                },
                allowLocalhostAsSecureOrigin: true,
                autoResubscribe: true,
                promptOptions: {
                    slidedown: {
                        enabled: true,
                        actionMessage: "Get notified when your favorite stores add new coupons and deals!",
                        acceptButtonText: "Allow",
                        cancelButtonText: "No Thanks"
                    }
                }
            });

            // Get player ID when available
            OneSignal.User.PushSubscription.addEventListener('change', function(event) {
                if (event.current.id) {
                    currentPlayerId = event.current.id;
                    localStorage.setItem('onesignal_player_id', currentPlayerId);
                    
                    // Update all follow buttons
                    updateAllFollowButtons();
                }
            });

            // Check if already subscribed
            const isPushEnabled = await OneSignal.User.PushSubscription.optedIn;
            
            if (isPushEnabled) {
                currentPlayerId = OneSignal.User.PushSubscription.id;
                if (currentPlayerId) {
                    localStorage.setItem('onesignal_player_id', currentPlayerId);
                    updateAllFollowButtons();
                }
            }
        } catch (error) {
            console.error('Error initializing OneSignal:', error);
        }
    });
}

// Follow/Unfollow store
async function toggleStoreFollow(storeId, storeName) {
    // Check if OneSignal is initialized
    if (!window.OneSignalInstance) {
        console.error('OneSignal not initialized');
        showNotification('Initializing notifications... Please try again in a moment.', 'warning');
        
        // Try to initialize if config exists
        const pushConfig = window.PUSH_NOTIFICATION_CONFIG;
        if (pushConfig && pushConfig.enabled && pushConfig.appId) {
            setTimeout(() => {
                showNotification('Please try following the store again', 'info');
            }, 2000);
        }
        return;
    }

    // Check if user is subscribed
    let isPushEnabled = false;
    try {
        isPushEnabled = await window.OneSignalInstance.User.PushSubscription.optedIn;
    } catch (error) {
        console.error('Error checking push subscription:', error);
    }
    
    if (!isPushEnabled) {
        // Prompt for notification permission
        showNotification('Please allow notifications to follow stores', 'info');
        try {
            await window.OneSignalInstance.Slidedown.promptPush();
        } catch (error) {
            console.error('Error prompting for push:', error);
            showNotification('Unable to request notification permission. Please check your browser settings.', 'error');
        }
        return;
    }

    // Get player ID
    let playerId = currentPlayerId || localStorage.getItem('onesignal_player_id');
    
    if (!playerId) {
        playerId = window.OneSignalInstance.User.PushSubscription.id;
        if (playerId) {
            currentPlayerId = playerId;
            localStorage.setItem('onesignal_player_id', playerId);
        } else {
            showNotification('Unable to get subscription ID. Please try again.', 'error');
            return;
        }
    }

    // Check current follow status
    const followBtn = document.querySelector(`[data-store-id="${storeId}"]`);
    const isFollowing = followBtn?.classList.contains('following');
    const action = isFollowing ? 'unfollow' : 'follow';

    // Show loading state
    if (followBtn) {
        followBtn.disabled = true;
        followBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
    }

    try {
        const response = await fetch(SITEURL + '/api_follow_store.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: action,
                store_id: storeId,
                player_id: playerId,
                device_type: getDeviceType()
            })
        });

        const data = await response.json();

        if (data.success) {
            // Update button state
            updateFollowButton(storeId, data.following);
            
            // Add tag to OneSignal for targeted notifications
            if (data.following) {
                await window.OneSignalInstance.User.addTag('store_' + storeId, 'true');
                showNotification(`You're now following ${storeName}! 🔔`, 'success');
            } else {
                await window.OneSignalInstance.User.removeTag('store_' + storeId);
                showNotification(`Unfollowed ${storeName}`, 'info');
            }
        } else {
            showNotification(data.message || 'An error occurred', 'error');
            if (followBtn) {
                followBtn.disabled = false;
                updateFollowButton(storeId, isFollowing);
            }
        }
    } catch (error) {
        showNotification('Network error. Please try again.', 'error');
        if (followBtn) {
            followBtn.disabled = false;
            updateFollowButton(storeId, isFollowing);
        }
    }
}

// Update follow button state
function updateFollowButton(storeId, isFollowing) {
    const followBtn = document.querySelector(`[data-store-id="${storeId}"]`);
    if (!followBtn) return;

    followBtn.disabled = false;

    if (isFollowing) {
        followBtn.classList.add('following');
        followBtn.innerHTML = '<i class="fas fa-bell"></i> Following';
        followBtn.title = 'Click to unfollow';
    } else {
        followBtn.classList.remove('following');
        followBtn.innerHTML = '<i class="far fa-bell"></i> Follow';
        followBtn.title = 'Get notified of new deals';
    }
}

// Check follow status for all stores on page
async function updateAllFollowButtons() {
    const playerId = currentPlayerId || localStorage.getItem('onesignal_player_id');
    if (!playerId) return;

    const followButtons = document.querySelectorAll('.follow-store-btn');
    
    for (const btn of followButtons) {
        const storeId = btn.getAttribute('data-store-id');
        if (!storeId) continue;

        try {
            const response = await fetch(SITEURL + '/api_follow_store.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'check',
                    store_id: storeId,
                    player_id: playerId
                })
            });

            const data = await response.json();
            if (data.success) {
                updateFollowButton(storeId, data.following);
            }
        } catch (error) {
            // Silent error handling
        }
    }
}

// Get device type
function getDeviceType() {
    const ua = navigator.userAgent;
    if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
        return 'tablet';
    }
    if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
        return 'mobile';
    }
    return 'desktop';
}

// Show notification message
function showNotification(message, type = 'info') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = `push-notification push-notification-${type}`;
    notification.innerHTML = `
        <div class="push-notification-content">
            <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
            <span>${message}</span>
        </div>
    `;

    document.body.appendChild(notification);

    // Show notification
    setTimeout(() => notification.classList.add('show'), 100);

    // Hide and remove after 4 seconds
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => notification.remove(), 300);
    }, 4000);
}

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    // Get OneSignal config from page
    const pushConfig = window.PUSH_NOTIFICATION_CONFIG;
    
    if (pushConfig && pushConfig.enabled && pushConfig.appId) {
        // Load OneSignal SDK
        const script = document.createElement('script');
        script.src = 'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js';
        script.defer = true;
        
        script.onerror = function() {
            console.error('Failed to load OneSignal SDK');
        };
        
        script.onload = function() {
            initializePushNotifications(pushConfig.appId, pushConfig.safariWebId);
        };
        
        document.head.appendChild(script);
    }

    // Add click handlers to follow buttons
    document.addEventListener('click', function(e) {
        if (e.target.closest('.follow-store-btn')) {
            e.preventDefault();
            const btn = e.target.closest('.follow-store-btn');
            const storeId = btn.getAttribute('data-store-id');
            const storeName = btn.getAttribute('data-store-name');
            
            if (storeId && storeName) {
                toggleStoreFollow(storeId, storeName);
            }
        }
    });
});
