/**
 * VMP Fence Toast Notification System
 * Standalone notification handler
 * 
 * @package VMPFence
 * @since 2.1.0
 */

(function(window, $) {
    'use strict';

    /**
     * Toast Notification System
     */
    window.VMPFenceNotifications = {
        
        /**
         * Configuration
         */
        config: {
            duration: 4000,           // Default duration in milliseconds
            maxToasts: 5,             // Maximum number of toasts to show at once
            position: 'top-right',    // Position of toast container
            pauseOnHover: true,       // Pause auto-dismiss on hover
            showProgressBar: true,    // Show progress bar
            enableSounds: false       // Enable notification sounds (future feature)
        },

        /**
         * Internal state
         */
        toasts: [],
        toastCounter: 0,
        confirmResolve: null,
        
        /**
         * Initialize notification system
         */
        init: function() {
            var self = this;
            
            // Create toast container if it doesn't exist
            if ($('#vmpfence-toast-container').length === 0) {
                $('body').append('<div id="vmpfence-toast-container" style="display: flex !important; flex-direction: column !important; gap: 12px !important;"></div>');
            } else {
                // Ensure existing container has correct styles
                $('#vmpfence-toast-container').css({
                    'display': 'flex',
                    'flex-direction': 'column',
                    'gap': '12px'
                });
            }
            
            // Create confirm modal if it doesn't exist
            if ($('#vmpfence-confirm-modal').length === 0) {
                var modalHTML = '<div id="vmpfence-confirm-modal" class="vmpfence-notification-modal" style="display:none;">' +
                    '<div class="vmpfence-notification-modal-overlay"></div>' +
                    '<div class="vmpfence-notification-modal-content">' +
                        '<div class="vmpfence-notification-modal-header">' +
                            '<span class="vmpfence-notification-modal-icon"></span>' +
                            '<h3 class="vmpfence-notification-modal-title"></h3>' +
                        '</div>' +
                        '<div class="vmpfence-notification-modal-body">' +
                            '<p class="vmpfence-notification-modal-message"></p>' +
                        '</div>' +
                        '<div class="vmpfence-notification-modal-footer">' +
                            '<button type="button" class="vmpfence-notification-modal-btn vmpfence-notification-modal-btn-cancel"></button>' +
                            '<button type="button" class="vmpfence-notification-modal-btn vmpfence-notification-modal-btn-confirm"></button>' +
                        '</div>' +
                    '</div>' +
                '</div>';
                $('body').append(modalHTML);
            }
            
            // Handle keyboard events for modal
            $(document).on('keydown', function(e) {
                var $modal = $('#vmpfence-confirm-modal');
                if ($modal.hasClass('show')) {
                    // ESC key - cancel
                    if (e.key === 'Escape' || e.keyCode === 27) {
                        e.preventDefault();
                        self.hideConfirmModal(false);
                    }
                    // Enter key - confirm
                    if (e.key === 'Enter' || e.keyCode === 13) {
                        var $confirmBtn = $modal.find('.vmpfence-notification-modal-btn-confirm');
                        if (!$confirmBtn.is(':focus')) {
                            e.preventDefault();
                            self.hideConfirmModal(true);
                        }
                    }
                }
            });
            
            // console.log('VMPFence Notifications: Initialized');
        },

        /**
         * Show toast notification
         * @param {string} message - Toast message
         * @param {string} type - Type: success, error, warning, info
         * @param {number} duration - Duration in ms (optional)
         * @param {string} title - Toast title (optional)
         */
        showToast: function(message, type, duration, title) {
            var self = this;
            
            // Validate type
            type = type || 'info';
            if (!['success', 'error', 'warning', 'info'].includes(type)) {
                type = 'info';
            }
            
            // Set duration
            duration = duration || this.config.duration;
            
            // Limit number of toasts
            if (this.toasts.length >= this.config.maxToasts) {
                this.removeToast(this.toasts[0]);
            }
            
            // Create unique ID
            var toastId = 'toast-' + (++this.toastCounter);
            
            // Create toast element
            var $toast = this.createToast(toastId, message, type, title);
            
            // Add to container
            $('#vmpfence-toast-container').append($toast);
            
            // Track toast
            var toastData = {
                id: toastId,
                element: $toast,
                timeout: null,
                pauseTimeout: null,
                remaining: duration
            };
            this.toasts.push(toastData);
            
            // Trigger show animation
            setTimeout(function() {
                $toast.addClass('show');
            }, 10);
            
            // Setup auto-dismiss
            if (duration > 0) {
                this.setupAutoDismiss(toastData, duration);
            }
            
            return toastId;
        },

        /**
         * Create toast HTML element
         */
        createToast: function(id, message, type, title) {
            var self = this;
            
            // Icon mapping
            var icons = {
                success: '✓',
                error: '✕',
                warning: '⚠',
                info: 'ℹ'
            };
            
            // Default titles
            var defaultTitles = {
                success: 'Success',
                error: 'Error',
                warning: 'Warning',
                info: 'Information'
            };
            
            title = title || defaultTitles[type];
            
            var $toast = $('<div>', {
                'id': id,
                'class': 'vmpfence-toast ' + type,
                'role': 'alert',
                'aria-live': type === 'error' ? 'assertive' : 'polite'
            });
            
            // Icon
            var $icon = $('<div>', {
                'class': 'vmpfence-toast-icon',
                'html': icons[type]
            });
            
            // Content
            var $content = $('<div>', {
                'class': 'vmpfence-toast-content'
            });
            
            if (title) {
                $content.append($('<div>', {
                    'class': 'vmpfence-toast-title',
                    'text': title
                }));
            }
            
            $content.append($('<div>', {
                'class': 'vmpfence-toast-message',
                'text': message
            }));
            
            // Close button
            var $close = $('<button>', {
                'class': 'vmpfence-toast-close',
                'html': '×',
                'title': 'Close',
                'aria-label': 'Close notification'
            }).on('click', function() {
                self.removeToast(id);
            });
            
            // Progress bar
            var $progress = null;
            if (this.config.showProgressBar) {
                $progress = $('<div>', {
                    'class': 'vmpfence-toast-progress'
                });
            }
            
            // Assemble toast
            $toast.append($icon).append($content).append($close);
            if ($progress) {
                $toast.append($progress);
            }
            
            // Pause on hover
            if (this.config.pauseOnHover) {
                $toast.on('mouseenter', function() {
                    self.pauseToast(id);
                }).on('mouseleave', function() {
                    self.resumeToast(id);
                });
            }
            
            return $toast;
        },

        /**
         * Setup auto-dismiss for toast
         */
        setupAutoDismiss: function(toastData, duration) {
            var self = this;
            var startTime = Date.now();
            
            // Progress bar animation
            if (this.config.showProgressBar) {
                var $progress = toastData.element.find('.vmpfence-toast-progress');
                $progress.css({
                    'width': '100%',
                    'transition-duration': duration + 'ms'
                });
                setTimeout(function() {
                    $progress.css('width', '0%');
                }, 10);
            }
            
            // Auto-dismiss timeout
            toastData.timeout = setTimeout(function() {
                self.removeToast(toastData.id);
            }, duration);
            
            toastData.startTime = startTime;
        },

        /**
         * Pause toast auto-dismiss
         */
        pauseToast: function(toastId) {
            var toast = this.toasts.find(function(t) { return t.id === toastId; });
            if (!toast || !toast.timeout) return;
            
            clearTimeout(toast.timeout);
            toast.remaining = toast.remaining - (Date.now() - toast.startTime);
            
            // Pause progress bar
            if (this.config.showProgressBar) {
                var $progress = toast.element.find('.vmpfence-toast-progress');
                var currentWidth = $progress.css('width');
                $progress.css({
                    'width': currentWidth,
                    'transition': 'none'
                });
            }
        },

        /**
         * Resume toast auto-dismiss
         */
        resumeToast: function(toastId) {
            var toast = this.toasts.find(function(t) { return t.id === toastId; });
            if (!toast) return;
            
            var self = this;
            toast.startTime = Date.now();
            
            // Resume progress bar
            if (this.config.showProgressBar) {
                var $progress = toast.element.find('.vmpfence-toast-progress');
                $progress.css({
                    'transition-duration': toast.remaining + 'ms'
                });
                setTimeout(function() {
                    $progress.css('width', '0%');
                }, 10);
            }
            
            // Resume timeout
            toast.timeout = setTimeout(function() {
                self.removeToast(toast.id);
            }, toast.remaining);
        },

        /**
         * Remove toast
         */
        removeToast: function(toastId) {
            var toastIndex = this.toasts.findIndex(function(t) {
                return t.id === toastId || (t.element && t.element.attr('id') === toastId);
            });
            
            if (toastIndex === -1) return;
            
            var toast = this.toasts[toastIndex];
            
            // Clear timeout
            if (toast.timeout) {
                clearTimeout(toast.timeout);
            }
            
            // Hide animation
            toast.element.removeClass('show').addClass('hide');
            
            // Remove from DOM after animation
            setTimeout(function() {
                toast.element.remove();
            }, 300);
            
            // Remove from array
            this.toasts.splice(toastIndex, 1);
        },

        /**
         * Show success toast
         */
        showSuccess: function(message, duration, title) {
            return this.showToast(message, 'success', duration, title);
        },

        /**
         * Show error toast
         */
        showError: function(message, duration, title) {
            return this.showToast(message, 'error', duration || 6000, title);
        },

        /**
         * Show warning toast
         */
        showWarning: function(message, duration, title) {
            return this.showToast(message, 'warning', duration || 5000, title);
        },

        /**
         * Show info toast
         */
        showInfo: function(message, duration, title) {
            return this.showToast(message, 'info', duration, title);
        },

        /**
         * Show confirmation modal
         * @param {object} options - Modal options
         * @returns {Promise} - Resolves with true (confirmed) or false (cancelled)
         */
        showConfirmModal: function(options) {
            var self = this;
            
            // Default options
            var defaults = {
                title: 'Confirm Action',
                message: 'Are you sure you want to proceed?',
                confirmText: 'Confirm',
                cancelText: 'Cancel',
                type: 'info', // info, warning, danger
                showIcon: true
            };
            
            options = $.extend({}, defaults, options);
            
            return new Promise(function(resolve) {
                self.confirmResolve = resolve;
                
                // Get or create modal
                var $modal = $('#vmpfence-confirm-modal');
                
                // Icon mapping
                var icons = {
                    info: 'ℹ',
                    warning: '⚠',
                    danger: '⚠'
                };
                
                // Update modal content
                $modal.removeClass('info warning danger').addClass(options.type);
                
                if (options.showIcon) {
                    $modal.find('.vmpfence-notification-modal-icon').html(icons[options.type]).show();
                } else {
                    $modal.find('.vmpfence-notification-modal-icon').hide();
                }
                
                $modal.find('.vmpfence-notification-modal-title').text(options.title);
                $modal.find('.vmpfence-notification-modal-message').text(options.message);
                $modal.find('.vmpfence-notification-modal-btn-confirm').text(options.confirmText);
                $modal.find('.vmpfence-notification-modal-btn-cancel').text(options.cancelText);
                
                // Show modal
                $modal.show().addClass('show');
                
                // Focus confirm button
                setTimeout(function() {
                    $modal.find('.vmpfence-notification-modal-btn-confirm').focus();
                }, 100);
            });
        },

        /**
         * Hide confirmation modal
         */
        hideConfirmModal: function(confirmed) {
            var self = this;
            var $modal = $('#vmpfence-confirm-modal');
            $modal.removeClass('show');
            
            // Wait for animation then hide
            setTimeout(function() {
                $modal.hide();
            }, 200);
            
            if (this.confirmResolve) {
                this.confirmResolve(confirmed === true);
                this.confirmResolve = null;
            }
        },

        /**
         * Clear all toasts
         */
        clearAll: function() {
            var self = this;
            this.toasts.forEach(function(toast) {
                self.removeToast(toast.id);
            });
        }
    };

    /**
     * Initialize on DOM ready
     */
    $(document).ready(function() {
        VMPFenceNotifications.init();
        
        // Setup modal event handlers
        var $modal = $('#vmpfence-confirm-modal');
        
        // Confirm button
        $modal.on('click', '.vmpfence-notification-modal-btn-confirm', function() {
            VMPFenceNotifications.hideConfirmModal(true);
        });
        
        // Cancel button
        $modal.on('click', '.vmpfence-notification-modal-btn-cancel', function() {
            VMPFenceNotifications.hideConfirmModal(false);
        });
        
        // Click overlay to cancel
        $modal.on('click', '.vmpfence-notification-modal-overlay', function() {
            VMPFenceNotifications.hideConfirmModal(false);
        });
        
        // Prevent clicks inside modal from closing
        $modal.on('click', '.vmpfence-notification-modal-content', function(e) {
            e.stopPropagation();
        });
    });

})(window, jQuery);
