/**
 * Biscotti CMP - Admin Shell JavaScript
 * 
 * Handles dynamic view initialization, toast notifications,
 * and generic API proxy calls for the Cloud-Bridge plugin.
 * 
 * @package Biscotti_CMP
 * @since 3.0.0
 */

(function($) {
    'use strict';

    var BiscottiAdmin = {
        config: window.biscottiAdmin || {},

        init: function() {
            this.bindEvents();
            this.initDynamicView();
        },

        bindEvents: function() {
            // Clear cache button
            $(document).on('click', '.biscotti-clear-cache', function(e) {
                e.preventDefault();
                BiscottiAdmin.clearCache($(this));
            });

            // Generic save form buttons (data-biscotti-save="action" data-biscotti-form="#form-id")
            $(document).on('click', '[data-biscotti-save]', function(e) {
                e.preventDefault();
                var $btn = $(this);
                var proxyAction = $btn.data('biscottiSave');
                var formSelector = $btn.data('biscottiForm');
                var formData = BiscottiAdmin.serializeForm(formSelector);
                BiscottiAdmin.saveForm(proxyAction, formData, $btn);
            });

            // Copy-to-clipboard buttons (shortcodes page and elsewhere)
            $(document).on('click', '.biscotti-copy-btn', function(e) {
                e.preventDefault();
                var $btn = $(this);
                var text = $btn.data('copy-text') || $btn.data('copyText');
                if (text) {
                    BiscottiAdmin.copyToClipboard(text, $btn);
                }
            });

            // Documents page: Generate document
            $(document).on('click', '.biscotti-generate-doc', function(e) {
                e.preventDefault();
                var $btn = $(this);
                var docType = $btn.data('docType');
                var docId = $btn.data('docId');
                var originalText = $btn.text();

                $btn.prop('disabled', true).text(BiscottiAdmin.config.i18n?.loading || '...');

                $.ajax({
                    url: BiscottiAdmin.config.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'biscotti_proxy',
                        nonce: BiscottiAdmin.config.nonce,
                        proxy_action: 'generate-document',
                        payload: JSON.stringify({ documentType: docType, type: docType, id: docId })
                    },
                    success: function(res) {
                        if (res.success) {
                            BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.saved || 'Done!');
                            location.reload();
                        } else {
                            BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                        }
                    },
                    error: function() {
                        BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text(originalText);
                    }
                });
            });

            // Documents page: View document in modal
            $(document).on('click', '.biscotti-view-doc', function(e) {
                e.preventDefault();
                var docId = $(this).data('docId');
                var docType = $(this).data('docType');
                var $modal = $('#biscotti-document-modal');
                var $content = $('#biscotti-document-content');

                // Show modal with loading state.
                $content.html('<div class="biscotti-loading"><span class="biscotti-spinner"></span></div>');
                $modal.addClass('active');

                $.ajax({
                    url: BiscottiAdmin.config.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'biscotti_proxy',
                        nonce: BiscottiAdmin.config.nonce,
                        proxy_action: 'view-document',
                        payload: JSON.stringify({ documentId: docId, id: docId, type: docType })
                    },
                    success: function(res) {
                        if (res.success && res.data && res.data.content) {
                            $content.html(res.data.content);
                        } else {
                            $content.html('<p>' + (res.data || 'Could not load document.') + '</p>');
                        }
                    },
                    error: function() {
                        $content.html('<p>' + (BiscottiAdmin.config.i18n?.connectionError || 'Connection error') + '</p>');
                    }
                });
            });

            // Documents page: Toggle publish/unpublish
            $(document).on('click', '.biscotti-toggle-doc', function(e) {
                e.preventDefault();
                var $btn = $(this);
                var docId = $btn.data('docId');
                var isPublished = $btn.data('published') === 1 || $btn.data('published') === '1';
                var originalText = $btn.text();

                $btn.prop('disabled', true).text(BiscottiAdmin.config.i18n?.loading || '...');

                $.ajax({
                    url: BiscottiAdmin.config.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'biscotti_proxy',
                        nonce: BiscottiAdmin.config.nonce,
                        proxy_action: 'toggle-document',
                        payload: JSON.stringify({ documentId: docId, id: docId, publish: !isPublished })
                    },
                    success: function(res) {
                        if (res.success) {
                            BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.saved || 'Done!');
                            location.reload();
                        } else {
                            BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                        }
                    },
                    error: function() {
                        BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                    },
                    complete: function() {
                        $btn.prop('disabled', false).text(originalText);
                    }
                });
            });

            // Modal: Close button and overlay click
            $(document).on('click', '.biscotti-modal-close, .biscotti-modal-close-btn', function(e) {
                e.preventDefault();
                $(this).closest('.biscotti-modal-overlay').removeClass('active');
            });

            $(document).on('click', '.biscotti-modal-overlay', function(e) {
                if ($(e.target).hasClass('biscotti-modal-overlay')) {
                    $(this).removeClass('active');
                }
            });

            // Modal: Close on Escape key
            $(document).on('keydown', function(e) {
                if (e.key === 'Escape') {
                    $('.biscotti-modal-overlay.active').removeClass('active');
                }
            });

            // Services page: category assignment dropdown change handler
            $(document).on('change', '.biscotti-service-category', function() {
                var $select = $(this);
                var serviceId = $select.data('serviceId');
                var newCategory = $select.val();

                $select.prop('disabled', true);

                $.ajax({
                    url: BiscottiAdmin.config.ajaxUrl,
                    method: 'POST',
                    data: {
                        action: 'biscotti_proxy',
                        nonce: BiscottiAdmin.config.nonce,
                        proxy_action: 'save-provider',
                        payload: JSON.stringify({
                            id: serviceId,
                            overrideCategory: newCategory
                        })
                    },
                    success: function(res) {
                        if (res.success) {
                            BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.saved || 'Saved!');
                            $select.data('originalCategory', newCategory);
                        } else {
                            BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                            $select.val($select.data('originalCategory'));
                        }
                    },
                    error: function() {
                        BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                        $select.val($select.data('originalCategory'));
                    },
                    complete: function() {
                        $select.prop('disabled', false);
                    }
                });
            });

            // Data Processing: Toggle create form visibility
            $(document).on('click', '#biscotti-toggle-create-form', function() {
                $('#biscotti-create-record-form-wrap').slideToggle(200);
            });

            // Data Processing: Cancel create form
            $(document).on('click', '#biscotti-cancel-create', function() {
                $('#biscotti-create-record-form-wrap').slideUp(200);
            });

            // Data Processing: Delete record with confirmation
            $(document).on('click', '.biscotti-delete-record', function(e) {
                e.preventDefault();
                var $btn = $(this);
                var recordId = $btn.data('record-id') || $btn.data('recordId');
                var recordName = $btn.data('record-name') || $btn.data('recordName');
                var confirmMsg = (BiscottiAdmin.config.i18n?.confirmDelete || 'Are you sure you want to delete this record?') + ' ' + recordName;

                BiscottiAdmin.confirmAction(confirmMsg, function() {
                    $btn.prop('disabled', true);

                    $.ajax({
                        url: BiscottiAdmin.config.ajaxUrl,
                        method: 'POST',
                        data: {
                            action: 'biscotti_proxy',
                            nonce: BiscottiAdmin.config.nonce,
                            proxy_action: 'delete-data-processing-record',
                            payload: JSON.stringify({ id: recordId })
                        },
                        success: function(res) {
                            if (res.success) {
                                BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.deleted || 'Record deleted.');
                                $btn.closest('tr').fadeOut(300, function() {
                                    $(this).remove();
                                });
                            } else {
                                BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                                $btn.prop('disabled', false);
                            }
                        },
                        error: function() {
                            BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                            $btn.prop('disabled', false);
                        }
                    });
                });
            });
        },

        /**
         * Initialize dynamic view elements after API content is injected
         */
        initDynamicView: function() {
            var $view = $('#biscotti-dynamic-view');
            if (!$view.length) return;

            // Initialize any data-driven components
            $view.find('[data-biscotti-action]').each(function() {
                var $el = $(this);
                $el.on('click', function(e) {
                    e.preventDefault();
                    var action = $el.data('biscottiAction');
                    var params = $el.data('biscottiParams') || {};
                    BiscottiAdmin.proxyAction(action, params, $el);
                });
            });
        },

        /**
         * Generic API proxy call
         */
        proxyAction: function(action, params, $trigger) {
            if ($trigger) {
                $trigger.prop('disabled', true).text(this.config.i18n?.loading || 'Loading...');
            }

            $.ajax({
                url: this.config.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'biscotti_proxy_api',
                    nonce: this.config.nonce,
                    endpoint: '/wp-plugin/proxy/' + action,
                    method: 'POST',
                    params: JSON.stringify(params)
                },
                success: function(res) {
                    if (res.success) {
                        BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.saved || 'Done!');
                    } else {
                        BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                    }
                },
                error: function() {
                    BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                },
                complete: function() {
                    if ($trigger) {
                        $trigger.prop('disabled', false).text($trigger.data('originalText') || 'Submit');
                    }
                }
            });
        },

        /**
         * Clear API response cache
         */
        clearCache: function($btn) {
            $btn.prop('disabled', true);

            $.ajax({
                url: this.config.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'biscotti_clear_cache',
                    nonce: this.config.nonce
                },
                success: function(res) {
                    if (res.success) {
                        BiscottiAdmin.showToast('success', 'Cache cleared');
                        location.reload();
                    }
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        },

        /**
         * Show a toast notification
         * @param {string} type - 'success', 'error', 'warning'
         * @param {string} message
         */
        showToast: function(type, message) {
            var existing = $('.biscotti-toast');
            if (existing.length) existing.remove();

            var colors = {
                success: { bg: '#dcfce7', border: '#22c55e', text: '#166534' },
                error:   { bg: '#fef2f2', border: '#ef4444', text: '#991b1b' },
                warning: { bg: '#fef3c7', border: '#f59e0b', text: '#92400e' }
            };
            var c = colors[type] || colors.success;

            var $toast = $('<div class="biscotti-toast"></div>')
                .css({
                    position: 'fixed',
                    top: '40px',
                    right: '20px',
                    padding: '12px 20px',
                    background: c.bg,
                    border: '1px solid ' + c.border,
                    borderRadius: '8px',
                    color: c.text,
                    fontWeight: '500',
                    zIndex: 99999,
                    boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
                    opacity: 0,
                    transition: 'opacity 0.3s'
                })
                .text(message)
                .appendTo('body');

            // Fade in
            setTimeout(function() { $toast.css('opacity', 1); }, 10);

            // Auto-dismiss after 3 seconds
            setTimeout(function() {
                $toast.css('opacity', 0);
                setTimeout(function() { $toast.remove(); }, 300);
            }, 3000);
        },

        /**
         * Generic save handler — sends form data to the Cloud API via the biscotti_proxy AJAX action.
         *
         * Uses biscottiAdmin.ajaxUrl and biscottiAdmin.nonce provided via wp_localize_script().
         *
         * @param {string} proxyAction - The proxy action name (e.g. 'save-banner', 'save-settings')
         * @param {object} formData    - Key/value object to send as JSON payload
         * @param {jQuery} $btn        - The submit button element (disabled during request)
         */
        saveForm: function(proxyAction, formData, $btn) {
            var originalText = $btn.text();
            $btn.data('label', originalText);
            $btn.prop('disabled', true).text(this.config.i18n?.saving || 'Saving...');

            $.ajax({
                url: BiscottiAdmin.config.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'biscotti_proxy',
                    nonce: BiscottiAdmin.config.nonce,
                    proxy_action: proxyAction,
                    payload: JSON.stringify(formData)
                },
                success: function(res) {
                    if (res.success) {
                        BiscottiAdmin.showToast('success', BiscottiAdmin.config.i18n?.saved || 'Saved!');
                    } else {
                        BiscottiAdmin.showToast('error', res.data || BiscottiAdmin.config.i18n?.error || 'Error');
                    }
                },
                error: function() {
                    BiscottiAdmin.showToast('error', BiscottiAdmin.config.i18n?.connectionError || 'Connection error');
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        },

        /**
         * Show or hide a loading state on a given element.
         *
         * @param {string}  selector - CSS selector for the container element
         * @param {boolean} show     - true to show loading, false to hide
         */
        loadingState: function(selector, show) {
            var $el = $(selector);
            if (!$el.length) return;

            if (show) {
                if ($el.find('.biscotti-loading').length) return;
                $el.addClass('biscotti-is-loading');
                $el.append('<div class="biscotti-loading"><span class="spinner is-active"></span></div>');
            } else {
                $el.removeClass('biscotti-is-loading');
                $el.find('.biscotti-loading').remove();
            }
        },

        /**
         * Show a confirmation dialog before executing a destructive action.
         *
         * @param {string}   message  - The confirmation message to display
         * @param {function} callback - Function to call if the user confirms
         */
        confirmAction: function(message, callback) {
            if (window.confirm(message)) {
                if (typeof callback === 'function') {
                    callback();
                }
            }
        },

        /**
         * Copy text to the clipboard and provide visual feedback on the button.
         *
         * @param {string} text - The text to copy
         * @param {jQuery} $btn - The button element (shows feedback)
         */
        copyToClipboard: function(text, $btn) {
            var originalText = $btn.text();

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(function() {
                    $btn.text(BiscottiAdmin.config.i18n?.copied || 'Copied!');
                    setTimeout(function() { $btn.text(originalText); }, 2000);
                }).catch(function() {
                    BiscottiAdmin._fallbackCopy(text, $btn, originalText);
                });
            } else {
                BiscottiAdmin._fallbackCopy(text, $btn, originalText);
            }
        },

        /**
         * Fallback clipboard copy using a temporary textarea (for older browsers).
         *
         * @param {string} text         - Text to copy
         * @param {jQuery} $btn         - Button element for feedback
         * @param {string} originalText - Original button label to restore
         * @private
         */
        _fallbackCopy: function(text, $btn, originalText) {
            var $temp = $('<textarea>').val(text).appendTo('body').select();
            try {
                document.execCommand('copy');
                $btn.text(BiscottiAdmin.config.i18n?.copied || 'Copied!');
            } catch (e) {
                $btn.text(BiscottiAdmin.config.i18n?.error || 'Error');
            }
            $temp.remove();
            setTimeout(function() { $btn.text(originalText); }, 2000);
        },

        /**
         * Serialize a form into a plain JSON object.
         * Handles text inputs, selects, textareas, checkboxes, and radio buttons.
         *
         * @param {string|jQuery} formSelector - CSS selector or jQuery object for the form
         * @return {object} Key/value pairs of form data
         */
        serializeForm: function(formSelector) {
            var $form = $(formSelector);
            var data = {};

            $form.find('input[name], select[name], textarea[name]').each(function() {
                var $field = $(this);
                var name = $field.attr('name');
                var type = ($field.attr('type') || '').toLowerCase();

                if (type === 'checkbox') {
                    data[name] = $field.is(':checked');
                } else if (type === 'radio') {
                    if ($field.is(':checked')) {
                        data[name] = $field.val();
                    }
                } else {
                    data[name] = $field.val();
                }
            });

            return data;
        }
    };

    $(document).ready(function() {
        BiscottiAdmin.init();
    });

    // Export for external JS access
    window.BiscottiAdmin = BiscottiAdmin;

})(jQuery);
