<?php
/**
 * GGM Commerce Elementor Integration
 *
 * @package GGM Commerce
 * @subpackage Elementor
 * @version 1.0.0
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
// phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter

/**
 * Class GGM_Commerce_Elementor
 *
 * Handles all Elementor integration functionality
 */
class GGM_Commerce_Elementor {

    /**
     * Initialize Elementor integration
     */
    public static function init() {
        // Initialize Elementor widgets
        self::init_widgets();
    }

    /**
     * Initialize Elementor widgets
     */
    public static function init_widgets() {
        // Check if Elementor is installed and activated
        if (!did_action('elementor/loaded')) {
            return;
        }

        // Add custom widget category
        add_action('elementor/elements/categories_registered', array(__CLASS__, 'add_widget_categories'));

        // Register widgets on Elementor widgets init
        add_action('elementor/widgets/widgets_registered', array(__CLASS__, 'register_widgets'));

        // Add editor styles and scripts for premium widget PRO badges
        add_action('elementor/editor/after_enqueue_styles', array(__CLASS__, 'add_editor_badge_styles'));
        add_action('elementor/editor/after_enqueue_scripts', array(__CLASS__, 'add_editor_badge_scripts'));

        // Component order panel styling is now handled inline via RAW_HTML in class-product-grid-controls.php
        // This ensures styles load when the specific widget panel is opened

        // Add AJAX handlers for product search autocomplete
        add_action('wp_ajax_ggmc_search_products', array(__CLASS__, 'ajax_search_products'));
        add_action('wp_ajax_ggmc_get_product_title', array(__CLASS__, 'ajax_get_product_title'));

        // Add editor script for product search SELECT2
        add_action('elementor/editor/after_enqueue_scripts', array(__CLASS__, 'add_product_search_script'));
    }

