/**
 * GGM Commerce Preview Manager
 *
 * Handles preview product selection UI in Elementor editor.
 */
(function($) {
    'use strict';

    var GGMPreviewManager = {
        /**
         * Initialize the preview manager
         */
        init: function() {
            var self = this;

            // Wait for Elementor to be fully loaded
            if (typeof elementor === 'undefined') {
                return;
            }

            try {
                elementor.on('document:loaded', function() {
                    self.showPreviewIndicator();
                });

                // Only set up change listener if settings.page exists and has model
                if (elementor.settings && elementor.settings.page && elementor.settings.page.model) {
                    elementor.settings.page.model.on('change:ggm_preview_product_id', function(model) {
                        self.onPreviewProductChanged(model);
                    });
                }
            } catch (e) {
                // Preview manager initialization not available in this context
            }
        },

        /**
         * Show preview indicator in the panel
         */
        showPreviewIndicator: function() {
            var self = this;
            var previewProductId = this.getPreviewProductId();

            if (!previewProductId) {
                return;
            }

            // Get product name via stored options
            var productName = this.getProductNameFromOptions(previewProductId);

            if (productName) {
                this.displayIndicator(productName);
            }
        },

        /**
         * Get preview product ID from page settings
         */
        getPreviewProductId: function() {
            try {
                if (typeof elementor === 'undefined' || !elementor.settings || !elementor.settings.page) {
                    return null;
                }

                var model = elementor.settings.page.model;
                if (model) {
                    return model.get('ggm_preview_product_id');
                }
            } catch (e) {
                // Preview product ID not available
            }

            return null;
        },

        /**
         * Get product name from the select options
         */
        getProductNameFromOptions: function(productId) {
            try {
                // Try to get the product name from the control's options
                if (typeof elementor !== 'undefined' && elementor.settings && elementor.settings.page) {
                    var control = elementor.settings.page.getControlModel('ggm_preview_product_id');
                    if (control) {
                        var options = control.get('options');
                        if (options && options[productId]) {
                            return options[productId];
                        }
                    }
                }
            } catch (e) {
                // Product name lookup failed
            }

            return 'Product #' + productId;
        },

        /**
         * Display the preview indicator
         */
        displayIndicator: function(productName) {
            // Remove any existing indicator
            $('.ggm-preview-indicator-panel').remove();

            // Create indicator HTML
            var indicatorHtml = '<div class="ggm-preview-indicator-panel">' +
                '<strong><span class="eicon-eye"></span> ' + ggmPreviewManager.strings.previewLabel + '</strong><br>' +
                '<span>' + productName + '</span>' +
                '</div>';

            // Add to the panel footer or a visible area
            var $panelFooter = $('#elementor-panel-footer');
            if ($panelFooter.length) {
                $panelFooter.before(indicatorHtml);
            }
        },

        /**
         * Handle preview product change
         */
        onPreviewProductChanged: function(model) {
            var productId = model.get('ggm_preview_product_id');

            if (productId) {
                // Show notification
                elementor.notifications.showToast({
                    message: 'Preview product updated. Save and refresh to see changes.',
                    buttons: [
                        {
                            name: 'refresh',
                            text: 'Save & Refresh',
                            callback: function() {
                                // Save and refresh
                                $e.run('document/save/default').then(function() {
                                    location.reload();
                                });
                            }
                        }
                    ]
                });

                // Update indicator
                var productName = this.getProductNameFromOptions(productId);
                this.displayIndicator(productName);
            } else {
                // Remove indicator
                $('.ggm-preview-indicator-panel').remove();
            }
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        GGMPreviewManager.init();
    });

})(jQuery);
