/**
 * Notifications & UI Utilities Module
 * Handles: Notifications, confirmations, common UI helpers
 */
(function($) {
    'use strict';

    window.SchemafyUtilities = {
        /**
         * Escape a value for interpolation into an HTML template literal.
         *
         * Quotes are escaped too, which is the whole point: the idiom this
         * replaces, $('<div>').text(v).html(), leaves " and ' untouched, so a
         * value containing a double quote broke out of any attribute it was
         * interpolated into (data-type="${v}") and could inject markup. Use
         * this for both text and attribute positions.
         *
         * @param {*} value - Value to escape
         * @returns {string} Escaped string, safe in text and attribute context
         */
        escapeHtml: function(value) {
            const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
            return String(value == null ? '' : value).replace(/[&<>"']/g, function(c) { return map[c]; });
        },

        /**
         * Show notification toast
         * @param {string} message - Notification message
         * @param {string} type - 'success', 'error', 'warning', 'info'
         */
        showNotification: function(message, type = 'info') {
            // Remove any existing notifications
            $('.schemafy-notification-v2').remove();

            const icons = {
                success: 'dashicons-yes-alt',
                error: 'dashicons-dismiss',
                warning: 'dashicons-warning',
                info: 'dashicons-info'
            };

            const icon = icons[type] || icons.info;

            const $notification = $(`
                <div class="schemafy-notification-v2 schemafy-notification-${type}">
                    <span class="dashicons ${icon}"></span>
                    <span class="schemafy-notification-message"></span>
                    <button class="schemafy-notification-close">&times;</button>
                </div>
            `);

            // Set as text, never interpolated into the markup above. Messages
            // quote things the user controls — schema property names, URLs,
            // server errors — and jQuery executes markup it is handed, so
            // building the element around the message made every caller a
            // potential injection. No caller passes HTML.
            $notification.find('.schemafy-notification-message').text(message);

            $('body').append($notification);

            // Animate in
            setTimeout(() => $notification.addClass('show'), 10);

            // Auto-hide after 4 seconds
            setTimeout(() => {
                $notification.removeClass('show');
                setTimeout(() => $notification.remove(), 300);
            }, 4000);

            // Close button
            $notification.find('.schemafy-notification-close').on('click', () => {
                $notification.removeClass('show');
                setTimeout(() => $notification.remove(), 300);
            });
        },

        /**
         * Show confirmation dialog
         * @param {string} message - Confirmation message
         * @param {Function} onConfirm - Callback on confirm
         * @param {Function} onCancel - Callback on cancel (optional)
         */
        confirm: function(message, onConfirm, onCancel) {
            const modalHtml = `
                <div class="schemafy-modal-overlay" id="schemafy-confirm-modal">
                    <div class="schemafy-modal-v2" style="max-width: 400px;">
                        <div class="schemafy-modal-header-v2">
                            <h3><span class="dashicons dashicons-warning"></span> Confirm Action</h3>
                            <button class="schemafy-modal-close-v2">&times;</button>
                        </div>
                        <div class="schemafy-modal-body-v2">
                            <p>${message}</p>
                        </div>
                        <div class="schemafy-modal-footer-v2">
                            <button class="schemafy-btn-secondary" id="schemafy-confirm-cancel">Cancel</button>
                            <button class="schemafy-btn-primary" id="schemafy-confirm-ok">Confirm</button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(modalHtml);

            $('#schemafy-confirm-ok').on('click', () => {
                $('#schemafy-confirm-modal').remove();
                if (typeof onConfirm === 'function') {
                    onConfirm();
                }
            });

            $('#schemafy-confirm-cancel, #schemafy-confirm-modal .schemafy-modal-close-v2').on('click', () => {
                $('#schemafy-confirm-modal').remove();
                if (typeof onCancel === 'function') {
                    onCancel();
                }
            });
        },

        /**
         * Render pagination HTML
         * @param {Object} pagination - Pagination data
         * @returns {string} HTML string
         */
        renderPagination: function(pagination) {
            // Support both 'current_page' and 'page' property names
            const current_page = pagination.current_page || pagination.page || 1;
            const total_pages = pagination.total_pages || 1;
            let html = '<div class="schemafy-pagination-v2">';

            // Previous button
            if (current_page > 1) {
                html += `<button class="schemafy-pagination-btn" data-page="${current_page - 1}">&laquo; Prev</button>`;
            }

            // Page numbers
            const startPage = Math.max(1, current_page - 2);
            const endPage = Math.min(total_pages, current_page + 2);

            if (startPage > 1) {
                html += `<button class="schemafy-pagination-btn" data-page="1">1</button>`;
                if (startPage > 2) {
                    html += '<span class="schemafy-pagination-ellipsis">...</span>';
                }
            }

            for (let i = startPage; i <= endPage; i++) {
                const activeClass = i === current_page ? 'active' : '';
                html += `<button class="schemafy-pagination-btn ${activeClass}" data-page="${i}">${i}</button>`;
            }

            if (endPage < total_pages) {
                if (endPage < total_pages - 1) {
                    html += '<span class="schemafy-pagination-ellipsis">...</span>';
                }
                html += `<button class="schemafy-pagination-btn" data-page="${total_pages}">${total_pages}</button>`;
            }

            // Next button
            if (current_page < total_pages) {
                html += `<button class="schemafy-pagination-btn" data-page="${current_page + 1}">Next &raquo;</button>`;
            }

            html += '</div>';
            return html;
        },

        /**
         * Get form data as object
         * @param {jQuery} $form - jQuery form element
         * @returns {Object} Form data object
         */
        getFormData: function($form) {
            const data = {};
            $form.serializeArray().forEach(item => {
                data[item.name] = item.value;
            });
            return data;
        },

        /**
         * Debounce utility function
         * @param {Function} func - Function to debounce
         * @param {number} wait - Milliseconds to wait
         * @returns {Function} Debounced function
         */
        debounce: function(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func.apply(this, args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        },

        /**
         * Get schema type icon
         * @param {string} type - Schema type
         * @returns {string} Icon character
         */
        getSchemaTypeIcon: function(type) {
            const icons = {
                'Article': '📰',
                'Product': '🛍️',
                'Organization': '🏢',
                'LocalBusiness': '🏪',
                'Person': '👤',
                'Event': '🎉',
                'Recipe': '🍳',
                'Review': '⭐',
                'FAQ': '❓',
                'FAQPage': '❓',
                'WebPage': '📄',
                'Course': '🎓',
                'HowTo': '🔧',
                'JobPosting': '💼',
                'Service': '🛠️',
                'Video': '🎬',
                'BreadcrumbList': '🔗'
            };
            return icons[type] || '⚙️';
        }
    };

})(jQuery);