    /**
     * Add editor styles for premium widget PRO badges
     */
    public static function add_editor_badge_styles() {
        $css = '
        /* GGM Commerce Premium Widget Pro Icon */
        .elementor-panel .elementor-element .ggmc-pro-badge {
            position: absolute;
            inset-block-start: 5px;
            inset-inline-end: 5px;
            font-family: eicons;
            font-style: normal;
            font-size: 12px;
            line-height: 1;
            color: inherit;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        .elementor-panel .elementor-element .ggmc-pro-badge::before {
            content: "\\e893";
        }
        ';

        wp_add_inline_style('elementor-editor', $css);
    }

    /**
     * Add editor scripts for premium widget PRO badges
     * Only activated premium widgets are shown in panel (via show_in_panel method)
     */
    public static function add_editor_badge_scripts() {
        // Premium widget titles (must match get_title() exactly)
        // These are all the premium widgets - only activated ones will be visible
        $pro_titles = array(
            'Wishlist',
            'Wishlist Icon',
            'Product Comparison',
            'Compare Icon',
            'Recently Viewed Products',
            'Product Review Form',
            'Review List',
            'Product Rating',
            'Custom Attributes',
            'Product Variations',
            'Stripe Payment',
            'PayPal Payment',
            'Kit Contents',
            'Customer Downloads',
            'Product Barcode',
            'Discount Code Input',
            'Applied Discount',
            'Subscription Management',
            'Product Carousel',
        );

        $js = '
        (function() {
            var proTitles = ' . wp_json_encode($pro_titles) . ';

            function addBadges() {
                var elements = document.querySelectorAll(".elementor-panel .elementor-element");

                elements.forEach(function(el) {
                    if (el.querySelector(".ggmc-pro-badge")) {
                        return;
                    }

                    var titleEl = el.querySelector(".title");
                    if (!titleEl) return;

                    var title = titleEl.textContent.trim();

                    if (proTitles.includes(title)) {
                        var badge = document.createElement("i");
                        badge.className = "ggmc-pro-badge";
                        el.style.position = "relative";
                        el.appendChild(badge);
                    }
                });
            }

            function init() {
                setTimeout(addBadges, 500);

                var observer = new MutationObserver(function() {
                    setTimeout(addBadges, 100);
                });

                var panel = document.getElementById("elementor-panel");
                if (panel) {
                    observer.observe(panel, { childList: true, subtree: true });
                }
            }

            if (window.elementor) {
                elementor.on("panel:init", init);
            }

            // Fallback if panel:init already fired
            setTimeout(init, 1000);
        })();
        ';

        wp_add_inline_script('elementor-editor', $js);
    }

    /**
     * Add custom Elementor widget category
     */
    public static function add_widget_categories($elements_manager) {
        $elements_manager->add_category(
            'ggmc-widgets',
            [
                'title' => 'GGM Commerce',
                'icon' => 'fa fa-shopping-cart',
            ]
        );
    }

    /**
     * Register all Elementor widgets
     */
    public static function register_widgets() {
        // Include the base widget class only if not already loaded
        if (!class_exists('GGM_Commerce_Base_Widget')) {
            require_once plugin_dir_path(dirname(__FILE__)) . 'widgets/class-ggm-commerce-base-widget.php';
        }

        // Include premium widget base class
        if (!class_exists('GGM_Commerce_Premium_Widget')) {
            require_once plugin_dir_path(dirname(__FILE__)) . 'widgets/class-ggm-commerce-premium-widget.php';
        }

        // Load shared control classes
        self::load_shared_controls();

        // Load all widget files with class_exists checks
        $widget_files = glob(plugin_dir_path(dirname(__FILE__)) . 'widgets/tags/*.php');

        if (!is_array($widget_files)) {
            $widget_files = [];
        }

        foreach ($widget_files as $widget_file) {
            // Extract the expected class name from filename
            $filename = basename($widget_file, '.php');
            $parts = explode('-', $filename);
            array_shift($parts); // Remove 'widget' part
            $class_parts = array_map('ucfirst', $parts);
            $class_name = 'GGM_Commerce_Widget_' . implode('_', $class_parts);
            
            // Only require if class doesn't exist
            if (!class_exists($class_name)) {
                require_once $widget_file;
            }
        }

        // Load premium widget files
        $premium_widget_files = glob(plugin_dir_path(dirname(__FILE__)) . 'widgets/premium/*.php');

        if (!is_array($premium_widget_files)) {
            $premium_widget_files = [];
        }

        foreach ($premium_widget_files as $widget_file) {
            $filename = basename($widget_file, '.php');
            $parts = explode('-', $filename);
            array_shift($parts); // Remove 'widget' part
            $class_parts = array_map('ucfirst', $parts);
            $class_name = 'GGM_Commerce_Widget_' . implode('_', $class_parts);
            
            if (!class_exists($class_name)) {
                require_once $widget_file;
            }
        }
        
        // Manual registration of all widgets with correct class names
        // Organized into logical groups for better UX
        $widgets = [
            // Single Product Display Widgets (for individual product pages)
            'GGM_Commerce_Widget_Product_Image',
            'GGM_Commerce_Widget_Product_Name',
            'GGM_Commerce_Widget_Product_Price',
            'GGM_Commerce_Widget_Product_Description',
            'GGM_Commerce_Widget_Product_Stock',
            'GGM_Commerce_Widget_Product_Categories',
            'GGM_Commerce_Widget_Product_Tags',
            'GGM_Commerce_Widget_Product_Attributes',
            'GGM_Commerce_Widget_Product_Details_Link',
            'GGM_Commerce_Product_Gallery_Widget',
            'GGM_Commerce_Widget_Product_Image_Grid',
            'GGM_Commerce_Widget_Add_To_Cart',

            // Archive Page Widgets (for category/tag archive pages)
            'GGM_Commerce_Widget_Taxonomy_Header',

            // Shop/Catalog Display Widgets (for product listings)
            'GGM_Commerce_Product_Grid_Widget',
            'GGM_Commerce_Widget_Product_Table_Refactored',
            'GGM_Commerce_Product_Filter_Widget',

            // Cart & Checkout Widgets
            'GGM_Commerce_Widget_Mini_Cart',
            'GGM_Commerce_Widget_Cart_Display',
            'GGM_Commerce_Widget_Checkout',
            'GGM_Commerce_Widget_Order_Confirmation',

            // Account Widgets
            'GGM_Commerce_Widget_Customer_Account',

            // Form Widgets
            'GGM_Commerce_Address_Form_Widget',

            // Premium Components (require license activation)
            'GGM_Commerce_Widget_Recently_Viewed',
            'GGM_Commerce_Widget_Wishlist',
            'GGM_Commerce_Widget_Wishlist_Icon',
            'GGM_Commerce_Widget_Product_Comparison',
            'GGM_Commerce_Widget_Compare_Icon',
            'GGM_Commerce_Widget_Product_Barcode',
            'GGM_Commerce_Widget_Custom_Attributes',
            'GGM_Commerce_Widget_Kit_Contents',
            'GGM_Commerce_Widget_Variation_Selector',
            'GGM_Commerce_Widget_Customer_Downloads',
            'GGM_Commerce_Widget_Product_Rating',
            'GGM_Commerce_Widget_Review_List',
            'GGM_Commerce_Widget_Review_Form',
            'GGM_Commerce_Widget_Discount_Code_Input',
            'GGM_Commerce_Widget_Applied_Discount',
            'GGM_Commerce_Widget_Subscription_Management',
            'GGM_Commerce_Widget_Product_Carousel',
        ];
        
        // Register each widget
        foreach ($widgets as $widget_class) {
            if (class_exists($widget_class)) {
                try {
                    \Elementor\Plugin::instance()->widgets_manager->register_widget_type(new $widget_class());
                    // Widget registration successful
                } catch (Exception $e) {
                    // Widget registration failed
                }
            } else {
                // Widget class not found
            }
        }
    }

    /**
     * Enqueue frontend assets for widgets
     */
    public static function enqueue_frontend_assets() {
        // Only load on pages that might use the shop widgets
        if (!is_admin()) {
            wp_enqueue_script('jquery');
            
            // Enqueue cart functionality for AJAX operations
            wp_enqueue_script(
                'ggmc-cart',
                plugin_dir_url(dirname(__FILE__)) . 'assets/js/cart.js',
                array('jquery'),
                '1.0.0',
                true
            );
            
            // Enqueue jQuery UI for price slider
            wp_enqueue_script('jquery-ui-slider');
            wp_enqueue_style('jquery-ui-style', '//code.jquery.com/ui/1.12.1/themes/ui-lightness/jquery-ui.css');
            
            // Get notification settings from widget controls
            $widget_controls = get_option('ggm_commerce_widget_controls', array());
            $notifications_config = array(
                'enabled'  => isset($widget_controls['notifications_enabled']) ? $widget_controls['notifications_enabled'] : '1',
                'position' => isset($widget_controls['notifications_position']) ? $widget_controls['notifications_position'] : 'top-right',
                'duration' => isset($widget_controls['notifications_duration']) ? intval($widget_controls['notifications_duration']) : 3000,
            );

            // Build i18n messages - use custom messages from widget controls if set, otherwise use defaults
            $i18n_messages = array(
                // General messages - use custom if set
                'error_occurred' => !empty($widget_controls['msg_error'])
                    ? $widget_controls['msg_error']
                    : __('An error occurred. Please try again.', 'ggm-commerce'),
                // Cart messages
                'select_options' => !empty($widget_controls['msg_select_options'])
                    ? $widget_controls['msg_select_options']
                    : __('Please select product options before adding to cart.', 'ggm-commerce'),
                'select_options_first' => !empty($widget_controls['msg_select_options'])
                    ? $widget_controls['msg_select_options']
                    : __('Please select product options first.', 'ggm-commerce'),
                'no_changes' => __('No changes to update.', 'ggm-commerce'),
                'added_to_cart' => !empty($widget_controls['msg_added_to_cart'])
                    ? $widget_controls['msg_added_to_cart']
                    : __('Product added to cart.', 'ggm-commerce'),
                'cart_updated' => __('Cart updated.', 'ggm-commerce'),
                // Wishlist messages
                'confirm_clear_wishlist' => __('Are you sure you want to clear your entire wishlist?', 'ggm-commerce'),
                // Comparison messages
                'max_compare_reached' => !empty($widget_controls['msg_max_compare'])
                    ? $widget_controls['msg_max_compare']
                    : __('Maximum of {max} products can be compared.', 'ggm-commerce'),
                'added_to_compare' => !empty($widget_controls['msg_added_to_compare'])
                    ? $widget_controls['msg_added_to_compare']
                    : __('Product added to comparison.', 'ggm-commerce'),
                'removed_from_compare' => !empty($widget_controls['msg_removed_from_compare'])
                    ? $widget_controls['msg_removed_from_compare']
                    : __('Product removed from comparison.', 'ggm-commerce'),
                'compare_cleared' => __('Comparison list cleared.', 'ggm-commerce'),
                'failed_add_compare' => __('Failed to add to comparison.', 'ggm-commerce'),
                'failed_remove_compare' => __('Failed to remove from comparison.', 'ggm-commerce'),
            );

            // Localize script for AJAX
            wp_localize_script('ggmc-cart', 'ggmCommerceAjax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('ggm_commerce_nonce'),
                'i18n' => $i18n_messages,
                'notifications' => $notifications_config,
            ));
            
            // Enqueue widget styles
            wp_enqueue_style(
                'ggmc-widgets',
                plugin_dir_url(dirname(__FILE__)) . 'assets/css/widgets.css',
                array(),
                '1.0.2'
            );

            // Conditionally enqueue professional defaults stylesheet
            // Only load if defaults are ENABLED (option is false/not set)
            $defaults_enabled = !get_option('ggm_commerce_defaults_cleared', false);
            if ($defaults_enabled) {
                wp_enqueue_style(
                    'ggmc-professional-defaults',
                    plugin_dir_url(dirname(__FILE__)) . 'assets/css/professional-defaults.css',
                    array('ggmc-widgets'),
                    '1.0.2'
                );
            }

            // Add inline CSS for widget controls customizations
            // Must be added AFTER professional-defaults to override the CSS variables
            $widget_controls_css = self::generate_widget_controls_css();
            if (!empty($widget_controls_css)) {
                // Attach to professional-defaults if loaded, otherwise to widgets
                $inline_style_handle = $defaults_enabled ? 'ggmc-professional-defaults' : 'ggmc-widgets';
                wp_add_inline_style($inline_style_handle, $widget_controls_css);
            }

            // Register payment gateway scripts (they will be enqueued by checkout widget if needed)
            if (function_exists('ggm_commerce_gateways')) {
                $gateway_manager = ggm_commerce_gateways();
                $available_gateways = $gateway_manager->get_available_gateways();
                foreach ($available_gateways as $gateway) {
                    $gateway_scripts = $gateway->get_scripts();
                    if (!empty($gateway_scripts)) {
                        foreach ($gateway_scripts as $script) {
                            if (isset($script['handle']) && isset($script['src'])) {
                                // Use null for version if explicitly set to null (for external SDKs like PayPal)
                                // This prevents WordPress from appending ?ver= which breaks some SDKs
                                $version = array_key_exists('ver', $script) ? $script['ver'] : '1.0.0';
                                wp_register_script(
                                    $script['handle'],
                                    $script['src'],
                                    $script['deps'] ?? array(),
                                    $version,
                                    true
                                );
                            }
                        }
                    }

                    // Localize script with gateway data if available
                    if (method_exists($gateway, 'get_js_data')) {
                        $js_data = $gateway->get_js_data();
                        if (!empty($js_data)) {
                            $localize_handle = 'ggmc-' . $gateway->get_id() . '-payment';
                            // Use proper casing for JavaScript object names
                            // stripe -> ggmcStripe, paypal -> ggmcPayPal
                            $gateway_id = $gateway->get_id();
                            if ($gateway_id === 'paypal') {
                                $localize_object = 'ggmcPayPal';
                            } elseif ($gateway_id === 'stripe') {
                                $localize_object = 'ggmcStripe';
                            } else {
                                $localize_object = 'ggmc' . ucfirst($gateway_id);
                            }
                            wp_localize_script($localize_handle, $localize_object, $js_data);
                        }
                    }
                }
            }
        }
    }

