/**
 * Custom Schema by SCHEMAFY - Toast Notifications
 * Version: 1.0.0
 * Stackable toast notification system
 */

(function() {
    'use strict';

    window.SCHEMAFY = window.SCHEMAFY || {};

    // Notification queue
    var notificationQueue = [];
    var $container = null;

    /**
     * Initialize notification system
     */
    function initNotificationSystem() {
        if ($container) return;

        // Create notification container
        $container = jQuery('<div class="schemafy-notifications-container"></div>');
        jQuery('body').append($container);

    }

    /**
     * Show a toast notification
     * @param {string} message - Notification message
     * @param {string} type - Type: success, error, warning, info
     * @param {number} duration - Duration in ms (0 = persistent)
     */
    window.SCHEMAFY.showNotification = function(message, type, duration) {
        initNotificationSystem();

        type = type || 'info';
        duration = typeof duration !== 'undefined' ? duration : 4000;

        // Create notification element
        var notificationId = 'schemafy-notification-' + Date.now();
        var icon = getIconForType(type);

        var $notification = jQuery('<div class="schemafy-notification schemafy-notification-' + type + '" id="' + notificationId + '"></div>');

        $notification.html(
            '<div class="schemafy-notification-icon">' + icon + '</div>' +
            '<div class="schemafy-notification-message"></div>' +
            '<button class="schemafy-notification-close" type="button">×</button>'
        );

        // Message goes in as text: it quotes user-controlled values (schema
        // property names, URLs, server errors) and jQuery runs markup it is
        // given. No caller passes HTML.
        $notification.find('.schemafy-notification-message').text(message);

        // Add to container
        $container.append($notification);

        // Add to queue
        notificationQueue.push({
            id: notificationId,
            $element: $notification,
            timeout: null
        });

        // Animate in
        setTimeout(function() {
            $notification.addClass('schemafy-notification-show');
        }, 10);

        // Auto-dismiss if duration > 0
        if (duration > 0) {
            var timeoutId = setTimeout(function() {
                dismissNotification(notificationId);
            }, duration);

            // Store timeout ID
            var notification = notificationQueue.find(function(n) { return n.id === notificationId; });
            if (notification) {
                notification.timeout = timeoutId;
            }
        }

        // Close button handler
        $notification.find('.schemafy-notification-close').on('click', function(e) {
            e.preventDefault();
            dismissNotification(notificationId);
        });

        return notificationId;
    };

    /**
     * Dismiss a notification
     * @param {string} notificationId - ID of notification to dismiss
     */
    function dismissNotification(notificationId) {
        var notification = notificationQueue.find(function(n) { return n.id === notificationId; });
        if (!notification) return;

        // Clear timeout if exists
        if (notification.timeout) {
            clearTimeout(notification.timeout);
        }

        // Animate out
        notification.$element.removeClass('schemafy-notification-show');

        // Remove from DOM after animation
        setTimeout(function() {
            notification.$element.remove();

            // Remove from queue
            notificationQueue = notificationQueue.filter(function(n) {
                return n.id !== notificationId;
            });
        }, 300);
    }

    /**
     * Clear all notifications
     */
    window.SCHEMAFY.clearAllNotifications = function() {
        notificationQueue.forEach(function(notification) {
            dismissNotification(notification.id);
        });
    };

    /**
     * Get icon for notification type
     */
    function getIconForType(type) {
        var icons = {
            'success': '✓',
            'error': '✕',
            'warning': '⚠',
            'info': 'ℹ'
        };
        return icons[type] || icons['info'];
    }

    /**
     * Shorthand methods for common notification types
     */
    window.SCHEMAFY.showSuccess = function(message, duration) {
        return window.SCHEMAFY.showNotification(message, 'success', duration);
    };

    window.SCHEMAFY.showError = function(message, duration) {
        return window.SCHEMAFY.showNotification(message, 'error', duration);
    };

    window.SCHEMAFY.showWarning = function(message, duration) {
        return window.SCHEMAFY.showNotification(message, 'warning', duration);
    };

    window.SCHEMAFY.showInfo = function(message, duration) {
        return window.SCHEMAFY.showNotification(message, 'info', duration);
    };

    /**
     * Confirm dialog (promise-based)
     * @param {string} message - Confirmation message
     * @param {object} options - Options (confirmText, cancelText)
     * @returns {Promise}
     */
    window.SCHEMAFY.confirm = function(message, options) {
        return new Promise(function(resolve, reject) {
            initNotificationSystem();

            var i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
            var settings = jQuery.extend({
                confirmText: i18n.confirm_label || 'Confirm',
                cancelText: i18n.cancel_label || 'Cancel',
                type: 'warning'
            }, options);

            var dialogId = 'schemafy-dialog-' + Date.now();

            var $dialog = jQuery('<div class="schemafy-notification schemafy-notification-dialog schemafy-notification-' + settings.type + '" id="' + dialogId + '"></div>');

            $dialog.html(
                '<div class="schemafy-notification-message"></div>' +
                '<div class="schemafy-notification-actions">' +
                    '<button class="schemafy-btn-secondary schemafy-dialog-cancel" type="button"></button>' +
                    '<button class="schemafy-btn-primary schemafy-dialog-confirm" type="button"></button>' +
                '</div>'
            );

            // Same reason as showNotification: confirmations quote schema names
            // and URLs the user supplied, so they go in as text.
            $dialog.find('.schemafy-notification-message').text(message);
            $dialog.find('.schemafy-dialog-cancel').text(settings.cancelText);
            $dialog.find('.schemafy-dialog-confirm').text(settings.confirmText);

            // Add to container
            $container.append($dialog);

            // Animate in
            setTimeout(function() {
                $dialog.addClass('schemafy-notification-show');
            }, 10);

            // Confirm handler
            $dialog.find('.schemafy-dialog-confirm').on('click', function(e) {
                e.preventDefault();
                closeDialog();
                resolve(true);
            });

            // Cancel handler
            $dialog.find('.schemafy-dialog-cancel').on('click', function(e) {
                e.preventDefault();
                closeDialog();
                resolve(false);
            });

            // Close dialog
            function closeDialog() {
                $dialog.removeClass('schemafy-notification-show');
                setTimeout(function() {
                    $dialog.remove();
                }, 300);
            }
        });
    };

    /**
     * Loading notification (persistent until dismissed)
     * @param {string} message - Loading message
     * @returns {string} notificationId
     */
    window.SCHEMAFY.showLoading = function(message) {
        initNotificationSystem();

        var i18nLoad = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
        message = message || i18nLoad.loading_label || 'Loading...';

        var notificationId = 'schemafy-loading-' + Date.now();

        var $notification = jQuery('<div class="schemafy-notification schemafy-notification-loading" id="' + notificationId + '"></div>');

        $notification.html(
            '<div class="schemafy-notification-spinner"></div>' +
            '<div class="schemafy-notification-message">' + message + '</div>'
        );

        // Add to container
        $container.append($notification);

        // Animate in
        setTimeout(function() {
            $notification.addClass('schemafy-notification-show');
        }, 10);

        // Add to queue
        notificationQueue.push({
            id: notificationId,
            $element: $notification,
            timeout: null
        });

        return notificationId;
    };

    /**
     * Dismiss loading notification
     * @param {string} notificationId - ID returned by showLoading
     */
    window.SCHEMAFY.hideLoading = function(notificationId) {
        dismissNotification(notificationId);
    };

})();