    /**
     * Generate inline CSS for widget controls customizations.
     *
     * This method reads settings from the ggm_commerce_widget_controls option
     * and generates CSS custom property overrides for comparison bar and
     * notification styling.
     *
     * @since 1.0.0
     * @return string CSS rules to be added inline, or empty string if using defaults.
     */
    public static function generate_widget_controls_css() {
        $widget_controls = get_option('ggm_commerce_widget_controls', array());
        $css_vars = array();

        // Comparison bar styling
        $compare_bar_mappings = array(
            'compare_bar_bg_start'     => '--ggmc-compare-bar-gradient-start',
            'compare_bar_bg_end'       => '--ggmc-compare-bar-gradient-end',
            'compare_bar_text_color'   => '--ggmc-compare-bar-text',
            'compare_bar_button_bg'    => '--ggmc-compare-bar-btn-bg',
            'compare_bar_button_text'  => '--ggmc-compare-bar-btn-text',
        );

        foreach ($compare_bar_mappings as $option_key => $css_var) {
            if (!empty($widget_controls[$option_key])) {
                $css_vars[$css_var] = esc_attr($widget_controls[$option_key]);
            }
        }

        // Comparison bar border radius (needs px unit)
        if (isset($widget_controls['compare_bar_border_radius']) && $widget_controls['compare_bar_border_radius'] !== '') {
            $css_vars['--ggmc-compare-bar-radius'] = intval($widget_controls['compare_bar_border_radius']) . 'px';
        }

        // Notification styling
        if (!empty($widget_controls['notifications_bg_color'])) {
            $css_vars['--ggmc-notification-bg'] = esc_attr($widget_controls['notifications_bg_color']);
        }
        if (!empty($widget_controls['notifications_text_color'])) {
            $css_vars['--ggmc-notification-text'] = esc_attr($widget_controls['notifications_text_color']);
        }
        if (isset($widget_controls['notifications_border_radius']) && $widget_controls['notifications_border_radius'] !== '') {
            $css_vars['--ggmc-notification-radius'] = intval($widget_controls['notifications_border_radius']) . 'px';
        }

        // Only output CSS if there are customizations
        if (empty($css_vars)) {
            return '';
        }

        // Build the CSS rule
        $css = ':root {';
        foreach ($css_vars as $var => $value) {
            $css .= $var . ':' . $value . ';';
        }
        $css .= '}';

        return $css;
    }

    /**
     * Load shared control classes for reuse across widgets.
     *
     * These classes provide standardized Elementor controls that can be
     * registered on any widget, reducing code duplication and ensuring
     * consistent naming and behavior.
     *
     * @since 1.0.0
     */
    private static function load_shared_controls() {
        $controls_path = plugin_dir_path(dirname(__FILE__)) . 'widgets/controls/';

        // Add to Cart button controls
        if (!class_exists('GGM_Add_To_Cart_Controls')) {
            require_once $controls_path . 'class-add-to-cart-controls.php';
        }

        // Rating stars controls
        if (!class_exists('GGM_Rating_Stars_Controls')) {
            require_once $controls_path . 'class-rating-stars-controls.php';
        }

        // Attribute display controls
        if (!class_exists('GGM_Attribute_Display_Controls')) {
            require_once $controls_path . 'class-attribute-display-controls.php';
        }

        // Table styling controls
        if (!class_exists('GGM_Table_Styling_Controls')) {
            require_once $controls_path . 'class-table-styling-controls.php';
        }
    }

    /**
     * AJAX handler for searching products (autocomplete)
     */
    public static function ajax_search_products() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_product_search', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check capabilities
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Permission denied']);
            return;
        }

        $search = isset($_POST['q']) ? sanitize_text_field(wp_unslash($_POST['q'])) : '';

        if (strlen($search) < 1) {
            wp_send_json_success(['results' => []]);
            return;
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_products';

        // Search by name or SKU
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT id, name, sku FROM {$table_name}
             WHERE status != 'deleted'
             AND (name LIKE %s OR sku LIKE %s)
             ORDER BY name ASC
             LIMIT 20",
            '%' . $wpdb->esc_like($search) . '%',
            '%' . $wpdb->esc_like($search) . '%'
        ));

        $formatted_results = [];
        foreach ($results as $product) {
            $text = $product->name;
            if (!empty($product->sku)) {
                $text .= ' (SKU: ' . $product->sku . ')';
            }
            $formatted_results[] = [
                'id' => $product->id,
                'text' => $text,
            ];
        }

        wp_send_json_success(['results' => $formatted_results]);
    }

    /**
     * AJAX handler for getting a product title by ID
     * Used to display the selected product name when loading saved widget settings
     */
    public static function ajax_get_product_title() {
        // Verify nonce
        if (!check_ajax_referer('ggmc_product_search', 'nonce', false)) {
            wp_send_json_error(['message' => 'Security check failed']);
            return;
        }

        // Check capabilities
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Permission denied']);
            return;
        }

        $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;

        if (empty($product_id)) {
            wp_send_json_error(['message' => 'No product ID provided']);
            return;
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'ggmc_products';

        $product = $wpdb->get_row($wpdb->prepare(
            "SELECT id, name, sku FROM {$table_name} WHERE id = %d",
            $product_id
        ));

        if (!$product) {
            wp_send_json_error(['message' => 'Product not found']);
            return;
        }

        $text = $product->name;
        if (!empty($product->sku)) {
            $text .= ' (SKU: ' . $product->sku . ')';
        }

        wp_send_json_success([
            'id' => $product->id,
            'text' => $text,
        ]);
    }

    /**
     * Add editor script for product search SELECT2 initialization
     */
    public static function add_product_search_script() {
        $js = '
        (function($) {
            "use strict";

            // Product search autocomplete configuration
            var ggmcProductSearch = {
                ajaxUrl: "' . admin_url('admin-ajax.php') . '",
                nonce: "' . wp_create_nonce('ggmc_product_search') . '",

                init: function() {
                    // Initialize on panel open/change
                    if (window.elementor) {
                        elementor.hooks.addAction("panel/open_editor/widget", this.initProductSearch.bind(this));
                    }

                    // Also watch for DOM changes in the panel
                    this.observePanel();
                },

                observePanel: function() {
                    var self = this;
                    var observer = new MutationObserver(function(mutations) {
                        mutations.forEach(function(mutation) {
                            if (mutation.addedNodes.length) {
                                setTimeout(function() {
                                    self.convertProductIdControls();
                                }, 100);
                            }
                        });
                    });

                    // Start observing when panel is ready
                    var checkPanel = setInterval(function() {
                        var panel = document.getElementById("elementor-panel");
                        if (panel) {
                            clearInterval(checkPanel);
                            observer.observe(panel, { childList: true, subtree: true });
                        }
                    }, 500);
                },

                initProductSearch: function(panel, model, view) {
                    var self = this;
                    // Small delay to ensure controls are rendered
                    setTimeout(function() {
                        self.convertProductIdControls();
                    }, 200);
                },

                convertProductIdControls: function() {
                    var self = this;

                    // Find all product_id number inputs that have not been converted
                    $(".elementor-control-product_id").each(function() {
                        var $control = $(this);

                        // Skip if already converted
                        if ($control.hasClass("ggmc-product-search-initialized")) {
                            return;
                        }

                        var $input = $control.find("input[type=\"number\"]");
                        if (!$input.length) return;

                        // Mark as initialized
                        $control.addClass("ggmc-product-search-initialized");

                        // Get current value
                        var currentValue = $input.val();

                        // Create SELECT2 container
                        var $select = $("<select class=\"ggmc-product-search-select\"></select>");

                        // Find the content wrapper and clear it for our select
                        var $contentWrapper = $control.find(".elementor-control-content");

                        // Create new wrapper for select2
                        var $selectWrapper = $("<div class=\"ggmc-product-select-wrapper\"></div>");
                        $selectWrapper.append($select);

                        // Append our wrapper after the field description (or at end of content)
                        $contentWrapper.append($selectWrapper);

                        // If there is a current value, we need to fetch its title
                        if (currentValue) {
                            self.fetchProductTitle(currentValue, function(data) {
                                if (data && data.id) {
                                    $select.append(new Option(data.text, data.id, true, true));
                                }
                                self.initSelect2($select, $input, $control);
                            });
                        } else {
                            self.initSelect2($select, $input, $control);
                        }
                    });
                },

                initSelect2: function($select, $input, $control) {
                    var self = this;

                    $select.select2({
                        placeholder: "Type 2+ characters to search...",
                        allowClear: true,
                        minimumInputLength: 2,
                        ajax: {
                            url: self.ajaxUrl,
                            type: "POST",
                            dataType: "json",
                            delay: 300,
                            data: function(params) {
                                return {
                                    action: "ggmc_search_products",
                                    nonce: self.nonce,
                                    q: params.term
                                };
                            },
                            processResults: function(response) {
                                if (response.success && response.data.results) {
                                    return { results: response.data.results };
                                }
                                return { results: [] };
                            },
                            cache: true
                        },
                        dropdownParent: $control
                    });

                    // Sync changes back to original input and trigger Elementor update
                    $select.on("change", function() {
                        var newVal = $(this).val() || "";
                        $input.val(newVal).trigger("input");

                        // Trigger Elementor to recognize the change
                        var controlView = elementor.getPanelView().getCurrentPageView().getControlViewByName("product_id");
                        if (controlView) {
                            controlView.setValue(newVal);
                        }
                    });
                },

                fetchProductTitle: function(productId, callback) {
                    $.ajax({
                        url: this.ajaxUrl,
                        type: "POST",
                        data: {
                            action: "ggmc_get_product_title",
                            nonce: this.nonce,
                            product_id: productId
                        },
                        success: function(response) {
                            if (response.success && response.data) {
                                callback(response.data);
                            } else {
                                callback(null);
                            }
                        },
                        error: function() {
                            callback(null);
                        }
                    });
                }
            };

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

        })(jQuery);
        ';

        // Add custom styles for the product search
        $css = '
        /* Hide original number input and its wrapper when converted */
        .ggmc-product-search-initialized .elementor-control-input-wrapper {
            display: none !important;
        }
        /* Hide the original label and description */
        .ggmc-product-search-initialized > .elementor-control-content > .elementor-control-field > .elementor-control-title {
            display: none !important;
        }
        .ggmc-product-search-initialized .elementor-control-field-description {
            display: none !important;
        }
        /* Product select wrapper */
        .ggmc-product-select-wrapper {
            width: 100%;
            padding: 0;
        }
        /* SELECT2 styling */
        .ggmc-product-search-initialized .select2-container {
            width: 100% !important;
        }
        .ggmc-product-search-initialized .select2-container--default .select2-selection--single {
            height: 40px;
            border: 1px solid #d5dadf;
            border-radius: 3px;
            background-color: #fff;
        }
        .ggmc-product-search-initialized .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 38px;
            padding-left: 10px;
            color: #495157;
        }
        .ggmc-product-search-initialized .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 38px;
        }
        .ggmc-product-search-initialized .select2-container--default .select2-selection--single .select2-selection__placeholder {
            color: #a4afb7;
        }
        .select2-dropdown {
            z-index: 999999 !important;
        }
        .select2-results__option {
            padding: 8px 12px;
        }
        .select2-results__option--highlighted {
            background-color: #93003c !important;
        }
        ';

        wp_add_inline_style('elementor-editor', $css);
        wp_add_inline_script('elementor-editor', $js);
    }
}