<?php

/**
 * The admin-specific functionality of the plugin.
 * Updated: Fixed metric pills syntax error
 *
 * @link       garidium.com
 * @since      1.0.0
 *
 * @package    g_Ffl_Cockpit
 * @subpackage g_Ffl_Cockpit/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    g_Ffl_Cockpit
 * @subpackage g_Ffl_Cockpit/admin
 * @author     Big G <sales@garidium.com>
 */
class g_ffl_Cockpit_Admin
{
    /**
     * Capability required to load the Cockpit admin page.
     *
     * We do NOT use `manage_options` here because allowlisted Product Search users
     * must be able to load the page (they are still restricted to the Product
     * Search tab via redirects + UI restrictions).
     */
    private const COCKPIT_PAGE_CAPABILITY = 'g_ffl_cockpit_access';

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $plugin_name The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * Ensure our capability filter is registered once.
     *
     * This runs early (admin_init priority 1) so direct URL loads
     * to `admin.php?page=g-ffl-cockpit-settings` work reliably.
     */
    private static $cap_filter_registered = false;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     * @since    1.0.0
     */
    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

    }

    /**
     * Determine whether the current user should be restricted to Cockpit Product Search only.
     *
     * Default behavior:
     * - Admins (manage_options) are never restricted.
     * - Any user with the capability `g_ffl_cockpit_product_search` is treated as restricted.
     *
     * Site owners can override this via:
     * `add_filter('g_ffl_cockpit_is_restricted_user', fn($is_restricted, $user) => ... , 10, 2);`
     *
     * @return bool
     */
    private function is_restricted_user(): bool
    {
        if (!is_user_logged_in()) {
            return false;
        }

        // Never restrict admins.
        if (current_user_can('manage_options')) {
            return false;
        }

        $user = wp_get_current_user();

        // Admin-managed allowlist: if present, it takes precedence as the primary mechanism.
        $allowlist_ids = $this->get_product_search_allowlist_user_ids();
        $is_allowlisted = !empty($allowlist_ids) && in_array((int) $user->ID, $allowlist_ids, true);

        // Capability-based fallback: supports role editor workflows without using the UI.
        $is_cap_allowed = user_can($user, 'g_ffl_cockpit_product_search');

        $is_restricted = $is_allowlisted || $is_cap_allowed;

        /**
         * Filter whether a user should be restricted to Product Search.
         *
         * @param bool    $is_restricted
         * @param WP_User $user
         */
        return (bool) apply_filters('g_ffl_cockpit_is_restricted_user', $is_restricted, $user);
    }

    /**
     * Determine whether the current user is a "tab-restricted" user.
     *
     * Tab-restricted users keep their normal WP admin menu and access,
     * but within the Cockpit plugin they only see the Product Search tab.
     * This applies to Shop Managers by default.
     *
     * Fully restricted (allowlisted/cap-based) users are handled separately
     * by is_restricted_user() and get the kiosk-mode experience.
     *
     * Site owners can override via:
     * `add_filter('g_ffl_cockpit_is_tab_restricted_user', fn($val, $user) => ... , 10, 2);`
     *
     * @return bool
     */
    private function is_tab_restricted_user(): bool
    {
        if (!is_user_logged_in()) {
            return false;
        }

        // Admins are never restricted.
        if (current_user_can('manage_options')) {
            return false;
        }

        // Fully restricted users are handled by the kiosk-mode path.
        if ($this->is_restricted_user()) {
            return false;
        }

        $user = wp_get_current_user();

        // Shop Managers see normal WP admin but restricted Cockpit tabs.
        $is_shop_manager = in_array('shop_manager', (array) $user->roles, true);

        /**
         * Filter whether a user should be tab-restricted within Cockpit.
         *
         * @param bool    $is_tab_restricted
         * @param WP_User $user
         */
        return (bool) apply_filters('g_ffl_cockpit_is_tab_restricted_user', $is_shop_manager, $user);
    }

    /**
     * Whether we are on the Cockpit settings page.
     */
    private function is_cockpit_page(): bool
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page routing only
        return is_admin() && isset($_GET['page']) && $_GET['page'] === 'g-ffl-cockpit-settings';
    }

    /**
     * Option name for user IDs allowed to access Product Search.
     */
    private function get_product_search_allowlist_option_name(): string
    {
        return 'g_ffl_cockpit_product_search_allowed_users';
    }

    /**
     * Get sanitized list of user IDs allowed to use Product Search.
     *
     * @return int[]
     */
    private function get_product_search_allowlist_user_ids(): array
    {
        $raw = get_option($this->get_product_search_allowlist_option_name(), array());
        if (!is_array($raw)) {
            $raw = array();
        }
        $ids = array_values(array_unique(array_filter(array_map('intval', $raw))));
        return $ids;
    }

    /**
     * Grant Cockpit page access to restricted Product Search users.
     *
     * Hooked to `user_has_cap` to dynamically grant `self::COCKPIT_PAGE_CAPABILITY`
     * to allowlisted/cap-based Product Search users, while admins keep full access.
     *
     * @param array   $allcaps
     * @param string[] $caps
     * @param array   $args
     * @param WP_User $user
     * @return array
     */
    public function maybe_grant_cockpit_page_cap_to_restricted_users($allcaps, $caps, $args, $user)
    {
        // Only intervene when WP is checking the Cockpit page capability.
        // IMPORTANT: `user_has_cap` is invoked by `user_can()`; calling `user_can()` from
        // within this filter can recurse and exhaust memory.
        if (!is_array($caps) || !in_array(self::COCKPIT_PAGE_CAPABILITY, $caps, true)) {
            return $allcaps;
        }

        // Admins should always have access.
        if (is_array($allcaps) && !empty($allcaps['manage_options'])) {
            $allcaps[self::COCKPIT_PAGE_CAPABILITY] = true;
            return $allcaps;
        }

        if (!is_object($user) || empty($user->ID)) {
            return $allcaps;
        }

        // Only grant the cap to users we consider "restricted" (Product Search only).
        $allowlist_ids = $this->get_product_search_allowlist_user_ids();
        $is_allowlisted = !empty($allowlist_ids) && in_array((int) $user->ID, $allowlist_ids, true);
        // Don't call user_can() here (recursion). Check existing caps directly.
        $is_cap_allowed = is_array($allcaps) && !empty($allcaps['g_ffl_cockpit_product_search']);

        if ($is_allowlisted || $is_cap_allowed) {
            $allcaps[self::COCKPIT_PAGE_CAPABILITY] = true;
            return $allcaps;
        }

        // Grant access to tab-restricted users (e.g., Shop Managers).
        // They keep normal WP admin but only see Product Search inside Cockpit.
        $is_shop_manager = is_array($user->roles) && in_array('shop_manager', $user->roles, true);
        if ($is_shop_manager) {
            $allcaps[self::COCKPIT_PAGE_CAPABILITY] = true;
        }

        return $allcaps;
    }

    /**
     * Register the Cockpit capability grant filter.
     *
     * This is called early via `admin_init` so capability checks during admin routing
     * will see our dynamic grant.
     */
    public function register_cockpit_cap_filter()
    {
        if (self::$cap_filter_registered) {
            return;
        }
        self::$cap_filter_registered = true;
        add_filter('user_has_cap', array($this, 'maybe_grant_cockpit_page_cap_to_restricted_users'), 10, 4);
    }

    /**
     * Handle saving the Product Search allowlist from the admin UI.
     * Runs on `admin_init`.
     */
    public function maybe_handle_product_search_allowlist_save()
    {
        if (!is_admin() || !is_user_logged_in()) {
            return;
        }
        if (!current_user_can('manage_options')) {
            return;
        }
        if (!$this->is_cockpit_page()) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- We verify below
        if (!isset($_POST['g_ffl_cockpit_action']) || $_POST['g_ffl_cockpit_action'] !== 'save_product_search_allowlist') {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- We verify below
        if (!isset($_POST['g_ffl_cockpit_allowlist_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['g_ffl_cockpit_allowlist_nonce'])), 'g_ffl_cockpit_save_product_search_allowlist')) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Form processing
        $user_ids = isset($_POST['g_ffl_cockpit_product_search_allow_users']) ? (array) $_POST['g_ffl_cockpit_product_search_allow_users'] : array();
        $sanitized = array_values(array_unique(array_filter(array_map('intval', $user_ids))));

        update_option($this->get_product_search_allowlist_option_name(), $sanitized, false);

        // Redirect back to avoid resubmits.
        $redirect_url = add_query_arg(
            array(
                'page' => 'g-ffl-cockpit-settings',
                'gffc_tab' => 'product_feed',
                'gffc_allowlist_saved' => '1',
            ),
            admin_url('admin.php')
        );
        wp_safe_redirect($redirect_url);
        exit;
    }

    /**
     * Redirect restricted users to Cockpit, and prevent them from using other wp-admin pages.
     *
     * Also forces Product Search to be the active tab.
     */
    public function maybe_restrict_cockpit_access()
    {
        if (!$this->is_restricted_user()) {
            return;
        }

        // Avoid redirect loops during AJAX, cron, or CLI.
        if (wp_doing_ajax() || (defined('DOING_CRON') && DOING_CRON) || (defined('WP_CLI') && WP_CLI)) {
            return;
        }

        global $pagenow;
        $allowed_url = add_query_arg(
            array(
                'page' => 'g-ffl-cockpit-settings',
                'gffc_tab' => 'product_feed',
            ),
            admin_url('admin.php')
        );

        // If not on admin.php?page=g-ffl-cockpit-settings redirect to it.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page routing only
        if ($pagenow !== 'admin.php' || !$this->is_cockpit_page()) {
            wp_safe_redirect($allowed_url);
            exit;
        }

        // If user is on cockpit page but tries to view other tabs, force Product Search.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Page routing only
        if (!isset($_GET['gffc_tab']) || $_GET['gffc_tab'] !== 'product_feed') {
            wp_safe_redirect($allowed_url);
            exit;
        }
    }

    /**
     * Remove most admin menu entries for restricted users.
     *
     * NOTE: This does not replace capability checks; it simply cleans up the UI.
     */
    public function maybe_cleanup_admin_menu_for_restricted_users()
    {
        if (!$this->is_restricted_user()) {
            return;
        }

        // Keep only our cockpit menu entry.
        global $menu;
        $keep_slug = 'g-ffl-cockpit-settings';
        if (!is_array($menu)) {
            return;
        }

        foreach ($menu as $index => $item) {
            if (!isset($item[2]) || $item[2] === $keep_slug) {
                continue;
            }
            unset($menu[$index]);
        }

        /**
         * Allow other code to further adjust admin menus for restricted users.
         */
        do_action('g_ffl_cockpit_restricted_admin_menu_cleaned');
    }

    /**
     * Hide the admin bar for restricted users.
     */
    public function maybe_hide_admin_bar_for_restricted_users()
    {
        if ($this->is_restricted_user()) {
            show_admin_bar(false);
        }
    }

    /**
     * Output lightweight CSS to make wp-admin feel like a single-purpose screen.
     * Scoped to the Cockpit page only.
     */
    public function maybe_output_restricted_ui_css()
    {
        // ── Fully restricted users: kiosk mode (hides WP chrome) ──
        if ($this->is_restricted_user() && $this->is_cockpit_page()) {
            $enable_css = (bool) apply_filters('g_ffl_cockpit_restricted_ui_enable_css', true);
            if (!$enable_css) {
                return;
            }

            ?>
            <style type="text/css">
                /* Remove download + disclaimer in Product Search for restricted users */
                #download_inventory_button {
                    display: none !important;
                }
                #gffc-product-search-disclaimer {
                    display: none !important;
                }

                /* Remove bottom admin-only configuration controls */
                #g_ffl_cockpit_key_form,
                #g_ffl_cockpit_key,
                #g-ffl-admin-buttons {
                    display: none !important;
                }
                #gffc-cockpit-key-label {
                    display: none !important;
                }
                #g_ffl_cockpit_key_form,
                #g_ffl_cockpit_key_form * {
                    visibility: hidden !important;
                }

                /* Hide global WP chrome */
                #wpadminbar,
                #adminmenumain,
                #wpfooter,
                #screen-meta-links {
                    display: none !important;
                }

                /* Expand content */
                #wpcontent {
                    margin-left: 0 !important;
                }

                /* Only show Product Search tab button */
                #cockpit_main_tab_control button.tablinks {
                    display: none !important;
                }
                #cockpit_main_tab_control button.tablinks[onclick*="product_feed"] {
                    display: inline-block !important;
                }

                /* Only show Product Search tab content */
                .tabcontent {
                    display: none !important;
                }
                #product_feed {
                    display: block !important;
                }

                /* Product Search-only users must not see the Edit Category control */
                body.g-ffl-cockpit-restricted i[title="Edit Category"],
                body.g-ffl-cockpit-restricted button[title="Edit Category"],
                body.g-ffl-cockpit-restricted i.fas.fa-edit[title="Edit Category"],
                body.g-ffl-cockpit-restricted i[onclick*="openCategoryChangeModal"],
                body.g-ffl-cockpit-restricted i.fas.fa-edit[onclick*="openCategoryChangeModal"],
                body.g-ffl-cockpit-restricted i.fas.fa-edit[onclick*="openDashboardCategoryChangeModal"] {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    width: 0 !important;
                    height: 0 !important;
                    overflow: hidden !important;
                    pointer-events: none !important;
                }

                body.g-ffl-cockpit-restricted #product_feed i.fas.fa-edit[title="Edit Category"],
                body.g-ffl-cockpit-restricted #product_feed i[onclick*="openCategoryChangeModal"],
                body.g-ffl-cockpit-restricted #product_feed i[title="Edit Category"] {
                    display: none !important;
                    visibility: hidden !important;
                    opacity: 0 !important;
                    pointer-events: none !important;
                }

                body.g-ffl-cockpit-restricted #categoryChangeModal {
                    display: none !important;
                    visibility: hidden !important;
                }

                /* Hide "Why Isn't This Product on Your Site?" diagnosis for kiosk users */
                #g_ffl_cockpit_diagnosis_section {
                    display: none !important;
                }
            </style>
            <?php
            return;
        }

        // ── Tab-restricted users (e.g., Shop Managers): keep WP chrome, hide non-search tabs ──
        if ($this->is_tab_restricted_user() && $this->is_cockpit_page()) {
            $enable_css = (bool) apply_filters('g_ffl_cockpit_tab_restricted_ui_enable_css', true);
            if (!$enable_css) {
                return;
            }

            ?>
            <style type="text/css">
                /* ── Hide non-allowed tab buttons (Product Search + Cart + Fulfillment + Help Center allowed) ── */
                #cockpit_main_tab_control button.tablinks:not(#gffc_cart_tab_btn):not([onclick*="product_feed"]):not([onclick*="fulfillment"]):not([onclick*="help_center"]) {
                    display: none !important;
                }
                /* Cart tab: starts hidden via inline style; JS toggles it — no conflict */

                /* ── Hide non-allowed tab content ── */
                #configuration,
                #logs,
                #marketplace_dashboard {
                    display: none !important;
                }

                /* ── Hide accordion buttons for other sections (but keep cart accordion) ── */
                button.accordion:not(#gffc_cart_accordion_btn) {
                    display: none !important;
                }

                /* ── Hide API key / admin controls ── */
                .gffc-key-admin-table {
                    display: none !important;
                }
                #g_ffl_cockpit_key_form {
                    display: none !important;
                }
                #gffc-cockpit-key-label {
                    display: none !important;
                }
                #g-ffl-admin-buttons {
                    display: none !important;
                }
                .gffc-admin-action-table {
                    display: none !important;
                }

                /* ── Hide download button and disclaimer ── */
                #download_inventory_button {
                    display: none !important;
                }
                #gffc-product-search-disclaimer {
                    display: none !important;
                }

                /* ── Hide Edit Category controls ── */
                i[title="Edit Category"],
                i[onclick*="openCategoryChangeModal"],
                i[onclick*="openDashboardCategoryChangeModal"] {
                    display: none !important;
                    pointer-events: none !important;
                }
                #categoryChangeModal {
                    display: none !important;
                }

                /* ── Hide user management section ── */
                .gffc-user-mgmt {
                    display: none !important;
                }
            </style>
            <?php
        }
    }

    /**
     * Output JS that forces Product Search tab on load and disables other tab navigation.
     * Scoped to Cockpit page only.
     */
    public function maybe_output_restricted_ui_js()
    {
        // ── Fully restricted users: force Product Search tab + block everything else ──
        if ($this->is_restricted_user() && $this->is_cockpit_page()) {
            $enable_js = (bool) apply_filters('g_ffl_cockpit_restricted_ui_enable_js', true);
            if (!$enable_js) {
                return;
            }

            ?>
            <script type="text/javascript">
                jQuery(function($) {
                    // Ensure Product Search is active.
                    var productFeedTab = document.querySelector('#cockpit_main_tab_control button[onclick*="product_feed"]');
                    if (productFeedTab) {
                        if (typeof window.openTab === 'function') {
                            try {
                                window.openTab({ currentTarget: productFeedTab, preventDefault: function(){} }, 'product_feed');
                            } catch (e) {
                                productFeedTab.click();
                            }
                        } else {
                            productFeedTab.click();
                        }
                    }

                    // Block other cockpit tab clicks.
                    $(document).on('click', '#cockpit_main_tab_control button.tablinks:not([onclick*="product_feed"])', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });

                    // Block category edit clicks.
                    $(document).on('click', 'i[title="Edit Category"], i[onclick*="openCategoryChangeModal"], i[onclick*="openDashboardCategoryChangeModal"]', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });

                    // Disable modal-opening functions.
                    try {
                        var noop = function() { return false; };
                        if (typeof window.openCategoryChangeModal === 'function') {
                            window.openCategoryChangeModal = noop;
                        }
                        if (typeof window.openDashboardCategoryChangeModal === 'function') {
                            window.openDashboardCategoryChangeModal = noop;
                        }
                        var modal = document.getElementById('categoryChangeModal');
                        if (modal) {
                            modal.style.display = 'none';
                            modal.style.visibility = 'hidden';
                        }
                    } catch (e) {}
                });
            </script>
            <?php
            return;
        }

        // ── Tab-restricted users (e.g., Shop Managers): block non-search tabs + category edits ──
        if ($this->is_tab_restricted_user() && $this->is_cockpit_page()) {
            $enable_js = (bool) apply_filters('g_ffl_cockpit_tab_restricted_ui_enable_js', true);
            if (!$enable_js) {
                return;
            }

            ?>
            <script type="text/javascript">
                jQuery(function($) {
                    // Force Product Search tab active on load.
                    var productFeedTab = document.querySelector('#cockpit_main_tab_control button[onclick*="product_feed"]');
                    if (productFeedTab) {
                        if (typeof window.openTab === 'function') {
                            try {
                                window.openTab({ currentTarget: productFeedTab, preventDefault: function(){} }, 'product_feed');
                            } catch (e) {
                                productFeedTab.click();
                            }
                        } else {
                            productFeedTab.click();
                        }
                    }

                    // Block non-allowed cockpit tab clicks (allow Product Search + Cart + Fulfillment + Help Center).
                    $(document).on('click', '#cockpit_main_tab_control button.tablinks', function(e) {
                        var onclick = $(this).attr('onclick') || '';
                        var id = $(this).attr('id') || '';
                        if (onclick.indexOf('product_feed') !== -1 || onclick.indexOf("'cart'") !== -1 || id === 'gffc_cart_tab_btn' || onclick.indexOf('fulfillment') !== -1 || onclick.indexOf('help_center') !== -1) {
                            return; // allow
                        }
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });

                    // Block category edit clicks.
                    $(document).on('click', 'i[title="Edit Category"], i[onclick*="openCategoryChangeModal"], i[onclick*="openDashboardCategoryChangeModal"]', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    });

                    // Disable modal-opening functions.
                    try {
                        var noop = function() { return false; };
                        if (typeof window.openCategoryChangeModal === 'function') {
                            window.openCategoryChangeModal = noop;
                        }
                        if (typeof window.openDashboardCategoryChangeModal === 'function') {
                            window.openDashboardCategoryChangeModal = noop;
                        }
                        var modal = document.getElementById('categoryChangeModal');
                        if (modal) {
                            modal.style.display = 'none';
                            modal.style.visibility = 'hidden';
                        }
                    } catch (e) {}
                });
            </script>
            <?php
        }
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles($hook)
    {
        // Only load on our specific admin pages
        if ($hook !== 'toplevel_page_g-ffl-cockpit-settings') {
            return;
        }

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Ffl_Cockpit_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Ffl_Cockpit_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/g-ffl-cockpit-admin.css', array(), $this->version, 'all');
        wp_enqueue_style('jsoneditor-style', plugin_dir_url(__FILE__) . 'css/jsoneditor.min.css', array(), $this->version, 'all');
        wp_enqueue_style('table-style', plugin_dir_url(__FILE__) . 'css/table.min.css', array(), $this->version, 'all');
        
        // External CSS dependencies - check for conflicts first
        if (!wp_style_is('font-awesome', 'enqueued') && !wp_style_is('fontawesome', 'enqueued')) {
            wp_enqueue_style('g-ffl-font-awesome', plugin_dir_url(__FILE__) . 'css/fa.css', array(), '6.0.0-beta3');
        }
        
        // Only load Bootstrap CSS if not already loaded
        if (!wp_style_is('bootstrap', 'enqueued') && !wp_style_is('bootstrap-css', 'enqueued')) {
            wp_enqueue_style('g-ffl-bootstrap', plugin_dir_url(__FILE__) . 'css/bootstrap.min.css', array(), '4.5.2');
        }

    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts($hook)
    {
        // Only load on our specific admin pages
        if ($hook !== 'toplevel_page_g-ffl-cockpit-settings') {
            return;
        }

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in g_Ffl_Cockpit_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The g_Ffl_Cockpit_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        // Ensure jQuery is loaded first
        wp_enqueue_script('jquery');
        
        // Enqueue jQuery UI components
        wp_enqueue_script('jquery-ui-core');
        wp_enqueue_script('jquery-ui-widget');
        wp_enqueue_script('jquery-ui-mouse');
        wp_enqueue_script('jquery-ui-sortable');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-slider');
        
        wp_enqueue_script('iris', admin_url('js/iris.min.js'), array('jquery-ui-draggable', 'jquery-ui-slider', 'jquery-touch-punch'), '1.0.0', true);
        
        // Deregister WordPress's built-in TinyMCE to prevent conflict with our bundled version
        // WP's TinyMCE 4.x uses theme:'modern' which doesn't exist in TinyMCE 5/6
        wp_deregister_script('wp-tinymce');
        wp_deregister_script('wp-tinymce-root');

        // Use local TinyMCE (Requires skins, themes, and icons folders in admin/js/)
        wp_enqueue_script('tinymce-external', plugin_dir_url(__FILE__) . 'js/tinymce.min.js', array('jquery'), $this->version, false);
        
        // Enqueue WordPress built-in TinyMCE
        
        // Ensure TinyMCE is loaded in the admin
        add_filter('user_can_richedit', '__return_true');
        
        // Load JSONEditor with proper dependencies
        wp_enqueue_script('jsoneditor', plugin_dir_url(__FILE__) . 'js/jsoneditor.min.js', array('jquery'), $this->version, false);
        wp_enqueue_style('jsoneditor-css', plugin_dir_url(__FILE__) . 'css/jsoneditor.min.css', array(), $this->version);
        
        // Load table component
        wp_enqueue_script('table_component', plugin_dir_url(__FILE__) . 'js/table.min.js', array('jquery'), $this->version, false);
        
        // Load main plugin script with all dependencies
        wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/g-ffl-cockpit-admin.js', array('jquery', 'jsoneditor', 'table_component'), $this->version, true);
        
        // Localize script with REST API settings for AI Helpdesk
        wp_localize_script($this->plugin_name, 'wpApiSettings', array(
            'root' => esc_url_raw(rest_url()),
            'nonce' => wp_create_nonce('wp_rest'),
        ));
        
        // Add conflict prevention script
        wp_add_inline_script($this->plugin_name, '
            jQuery(document).ready(function($) {
                // Wrap all functionality in try-catch to prevent conflicts
                try {
                    // Ensure JSONEditor is available globally
                    if (typeof window.JSONEditor === "undefined" && typeof JSONEditor !== "undefined") {
                        window.JSONEditor = JSONEditor;
                    }
                    
                    // Fix Bootstrap modal focus enforcement for TinyMCE dialogs
                    // TinyMCE dialogs are rendered outside the Bootstrap modal, so we need to
                    // temporarily disable focus enforcement when a TinyMCE dialog is open
                    $(document).on("focusin", function(e) {
                        if ($(e.target).closest(".tox-tinymce-aux, .tox-dialog, .moxman-container").length) {
                            e.stopImmediatePropagation();
                        }
                    });
                    
                    // Initialize TinyMCE editors after page load
                    setTimeout(function() {
                        initializeTinyMCEEditors();
                    }, 1000);
                    
                    // Make function available globally
                    window.initializeTinyMCEEditors = initializeTinyMCEEditors;
                    window.loadEditorContent = loadEditorContent;
                    window.syncNotificationEditorsFromCurrentConfiguration = syncNotificationEditorsFromCurrentConfiguration;
                    window.waitForTinyMCEEditors = waitForTinyMCEEditors;
                    window.gFFLCockpitIsApplyingConfiguration = false;
                    
                    // Make configuration available globally for editor content loading
                    window.currentConfiguration = null;
                    
                    console.log("G-FFL Cockpit: Scripts loaded successfully");
                } catch (e) {
                    console.warn("G-FFL Cockpit: Script error caught and handled:", e.message);
                }
                
                    // Function to initialize TinyMCE editors
                function initializeTinyMCEEditors() {
                    // Find all textareas that should be rich text editors (email templates)
                    var editorTargets = [
                        "fulfillment-emailer-templates-order_processed-message_ffl_order",
                        "fulfillment-emailer-templates-order_processed-message_non_ffl_order",
                        "fulfillment-emailer-templates-order_shipped-message_ffl_order",
                        "fulfillment-emailer-templates-order_shipped-message_non_ffl_order",
                        "fulfillment-emailer-templates-order_delivered-message_ffl_order",
                        "fulfillment-emailer-templates-order_delivered-message_non_ffl_order",
                        "fulfillment-emailer-templates-ffl_request-message"
                    ];
                    
                    editorTargets.forEach(function(editorId) {
                        var element = document.getElementById(editorId);
                        if (element && typeof tinymce !== "undefined") {
                            // Remove existing editor if it exists
                            if (tinymce.get(editorId)) {
                                tinymce.remove("#" + editorId);
                            }
                            
                            // Store the current content before initializing
                            var currentContent = element.value || "";
                            
                            // Initialize new editor
                            tinymce.init({
                                selector: "#" + editorId,
                                height: 375,
                                menubar: false,
                                plugins: "advlist autolink lists link charmap anchor searchreplace visualblocks code insertdatetime table help image",
                                toolbar: "code link image bold italic underline forecolor backcolor alignleft aligncenter alignright bullist numlist",
                                content_style: "body { font-family: -apple-system, BlinkMacSystemFont, San Francisco, Segoe UI, Roboto, Helvetica Neue, sans-serif; font-size: 14px; line-height: 1.4; }",
                                branding: false,
                                statusbar: false,
                                license_key: "gpl",
                                convert_urls: false,
                                relative_urls: false,
                                paste_data_images: false,
                                init_instance_callback: function(editor) {
                                    // Set content after editor is ready
                                    if (currentContent) {
                                        editor.setContent(currentContent);
                                    }
                                    
                                    // Load content from configuration if available
                                    if (typeof currentConfiguration !== "undefined" && currentConfiguration) {
                                        loadEditorContent(editor, editorId);
                                    }
                                },
                                setup: function(editor) {
                                    editor.on("change", function() {
                                        editor.save();
                                        // Trigger the auto-save function to update the JSON configuration
                                        var field = document.getElementById(editor.id);
                                        if (window.gFFLCockpitIsApplyingConfiguration) {
                                            return;
                                        }
                                        if (field && typeof autoSave === "function") {
                                            autoSave(field);
                                        }
                                    });
                                    editor.on("input", function() {
                                        editor.save();
                                        // Trigger the auto-save function to update the JSON configuration
                                        var field = document.getElementById(editor.id);
                                        if (window.gFFLCockpitIsApplyingConfiguration) {
                                            return;
                                        }
                                        if (field && typeof autoSave === "function") {
                                            autoSave(field);
                                        }
                                    });
                                }
                            });
                        }
                    });
                }

                // Wait until the given TinyMCE editors exist (or timeout)
                function waitForTinyMCEEditors(editorIds, timeoutMs) {
                    timeoutMs = typeof timeoutMs === "number" ? timeoutMs : 8000;
                    var start = Date.now();

                    return new Promise(function(resolve) {
                        (function check() {
                            var ready = true;

                            if (typeof tinymce === "undefined") {
                                ready = false;
                            } else {
                                editorIds.forEach(function(id) {
                                    if (!tinymce.get(id)) {
                                        ready = false;
                                    }
                                });
                            }

                            if (ready) {
                                resolve(true);
                                return;
                            }

                            if (Date.now() - start >= timeoutMs) {
                                resolve(false);
                                return;
                            }

                            setTimeout(check, 150);
                        })();
                    });
                }

                // Force TinyMCE + textarea content to reflect the latest loaded config
                function syncNotificationEditorsFromCurrentConfiguration() {
                    if (!window.currentConfiguration) {
                        return Promise.resolve(false);
                    }

                    // Protect against autosave while we apply new configuration
                    window.gFFLCockpitIsApplyingConfiguration = true;

                    var editorTargets = [
                        "fulfillment-emailer-templates-order_processed-message_ffl_order",
                        "fulfillment-emailer-templates-order_processed-message_non_ffl_order",
                        "fulfillment-emailer-templates-order_shipped-message_ffl_order",
                        "fulfillment-emailer-templates-order_shipped-message_non_ffl_order",
                        "fulfillment-emailer-templates-order_delivered-message_ffl_order",
                        "fulfillment-emailer-templates-order_delivered-message_non_ffl_order",
                        "fulfillment-emailer-templates-ffl_request-message"
                    ];

                    // Always ensure editors exist for hidden tabs; init is safe (it removes existing first)
                    if (typeof window.initializeTinyMCEEditors === "function") {
                        window.initializeTinyMCEEditors();
                    }

                    return waitForTinyMCEEditors(editorTargets, 8000).then(function() {
                        if (typeof tinymce !== "undefined") {
                            editorTargets.forEach(function(editorId) {
                                var editor = tinymce.get(editorId);
                                if (!editor) {
                                    return;
                                }
                                // Map config -> editor content
                                loadEditorContent(editor, editorId);
                                // Persist to textarea so JSONEditor autosave reads correct content
                                editor.save();
                                // Avoid showing unsaved changes just because we loaded remote config
                                if (typeof editor.setDirty === "function") {
                                    editor.setDirty(false);
                                }
                            });
                        }

                        window.gFFLCockpitIsApplyingConfiguration = false;
                        return true;
                    });
                }
                
                // Function to load content into a specific editor
                function loadEditorContent(editor, editorId) {
                    if (!currentConfiguration || !currentConfiguration.fulfillment || !currentConfiguration.fulfillment.emailer || !currentConfiguration.fulfillment.emailer.templates) {
                        return;
                    }
                    
                    var templates = currentConfiguration.fulfillment.emailer.templates;
                    var content = "";
                    
                    switch (editorId) {
                        case "fulfillment-emailer-templates-order_processed-message_ffl_order":
                            content = templates.order_processed && templates.order_processed.message_ffl_order ? templates.order_processed.message_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-order_processed-message_non_ffl_order":
                            content = templates.order_processed && templates.order_processed.message_non_ffl_order ? templates.order_processed.message_non_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-order_shipped-message_ffl_order":
                            content = templates.order_shipped && templates.order_shipped.message_ffl_order ? templates.order_shipped.message_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-order_shipped-message_non_ffl_order":
                            content = templates.order_shipped && templates.order_shipped.message_non_ffl_order ? templates.order_shipped.message_non_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-order_delivered-message_ffl_order":
                            content = templates.order_delivered && templates.order_delivered.message_ffl_order ? templates.order_delivered.message_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-order_delivered-message_non_ffl_order":
                            content = templates.order_delivered && templates.order_delivered.message_non_ffl_order ? templates.order_delivered.message_non_ffl_order : "";
                            break;
                        case "fulfillment-emailer-templates-ffl_request-message":
                            content = templates.ffl_request && templates.ffl_request.message ? templates.ffl_request.message : "";
                            break;
                    }
                    
                    if (content) {
                        editor.setContent(content);
                    }
                }
                
                // Re-initialize editors when tabs are switched
                $(document).on("click", ".nav-tab", function() {
                    setTimeout(function() {
                        initializeTinyMCEEditors();
                    }, 500);
                });
                
                // NOTE: We intentionally do not re-sync TinyMCE on Notifications tab click.
                // Editors are synced when a customer configuration is loaded (see load_fancy_editor).
            });
        ', 'after');
        
        // Load Select2 if not already loaded by another plugin
        if (!wp_script_is('select2', 'enqueued')) {
            wp_enqueue_script('select2', plugin_dir_url(__FILE__) . 'js/select2.min.js', array('jquery'), '4.0.13', true);
            wp_enqueue_style('select2', plugin_dir_url(__FILE__) . 'css/select2.min.css', array(), '4.0.13');
        }
        
        // Enqueue external libraries
        wp_enqueue_style('bootstrap-css', plugin_dir_url(__FILE__) . 'css/bootstrap.min.css', array(), '4.5.2');
        wp_enqueue_script('bootstrap-js', plugin_dir_url(__FILE__) . 'js/bootstrap.min.js', array('jquery'), '4.5.2', true);
        
        // Suppress source map warning for bootstrap
        wp_add_inline_script('bootstrap-js', '//# sourceMappingURL=', 'before');
        
        wp_enqueue_style('font-awesome-admin', plugin_dir_url(__FILE__) . 'css/fa.css', array(), '6.0.0-beta3');
        
        wp_enqueue_style('forms');

    }
    
    /**
     * Handle script conflicts with other plugins
     */
    public function handle_script_conflicts() {
        // Only on our admin page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Simple page check, not processing form data
        if (!isset($_GET['page']) || $_GET['page'] !== 'g-ffl-cockpit-settings') {
            return;
        }
        
        // Simple logging
        add_action('wp_footer', function() {
            ?>
            <script>
            if (typeof console !== 'undefined') {
                console.log('G-FFL Cockpit: Page loaded successfully');
            }
            </script>
            <?php
        });
    }
    
    /**
     * Admin init hook to handle conflicts early
     */
    public function admin_init_conflicts() {
        // Simple approach - prevent specific plugin scripts on our page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Simple page check, not processing form data
        if (isset($_GET['page']) && $_GET['page'] === 'g-ffl-cockpit-settings') {
            // Add action to prevent ShopLentor from enqueueing scripts on our page
            add_action('wp_enqueue_scripts', array($this, 'prevent_shoplentor_scripts'), 5);
            add_action('admin_enqueue_scripts', array($this, 'prevent_shoplentor_scripts'), 5);
        }
    }
    
    /**
     * Prevent ShopLentor scripts from loading on our page
     */
    public function prevent_shoplentor_scripts() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Simple page check for script conflict prevention
        if (!isset($_GET['page']) || $_GET['page'] !== 'g-ffl-cockpit-settings') {
            return;
        }
        
        // Temporarily remove ShopLentor hooks to prevent script enqueuing
        
        global $wp_filter;
        
        if (isset($wp_filter['admin_enqueue_scripts'])) {
            foreach ($wp_filter['admin_enqueue_scripts']->callbacks as $priority => $callbacks) {
                foreach ($callbacks as $callback_id => $callback) {
                    if (is_array($callback['function']) && 
                        is_object($callback['function'][0]) &&
                        (strpos(get_class($callback['function'][0]), 'ShopLentor') !== false ||
                         strpos(get_class($callback['function'][0]), 'Woolentor') !== false)) {
                        
                        remove_action('admin_enqueue_scripts', $callback['function'], $priority);
                        g_ffl_debug_log("Removed ShopLentor enqueue hook", 'info');
                    }
                }
            }
        }
        
    }

    public function ffl_load_menu()
    {
        $custom_plugin_name = (get_option('g_ffl_cockpit_plugin_name') != ''? get_option('g_ffl_cockpit_plugin_name') : 'FFL Cockpit');
        add_menu_page('g-FFL Cockpit Settings Page', $custom_plugin_name, self::COCKPIT_PAGE_CAPABILITY, 'g-ffl-cockpit-settings', array($this, 'g_ffl_cockpit_settings_page'), 'dashicons-database-import', 70);
        add_action('admin_init', array($this, 'register_g_ffl_cockpit_settings'));
		add_action('admin_init', array($this, 'maybe_handle_product_search_allowlist_save'));
    }

    function register_g_ffl_cockpit_settings()
    {
        //register our settings
        register_setting('g-ffl-cockpit-settings', 'g_ffl_cockpit_key', 'sanitize_text_field');
        //register_setting('g-ffl-cockpit-settings', 'g_ffl_cockpit_configuration');
        register_setting('g-ffl-cockpit-settings', 'g_ffl_cockpit_plugin_name', 'sanitize_text_field');
        register_setting('g-ffl-cockpit-settings', 'g_ffl_cockpit_plugin_logo_url', 'esc_url_raw');
    }

    /**
     * Generate the complete purchase URL with account identification
     * 
     * @param string $api_key The API key
     * @param string $base_url The base purchase URL (optional, defaults to standard token URL)
     * @return string The complete purchase URL with API key parameter
     */
    private function get_purchase_url($api_key, $base_url = 'https://fflcockpit.com/product/ai-tokens/')
    {
        // Ensure API key is a string and not empty
        if (empty($api_key) || !is_string($api_key)) {
            return $base_url; // Return base URL without account_id if API key is invalid
        }
        
        // Create shortened version: first 10 chars + "-" + last 5 chars
        $key_length = strlen($api_key);
        if ($key_length <= 15) {
            // If key is too short, use the whole key
            $shortened_key = $api_key;
        } else {
            $shortened_key = substr($api_key, 0, 10) . '-' . substr($api_key, -5);
        }
        
        $separator = strpos($base_url, '?') !== false ? '&' : '?';
        return $base_url . $separator . 'account_id=' . urlencode($shortened_key);
    }

    function g_ffl_cockpit_settings_page()
    {
        $gFFLCockpitKey = get_option('g_ffl_cockpit_key');
        $current_user = wp_get_current_user();
        echo '<script type="text/javascript">
                    const siteBaseUrl = "<?php echo esc_js(home_url()); ?>";
                    // Create namespace to prevent conflicts with other plugins
                window.gFFLCockpit = window.gFFLCockpit || {};
                window.gFFLCockpit.apiKey = "' . esc_attr($gFFLCockpitKey) . '";
                window.gFFLCockpit.currentUser = {
                    id: ' . esc_js($current_user->ID) . ',
                    login: "' . esc_js($current_user->user_login) . '",
                    email: "' . esc_js($current_user->user_email) . '",
                    displayName: "' . esc_js($current_user->display_name) . '",
                    roles: ' . wp_json_encode($current_user->roles) . '
                };
                window.gFFLCockpit.isAdmin = ' . (current_user_can('manage_options') ? 'true' : 'false') . ';
                window.gFFLCockpit.keyJustSaved = ' . ((isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'true') ? 'true' : 'false') . ';
                window.gFFLCockpit.pluginVersion = "' . esc_js(defined('G_FFL_COCKPIT_VERSION') ? G_FFL_COCKPIT_VERSION : '') . '";
                window.gFFLCockpit.wpHomeUrl = "' . esc_url_raw(home_url()) . '";
                window.gFFLCockpit.wpSiteUrl = "' . esc_url_raw(site_url()) . '";
                window.gFFLCockpit.wpAdminUrl = "' . esc_url_raw(admin_url()) . '";

                // Generate complete purchase URL with account identification
                window.gFFLCockpit.getPurchaseUrl = function(apiKey, baseUrl = "https://fflcockpit.com/product/ai-tokens/") {
                    // Ensure API key is valid
                    if (!apiKey || typeof apiKey !== "string" || apiKey.length === 0) {
                        return baseUrl; // Return base URL without account_id if API key is invalid
                    }
                    
                    // Create shortened version: first 10 chars + "-" + last 5 chars
                    let shortenedKey;
                    if (apiKey.length <= 15) {
                        // If key is too short, use the whole key
                        shortenedKey = apiKey;
                    } else {
                        shortenedKey = apiKey.substring(0, 10) + \'-\' + apiKey.substring((apiKey.length - 5));
                    }
                    
                    const separator = baseUrl.indexOf("?") !== -1 ? "&" : "?";
                    return baseUrl + separator + "account_id=" + encodeURIComponent(shortenedKey);
                };
                
                // Update any existing purchase links on the page
                window.gFFLCockpit.updatePurchaseLinks = function() {
                    const purchaseLinks = document.querySelectorAll(\'a[href*="fflcockpit.com/product/ai-tokens/"]\');
                    purchaseLinks.forEach(link => {
                        if (!link.href.includes("account_id=")) {
                            link.href = window.gFFLCockpit.getPurchaseUrl(window.gFFLCockpit.apiKey);
                        }
                    });
                };
                
                // Run on page load
                document.addEventListener("DOMContentLoaded", window.gFFLCockpit.updatePurchaseLinks);
              </script>';
        ?>
        
        
        <style>
            .tab-pane {
                min-height: 500px;
            }
        </style>
        <script>
            (function() {
                /* ================================================================
                   Site Health Dashboard
                   ================================================================ */
                const _healthColors = {
                    healthy:  { bg: '#ecfdf5', strip: '#10b981', text: '#065f46', badge: '#d1fae5', label: 'Healthy' },
                    degraded: { bg: '#fffbeb', strip: '#f59e0b', text: '#92400e', badge: '#fef3c7', label: 'Degraded' },
                    critical: { bg: '#fef2f2', strip: '#ef4444', text: '#991b1b', badge: '#fee2e2', label: 'Critical' },
                    inactive: { bg: '#f9fafb', strip: '#9ca3af', text: '#6b7280', badge: '#f3f4f6', label: 'Inactive' },
                    unknown:  { bg: '#f9fafb', strip: '#9ca3af', text: '#6b7280', badge: '#f3f4f6', label: 'Unknown' },
                    error:    { bg: '#f9fafb', strip: '#9ca3af', text: '#6b7280', badge: '#f3f4f6', label: 'Error' }
                };

                function _hc(status) { return _healthColors[status] || _healthColors.unknown; }

                function _fmt(v, fallback) { return (v != null && v !== '') ? v : (fallback || '--'); }
                function _num(v) { return (v != null) ? Number(v) : 0; }
                function _pct(v) { return _num(v).toFixed(1) + '%'; }
                function _comma(v) { return _num(v).toLocaleString(); }

                function _timeAgo(ts) {
                    if (!ts) return 'Never';
                    const d = new Date(ts.replace ? ts.replace(' ', 'T') + 'Z' : ts);
                    if (isNaN(d)) return ts;
                    const sec = Math.floor((Date.now() - d.getTime()) / 1000);
                    if (sec < 60) return 'Just now';
                    if (sec < 3600) return Math.floor(sec / 60) + 'm ago';
                    if (sec < 86400) return Math.floor(sec / 3600) + 'h ago';
                    return Math.floor(sec / 86400) + 'd ago';
                }

                function _isOlderThan24h(ts) {
                    if (!ts) return true;
                    var d = new Date(ts.replace ? ts.replace(' ', 'T') + 'Z' : ts);
                    if (isNaN(d)) return true;
                    return (Date.now() - d.getTime()) > 86400000;
                }

                function _scoreBar(score, label, weight) {
                    const s = _num(score);
                    const col = s >= 90 ? '#10b981' : s >= 70 ? '#f59e0b' : s >= 50 ? '#f97316' : '#ef4444';
                    return '<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;">'
                        + '<span style="font-size:13px;font-weight:600;color:#334155;">' + label + ' <span style="font-weight:400;color:#94a3b8;font-size:11px;">(' + weight + '% weight)</span></span>'
                        + '<span style="font-size:15px;font-weight:700;color:' + col + ';">' + Math.round(s) + '</span>'
                        + '</div>'
                        + '<div style="height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden;margin-bottom:12px;">'
                        + '<div style="height:100%;width:' + Math.min(100, Math.max(0, s)) + '%;background:' + col + ';border-radius:3px;transition:width 0.4s;"></div>'
                        + '</div>';
                }

                function _metricRow(label, value, adminOnly) {
                    return '<div class="gffc-health-metric' + (adminOnly ? ' gffc-health-admin-only' : '') + '">'
                        + '<span class="gffc-health-metric-label">' + label + '</span>'
                        + '<span class="gffc-health-metric-value">' + value + '</span></div>';
                }

                function _helpBtn(cat) {
                    return ' <button type="button" class="gffc-health-help-btn" onclick="gffcHealthHelp(\'' + cat + '\')" title="How is this calculated?"><i class="fas fa-question-circle"></i></button>';
                }

                /* ---- Sub-score recalculation (mirrors backend formula) ---- */
                function _calcSynchScore(d) {
                    var synchCount = _num(d.synch_count_24h);
                    var timeouts = _num(d.timeout_count_24h);
                    var changePct = _num(d.change_pct_applied_24h);
                    var synchCount7d = _num(d.synch_count_7d);
                    var score;
                    if (synchCount > 0) {
                        var timeoutPct = (timeouts / synchCount) * 100;
                        score = Math.max(0, 100 - timeoutPct - (timeouts >= 5 ? 25 : 0));
                    } else if (synchCount === 0 && synchCount7d > 0) {
                        score = 50;
                    } else {
                        score = 0;
                    }
                    if (changePct > 0) score = score * 0.6 + changePct * 0.4;
                    return Math.max(0, Math.min(100, score));
                }
                function _calcOnsiteScore(d) {
                    var ok = _num(d.insert_successful_24h) + _num(d.update_successful_24h) + _num(d.delete_successful_24h);
                    var fail = _num(d.insert_failed_24h) + _num(d.update_failed_24h) + _num(d.delete_failed_24h);
                    var total = ok + fail;
                    return total > 0 ? (ok / total) * 100 : 100;
                }
                function _calcAlertScore(d) {
                    var crit = _num(d.alerts_critical_24h);
                    var critPenalty = crit === 0 ? 0 : crit === 1 ? 25 : 25 + (crit - 1) * 30;
                    return Math.max(0, 100 - critPenalty - _num(d.alerts_error_24h) * 10);
                }
                function _calcConnScore(d) {
                    var total = _num(d.conn_tests_total);
                    return total > 0 ? (_num(d.conn_tests_passed) / total) * 100 : 100;
                }

                /* ---- Recommendations engine ---- */
                function _generateRecs(d, isAdmin) {
                    var recs = [];
                    if (d.status === 'inactive') {
                        recs.push({ sev: 'critical', icon: 'fa-exclamation-triangle', msg: 'No sync or onsite activity detected in the last 24 hours. Verify that your WordPress cron is running and that FFL Cockpit is properly configured.' });
                    }
                    if (_num(d.conn_tests_total) > 0 && _num(d.conn_success) === 0) {
                        // Check if failures are only minor (plugin version, etc.) vs actual connectivity issues
                        var minorOnlyFailures = ['FFL Cockpit Plugin Version'];
                        var failed = d.conn_failed_tests;
                        var hasConnectivityFailure = !failed || !Array.isArray(failed) || failed.some(function(t) { return minorOnlyFailures.indexOf(t) === -1; });
                        if (hasConnectivityFailure) {
                            recs.push({ sev: 'critical', icon: 'fa-plug', msg: 'The last connection test failed. Your site may not be reachable by the sync service. Check your firewall, security plugins, and REST API access.' });
                        }
                    }
                    var failedTests = d.conn_failed_tests;
                    var tips = d.conn_troubleshooting_tips || {};
                    var knownTips = {
                        'FFL Cockpit Plugin Version': 'Update the FFL Cockpit plugin to the latest version. Go to <strong>Plugins &gt; Installed Plugins</strong> in your WordPress admin and click "Update" next to FFL Cockpit.',
                        'API Authentication': 'Your WooCommerce REST API keys may be invalid or expired. Verify them in <strong>WooCommerce &gt; Settings &gt; Advanced &gt; REST API</strong>.',
                        'Website Reachable': 'Your site may be down or behind a maintenance page. Verify the site loads in a browser.',
                        'WordPress Detected': 'WordPress could not be detected at the configured URL. Verify the site URL is correct.',
                    };
                    if (failedTests && Array.isArray(failedTests)) {
                        failedTests.forEach(function(t) {
                            var tip = (typeof tips === 'object' && tips[t]) ? tips[t] : (knownTips[t] || 'Review the connection test details for "' + t + '".');
                            recs.push({ sev: 'warning', icon: 'fa-network-wired', msg: '<strong>Connection test failed:</strong> ' + t + ' &mdash; ' + tip });
                        });
                    }
                    if (isAdmin && _num(d.timeout_count_24h) >= 5) {
                        recs.push({ sev: 'critical', icon: 'fa-clock', msg: 'Your site had ' + d.timeout_count_24h + ' sync timeouts in 24 hours. Consider increasing PHP <code>max_execution_time</code> or upgrading your hosting plan.' });
                    } else if (isAdmin && _num(d.timeout_count_24h) >= 2) {
                        recs.push({ sev: 'warning', icon: 'fa-clock', msg: 'Your site had ' + d.timeout_count_24h + ' sync timeouts recently. Monitor this &mdash; frequent timeouts degrade sync reliability.' });
                    }
                    var failOps = _num(d.insert_failed_24h) + _num(d.update_failed_24h) + _num(d.delete_failed_24h);
                    var totalOps = failOps + _num(d.insert_successful_24h) + _num(d.update_successful_24h) + _num(d.delete_successful_24h);
                    if (failOps > 0 && totalOps > 0 && (failOps / totalOps) > 0.1) {
                        recs.push({ sev: 'warning', icon: 'fa-exclamation-circle', msg: 'Over 10% of product operations failed in the last 24 hours (' + failOps + ' failures). Check the <strong>Logs</strong> tab for error details.' });
                    } else if (failOps > 0) {
                        recs.push({ sev: 'info', icon: 'fa-info-circle', msg: failOps + ' product operation(s) failed in the last 24 hours. Review the <strong>Logs</strong> tab if this is unexpected.' });
                    }
                    var recMaxExec = (d.server_stats && d.server_stats.php_config) ? Number(d.server_stats.php_config.max_execution_time) : 0;
                    if (recMaxExec > 0 && recMaxExec < 300) {
                        recs.push({ sev: 'warning', icon: 'fa-tachometer-alt', msg: 'PHP <code>max_execution_time</code> is set to <strong>' + recMaxExec + 's</strong>. FFL Cockpit recommends <strong>300s</strong> or higher to avoid timeouts during product sync. Ask your hosting provider to increase this value.' });
                    }
                    if (_num(d.alerts_error_24h) > 0) {
                        recs.push({ sev: 'warning', icon: 'fa-bell', msg: _num(d.alerts_error_24h) + ' error alert(s) in the last 24 hours. Review alerts in the <strong>Logs</strong> tab.' });
                    }
                    if (_num(d.alerts_warning_24h) > 3) {
                        recs.push({ sev: 'info', icon: 'fa-bell', msg: 'Multiple warnings detected (' + _num(d.alerts_warning_24h) + ' in 24h). While not critical, these may indicate emerging issues.' });
                    }
                    if (_num(d.health_score) >= 95 && recs.length === 0) {
                        recs.push({ sev: 'success', icon: 'fa-check-circle', msg: 'Your site is running optimally. No action needed.' });
                    } else if (_num(d.health_score) >= 80 && recs.length === 0) {
                        recs.push({ sev: 'success', icon: 'fa-thumbs-up', msg: 'Your site health is good. Keep an eye on the dashboard for any changes.' });
                    }
                    return recs;
                }

                /* ---- Help content ---- */
                var _healthHelp = {
                    synch: {
                        title: 'Synch Reliability Score (30% of total) + Refresh Score (5% of total)',
                        body: '<p>This measures how reliably your site completes product synchronization cycles without errors or timeouts, and whether the daily refresh is running.</p>'
                            + '<table class="gffc-health-help-table"><tr><th>Factor</th><th>Impact</th></tr>'
                            + '<tr><td>Timeout rate</td><td>Each timeout reduces the synch score proportionally. 5+ timeouts in 24h adds a 25-point penalty.</td></tr>'
                            + '<tr><td>Change application</td><td>The percentage of expected product changes actually applied is blended in (40% weight within the synch score).</td></tr>'
                            + '<tr><td>Inactivity</td><td>No syncs in 24h but some in the past 7 days = synch score of 50. No activity in 7+ days = synch score of 0.</td></tr>'
                            + '<tr><td>Refresh freshness</td><td>The full product refresh should run at least once per day. Within 26h = 100, 1&ndash;2 days = 60, 2&ndash;3 days = 30, 3+ days = 0.</td></tr>'
                            + '</table>'
                            + '<div class="gffc-dash-help-note"><strong>How to improve:</strong> If you see frequent timeouts, increase your PHP <code>max_execution_time</code> setting (ask your host), reduce the number of products per batch in your configuration, or consider upgrading your hosting plan. If the refresh is stale, verify that your scheduled sync is running daily.</div>'
                    },
                    updates: {
                        title: 'Update Processing Score (25% of total)',
                        body: '<p>This measures the success rate of product operations (inserts, updates, and deletes) applied to your WooCommerce store. Updates can be processed via the <strong>Onsite Updater</strong> (runs directly on your server) or <strong>Cloud Sync</strong> (pushed from FFL Cockpit servers).</p>'
                            + '<table class="gffc-health-help-table"><tr><th>Factor</th><th>Impact</th></tr>'
                            + '<tr><td>Success rate</td><td>Calculated as (successful operations / total operations) &times; 100. A score of 100 means every operation succeeded.</td></tr>'
                            + '<tr><td>No activity</td><td>If no update operations were performed, the score defaults to 100 (no penalty).</td></tr>'
                            + '</table>'
                            + '<div class="gffc-dash-help-note"><strong>How to improve:</strong> Failed operations typically indicate plugin conflicts, database issues, or PHP memory limits. Check the <strong>Logs</strong> tab for specific error messages. Common fixes include disabling conflicting plugins, increasing PHP memory, or repairing your WooCommerce database.</div>'
                    },
                    alerts: {
                        title: 'Alert Health Score (25% of total)',
                        body: '<p>This reflects the severity and frequency of system alerts generated during synchronization.</p>'
                            + '<table class="gffc-health-help-table"><tr><th>Factor</th><th>Impact</th></tr>'
                            + '<tr><td>Critical alerts</td><td>First critical alert deducts <strong>25 points</strong>. Each additional deducts <strong>30 points</strong>. A single transient critical is treated as a warning; persistent criticals are severe.</td></tr>'
                            + '<tr><td>Error alerts</td><td>Each error alert in the last 24 hours deducts <strong>10 points</strong>.</td></tr>'
                            + '<tr><td>Warnings</td><td>Warnings are tracked but do not directly reduce this score.</td></tr>'
                            + '</table>'
                            + '<div class="gffc-dash-help-note"><strong>How to improve:</strong> Address critical alerts first as they have the greatest impact. Review the <strong>Logs</strong> tab to see alert details and resolve the underlying issues. Even a single critical alert will significantly lower your score.</div>'
                    },
                    conn: {
                        title: 'Connection Test Score (15% of total)',
                        body: '<p>This checks whether your site\'s REST API, WooCommerce endpoints, and authentication are working correctly so the sync service can communicate with your store.</p>'
                            + '<table class="gffc-health-help-table"><tr><th>Factor</th><th>Impact</th></tr>'
                            + '<tr><td>Tests passed</td><td>Score = (tests passed / total tests) &times; 100.</td></tr>'
                            + '<tr><td>No tests yet</td><td>If no connection test has been run, the score defaults to 100 (no penalty).</td></tr>'
                            + '</table>'
                            + '<div class="gffc-dash-help-note"><strong>How to improve:</strong> If connection tests fail, check: (1) your security plugin isn\'t blocking REST API access, (2) your SSL certificate is valid, (3) your WooCommerce REST API keys are correct in the Configuration tab, and (4) your site isn\'t behind a maintenance mode page.</div>'
                    },
                    overall: {
                        title: 'Overall Health Score',
                        body: '<p>Your overall site health score is a weighted average of four component scores:</p>'
                            + '<table class="gffc-health-help-table"><tr><th>Component</th><th>Weight</th><th>What it measures</th></tr>'
                            + '<tr><td>Synch Reliability</td><td>30%</td><td>Sync completion rate and timeout frequency</td></tr>'
                            + '<tr><td>Refresh Freshness</td><td>5%</td><td>Whether the daily full product refresh is running</td></tr>'
                            + '<tr><td>Update Processing</td><td>25%</td><td>Product operation success rate on your store</td></tr>'
                            + '<tr><td>Alert Health</td><td>25%</td><td>Severity and frequency of system alerts</td></tr>'
                            + '<tr><td>Connection Tests</td><td>15%</td><td>REST API and endpoint accessibility</td></tr>'
                            + '</table>'
                            + '<p style="margin-top:12px;"><strong>Status thresholds:</strong></p>'
                            + '<ul style="margin:4px 0 0 18px;font-size:12px;">'
                            + '<li><span style="color:#10b981;font-weight:600;">Healthy</span> &mdash; Score &ge; 80 with no critical or error alerts</li>'
                            + '<li><span style="color:#f59e0b;font-weight:600;">Degraded</span> &mdash; Score &lt; 80, or any critical or error alerts present</li>'
                            + '<li><span style="color:#ef4444;font-weight:600;">Critical</span> &mdash; Score &lt; 50 or 3+ critical alerts in 24 hours</li>'
                            + '<li><span style="color:#9ca3af;font-weight:600;">Inactive</span> &mdash; No sync or update activity in 24 hours</li>'
                            + '</ul>'
                    }
                };

                window.gffcHealthHelp = function(cat) {
                    var h = _healthHelp[cat];
                    if (!h) return;
                    var overlay = document.getElementById('gffc-health-help-overlay');
                    document.getElementById('gffc-health-help-title').textContent = h.title;
                    document.getElementById('gffc-health-help-body').innerHTML = h.body;
                    overlay.classList.add('open');
                };

                /* ---- Render functions ---- */
                function _renderBanner(d, isAdmin) {
                    var c = _hc(d.status);
                    var score = Math.round(_num(d.health_score));
                    var html = '<div class="gffc-health-banner" style="background:' + c.bg + ';border:1px solid ' + c.strip + '33;">';
                    html += '<div class="gffc-health-banner-inner">';
                    // Score circle
                    html += '<div class="gffc-health-score-circle" style="background:' + c.strip + ';color:#fff;">';
                    html += '<span style="font-size:24px;font-weight:800;line-height:1;">' + (score || '--') + '</span>';
                    html += '<span style="font-size:9px;text-transform:uppercase;letter-spacing:0.5px;opacity:0.85;">/ 100</span>';
                    html += '</div>';
                    // Info
                    html += '<div style="flex:1;min-width:0;">';
                    html += '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">';
                    html += '<span style="font-size:18px;font-weight:700;color:' + c.text + ';">' + c.label + '</span>';
                    html += _helpBtn('overall');
                    html += '</div>';
                    html += '<div style="font-size:12px;color:#64748b;margin-top:4px;">';
                    if (isAdmin && d.origin_host) {
                        var hosts = d.origin_host;
                        try { if (typeof hosts === 'string') hosts = JSON.parse(hosts); } catch(e) {}
                        if (!Array.isArray(hosts)) hosts = [hosts];
                        var links = hosts.map(function(h) {
                            h = String(h).replace(/^["'\s]+|["'\s]+$/g, '');
                            var href = h.indexOf('://') === -1 ? 'https://' + h : h;
                            return '<a href="' + href + '" target="_blank" rel="noopener" style="color:#64748b;text-decoration:underline;">' + h + '</a>';
                        });
                        html += '<span style="margin-right:12px;"><i class="fas fa-globe" style="margin-right:3px;"></i>' + links.join(' <span style="color:#cbd5e1;">|</span> ') + '</span>';
                    }
                    html += '<span style="margin-right:12px;"><i class="fas fa-sync-alt" style="margin-right:3px;"></i>Last sync: ' + _timeAgo(d.mapping_last_synch || d.last_synch_at) + '</span>';
                    var _refreshStale = _isOlderThan24h(d.mapping_last_refresh);
                    html += '<span style="margin-right:12px;' + (_refreshStale ? 'color:#ef4444;font-weight:600;' : '') + '"><i class="fas fa-redo" style="margin-right:3px;"></i>Last Daily Mapping Refresh: ' + _timeAgo(d.mapping_last_refresh) + '</span>';
                    html += '<span><i class="fas fa-database" style="margin-right:3px;"></i>' + _comma(d.total_listings) + ' listings</span>';
                    html += '</div>';
                    html += '</div></div></div>';
                    return html;
                }

                function _renderSynchCard(d, isAdmin) {
                    var score = _calcSynchScore(d);
                    var refreshScore = _num(d.refresh_score);
                    var refreshColor = refreshScore >= 80 ? '#10b981' : refreshScore >= 50 ? '#f59e0b' : '#ef4444';
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-sync-alt"></i> Synch Reliability</span>' + _helpBtn('synch') + '</div>';
                    html += '<div class="gffc-health-card-body">';
                    html += _scoreBar(score, 'Synch Score', 30);
                    html += _metricRow('Syncs (24h)', _comma(d.synch_count_24h));
                    html += _metricRow('Timeouts (24h)', _num(d.timeout_count_24h) > 0 ? '<span style="color:#ef4444;font-weight:600;">' + _num(d.timeout_count_24h) + '</span>' : '0');
                    html += _metricRow('Changes Applied (24h)', _pct(d.change_pct_applied_24h));
                    html += _metricRow('Last Sync', _timeAgo(d.mapping_last_synch || d.last_synch_at));
                    var refreshStale = _isOlderThan24h(d.mapping_last_refresh);
                    var refreshAgoStr = _timeAgo(d.mapping_last_refresh);
                    var refreshDur = _num(d.last_refresh_duration_minutes);
                    var refreshVal = (refreshStale ? '<span style="color:#ef4444;font-weight:600;">' + refreshAgoStr + '</span>' : refreshAgoStr)
                        + (refreshDur > 0 ? ' <span style="color:#94a3b8;">(' + refreshDur.toFixed(1) + ' min)</span>' : '');
                    html += _metricRow('Last Daily Mapping Refresh', refreshVal);
                    html += _scoreBar(refreshScore, 'Refresh Score', 5);
                    // Admin-only rows
                    if (isAdmin) {
                        html += '<div class="gffc-health-admin-divider"></div>';
                        html += _metricRow('Syncs (7d / 30d)', _comma(d.synch_count_7d) + ' / ' + _comma(d.synch_count_30d), true);
                        html += _metricRow('Timeouts (7d / 30d)', _num(d.timeout_count_7d) + ' / ' + _num(d.timeout_count_30d), true);
                        html += _metricRow('Avg Duration (24h)', _num(d.avg_elapsed_seconds_24h).toFixed(1) + 's', true);
                        html += _metricRow('Avg Duration (7d)', _num(d.avg_elapsed_seconds_7d).toFixed(1) + 's', true);
                        html += _metricRow('Changes Applied (7d)', _pct(d.change_pct_applied_7d), true);
                        html += _metricRow('Changes Applied (30d)', _pct(d.change_pct_applied_30d), true);
                        if (_num(d.last_refresh_product_count) > 0) html += _metricRow('Refresh Products', _comma(d.last_refresh_product_count), true);
                        if (_num(d.last_refresh_duration_minutes) > 0) html += _metricRow('Refresh Duration', _num(d.last_refresh_duration_minutes).toFixed(1) + ' min', true);
                    }
                    html += '</div></div>';
                    return html;
                }

                function _renderUpdateCard(d, isAdmin) {
                    var score = _calcOnsiteScore(d);
                    var usesOnsite = d.uses_onsite_updates;
                    var modeLabel = usesOnsite ? 'Onsite Updater' : 'Cloud Sync';
                    var modeIcon = usesOnsite ? 'fa-server' : 'fa-cloud';
                    var modeColor = usesOnsite ? '#6366f1' : '#3b82f6';
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-cogs"></i> Update Processing</span>' + _helpBtn('updates') + '</div>';
                    html += '<div class="gffc-health-card-body">';
                    html += '<div style="margin-bottom:8px;"><span style="display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:600;color:' + modeColor + ';background:' + modeColor + '14;padding:2px 8px;border-radius:10px;"><i class="fas ' + modeIcon + '" style="font-size:10px;"></i> ' + modeLabel + '</span></div>';
                    var totalOps = _num(d.insert_successful_24h) + _num(d.insert_failed_24h) + _num(d.update_successful_24h) + _num(d.update_failed_24h) + _num(d.delete_successful_24h) + _num(d.delete_failed_24h);
                    var jobs24 = _num(d.onsite_jobs_24h);
                    var synchs24 = _num(d.synch_count_24h);
                    var timeouts24 = _num(d.timeout_count_24h);
                    var healthySyncs = synchs24 > 0 && timeouts24 < synchs24;
                    var hasRecentActivity = healthySyncs || jobs24 > 0;
                    if (totalOps === 0 && !hasRecentActivity) {
                        // Site is not communicating - don't show misleading green score
                        html += '<div style="text-align:center;padding:14px 0;color:#ef4444;font-size:12px;line-height:1.5;"><i class="fas fa-exclamation-triangle" style="margin-right:4px;font-size:14px;"></i><strong>No update activity detected</strong><br><span style="color:#64748b;">No successful syncs or update jobs in the last 24 hours. The site may not be communicating with FFL Cockpit.</span></div>';
                    } else {
                        html += _scoreBar(score, 'Update Score', 25);
                    }
                    html += _metricRow('Total Listings', _comma(d.total_listings));
                    if (totalOps === 0 && hasRecentActivity) {
                        html += '<div style="text-align:center;padding:12px 0;color:#10b981;font-size:12px;"><i class="fas fa-check-circle" style="margin-right:4px;"></i>All products are in sync &mdash; no updates needed in the last 24h</div>';
                    } else {
                        html += _metricRow('Inserts', '<span style="color:#10b981;">' + _num(d.insert_successful_24h) + ' OK</span>' + (_num(d.insert_failed_24h) > 0 ? ' / <span style="color:#ef4444;">' + _num(d.insert_failed_24h) + ' failed</span>' : ''));
                        html += _metricRow('Updates', '<span style="color:#10b981;">' + _num(d.update_successful_24h) + ' OK</span>' + (_num(d.update_failed_24h) > 0 ? ' / <span style="color:#ef4444;">' + _num(d.update_failed_24h) + ' failed</span>' : ''));
                        html += _metricRow('Deletes', '<span style="color:#10b981;">' + _num(d.delete_successful_24h) + ' OK</span>' + (_num(d.delete_failed_24h) > 0 ? ' / <span style="color:#ef4444;">' + _num(d.delete_failed_24h) + ' failed</span>' : ''));
                        html += _metricRow('Success Rate', '<span style="font-weight:600;color:' + (score >= 95 ? '#10b981' : score >= 70 ? '#f59e0b' : '#ef4444') + ';">' + score.toFixed(1) + '%</span>');
                    }
                    // Job runtime metrics
                    if (_num(d.onsite_jobs_24h) > 0) {
                        var avgD = _num(d.avg_onsite_elapsed_24h);
                        var minD = _num(d.min_onsite_elapsed_24h);
                        var maxD = _num(d.max_onsite_elapsed_24h);
                        // Get max_execution_time from server stats if available
                        var maxExecTime = (d.server_stats && d.server_stats.php_config) ? Number(d.server_stats.php_config.max_execution_time) : 0;
                        var maxExecLabel = maxExecTime > 0 ? ' <span style="color:#94a3b8;font-size:10px;">(limit: ' + maxExecTime + 's)</span>' : '';
                        var maxColor = maxD >= 60 ? (maxExecTime > 0 && maxD >= maxExecTime * 0.8 ? '#ef4444' : '#f59e0b') : '';
                        html += _metricRow('Job Runtime (avg)', avgD.toFixed(1) + 's');
                        html += _metricRow('Job Runtime (min / max)', minD.toFixed(1) + 's / ' + (maxColor ? '<span style="color:' + maxColor + ';font-weight:600;">' + maxD.toFixed(1) + 's</span>' : maxD.toFixed(1) + 's') + maxExecLabel);
                        // Warning if max_execution_time is below the recommended 300s
                        if (maxExecTime > 0 && maxExecTime < 300) {
                            var sevColor = maxD >= maxExecTime ? '#ef4444' : '#f59e0b';
                            html += '<details style="margin-top:6px;"><summary style="cursor:pointer;font-size:11px;font-weight:600;color:' + sevColor + ';"><i class="fas fa-exclamation-triangle" style="margin-right:4px;"></i>'
                                + 'PHP max_execution_time is ' + maxExecTime + 's (recommended: 300s)</summary>';
                            html += '<div style="font-size:11px;color:#475569;margin-top:4px;line-height:1.5;">';
                            html += '<p style="margin:0 0 6px;">Your PHP <code>max_execution_time</code> is set to <strong>' + maxExecTime + 's</strong>. '
                                + 'FFL Cockpit recommends <strong>300s or higher</strong>. '
                                + 'When a job exceeds this limit, PHP terminates the process mid-update, which can cause incomplete product updates or failed operations.</p>';
                            html += '<p style="margin:0 0 4px;font-weight:600;">How to increase max_execution_time:</p>';
                            html += '<ul style="margin:0 0 0 16px;padding:0;">';
                            html += '<li><strong>cPanel / Hosting Dashboard:</strong> Look for "PHP Settings" or "MultiPHP INI Editor" and increase <code>max_execution_time</code> to 300 or higher.</li>';
                            html += '<li><strong>wp-config.php:</strong> Add <code>set_time_limit(300);</code> before the "That\'s all" comment.</li>';
                            html += '<li><strong>php.ini:</strong> Set <code>max_execution_time = 300</code></li>';
                            html += '<li><strong>.htaccess:</strong> Add <code>php_value max_execution_time 300</code></li>';
                            html += '<li><strong>Contact your host:</strong> Some managed hosts (WP Engine, Flywheel, etc.) require a support request to change this setting.</li>';
                            html += '</ul></div></details>';
                        }
                    }
                    if (isAdmin) {
                        html += '<div class="gffc-health-admin-divider"></div>';
                        html += _metricRow('Jobs (24h)', _comma(d.onsite_jobs_24h), true);
                        html += _metricRow('Last Job', _timeAgo(d.last_onsite_at), true);
                    }
                    html += '</div></div>';
                    return html;
                }

                function _renderAlertCard(d, isAdmin) {
                    var score = _calcAlertScore(d);
                    var crit24 = _num(d.alerts_critical_24h);
                    var err24 = _num(d.alerts_error_24h);
                    var warn24 = _num(d.alerts_warning_24h);
                    var crit7 = _num(d.alerts_critical_7d);
                    var crit30 = _num(d.alerts_critical_30d);
                    var err7 = _num(d.alerts_error_7d);
                    var err30 = _num(d.alerts_error_30d);
                    var warn7 = _num(d.alerts_warning_7d);
                    var warn30 = _num(d.alerts_warning_30d);
                    var total24 = crit24 + err24 + warn24;
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-bell"></i> Alert Health</span>' + _helpBtn('alerts') + '</div>';
                    html += '<div class="gffc-health-card-body">';
                    html += _scoreBar(score, 'Alert Score', 25);
                    if (total24 === 0 && crit7 === 0 && err7 === 0) {
                        html += '<div style="text-align:center;padding:8px 0;color:#10b981;font-size:12px;"><i class="fas fa-check-circle" style="margin-right:4px;"></i>No alerts in the last 24 hours</div>';
                    } else if (total24 === 0 && (crit7 > 0 || err7 > 0)) {
                        html += '<div style="text-align:center;padding:8px 0;color:#f59e0b;font-size:12px;"><i class="fas fa-exclamation-circle" style="margin-right:4px;"></i>Clear in the last 24h, but ' + (crit7 > 0 ? crit7 + ' critical' : '') + (crit7 > 0 && err7 > 0 ? ' and ' : '') + (err7 > 0 ? err7 + ' error' : '') + ' alert' + ((crit7 + err7) > 1 ? 's' : '') + ' in the last 7 days</div>';
                    } else {
                        if (isAdmin) {
                            html += _metricRow('Critical (24h)', crit24 > 0 ? '<span style="color:#ef4444;font-weight:700;">' + crit24 + '</span>' : '0', true);
                        }
                        html += _metricRow('Errors (24h)', err24 > 0 ? '<span style="color:#f97316;font-weight:600;">' + err24 + '</span>' : '0');
                        html += _metricRow('Warnings (24h)', warn24 > 0 ? '<span style="color:#eab308;">' + warn24 + '</span>' : '0');
                    }
                    if (isAdmin) {
                        html += '<div class="gffc-health-admin-divider"></div>';
                        var c7Style = crit7 > 0 ? 'color:#ef4444;font-weight:700;' : '';
                        var c30Style = crit30 > 0 ? 'color:#ef4444;font-weight:700;' : '';
                        var e7Style = err7 > 0 ? 'color:#f97316;font-weight:600;' : '';
                        var e30Style = err30 > 0 ? 'color:#f97316;font-weight:600;' : '';
                        html += _metricRow('Critical (7d / 30d)', '<span style="' + c7Style + '">' + crit7 + '</span> / <span style="' + c30Style + '">' + crit30 + '</span>', true);
                        html += _metricRow('Errors (7d / 30d)', '<span style="' + e7Style + '">' + err7 + '</span> / <span style="' + e30Style + '">' + err30 + '</span>', true);
                        html += _metricRow('Warnings (7d / 30d)', warn7 + ' / ' + warn30, true);
                        if (d.most_recent_alert_subject) {
                            html += _metricRow('Latest Alert', '<span title="' + (d.most_recent_alert_type || '') + '">' + d.most_recent_alert_subject + '</span> <span style="color:#94a3b8;font-size:11px;">' + _timeAgo(d.most_recent_alert_at) + '</span>', true);
                        }
                        // Recent alerts table
                        if (d.recent_alerts && d.recent_alerts.length > 0) {
                            html += '<details class="gffc-health-alerts-details" style="margin-top:8px;">';
                            html += '<summary style="cursor:pointer;font-size:12px;font-weight:600;color:#6366f1;">View Recent Alerts (' + d.recent_alerts.length + ')</summary>';
                            html += '<div style="max-height:350px;overflow-y:auto;margin-top:6px;">';
                            d.recent_alerts.forEach(function(a, idx) {
                                var sevCol = a.severity === 'critical' ? '#ef4444' : a.severity === 'error' ? '#f97316' : '#eab308';
                                var sevBg = a.severity === 'critical' ? '#fef2f2' : a.severity === 'error' ? '#fff7ed' : '#fefce8';
                                html += '<div style="border:1px solid #e5e7eb;border-radius:6px;padding:8px 10px;margin-bottom:6px;background:' + sevBg + ';">';
                                html += '<div style="display:flex;justify-content:space-between;align-items:center;gap:8px;">';
                                html += '<div><span style="color:' + sevCol + ';font-weight:700;font-size:11px;text-transform:uppercase;">' + (a.severity || '') + '</span>';
                                html += ' <span style="font-weight:600;font-size:12px;color:#1e293b;">' + (a.subject || '') + '</span></div>';
                                html += '<span style="color:#94a3b8;font-size:11px;white-space:nowrap;">' + _timeAgo(a.created_at) + '</span>';
                                html += '</div>';
                                if (a.message) {
                                    html += '<div style="margin-top:4px;font-size:11px;color:#475569;word-break:break-word;">' + (a.message || '').replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</div>';
                                }
                                if (a.detail) {
                                    var detailStr = typeof a.detail === 'string' ? a.detail : JSON.stringify(a.detail, null, 2);
                                    html += '<details style="margin-top:4px;"><summary style="cursor:pointer;font-size:10px;color:#6366f1;font-weight:600;">Detail</summary>';
                                    html += '<pre style="margin:4px 0 0;padding:6px;background:#f1f5f9;border-radius:4px;font-size:10px;color:#334155;white-space:pre-wrap;word-break:break-word;max-height:150px;overflow-y:auto;">' + detailStr.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</pre></details>';
                                }
                                html += '</div>';
                            });
                            html += '</div></details>';
                        }
                    }
                    html += '</div></div>';
                    return html;
                }

                function _renderConnCard(d) {
                    var score = _calcConnScore(d);
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-plug"></i> Connection Tests</span>' + _helpBtn('conn') + '</div>';
                    html += '<div class="gffc-health-card-body">';
                    html += _scoreBar(score, 'Connection Score', 15);
                    html += _metricRow('Tests Passed', _num(d.conn_tests_passed) + ' / ' + _num(d.conn_tests_total));
                    html += _metricRow('Last Tested', _timeAgo(d.conn_tested_at));
                    // Run tests button
                    html += '<div style="margin-top:8px;margin-bottom:8px;">';
                    html += '<button type="button" id="gffc-run-conn-tests-btn" class="button" onclick="gffcRunConnectionTests()" style="font-size:11px;padding:2px 10px;">';
                    html += '<i class="fas fa-play-circle" style="margin-right:4px;"></i>Run Connection Tests</button>';
                    html += '</div>';
                    // Test results container
                    html += '<div id="gffc-conn-test-results">';
                    html += _renderConnTestDetails(d.conn_test_details);
                    html += '</div>';
                    html += '</div></div>';
                    return html;
                }

                function _renderConnTestDetails(details) {
                    var html = '';
                    if (details && typeof details === 'object') {
                        var items = Array.isArray(details) ? details : Object.keys(details).map(function(k) { var v = details[k]; return typeof v === 'object' ? v : { name: k, passed: v }; });
                        if (items.length > 0) {
                            items.forEach(function(t) {
                                var passed = t.passed === true;
                                var icon = passed ? '<i class="fas fa-check-circle" style="color:#10b981;"></i>' : '<i class="fas fa-times-circle" style="color:#ef4444;"></i>';
                                var name = t.name || 'Unknown Test';
                                html += '<div class="gffc-health-test-row">' + icon + ' <span>' + name + '</span></div>';
                                if (!passed && t.message) {
                                    html += '<div style="margin-left:22px;font-size:11px;color:#64748b;margin-bottom:2px;">' + t.message + '</div>';
                                }
                                if (!passed && t.hint) {
                                    html += '<div style="margin-left:22px;font-size:11px;color:#dc2626;margin-bottom:4px;">' + t.hint + '</div>';
                                }
                            });
                        }
                    }
                    return html;
                }

                window.gffcRunConnectionTests = function() {
                    var btn = document.getElementById('gffc-run-conn-tests-btn');
                    var resultsDiv = document.getElementById('gffc-conn-test-results');
                    if (!btn || !resultsDiv) return;

                    var d = window.gFFLCockpit._healthData;
                    var targetKey = (d && d.api_key) ? d.api_key : "<?php echo esc_js($gFFLCockpitKey); ?>";
                    var authKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";

                    // Record the current tested_at so we know when new results arrive
                    var previousTestedAt = (d && d.conn_tested_at) ? d.conn_tested_at : null;

                    btn.disabled = true;
                    btn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right:4px;"></i>Running tests...';
                    resultsDiv.innerHTML = '<div style="color:#64748b;font-size:11px;padding:4px 0;"><i class="fas fa-spinner fa-spin" style="margin-right:4px;"></i>Running connection tests — this typically takes 30-60 seconds...</div>';

                    // Step 1: Kick off async
                    fetch("https://ffl-api.garidium.com", {
                        method: "POST",
                        headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": authKey },
                        body: JSON.stringify({ "action": "run_connection_tests_async", "data": { "api_key": targetKey } })
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(resp) {
                        if (!resp || resp.status !== 'started') {
                            throw new Error('Failed to start tests');
                        }
                        // Step 2: Poll for results
                        var pollCount = 0;
                        var maxPolls = 24; // 24 * 5s = 120s max
                        var pollInterval = setInterval(function() {
                            pollCount++;
                            var elapsed = pollCount * 5;
                            resultsDiv.innerHTML = '<div style="color:#64748b;font-size:11px;padding:4px 0;"><i class="fas fa-spinner fa-spin" style="margin-right:4px;"></i>Running connection tests... (' + elapsed + 's)</div>';

                            if (pollCount > maxPolls) {
                                clearInterval(pollInterval);
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fas fa-play-circle" style="margin-right:4px;"></i>Run Connection Tests';
                                resultsDiv.innerHTML = '<div style="color:#ef4444;font-size:11px;"><i class="fas fa-exclamation-triangle" style="margin-right:4px;"></i>Tests timed out after 2 minutes. The site may be unreachable or very slow.</div>';
                                return;
                            }

                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": authKey },
                                body: JSON.stringify({ "action": "get_connection_test_status", "data": { "api_key": targetKey } })
                            })
                            .then(function(r) { return r.json(); })
                            .then(function(status) {
                                if (!status || !status.tested_at) return; // no results yet
                                // Check if tested_at is newer than what we had before
                                if (previousTestedAt && status.tested_at <= previousTestedAt) return; // still old results

                                // New results arrived
                                clearInterval(pollInterval);
                                btn.disabled = false;
                                btn.innerHTML = '<i class="fas fa-play-circle" style="margin-right:4px;"></i>Run Connection Tests';

                                var testDetails = status.test_details || [];
                                var passed = Number(status.tests_passed) || 0;
                                var total = Number(status.tests_total) || 0;

                                var html = '<div style="font-size:11px;color:#10b981;margin-bottom:6px;font-weight:600;"><i class="fas fa-check-circle" style="margin-right:3px;"></i>Tests completed: ' + passed + ' / ' + total + ' passed</div>';
                                html += _renderConnTestDetails(testDetails);

                                var tips = status.troubleshooting_tips;
                                if (tips && Array.isArray(tips) && tips.length > 0) {
                                    html += '<details style="margin-top:8px;"><summary style="cursor:pointer;font-size:11px;font-weight:600;color:#6366f1;">Troubleshooting Tips</summary>';
                                    html += '<ul style="margin:4px 0 0;padding-left:16px;font-size:11px;color:#475569;">';
                                    tips.forEach(function(tip) { html += '<li style="margin-bottom:4px;">' + tip + '</li>'; });
                                    html += '</ul></details>';
                                }

                                resultsDiv.innerHTML = html;
                            })
                            .catch(function() { /* poll error, will retry next interval */ });
                        }, 5000);
                    })
                    .catch(function(err) {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fas fa-play-circle" style="margin-right:4px;"></i>Run Connection Tests';
                        resultsDiv.innerHTML = '<div style="color:#ef4444;font-size:11px;"><i class="fas fa-exclamation-triangle" style="margin-right:4px;"></i>Failed to start tests: ' + (err.message || err) + '</div>';
                    });
                };

                function _renderRecs(d, isAdmin) {
                    var recs = _generateRecs(d, isAdmin);
                    if (recs.length === 0) return '';
                    var sevColors = { critical: '#fef2f2;border-left-color:#ef4444', warning: '#fffbeb;border-left-color:#f59e0b', info: '#f0f9ff;border-left-color:#3b82f6', success: '#f0fdf4;border-left-color:#10b981' };
                    var html = '<div style="margin-top:16px;">';
                    html += '<div style="font-size:14px;font-weight:700;color:#334155;margin-bottom:8px;"><i class="fas fa-lightbulb" style="color:#f59e0b;margin-right:6px;"></i>Recommendations</div>';
                    recs.forEach(function(r) {
                        html += '<div class="gffc-health-recommendation" style="background:' + (sevColors[r.sev] || sevColors.info) + ';">';
                        html += '<i class="fas ' + r.icon + '" style="margin-right:8px;flex-shrink:0;margin-top:2px;"></i>';
                        html += '<span>' + r.msg + '</span></div>';
                    });
                    html += '</div>';
                    return html;
                }

                function _renderContactCard(d) {
                    var c = d.contact;
                    if (!c) return '';
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-user"></i> Account Info</span></div>';
                    html += '<div class="gffc-health-card-body">';
                    if (c.contact_name) html += _metricRow('Contact', c.contact_name);
                    if (c.contact_email) html += _metricRow('Email', '<a href="mailto:' + c.contact_email + '" style="color:#3b82f6;">' + c.contact_email + '</a>');
                    if (c.key_name) html += _metricRow('Key Name', c.key_name);
                    if (c.customer_id) html += _metricRow('Customer ID', c.customer_id);
                    if (c.wordpress_host) html += _metricRow('WordPress Host', c.wordpress_host);
                    if (c.subscription_start) html += _metricRow('Subscribed', c.subscription_start);
                    if (c.cancelled) html += _metricRow('Status', '<span style="color:#ef4444;font-weight:600;">Cancelled</span>');
                    html += '</div></div>';
                    return html;
                }

                function _renderServerCard(d) {
                    var ss = d.server_stats;
                    if (!ss) return '';
                    var html = '<div class="gffc-health-card">';
                    html += '<div class="gffc-health-card-header"><span><i class="fas fa-server"></i> Server Environment</span></div>';
                    html += '<div class="gffc-health-card-body">';
                    if (d.server_stats_updated_at) html += _metricRow('Last Reported', _timeAgo(d.server_stats_updated_at));
                    // Plugin
                    if (ss.plugin) {
                        html += _metricRow('Plugin Version', ss.plugin.version || '--');
                    }
                    // Server
                    if (ss.server) {
                        html += _metricRow('PHP Version', ss.server.php_version || '--');
                        html += _metricRow('OS', ss.server.operating_system || '--');
                        if (ss.server.server_load) {
                            var loadParts = String(ss.server.server_load).split(',').map(function(v) { return parseFloat(v).toFixed(2); });
                            if (loadParts.length === 3) {
                                html += _metricRow('Load Avg (1 / 5 / 15m)', loadParts.join(' / '));
                            } else {
                                html += _metricRow('Server Load', ss.server.server_load);
                            }
                        }
                    }
                    // Memory
                    if (ss.memory_usage) {
                        var mu = ss.memory_usage;
                        html += _metricRow('Memory', (mu.current_formatted || '--') + ' / ' + (mu.limit_formatted || '--'));
                        if (mu.usage_percentage != null) {
                            var memPct = Number(mu.usage_percentage);
                            var memCol = memPct >= 90 ? '#ef4444' : memPct >= 70 ? '#f59e0b' : '#10b981';
                            html += _metricRow('Memory Usage', '<span style="color:' + memCol + ';font-weight:600;">' + memPct.toFixed(1) + '%</span>');
                        }
                    }
                    // PHP Config
                    if (ss.php_config) {
                        var pc = ss.php_config;
                        html += _metricRow('max_execution_time', pc.max_execution_time || '--');
                        html += _metricRow('memory_limit', pc.memory_limit || '--');
                        html += _metricRow('post_max_size', pc.post_max_size || '--');
                        if (pc.opcache) html += _metricRow('OPcache', pc.opcache.enabled ? '<span style="color:#10b981;">Enabled</span>' : '<span style="color:#f59e0b;">Disabled</span>');
                    }
                    // Database
                    if (ss.database) {
                        html += _metricRow('MySQL Version', ss.database.version || '--');
                        if (ss.database.size) html += _metricRow('DB Size', ss.database.size);
                    }
                    // Disk
                    if (ss.disk_space) {
                        var ds = ss.disk_space;
                        html += _metricRow('Disk Free', ds.free_formatted || '--');
                        if (ds.used_percentage != null) {
                            var diskPct = Number(ds.used_percentage);
                            var diskCol = diskPct >= 90 ? '#ef4444' : diskPct >= 70 ? '#f59e0b' : '#10b981';
                            html += _metricRow('Disk Used', '<span style="color:' + diskCol + ';font-weight:600;">' + diskPct.toFixed(1) + '%</span>');
                        }
                    }
                    // Active Plugins
                    var wp = ss.wordpress;
                    var plugins = wp && wp.active_plugins;
                    if (plugins && Array.isArray(plugins) && plugins.length > 0) {
                        html += '<details style="margin-top:8px;"><summary style="cursor:pointer;font-size:12px;font-weight:600;color:#6366f1;"><i class="fas fa-puzzle-piece" style="margin-right:4px;"></i>Active Plugins (' + plugins.length + ')</summary>';
                        html += '<div style="max-height:250px;overflow-y:auto;margin-top:6px;">';
                        plugins.forEach(function(p) {
                            html += '<div style="border:1px solid #e2e8f0;border-radius:5px;padding:6px 8px;margin-bottom:4px;background:#f8fafc;">';
                            html += '<div style="display:flex;justify-content:space-between;align-items:center;">';
                            html += '<span style="font-size:12px;font-weight:600;color:#1e293b;">' + (p.name || 'Unknown') + '</span>';
                            html += '<span style="font-size:10px;color:#64748b;background:#e2e8f0;padding:1px 6px;border-radius:8px;">' + (p.version || '?') + '</span>';
                            html += '</div>';
                            if (p.author) html += '<div style="font-size:10px;color:#94a3b8;">by ' + p.author + '</div>';
                            html += '</div>';
                        });
                        html += '</div></details>';
                    }
                    html += '</div></div>';
                    return html;
                }

                function _renderDashboard(d) {
                    var isAdmin = window.gFFLCockpit.isAdmin;
                    var html = _renderBanner(d, isAdmin);
                    // Quarantine alert
                    if (_num(d.quarantine) > 0) {
                        html += '<div style="margin:12px 0;padding:14px 16px;background:#fef2f2;border:2px solid #ef4444;border-radius:8px;display:flex;align-items:flex-start;gap:12px;">';
                        html += '<div style="flex-shrink:0;width:40px;height:40px;background:#ef4444;border-radius:50%;display:flex;align-items:center;justify-content:center;"><i class="fas fa-exclamation-triangle" style="color:#fff;font-size:18px;"></i></div>';
                        html += '<div>';
                        html += '<div style="font-size:15px;font-weight:800;color:#991b1b;margin-bottom:4px;">Site is in Quarantine Mode</div>';
                        html += '<div style="font-size:12px;color:#7f1d1d;line-height:1.5;">';
                        html += 'This site has been automatically placed in <strong>quarantine</strong> due to excessive sync timeouts. ';
                        html += 'When a site repeatedly times out during synchronization, FFL Cockpit temporarily pauses sync operations to prevent further resource strain on the hosting server and to avoid cascading failures.</div>';
                        html += '<div style="font-size:12px;color:#991b1b;margin-top:8px;line-height:1.5;">';
                        html += '<strong>What this means:</strong> Instead of the normal sync schedule, this site is being synced on a reduced <strong>every-4-hour</strong> schedule to minimize strain on the server while still keeping inventory reasonably up to date.</div>';
                        html += '<div style="font-size:12px;color:#991b1b;margin-top:8px;line-height:1.5;">';
                        html += '<strong>How to resolve:</strong> Once the 4-hour syncs start completing successfully without timeouts, quarantine mode is <strong>automatically removed</strong> and the normal sync schedule resumes. To speed up recovery:';
                        html += '<ul style="margin:4px 0 0 16px;padding:0;">';
                        html += '<li>Increase PHP <code>max_execution_time</code> (ask your hosting provider) &mdash; 120 seconds or higher recommended</li>';
                        html += '<li>Increase PHP <code>memory_limit</code> to at least 512M</li>';
                        html += '<li>Check for plugin conflicts that slow down WooCommerce REST API responses</li>';
                        html += '<li>Consider upgrading to a higher-tier hosting plan if the server is resource-constrained</li>';
                        html += '</ul></div>';
                        html += '</div></div>';
                    }
                    html += '<div class="gffc-health-grid">';
                    html += _renderSynchCard(d, isAdmin);
                    html += _renderUpdateCard(d, isAdmin);
                    html += _renderAlertCard(d, isAdmin);
                    html += _renderConnCard(d);
                    if (isAdmin && d.server_stats) html += _renderServerCard(d);
                    if (isAdmin && d.contact) html += _renderContactCard(d);
                    html += '</div>';
                    html += _renderRecs(d, isAdmin);
                    // Recent logs section
                    html += '<div style="margin-top:16px;">';
                    html += '<div style="font-size:14px;font-weight:700;color:#334155;margin-bottom:8px;"><i class="fas fa-terminal" style="color:#64748b;margin-right:6px;"></i>Recent Sync Logs (last hour)</div>';
                    html += '<div id="gffc-health-logs" style="background:#0b0b0b;border-radius:6px;padding:10px;max-height:300px;overflow-y:auto;font-family:monospace;font-size:11px;line-height:1.5;color:#a1e89f;">';
                    html += '<span style="color:#64748b;">Loading logs...</span>';
                    html += '</div></div>';
                    // Onsite process status (only if site uses onsite updates)
                    if (d.uses_onsite_updates) {
                        html += '<div style="margin-top:16px;">';
                        html += '<div style="font-size:14px;font-weight:700;color:#334155;margin-bottom:8px;"><i class="fas fa-server" style="color:#6366f1;margin-right:6px;"></i>Onsite Process Status</div>';
                        html += '<div id="gffc-health-onsite-status" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;padding:12px;font-size:12px;color:#334155;">';
                        html += '<span style="color:#94a3b8;"><i class="fas fa-spinner fa-spin" style="margin-right:4px;"></i>Loading onsite status...</span>';
                        html += '</div></div>';
                    }
                    return html;
                }

                function _b64toBytes(b64) {
                    var bin = atob(b64);
                    var bytes = new Uint8Array(bin.length);
                    for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
                    return bytes;
                }

                function _gunzip(bytes) {
                    var ds = new DecompressionStream('gzip');
                    return new Response(new Blob([bytes]).stream().pipeThrough(ds)).arrayBuffer()
                        .then(function(ab) { return new TextDecoder().decode(ab); });
                }

                function _parseLogsResponse(text) {
                    // Unwrap: keep parsing until we get an object (handles double-encoded JSON strings)
                    var obj = text;
                    for (var i = 0; i < 5; i++) {
                        if (typeof obj !== 'string') break;
                        try { obj = JSON.parse(obj); } catch(e) { break; }
                    }
                    if (obj && typeof obj === 'object' && obj.logs) return Promise.resolve(obj);
                    // If body is a nested string, unwrap that too
                    if (obj && typeof obj === 'object' && obj.body && typeof obj.body === 'string') {
                        var inner = obj.body;
                        for (var j = 0; j < 5; j++) {
                            if (typeof inner !== 'string') break;
                            try { inner = JSON.parse(inner); } catch(e) { break; }
                        }
                        if (inner && typeof inner === 'object' && inner.logs) return Promise.resolve(inner);
                        // body might be base64+gzip
                        try {
                            return _gunzip(_b64toBytes(obj.body.trim())).then(function(t) { return JSON.parse(t); });
                        } catch(e) {}
                    }
                    // Maybe the whole response is base64+gzip
                    try {
                        return _gunzip(_b64toBytes(String(text).trim())).then(function(t) { return JSON.parse(t); });
                    } catch(e) {}
                    return Promise.resolve(null);
                }

                function _loadHealthLogs(apiKey) {
                    var targetKey = apiKey || "<?php echo esc_js($gFFLCockpitKey); ?>";
                    var authKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";
                    console.log('[HealthLogs] Fetching logs for key:', targetKey.substring(0, 10) + '...');
                    fetch("https://ffl-api.garidium.com", {
                        method: "POST",
                        headers: {
                            "Accept": "application/json",
                            "Content-Type": "application/json",
                            "x-api-key": authKey
                        },
                        body: JSON.stringify({ "action": "get_logs", "data": { "api_key": targetKey, "minutes_back": 60, "target": "woo" } })
                    })
                    .then(function(r) { return r.text(); })
                    .then(function(text) {
                        console.log('[HealthLogs] Raw response length:', text.length, 'first 200 chars:', text.substring(0, 200));
                        return _parseLogsResponse(text);
                    })
                    .then(function(data) {
                        console.log('[HealthLogs] Parsed data:', data ? 'count=' + (data.count || 0) + ' logs=' + ((data.logs || []).length) : 'null');
                        var container = document.getElementById('gffc-health-logs');
                        if (!container) return;
                        var logs = (data && data.logs) ? data.logs : [];
                        if (logs.length === 0) {
                            container.innerHTML = '<span style="color:#64748b;">No WooCommerce sync logs in the last hour.</span>';
                            return;
                        }
                        var html = '';
                        logs.forEach(function(log) {
                            var ts = '';
                            try {
                                var d = new Date(log.timestamp);
                                ts = d.toLocaleTimeString();
                            } catch(e) { ts = log.timestamp || ''; }
                            var msg = (log.message || '').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                            var lineColor = '#a1e89f';
                            if (/error|fail|exception/i.test(msg)) lineColor = '#ef4444';
                            else if (/warn|timeout/i.test(msg)) lineColor = '#f59e0b';
                            else if (/<<<|>>>/i.test(msg)) lineColor = '#64748b';
                            html += '<div style="color:' + lineColor + ';"><span style="color:#e6ffe6;margin-right:8px;">' + ts + '</span>' + msg + '</div>';
                        });
                        container.innerHTML = html;
                        container.scrollTop = container.scrollHeight;
                    })
                    .catch(function(err) {
                        console.error("Error fetching health logs:", err);
                        var container = document.getElementById('gffc-health-logs');
                        if (container) container.innerHTML = '<span style="color:#ef4444;">Failed to load logs: ' + (err.message || err) + '</span>';
                    });
                }

                function _loadOnsiteStatus(apiKey) {
                    var targetKey = apiKey || "<?php echo esc_js($gFFLCockpitKey); ?>";
                    var authKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";
                    fetch("https://ffl-api.garidium.com", {
                        method: "POST",
                        headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": authKey },
                        body: JSON.stringify({ "action": "get_onsite_process_status", "data": { "api_key": targetKey } })
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        var container = document.getElementById('gffc-health-onsite-status');
                        if (!container) return;
                        if (!data || data.error) {
                            container.innerHTML = '<span style="color:#ef4444;">' + (data && data.error ? data.error : 'Failed to retrieve onsite status.') + '</span>';
                            return;
                        }
                        var html = '';
                        // Status badge
                        var st = (data.status || 'unknown').toLowerCase();
                        if (st === 'no status available.' || st === 'no status available') st = 'idle';
                        var stColor = st === 'processing' ? '#3b82f6' : st === 'completed' ? '#10b981' : st === 'queued' ? '#f59e0b' : st === 'stopped' || st.indexOf('stopped') >= 0 ? '#ef4444' : st === 'idle' ? '#94a3b8' : '#94a3b8';
                        html += '<div style="margin-bottom:8px;"><span style="display:inline-flex;align-items:center;gap:4px;font-size:11px;font-weight:700;color:#fff;background:' + stColor + ';padding:2px 10px;border-radius:10px;text-transform:uppercase;">';
                        if (st === 'processing') html += '<i class="fas fa-spinner fa-spin" style="font-size:9px;"></i> ';
                        html += st + '</span>';
                        if (data.plugin_version) html += ' <span style="font-size:10px;color:#94a3b8;">v' + data.plugin_version + '</span>';
                        html += '</div>';
                        if (st === 'idle') {
                            html += '<div style="font-size:11px;color:#94a3b8;">No onsite processing activity. The queue is empty.</div>';
                            container.innerHTML = html;
                            return;
                        }
                        // Timing
                        if (data.start_time_utc) html += '<div style="font-size:11px;color:#64748b;margin-bottom:6px;">Started: ' + _timeAgo(data.start_time_utc) + '</div>';
                        // Progress summary
                        var queued = Number(data.queued || 0);
                        var processed = Number(data.processed || 0);
                        var remaining = Number(data.remaining || 0);
                        if (queued > 0) {
                            var pctDone = queued > 0 ? Math.round((processed / queued) * 100) : 0;
                            html += '<div style="margin-bottom:8px;">';
                            html += '<div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:2px;"><span>Progress</span><span style="font-weight:600;">' + processed + ' / ' + queued + ' (' + pctDone + '%)</span></div>';
                            html += '<div style="background:#e2e8f0;border-radius:4px;height:6px;overflow:hidden;"><div style="background:' + stColor + ';height:100%;width:' + pctDone + '%;border-radius:4px;transition:width 0.3s;"></div></div>';
                            if (remaining > 0) html += '<div style="font-size:10px;color:#94a3b8;margin-top:2px;">' + remaining + ' remaining</div>';
                            html += '</div>';
                        }
                        // Operation breakdown
                        var ops = ['insert', 'update', 'delete'];
                        var hasOps = false;
                        ops.forEach(function(op) {
                            if (data[op] && (data[op].queued > 0 || data[op].processed > 0)) hasOps = true;
                        });
                        if (hasOps) {
                            html += '<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:8px;">';
                            ops.forEach(function(op) {
                                var o = data[op];
                                if (!o) return;
                                var ok = Number(o.successful || 0);
                                var fail = Number(o.failed || 0);
                                var opQueued = Number(o.queued || 0);
                                if (opQueued === 0 && ok === 0 && fail === 0) return;
                                html += '<div style="background:#fff;border:1px solid #e2e8f0;border-radius:6px;padding:6px 8px;text-align:center;">';
                                html += '<div style="font-size:10px;font-weight:600;color:#64748b;text-transform:capitalize;margin-bottom:2px;">' + op + 's</div>';
                                html += '<div style="font-size:14px;font-weight:700;color:#1e293b;">' + ok + '</div>';
                                if (fail > 0) html += '<div style="font-size:10px;color:#ef4444;font-weight:600;">' + fail + ' failed</div>';
                                if (opQueued > 0) html += '<div style="font-size:9px;color:#94a3b8;">' + opQueued + ' queued</div>';
                                html += '</div>';
                            });
                            html += '</div>';
                        }
                        // Errors
                        var allErrors = [];
                        ops.forEach(function(op) {
                            if (data[op] && data[op].errors && data[op].errors.length > 0) {
                                data[op].errors.forEach(function(e) { allErrors.push({ op: op, error: e }); });
                            }
                        });
                        if (allErrors.length > 0) {
                            html += '<details><summary style="cursor:pointer;font-size:11px;font-weight:600;color:#ef4444;"><i class="fas fa-exclamation-triangle" style="margin-right:4px;"></i>Errors (' + allErrors.length + ')</summary>';
                            html += '<div style="max-height:150px;overflow-y:auto;margin-top:4px;">';
                            allErrors.forEach(function(e) {
                                var errMsg = typeof e.error === 'string' ? e.error : JSON.stringify(e.error);
                                html += '<div style="font-size:10px;color:#ef4444;padding:2px 0;border-bottom:1px solid #fee2e2;"><span style="font-weight:600;text-transform:capitalize;">' + e.op + ':</span> ' + errMsg.replace(/</g, '&lt;') + '</div>';
                            });
                            html += '</div></details>';
                        }
                        container.innerHTML = html;
                    })
                    .catch(function(err) {
                        var container = document.getElementById('gffc-health-onsite-status');
                        if (container) container.innerHTML = '<span style="color:#ef4444;">Failed to load onsite status: ' + (err.message || err) + '</span>';
                    });
                }

                /* ---- Annunciator update ---- */
                function _updateAnnunciator(d) {
                    var scoreEl = document.getElementById('gffc-health-score');
                    var labelEl = document.getElementById('gffc-health-status-label');
                    var stripEl = document.getElementById('gffc-health-strip');
                    var iconEl = document.getElementById('gffc-health-icon');
                    var ann = document.getElementById('gffc-health-annunciator');
                    if (!scoreEl) return;
                    if (!d || d.status === 'unknown' || d.status === 'error') {
                        scoreEl.textContent = '--';
                        labelEl.textContent = 'No Data';
                        stripEl.style.backgroundColor = '#9ca3af';
                        if (iconEl) iconEl.style.color = '#9ca3af';
                        return;
                    }
                    var c = _hc(d.status);
                    scoreEl.textContent = Math.round(_num(d.health_score));
                    labelEl.textContent = c.label;
                    stripEl.style.backgroundColor = c.strip;
                    if (iconEl) iconEl.style.color = c.strip;
                    if (ann) ann.title = 'Site Health: ' + c.label + ' (' + Math.round(_num(d.health_score)) + '/100) — Click for details';
                }

                /* ---- Open dashboard modal ---- */
                window.gffcOpenHealthDashboard = function() {
                    var d = window.gFFLCockpit._healthData;
                    var overlay = document.getElementById('gffc-health-overlay');
                    var body = document.getElementById('gffc-health-body');
                    if (!overlay || !body) return;
                    if (!d) {
                        body.innerHTML = '<div style="padding:40px;text-align:center;color:#64748b;">No site health data available. Data will appear after your first synchronization cycle.</div>';
                    } else {
                        body.innerHTML = _renderDashboard(d);
                        // Load recent logs for the key being viewed
                        var logKey = d.api_key || null;
                        _loadHealthLogs(logKey);
                        // Load onsite process status if applicable
                        if (d.uses_onsite_updates) {
                            _loadOnsiteStatus(logKey);
                        }
                    }
                    overlay.classList.add('open');
                };

                /* ---- Main load function ---- */
                window.gFFLCockpit.loadSiteHealth = function(apiKey, lookupKey) {
                    var isAdmin = window.gFFLCockpit.isAdmin;
                    var action = isAdmin ? 'get_site_health_admin' : 'get_site_health';
                    var targetKey = lookupKey || "<?php echo esc_js($gFFLCockpitKey); ?>";
                    fetch("https://ffl-api.garidium.com", {
                        method: "POST",
                        headers: {
                            "Accept": "application/json",
                            "Content-Type": "application/json",
                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>"
                        },
                        body: JSON.stringify({ "action": action, "data": { "api_key": targetKey } })
                    })
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        window.gFFLCockpit._healthData = data;
                        _updateAnnunciator(data);
                    })
                    .catch(function(err) {
                        console.error("Error fetching site health:", err);
                        _updateAnnunciator(null);
                    });
                };

                /* ---- Modal close handlers ---- */
                document.addEventListener('DOMContentLoaded', function() {
                    // Health dashboard modal
                    var overlay = document.getElementById('gffc-health-overlay');
                    var closeBtn = document.getElementById('gffc-health-close');
                    if (closeBtn) closeBtn.addEventListener('click', function() { overlay.classList.remove('open'); });
                    if (overlay) overlay.addEventListener('click', function(e) { if (e.target === overlay) overlay.classList.remove('open'); });
                    // Health help sub-modal
                    var helpOverlay = document.getElementById('gffc-health-help-overlay');
                    var helpClose = document.getElementById('gffc-health-help-close');
                    if (helpClose) helpClose.addEventListener('click', function() { helpOverlay.classList.remove('open'); });
                    if (helpOverlay) helpOverlay.addEventListener('click', function(e) { if (e.target === helpOverlay) helpOverlay.classList.remove('open'); });
                    // Escape key closes topmost modal
                    document.addEventListener('keydown', function(e) {
                        if (e.key === 'Escape') {
                            if (helpOverlay && helpOverlay.classList.contains('open')) { helpOverlay.classList.remove('open'); }
                            else if (overlay && overlay.classList.contains('open')) { overlay.classList.remove('open'); }
                        }
                    });
                });
            })();
        </script>

        <?php if (function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain()) : ?>
            <style>
                /* Mobile-only: tighten top spacing on fflcockpit multisite admin */
                @media screen and (max-width: 782px) {
                    body.toplevel_page_g-ffl-cockpit-settings .wrap {
                        margin-top: 0 !important;
                    }
                    body.toplevel_page_g-ffl-cockpit-settings .wrap > h1,
                    body.toplevel_page_g-ffl-cockpit-settings .wrap > h1.wp-heading-inline {
                        margin-top: 0 !important;
                        padding-top: 0 !important;
                    }
                }
            </style>
        <?php endif; ?>

        <style>
            /* Header: hide username on narrow screens, keep logout visible */
            @media screen and (max-width: 782px) {
                .gffc-header-username {
                    display: none !important;
                }
                .gffc-header-account {
                    gap: 8px !important;
                }
            }

            /* ---- Site Health Annunciator ---- */
            .gffc-health-annunciator {
                display: inline-flex;
                align-items: center;
                gap: 8px;
                padding: 4px 12px 4px 0;
                background: #fff;
                border-radius: 6px;
                box-shadow: 0 1px 4px rgba(0,0,0,0.10);
                cursor: pointer;
                transition: box-shadow 0.2s, transform 0.15s;
                user-select: none;
                overflow: hidden;
                white-space: nowrap;
            }
            .gffc-health-annunciator:hover {
                box-shadow: 0 3px 12px rgba(0,0,0,0.15);
                transform: translateY(-1px);
            }
            .gffc-health-strip {
                width: 4px;
                align-self: stretch;
                border-radius: 6px 0 0 6px;
                background: #9ca3af;
                transition: background 0.3s;
            }
            .gffc-health-score {
                font-size: 20px;
                font-weight: 800;
                color: #1e293b;
                line-height: 1;
            }
            .gffc-health-status-label {
                font-size: 11px;
                font-weight: 600;
                color: #64748b;
                text-transform: uppercase;
                letter-spacing: 0.3px;
            }
            .gffc-health-ann-icon {
                font-size: 16px;
                color: #9ca3af;
                transition: color 0.3s;
            }
            .gffc-health-ann-text {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
            .gffc-health-ann-hint {
                font-size: 10px;
                color: #94a3b8;
                font-weight: 400;
            }
            @media screen and (max-width: 600px) {
                .gffc-health-annunciator { padding: 3px 8px 3px 0; gap: 5px; }
                .gffc-health-ann-hint { display: none; }
                .gffc-health-score { font-size: 16px; }
            }

            /* ---- Site Health Dashboard Modal ---- */
            .gffc-health-overlay {
                display: none;
                position: fixed;
                top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0,0,0,0.5);
                z-index: 100001;
                align-items: center;
                justify-content: center;
            }
            .gffc-health-overlay.open { display: flex; }
            .gffc-health-modal {
                background: #fff;
                border-radius: 12px;
                box-shadow: 0 8px 30px rgba(0,0,0,0.25);
                max-width: 1400px;
                width: 96%;
                max-height: 94vh;
                display: flex;
                flex-direction: column;
            }
            .gffc-health-modal-header {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 14px 20px;
                border-bottom: 1px solid #e2e8f0;
            }
            .gffc-health-modal-header h3 {
                margin: 0;
                font-size: 17px;
                font-weight: 700;
                color: #1e293b;
            }
            .gffc-health-modal-close {
                background: none;
                border: none;
                font-size: 22px;
                color: #999;
                cursor: pointer;
                padding: 0 4px;
                line-height: 1;
            }
            .gffc-health-modal-close:hover { color: #333; }
            .gffc-health-modal-body {
                padding: 16px 20px;
                overflow-y: auto;
                font-size: 13px;
                line-height: 1.55;
                color: #334155;
            }

            /* Banner */
            .gffc-health-banner {
                border-radius: 10px;
                padding: 16px 20px;
                margin-bottom: 16px;
            }
            .gffc-health-banner-inner {
                display: flex;
                align-items: center;
                gap: 16px;
            }
            .gffc-health-score-circle {
                width: 64px; height: 64px;
                border-radius: 50%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;
            }

            /* 2x2 grid */
            .gffc-health-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 14px;
            }
            @media (max-width: 1000px) {
                .gffc-health-grid { grid-template-columns: 1fr 1fr; }
            }
            @media (max-width: 700px) {
                .gffc-health-grid { grid-template-columns: 1fr; }
            }

            /* Category cards */
            .gffc-health-card {
                background: #fff;
                border: 1px solid #e2e8f0;
                border-radius: 8px;
                overflow: hidden;
            }
            .gffc-health-card-header {
                background: #f8fafc;
                padding: 8px 12px;
                border-bottom: 1px solid #e2e8f0;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 13px;
                font-weight: 600;
                color: #334155;
            }
            .gffc-health-card-header i { margin-right: 5px; color: #64748b; }
            .gffc-health-card-body { padding: 12px; }

            /* Metric rows */
            .gffc-health-metric {
                display: flex;
                justify-content: space-between;
                align-items: baseline;
                padding: 3px 0;
                font-size: 12px;
            }
            .gffc-health-metric-label { color: #64748b; }
            .gffc-health-metric-value { font-weight: 600; color: #1e293b; text-align: right; }
            .gffc-health-admin-only { }
            .gffc-health-admin-divider {
                border-top: 1px dashed #e2e8f0;
                margin: 6px 0;
            }

            /* Help button */
            .gffc-health-help-btn {
                background: none; border: none; cursor: pointer;
                color: #94a3b8; font-size: 13px; padding: 2px 4px;
                transition: color 0.15s;
            }
            .gffc-health-help-btn:hover { color: #6366f1; }

            /* Help sub-modal (higher z-index) */
            .gffc-health-help-overlay {
                display: none;
                position: fixed;
                top: 0; left: 0; right: 0; bottom: 0;
                background: rgba(0,0,0,0.35);
                z-index: 100002;
                align-items: center;
                justify-content: center;
            }
            .gffc-health-help-overlay.open { display: flex; }
            .gffc-health-help-modal {
                background: #fff;
                border-radius: 10px;
                box-shadow: 0 8px 30px rgba(0,0,0,0.25);
                max-width: 560px;
                width: 90%;
                max-height: 70vh;
                display: flex;
                flex-direction: column;
            }
            .gffc-health-help-table {
                width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 12px;
            }
            .gffc-health-help-table th {
                background: #f1f5f9; padding: 6px 10px; text-align: left; font-weight: 600; border-bottom: 1px solid #e2e8f0;
            }
            .gffc-health-help-table td {
                padding: 6px 10px; border-bottom: 1px solid #f1f5f9;
            }

            /* Connection test rows */
            .gffc-health-test-row {
                display: flex;
                align-items: center;
                gap: 6px;
                padding: 3px 0;
                font-size: 12px;
            }

            /* Recommendations */
            .gffc-health-recommendation {
                display: flex;
                align-items: flex-start;
                gap: 6px;
                padding: 8px 12px;
                border-left: 3px solid #3b82f6;
                border-radius: 0 6px 6px 0;
                margin-bottom: 6px;
                font-size: 12px;
                line-height: 1.5;
            }

            /* Alerts table */
            .gffc-health-alerts-table {
                width: 100%; border-collapse: collapse; font-size: 11px;
            }
            .gffc-health-alerts-table th {
                background: #f8fafc; padding: 4px 8px; text-align: left; font-weight: 600; border-bottom: 1px solid #e2e8f0; font-size: 10px; text-transform: uppercase; color: #64748b;
            }
            .gffc-health-alerts-table td {
                padding: 4px 8px; border-bottom: 1px solid #f1f5f9;
            }
        </style>

        <div class="wrap">
            <div style="margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between; width: 99%;">
                <img src="<?php echo esc_attr(plugin_dir_url(__FILE__) . 'images/ffl-cockpit-logo.svg');?>" style="max-height: 50px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <?php if ($this->is_restricted_user()) : ?>
                        <div class="gffc-header-account" style="display: flex; align-items: center; gap: 15px;">
                            <div style="font-weight: 600; color: #3c434a; font-size: 14px; display: flex; align-items: center; gap: 6px;">
                                <span class="gffc-header-username"><?php echo esc_html($current_user->display_name); ?></span>
                            </div>
                            <a href="<?php echo esc_url(wp_logout_url()); ?>" aria-label="Log Out" title="Log Out" style="font-size: 13px; color: #d63638; text-decoration: none; display: flex; align-items: center; gap: 4px; font-weight: 500; padding: 4px;">
                                <span class="dashicons dashicons-migrate" style="font-size: 32px; width: 32px; height: 32px;"></span>
                            </a>
                        </div>
                    <?php elseif (function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain()) : ?>
                        <div class="gffc-header-account" style="display: flex; align-items: center; gap: 15px;">
                            <div style="font-weight: 600; color: #3c434a; font-size: 14px; display: flex; align-items: center; gap: 6px;">
                                <span class="gffc-header-username"><?php echo esc_html($current_user->display_name); ?></span>
                            </div>
                            <a href="<?php echo esc_url(wp_logout_url()); ?>" aria-label="Log Out" title="Log Out" style="font-size: 13px; color: #d63638; text-decoration: none; display: flex; align-items: center; gap: 4px; font-weight: 500; padding: 4px;">
                                <span class="dashicons dashicons-migrate" style="font-size: 32px; width: 32px; height: 32px;"></span>
                            </a>
                        </div>
                    <?php elseif (!(function_exists('g_ffl_is_fflcockpit_multisite_domain') ? g_ffl_is_fflcockpit_multisite_domain() : is_multisite())) : ?>
                        <div id="gffc-health-annunciator" class="gffc-health-annunciator" onclick="gffcOpenHealthDashboard()" title="Site Health — Click for details">
                            <div id="gffc-health-strip" class="gffc-health-strip"></div>
                            <i id="gffc-health-icon" class="fas fa-heartbeat gffc-health-ann-icon"></i>
                            <div class="gffc-health-ann-text">
                                <div><span id="gffc-health-score" class="gffc-health-score">--</span></div>
                                <span id="gffc-health-status-label" class="gffc-health-status-label">Loading...</span>
                                <span class="gffc-health-ann-hint">Site Health</span>
                            </div>
                        </div>

                        <!-- Site Health Dashboard Modal -->
                        <div class="gffc-health-overlay" id="gffc-health-overlay">
                            <div class="gffc-health-modal">
                                <div class="gffc-health-modal-header">
                                    <h3><i class="fas fa-heartbeat" style="color:#6366f1;margin-right:6px;"></i>Site Health Dashboard</h3>
                                    <button type="button" class="gffc-health-modal-close" id="gffc-health-close">&times;</button>
                                </div>
                                <div class="gffc-health-modal-body" id="gffc-health-body">
                                    <div style="padding:40px;text-align:center;color:#94a3b8;">Loading site health data...</div>
                                </div>
                            </div>
                        </div>

                        <!-- Site Health Help Sub-Modal -->
                        <div class="gffc-health-help-overlay" id="gffc-health-help-overlay">
                            <div class="gffc-health-help-modal">
                                <div class="gffc-health-modal-header">
                                    <h3 id="gffc-health-help-title"></h3>
                                    <button type="button" class="gffc-health-modal-close" id="gffc-health-help-close">&times;</button>
                                </div>
                                <div class="gffc-health-modal-body" id="gffc-health-help-body"></div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Tab links -->
            <div class="tab" id="cockpit_main_tab_control">
                <?php
                    $gffc_is_multisite_domain = function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain();
                    // When the API key is missing/invalid, do NOT default into Product Search.
                    $gffc_key_valid = is_string($gFFLCockpitKey) && strlen($gFFLCockpitKey) >= 40;
                    $gffc_default_to_search = $gffc_is_multisite_domain && $gffc_key_valid;
                ?>
                <button class="tablinks" onclick="openTab(event, 'configuration')" <?php echo $gffc_default_to_search ? '' : 'id="defaultOpen"'; ?>><span class="gffc-tab-desktop">Configuration</span><span class="gffc-tab-mobile">Config</span></button>
                <button class="tablinks" onclick="openTab(event, 'product_feed')" <?php echo $gffc_default_to_search ? 'id="defaultOpen"' : ''; ?>><span class="gffc-tab-desktop">Product Search</span><span class="gffc-tab-mobile">Search</span></button>
                <button class="tablinks" onclick="openTab(event, 'marketplace_dashboard');loadDashboard();"><span class="gffc-tab-desktop">Analytics</span><span class="gffc-tab-mobile">Analytics</span></button>
                <button class="tablinks" id="gffc_cart_tab_btn" style="display:none;" onclick="openTab(event, 'cart');">Cart <span id="gffc_cart_badge" style="display:inline-block; margin-left:6px; background:#dc3545; color:white; padding:1px 7px; border-radius:999px; font-size:11px; font-weight:700;">0</span></button>
                <button class="tablinks" onclick="openTab(event, 'fulfillment');of_grid.render(document.getElementById('order_fulfillment_table'));">Fulfillment</button>
                <?php if (!$gffc_is_multisite_domain) : ?>
                    <button class="tablinks" onclick="openTab(event, 'logs');if(!gffc_log_grid_rendered['woo']){gffc_log_grids['woo'].render(document.getElementById('log_table_woo'));gffc_log_grid_rendered['woo']=true;}">Logs</button>
                <?php endif; ?>
                <button class="tablinks" onclick="openTab(event, 'help_center');load_help_videos();"><span class="gffc-tab-desktop">Help Center</span><span class="gffc-tab-mobile">Help</span></button>
                    <button class="tablinks" id="gffc-ai-review-tab" onclick="openTab(event, 'ai_category_review');gffcLoadAiReview();" style="display:none;"><span class="gffc-tab-desktop">Category Review</span><span class="gffc-tab-mobile">Review</span></button>
                    <!-- Earn Tokens Modal -->
                    <div id="gffc-earn-tokens-modal" onclick="if(event.target===this)this.style.display='none';" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:100000;align-items:center;justify-content:center;">
                        <div style="background:#fff;border-radius:12px;max-width:520px;width:90%;padding:32px;box-shadow:0 8px 32px rgba(0,0,0,0.2);text-align:center;position:relative;">
                            <button onclick="document.getElementById('gffc-earn-tokens-modal').style.display='none';" style="position:absolute;top:10px;right:14px;background:none;border:none;font-size:20px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
                            <div style="font-size:48px;margin-bottom:12px;"><i class="fas fa-coins" style="color:#f59e0b;"></i></div>
                            <h2 style="margin:0 0 8px;font-size:22px;color:#1e293b;">Earn Free AI Tokens</h2>
                            <p style="color:#64748b;font-size:14px;line-height:1.6;margin:0 0 16px;">
                                Help us improve product categorization and earn AI tokens in return!
                                We use AI to suggest categories for thousands of products, but we need your expertise to verify them.
                            </p>
                            <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px;margin-bottom:16px;text-align:left;">
                                <div style="font-size:13px;font-weight:600;color:#166534;margin-bottom:6px;"><i class="fas fa-check-circle" style="margin-right:4px;"></i>How it works:</div>
                                <ul style="margin:0;padding-left:18px;font-size:12px;color:#334155;line-height:1.8;">
                                    <li>Review AI-suggested categories for products</li>
                                    <li>Approve correct suggestions to earn <b>250 tokens</b></li>
                                    <li>Correct wrong suggestions to earn <b>500 tokens</b></li>
                                    <li>Tokens are credited instantly to your account</li>
                                </ul>
                            </div>
                            <div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:12px;margin-bottom:16px;text-align:left;max-height:120px;overflow-y:auto;">
                                <div style="font-size:12px;font-weight:600;color:#991b1b;margin-bottom:6px;"><i class="fas fa-file-contract" style="margin-right:4px;"></i>Reviewer Agreement</div>
                                <p style="margin:0;font-size:11px;color:#334155;line-height:1.7;">
                                    By participating in the Category Review program, you acknowledge that your categorization decisions directly impact product listings for <b>all FFL Cockpit customers</b>. Please review each product carefully and select categories thoughtfully. Inaccurate categorizations can affect how products appear across multiple storefronts.
                                </p>
                                <p style="margin:8px 0 0;font-size:11px;color:#334155;line-height:1.7;">
                                    All review activity is logged and associated with your account, including the products reviewed, decisions made, and timestamps. FFL Cockpit reserves the right to revoke earned tokens and suspend access to this program if reviews are found to be careless, abusive, or conducted in bad faith.
                                </p>
                            </div>
                            <div style="margin-bottom:16px;">
                                <label style="font-size:12px;color:#334155;cursor:pointer;display:flex;align-items:flex-start;gap:8px;">
                                    <input type="checkbox" id="gffc-earn-tokens-agree" onchange="document.getElementById('gffc-earn-tokens-start').disabled=!this.checked;document.getElementById('gffc-earn-tokens-start').style.opacity=this.checked?'1':'0.5';" style="margin-top:2px;flex-shrink:0;">
                                    <span>I understand that my categorization decisions affect all FFL Cockpit customers and agree to review products carefully and in good faith.</span>
                                </label>
                            </div>
                            <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap;">
                                <button id="gffc-earn-tokens-start" disabled onclick="document.getElementById('gffc-earn-tokens-modal').style.display='none';document.getElementById('gffc-ai-review-tab').style.display='';document.getElementById('gffc-ai-review-tab').click();" style="padding:12px 28px;background:#10b981;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:700;cursor:pointer;opacity:0.5;"><i class="fas fa-rocket" style="margin-right:6px;"></i>Start Earning</button>
                                <a href="<?php echo esc_attr($this->get_purchase_url($gFFLCockpitKey)); ?>" target="_blank" onclick="document.getElementById('gffc-earn-tokens-modal').style.display='none';" style="padding:12px 28px;background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;border-radius:8px;font-size:15px;font-weight:700;cursor:pointer;text-decoration:none;display:inline-block;"><i class="fas fa-shopping-cart" style="margin-right:6px;"></i>Just Buy Tokens</a>
                            </div>
                        </div>
                    </div>
            </div>
            <!-- Tab content -->
            <button class="accordion">Configuration</button>
            <div id="configuration" class="tabcontent">
                <div style="background: #fff; padding: 0;">
                        <span id="unsaved-indicator">There are <span style="color:red;text-decoration: underline;">Unsaved Changes</span> to your configuration. Hit the "Save Changes" button at the bottom of your screen, or refresh the browser page to revert.</span>
                        <span class="validator_view" id="validation-errors"></span>
                        <?php settings_fields('g-ffl-cockpit-settings'); ?>
                        <script>
                            const statesAndTerritories = [
                                { value: "", text: "Select State/Territory" },
                                { value: "AL", text: "Alabama" },
                                { value: "AK", text: "Alaska" },
                                { value: "AZ", text: "Arizona" },
                                { value: "AR", text: "Arkansas" },
                                { value: "CA", text: "California" },
                                { value: "CO", text: "Colorado" },
                                { value: "CT", text: "Connecticut" },
                                { value: "DE", text: "Delaware" },
                                { value: "FL", text: "Florida" },
                                { value: "GA", text: "Georgia" },
                                { value: "HI", text: "Hawaii" },
                                { value: "ID", text: "Idaho" },
                                { value: "IL", text: "Illinois" },
                                { value: "IN", text: "Indiana" },
                                { value: "IA", text: "Iowa" },
                                { value: "KS", text: "Kansas" },
                                { value: "KY", text: "Kentucky" },
                                { value: "LA", text: "Louisiana" },
                                { value: "ME", text: "Maine" },
                                { value: "MD", text: "Maryland" },
                                { value: "MA", text: "Massachusetts" },
                                { value: "MI", text: "Michigan" },
                                { value: "MN", text: "Minnesota" },
                                { value: "MS", text: "Mississippi" },
                                { value: "MO", text: "Missouri" },
                                { value: "MT", text: "Montana" },
                                { value: "NE", text: "Nebraska" },
                                { value: "NV", text: "Nevada" },
                                { value: "NH", text: "New Hampshire" },
                                { value: "NJ", text: "New Jersey" },
                                { value: "NM", text: "New Mexico" },
                                { value: "NY", text: "New York" },
                                { value: "NC", text: "North Carolina" },
                                { value: "ND", text: "North Dakota" },
                                { value: "OH", text: "Ohio" },
                                { value: "OK", text: "Oklahoma" },
                                { value: "OR", text: "Oregon" },
                                { value: "PA", text: "Pennsylvania" },
                                { value: "RI", text: "Rhode Island" },
                                { value: "SC", text: "South Carolina" },
                                { value: "SD", text: "South Dakota" },
                                { value: "TN", text: "Tennessee" },
                                { value: "TX", text: "Texas" },
                                { value: "UT", text: "Utah" },
                                { value: "VT", text: "Vermont" },
                                { value: "VA", text: "Virginia" },
                                { value: "WA", text: "Washington" },
                                { value: "WV", text: "West Virginia" },
                                { value: "WI", text: "Wisconsin" },
                                { value: "WY", text: "Wyoming" },
                                { value: "DC", text: "District of Columbia" },
                                { value: "AS", text: "American Samoa" },
                                { value: "GU", text: "Guam" },
                                { value: "MP", text: "Northern Mariana Islands" },
                                { value: "PR", text: "Puerto Rico" },
                                { value: "UM", text: "United States Minor Outlying Islands" },
                                { value: "VI", text: "U.S. Virgin Islands" }
                            ];

                            let typingTimer;
                            const doneTypingInterval = 2000;
                            function setupAutoSave() {
                                var autoSaveFields = document.querySelectorAll('[data-autosave="true"]');
                                autoSaveFields.forEach(field => {
                                    if (typeof tinymce !== 'undefined' && !tinymce.get(field.id) && !field.dataset.listenerAdded) {
                                        field.addEventListener('input', () => {
                                            clearTimeout(typingTimer);
                                            typingTimer = setTimeout(() => autoSave(field), doneTypingInterval);
                                        });

                                        field.addEventListener('keydown', () => {
                                            clearTimeout(typingTimer);
                                        });

                                        field.addEventListener('blur', () => autoSave(field));
                                        
                                        // Add change event for select elements and checkboxes
                                        if (field.tagName === 'SELECT' || field.type === 'checkbox') {
                                            field.addEventListener('change', () => autoSave(field));
                                        }

                                        // Mark this field as having listeners added
                                        field.dataset.listenerAdded = 'true';
                                    }
                                });
                            }

                            function refreshEditor(){
                                load_fancy_editor(editor.get());
                                document.getElementById("unsaved-indicator").style.display='none';
                                initialCockpitConfiguration = editor.get();
                                
                                // Update button states after refresh
                                if (typeof updateButtonStates === 'function') {
                                    updateButtonStates();
                                }
                            }
                   
                            function autoSave(field) {
                                var value;
                                if (typeof tinymce !== 'undefined' && tinymce.get(field.id)) {
                                    // Handle TinyMCE editor
                                    value = tinymce.get(field.id).getContent();
                                } else {
                                    if (field.type === 'checkbox') {
                                        value = field.checked;
                                    }else{
                                        // Handle regular input/textarea
                                        value = field.value;
                                    }
                                    if (field.type == "number"){
                                        if (!isNaN(value) && value.trim() !== "") {
                                            value = parseFloat(value);
                                        } else {
                                            value = ""; // Keep as empty string to detect clearing
                                        }
                                    }
                                }
                                // console.log('Auto-saving form data for field:', field.id, value);
                                const cc = editor.get();
                                setConfigValue(cc, field.id, value);
                                editor.set(cc);
                            }

                            function filterOptions(searchTerm, modalListId, modifier = null) {
                                const filter = searchTerm.toLowerCase();
                                const modalList = document.getElementById(modalListId);
                                const containers = Array.from(modalList.getElementsByClassName('checkbox-option'));

                                const matches = [];
                                const modifierMatches = [];
                                const nonMatches = [];

                                // Separate matches based on search term and modifier
                                containers.forEach(container => {
                                    const label = container.getElementsByTagName('label')[0];
                                    const txtValue = label.textContent || label.innerText;

                                    // Check if the item matches the search term
                                    if (filter.length == 0 && modifier && container['attributes'][modifier].value === "1") {
                                        // Add the "Dropship Restricted" label if not already added
                                        if (!container.querySelector('.dropship-label')) {
                                            const dropshipLabel = document.createElement('span');
                                            dropshipLabel.textContent = "Dropship Restricted";
                                            dropshipLabel.className = "dropship-label";
                                            dropshipLabel.style.color = "red"; // Optional: Make the label red for emphasis
                                            dropshipLabel.style.marginLeft = "auto";
                                            dropshipLabel.style.fontSize = "0.9em"; // Optional: Adjust font size
                                            dropshipLabel.style.display = "inline-block";
                                            dropshipLabel.style.float = "right"; // Align to the right
                                            container.appendChild(dropshipLabel);
                                        }
                                        modifierMatches.push(container); // Items with the modifier
                                    } else if (filter.length > 0 && txtValue.toLowerCase().indexOf(filter) > -1) {
                                        // Check if the item has the modifier
                                        matches.push(container); // Items matching the search term but not the modifier
                                    } else {
                                        nonMatches.push(container); // Items not matching the search term
                                    }
                                });

                                // Sort non-matches alphabetically by their label text
                                matches.sort((a, b) => {
                                    const labelA = a.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                    const labelB = b.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                    return labelA.localeCompare(labelB);
                                });
                                
                                if (filter.length == 0 && modifier){
                                    modifierMatches.sort((a, b) => {
                                        const labelA = a.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                        const labelB = b.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                        return labelA.localeCompare(labelB);
                                    });
                                 }

                                nonMatches.sort((a, b) => {
                                    const labelA = a.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                    const labelB = b.getElementsByTagName('label')[0].textContent.trim().toLowerCase();
                                    return labelA.localeCompare(labelB);
                                });

                                // Clear the modal list
                                while (modalList.firstChild) {
                                    modalList.removeChild(modalList.firstChild);
                                }

                                // Append modifier matches first
                                modifierMatches.forEach(container => {
                                    modalList.appendChild(container);
                                    container.style.display = ""; // Ensure matches are displayed
                                });

                                // Append other matches
                                matches.forEach(container => {
                                    modalList.appendChild(container);
                                    container.style.display = ""; // Ensure matches are displayed
                                });

                                // Add a separator line if there are matches and non-matches
                                if ((modifierMatches.length > 0 || matches.length > 0) && nonMatches.length > 0) {
                                    const separator = document.createElement('hr');
                                    separator.style.borderTop = "2px solid black"; // Set the thickness of the separator
                                    modalList.appendChild(separator);
                                }

                                // Append non-matches
                                nonMatches.forEach(container => {
                                    modalList.appendChild(container);
                                    container.style.display = ""; // Ensure non-matches are displayed
                                });

                                // Scroll to the top of the modal list
                                modalList.scrollTop = 0;
                            }




                            async function load_modal_check_option(modal, action, selectedItemsContainerId) {
                                var element_name = "categories";
                                var element_id = "name";
                                var element_description = "name";
                                var modifier = null;
                                if (action == "get_product_classes") {
                                    element_name = "product_classes";
                                    element_id = "product_class";
                                    element_description = "description";
                                }else if (action == "get_distributors") {
                                    element_name = "distributors";
                                    element_id = "distid";
                                    element_description = "dist_name";
                                }else if (action == "get_manufacturer_list") {
                                    element_name = "manufacturers";
                                    element_id = "name";
                                    element_description = "name";
                                    modifier = "dropship_restricted";
                                } else if (action == "get_category_list") {
                                    element_name = "categories";
                                    element_id = "name";
                                    element_description = "name";
                                }
                                const response = await fetch("https://ffl-api.garidium.com", {
                                    method: "POST",
                                    headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                    },
                                    body: JSON.stringify({ "action": action })
                                });

                                const selectedItemsContainer = document.getElementById(selectedItemsContainerId);
                                const selectedItems = Array.from(selectedItemsContainer.getElementsByClassName('selected-item')).map(item => item.querySelector('span').textContent);
                                
                                const data = await response.json();
                                try {
                                    if (data != null && data[element_name].length > 0) {
                                        for (let i = 0; i < data[element_name].length; i++) {
                                            const item = data[element_name][i];
                                            const checkbox = document.createElement("input");
                                            checkbox.type = "checkbox";
                                            checkbox.value = item[element_id];
                                            checkbox.id = `checkbox_${element_id}_${item[element_id]}`;

                                            if (selectedItems.includes(checkbox.value)){
                                                checkbox.checked =true;
                                            }

                                            const label = document.createElement("label");
                                            label.htmlFor = `checkbox_${element_id}_${item[element_id]}`;
                                            if (action == "get_product_classes" || action == "get_distributors"){
                                                label.textContent = item[element_description] + " (" + item[element_id] + ")";
                                            } else {
                                                label.textContent = item[element_description];
                                            }
                            
                                            const container = document.createElement("div");
                                            container.classList.add("checkbox-option");
                                            if (modifier) {
                                                container.setAttribute(modifier, item[modifier]);
                                            }
                                            container.appendChild(checkbox);
                                            container.appendChild(label);
                                            modal.appendChild(container);
                                        }
                                    }
                                } catch (error) {
                                    alert("Problem retrieving options.");
                                }
                            }
                          
                            function openModal(modalId, selectedItemsId) {
                                const modal = document.getElementById(modalId);
                                const modal_options = document.getElementById(modalId + "List");
                                
                                // Special handling for priceBasedMarginModal
                                if (modalId === "priceBasedMarginModal") {
                                    const modalHeader = modal.querySelector('.modalHeader');
                                    const submitButton = modal.querySelector('button');
                                    
                                    // Reset modal to add mode (in case it was previously in edit mode)
                                    modalHeader.textContent = 'Add Cost Based Margin';
                                    submitButton.textContent = 'Add';
                                    
                                    // Clear form fields
                                    document.getElementById('min_price').value = '0';
                                    document.getElementById('max_price').value = '0';
                                    document.getElementById('margin_dollar').value = '0';
                                    document.getElementById('margin_percentage').value = '0';
                                    
                                    // Clear editing state
                                    modal.removeAttribute('data-editing-row-index');
                                    modal.removeAttribute('data-editing-group');
                                }
                                
                                // Create the search div
                                const searchDiv = document.getElementById(modalId + "SearchDiv");
                                
                                if (searchDiv != null){
                                    const div = document.createElement('div');
                                    div.style = "margin-bottom:20px";
                                    searchDiv.replaceChildren();
                                    var searchType = "brand";
                                    if (modalId.startsWith("category")){
                                        searchType = "category";
                                    } else if (modalId.startsWith("ignoreMap")){
                                        searchType = "ignoreMapBrand";
                                    } else if (modalId.startsWith("distributor")){
                                        searchType = "distributor";
                                    }
                                    const container = document.createElement('span');
                                    container.style = 'margin-left:20px;';
                                    // Static part of the text
                                    const staticText = document.createTextNode('Filter: ');

                                    // Dynamic part of the text, styled as a link
                                    const link = document.createElement('a');
                                    link.id = searchType + 'SearchInput';
                                    link.href = '#'; // Prevent default anchor behavior
                                    link.textContent = 'Enter Search Term';
                                    link.style.textDecoration = 'underline'; // Style to look like a link
                                    link.style.color = 'blue'; // Optional: Color to look like a link

                                    // Add click listener to prompt for search term and update the text
                                    link.addEventListener('click', function(event) {
                                        event.preventDefault(); // Prevent default anchor behavior
                                        const newValue = prompt("Enter Search Term", link.textContent);
                                        if (newValue !== null) { // Check if the user didn't cancel the prompt
                                            link.textContent = newValue;
                                            filterOptions(document.getElementById(searchType + 'SearchInput').textContent, searchType + 'ModalList');
                                        }
                                    });

                                    // Append the static text and link to the container
                                    container.appendChild(staticText);
                                    container.appendChild(link);

                                    // If searchType is "brand", add the Dropship Restricted link
                                    if (searchType === "brand") {
                                        // Add pipe symbol
                                        const pipe = document.createTextNode(' | ');
                                        container.appendChild(pipe);

                                        // Dropship Restricted link
                                        const dslink = document.createElement('a');
                                        dslink.id = 'brandDropShipRestrictedFilter';
                                        dslink.href = '#'; // Prevent default anchor behavior
                                        dslink.textContent = 'Brands with Dropship Restrictions';
                                        dslink.style.textDecoration = 'underline'; // Style to look like a link
                                        dslink.style.color = 'blue'; // Optional: Color to look like a link

                                        dslink.addEventListener('click', function(event) {
                                            event.preventDefault(); // Prevent default anchor behavior
                                            filterOptions('', searchType + 'ModalList', 'dropship_restricted'); // Pass the modifier to prioritize these items
                                        });

                                        container.appendChild(dslink);
                                    }
                                  
                                    // Append input element to the div
                                    div.appendChild(container);
                                    searchDiv.appendChild(div);
                                }

                                if (modalId != "priceBasedMarginModal"){
                                    modal_options.replaceChildren();
                                    var api_function = "get_product_classes";
                                    if (modalId == "brandModal" || modalId == "ignoreMapBrandModal"){
                                        api_function = "get_manufacturer_list";
                                    }else if (modalId == "categoryModal"){
                                        api_function = "get_category_list";
                                    }else if (modalId == "distributorModal"){
                                        api_function = "get_distributors";
                                    }
                                    load_modal_check_option(modal_options, api_function, selectedItemsId)
                                }

                                
                                modal.style.display = "block";
                               // modal.style.zIndex = zIndex;
                                modal.setAttribute('data-selected-items-id', selectedItemsId);

                              
                            }

                            function closeModal(modalId) {
                                const modal = document.getElementById(modalId);
                                modal.style.display = "none";
                                
                            }

                            function saveSelections(modalId, itemType) {
                                const modal = document.getElementById(modalId);
                                const selectedItemsId = modal.getAttribute('data-selected-items-id');
                                const selectedItemsContainer = document.getElementById(selectedItemsId);
                                
                                const checkboxes = modal.querySelectorAll('input[type="checkbox"]:checked');
                                
                                // First remove all items from config (BEFORE clearing the DOM)
                                removeAllConfigArrayItems(selectedItemsContainer, true);
                                
                                // Now clear the DOM
                                selectedItemsContainer.innerHTML = '';
                                
                                checkboxes.forEach(checkbox => {

                                    // add item to configuration
                                    addConfigArrayItem(selectedItemsContainer, checkbox.value);

                                    const div = document.createElement('div');
                                    div.className = 'selected-item';
                                    const span = document.createElement('span');
                                    span.textContent = checkbox.value;
                                    const link = document.createElement('i');
                                    link.className = 'fas fa-trash-alt remove-link';
                                    link.title = 'Remove item'; 
                                    link.onclick = () => removeConfigArrayItem(selectedItemsContainer, div);
                                    div.appendChild(span);
                                    div.appendChild(link);
                                    selectedItemsContainer.appendChild(div);
                                });

                                closeModal(modalId);
                            }

                            // Toggle cost range inputs visibility
                            function toggleCostRange(baseId) {
                                const inputsDiv = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-inputs'));
                                const toggleBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-toggle'));
                                const removeBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-remove'));
                                
                                if (inputsDiv.style.display === 'none') {
                                    inputsDiv.style.display = 'block';
                                    toggleBtn.textContent = 'Cancel';
                                    removeBtn.style.display = 'none';
                                } else {
                                    inputsDiv.style.display = 'none';
                                    toggleBtn.textContent = 'Add Range';
                                    
                                    // Clear inputs
                                    const minInput = document.getElementById(baseId.replace('product_restrictions-cost', 'min-cost'));
                                    const maxInput = document.getElementById(baseId.replace('product_restrictions-cost', 'max-cost'));
                                    if (minInput) minInput.value = '';
                                    if (maxInput) maxInput.value = '';
                                }
                            }

                            // Save cost range
                            function saveCostRange(baseId) {
                                const minInput = document.getElementById(baseId.replace('product_restrictions-cost', 'min-cost'));
                                const maxInput = document.getElementById(baseId.replace('product_restrictions-cost', 'max-cost'));
                                const displayDiv = document.getElementById(baseId + '-display');
                                const inputsDiv = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-inputs'));
                                const toggleBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-toggle'));
                                const removeBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-remove'));
                                
                                const minValue = minInput ? minInput.value.trim() : '';
                                const maxValue = maxInput ? maxInput.value.trim() : '';
                                
                                // Validate that both min and max values are provided
                                if (minValue === '' || maxValue === '') {
                                    alert('Please enter both minimum and maximum cost values.');
                                    return;
                                }
                                
                                // Validate that min is less than max
                                const minNum = parseFloat(minValue);
                                const maxNum = parseFloat(maxValue);
                                
                                if (minNum >= maxNum) {
                                    alert('Minimum cost must be less than maximum cost.');
                                    return;
                                }
                                
                                let rangeText = '';
                                let rangeValue = { global_restrictions: {} };
                                
                                rangeValue.global_restrictions.min_distributor_cost = minNum;
                                rangeValue.global_restrictions.max_distributor_cost = maxNum;
                                rangeText = `$${minValue} - $${maxValue}`;
                                
                                // Update display
                                displayDiv.innerHTML = `
                                    <div class="selected-item">
                                        <span>${rangeText}</span>
                                    </div>
                                `;
                                
                                // Update configuration - parse baseId to get correct path
                                const cc = editor.get();
                                
                                // Extract target and profile/class name from baseId
                                // baseId format: targets-{target}-shipping_profiles-{profile_name}-product_restrictions-cost
                                // baseId format: targets-{target}-shipping_classes-{class_name}-product_restrictions-cost
                                const baseIdParts = baseId.split('-');
                                if (baseIdParts.length >= 6 && baseIdParts[0] === 'targets') {
                                    const target = baseIdParts[1];
                                    const shippingType = baseIdParts[2]; // shipping_profiles or shipping_classes
                                    const name = baseIdParts.slice(3, baseIdParts.length-2).join('-'); // Handle names with dashes
                                    
                                    if ((shippingType === 'shipping_profiles' || shippingType === 'shipping_classes') && 
                                        baseIdParts[baseIdParts.length-2] === 'product_restrictions' && 
                                        baseIdParts[baseIdParts.length-1] === 'cost') {
                                        
                                        // Ensure the path exists
                                        if (!cc.targets) cc.targets = {};
                                        if (!cc.targets[target]) cc.targets[target] = {};
                                        if (!cc.targets[target][shippingType]) cc.targets[target][shippingType] = {};
                                        if (!cc.targets[target][shippingType][name]) cc.targets[target][shippingType][name] = {};
                                        if (!cc.targets[target][shippingType][name].product_restrictions) cc.targets[target][shippingType][name].product_restrictions = {};
                                        
                                        // Set the cost value
                                        cc.targets[target][shippingType][name].product_restrictions.cost = rangeValue;
                                    } else {
                                        console.error('Invalid baseId format:', baseId);
                                    }
                                }
                                
                                editor.set(cc);
                                
                                // Hide inputs and update buttons
                                inputsDiv.style.display = 'none';
                                toggleBtn.textContent = 'Edit Range';
                                removeBtn.style.display = 'inline';
                            }

                            // Remove cost range
                            function removeCostRange(baseId) {
                                const displayDiv = document.getElementById(baseId + '-display');
                                const toggleBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-toggle'));
                                const removeBtn = document.getElementById(baseId.replace('product_restrictions-cost', 'cost-remove'));
                                const minInput = document.getElementById(baseId.replace('product_restrictions-cost', 'min-cost'));
                                const maxInput = document.getElementById(baseId.replace('product_restrictions-cost', 'max-cost'));
                                
                                // Clear display
                                displayDiv.innerHTML = '';
                                
                                // Clear inputs
                                if (minInput) minInput.value = '';
                                if (maxInput) maxInput.value = '';
                                
                                // Update buttons
                                toggleBtn.textContent = 'Add Range';
                                removeBtn.style.display = 'none';
                                
                                // Remove from configuration - parse baseId to get correct path
                                const cc = editor.get();
                                
                                // Extract target and profile/class name from baseId
                                // baseId format: targets-{target}-shipping_profiles-{profile_name}-product_restrictions-cost
                                // baseId format: targets-{target}-shipping_classes-{class_name}-product_restrictions-cost
                                const baseIdParts = baseId.split('-');
                                if (baseIdParts.length >= 6 && baseIdParts[0] === 'targets') {
                                    const target = baseIdParts[1];
                                    const shippingType = baseIdParts[2]; // shipping_profiles or shipping_classes
                                    const name = baseIdParts.slice(3, baseIdParts.length-2).join('-'); // Handle names with dashes
                                    
                                    if ((shippingType === 'shipping_profiles' || shippingType === 'shipping_classes') && 
                                        baseIdParts[baseIdParts.length-2] === 'product_restrictions' && 
                                        baseIdParts[baseIdParts.length-1] === 'cost') {
                                        
                                        // Remove the cost value if it exists
                                        if (cc.targets && cc.targets[target] && cc.targets[target][shippingType] && cc.targets[target][shippingType][name] && cc.targets[target][shippingType][name].product_restrictions) {
                                            delete cc.targets[target][shippingType][name].product_restrictions.cost;
                                        }
                                    } else {
                                        console.error('Invalid baseId format:', baseId);
                                    }
                                }
                                
                                editor.set(cc);
                            }

                            // Close the modal when the user clicks anywhere outside of it
                            window.onclick = function(event) {
                                // Check if text is selected - if so, do not close the modal
                                if (window.getSelection().toString().length > 0) {
                                    return;
                                }
                                const modals = document.querySelectorAll('.modal');
                                modals.forEach(modal => {
                                    if (event.target === modal) {
                                        if (modal.id === 'detailsModal') {
                                            // Bootstrap modal - use Bootstrap API
                                            if (typeof jQuery !== 'undefined' && jQuery(modal).modal) {
                                                jQuery(modal).modal('hide');
                                            }
                                        } else {
                                            // Custom modal
                                            modal.style.display = "none";
                                        }
                                    }
                                });
                            };

                            function addSelectedItemsToContainer(selectedItemsContainer, items){
                                for (const item of items) {
                                    const div = document.createElement('div');
                                    div.className = 'selected-item';
                                    const span = document.createElement('span');
                                    span.textContent = item;
                                    const link = document.createElement('i');
                                    link.className = 'fas fa-trash-alt remove-link';
                                    link.title = 'Remove item'; 
                                    link.onclick = () => removeConfigArrayItem(selectedItemsContainer, div);
                                    div.appendChild(span);
                                    div.appendChild(link);
                                    selectedItemsContainer.appendChild(div);
                                }
                            }

                            function removeConfigArrayItem(container, item) {
                                // Check if this is a target product group container
                                const containerId = container.id;
                                const targetGroupMatch = containerId.match(/^target_group_([^_]+)_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (targetGroupMatch) {
                                    // This is a target product group - use the target group handler
                                    removeConfigArrayItemFromTargetGroup(container, item);
                                    return;
                                }
                                
                                // Check if this is a distributor product group container
                                const distributorGroupMatch = containerId.match(/^distributor_group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (distributorGroupMatch) {
                                    // This is a distributor product group - use the distributor group handler
                                    removeConfigArrayItemFromDistributorGroup(container, item);
                                    return;
                                }
                                
                                // Check if this is a regular product group container
                                const groupIdMatch = containerId.match(/^group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (groupIdMatch) {
                                    // This is a product group - use the product group handler
                                    removeConfigArrayItemFromGroup(container, item);
                                    return;
                                }
                                
                                // Import out of stock UPC handler
                                if (containerId === 'import-out-of-stock-upc-include') {
                                    let config = editor.get();
                                    const itemText = item.querySelector('span').textContent;
                                    var oos = config.targets && config.targets.woo && config.targets.woo.import_out_of_stock_product;
                                    if (oos && oos.upc && Array.isArray(oos.upc.include)) {
                                        const idx = oos.upc.include.indexOf(itemText);
                                        if (idx !== -1) oos.upc.include.splice(idx, 1);
                                        editor.set(config);
                                    }
                                    container.removeChild(item);
                                    return;
                                }

                                // Analytics Tag Mapping (multi-entry): per-entry product_classes / categories
                                if (typeof gffcAnalyticsTagParseContainerId === 'function') {
                                    const atagParsed = gffcAnalyticsTagParseContainerId(containerId);
                                    if (atagParsed) {
                                        const entry = gffcAnalyticsTagFindEntry(atagParsed.section, atagParsed.entryId);
                                        if (entry) {
                                            const itemText = (item.querySelector && item.querySelector('span')) ? item.querySelector('span').textContent : String(item);
                                            const arr = entry[atagParsed.field] || [];
                                            const idx = arr.indexOf(itemText);
                                            if (idx !== -1) arr.splice(idx, 1);
                                            entry[atagParsed.field] = arr;
                                            gffcAnalyticsTagsSyncToConfig();
                                        }
                                        container.removeChild(item);
                                        return;
                                    }
                                }

                                // Legacy handling for other containers
                                let config = editor.get();
                                var configItemsArray = getConfigValue(config, container.id);
                                const itemText = item.querySelector('span').textContent;
                                if (configItemsArray != undefined){
                                    const index = configItemsArray.indexOf(itemText);
                                    if (index !== -1) {
                                        configItemsArray.splice(index, 1);
                                    }
                                    editor.set(config);
                                }else{
                                    alert("This item was not defined in the configuration");
                                }
                                container.removeChild(item);
                            }
                            
               
                            function removeAllConfigArrayItems(container, skipPrompt = false) {
                                if (skipPrompt || confirm("Are you sure that you want to remove all items from this selection?")){
                                    // Get all selected items in the container
                                    const selectedItems = Array.from(container.getElementsByClassName('selected-item'));
                                    
                                    // Remove each item individually using the existing removeConfigArrayItem function
                                    // This ensures all the existing logic for different container types is reused
                                    selectedItems.forEach(item => {
                                        removeConfigArrayItem(container, item);
                                    });
                                }
                            }

                            function addConfigArrayItem(container, item) {
                                console.log('addConfigArrayItem called with:', { container, item, containerId: container.id });

                                const containerId = container.id;

                                // Import out of stock UPC handler
                                if (containerId === 'import-out-of-stock-upc-include') {
                                    let itemText = (item && item.querySelector) ? (item.querySelector('span') ? item.querySelector('span').textContent : '') : String(item).trim();
                                    if (!itemText) return;
                                    let config = editor.get();
                                    if (!config.targets) config.targets = {};
                                    if (!config.targets.woo) config.targets.woo = {};
                                    if (!config.targets.woo.import_out_of_stock_product) config.targets.woo.import_out_of_stock_product = {};
                                    if (!config.targets.woo.import_out_of_stock_product.upc) config.targets.woo.import_out_of_stock_product.upc = {};
                                    if (!Array.isArray(config.targets.woo.import_out_of_stock_product.upc.include)) config.targets.woo.import_out_of_stock_product.upc.include = [];
                                    if (!config.targets.woo.import_out_of_stock_product.upc.include.includes(itemText)) {
                                        config.targets.woo.import_out_of_stock_product.upc.include.push(itemText);
                                    }
                                    editor.set(config);
                                    return;
                                }

                                // Analytics Tag Mapping (multi-entry): per-entry product_classes / categories
                                if (typeof gffcAnalyticsTagParseContainerId === 'function') {
                                    const atagParsed = gffcAnalyticsTagParseContainerId(containerId);
                                    if (atagParsed) {
                                        const entry = gffcAnalyticsTagFindEntry(atagParsed.section, atagParsed.entryId);
                                        if (entry) {
                                            const itemText = (item && item.querySelector)
                                                ? (item.querySelector('span') ? item.querySelector('span').textContent : '')
                                                : String(item).trim();
                                            if (itemText) {
                                                if (!Array.isArray(entry[atagParsed.field])) entry[atagParsed.field] = [];
                                                if (!entry[atagParsed.field].includes(itemText)) {
                                                    entry[atagParsed.field].push(itemText);
                                                    gffcAnalyticsTagsSyncToConfig();
                                                }
                                            }
                                        }
                                        return;
                                    }
                                }

                                // Check if this is a target product group container
                                const targetGroupMatch = containerId.match(/^target_group_([^_]+)_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (targetGroupMatch) {
                                    // This is a target product group - use the target group handler
                                    addConfigArrayItemToTargetGroup(container, item);
                                    return;
                                }
                                
                                // Check if this is a distributor product group container
                                const distributorGroupMatch = containerId.match(/^distributor_group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (distributorGroupMatch) {
                                    console.log('Distributor group detected:', distributorGroupMatch);
                                    const groupIdPart = distributorGroupMatch[1];
                                    const field = distributorGroupMatch[2];
                                    console.log('Distributor group details:', { groupIdPart, field, item, itemType: typeof item });
                                    
                                    const config = editor.get();
                                    let targetDistributor = null;
                                    
                                    // Find the distributor by looking for the group in all distributors
                                    for (const distributor in config.distributors) {
                                        if (config.distributors[distributor].product_restrictions?.product_groups?.find(g => g.id === groupIdPart)) {
                                            targetDistributor = distributor;
                                            break;
                                        }
                                    }
                                    
                                    if (targetDistributor) {
                                        const group = config.distributors[targetDistributor].product_restrictions.product_groups.find(g => g.id === groupIdPart);
                                        if (group) {
                                            if (!group.criteria) group.criteria = {};
                                            if (!group.criteria[field]) group.criteria[field] = [];
                                            
                                            // Extract text properly from item
                                            let itemText;
                                            if (item.querySelector) {
                                                // item is an element, use querySelector to get the text content of the span
                                                itemText = item.querySelector('span') ? item.querySelector('span').textContent : '';
                                            } else {
                                                // item is already text
                                                itemText = item;
                                            }
                                            
                                            console.log('Distributor extracted itemText:', { itemText, originalItem: item, field });
                                            
                                            if (itemText && !group.criteria[field].includes(itemText)) {
                                                group.criteria[field].push(itemText);
                                                editor.set(config);
                                                console.log('Successfully added item to distributor group:', { targetDistributor, groupId: groupIdPart, field, itemText });
                                            } else if (!itemText) {
                                                console.log('Empty itemText, not adding to distributor group:', { targetDistributor, groupId: groupIdPart, field, item });
                                            } else {
                                                console.log('Item already exists in distributor group:', { targetDistributor, groupId: groupIdPart, field, itemText });
                                            }
                                        } else {
                                            console.log('Distributor group not found with id:', groupIdPart);
                                        }
                                    } else {
                                        console.log('No distributor found with group id:', groupIdPart);
                                    }
                                    return;
                                }
                                
                                // Check if this is a regular product group container
                                const groupIdMatch = containerId.match(/^group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                
                                if (groupIdMatch) {
                                    // This is a product group - use the product group handler
                                    addConfigArrayItemToGroup(container, item);
                                    return;
                                }
                                
                                // Legacy handling for other containers
                                let configItemsArray = null
                                let config = editor.get();
                                configItemsArray = getConfigValue(config, container.id);
                                if (configItemsArray == undefined){
                                    setConfigValue(config, container.id, []);
                                    configItemsArray = getConfigValue(config, container.id);
                                }
                                
                                var itemText = null;
                                if (item.querySelector) {
                                    // item is an element, use querySelector to get the text content of the span
                                    itemText = item.querySelector('span') ? item.querySelector('span').textContent : '';
                                } else {
                                    // item is already text
                                    itemText = item;
                                }

                                if (configItemsArray == null){
                                    configItemsArray = [itemText];
                                }else{
                                    if (!configItemsArray.includes(itemText)) {
                                        configItemsArray.push(itemText);
                                    }
                                }

                                editor.set(config);
                            }

                            function addMarginGroup(margin_name=null, margin_config=null, is_new=false, parent=null) {
                                if (is_new && margin_name == null) {
                                    margin_name = prompt(`Enter your custom margin group name (ex: Firearms, Ammunition):`);
                                    if (margin_name == null) {
                                        return;
                                    } else {
                                        margin_name = margin_name.replace(/[^a-zA-Z0-9-\s]/g, "").replace(/[-\s]/g, "_");
                                    }
                                    var config = editor.get();
                                    if (parent != null){
                                        config.pricing.margin[margin_name] = JSON.parse(JSON.stringify(config.pricing.margin[parent]));
                                    }else{
                                        config.pricing.margin[margin_name] = {
                                            "margin_dollar": config.pricing.margin.default.margin_dollar,
                                            "margin_percentage": config.pricing.margin.default.margin_percentage,
                                            "product_class": [],
                                            "distributor": [],
                                            "sku": [],
                                            "category": [],
                                            "upc": [],
                                            "brand": []
                                        };
                                    }
                                    editor.set(config);
                                    config = editor.get();
                                    margin_config = config.pricing.margin[margin_name];
                                }
                                const container = document.getElementById('margin-group-container');
                                const div = document.createElement('div');
                                div.className = 'group-container';
                                var groupId = `group-${margin_name ? margin_name : Date.now()}`;
        
                                div.innerHTML = `
                                    <div class="group-header">
                                        <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${groupId}', this)">
                                            <i class="fas fa-plus accordion-toggle-icon"></i>${margin_name}
                                        </div>
                                        <i class="fas fa-copy copy-link" title="Duplicate Margin Group" style="margin-left: auto; margin-right: 8px;" onclick="addMarginGroup(null,null, true, '${margin_name}')"></i>
                                        <i class="fas fa-trash-alt remove-link" title="Delete Margin Group" onclick="removeMarginGroup(this, '${margin_name}')"></i>
                                    </div>
                                    <div class="accordion-content" id="${groupId}">
                                        <div id="group-summary-${groupId}" style="margin-bottom:12px;padding:10px 12px;background:#f0f9ff;border:1px solid #bae6fd;border-radius:6px;font-size:12px;color:#0c4a6e;display:none;">
                                        </div>
                                        <div class="form-row">
                                            <label for="product_class">Product Class:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-product_class"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('productClassModal', 'pricing-margin-${margin_name}-product_class')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-product_class'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label>Category:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-category"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('categoryModal', 'pricing-margin-${margin_name}-category')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-category'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label for="brand">Brand:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-brand"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('brandModal', 'pricing-margin-${margin_name}-brand')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-brand'))">Remove All</span>
                                                </div>  
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label for="distributor">Distributor:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-distributor"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('distributorModal', 'pricing-margin-${margin_name}-distributor')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-distributor'))">Remove All</span>
                                                </div>  
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label for="sku">SKU:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-sku"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="promptAndAddItems(this, 'sku', 'pricing-margin-${margin_name}-sku')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-sku'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label for="upc">UPC:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="pricing-margin-${margin_name}-upc"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="promptAndAddItems(this, 'upc', 'pricing-margin-${margin_name}-upc')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-margin-${margin_name}-upc'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-row">
                                            <label for="margin_percentage">Margin (%):</label>
                                            <input class="field-number" type="number" name="margin_percentage" id="pricing-margin-${margin_name}-margin_percentage" min="0" max="0.99" step="0.01" value="${margin_config ? margin_config.margin_percentage : ''}"  data-autosave="true">
                                        </div>
                                        <div class="form-row">
                                            <label for="margin_dollar">Margin ($):</label>
                                            <input class="field-number" type="number" name="margin_dollar" id="pricing-margin-${margin_name}-margin_dollar" value="${margin_config ? margin_config.margin_dollar : ''}" data-autosave="true">
                                        </div>
                                        <div class="form-row">
                                            <label for="price_based_margin">Cost Based Margin:</label>
                                            <div class="field-container">
                                                <div style="font-size: 12px; color: #b32d2e; margin-bottom: 8px; font-style: italic; font-weight: 600;">Margin applies when: cost ≥ Min Cost AND cost &lt; Max Cost</div>
                                                <table class="price-based-margin-table" id="price-based-margin-table-${groupId}">
                                                    <thead>
                                                        <tr style="white-space: nowrap;">
                                                            <th><span class="gffc-th-full">Min Cost ($)</span><span class="gffc-th-short">Min ($)</span></th>
                                                            <th><span class="gffc-th-full">Max Cost ($)</span><span class="gffc-th-short">Max ($)</span></th>
                                                            <th><span class="gffc-th-full">Margin (%)</span><span class="gffc-th-short">Margin (%)</span></th>
                                                            <th><span class="gffc-th-full">Margin ($)</span><span class="gffc-th-short">Margin ($)</span></th>
                                                            <th><span class="gffc-th-full">Actions</span><span class="gffc-th-short">Act</span></th>
                                                        </tr>
                                                    </thead>
                                                    <tbody></tbody>
                                                </table>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('priceBasedMarginModal', 'price-based-margin-table-${groupId}')">Add Cost Based Margin</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                container.appendChild(div);

                                if (margin_config!=null){
                                    filterElements = [
                                        {"name": "product_class", "selectedItemsContainer": "pricing-margin-" + margin_name + "-product_class"},
                                        {"name": "brand", "selectedItemsContainer": "pricing-margin-" + margin_name + "-brand"},
                                        {"name": "category", "selectedItemsContainer": "pricing-margin-" + margin_name + "-category"},
                                        {"name": "distributor", "selectedItemsContainer": "pricing-margin-" + margin_name + "-distributor"},
                                        {"name": "sku", "selectedItemsContainer": "pricing-margin-" + margin_name + "-sku"},
                                        {"name": "upc", "selectedItemsContainer": "pricing-margin-" + margin_name + "-upc"}
                                    ];
                                    for (const filterElement of filterElements) {
                                        if (margin_config[filterElement.name]){
                                            selectedItemsContainer = document.getElementById(`${filterElement.selectedItemsContainer}`);
                                            addSelectedItemsToContainer(selectedItemsContainer, margin_config[filterElement.name]);
                                        }
                                    }

                                    // load price-based margin table
                                    if (margin_config.price_based_margin){
                                        price_based_margin_table = document.getElementById(`price-based-margin-table-${groupId}`);
                                        const price_based_margin_tbody = price_based_margin_table.querySelector('tbody');
                                        margin_config.price_based_margin.forEach((pbm, index) => {
                                            loadPriceBasedMargin(groupId, price_based_margin_tbody, pbm.minimum_unit_cost, pbm.maximum_unit_cost, pbm.margin_dollar, pbm.margin_percentage, index);
                                        });
                                    }

                                }
                                if (is_new){
                                    expandGroup(groupId, div);
                                    setupAutoSave();
                                }

                                // Set up MutationObserver for dynamic filter summary
                                var mAccContent = document.getElementById(groupId);
                                if (mAccContent) {
                                    (function(gid, mn) {
                                        var mObs = new MutationObserver(function() {
                                            updateGroupFilterSummary(gid, 'pricing-margin-' + mn + '-', gid, 'pricing');
                                        });
                                        mObs.observe(mAccContent, { childList: true, subtree: true, characterData: true });
                                        setTimeout(function() {
                                            updateGroupFilterSummary(gid, 'pricing-margin-' + mn + '-', gid, 'pricing');
                                        }, 100);
                                    })(groupId, margin_name);
                                }
                            }

                            function promptAndAddItems(element, itemType, containerId) {
                                const items = prompt(`Enter ${itemType}s separated by commas:`);
                                
                                if (items) {
                                    const itemArray = items.split(',');
                                    const container = document.getElementById(containerId);
                                    container.classList.remove('hidden');
                                    itemArray.forEach(item => {
                                        // add the item to the configuration
                                        addConfigArrayItem(container, item);

                                        // add theitem to theUI
                                        const div = document.createElement('div');
                                        div.className = 'selected-item';
                                        const span = document.createElement('span');
                                        span.textContent = item.trim();
                                        const link = document.createElement('i');
                                        link.className = 'fas fa-trash-alt remove-link';
                                        link.title = 'Remove item'; 
                                        link.onclick = () => removeConfigArrayItem(container, div);
                                        div.appendChild(span);
                                        div.appendChild(link);
                                        container.appendChild(div);
                                        
                                    });
                                }
                            }

                            function removeMarginGroup(link, group_name) {
                                
                                const config = editor.get();
                                delete config.pricing.margin[group_name];
                                editor.set(config);

                                const group = link.closest('.group-container');
                                group.parentNode.removeChild(group);
                            }

                            // Shipping Profile Functions
                            function addShippingProfile(target, profile_name=null, profile_config=null, is_new=false, parent=null) {
                                if (is_new && profile_name == null) {
                                    profile_name = prompt(`Enter shipping profile name (ex: Standard, Expedited):`);
                                    if (profile_name == null) {
                                        return;
                                    } else {
                                        profile_name = profile_name.replace(/[^a-zA-Z0-9-\s]/g, "").replace(/[-\s]/g, "_").toLowerCase();
                                    }
                                    var config = editor.get();
                                    if (!config.targets[target].shipping_profiles) {
                                        config.targets[target].shipping_profiles = {};
                                    }
                                    if (parent != null){
                                        config.targets[target].shipping_profiles[profile_name] = JSON.parse(JSON.stringify(config.targets[target].shipping_profiles[parent]));
                                    }else{
                                        config.targets[target].shipping_profiles[profile_name] = {
                                            "profile_id": 1,
                                            "distributors": [],
                                            "product_restrictions": {
                                                "product_class": {
                                                    "include": [],
                                                    "exclude": []
                                                },
                                                "category": {
                                                    "include": [],
                                                    "exclude": []
                                                },
                                                "brand": {
                                                    "include": [],
                                                    "exclude": []
                                                }
                                            }
                                        };
                                    }
                                    editor.set(config);
                                    config = editor.get();
                                    profile_config = config.targets[target].shipping_profiles[profile_name];
                                }
                                
                                const container = document.getElementById(`shipping-profile-container-${target}`);
                                const div = document.createElement('div');
                                div.className = 'group-container';
                                var profileId = `shipping-profile-${target}-${profile_name ? profile_name : Date.now()}`;
        
                                div.innerHTML = `
                                    <div class="group-header">
                                        <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${profileId}', this)">
                                            <i class="fas fa-plus accordion-toggle-icon"></i>${profile_name}
                                        </div>
                                        <i class="fas fa-copy copy-link" title="Duplicate Shipping Profile" style="margin-left: auto; margin-right: 8px;" onclick="addShippingProfile('${target}', null, null, true, '${profile_name}')"></i>
                                        <i class="fas fa-trash-alt remove-link" title="Delete Shipping Profile" onclick="removeShippingProfile(this, '${target}', '${profile_name}')"></i>
                                    </div>
                                    <div class="accordion-content" id="${profileId}">
                                        <div class="helperDialog">Configure the shipping profile ID and which products it applies to</div>
                                        <div class="form-row">
                                            <label for="profile_id">Profile ID:</label>
                                            <input class="field-number" type="number" name="profile_id" id="targets-${target}-shipping_profiles-${profile_name}-profile_id" min="1" value="${profile_config ? profile_config.profile_id : '1'}" data-autosave="true">
                                        </div>
                                        <div class="form-row">
                                            <label for="distributors">Distributors:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-distributors"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('distributorModal', 'targets-${target}-shipping_profiles-${profile_name}-distributors')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-distributors'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Product Classes</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('productClassModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-include'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="product_class">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('productClassModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-product_class-exclude'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Categories</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('categoryModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-include'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="category">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('categoryModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-category-exclude'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Brands</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('brandModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-include'))">Remove All</span>
                                                        </div>  
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="brand">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('brandModal', 'targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-brand-exclude'))">Remove All</span>
                                                        </div>  
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Cost Restrictions</strong></div>
                                            <div style="width: 100%;">
                                                <div style="width: 100%;">
                                                    <label>Cost Range:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_profiles-${profile_name}-product_restrictions-cost-display" style="min-height: 20px;"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="toggleCostRange('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-cost')" id="targets-${target}-shipping_profiles-${profile_name}-cost-toggle">Add Range</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeCostRange('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-cost')" id="targets-${target}-shipping_profiles-${profile_name}-cost-remove" style="display: none;">Remove Range</span>
                                                        </div>
                                                    </div>
                                                    <div class="cost-range-inputs" id="targets-${target}-shipping_profiles-${profile_name}-cost-inputs" style="display: none; margin-top: 15px; padding: 20px; background: #f9f9f9; border-radius: 4px; border: 1px solid #e0e0e0;">
                                                        <div style="margin-bottom: 20px;">
                                                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; max-width: 600px;">
                                                                <div>
                                                                    <label for="min-cost" style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 500; color: #333;">Minimum Cost ($):</label>
                                                                    <input type="number" id="targets-${target}-shipping_profiles-${profile_name}-min-cost" placeholder="0.00" step="0.01" min="0" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                                                                </div>
                                                                <div>
                                                                    <label for="max-cost" style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 500; color: #333;">Maximum Cost ($):</label>
                                                                    <input type="number" id="targets-${target}-shipping_profiles-${profile_name}-max-cost" placeholder="999.99" step="0.01" min="0" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                                                                </div>
                                                            </div>
                                                            <div style="text-align: right;">
                                                                <button type="button" onclick="saveCostRange('targets-${target}-shipping_profiles-${profile_name}-product_restrictions-cost')" class="button button-primary" style="padding: 10px 20px; height: auto; font-size: 14px;">Save Cost Range</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                container.appendChild(div);

                                if (profile_config != null) {
                                    // Load existing distributors
                                    if (profile_config.distributors) {
                                        const distributorsContainer = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-distributors`);
                                        addSelectedItemsToContainer(distributorsContainer, profile_config.distributors);
                                    }
                                    
                                    // Load existing product restrictions
                                    const restrictions = ['product_class', 'category', 'brand'];
                                    const includeExcludes = ['include', 'exclude'];
                                    
                                    restrictions.forEach(restriction => {
                                        includeExcludes.forEach(includeExclude => {
                                            if (profile_config.product_restrictions && profile_config.product_restrictions[restriction] && profile_config.product_restrictions[restriction][includeExclude]) {
                                                const container = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-product_restrictions-${restriction}-${includeExclude}`);
                                                if (container) {
                                                    addSelectedItemsToContainer(container, profile_config.product_restrictions[restriction][includeExclude]);
                                                }
                                            }
                                        });
                                    });
                                    
                                    // Load existing cost restrictions
                                    if (profile_config.product_restrictions && profile_config.product_restrictions.cost) {
                                        const costDisplayDiv = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-product_restrictions-cost-display`);
                                        const minInput = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-min-cost`);
                                        const maxInput = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-max-cost`);
                                        const toggleBtn = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-cost-toggle`);
                                        const removeBtn = document.getElementById(`targets-${target}-shipping_profiles-${profile_name}-cost-remove`);
                                        
                                        if (costDisplayDiv && profile_config.product_restrictions.cost.global_restrictions) {
                                            const globalRestrictions = profile_config.product_restrictions.cost.global_restrictions;
                                            let rangeText = '';
                                            
                                            if (globalRestrictions.min_distributor_cost !== undefined && globalRestrictions.max_distributor_cost !== undefined) {
                                                rangeText = `$${globalRestrictions.min_distributor_cost} - $${globalRestrictions.max_distributor_cost}`;
                                                if (minInput) minInput.value = globalRestrictions.min_distributor_cost;
                                                if (maxInput) maxInput.value = globalRestrictions.max_distributor_cost;
                                            } else if (globalRestrictions.min_distributor_cost !== undefined) {
                                                rangeText = `$${globalRestrictions.min_distributor_cost}+`;
                                                if (minInput) minInput.value = globalRestrictions.min_distributor_cost;
                                            } else if (globalRestrictions.max_distributor_cost !== undefined) {
                                                rangeText = `Up to $${globalRestrictions.max_distributor_cost}`;
                                                if (maxInput) maxInput.value = globalRestrictions.max_distributor_cost;
                                            }
                                            
                                            if (rangeText) {
                                                costDisplayDiv.innerHTML = `
                                                    <div class="selected-item">
                                                        <span>${rangeText}</span>
                                                    </div>
                                                `;
                                                if (toggleBtn) toggleBtn.textContent = 'Edit Range';
                                                if (removeBtn) removeBtn.style.display = 'inline';
                                            }
                                        }
                                    }
                                }
                                
                                if (is_new) {
                                    expandGroup(profileId, div);
                                    setupAutoSave();
                                }
                            }

                            function removeShippingProfile(link, target, profile_name) {
                                if (confirm('Are you sure you want to remove this shipping profile?')) {
                                    const config = editor.get();
                                    if (config.targets[target].shipping_profiles) {
                                        delete config.targets[target].shipping_profiles[profile_name];
                                        editor.set(config);
                                    }
                                    const group = link.closest('.group-container');
                                    group.parentNode.removeChild(group);
                                }
                            }

                            // Shipping Class Functions for WooCommerce
                            function addShippingClass(target, class_name=null, class_config=null, is_new=false, parent=null) {
                                if (is_new && class_name == null) {
                                    class_name = prompt(`Enter shipping class name (ex: Free Shipping, Heavy Items):`);
                                    if (class_name == null) {
                                        return;
                                    } else {
                                        class_name = class_name.replace(/[^a-zA-Z0-9-\s]/g, "").replace(/[-\s]/g, "_").toLowerCase();
                                    }
                                    var config = editor.get();
                                    if (!config.targets[target].shipping_classes) {
                                        config.targets[target].shipping_classes = {};
                                    }
                                    if (parent != null){
                                        config.targets[target].shipping_classes[class_name] = JSON.parse(JSON.stringify(config.targets[target].shipping_classes[parent]));
                                    }else{
                                        config.targets[target].shipping_classes[class_name] = {
                                            "distributors": [],
                                            "product_restrictions": {
                                                "product_class": {
                                                    "include": [],
                                                    "exclude": []
                                                },
                                                "category": {
                                                    "include": [],
                                                    "exclude": []
                                                },
                                                "brand": {
                                                    "include": [],
                                                    "exclude": []
                                                }
                                            }
                                        };
                                    }
                                    editor.set(config);
                                    config = editor.get();
                                    class_config = config.targets[target].shipping_classes[class_name];
                                }

                                const container = document.getElementById(`shipping-class-container-${target}`);
                                const div = document.createElement('div');
                                div.className = 'group-container';
                                var classId = `shipping-class-${class_name ? class_name : Date.now()}`;
                                
                                div.innerHTML = `
                                    <div class="group-header">
                                        <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${classId}', this)">
                                            <i class="fas fa-plus accordion-toggle-icon"></i>${class_name}
                                        </div>
                                        <i class="fas fa-copy copy-link" title="Duplicate Shipping Class" style="margin-left: auto; margin-right: 8px;" onclick="addShippingClass('${target}', null, null, true, '${class_name}')"></i>
                                        <i class="fas fa-trash-alt remove-link" title="Delete Shipping Class" onclick="removeShippingClass(this, '${target}', '${class_name}')"></i>
                                    </div>
                                    <div class="accordion-content" id="${classId}">
                                        <div class="helperDialog">Configure which products should be assigned to the "${class_name}" shipping class</div>
                                        <div class="form-row">
                                            <label for="distributors">Distributors:</label>
                                            <div class="field-container">
                                                <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-distributors"></div>
                                                <div class="add-item-container">
                                                    <span class="add-item" onclick="openModal('distributorModal', 'targets-${target}-shipping_classes-${class_name}-distributors')">Select</span>&nbsp;|&nbsp;
                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-distributors'))">Remove All</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Product Classes</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('productClassModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-include'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="product_class">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('productClassModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-product_class-exclude'))">Remove All</span>
                                                        </div>  
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Categories</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-category-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('categoryModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-category-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-category-include'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="category">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-category-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('categoryModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-category-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-category-exclude'))">Remove All</span>
                                                        </div>  
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Brands</strong></div>
                                            <div class="restriction-container">
                                                <div class="restriction-item">
                                                    <label>Include:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-include"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('brandModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-include')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-include'))">Remove All</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="restriction-item">
                                                    <label for="brand">Exclude:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-exclude"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="openModal('brandModal', 'targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-exclude')">Select</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-shipping_classes-${class_name}-product_restrictions-brand-exclude'))">Remove All</span>
                                                        </div>  
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="restriction-section">
                                            <div class="g-ffl-restriction-header"><strong>Cost Restrictions</strong></div>
                                            <div style="width: 100%;">
                                                <div style="width: 100%;">
                                                    <label>Cost Range:</label>
                                                    <div class="field-container">
                                                        <div class="selected-items" id="targets-${target}-shipping_classes-${class_name}-product_restrictions-cost-display" style="min-height: 20px;"></div>
                                                        <div class="add-item-container">
                                                            <span class="add-item" onclick="toggleCostRange('targets-${target}-shipping_classes-${class_name}-product_restrictions-cost')" id="targets-${target}-shipping_classes-${class_name}-cost-toggle">Add Range</span>&nbsp;|&nbsp;
                                                            <span class="add-item" onclick="removeCostRange('targets-${target}-shipping_classes-${class_name}-product_restrictions-cost')" id="targets-${target}-shipping_classes-${class_name}-cost-remove" style="display: none;">Remove Range</span>
                                                        </div>
                                                    </div>
                                                    <div class="cost-range-inputs" id="targets-${target}-shipping_classes-${class_name}-cost-inputs" style="display: none; margin-top: 15px; padding: 20px; background: #f9f9f9; border-radius: 4px; border: 1px solid #e0e0e0;">
                                                        <div style="margin-bottom: 20px;">
                                                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; max-width: 600px;">
                                                                <div>
                                                                    <label for="min-cost" style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 500; color: #333;">Minimum Cost ($):</label>
                                                                    <input type="number" id="targets-${target}-shipping_classes-${class_name}-min-cost" placeholder="0.00" step="0.01" min="0" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                                                                </div>
                                                                <div>
                                                                    <label for="max-cost" style="display: block; margin-bottom: 8px; font-size: 14px; font-weight: 500; color: #333;">Maximum Cost ($):</label>
                                                                    <input type="number" id="targets-${target}-shipping_classes-${class_name}-max-cost" placeholder="999.99" step="0.01" min="0" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                                                                </div>
                                                            </div>
                                                            <div style="text-align: right;">
                                                                <button type="button" onclick="saveCostRange('targets-${target}-shipping_classes-${class_name}-product_restrictions-cost')" class="button button-primary" style="padding: 10px 20px; height: auto; font-size: 14px;">Save Cost Range</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;
                                container.appendChild(div);

                                if (class_config != null) {
                                    // Load existing distributors
                                    if (class_config.distributors) {
                                        const distributorsContainer = document.getElementById(`targets-${target}-shipping_classes-${class_name}-distributors`);
                                        addSelectedItemsToContainer(distributorsContainer, class_config.distributors);
                                    }
                                    
                                    // Load existing product restrictions
                                    const restrictionTypes = ['product_class', 'category', 'brand'];
                                    restrictionTypes.forEach(restrictionType => {
                                        ['include', 'exclude'].forEach(operation => {
                                            const containerId = `targets-${target}-shipping_classes-${class_name}-product_restrictions-${restrictionType}-${operation}`;
                                            const container = document.getElementById(containerId);
                                            if (container && class_config.product_restrictions && class_config.product_restrictions[restrictionType] && class_config.product_restrictions[restrictionType][operation]) {
                                                addSelectedItemsToContainer(container, class_config.product_restrictions[restrictionType][operation]);
                                            }
                                        });
                                    });
                                    
                                    // Load existing cost restrictions
                                    if (class_config.product_restrictions && class_config.product_restrictions.cost) {
                                        const costDisplayDiv = document.getElementById(`targets-${target}-shipping_classes-${class_name}-product_restrictions-cost-display`);
                                        const minInput = document.getElementById(`targets-${target}-shipping_classes-${class_name}-min-cost`);
                                        const maxInput = document.getElementById(`targets-${target}-shipping_classes-${class_name}-max-cost`);
                                        const toggleBtn = document.getElementById(`targets-${target}-shipping_classes-${class_name}-cost-toggle`);
                                        const removeBtn = document.getElementById(`targets-${target}-shipping_classes-${class_name}-cost-remove`);
                                        
                                        if (costDisplayDiv && class_config.product_restrictions.cost.global_restrictions) {
                                            const globalRestrictions = class_config.product_restrictions.cost.global_restrictions;
                                            let rangeText = '';
                                            
                                            if (globalRestrictions.min_distributor_cost !== undefined && globalRestrictions.max_distributor_cost !== undefined) {
                                                rangeText = `$${globalRestrictions.min_distributor_cost} - $${globalRestrictions.max_distributor_cost}`;
                                                if (minInput) minInput.value = globalRestrictions.min_distributor_cost;
                                                if (maxInput) maxInput.value = globalRestrictions.max_distributor_cost;
                                            } else if (globalRestrictions.min_distributor_cost !== undefined) {
                                                rangeText = `$${globalRestrictions.min_distributor_cost}+`;
                                                if (minInput) minInput.value = globalRestrictions.min_distributor_cost;
                                            } else if (globalRestrictions.max_distributor_cost !== undefined) {
                                                rangeText = `Up to $${globalRestrictions.max_distributor_cost}`;
                                                if (maxInput) maxInput.value = globalRestrictions.max_distributor_cost;
                                            }
                                            
                                            if (rangeText) {
                                                costDisplayDiv.innerHTML = `
                                                    <div class="selected-item">
                                                        <span>${rangeText}</span>
                                                    </div>
                                                `;
                                                if (toggleBtn) toggleBtn.textContent = 'Edit Range';
                                                if (removeBtn) removeBtn.style.display = 'inline';
                                            }
                                        }
                                    }
                                }
                                
                                setupAutoSave();
                                
                                if (is_new) {
                                    const header = div.querySelector('.accordion-header');
                                    if (header) {
                                        header.click();
                                    }
                                }
                                
                                return class_name;
                            }

                            function removeShippingClass(link, target, class_name) {
                                if (confirm('Are you sure you want to remove this shipping class?')) {
                                    const config = editor.get();
                                    if (config.targets[target].shipping_classes) {
                                        delete config.targets[target].shipping_classes[class_name];
                                        editor.set(config);
                                    }
                                    const group = link.closest('.group-container');
                                    group.parentNode.removeChild(group);
                                }
                            }

                            function toggleAccordion(groupId, element) {
                                const content = document.getElementById(groupId);
                                if (!content) {
                                    console.error(`Element with id ${groupId} not found.`);
                                    return;
                                }

                                const header = element.closest('.accordion-header');
                                if (!header) {
                                    console.error('Header element not found.');
                                    return;
                                }

                                const icon = header.querySelector('.accordion-toggle-icon');
                                if (!icon) {
                                    console.error(`Icon element with class 'accordion-toggle-icon' not found.`);
                                    return;
                                }

                                if (content.style.display === 'none' || content.style.display === '') {
                                    expandGroup(groupId, header.parentNode);
                                    icon.classList.add('fa-minus');
                                    icon.classList.remove('fa-plus');
                                    
                                    // Load job status table when expanding AI product groups
                                    if (groupId.startsWith('ai-product-group-')) {
                                        const groupName = groupId.replace('ai-product-group-', '');
                                        // Only load if the table container exists but is empty or has loading message
                                        const tableContainer = document.getElementById(`job-status-table-${groupName}`);
                                        if (tableContainer && (tableContainer.innerHTML.trim() === '' || tableContainer.innerHTML.includes('Loading job history'))) {
                                            loadJobStatusTable(groupName);
                                        }
                                    }
                                } else {
                                    content.style.display = 'none';
                                    icon.classList.add('fa-plus');
                                    icon.classList.remove('fa-minus');
                                }
                            }


                            function expandGroup(groupId, groupElement) {
                                const content = document.getElementById(groupId);
                                const allGroups = document.querySelectorAll('.group-container .accordion-content');
                                allGroups.forEach(group => {
                                    if (group !== content) {
                                        group.style.display = 'none';
                                        group.previousElementSibling.querySelector('.accordion-toggle-icon').classList.add('fa-plus');
                                        group.previousElementSibling.querySelector('.accordion-toggle-icon').classList.remove('fa-minus');
                                    }
                                });
                                content.style.display = 'block';
                                groupElement.querySelector('.accordion-toggle-icon').classList.remove('fa-plus');
                                groupElement.querySelector('.accordion-toggle-icon').classList.add('fa-minus');
                            }

                            function updateGroupName(input) {
                                const groupName = input.closest('.accordion-content').previousElementSibling.querySelector('.group-name');
                                groupName.textContent = input.value;
                            }

                            function removeAllRowsExceptHeader(table) {
                                var rowCount = table.rows.length;
                                for (var i = rowCount - 1; i > 0; i--) {
                                    table.deleteRow(i);
                                }
                            }

                            function loadPriceBasedMargin(margin_group, tableBody, minPrice, maxPrice, marginDollar, marginPercentage, rowIndex = null){
                                const row = document.createElement('tr');
                                const margin = {
                                    "minimum_unit_cost": minPrice,
                                    "maximum_unit_cost": maxPrice,
                                    "margin_dollar": marginDollar,
                                    "margin_percentage": marginPercentage
                                }
                                
                                // Use the row index from the table (will be set after appending)
                                // or calculate it if not provided
                                let actualRowIndex = rowIndex;
                                if (actualRowIndex === null) {
                                    actualRowIndex = tableBody.rows.length;
                                }
                                
                                row.innerHTML = `
                                    <td class="editable-cell" data-field="min">${minPrice}</td>
                                    <td class="editable-cell" data-field="max">${maxPrice}</td>
                                    <td class="editable-cell" data-field="margin_percentage">${marginPercentage}</td>
                                    <td class="editable-cell" data-field="margin_dollar">${marginDollar}</td>
                                    <td>
                                        <i class="fas fa-edit edit-link" title="Edit Row" onclick="editPriceBasedMarginRowByIndex(this, '${margin_group}')" style="margin-right: 10px; cursor: pointer; color: #0073aa;"></i>
                                        <i class="fas fa-trash-alt remove-link" title="Remove Item" onclick="removePriceBasedMarginTierByIndex(this, '${margin_group}')"></i>
                                    </td>
                                `;
                                tableBody.appendChild(row);
                            }

                            function savePriceBasedMargin() {
                                const modal = document.getElementById('priceBasedMarginModal');
                                const selectedItemsId = modal.getAttribute('data-selected-items-id');
                                const tableBody = document.querySelector(`#${CSS.escape(selectedItemsId)} tbody`);
                                const minPrice = isNaN(parseFloat(document.getElementById('min_price').value)) ? 0 : parseFloat(document.getElementById('min_price').value);
                                const maxPrice = isNaN(parseFloat(document.getElementById('max_price').value)) ? 0 : parseFloat(document.getElementById('max_price').value);
                                const marginDollar = isNaN(parseFloat(document.getElementById('margin_dollar').value)) ? 0 : parseFloat(document.getElementById('margin_dollar').value);
                                const marginPercentage = isNaN(parseFloat(document.getElementById('margin_percentage').value)) ? 0 : parseFloat(document.getElementById('margin_percentage').value);
                                const config = editor.get();
                                var groupName = selectedItemsId.split("group-")[1];
                                const pbm = {
                                        "minimum_unit_cost": minPrice,
                                        "maximum_unit_cost": maxPrice,
                                        "margin_dollar": marginDollar,
                                        "margin_percentage": marginPercentage
                                }
                                
                                // Check if we're editing an existing row
                                const editingRowIndex = modal.getAttribute('data-editing-row-index');
                                const editingGroup = modal.getAttribute('data-editing-group');
                                
                                if (minPrice >= 0 && maxPrice > 0 && maxPrice >= minPrice) {
                                    if (editingRowIndex !== null && editingGroup) {
                                        // Update existing row by index - use the editing group name
                                        const rowIndex = parseInt(editingRowIndex);
                                        let actualGroupName = editingGroup;
                                        if (actualGroupName.startsWith("group-")){
                                            actualGroupName = actualGroupName.split("group-")[1];
                                        }
                                        if (config.pricing.margin[actualGroupName].price_based_margin && 
                                            config.pricing.margin[actualGroupName].price_based_margin[rowIndex]) {
                                            config.pricing.margin[actualGroupName].price_based_margin[rowIndex] = pbm;
                                            
                                            // Sort the array by minimum_unit_cost
                                            config.pricing.margin[actualGroupName].price_based_margin.sort((a, b) => a.minimum_unit_cost - b.minimum_unit_cost);
                                            
                                            editor.set(config);
                                            
                                            // Rebuild the table to reflect the new order
                                            rebuildPriceBasedMarginTable(actualGroupName, tableBody);
                                        }
                                    } else {
                                        // Add new row
                                        if (!config.pricing.margin[groupName].price_based_margin){
                                            config.pricing.margin[groupName]['price_based_margin'] = [pbm];
                                        }else{
                                            config.pricing.margin[groupName].price_based_margin.push(pbm);
                                        }
                                        
                                        // Sort the array by minimum_unit_cost
                                        config.pricing.margin[groupName].price_based_margin.sort((a, b) => a.minimum_unit_cost - b.minimum_unit_cost);
                                        
                                        editor.set(config);
                                        
                                        // Rebuild the table to show sorted order
                                        rebuildPriceBasedMarginTable(groupName, tableBody);
                                    }
                                } else {
                                    alert('Please ensure Min Price is non-negative, Max Price is greater than 0, and Max Price is greater than or equal to Min Price.');
                                    return;
                                }
                                
                                // Clear editing state
                                modal.removeAttribute('data-editing-row-index');
                                modal.removeAttribute('data-editing-group');
                                
                                closeModal('priceBasedMarginModal');
                            }

                            function removePriceBasedMarginTierByIndex(deleteButton, groupName) {
                                if (confirm('Are you sure you want to remove this cost based margin tier?')) {
                                    const row = deleteButton.closest('tr');
                                    const tableBody = row.closest('tbody');
                                    const rowIndex = Array.from(tableBody.rows).indexOf(row);
                                    
                                    // Validation
                                    if (rowIndex === -1) {
                                        console.error('Could not find row index');
                                        return;
                                    }
                                    
                                    var config = editor.get();
                                    let actualGroupName = groupName;
                                    if (actualGroupName.startsWith("group-")){
                                        actualGroupName = actualGroupName.split("group-")[1];
                                    }
                                    
                                    // Remove the item at the specific index
                                    if (config.pricing.margin[actualGroupName].price_based_margin && 
                                        config.pricing.margin[actualGroupName].price_based_margin[rowIndex]) {
                                        config.pricing.margin[actualGroupName].price_based_margin.splice(rowIndex, 1);
                                        
                                        // Sort the remaining elements by minimum_unit_cost in ascending order
                                        config.pricing.margin[actualGroupName].price_based_margin.sort((a, b) => a.minimum_unit_cost - b.minimum_unit_cost);
                                        
                                        editor.set(config);
                                        
                                        // Rebuild the table to reflect the new order and indices
                                        rebuildPriceBasedMarginTable(actualGroupName, tableBody);
                                    }
                                }
                            }

                            function editPriceBasedMarginRowByIndex(editButton, groupName) {
                                const row = editButton.closest('tr');
                                const tableBody = row.closest('tbody');
                                const rowIndex = Array.from(tableBody.rows).indexOf(row);
                                
                                // Validation
                                if (rowIndex === -1) {
                                    console.error('Could not find row index');
                                    return;
                                }
                                
                                // Get current values from the row cells
                                const cells = row.cells;
                                const minPrice = parseFloat(cells[0].textContent) || 0;
                                const maxPrice = parseFloat(cells[1].textContent) || 0;
                                const marginPercentage = parseFloat(cells[2].textContent) || 0;
                                const marginDollar = parseFloat(cells[3].textContent) || 0;
                                
                                const modal = document.getElementById('priceBasedMarginModal');
                                const modalHeader = modal.querySelector('.modalHeader');
                                const submitButton = modal.querySelector('button');
                                
                                // Set modal to edit mode
                                modalHeader.textContent = 'Edit Cost Based Margin';
                                submitButton.textContent = 'Update';
                                
                                // Store editing state with row index
                                modal.setAttribute('data-editing-row-index', rowIndex);
                                modal.setAttribute('data-editing-group', groupName);
                                
                                // Populate form with current values
                                document.getElementById('min_price').value = minPrice;
                                document.getElementById('max_price').value = maxPrice;
                                document.getElementById('margin_dollar').value = marginDollar;
                                document.getElementById('margin_percentage').value = marginPercentage;
                                
                                // Open modal
                                const tableId = tableBody.closest('table').id;
                                modal.setAttribute('data-selected-items-id', tableId);
                                modal.style.display = 'block';
                            }



                            function rebuildPriceBasedMarginTable(groupName, tableBody) {
                                const config = editor.get();
                                const pbm = config.pricing.margin[groupName].price_based_margin;
                                
                                // Clear existing rows
                                tableBody.innerHTML = '';
                                
                                // Rebuild rows in sorted order
                                if (pbm && pbm.length > 0) {
                                    // Ensure we pass the group name with "group-" prefix for onclick handlers
                                    const groupNameForHandlers = groupName.startsWith('group-') ? groupName : `group-${groupName}`;
                                    
                                    pbm.forEach((item, index) => {
                                        loadPriceBasedMargin(groupNameForHandlers, tableBody, 
                                            item.minimum_unit_cost, 
                                            item.maximum_unit_cost, 
                                            item.margin_dollar, 
                                            item.margin_percentage,
                                            index
                                        );
                                    });
                                }
                            }


                            function sortTableByMinPrice(tableBody) {
                                const rowsArray = Array.from(tableBody.rows);
                                rowsArray.sort((a, b) => parseFloat(a.cells[0].innerText) - parseFloat(b.cells[0].innerText));
                                rowsArray.forEach(row => tableBody.appendChild(row));
                            }

                            // Add an initial margin group on page load
                            //window.onload = addMarginGroup;

                            // Close the modal when the user clicks anywhere outside of it
                            window.onclick = function(event) {
                                // Check if text is selected - if so, do not close the modal
                                if (window.getSelection().toString().length > 0) {
                                    return;
                                }
                                const modals = document.querySelectorAll('.modal');
                                modals.forEach(modal => {
                                    if (event.target === modal) {
                                        if (modal.id === 'detailsModal') {
                                            // Bootstrap modal - use Bootstrap API
                                            if (typeof jQuery !== 'undefined' && jQuery(modal).modal) {
                                                jQuery(modal).modal('hide');
                                            }
                                        } else {
                                            // Custom modal
                                            modal.style.display = "none";
                                        }
                                    }
                                });
                            }
                        </script>
                        <style>
                            #unsaved-indicator {
                                text-align: left;
                                padding: 5px;
                                width: 100%;
                                display: none;
                            }
                            .validator_view {
                                text-align: left;
                                padding: 5px;
                                width: 100%;
                            }
                            .validator_view:empty {
                                height: 0;
                                padding: 0; /* Optionally, you can also remove padding if there's no content */
                            }
                            .card {
                                width: 220px;
                                margin-bottom: 10px;
                                padding: 5px;
                                position: relative;
                                height: 200px;
                            }

                            .distcards {
                                display: flex;
                                padding-left: 15px;
                                flex-wrap: wrap;
                                justify-content: center; /* Center elements horizontally */
                                align-content: center; /* Center elements vertically within the container */
                                width: 230px;
                            }
                            
                            .targetcards {
                                display: flex;
                                padding-left: 15px;
                                flex-wrap: wrap;
                                gap: 10px;
                                justify-content: center; /* Center elements horizontally */
                                align-content: center; /* Center elements vertically within the container */
                                width: 230px;
                            }

                            @media screen and (max-width: 768px) {
                                /* Distributors + Targets: one card per row */
                                #distributors-container,
                                #targets-container {
                                    margin-left: 0;
                                    margin-right: 0;
                                }

                                #distributors-container .distcards,
                                #targets-container .targetcards {
                                    width: 100% !important;
                                    padding-left: 0 !important;
                                    justify-content: stretch;
                                }

                                #distributors-container .distcards .card,
                                #targets-container .targetcards .card {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                }
                            }

                            .card-header {
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                padding: 5px;
                                background-color: #f8f9fa;
                                border-bottom: 1px solid #e9ecef;
                            }
                            .card-header .card-title {
                                margin-bottom: 5px;
                                font-size: 10px;
                            }
                            .toggle-switch {
                                position: relative;
                                display: inline-block;
                                width: 50px;
                                height: 25px;
                            }
                            .distid_image_area {
                                display: flex;
                                justify-content: center;
                                align-items: center;
                                height: 100px;
                            }
                            .toggle-switch input {
                                opacity: 0;
                                width: 0;
                                height: 0;
                            }
                            .slider {
                                position: absolute;
                                cursor: pointer;
                                top: 0;
                                left: 0;
                                right: 0;
                                bottom: 0;
                                background-color: #ccc;
                                transition: .4s;
                                border-radius: 25px;
                            }
                            .slider:before {
                                position: absolute;
                                content: "";
                                height: 19px;
                                width: 19px;
                                left: 3px;
                                bottom: 3px;
                                background-color: white;
                                transition: .4s;
                                border-radius: 50%;
                            }
                            input:checked + .slider {
                                background-color: #2196F3;
                            }
                            input:checked + .slider:before {
                                transform: translateX(25px);
                            }
                            .email_template_header {
                                display: block;
                                margin-top: 30px;
                                width: 100%;
                                background: #f1f9fbff;
                                border: 1px solid #8cc8e1;
                                border-bottom: 1px solid #000000;
                                border-radius: 4px;
                                padding: 10px 12px;
                                color: black;
                                font-size: 14px;
                                text-align: left;
                                box-sizing: border-box;
                            }
                            .card-body {
                                display: flex;
                                flex-direction: column;
                                align-items: center;
                                padding: 5px;
                            }
                            .action-links {
                                margin-top: 10px;
                                text-align: center;
                                cursor: pointer;
                                
                            }
                            .action-links .remove-link {
                                color: red;
                                margin-left: 5px;
                                text-decoration: underline;
                            }
                            .action-links span {
                                margin: 0 5px;
                                color: #2271b1;
                                text-decoration: underline;
                            }
                            .card-header img {
                                max-height: 75px;
                                max-width: 200px;
                                margin-bottom: 5px;
                            }
                            .form-group {
                                display: flex;
                                flex-wrap: wrap;
                                gap: 10px; /* Adjust spacing between textareas as needed */
                            }
                            .form-groups-wrapper {
                                display: flex;
                                flex-wrap: wrap;
                                gap: 10px; /* Adjust spacing between form groups as needed */
                            }

                            .form-group {
                                flex: 1; /* Allow form groups to grow and fill available space */
                                min-width: 300px; /* Optional: set a minimum width for the form groups */
                            }

                            input {
                                width: 100%; /* Ensure inputs take up full width of their container */
                            }

                            .textarea-wrapper {
                                display: flex;
                                flex-direction: column;
                                flex: 1; /* Allow textareas to grow and fill available space */
                            }

                            /* Mobile: Notifications templates should stack (FFL above Non-FFL) */
                            @media screen and (max-width: 768px) {
                                #notifications-config .textarea-wrapper {
                                    flex: 0 0 100%;
                                    max-width: 100%;
                                    min-width: 0;
                                }

                                #notifications-config textarea {
                                    min-width: 0;
                                }

                                #notifications-config .tox-tinymce {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                }
                            }

                            textarea {
                                width: 100%; /* Ensure textareas take up full width of their container */
                                min-width: 200px; /* Optional: set a minimum width for the textareas */
                            }

                            .nav-tabs {
                                border: 1px solid #ddd;
                                background-color: #eee;
                            }

                            .nav-tabs .nav-item {
                                position: relative;
                            }

                            .nav-tabs .nav-link {
                                border: 1px solid transparent;
                                color: black;
                            }

                            .nav-tabs .nav-link.active {
                                color: black;
                                border: 1px solid #ddd;
                                background-color: #dddddd;
                                position: relative;
                                z-index: 2;
                            }

                            .nav-tabs .nav-link {
                                position: relative;
                                z-index: 1;
                            }

                            .email-template-label {
                                font-style: italic;
                                color: #5F6D9D;
                                font-weight:bold;
                            }

                            #order_fulfillment_table a {
                                color: #2271b1;; /* Sets the link color within the specific div */
                            }

                            .pricing-assumptions-form-header {
                                font-size: 1.5em;
                                margin-bottom: 20px;
                                text-align: center;
                            }
                            .pricing-assumptions-form-row {
                                display: flex;
                                justify-content: space-between;
                                margin-bottom: 10px;
                            }
                            .pricing-assumptions-form-row label {
                                text-align: right;
                                padding-right: 10px;
                            }
                           
                            .pricing-assumptions-form-row input[type="checkbox"] {
                                width: auto;
                                margin-left: 10px;
                            }
                            
                            .pricing-assumptions-form-header {
                                font-size: 1.5em;
                                margin-bottom: 20px;
                                text-align: center;
                            }
                            .pricing-assumptions-form-row {
                                display: flex;
                                justify-content: space-between;
                                align-items: top;
                                margin-bottom: 10px;
                            }
                            .pricing-assumptions-form-row label {
                                width: 45%;
                                text-align: right;
                                padding-right: 10px;
                            }
                            .pricing-assumptions-form-row input,
                            .pricing-assumptions-form-row select {
                                width: 45%;
                                text-align: left;
                            }
               
                            .pricing-tab-container {
                                display: flex;
                                padding: 10px;
                                align-items: flex-start; /* Align items to the top */
                            }

                            .pricing-assumptions-form-container {
                                width: 525px; /* or your preferred width */
                                margin-right: 20px; /* Adjust space between containers */
                                box-sizing: border-box;
                            }

                            /* Mobile: Store/Location fields should stack cleanly */
                            @media screen and (max-width: 768px) {
                                #store-config .helperDialog strong {
                                    display: block;
                                    margin-bottom: 6px;
                                }

                                #store-config .pricing-assumptions-form-container {
                                    width: auto;
                                    max-width: 100%;
                                    margin: 10px 0;
                                    box-sizing: border-box;
                                }

                                #store-config .pricing-assumptions-form-header {
                                    text-align: left;
                                    margin-bottom: 14px;
                                }

                                #store-config .pricing-assumptions-form-row {
                                    display: block;
                                    margin-bottom: 12px;
                                }

                                #store-config .pricing-assumptions-form-row label {
                                    width: 100%;
                                    display: block;
                                    text-align: left;
                                    padding-right: 0;
                                    margin-bottom: 6px;
                                }

                                #store-config .pricing-assumptions-form-row input,
                                #store-config .pricing-assumptions-form-row select {
                                    width: 100%;
                                    max-width: 100%;
                                    box-sizing: border-box;
                                }

                                /* Pricing: switch to one column (core above custom) */
                                #pricing .pricing-tab-container {
                                    flex-direction: column;
                                    align-items: stretch;
                                }

                                #pricing .pricing-assumptions-form-container {
                                    width: auto;
                                    max-width: 100%;
                                    margin-right: 0;
                                    box-sizing: border-box;
                                }

                                #pricing .core-pricing-container { order: 1; }
                                #pricing .custom-margin-container { order: 2; }

                                /* Pricing: make form rows one-column on mobile */
                                #pricing .form-row {
                                    display: block;
                                    margin-bottom: 12px;
                                }
                                #pricing .form-row label {
                                    flex: none;
                                    width: 100%;
                                    display: block;
                                    text-align: left;
                                    margin-bottom: 6px;
                                }
                                #pricing .form-row input,
                                #pricing .form-row select,
                                #pricing .form-row .field-container {
                                    width: 100%;
                                    max-width: 100%;
                                    box-sizing: border-box;
                                }

                                /* Pricing: keep Cost Based Margin looking like a table */
                                #pricing .form-row .field-container {
                                    overflow-x: auto;
                                    -webkit-overflow-scrolling: touch;
                                }
                                #pricing .price-based-margin-table {
                                    display: table;
                                    width: 100%;
                                    max-width: 100%;
                                    min-width: 0;
                                    border-collapse: collapse;
                                    table-layout: fixed;
                                }
                                #pricing .price-based-margin-table thead { display: table-header-group; }
                                #pricing .price-based-margin-table tbody { display: table-row-group; }
                                #pricing .price-based-margin-table tr { display: table-row; }
                                #pricing .price-based-margin-table th,
                                #pricing .price-based-margin-table td {
                                    display: table-cell;
                                    padding: 3px 4px;
                                    font-size: 11px;
                                    white-space: nowrap;
                                    overflow: hidden;
                                    text-overflow: ellipsis;
                                }
                                #pricing .price-based-margin-table th {
                                    font-size: 11px;
                                }

                                /* Pricing: column sizing on mobile so headers fit */
                                #pricing .price-based-margin-table th:nth-child(1),
                                #pricing .price-based-margin-table td:nth-child(1) {
                                    width: 60px;
                                }
                                #pricing .price-based-margin-table th:nth-child(2),
                                #pricing .price-based-margin-table td:nth-child(2) {
                                    width: 60px;
                                }
                                #pricing .price-based-margin-table th:nth-child(3),
                                #pricing .price-based-margin-table td:nth-child(3) {
                                    width: 86px;
                                }
                                #pricing .price-based-margin-table th:nth-child(4),
                                #pricing .price-based-margin-table td:nth-child(4) {
                                    width: 76px;
                                }
                                #pricing .price-based-margin-table th:nth-child(5),
                                #pricing .price-based-margin-table td:nth-child(5) {
                                    width: 84px;
                                    text-align: center;
                                    overflow: visible;
                                    text-overflow: clip;
                                }

                                /* Pricing: don't truncate action icons (edit + trash) */
                                #pricing .price-based-margin-table td:nth-child(5) {
                                    white-space: nowrap;
                                }
                                #pricing .price-based-margin-table td:nth-child(5) i {
                                    margin-right: 6px;
                                }
                                #pricing .price-based-margin-table td:nth-child(5) i:last-child {
                                    margin-right: 0;
                                }

                                /* Pricing: abbreviate table headers on mobile only */
                                #pricing .gffc-th-full { display: none; }
                                #pricing .gffc-th-short { display: inline; }

                                /* Pricing: keep Actions header blank on mobile */
                                #pricing .price-based-margin-table thead th:nth-child(5) .gffc-th-full,
                                #pricing .price-based-margin-table thead th:nth-child(5) .gffc-th-short {
                                    display: none !important;
                                }

                                /* Pricing: Custom Margin group header should be left-aligned */
                                #pricing #margin-group-container .group-header {
                                    width: 100% !important;
                                    flex-direction: row !important;
                                    align-items: center !important;
                                    justify-content: space-between !important;
                                }
                                #pricing #margin-group-container .accordion-header {
                                    flex: 1 1 auto !important;
                                    min-width: 0 !important;
                                    justify-content: flex-start !important;
                                    text-align: left !important;
                                }

                                /* Pricing: reduce extra wrapper borders/padding on mobile */
                                #pricing .custom-margin-container .form-container {
                                    max-width: 100%;
                                    margin: 0;
                                    padding: 0;
                                    border: none;
                                    border-radius: 0;
                                }

                                #pricing #margin-group-container {
                                    max-width: 100%;
                                    overflow-x: hidden;
                                }

                                #pricing #margin-group-container .group-container {
                                    padding: 6px;
                                }

                                #pricing #margin-group-container .accordion-content {
                                    margin-top: 8px;
                                }

                                /* Pricing: remove extra padding on field wrapper (prevents horizontal squeeze) */
                                #pricing .form-row .field-container {
                                    padding: 0;
                                }

                                /* AI Product Info: mobile-only layout fixes (do not affect desktop) */
                                #ai-product-info .gffc-ai-summary {
                                    padding: 12px 15px !important;
                                }

                                #ai-product-info .gffc-ai-token-card {
                                    position: static !important;
                                    top: auto !important;
                                    right: auto !important;
                                    width: auto !important;
                                    margin-top: 10px;
                                }

                                #ai-product-info .gffc-ai-token-card .g-ffl-metric-card {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                }

                                #ai-product-info .gffc-ai-col {
                                    padding: 0 !important;
                                }

                                #ai-product-info .gffc-ai-col + .gffc-ai-col {
                                    margin-top: 12px;
                                }

                                #ai-product-info .g-ffl-restriction-header {
                                    flex-direction: column !important;
                                    align-items: stretch !important;
                                    gap: 10px;
                                }

                                #ai-product-info .g-ffl-restriction-header button {
                                    width: 100%;
                                    box-sizing: border-box;
                                }

                                /* AI Product Groups: allow action buttons to wrap on mobile */
                                #ai-product-info #ai-product-group-container .group-header {
                                    flex-direction: column !important;
                                    align-items: stretch !important;
                                    gap: 8px;
                                }

                                #ai-product-info #ai-product-group-container .group-header > div:last-child {
                                    flex-wrap: wrap;
                                    justify-content: flex-start;
                                    gap: 6px;
                                }

                                #ai-product-info #ai-product-group-container .group-header button.btn {
                                    padding: 6px 8px !important;
                                    font-size: 12px;
                                    line-height: 1.2;
                                    white-space: nowrap;
                                }
                            }

                            .custom-margin-container {
                                width: 60%; /* or your preferred width */
                                box-sizing: border-box;
                            }
                            .form-container {
                                max-width: 800px;
                                margin: auto;
                                padding: 20px;
                                border: 1px solid #ccc;
                                border-radius: 5px;
                            }
                            .form-header {
                                font-size: 1.5em;
                                margin-bottom: 10px;
                            }
                            .form-row {
                                display: flex;
                                align-items: flex-start;
                                margin-bottom: 5px;
                            }
                            .form-row label {
                                flex: 0 0 150px;
                                margin-bottom: 5px;
                                align-self: flex-start;
                            }
                            .form-row .field-container {
                                flex: 1;
                                display: flex;
                                flex-wrap: wrap;
                                gap: 5px;
                            }

                            .field-number {
                                width:100px;
                                height:20px;
                            
                            }
                            .form-row input, .form-row select, .field-container {
                                padding: 8px;
                                box-sizing: border-box;
                            }
                            .array-container, .group-container {
                                margin-bottom: 5px;
                                border: 1px solid #ccc;
                                padding: 10px;
                                border-radius: 5px;
                            }
                            .array-container.hidden {
                                border: none;
                                padding: 0;
                            }
                            .selected-item {
                                display: flex;
                                align-items: center;
                                margin-bottom: 5px;
                                background-color: #e9e9e9;
                                padding: 5px 10px;
                                border-radius: 5px;
                            }
                            .selected-item span {
                                margin-right: 10px;
                            }
                            .add-item, .add-group, .accordion-toggle {
                                cursor: pointer;
                                color: #2271b1;
                                text-decoration: underline;
                                display: inline-block;
                            }
                            .remove-link {
                                color: #f1afae;
                                cursor: pointer;
                                margin-left: 10px;
                            }
                            .accordion-content {
                                display: none;
                                margin-top: 10px;
                            }
                            .group-header {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                            }
                            .group-header .form-row {
                                flex: 1;
                                margin-bottom: 0;
                            }
                            .accordion-toggle-icon {
                                margin-right: 10px;
                                cursor: pointer;
                                border: 1px solid #000;
                                padding: 2px;
                                border-radius: 3px;
                                display: inline-block;
                                width: 20px;
                                text-align: center;
                            }
                            .group-name {
                                font-weight: normal !important;
                                cursor: pointer;
                                flex: 1;
                            }
                            .modal {
                                display: none;
                                position: fixed;
                                left: 0;
                                top: 0;
                                width: 100%;
                                height: 100%;
                                overflow: auto;
                                z-index: 100000 !important;
                            }
                            
                            /* Custom modals styles - apply background only to non-Bootstrap modals */
                            .modal:not(.fade) {
                                background-color: rgba(0,0,0,0.4);
                                padding-top: 60px;
                            }

                            /* Bootstrap modals overrides */
                            /* Hide the default backdrop element to prevent z-index issues */
                            .modal-backdrop {
                                display: none !important;
                                z-index: -1 !important;
                            }
                            
                            /* Apply the backdrop to the modal container instead */
                            .modal.fade.show {
                                background-color: rgba(0,0,0,0.4) !important;
                                padding-top: 0 !important;
                            }
                            
                            /* Ensure initial state is transparent */
                            .modal.fade {
                                background-color: transparent;
                            }
                            
                            .cockpit-modal-content {
                                background-color: #fefefe;
                                margin: 5% auto;
                                padding: 10px;
                                border: 1px solid #888;
                                width: 500px;
                                box-shadow: 0px 4px 8px rgba(0,0,0,0.2);
                                position: relative;
                            }
                            .close {
                                color: red;
                                float: right;
                                font-size: 28px;
                                font-weight: bold;
                                cursor: pointer;
                            }
                            .close:hover,
                            .close:focus {
                                color: darkred;
                                text-decoration: none;
                            }
                            .selected-items {
                                display: flex;
                                flex-wrap: wrap;
                                gap: 5px;
                                overflow-y: auto;
                                max-height:750px;
                                background-color: white !important;
                                color: black !important;
                            }
                            .price-based-margin-table {
                                width: 100%;
                                border-collapse: collapse;
                                margin-top: 10px;
                            }

                            /* Default: show full header labels */
                            .gffc-th-short { display: none; }
                            .price-based-margin-table th, .price-based-margin-table td {
                                border: 1px solid #ddd;
                                padding: 8px;
                            }
                            .price-based-margin-table th {
                                background-color: #f2f2f2;
                                text-align: left;
                            }
                            .price-based-margin-table .editable-cell {
                                position: relative;
                                cursor: text;
                            }
                            .price-based-margin-table .editable-cell:hover {
                                background-color: #f9f9f9;
                            }
                            .edit-link {
                                color: #0073aa !important;
                                cursor: pointer;
                                margin-right: 10px;
                            }
                            .edit-link:hover {
                                color: #005177 !important;
                            }
                            
                            .modalPopupContent {
                                flex-grow: 1;
                                height:300px;
                                overflow-y: auto;
                            }
                            
                            .add-item-container {
                                display: flex;
                                justify-content: flex-start;
                            }
                            
                            .helperDialog {
                                margin:10px;
                                padding:10px;
                                text-align:left;
                                width:95%;
                                border:solid gray 1px;
                                background:#e1edf1;
                                
                                font-weight:normal;
                            }
                            .helperDialog {
                                background-color: #e6f4f9;
                                border: 1px solid #ccc;
                                padding: 10px;
                                font-family: Arial, sans-serif;
                                font-size: 14px;
                            }
                            .helperDialog {
                                background-color: #e6f4f9;
                                border: 1px solid #ccc;
                                padding: 10px;
                                font-family: Arial, sans-serif;
                                font-size: 14px;
                            }
                            .helperDialog ul {
                                list-style-type: disc;
                                padding-left: 30px; /* Increase padding to indent the list items */
                                margin-top: 5px;
                            }
                            .helperDialog ul li {
                                margin-bottom: 5px;
                            }
                            .helperDialog .important-tips {
                                font-weight: bold;
                                margin-left: 20px; /* Indent the "Important Tips:" text */
                            }
                            .optionFilterInput {
                                margin-bottom:15px;
                            }
                            .main-container {
                                display: flex;
                                justify-content: space-between;
                            }

                            .left-container, .right-container {
                                width: 48%;
                                padding: 10px;
                                border: 1px solid #ccc;
                                border-radius: 5px;
                                margin-top:10px;
                            }

                            /* Product Restrictions Help accordion (mobile only) */
                            #product-restrictions .gffc-pr-help-summary {
                                display: none;
                            }

                            @media screen and (max-width: 768px) {
                                /* Product Restrictions: collapse 2-column into 1-column */
                                #product-restrictions .main-container {
                                    flex-direction: column;
                                    gap: 12px;
                                    max-width: 100%;
                                }
                                #product-restrictions .left-container,
                                #product-restrictions .right-container {
                                    width: 100% !important;
                                    margin-top: 0;
                                    box-sizing: border-box;
                                    max-width: 100%;
                                    overflow-x: hidden;
                                }

                                /* Ensure no horizontal scroll on the tab itself */
                                #product-restrictions {
                                    overflow-x: hidden;
                                }

                                /* Help Documentation accordion styling (mobile only) */
                                #product-restrictions .gffc-pr-help-details {
                                    border: 1px solid #dee2e6;
                                    border-radius: 6px;
                                    background: #fff;
                                }
                                #product-restrictions .gffc-pr-help-summary {
                                    display: flex;
                                    align-items: center;
                                    justify-content: space-between;
                                    padding: 12px 14px;
                                    cursor: pointer;
                                    font-weight: 600;
                                    background: #f8f9fa;
                                    border-radius: 6px;
                                    list-style: none;
                                }
                                #product-restrictions .gffc-pr-help-summary::-webkit-details-marker {
                                    display: none;
                                }
                                #product-restrictions .gffc-pr-help-summary:after {
                                    content: '+';
                                    font-weight: 700;
                                    margin-left: 10px;
                                }
                                #product-restrictions details[open] > .gffc-pr-help-summary:after {
                                    content: '\2212';
                                }

                                /* Make the embedded help video responsive */
                                #product-restrictions iframe {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                }

                                /* Guardrails to prevent overrun from long tokens/content */
                                #product-restrictions img,
                                #product-restrictions table,
                                #product-restrictions input,
                                #product-restrictions select,
                                #product-restrictions textarea {
                                    max-width: 100%;
                                }
                                #product-restrictions .product-groups-container {
                                    max-width: 100%;
                                    overflow-x: auto;
                                }

                                /* Product Groups: full-width accordion cards on mobile */
                                #product-restrictions #product-groups-section,
                                #product-restrictions #product-groups-interface,
                                #product-restrictions #product-groups-container {
                                    width: 100% !important;
                                    box-sizing: border-box;
                                }
                                #product-restrictions #product-groups-container .group-container.product-group {
                                    width: 100% !important;
                                    max-width: 100% !important;
                                    margin-left: 0 !important;
                                    margin-right: 0 !important;
                                }
                                #product-restrictions #product-groups-container .group-header {
                                    width: 100% !important;
                                    flex-direction: column !important;
                                    align-items: flex-start !important;
                                    justify-content: flex-start !important;
                                }
                                #product-restrictions #product-groups-container .accordion-header {
                                    width: 100% !important;
                                    flex: 1 1 auto !important;
                                    justify-content: flex-start !important;
                                }
                                #product-restrictions #product-groups-container .group-actions {
                                    margin-left: 0 !important;
                                    align-self: flex-end !important;
                                }

                                /* Nested 2-column restriction blocks: stack on mobile */
                                #product-restrictions .restriction-container {
                                    flex-direction: column;
                                    gap: 10px;
                                }
                                #product-restrictions .restriction-item {
                                    width: 100% !important;
                                }
                            }

                            .other-restrictions-header {
                                text-align: center;
                                margin-bottom: 10px;
                                font-size: 1.2em;
                                font-weight: bold;
                            }

                            .restriction-section {
                                border: 1px solid #ccc;
                                padding: 10px;
                                margin-bottom: 10px;
                                border-radius: 5px;
                            }

                            .g-ffl-restriction-header {
                                text-align: center;
                                margin-bottom: 10px;
                                font-size: 1.2em;
                                font-weight: bold;
                            }

                            .restriction-container {
                                display: flex;
                                justify-content: space-between;
                            }

                            .restriction-item {
                                display: flex;
                                flex-direction: column;
                                gap: 5px;
                                width: 48%;
                            }

                            .field-container {
                                display: flex;
                                flex-direction: column;
                                gap: 10px;
                            }

                            .add-item-container {
                                text-align: center;
                            }

                            #delete_gunbroker_listings_button {
                                margin-top:50px;
                                background-color: red;
                                display: block;
                                margin: 0 auto;
                                color: white; /* Ensures text is readable */
                            }

                            .selected-items {
                                flex-grow: 1;
                            }
                            .modalHeader{
                                font-weight:bold;
                                font-size:15pt;
                                padding:5px;
                            }
                            .cost-restrictions {
                                display: flex;
                                justify-content: space-between;
                            }

                            .cost-field {
                                flex: 1;
                                margin-right: 10px; /* Adds some space between the two fields */
                            }

                            .cost-field:last-child {
                                margin-right: 0; /* Removes margin from the last child */
                            }

                            .cost-field label {
                                display: block;
                                margin-bottom: 5px;
                            }

                            .cost-field input {
                                width: 100%;
                                padding: 5px;
                                box-sizing: border-box;
                            }
                            @keyframes spin {
                                0% { transform: rotate(0deg); }
                                100% { transform: rotate(360deg); }
                            }
                           
                            .operand_selected {
                                font-weight: bold;
                                text-decoration: underline;
                            }
                            
                            .grid_cell_label{
                                color:#165e7e;
                                font-style: italic;
                                width: 40%;
                                text-align:right;
                            }

                            .cockpit-watermark {
                                position: absolute;
                                top: 50%;
                                left: 50%;
                                transform: translate(-50%, -50%);
                                color: red;
                                font-size: 10px;
                                font-weight: bold;
                                background: rgba(255, 255, 255, 0.7); /* Optional: Add background to improve readability */
                                padding: 2px 2px; /* Optional: Add some padding */
                                border-radius: 3px; /* Optional: Add rounded corners */
                            }
                            .cockpit-product-search-container {
                                display: flex;
                                align-items: center;
                                width:50%;
                                margin-bottom:20px;
                            }

                            .product_feed_table_container {
                                overflow-x: auto;
                                width: 100%;
                            }

                            .product_feed_table {
                                min-width: 1000px;
                            }
                        
    
                            .category_change_modal {
                            position: fixed;
                            z-index: 1000;
                            top: 0;
                            left: 0;
                            width: 100%;
                            height: 100%;
                            background-color: rgba(0, 0, 0, 0.4);
                            display: none; /* Ensure flexbox is applied */
                            justify-content: center !important; /* Center horizontally */
                            align-items: center !important; /* Center vertically */
                        }

                        .category_change_modal_content {
                            background-color: #fefefe;
                            padding: 20px;
                            border: 1px solid #888;
                            width: 500px;
                            max-width: 90%; /* Responsiveness */
                            max-height: 90%; /* Ensure content fits on smaller screens */
                            overflow-y: auto; /* Add scrolling if content overflows */
                            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
                            border-radius: 5px;
                            position: relative;
                        }

                        .category_change_modal_close {
                            position: absolute;
                            top: 10px;
                            right: 20px;
                            color: #aaa;
                            font-size: 28px;
                            font-weight: bold;
                            cursor: pointer;
                        }

                        .cockpit-distributor-ribbon {
                            position: absolute;
                            top: 7px; /* Maintain original vertical position */
                            right: 7px; /* Maintain original horizontal position */
                            padding: 1px 2px; /* Add padding for spacing */
                            background-color: #b5ffd2; /* Green background */
                            color: black;
                            text-align: center;
                            font-size: 7px; /* Adjust font size as needed */
                            font-weight: bold;
                            z-index: 1;
                            border: 2px solid #fff; /* White border to simulate stamp edge */
                            border-radius: 2px; /* Slight rounding for stamp corners */
                            box-shadow: 0 0 0 1px #b5ffd2, /* Outer green border */
                                        0 1px 5px rgba(0, 0, 0, 0.2); /* Subtle shadow */
                            letter-spacing: 1px; /* Spacing between letters */
                            opacity: 0.9; /* Slight transparency for a worn look */
                        }

                        .cockpit-distributor-ribbon-incomplete {
                            position: absolute;
                            top: 7px; /* Maintain original vertical position */
                            right: 7px; /* Maintain original horizontal position */
                            padding: 1px 2px; /* Add padding for spacing */
                            background-color: yellow; /* Green background */
                            color: black;
                            text-align: center;
                            font-size: 7px; /* Adjust font size as needed */
                            font-weight: bold;
                            z-index: 1;
                            border: 2px solid #fff; /* White border to simulate stamp edge */
                            border-radius: 2px; /* Slight rounding for stamp corners */
                            box-shadow: 0 0 0 1px yellow, /* Outer green border */
                                        0 1px 5px rgba(0, 0, 0, 0.2); /* Subtle shadow */
                            letter-spacing: 1px; /* Spacing between letters */
                            opacity: 0.9; /* Slight transparency for a worn look */
                        }

                        /* Custom styling for cockpit main tab control */
                        #cockpit_main_tab_control {
                            background-color: #f1f1f1;
                            border: none;
                            margin: 0;
                            padding: 0;
                            overflow: hidden;
                            border-radius: 5px 5px 0 0;
                        }
                        
                        #cockpit_main_tab_control .tablinks {
                            background-color: #f1f1f1;
                            color: #333;
                            float: left;
                            border: none;
                            outline: none;
                            cursor: pointer;
                            padding: 8px 16px; /* Reduced padding for shorter height */
                            transition: 0.3s;
                            font-size: 14px;
                            height: 36px; /* Reduced height */
                            line-height: 20px; /* Adjust line height for vertical centering */
                            margin: 0;
                            border-right: 1px solid #ccc;
                        }
                        
                        #cockpit_main_tab_control .tablinks:last-child {
                            border-right: none;
                        }
                        
                        #cockpit_main_tab_control .tablinks:hover {
                            background-color: #ddd;
                        }
                        
                        #cockpit_main_tab_control .tablinks.active {
                            background-color: #3d3d3cff !important; /* Dark background for selected tab */
                            color: #fff !important; /* White text for selected tab */
                        }


                        </style>

                        <!-- Modal -->
                        <div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="true">
                            <div id="modal_dialog" class="modal-dialog modal-dialog-centered">
                                <div class="cockpit-modal-content modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="detailsModalLabel">Distributor Details</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body" id="modal-body">
                                        <!-- Form fields will be populated here -->
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <table class="form-table">
                            <tr valign="top">
                                <td colspan=3>
                                        <div class="ui_form_container">                                        
                                         <div id="brandModal" class="modal">
                                            <div class="cockpit-modal-content modal-content">
                                                <span class="close" onclick="closeModal('brandModal')">&times;</span>
                                                <span class="modalHeader">Select Brands</span>
                                                <div id="brandModalSearchDiv"></div>
                                                <div class="modalPopupContent" id="brandModalList"></div>
                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="saveSelections('brandModal', 'brand')">Apply</button>
                                            </div>
                                        </div>
                                        <div id="ignoreMapBrandModal" class="modal">
                                            <div class="cockpit-modal-content modal-content">
                                                <span class="close" onclick="closeModal('ignoreMapBrandModal')">&times;</span>
                                                <span class="modalHeader">Select Brands</span>
                                                <div id="ignoreMapBrandModalSearchDiv"></div>
                                                <div class="modalPopupContent" id="ignoreMapBrandModalList"></div>
                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="saveSelections('ignoreMapBrandModal', 'brand')">Apply</button>
                                            </div>
                                        </div>
                                        <div id="categoryModal" class="modal">
                                            <div class="cockpit-modal-content modal-content">
                                                <span class="close" onclick="closeModal('categoryModal')">&times;</span>
                                                <span class="modalHeader">Select Categories</span>
                                                <div id="categoryModalSearchDiv"></div>
                                                <div class="modalPopupContent" id="categoryModalList"></div>
                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="saveSelections('categoryModal', 'category')">Apply</button>
                                            </div>
                                        </div>

                                        <div id="distributorModal" class="modal">
                                            <div class="cockpit-modal-content modal-content">
                                                <span class="close" onclick="closeModal('distributorModal')">&times;</span>
                                                <span class="modalHeader">Select Distributors</span>
                                                <div id="distributorModalSearchDiv"></div>
                                                <div class="modalPopupContent" id="distributorModalList"></div>
                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="saveSelections('distributorModal', 'distributor')">Apply</button>
                                            </div>
                                        </div>

                                        <div id="productClassModal" class="modal">
                                            <div class="cockpit-modal-content modal-content">
                                                <span class="close" onclick="closeModal('productClassModal')">&times;</span>
                                                <span  class="modalHeader">Select Product Classes</span>
                                                <div class="modalPopupContent" id="productClassModalList"></div>
                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="saveSelections('productClassModal', 'product_class')">Apply</button>
                                            </div>
                                        </div>
                                        <?php $gffc_is_fflcockpit_ms = function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain(); ?>
                                        <ul class="nav nav-tabs" id="configTabs" role="tablist">
                                            <li class="nav-item">
                                                <a class="nav-link active" id="distributors-tab" data-toggle="tab" href="#distributors" role="tab" aria-controls="distributors" aria-selected="true">Distributors</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" id="product-restrictions-tab" data-toggle="tab" href="#product-restrictions" role="tab" aria-controls="product-restrictions" aria-selected="false" onclick="setTimeout(ensureProductRestrictionsInitialized, 200)">Product Restrictions</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link<?php echo $gffc_is_fflcockpit_ms ? ' gffc-premium-locked' : ''; ?>" id="pricing-tab" data-toggle="tab" href="#pricing" role="tab" aria-controls="pricing" aria-selected="false"<?php echo $gffc_is_fflcockpit_ms ? ' aria-disabled="true" tabindex="-1"' : ''; ?>>Pricing</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link<?php echo $gffc_is_fflcockpit_ms ? ' gffc-premium-locked' : ''; ?>" id="targets-tab" data-toggle="tab" href="#targets" role="tab" aria-controls="targets" aria-selected="false"<?php echo $gffc_is_fflcockpit_ms ? ' aria-disabled="true" tabindex="-1"' : ''; ?>>Targets</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" id="notifications-config-tab" data-toggle="tab" href="#notifications-config" role="tab" aria-controls="notifications-config" aria-selected="false">Notifications</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" id="store-config-tab" data-toggle="tab" href="#store-config" role="tab" aria-controls="store-config" aria-selected="false">Store/Location</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link<?php echo $gffc_is_fflcockpit_ms ? ' gffc-premium-locked' : ''; ?>" id="ai-product-info-tab" data-toggle="tab" href="#ai-product-info" role="tab" aria-controls="ai-product-info" aria-selected="false" onclick="setTimeout(ensureAITabInitialized, 200)" style="background: linear-gradient(to right, #f8f9fa 0%, #e3e7f1 100%); color: #0073aa; font-weight: 500; position: relative;"<?php echo $gffc_is_fflcockpit_ms ? ' aria-disabled="true" tabindex="-1"' : ''; ?>>
                                                    <i class="fas fa-robot" style="margin-right: 5px; font-size: 14px; color: #0073aa;"></i>AI Product Info
                                                </a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link<?php echo $gffc_is_fflcockpit_ms ? ' gffc-premium-locked' : ''; ?>" id="classic-configurator-tab" data-toggle="tab" href="#classic-configurator" role="tab" aria-controls="classic-configurator" aria-selected="false"<?php echo $gffc_is_fflcockpit_ms ? ' aria-disabled="true" tabindex="-1"' : ''; ?>>Advanced</a>
                                            </li>
                                        </ul>
                                    <style>
                                        .gffc-premium-overlay {
                                            position: absolute;
                                            inset: 0;
                                            background: rgba(248, 249, 250, 0.85);
                                            z-index: 20;
                                            padding: 16px;
                                            display: flex;
                                            align-items: flex-start;
                                            justify-content: center;
                                            pointer-events: auto;
                                        }
                                        .gffc-premium-overlay .helperDialog {
                                            max-width: 900px;
                                            width: 100%;
                                        }

                                            /* Mobile Accordion Styles */
                                            .gffc-mobile-accordion-header {
                                                display: none;
                                                background-color: #f8f9fa;
                                                color: #444;
                                                padding: 15px 20px;
                                                border: 1px solid #dee2e6;
                                                border-bottom: none;
                                                cursor: pointer;
                                                font-weight: 600;
                                                font-size: 15px;
                                                position: relative;
                                                transition: background-color 0.2s;
                                            }
                                            .gffc-mobile-accordion-header:hover {
                                                background-color: #e9ecef;
                                            }
                                            .gffc-mobile-accordion-header:after {
                                                content: '\f078'; /* FontAwesome chevron-down */
                                                font-family: 'Font Awesome 5 Free';
                                                font-weight: 900;
                                                position: absolute;
                                                right: 20px;
                                                font-size: 12px;
                                                transition: transform 0.3s;
                                            }
                                            .gffc-mobile-accordion-header.active {
                                                background-color: #fff;
                                                color: #2271b1;
                                                border-bottom: 1px solid #fff; /* Merge with content */
                                                margin-bottom: -1px; /* Overlap border */
                                                z-index: 2;
                                            }
                                            .gffc-mobile-accordion-header.active:after {
                                                transform: rotate(180deg);
                                            }

                                            @media screen and (max-width: 768px) {
                                                #configTabs {
                                                    display: none !important;
                                                }
                                                .gffc-mobile-accordion-header {
                                                    display: flex;
                                                    align-items: center;
                                                    justify-content: space-between;
                                                }
                                                /* Reset tab content borders for accordion look */
                                                #configTabContent {
                                                    border: 1px solid #dee2e6;
                                                    border-top: none;
                                                }
                                                .tab-pane {
                                                    border-top: 1px solid #dee2e6; /* Separator between header and content */
                                                }
                                                .tab-pane.active {
                                                    border-top: none; /* No border if active header is above */
                                                    padding-top: 20px;
                                                }
                                            }
                                        </style>
                                        <script>
                                            document.addEventListener('DOMContentLoaded', function() {
                                                var gffcIsFFLCockpitMultisite = <?php echo $gffc_is_fflcockpit_ms ? 'true' : 'false'; ?>;
                                                window.gffcIsFFLCockpitMultisite = gffcIsFFLCockpitMultisite;
                                                if (gffcIsFFLCockpitMultisite) {
                                                    var gffcLockedPaneIds = new Set(['pricing', 'targets', 'ai-product-info', 'classic-configurator']);
                                                    var gffcPremiumOverlayEl = document.createElement('div');
                                                    gffcPremiumOverlayEl.className = 'gffc-premium-overlay';
                                                    gffcPremiumOverlayEl.innerHTML = '<div class="helperDialog" style="margin:0;"><strong>Premium feature.</strong> This section becomes available when subscribed to <strong>FFL Cockpit - Premium</strong>.</div>';

                                                    function gffcHidePremiumOverlay() {
                                                        if (gffcPremiumOverlayEl && gffcPremiumOverlayEl.parentElement) {
                                                            gffcPremiumOverlayEl.parentElement.removeChild(gffcPremiumOverlayEl);
                                                        }
                                                    }

                                                    function gffcShowPremiumOverlayForPane(paneId) {
                                                        var pane = document.getElementById(paneId);
                                                        if (!pane) return;
                                                        if (getComputedStyle(pane).position === 'static') {
                                                            pane.style.position = 'relative';
                                                        }
                                                        gffcHidePremiumOverlay();
                                                        pane.appendChild(gffcPremiumOverlayEl);
                                                    }

                                                    function gffcSyncPremiumOverlayFromActiveTab() {
                                                        var activeTab = document.querySelector('#configTabs a.nav-link.active');
                                                        if (!activeTab) {
                                                            gffcHidePremiumOverlay();
                                                            return;
                                                        }
                                                        var href = activeTab.getAttribute('href') || '';
                                                        var paneId = href.startsWith('#') ? href.substring(1) : '';
                                                        if (paneId && gffcLockedPaneIds.has(paneId)) {
                                                            gffcShowPremiumOverlayForPane(paneId);
                                                        } else {
                                                            gffcHidePremiumOverlay();
                                                        }
                                                    }

                                                    function gffcSetTabLockedState(tabId, isLocked) {
                                                        var tab = document.getElementById(tabId);
                                                        if (!tab) return;
                                                        if (isLocked) {
                                                            tab.classList.add('gffc-premium-locked');
                                                            tab.setAttribute('aria-disabled', 'true');
                                                            tab.setAttribute('tabindex', '-1');
                                                        } else {
                                                            tab.classList.remove('gffc-premium-locked');
                                                            tab.removeAttribute('aria-disabled');
                                                            tab.removeAttribute('tabindex');
                                                        }
                                                    }

                                                    window.gffcApplyMultiServerConfigAccess = function(currentConfig) {
                                                        var hasGunbrokerTarget = !!(currentConfig && currentConfig.targets && currentConfig.targets.gunbroker);
                                                        window.gffcHasGunbrokerTargetInConfig = hasGunbrokerTarget;

                                                        gffcLockedPaneIds = new Set(['pricing', 'targets', 'ai-product-info', 'classic-configurator']);
                                                        if (hasGunbrokerTarget) {
                                                            gffcLockedPaneIds.delete('pricing');
                                                            gffcLockedPaneIds.delete('targets');
                                                            gffcLockedPaneIds.delete('classic-configurator');
                                                        }

                                                        gffcSetTabLockedState('pricing-tab', gffcLockedPaneIds.has('pricing'));
                                                        gffcSetTabLockedState('targets-tab', gffcLockedPaneIds.has('targets'));
                                                        gffcSetTabLockedState('classic-configurator-tab', gffcLockedPaneIds.has('classic-configurator'));

                                                        gffcSyncPremiumOverlayFromActiveTab();
                                                    };

                                                    window.gffcApplyMultiServerConfigAccess(window.currentConfiguration || null);

                                                    // When a tab is shown, toggle overlay only for locked panes.
                                                    jQuery('#configTabs a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
                                                        var href = e.target && e.target.getAttribute('href');
                                                        var paneId = href && href.startsWith('#') ? href.substring(1) : '';
                                                        if (paneId && gffcLockedPaneIds.has(paneId)) {
                                                            gffcShowPremiumOverlayForPane(paneId);
                                                        } else {
                                                            gffcHidePremiumOverlay();
                                                        }
                                                    });

                                                    // Initial state on load
                                                    gffcSyncPremiumOverlayFromActiveTab();
                                                }

                                                // Deep link Configuration sub-tabs (Distributors / Targets / etc.)
                                                // Keeps the user on the same sub-tab after refresh.
                                                jQuery('#configTabs a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
                                                    try {
                                                        var href = e && e.target && e.target.getAttribute ? e.target.getAttribute('href') : '';
                                                        var paneId = href && href.startsWith('#') ? href.substring(1) : '';
                                                        if (paneId && typeof window.gffcSetActiveConfigSubTabDeepLink === 'function') {
                                                            window.gffcSetActiveConfigSubTabDeepLink(paneId);
                                                        }
                                                    } catch (err) {
                                                        // Ignore
                                                    }
                                                });

                                                // Only run if configTabs exists
                                                var tabsList = document.getElementById('configTabs');
                                                if (!tabsList) return;

                                                var tabs = tabsList.querySelectorAll('.nav-link');
                                                var tabContent = document.getElementById('configTabContent');
                                                var isMobile = window.matchMedia("(max-width: 768px)").matches;
                                                
                                                if (tabs.length > 0 && tabContent) {
                                                    // Reorder panes to match tab order and insert headers
                                                    tabs.forEach(function(tab) {
                                                        var targetId = tab.getAttribute('href').replace('#', '');
                                                        var targetPane = document.getElementById(targetId);
                                                        
                                                        if (targetPane) {
                                                            // Check if header already exists
                                                            var existingHeader = targetPane.previousElementSibling;
                                                            if (existingHeader && existingHeader.classList.contains('gffc-mobile-accordion-header')) {
                                                                existingHeader.remove();
                                                            }

                                                            var header = document.createElement('div');
                                                            header.className = 'gffc-mobile-accordion-header';
									
                                                            // Important: never mark accordion headers as `.active` on desktop.
                                                            // Bootstrap deactivates `.tab-content > .active` children; if a hidden
                                                            // header has `active`, it may be deactivated instead of the prior pane,
                                                            // leaving multiple panes visible and making tabs look mismatched.
                                                            if (isMobile && tab.classList.contains('active')) {
                                                                // If mobile, ensure the tab and pane are NOT active initially
                                                                tab.classList.remove('active');
                                                                tab.setAttribute('aria-selected', 'false');
                                                                targetPane.classList.remove('active', 'show');
                                                            }
                                                            
                                                            // Copy HTML
                                                            var tempDiv = document.createElement('div');
                                                            tempDiv.innerHTML = tab.innerHTML;
                                                            // Wrap in span to ensure icon and text stay together
                                                            header.innerHTML = '<span>' + tempDiv.innerHTML + '</span>';
                                                            
                                                            header.onclick = function(e) {
                                                                e.preventDefault();
                                                                
                                                                // Toggle logic
                                                                if (header.classList.contains('active')) {
                                                                    // Collapse
                                                                    header.classList.remove('active');
                                                                    targetPane.classList.remove('active', 'show');
                                                                    tab.classList.remove('active');
                                                                    tab.setAttribute('aria-selected', 'false');
                                                                } else {
                                                                    // Expand (Standard Bootstrap Tab behavior)
                                                                    tab.click();
                                                                    
                                                                    // Sync header state (mobile only)
                                                                    if (window.matchMedia("(max-width: 768px)").matches) {
                                                                        document.querySelectorAll('.gffc-mobile-accordion-header').forEach(h => h.classList.remove('active'));
                                                                        header.classList.add('active');
                                                                    }
                                                                    
                                                                    setTimeout(() => {
                                                                        header.scrollIntoView({behavior: 'smooth', block: 'nearest'});
                                                                    }, 100);
                                                                }
                                                            };
                                                            
                                                            // Move header and pane to the end of the container
                                                            // This ensures they appear in the same order as the tabs
                                                            tabContent.appendChild(header);
                                                            tabContent.appendChild(targetPane);
                                                        }
                                                    });

                                                    // Force sync active state on load (if not mobile)
                                                    if (!isMobile) {
                                                        var activeTab = tabsList.querySelector('.nav-link.active');
                                                        if (activeTab) {
                                                            var targetId = activeTab.getAttribute('href').replace('#', '');
                                                            var targetPane = document.getElementById(targetId);
                                                            if (targetPane) {
                                                                // Deactivate all panes first
                                                                var panes = tabContent.querySelectorAll('.tab-pane');
                                                                panes.forEach(function(p) {
                                                                    p.classList.remove('show', 'active');
                                                                });
                                                                // Activate target pane
                                                                targetPane.classList.add('show', 'active');
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Listen for tab changes from other sources (mobile only)
                                                    jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                                                        if (!window.matchMedia("(max-width: 768px)").matches) {
                                                            return;
                                                        }
                                                        var targetId = e.target.getAttribute('href').replace('#', '');
                                                        document.querySelectorAll('.gffc-mobile-accordion-header').forEach(h => h.classList.remove('active'));
									
                                                        // Find the header associated with this pane
                                                        var pane = document.getElementById(targetId);
                                                        if (pane && pane.previousElementSibling && pane.previousElementSibling.classList.contains('gffc-mobile-accordion-header')) {
                                                            pane.previousElementSibling.classList.add('active');
                                                        }
                                                    });
                                                }
                                            });
                                        </script>
                  
                                        <div  class="tab-content" id="configTabContent">
                                            <div class="overlay" id="configuration_loading_overlay" style="display:flex;position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-color: rgba(255, 255, 255, 0.7);justify-content: center;align-items: center;">
                                                <div class="loader" style="border: 8px solid #f3f3f3;border-top: 8px solid #3498db;border-radius: 50%;width: 50px;height: 50px;animation: spin 1s linear infinite;"></div>
                                            </div>
                                            <div class="tab-pane fade" id="pricing" role="tabpanel" aria-labelledby="pricing-tab">
                                            <div class="helperDialog"><strong>Pricing/Margin settings</strong> allow you to fine-tune list prices of your product on your site. There are core pricing assumptions, and custom margin groups you can setup to price specific types of products accordingly. <strong>Important:</strong> Margin settings in percentage should be entered in their decimal format. (Examples: 25% = 0.25, 2.49% = 0.0249...etc). <span style="color:red;font-weight:bold;">Pricing changes will not appear immediately and can take an hour or longer to apply, depending on the number of products affected and the performance of your site.</span></div>
                                            <div class="pricing-tab-container">
                                                    <!-- Pricing Form Content -->
                                                    <div class="pricing-assumptions-form-container core-pricing-container">
                                                        <div class="pricing-assumptions-form-header">Core Pricing Assumptions</div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-margin-default-margin_percentage">Default Margin (%):</label>
                                                            <input type="number" id="pricing-margin-default-margin_percentage" name="pricing-margin-default-margin_percentage" min="0" max="0.99" step="0.01"  data-autosave="true">
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-margin-default-margin_dollar">Default Margin ($):</label>
                                                            <input type="number" id="pricing-margin-default-margin_dollar" name="pricing-margin-default-margin_dollar"  data-autosave="true">
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-rounding">Price Rounding:</label>
                                                            <select id="pricing-rounding" name="pricing-rounding"  data-autosave="true">
                                                                <option value="none">None</option>
                                                                <option value="round_to_nearest_dollar">Round to Nearest Dollar</option>
                                                                <option value="round_up_to_99_cents">Round up to 99 Cents</option>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="helperDialog">Sales Tax Assumption and Credit Card fees help Cockpit calculate the total cost of a customer's order. If you include Credit Card fees, we can accurately determine these charges based on the overall order value.</div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-include_credit_card_fees_in_price">Include CC Fees in Price:</label>
                                                            <label style="align:left;width:50px;" class="toggle-switch">
                                                                <input type="checkbox" id="pricing-include_credit_card_fees_in_price" name="pricing-include_credit_card_fees_in_price"  data-autosave="true">
                                                                <span class="slider"></span>
                                                            </label>
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-credit_card_fee_percent">CC Fee Percent:</label>
                                                            <input type="number" id="pricing-credit_card_fee_percent" name="pricing-credit_card_fee_percent" min="0" max="0.99" step="0.01"  data-autosave="true">
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-credit_card_fee_transaction">CC Fee (per Transaction):</label>
                                                            <input type="number" id="pricing-credit_card_fee_transaction" name="pricing-credit_card_fee_transaction"  data-autosave="true">
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="pricing-sales_tax_assumption">Sales Tax Assumption:</label>
                                                            <input type="number" id="pricing-sales_tax_assumption" name="pricing-sales_tax_assumption" min="0" max="0.99" step="0.01"  data-autosave="true">
                                                        </div>
                                                        <div class="helperDialog"><strong>"Ignore Margin when setting MAP"</strong> will set prices to their MAP (if one exists) ignoring your margin settings. When deactivated MAP is applied only when the margin-based calculated list price falls below MAP.</div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label for="sell_at_map">Ignore&nbsp;Margin&nbsp;when&nbsp;setting&nbsp;MAP:</label>
                                                            <label style="align:left;width:50px;" class="toggle-switch">
                                                                <input type="checkbox" id="pricing-sell_at_map" name="pricing-sell_at_map" data-autosave="true">
                                                                <span class="slider"></span>
                                                            </label>
                                                        </div>
                                                        <div class="pricing-assumptions-form-row">
                                                            <label nowrap for="ignore_map_brands">Ignore&nbsp;MAP&nbsp;Brands:</label>
                                                            <div class="field-container">
                                                                <div class="selected-items" id="pricing-ignore_map_brands"></div>
                                                                <div class="add-item-container">
                                                                    <span class="add-item" onclick="openModal('ignoreMapBrandModal', 'pricing-ignore_map_brands')">Select</span>&nbsp;|&nbsp;
                                                                    <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('pricing-ignore_map_brands'))">Remove All</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="form-row">
                                                            <label for="price-based-margin-table-default">Cost Based Margin:</label>
                                                            <div class="field-container">
                                                                <div style="font-size: 12px; color: #b32d2e; margin-bottom: 8px; font-style: italic; font-weight: 600;">Margin applies when: cost ≥ Min Cost AND cost &lt; Max Cost</div>
                                                                <table class="price-based-margin-table" id="price-based-margin-table-group-default">
                                                                    <thead>
                                                                        <tr style="white-space: nowrap;">
                                                                            <th><span class="gffc-th-full">Min Cost ($)</span><span class="gffc-th-short">Min ($)</span></th>
                                                                            <th><span class="gffc-th-full">Max Cost ($)</span><span class="gffc-th-short">Max ($)</span></th>
                                                                            <th><span class="gffc-th-full">Margin (%)</span><span class="gffc-th-short">Margin (%)</span></th>
                                                                            <th><span class="gffc-th-full">Margin ($)</span><span class="gffc-th-short">Margin ($)</span></th>
                                                                            <th><span class="gffc-th-full">Actions</span><span class="gffc-th-short">Act</span></th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody></tbody>
                                                                </table>
                                                                <div class="add-item-container">
                                                                    <span class="add-item" onclick="openModal('priceBasedMarginModal', 'price-based-margin-table-group-default')">Add Cost Based Margin</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="pricing-assumptions-form-container custom-margin-container">
                                                        <div class="pricing-assumptions-form-header">Custom Margin Settings</div>
                                                        <div class="form-container">
                                                            <div id="margin-group-container"></div>
                                                            <span class="add-group" onclick="addMarginGroup(null,null,true)">Add Margin Group</span>
                                                        </div>
                                                        <div id="priceBasedMarginModal" class="modal">
                                                            <div class="cockpit-modal-content modal-content">
                                                                <span class="close" onclick="closeModal('priceBasedMarginModal')">&times;</span>
                                                                <span class="modalHeader">Add Cost Based Margin</span>
                                                                <div style="background-color: #fff5f5; padding: 10px; margin-bottom: 15px; border-left: 3px solid #b32d2e; font-size: 13px; color: #b32d2e; font-weight: 600;">
                                                                    <strong>How it works:</strong> The margin will apply when the product cost is greater than or equal to Min Price AND less than Max Price (cost ≥ min AND cost &lt; max).
                                                                </div>
                                                                <div>
                                                                    <label for="min_price">Min Price ($):</label>
                                                                    <input type="number" id="min_price" value="0">
                                                                </div>
                                                                <div>
                                                                    <label for="max_price">Max Price ($):</label>
                                                                    <input type="number" id="max_price" value="0">
                                                                </div>
                                                                <div>
                                                                    <label for="margin_percentage">Margin (%):</label>
                                                                    <input type="number" id="margin_percentage"  value="0">
                                                                </div>
                                                                <div>
                                                                    <label for="margin_dollar">Margin ($):</label>
                                                                    <input type="number" id="margin_dollar" value="0">
                                                                </div>
                                                                <button style="margin-top:50px;" class="btn btn-primary" onclick="savePriceBasedMargin()">Add</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="tab-pane fade" id="targets" role="tabpanel" aria-labelledby="targets-tab">
                                                <!-- Targets Form Content -->
                                                <div class="helperDialog"><strong>Targets</strong> are representing where you want your product to be listed. We support listing product on your site (WooCommerce), we support feeding aggregators like WikiArms, AmmoSeek, and Gun.deals. These aggregators require you subscribe with them and pay a monthly fee to list products. We also support feeding product (distributor-based only, no local inventory) to Gunbroker. Add the Targets you wish to use, and only add those you are subscribed to. The toggle in each card below represents whether or not the feed is activated.</div>
                                                <div>
                                                    <div class="row" id="targets-container">
                                                        <!-- Existing targets will be loaded here -->
                                                    </div>
                                                    <div class="d-flex align-items-center mt-2" id="targets-select-container">
                                                        <select class="form-control mr-2" id="available-targets">
                                                            <!-- Options will be populated by JavaScript -->
                                                        </select>
                                                        <button class="button alt" id="add-target">Add Target</button>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="tab-pane fade" id="notifications-config" role="tabpanel" aria-labelledby="notifications-tab">
                                            <div class="helperDialog"><strong>A note about notifications: </strong>Set up your notification settings using the forms below to customize your email templates. The notification email is where you will receive FFL Cockpit system alerts, including distributor order information. Use the templates below to modify the messages sent to your customers at various stages of the order fulfillment process. </div>
                                                <!-- Fulfillment Form Content -->
                                                <script>
                                                    const email_templates = [
                                                        {"type": "subject", "group_label":"Email Template: <strong>Order Processed</strong>", "label":"Order Processed (FFL Order) Subject", "id": "order_processed_subject", "config_key":"fulfillment-emailer-templates-order_processed-subject"},
                                                        {"type": "body", "label":"FFL Order", "id": "order_processed_ffl", "config_key":"fulfillment-emailer-templates-order_processed-message_ffl_order"},
                                                        {"type": "body", "label":"Non-FFL Order", "id": "order_processed_nonffl", "config_key":"fulfillment-emailer-templates-order_processed-message_non_ffl_order"},
                                                        {"type": "subject","group_label":"Email Template: <strong>Order Shipped</strong>", "label":"Order Shipped (FFL Order) Subject", "id": "order_shipped_subject", "config_key":"fulfillment-emailer-templates-order_shipped-subject"},
                                                        {"type": "body", "label":"FFL Order", "id": "order_shipped_ffl", "config_key":"fulfillment-emailer-templates-order_shipped-message_ffl_order"},
                                                        {"type": "body", "label":"Non-FFL Order", "id": "order_shipped_nonffl", "config_key":"fulfillment-emailer-templates-order_shipped-message_non_ffl_order"},
                                                        {"type": "subject","group_label":"Email Template: <strong>Order Delivered</strong>", "label":"Order Delivered (FFL Order) Subject", "id": "order_delivered_subject", "config_key":"fulfillment-emailer-templates-order_delivered-subject"},
                                                        {"type": "body", "label":"FFL Order", "id": "order_delivered_ffl", "config_key":"fulfillment-emailer-templates-order_delivered-message_ffl_order"},
                                                        {"type": "body", "label":"Non-FFL Order", "id": "order_delivered_nonffl", "config_key":"fulfillment-emailer-templates-order_delivered-message_non_ffl_order"},
                                                        {"type": "subject", "group_label": "Email Template: <strong>FFL Document Request</strong>", "label":"FFL Document Request Subject", "id": "ffl_request_subject", "config_key":"fulfillment-emailer-templates-ffl_request-subject"},
                                                        {"type": "body", "label":"FFL Document Request", "id": "ffl_request", "config_key":"fulfillment-emailer-templates-ffl_request-message"}
                                                    ];

                                                    const container = document.getElementById('notifications-config');
                                                    container.innerHTML += `
                                                        <div class="form-groups-wrapper">
                                                            <div class="form-group">
                                                                <label class="email_template_header" for="notification_email">Email to receive FFL Cockpit System Notifications</label>
                                                                <input placeholder="Notification Email" type="text" class="form-control" style="width:300px;" id="notification_email" data-autosave="true">
                                                            </div>
                                                            <div class="form-group">
                                                                <label class="email_template_header" for="from_email">Email for sending order updates to your customers</label>
                                                                <div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
                                                                    <input placeholder="From Email" type="text" class="form-control" style="width:300px;" id="fulfillment-emailer-from_email" data-autosave="true">
                                                                    <span id="gffc_email_verification_status" style="display: none; font-size: 13px; font-weight: 500; padding: 4px 10px; border-radius: 4px;"></span>
                                                                    <button type="button" id="gffc_send_verification_btn" style="display: none; padding: 6px 12px; font-size: 13px; border-radius: 4px; border: 1px solid #0073aa; background: #0073aa; color: white; cursor: pointer;" onclick="gffcSendEmailVerification()">
                                                                        <i class="fas fa-paper-plane" style="margin-right: 5px;"></i>Resend Verification
                                                                    </button>
                                                                </div>
                                                                <div id="gffc_email_verification_message" style="display: none; margin-top: 8px; padding: 10px 14px; border-radius: 6px; font-size: 13px;"></div>
                                                            </div>
                                                        </div>
                                                    `;

                                                    let currentDiv = null;
                                                    for (const email_template of email_templates) {
                                                        if (email_template.type === "subject") {
                                                            if (currentDiv) {
                                                                container.appendChild(currentDiv);
                                                            }
                                                            currentDiv = document.createElement('div');
                                                            currentDiv.className = 'form-group';
                                                            currentDiv.innerHTML = `
                                                                <label class="email_template_header" for="${email_template.config_key}">${email_template.group_label}</label>
                                                                <label class="email-template-label">Subject</i></label>
                                                                <input style="margin-bottom:20px;" placeholder="Email Subject" type="text" class="form-control" id="${email_template.config_key}" data-autosave="true">
                                                            `;
                                                        } else {
                                                            const wrapperDiv = document.createElement('div');
                                                            wrapperDiv.className = 'textarea-wrapper';

                                                            const label = document.createElement('label');
                                                            label.className = 'email-template-label';
                                                            label.setAttribute('for', email_template.config_key);
                                                            label.textContent = email_template.label;
                                                            wrapperDiv.appendChild(label);

                                                            const textarea = document.createElement('textarea');
                                                            textarea.id = email_template.config_key;
                                                            textarea.name = email_template.config_key;
                                                            textarea.setAttribute('data-autosave', 'true');
                                                            wrapperDiv.appendChild(textarea);

                                                            currentDiv.appendChild(wrapperDiv);
                                                        }
                                                    }
                                                    if (currentDiv) {
                                                        container.appendChild(currentDiv);
                                                    }

                                                    // Initialize TinyMCE for each textarea after a delay to ensure DOM is ready
                                                    setTimeout(function() {
                                                        if (typeof initializeTinyMCEEditors === 'function') {
                                                            initializeTinyMCEEditors();
                                                        }
                                                    }, 500);
                                                    
                                                    // Email verification state tracking
                                                    window.gffcEmailVerificationChecked = false;
                                                    window.gffcLastCheckedEmail = null;
                                                    
                                                    // Check email verification status
                                                    async function gffcCheckEmailVerification() {
                                                        const emailInput = document.getElementById('fulfillment-emailer-from_email');
                                                        const statusEl = document.getElementById('gffc_email_verification_status');
                                                        const btnEl = document.getElementById('gffc_send_verification_btn');
                                                        const msgEl = document.getElementById('gffc_email_verification_message');
                                                        
                                                        if (!emailInput || !statusEl || !btnEl) return;
                                                        
                                                        const email = emailInput.value.trim();
                                                        
                                                        // Don't check if email is empty or same as last checked
                                                        if (!email) {
                                                            statusEl.style.display = 'none';
                                                            btnEl.style.display = 'none';
                                                            msgEl.style.display = 'none';
                                                            return;
                                                        }
                                                        
                                                        // Show loading state
                                                        statusEl.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking...';
                                                        statusEl.style.display = 'inline-block';
                                                        statusEl.style.background = '#e7f3ff';
                                                        statusEl.style.color = '#0073aa';
                                                        btnEl.style.display = 'none';
                                                        msgEl.style.display = 'none';
                                                        
                                                        try {
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "check_email_verified",
                                                                    "data": {
                                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                                                        "email": email
                                                                    }
                                                                })
                                                            });
                                                            
                                                            const responseData = await response.json();
                                                            let data;
                                                            
                                                            // Handle gzip+base64 encoded response
                                                            if (responseData.body && typeof responseData.body === 'string') {
                                                                try {
                                                                    data = await gffcDecodeGzipBase64(responseData.body);
                                                                } catch (e) {
                                                                    try {
                                                                        data = JSON.parse(responseData.body);
                                                                    } catch (e2) {
                                                                        data = responseData;
                                                                    }
                                                                }
                                                            } else {
                                                                data = responseData;
                                                            }
                                                            
                                                            window.gffcLastCheckedEmail = email;
                                                            window.gffcEmailVerificationChecked = true;
                                                            
                                                            if (data.success && data.is_verified) {
                                                                statusEl.innerHTML = '<i class="fas fa-check-circle"></i> Verified';
                                                                statusEl.style.background = '#d4edda';
                                                                statusEl.style.color = '#155724';
                                                                btnEl.style.display = 'none';
                                                            } else if (data.success && !data.is_verified) {
                                                                statusEl.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Not Verified';
                                                                statusEl.style.background = '#fff3cd';
                                                                statusEl.style.color = '#856404';
                                                                btnEl.style.display = 'inline-block';
                                                            } else {
                                                                statusEl.innerHTML = '<i class="fas fa-question-circle"></i> Unknown';
                                                                statusEl.style.background = '#f8d7da';
                                                                statusEl.style.color = '#721c24';
                                                                btnEl.style.display = 'inline-block';
                                                            }
                                                        } catch (error) {
                                                            console.error('Email verification check error:', error);
                                                            statusEl.innerHTML = '<i class="fas fa-times-circle"></i> Error';
                                                            statusEl.style.background = '#f8d7da';
                                                            statusEl.style.color = '#721c24';
                                                            btnEl.style.display = 'inline-block';
                                                        }
                                                    }
                                                    
                                                    // Send email verification
                                                    async function gffcSendEmailVerification() {
                                                        const emailInput = document.getElementById('fulfillment-emailer-from_email');
                                                        const btnEl = document.getElementById('gffc_send_verification_btn');
                                                        const msgEl = document.getElementById('gffc_email_verification_message');
                                                        
                                                        if (!emailInput || !btnEl) return;
                                                        
                                                        const email = emailInput.value.trim();
                                                        if (!email) {
                                                            alert('Please enter an email address first.');
                                                            return;
                                                        }
                                                        
                                                        // Show loading state
                                                        const originalHTML = btnEl.innerHTML;
                                                        btnEl.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
                                                        btnEl.disabled = true;
                                                        
                                                        try {
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "verify_email",
                                                                    "data": {
                                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                                                        "email": email
                                                                    }
                                                                })
                                                            });
                                                            
                                                            const responseData = await response.json();
                                                            let data;
                                                            
                                                            // Handle gzip+base64 encoded response
                                                            if (responseData.body && typeof responseData.body === 'string') {
                                                                try {
                                                                    data = await gffcDecodeGzipBase64(responseData.body);
                                                                } catch (e) {
                                                                    try {
                                                                        data = JSON.parse(responseData.body);
                                                                    } catch (e2) {
                                                                        data = responseData;
                                                                    }
                                                                }
                                                            } else {
                                                                data = responseData;
                                                            }
                                                            
                                                            btnEl.innerHTML = originalHTML;
                                                            btnEl.disabled = false;
                                                            
                                                            if (data.success) {
                                                                if (data.is_verified) {
                                                                    // Already verified
                                                                    msgEl.innerHTML = '<i class="fas fa-check-circle" style="margin-right: 6px;"></i>' + data.message;
                                                                    msgEl.style.background = '#d4edda';
                                                                    msgEl.style.color = '#155724';
                                                                    msgEl.style.border = '1px solid #c3e6cb';
                                                                    // Update status indicator
                                                                    gffcCheckEmailVerification();
                                                                } else if (data.verification_sent) {
                                                                    // Verification email sent
                                                                    msgEl.innerHTML = '<i class="fas fa-envelope" style="margin-right: 6px;"></i>' + data.message + '<br><br><strong>Note:</strong> After clicking the verification link in the email, please reload this page to see the updated verification status.';
                                                                    msgEl.style.background = '#e7f3ff';
                                                                    msgEl.style.color = '#004085';
                                                                    msgEl.style.border = '1px solid #b8daff';
                                                                    
                                                                    // Double-check verification status in case it was already verified
                                                                    setTimeout(async function() {
                                                                        await gffcCheckEmailVerification();
                                                                        // If now verified, update the message
                                                                        const statusEl = document.getElementById('gffc_email_verification_status');
                                                                        if (statusEl && statusEl.innerHTML.includes('Verified') && !statusEl.innerHTML.includes('Not Verified')) {
                                                                            msgEl.innerHTML = '<i class="fas fa-check-circle" style="margin-right: 6px;"></i>Great news! Your email is now verified.';
                                                                            msgEl.style.background = '#d4edda';
                                                                            msgEl.style.color = '#155724';
                                                                            msgEl.style.border = '1px solid #c3e6cb';
                                                                        }
                                                                    }, 1000);
                                                                } else {
                                                                    msgEl.innerHTML = '<i class="fas fa-info-circle" style="margin-right: 6px;"></i>' + data.message;
                                                                    msgEl.style.background = '#e7f3ff';
                                                                    msgEl.style.color = '#004085';
                                                                    msgEl.style.border = '1px solid #b8daff';
                                                                }
                                                                msgEl.style.display = 'block';
                                                            } else {
                                                                msgEl.innerHTML = '<i class="fas fa-times-circle" style="margin-right: 6px;"></i>Error: ' + (data.error || 'Failed to send verification email');
                                                                msgEl.style.background = '#f8d7da';
                                                                msgEl.style.color = '#721c24';
                                                                msgEl.style.border = '1px solid #f5c6cb';
                                                                msgEl.style.display = 'block';
                                                            }
                                                        } catch (error) {
                                                            console.error('Send verification error:', error);
                                                            btnEl.innerHTML = originalHTML;
                                                            btnEl.disabled = false;
                                                            msgEl.innerHTML = '<i class="fas fa-times-circle" style="margin-right: 6px;"></i>Error: Failed to send verification request';
                                                            msgEl.style.background = '#f8d7da';
                                                            msgEl.style.color = '#721c24';
                                                            msgEl.style.border = '1px solid #f5c6cb';
                                                            msgEl.style.display = 'block';
                                                        }
                                                    }
                                                    
                                                    // Make function globally accessible
                                                    window.gffcSendEmailVerification = gffcSendEmailVerification;
                                                    window.gffcCheckEmailVerification = gffcCheckEmailVerification;
                                                    
                                                    // Listen for tab selection to trigger verification check
                                                    jQuery('#notifications-config-tab').on('shown.bs.tab', function(e) {
                                                        // Check verification when tab is shown
                                                        setTimeout(function() {
                                                            gffcCheckEmailVerification();
                                                        }, 300);
                                                    });
                                                    
                                                    // Check on page load if notifications tab is already active (deep link support)
                                                    jQuery(document).ready(function() {
                                                        setTimeout(function() {
                                                            const notificationsTab = document.getElementById('notifications-config-tab');
                                                            const notificationsPane = document.getElementById('notifications-config');
                                                            if ((notificationsTab && notificationsTab.classList.contains('active')) || 
                                                                (notificationsPane && notificationsPane.classList.contains('active'))) {
                                                                gffcCheckEmailVerification();
                                                            }
                                                        }, 1000); // Delay to ensure config is loaded first
                                                    });
                                                    
                                                    // Also check when the email input changes (with debounce)
                                                    let gffcEmailCheckTimeout = null;
                                                    document.getElementById('fulfillment-emailer-from_email').addEventListener('change', function() {
                                                        clearTimeout(gffcEmailCheckTimeout);
                                                        gffcEmailCheckTimeout = setTimeout(function() {
                                                            window.gffcEmailVerificationChecked = false;
                                                            gffcCheckEmailVerification();
                                                        }, 500);
                                                    });
                                                </script>

                                            </div>
                                            <div class="tab-pane fade" id="store-config" role="tabpanel" aria-labelledby="store-tab">
                                                <!-- Store Config Form Content -->
                                                <!-- Pricing Form Content -->
                                                <div class="helperDialog"><strong>Store/Location Information</strong>Your FFL number and store information is needed for certain distributors to place a "ship-to-store" order. Ship-to-Store orders are usually required when there may be a drop-ship restriction on a brand, and you have to have the item shipped locally before reshipping the product out to your customer. </div>
                                                <div style="margin:10px;" class="pricing-assumptions-form-container">
                                                    <div class="pricing-assumptions-form-header">Store/Location Information</div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-ffl">FFL License Number:</label>
                                                        <input type="text" id="fulfillment-ship_to_store-ffl" name="fulfillment-ship_to_store-ffl" data-autosave="true">
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-phone">Phone Number:</label>
                                                        <input type="number" id="fulfillment-ship_to_store-phone" name="fulfillment-ship_to_store-phone" data-autosave="true">
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-address-ship_to_name">Business/Name:</label>
                                                        <input type="text" id="fulfillment-ship_to_store-address-ship_to_name" name="fulfillment-ship_to_store-address-ship_to_name"  data-autosave="true">
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-address-address_street">Street Address:</label>
                                                        <input type="text" id="fulfillment-ship_to_store-address-address_street" name="fulfillment-ship_to_store-address-address_street"  data-autosave="true">
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-address-city">City:</label>
                                                        <input type="text" id="fulfillment-ship_to_store-address-city" name="fulfillment-ship_to_store-address-city"  data-autosave="true">
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-address-state">State:</label>
                                                        <select id="fulfillment-ship_to_store-address-state" name="fulfillment-ship_to_store-address-state"  data-autosave="true"></select>
                                                        <script>
                                                            const dropdown = document.getElementById('fulfillment-ship_to_store-address-state');
                                                            statesAndTerritories.forEach(state => {
                                                                const option = document.createElement('option');
                                                                option.value = state.value;
                                                                option.textContent = state.text;
                                                                dropdown.appendChild(option);
                                                            });
                                                        </script>
                                                    </div>
                                                    <div class="pricing-assumptions-form-row">
                                                        <label for="fulfillment-ship_to_store-address-postal_code">Zip Code:</label>
                                                        <input type="text" id="fulfillment-ship_to_store-address-postal_code" name="fulfillment-ship_to_store-address-postal_code"  data-autosave="true">
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                            <div class="tab-pane fade show active" id="distributors" role="tabpanel" aria-labelledby="distributors-tab">
                                                <!-- Distributors Form Content -->
                                                    <div class="helperDialog"><strong>Distributors (or Sources)</strong> allow you select where you want to pull the catalog data from to list products on your site. Select all of your distributors you'd like, making sure that you click on the Configure links to enter in your account credentials and other important information. The toggle in each card is showing whether or not the distributor is activated and feeding product to your site.</div>
                                                    <div>
                                                        <div class="row" id="distributors-container">
                                                            <!-- Existing distributors will be loaded here -->
                                                        </div>
                                                        <div class="d-flex align-items-center mt-2" id="distributor-select-container">
                                                            <select class="form-control mr-2" id="available-distributors">
                                                                <!-- Options will be populated by JavaScript -->
                                                            </select>
                                                            <button class="button alt" id="add-distributor">Add Distributor</button>
                                                        </div>
                                                    </div>
                                                    <script>
                                                        let initialCockpitConfiguration = null;
                                                        let distributorsSchema = null;
                                                        let targetSchema = null;
                                                        let validatedDistributors = null;
                                                        

                                                        function getDistributorStatus(distid) {
                                                            if (validatedDistributors != null) {
                                                                // Use the find() method to locate the distributor object with the matching distid
                                                                const distributor = validatedDistributors.find(distributor => distributor.distid === distid);
                                                                // If the distributor is found, return its status; otherwise, return 'not found' or another appropriate value
                                                                return distributor ? distributor.status : 'not found';
                                                            }
                                                            // Return 'not found' or another appropriate value if validatedDistributors is null
                                                            return 'not valid';
                                                        }

                                                        async function reset_validated_distributors() {
                                                            validatedDistributors = null;
                                                            //alert("Getting validated distributors");
                                                            try {
                                                                const response = await fetch("https://ffl-api.garidium.com", {
                                                                    method: "POST",
                                                                    headers: {
                                                                        "Accept": "application/json",
                                                                        "Content-Type": "application/json",
                                                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                    },
                                                                    body: JSON.stringify({ "action": "get_validated_distributors", "data": {"api_key": document.getElementById('g_ffl_cockpit_key').value}})
                                                                });
                                                                const data = await response.json();
                                                                validatedDistributors = data;
                                                            } catch (error) {
                                                                console.error('Error fetching validated distributors:', error);
                                                                return null; // Return null or handle the error as needed
                                                            }
                                                            return validatedDistributors;
                                                        }

                                                        async function get_distributors_schema() {
                                                            if (distributorsSchema == null) {
                                                                try {
                                                                    const response = await fetch("https://ffl-api.garidium.com", {
                                                                        method: "POST",
                                                                        headers: {
                                                                            "Accept": "application/json",
                                                                            "Content-Type": "application/json",
                                                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                        },
                                                                        body: JSON.stringify({ "action": "get_distributors_schema" })
                                                                    });

                                                                    const data = await response.json();
                                                                    distributorsSchema = data;
                                                                } catch (error) {
                                                                    console.error('Error fetching target schema:', error);
                                                                    return null; // Return null or handle the error as needed
                                                                }
                                                            }
                                                            
                                                            return distributorsSchema;
                                                        }

                                                        async function get_target_schema() {
                                                            if (targetSchema == null) {
                                                                try {
                                                                    const response = await fetch("https://ffl-api.garidium.com", {
                                                                        method: "POST",
                                                                        headers: {
                                                                            "Accept": "application/json",
                                                                            "Content-Type": "application/json",
                                                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                        },
                                                                        body: JSON.stringify({ "action": "get_targets_schema" })
                                                                    });

                                                                    const data = await response.json();
                                                                    targetSchema = data;
                                                                } catch (error) {
                                                                    console.error('Error fetching target schema:', error);
                                                                    return null; // Return null or handle the error as needed
                                                                }
                                                            }
                                                            
                                                            return targetSchema;
                                                        }

                                                        function load_fancy_editor(config){
                                                            // Store configuration globally for editor content loading
                                                            window.currentConfiguration = config;
                                                            window.gffcHasGunbrokerTargetInConfig = !!(config && config.targets && config.targets.gunbroker);
                                                            if (typeof window.gffcApplyMultiServerConfigAccess === "function") {
                                                                window.gffcApplyMultiServerConfigAccess(config);
                                                            }
                                                            if (typeof window.gffcSyncGunbrokerProcessorVisibility === "function") {
                                                                window.gffcSyncGunbrokerProcessorVisibility();
                                                            }
                                                            if (typeof window.gffcRefreshProductSearchAvailability === "function") {
                                                                window.gffcRefreshProductSearchAvailability(true);
                                                            }

                                                            // Ensure Notification editors immediately reflect the newly loaded config
                                                            // (prevents stale content / JSON corruption when saving)
                                                            if (typeof window.syncNotificationEditorsFromCurrentConfiguration === "function") {
                                                                window.syncNotificationEditorsFromCurrentConfiguration();
                                                                // One extra retry shortly after load to handle slow TinyMCE init timing
                                                                setTimeout(function() {
                                                                    window.syncNotificationEditorsFromCurrentConfiguration();
                                                                }, 1200);
                                                            }
                                                            
                                                            $('#distributors-container').empty();
                                                            $('#targets-container').empty();
                      
                                                            // console.log(">>Adding Distributor Forms");
                                                            for (let key in config.distributors) {
                                                                addDistributorForm(key, config.distributors[key]);
                                                            }

                                                            // console.log(">>Adding Target Forms");
                                                            const gunbrokerOnlyMode = isGunbrokerOnlyTargetMode(config);
                                                            for (let key in config.targets) {
                                                                if (gunbrokerOnlyMode && key !== 'gunbroker') {
                                                                    continue;
                                                                }
                                                                addTargetForm(key, config.targets[key]);
                                                            }
                                                            
                                                            //pricing fields
                                                            document.getElementById("pricing-margin-default-margin_percentage").value = config.pricing.margin.default.margin_percentage;
                                                            document.getElementById("pricing-margin-default-margin_dollar").value = config.pricing.margin.default.margin_dollar;
                                                            document.getElementById("pricing-sales_tax_assumption").value = config.pricing.sales_tax_assumption;
                                                            document.getElementById("pricing-credit_card_fee_percent").value = config.pricing.credit_card_fee_percent;
                                                            document.getElementById("pricing-credit_card_fee_transaction").value = config.pricing.credit_card_fee_transaction;
                                                            
                                                            document.getElementById("pricing-rounding").value = config.pricing.rounding;
                                                            //document.getElementById("pricing-include_shipping_in_price").checked = config.pricing.include_shipping_in_price;
                                                            document.getElementById("pricing-include_credit_card_fees_in_price").checked = config.pricing.include_credit_card_fees_in_price;
                                                            document.getElementById("pricing-sell_at_map").checked = config.pricing.sell_at_map;
                                                            
                                                            $('#pricing-ignore_map_brands').empty();
                                                            if (config.pricing.ignore_map_brands){
                                                                addSelectedItemsToContainer(document.getElementById("pricing-ignore_map_brands"), config.pricing.ignore_map_brands);
                                                            }
                                                            
                                                            // load price-based default margin table
                                                            // Always clear the table first, then load new data if it exists
                                                            price_based_margin_table = document.getElementById(`price-based-margin-table-group-default`);
                                                            removeAllRowsExceptHeader(price_based_margin_table);
                                                            if (config.pricing.margin.default.price_based_margin && config.pricing.margin.default.price_based_margin.length > 0){
                                                                const price_based_margin_tbody = price_based_margin_table.querySelector('tbody');
                                                                config.pricing.margin.default.price_based_margin.forEach((pbm, index) => {
                                                                    loadPriceBasedMargin("group-default", price_based_margin_tbody, pbm.minimum_unit_cost, pbm.maximum_unit_cost, pbm.margin_dollar, pbm.margin_percentage, index);
                                                                });
                                                            }
                                                            
                                                            $('#margin-group-container').empty();
                                                            for (let key in config.pricing.margin) {
                                                                if (key!="default"){
                                                                    addMarginGroup(key, config.pricing.margin[key]);
                                                                }
                                                            }
                                                            
                                                            // Ship-to-Store/Location Info
                                                            document.getElementById("fulfillment-ship_to_store-address-ship_to_name").value = config.fulfillment.ship_to_store.address.ship_to_name;
                                                            document.getElementById("fulfillment-ship_to_store-ffl").value = config.fulfillment.ship_to_store.ffl;
                                                            document.getElementById("fulfillment-ship_to_store-phone").value = config.fulfillment.ship_to_store.phone?config.fulfillment.ship_to_store.phone:"";
                                                            document.getElementById("fulfillment-ship_to_store-address-address_street").value = config.fulfillment.ship_to_store.address.address_street;
                                                            document.getElementById("fulfillment-ship_to_store-address-city").value = config.fulfillment.ship_to_store.address.city;
                                                            document.getElementById("fulfillment-ship_to_store-address-postal_code").value = config.fulfillment.ship_to_store.address.postal_code;
                                                            document.getElementById("fulfillment-ship_to_store-address-state").value = config.fulfillment.ship_to_store.address.state;
                                                            
                                                            
                                                            // load email templates
                                                            document.getElementById("notification_email").value = config.notification_email;
                                                            document.getElementById("fulfillment-emailer-from_email").value = config.fulfillment.emailer.from_email;
                                                            
                                                            document.getElementById("fulfillment-emailer-templates-ffl_request-subject").value = config.fulfillment.emailer.templates.ffl_request.subject;
                                                            // Set textarea content as backup for TinyMCE loading
                                                            var fflRequestTextarea = document.getElementById("fulfillment-emailer-templates-ffl_request-message");
                                                            if (fflRequestTextarea) {
                                                                fflRequestTextarea.value = config.fulfillment.emailer.templates.ffl_request.message;
                                                            }
                                                            
                                                            document.getElementById("fulfillment-emailer-templates-order_processed-subject").value = config.fulfillment.emailer.templates.order_processed.subject;
                                                            // Set textarea content as backup for TinyMCE loading
                                                            var processedFflTextarea = document.getElementById("fulfillment-emailer-templates-order_processed-message_ffl_order");
                                                            var processedNonFflTextarea = document.getElementById("fulfillment-emailer-templates-order_processed-message_non_ffl_order");
                                                            if (processedFflTextarea) {
                                                                processedFflTextarea.value = config.fulfillment.emailer.templates.order_processed.message_ffl_order;
                                                            }
                                                            if (processedNonFflTextarea) {
                                                                processedNonFflTextarea.value = config.fulfillment.emailer.templates.order_processed.message_non_ffl_order;
                                                            }

                                                            document.getElementById("fulfillment-emailer-templates-order_shipped-subject").value = config.fulfillment.emailer.templates.order_shipped.subject;
                                                            // Set textarea content as backup for TinyMCE loading
                                                            var shippedFflTextarea = document.getElementById("fulfillment-emailer-templates-order_shipped-message_ffl_order");
                                                            var shippedNonFflTextarea = document.getElementById("fulfillment-emailer-templates-order_shipped-message_non_ffl_order");
                                                            if (shippedFflTextarea) {
                                                                shippedFflTextarea.value = config.fulfillment.emailer.templates.order_shipped.message_ffl_order;
                                                            }
                                                            if (shippedNonFflTextarea) {
                                                                shippedNonFflTextarea.value = config.fulfillment.emailer.templates.order_shipped.message_non_ffl_order;
                                                            }

                                                            document.getElementById("fulfillment-emailer-templates-order_delivered-subject").value = config.fulfillment.emailer.templates.order_delivered.subject;
                                                            // Set textarea content as backup for TinyMCE loading
                                                            var deliveredFflTextarea = document.getElementById("fulfillment-emailer-templates-order_delivered-message_ffl_order");
                                                            var deliveredNonFflTextarea = document.getElementById("fulfillment-emailer-templates-order_delivered-message_non_ffl_order");
                                                            if (deliveredFflTextarea) {
                                                                deliveredFflTextarea.value = config.fulfillment.emailer.templates.order_delivered.message_ffl_order;
                                                            }
                                                            if (deliveredNonFflTextarea) {
                                                                deliveredNonFflTextarea.value = config.fulfillment.emailer.templates.order_delivered.message_non_ffl_order;
                                                            }

                                                            // Product Restrictions
                                                            document.getElementById("product_restrictions-min_quantity_to_list").value = config.product_restrictions.min_quantity_to_list;
                                                            document.getElementById("product_restrictions-cost-global_restrictions-min_distributor_cost").value = config.product_restrictions.cost.global_restrictions.min_distributor_cost;
                                                            document.getElementById("product_restrictions-cost-global_restrictions-max_distributor_cost").value = config.product_restrictions.cost.global_restrictions.max_distributor_cost;
                                                            
                                                            const restrictions = ["product_class","category","brand","sku","upc"];
                                                            const include_excludes = ["include","exclude"];
                                                        
                                                            // Only try to set operand options if product_restrictions exists and elements are available
                                                            if (config.product_restrictions) {
                                                                restrictions.forEach(restriction => {
                                                                    if (config.product_restrictions[restriction] && config.product_restrictions[restriction]['include_operand']){
                                                                        toggleOperandOption(`product_restrictions-${restriction}`, config.product_restrictions[restriction].include_operand);
                                                                    }else{
                                                                        toggleOperandOption(`product_restrictions-${restriction}`, "AND");
                                                                    }
                                                                });
                                                            }
                                                            

                                                            // Only try to populate restrictions if product_restrictions exists and elements are available
                                                            if (config.product_restrictions) {
                                                                restrictions.forEach(restriction => {
                                                                include_excludes.forEach(include_exclude => {
                                                                    if (config.product_restrictions[restriction] && config.product_restrictions[restriction][include_exclude]){
                                                                        const restrictionElement = document.getElementById(`product_restrictions-${restriction}-${include_exclude}`);
                                                                        if (restrictionElement) {
                                                                            $(`#product_restrictions-${restriction}-${include_exclude}`).empty();
                                                                            addSelectedItemsToContainer(restrictionElement, config.product_restrictions[restriction][include_exclude]);
                                                                        } else {
                                                                            console.log(`Product restriction element not found: product_restrictions-${restriction}-${include_exclude}`);
                                                                        }
                                                                    }
                                                                });
                                                            });
                                                            }
                                                            populateAvailableDistributors();
                                                            populateAvailableTargets();
                                                            
                                                            // Reset product restrictions initialization flag so it reloads when accessed
                                                            if (typeof productRestrictionsInitialized !== 'undefined') {
                                                                productRestrictionsInitialized = false;
                                                            }
                                                            
                                                            // If currently on product restrictions tab, reinitialize it
                                                            if (document.getElementById('product-restrictions-tab').classList.contains('active')) {
                                                                setTimeout(ensureProductRestrictionsInitialized, 100);
                                                            }
                                                            
                                                            // Reset AI configuration loaded flag and reload AI configuration
                                                            if (typeof aiConfigurationLoaded !== 'undefined') {
                                                                aiConfigurationLoaded = false;
                                                            }
                                                            
                                                            // Refresh AI token count for the loaded configuration
                                                            if (typeof loadAITokens !== 'undefined') {
                                                                loadAITokens();
                                                            }
                                                            
                                                            // If currently on AI tab, reload the AI configuration
                                                            if (document.getElementById('ai-product-info-tab').classList.contains('active')) {
                                                                if (typeof loadExistingAIConfiguration !== 'undefined') {
                                                                    setTimeout(loadExistingAIConfiguration, 100);
                                                                }
                                                            }
                                                            
                                                            // Reload TinyMCE editors with the new configuration content
                                                            setTimeout(function() {
                                                                if (typeof window.initializeTinyMCEEditors === 'function') {
                                                                    window.initializeTinyMCEEditors();
                                                                }
                                                            }, 1000);
                                                            
                                                            document.getElementById("configuration_loading_overlay").style.display="none";
                                                        }

                                                        function isGunbrokerOnlyTargetMode(configOverride = null) {
                                                            const cfg = configOverride || window.currentConfiguration;
                                                            return !!(
                                                                window.gffcIsFFLCockpitMultisite &&
                                                                cfg &&
                                                                cfg.targets &&
                                                                cfg.targets.gunbroker
                                                            );
                                                        }

                                                        function populateAvailableDistributors() {
                                                            const selectElement = $('#available-distributors');
                                                            selectElement.empty();
                                                            for (let key in distributorsSchema) {
                                                                if (!$(`#distributors-container .card-title:contains(${key})`).length) {
                                                                    selectElement.append(`<option value="${key}">${key}</option>`);
                                                                }
                                                            }
                                                            toggleDistributorSelectContainer();
                                                        }

                                                        function populateAvailableTargets() {
                                                            const selectElement = $('#available-targets');
                                                            selectElement.empty();
                                                            const gunbrokerOnlyMode = isGunbrokerOnlyTargetMode(editor.get());
                                                            for (let key in targetSchema) {
                                                                if (gunbrokerOnlyMode && key !== 'gunbroker') {
                                                                    continue;
                                                                }
                                                                if (!$(`#targets-container .card-title:contains(${targetSchema[key].display_name})`).length) {
                                                                    selectElement.append(`<option value="${key}">${targetSchema[key].display_name}</option>`);
                                                                }
                                                            }
                                                            toggleTargetSelectContainer();
                                                        }

                                                        function toggleOperandOption(restriction_id, option, setConfig = false) {
                                                            const andOption = document.getElementById(restriction_id + '-and-option');
                                                            const orOption = document.getElementById(restriction_id + '-or-option');
                                                            
                                                            // Check if elements exist before trying to manipulate them
                                                            if (!andOption || !orOption) {
                                                                console.log(`Operand option elements not found for ${restriction_id}, skipping toggle`);
                                                                return;
                                                            }
                                                            
                                                            andOption.classList.remove('operand_selected');
                                                            orOption.classList.remove('operand_selected');
                                                            
                                                            if (option === 'AND') {
                                                                andOption.classList.add('operand_selected');
                                                            } else if (option === 'OR') {
                                                                orOption.classList.add('operand_selected');
                                                            }

                                                            if (setConfig){
                                                                const cc = editor.get();
                                                                setConfigValue(cc, `${restriction_id}-include_operand`, option);
                                                                editor.set(cc);
                                                            }
                                                        }
                                                  
                                                        function update_distributor_active(distid, distributor){
                                                            dist_active = document.getElementById(distid + "-active").checked;
                                                            config = editor.get();
                                                            config.distributors[distributor].active = dist_active;
                                                            editor.set(config);
                                                        }

                                                        function update_target_active(target){
                                                            target_active = document.getElementById(target + "-active").checked;
                                                            config = editor.get();
                                                            config.targets[target].active = target_active;
                                                            editor.set(config);
                                                        }

                                                        function remove_all_cockpit_gunbroker_listings(){
                                                            if (confirm("This will delete all gunbroker listings generated by FFL Cockpit. Do you wish to proceed?")){
                                                                document.getElementById("delete_gunbroker_listings_button").disabled = true;
                                                                document.getElementById('delete_gunbroker_listings_button').innerText = 'Request Sent';
                                                                
                                                                // Automatically disable the gunbroker target
                                                                const gunbrokerCheckbox = document.getElementById("gunbroker-active");
                                                                if (gunbrokerCheckbox) {
                                                                    gunbrokerCheckbox.checked = false;
                                                                    // Trigger the update function to save the change
                                                                    update_target_active('gunbroker');
                                                                }
                                                                
                                                                fetch("https://ffl-api.garidium.com", {
                                                                        method: "POST",
                                                                        headers: {
                                                                            "Accept": "application/json",
                                                                            "Content-Type": "application/json",
                                                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                                                        },
                                                                        body: JSON.stringify({"action": "remove_all_gunbroker_listings", "data": {"api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"}})
                                                                    })
                                                                    .then(response=>response.json())
                                                                    .then(data=>{ 
                                                                        alert("Your request for removal of all FFL Cockpit Generated Gunbroker Listings has been submitted. This can take up to an hour if you have many listings. The Gunbroker target has been automatically disabled to prevent re-listing.");
                                                                        document.getElementById("delete_gunbroker_listings_button").disabled = false; 
                                                                        document.getElementById('delete_gunbroker_listings_button').innerText = 'Delete all Cokpit-generated Gunbroker Listings';     
                                                                    });
                                                            }
                                                        }

                                                        function addDistributorForm(distributor = "", config = {}) {
                                                            if (distributorsSchema[distributor]){
                                                                const distid = distributorsSchema[distributor].distid;
                                                                let formHtml = `<div class="distcards">
                                                                                    <div class="card mt-2" id="${distid}">
                                                                                        <div class="card-header">
                                                                                            ${getDistributorStatus(distid) == "validated" ? '<div class="cockpit-distributor-ribbon">Validated</div>' : ''}
                                                                                            ${getDistributorStatus(distid) == "incomplete" ? '<div class="cockpit-distributor-ribbon-incomplete">Incomplete</div>' : ''}
                                                                                            <div class="distid_image_area">
                                                                                                <img src="${imageBaseUrl}distributor_logo_${distid}.png" alt="${distributor} logo" onerror="this.style.display='none';">
                                                                                            </div>
                                                                                            <h5 class="card-title">${distributor}</h5>${distributorsSchema[distributor].automated_fulfillment?"":" <span class='cockpit-watermark'>Product Feed Only</span>"}
                                                                                            <label class="toggle-switch">
                                                                                                <input onchange="update_distributor_active('${distid}', '${distributor}');" type="checkbox" id="${distid}-active" name="${distid}-active" ${config.active ? 'checked' : ''}>
                                                                                                <span class="slider"></span>
                                                                                            </label>
                                                                                        </div>
                                                                                        <div class="card-body">
                                                                                            <div class="action-links">
                                                                                                <span class="configure-link" onclick="viewDistributorDetails('${distributor}', '${distid}')">Configure</span>
                                                                                                <span>|</span>
                                                                                                <span class="remove-link" onclick="confirmRemoveDistributor('${distid}')">Remove</span>
                                                                                            </div>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>`;

                                                                $('#distributors-container').append(formHtml);

                                                                // Remove the selected distributor from the available list
                                                                $(`#available-distributors option[value="${distributor}"]`).remove();

                                                                // Check if all distributors are added
                                                                toggleDistributorSelectContainer();
                                                            }
                                                        }

                                                        function addTargetForm(target = "", config = {}) {
                                                            if (!targetSchema[target]){
                                                                return;
                                                            }
                                                            if (isGunbrokerOnlyTargetMode(editor.get()) && target !== 'gunbroker') {
                                                                return;
                                                            }
                                                            const target_id = target;
                                                            let formHtml = `<div class="targetcards">
                                                                                <div class="card mt-2" id="${target_id}">
                                                                                    <div class="card-header">
                                                                                        <div class="distid_image_area">
                                                                                            <img src="${imageBaseUrl}target_logo_${target_id}.png" alt="${target} logo" onerror="this.style.display='none';">
                                                                                        </div>
                                                                                        <h5 class="card-title">${targetSchema[target].display_name}</h5>
                                                                                        <label class="toggle-switch">
                                                                                            <input onchange="update_target_active('${target_id}');" type="checkbox" id="${target_id}-active" name="${target_id}-active" ${config.active ? 'checked' : ''}>
                                                                                            <span class="slider"></span>
                                                                                        </label>
                                                                                    </div>
                                                                                    <div class="card-body">
                                                                                        <div class="action-links">
                                                                                            <span class="configure-link" onclick="viewTargetDetails('${target}', '${target_id}')">Configure</span>
                                                                                            <span>|</span>
                                                                                            <span class="remove-link" onclick="confirmRemoveTarget('${target_id}')">Remove</span>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>`;

                                                            $('#targets-container').append(formHtml);

                                                            // Remove the selected distributor from the available list
                                                            $(`#available-targets option[value="${target}"]`).remove();

                                                            // Check if all distributors are added
                                                            toggleTargetSelectContainer();
                                                        }

                                                        function confirmRemoveDistributor(distributorId) {
                                                            if (confirm("Are you sure you want to delete this distributor?")) {
                                                                removeDistributor(distributorId);
                                                            }
                                                        }

                                                        function confirmRemoveTarget(targetId) {
                                                            if (confirm("Are you sure you want to delete this target, all existing configuration for this target will be reset.?")) {
                                                                removeTarget(targetId);
                                                            }
                                                        }

                                                        function removeDistributor(distributorId) {
                                                            const distributorName = $(`#${distributorId} .card-title`).text();
                                                            $(`#${distributorId}`).closest('.distcards').remove();

                                                            // Add the removed distributor back to the available list
                                                            $('#available-distributors').append(`<option value="${distributorName}">${distributorName}</option>`);

                                                            // Check if distributor dropdown and button should be shown
                                                            toggleDistributorSelectContainer();

                                                            // Now lets remove it from the actual configuration
                                                            config = editor.get();
                                                            delete config.distributors[distributorName];
                                                            editor.set(config);
                                                        
                                                        }

                                                        function removeTarget(targetId) {
                                                            $(`#${targetId.replace(/\./g, '\\.')}`).closest('.targetcards').remove();


                                                            // Add the removed distributor back to the available list
                                                            $('#available-targets').append(`<option value="${targetId}">${targetSchema[targetId].display_name}</option>`);

                                                            // Check if distributor dropdown and button should be shown
                                                            toggleTargetSelectContainer();

                                                            // Now lets remove it from the actual configuration
                                                            config = editor.get();
                                                            delete config.targets[targetId];
                                                            editor.set(config);
                                                        
                                                        }
                                                        
                                                        // Make jQuery available globally for onclick handlers
                                                        window.$ = window.$ || jQuery;
                                                        
                                                        function getConfigValue(obj, path) {
                                                            const keys = path.split('-');
                                                            let current = obj;

                                                            for (let key of keys) {
                                                                if (current[key] === undefined) {
                                                                    return undefined;
                                                                }
                                                                current = current[key];
                                                            }

                                                            return current;
                                                        }

                                                        function setConfigValue(obj, path, value) {
                                                            const keys = path.split('-');
                                                            let current = obj;

                                                            for (let i = 0; i < keys.length; i++) {
                                                                const key = keys[i];
                                                                
                                                                // If it's the last key, set the value
                                                                if (i === keys.length - 1) {
                                                                    current[key] = value;
                                                                } else {
                                                                    // If the key doesn't exist, create an empty object
                                                                    if (current[key] === undefined) {
                                                                        current[key] = {};
                                                                    }
                                                                    current = current[key];
                                                                }
                                                            }
                                                        }

                                                        /* ── Analytics Tag Mapping (multi-entry per section) ── */

                                                        // Section metadata used by the woo target's Analytics Tag Mapping panel.
                                                        const GFFC_ANALYTICS_SECTIONS = [
                                                            {key: 'top_products', label: 'Top Products by Movement', icon: 'fa-trophy'},
                                                            {key: 'trending',     label: 'Trending Products',        icon: 'fa-fire'},
                                                            {key: 'on_sale',      label: 'On Sale',                  icon: 'fa-tags'},
                                                            {key: 'new_arrivals', label: 'New Arrivals',             icon: 'fa-star'}
                                                        ];

                                                        function gffcAnalyticsTagSectionMeta(secKey) {
                                                            return GFFC_ANALYTICS_SECTIONS.find(s => s.key === secKey);
                                                        }

                                                        function gffcAnalyticsTagNewEntryId() {
                                                            return 'e' + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
                                                        }

                                                        // window.gffcAnalyticsTagState = { top_products: [{entryId, tag, product_classes, categories}, ...], ... }
                                                        function gffcAnalyticsTagsInitState() {
                                                            window.gffcAnalyticsTagState = {};
                                                            GFFC_ANALYTICS_SECTIONS.forEach(s => { window.gffcAnalyticsTagState[s.key] = []; });
                                                        }

                                                        const GFFC_ANALYTICS_WINDOWS = ['7d', '30d', '60d', '90d'];
                                                        const GFFC_ANALYTICS_DEFAULT_WINDOW = '30d';

                                                        function gffcAnalyticsTagsLoadFromConfig() {
                                                            gffcAnalyticsTagsInitState();
                                                            const cc = editor.get();
                                                            const atags = (cc && cc.targets && cc.targets.woo && cc.targets.woo.product_tags && cc.targets.woo.product_tags.analytics_tags) || {};
                                                            GFFC_ANALYTICS_SECTIONS.forEach(s => {
                                                                const raw = atags[s.key];
                                                                let entries = [];
                                                                if (Array.isArray(raw)) entries = raw;
                                                                else if (raw && typeof raw === 'object') entries = [raw]; // legacy single-object form
                                                                window.gffcAnalyticsTagState[s.key] = entries.map(e => ({
                                                                    entryId: gffcAnalyticsTagNewEntryId(),
                                                                    tag: (e && typeof e.tag === 'string') ? e.tag : '',
                                                                    window: (e && typeof e.window === 'string' && GFFC_ANALYTICS_WINDOWS.indexOf(e.window) !== -1)
                                                                            ? e.window : GFFC_ANALYTICS_DEFAULT_WINDOW,
                                                                    product_classes: Array.isArray(e && e.product_classes) ? e.product_classes.slice() : [],
                                                                    categories:      Array.isArray(e && e.categories)      ? e.categories.slice()      : []
                                                                }));
                                                            });
                                                        }

                                                        function gffcAnalyticsTagsSyncToConfig() {
                                                            const cc = editor.get();
                                                            if (!cc.targets) cc.targets = {};
                                                            if (!cc.targets.woo) cc.targets.woo = {};
                                                            if (!cc.targets.woo.product_tags) cc.targets.woo.product_tags = {};
                                                            if (!cc.targets.woo.product_tags.analytics_tags) cc.targets.woo.product_tags.analytics_tags = {};
                                                            const atags = cc.targets.woo.product_tags.analytics_tags;
                                                            GFFC_ANALYTICS_SECTIONS.forEach(s => {
                                                                const out = (window.gffcAnalyticsTagState[s.key] || [])
                                                                    .map(e => {
                                                                        const obj = { tag: (e.tag || '').trim() };
                                                                        const win = (typeof e.window === 'string' && GFFC_ANALYTICS_WINDOWS.indexOf(e.window) !== -1) ? e.window : GFFC_ANALYTICS_DEFAULT_WINDOW;
                                                                        obj.window = win;
                                                                        if (e.product_classes && e.product_classes.length > 0) obj.product_classes = e.product_classes.slice();
                                                                        if (e.categories      && e.categories.length      > 0) obj.categories      = e.categories.slice();
                                                                        return obj;
                                                                    })
                                                                    .filter(o => o.tag.length > 0 || (o.product_classes && o.product_classes.length) || (o.categories && o.categories.length));
                                                                if (out.length > 0) atags[s.key] = out;
                                                                else if (Object.prototype.hasOwnProperty.call(atags, s.key)) delete atags[s.key];
                                                            });
                                                            editor.set(cc);
                                                        }

                                                        // Parse "analytics-tag-<kind>-<section>-<entryId>" container IDs.
                                                        function gffcAnalyticsTagParseContainerId(id) {
                                                            if (typeof id !== 'string' || !id.startsWith('analytics-tag-')) return null;
                                                            const rest = id.slice('analytics-tag-'.length); // pc-top_products-eXYZ  OR  cat-trending-eXYZ
                                                            const dash1 = rest.indexOf('-');
                                                            if (dash1 < 0) return null;
                                                            const kind = rest.slice(0, dash1); // 'pc' or 'cat'
                                                            if (kind !== 'pc' && kind !== 'cat') return null;
                                                            const afterKind = rest.slice(dash1 + 1);
                                                            // section keys all contain underscores; entry id is the LAST hyphen-separated chunk
                                                            const lastDash = afterKind.lastIndexOf('-');
                                                            if (lastDash < 0) return null;
                                                            const section = afterKind.slice(0, lastDash);
                                                            const entryId = afterKind.slice(lastDash + 1);
                                                            if (!gffcAnalyticsTagSectionMeta(section)) return null;
                                                            return { kind: kind, section: section, entryId: entryId, field: kind === 'pc' ? 'product_classes' : 'categories' };
                                                        }

                                                        function gffcAnalyticsTagFindEntry(section, entryId) {
                                                            const list = window.gffcAnalyticsTagState && window.gffcAnalyticsTagState[section];
                                                            if (!Array.isArray(list)) return null;
                                                            return list.find(e => e.entryId === entryId) || null;
                                                        }

                                                        function gffcAnalyticsTagRenderRow(section, entry) {
                                                            const meta = gffcAnalyticsTagSectionMeta(section);
                                                            const eid = entry.entryId;
                                                            const row = document.createElement('div');
                                                            row.className = 'analytics-tag-row';
                                                            row.id = 'analytics-tag-row-' + section + '-' + eid;
                                                            row.dataset.section = section;
                                                            row.dataset.entryId = eid;
                                                            row.style.cssText = 'border:1px solid #e2e8f0; border-radius:6px; padding:12px; margin-top:10px; background:#fff;';
                                                            const escTag = (entry.tag || '').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
                                                            const entryWin = (typeof entry.window === 'string' && GFFC_ANALYTICS_WINDOWS.indexOf(entry.window) !== -1) ? entry.window : GFFC_ANALYTICS_DEFAULT_WINDOW;
                                                            const winLabels = { '7d': 'Last 7 days', '30d': 'Last 30 days', '60d': 'Last 60 days', '90d': 'Last 90 days' };
                                                            const windowOptions = GFFC_ANALYTICS_WINDOWS.map(w => `<option value="${w}"${w === entryWin ? ' selected' : ''}>${winLabels[w]}</option>`).join('');
                                                            row.innerHTML = `
                                                                <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px;">
                                                                    <div style="font-weight:600;"><i class="fas ${meta.icon}" style="color:#4a90d9; margin-right:6px;"></i>${meta.label}</div>
                                                                    <span class="add-item" style="font-size:12px;" onclick="gffcAnalyticsTagRemoveEntry('${section}','${eid}')">Remove</span>
                                                                </div>
                                                                <div class="form-row" style="margin-bottom:8px;">
                                                                    <label>Tag Name:</label>
                                                                    <div class="field-container">
                                                                        <input type="text"
                                                                               id="analytics-tag-name-${section}-${eid}"
                                                                               data-analytics-tag-input="1"
                                                                               data-section="${section}" data-entry-id="${eid}"
                                                                               value="${escTag}"
                                                                               placeholder="e.g. ${meta.label}"
                                                                               maxlength="100"
                                                                               style="width:100%; padding:6px 10px; border:1px solid #cbd5e1; border-radius:4px;" />
                                                                    </div>
                                                                </div>
                                                                <div class="form-row" style="margin-bottom:8px;">
                                                                    <label>Analytics Window:</label>
                                                                    <div class="field-container">
                                                                        <select id="analytics-tag-window-${section}-${eid}"
                                                                                data-analytics-tag-window="1"
                                                                                data-section="${section}" data-entry-id="${eid}"
                                                                                style="width:auto; padding:6px 10px; border:1px solid #cbd5e1; border-radius:4px;">
                                                                            ${windowOptions}
                                                                        </select>
                                                                    </div>
                                                                </div>
                                                                <div class="form-row" style="margin-bottom:8px;">
                                                                    <label>Product Classes:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="analytics-tag-pc-${section}-${eid}"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('productClassModal', 'analytics-tag-pc-${section}-${eid}')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('analytics-tag-pc-${section}-${eid}'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="form-row">
                                                                    <label>Categories:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="analytics-tag-cat-${section}-${eid}"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('categoryModal', 'analytics-tag-cat-${section}-${eid}')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('analytics-tag-cat-${section}-${eid}'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            `;
                                                            return row;
                                                        }

                                                        function gffcAnalyticsTagAttachInputListener(input) {
                                                            if (!input || input.dataset.bound === '1') return;
                                                            input.dataset.bound = '1';
                                                            const handler = function() {
                                                                const sec = input.dataset.section;
                                                                const eid = input.dataset.entryId;
                                                                const entry = gffcAnalyticsTagFindEntry(sec, eid);
                                                                if (!entry) return;
                                                                if (entry.tag !== input.value) {
                                                                    entry.tag = input.value;
                                                                    gffcAnalyticsTagsSyncToConfig();
                                                                }
                                                            };
                                                            input.addEventListener('input', handler);
                                                            input.addEventListener('blur', handler);
                                                        }

                                                        function gffcAnalyticsTagAttachWindowListener(sel) {
                                                            if (!sel || sel.dataset.bound === '1') return;
                                                            sel.dataset.bound = '1';
                                                            sel.addEventListener('change', function() {
                                                                const sec = sel.dataset.section;
                                                                const eid = sel.dataset.entryId;
                                                                const entry = gffcAnalyticsTagFindEntry(sec, eid);
                                                                if (!entry) return;
                                                                const val = GFFC_ANALYTICS_WINDOWS.indexOf(sel.value) !== -1 ? sel.value : GFFC_ANALYTICS_DEFAULT_WINDOW;
                                                                if (entry.window !== val) {
                                                                    entry.window = val;
                                                                    gffcAnalyticsTagsSyncToConfig();
                                                                }
                                                            });
                                                        }

                                                        function gffcAnalyticsTagsRenderAll() {
                                                            const list = document.getElementById('analytics-tag-list');
                                                            if (!list) return;
                                                            list.innerHTML = '';
                                                            GFFC_ANALYTICS_SECTIONS.forEach(s => {
                                                                (window.gffcAnalyticsTagState[s.key] || []).forEach(entry => {
                                                                    const row = gffcAnalyticsTagRenderRow(s.key, entry);
                                                                    list.appendChild(row);
                                                                    const pc = document.getElementById('analytics-tag-pc-' + s.key + '-' + entry.entryId);
                                                                    if (pc && entry.product_classes.length > 0) addSelectedItemsToContainer(pc, entry.product_classes);
                                                                    const cat = document.getElementById('analytics-tag-cat-' + s.key + '-' + entry.entryId);
                                                                    if (cat && entry.categories.length > 0) addSelectedItemsToContainer(cat, entry.categories);
                                                                });
                                                            });
                                                            list.querySelectorAll('input[data-analytics-tag-input="1"]').forEach(gffcAnalyticsTagAttachInputListener);
                                                            list.querySelectorAll('select[data-analytics-tag-window="1"]').forEach(gffcAnalyticsTagAttachWindowListener);
                                                            // Toggle empty-state hint
                                                            const empty = document.getElementById('analytics-tag-empty');
                                                            if (empty) empty.style.display = list.children.length === 0 ? 'block' : 'none';
                                                        }

                                                        function gffcAnalyticsTagAddFromSelect() {
                                                            const sel = document.getElementById('analytics-tag-section-select');
                                                            if (!sel) return;
                                                            const secKey = sel.value;
                                                            if (!secKey || !gffcAnalyticsTagSectionMeta(secKey)) {
                                                                alert('Pick an Analytics section first.');
                                                                return;
                                                            }
                                                            const entry = { entryId: gffcAnalyticsTagNewEntryId(), tag: '', window: GFFC_ANALYTICS_DEFAULT_WINDOW, product_classes: [], categories: [] };
                                                            window.gffcAnalyticsTagState[secKey].push(entry);
                                                            sel.value = '';
                                                            gffcAnalyticsTagsRenderAll();
                                                            gffcAnalyticsTagsSyncToConfig();
                                                            const newInput = document.getElementById('analytics-tag-name-' + secKey + '-' + entry.entryId);
                                                            if (newInput) newInput.focus();
                                                        }

                                                        // Trigger an immediate audit_analytics_tags batch run via ffl-api.
                                                        // Button stays disabled until the modal/page is reloaded so users can't fire it repeatedly.
                                                        async function gffcAnalyticsTagProcessNow() {
                                                            const btn = document.getElementById('analytics-tag-process-now-btn');
                                                            const status = document.getElementById('analytics-tag-process-status');
                                                            if (!btn) return;
                                                            if (btn.disabled) return;

                                                            // Block the run if there are unsaved cockpit config changes — the audit
                                                            // reads the live cockpit_configuration, so unsaved edits would be ignored.
                                                            if (typeof hasUnsavedChanges === 'function' && hasUnsavedChanges()) {
                                                                if (status) {
                                                                    status.innerHTML = '<i class="fas fa-exclamation-triangle"></i> You have unsaved changes. Click <strong>Save Changes</strong> at the bottom of the screen first, then try again — otherwise the audit would run against the old configuration.';
                                                                    status.style.color = '#78350f';
                                                                    status.style.background = '#fef3c7';
                                                                    status.style.border = '1px solid #fcd34d';
                                                                    status.style.padding = '10px 12px';
                                                                    status.style.borderRadius = '6px';
                                                                    status.style.fontSize = '13px';
                                                                    status.style.margin = '8px 12px 0';
                                                                }
                                                                return;
                                                            }

                                                            btn.disabled = true;
                                                            const origLabel = btn.innerHTML;
                                                            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting…';
                                                            if (status) {
                                                                status.textContent = '';
                                                                status.style.color = '#475569';
                                                                status.style.background = '';
                                                                status.style.border = '';
                                                                status.style.padding = '6px 12px 0';
                                                                status.style.borderRadius = '';
                                                                status.style.fontSize = '12px';
                                                                status.style.margin = '';
                                                            }
                                                            try {
                                                                const resp = await fetch('https://ffl-api.garidium.com', {
                                                                    method: 'POST',
                                                                    headers: {
                                                                        'Accept': 'application/json',
                                                                        'Content-Type': 'application/json',
                                                                        'x-api-key': window.gFFLCockpit.apiKey
                                                                    },
                                                                    body: JSON.stringify({
                                                                        action: 'run_audit_analytics_tags',
                                                                        data: { api_key: window.gFFLCockpit.apiKey }
                                                                    })
                                                                });
                                                                const data = await resp.json();
                                                                if (data && data.success) {
                                                                    btn.innerHTML = '<i class="fas fa-check"></i> Queued';
                                                                    const successMsg = data.message || 'Analytics tag audit submitted and now running in the background. Your WooCommerce product tags will update over the next few minutes — you don\'t need to wait on this page.';
                                                                    if (status) {
                                                                        status.innerHTML = '<i class="fas fa-info-circle"></i> ' + successMsg.replace(/&/g,'&amp;').replace(/</g,'&lt;');
                                                                        status.style.color = '#0c4a6e';
                                                                        status.style.background = '#e0f2fe';
                                                                        status.style.border = '1px solid #7dd3fc';
                                                                        status.style.padding = '10px 12px';
                                                                        status.style.borderRadius = '6px';
                                                                        status.style.fontSize = '13px';
                                                                        status.style.margin = '8px 12px 0';
                                                                    }
                                                                } else if (data && data.already_running) {
                                                                    btn.innerHTML = '<i class="fas fa-hourglass-half"></i> Already Running';
                                                                    const runningMsg = data.message || 'An analytics tag audit is already running in the background for this site. The previous run is still updating your product tags — no need to wait on this page.';
                                                                    if (status) {
                                                                        status.innerHTML = '<i class="fas fa-hourglass-half"></i> ' + runningMsg.replace(/&/g,'&amp;').replace(/</g,'&lt;');
                                                                        status.style.color = '#78350f';
                                                                        status.style.background = '#fef3c7';
                                                                        status.style.border = '1px solid #fcd34d';
                                                                        status.style.padding = '10px 12px';
                                                                        status.style.borderRadius = '6px';
                                                                        status.style.fontSize = '13px';
                                                                        status.style.margin = '8px 12px 0';
                                                                    }
                                                                } else {
                                                                    btn.innerHTML = origLabel;
                                                                    btn.disabled = false;
                                                                    if (status) { status.textContent = (data && data.message) ? data.message : 'Could not start the audit. Try again.'; status.style.color = '#dc2626'; }
                                                                }
                                                            } catch (err) {
                                                                console.error('Process Now failed:', err);
                                                                btn.innerHTML = origLabel;
                                                                btn.disabled = false;
                                                                if (status) { status.textContent = 'Network error. Try again.'; status.style.color = '#dc2626'; }
                                                            }
                                                        }

                                                        function gffcAnalyticsTagRemoveEntry(section, entryId) {
                                                            if (!confirm('Remove this analytics tag?')) return;
                                                            const list = window.gffcAnalyticsTagState && window.gffcAnalyticsTagState[section];
                                                            if (!Array.isArray(list)) return;
                                                            window.gffcAnalyticsTagState[section] = list.filter(e => e.entryId !== entryId);
                                                            gffcAnalyticsTagsSyncToConfig();
                                                            const row = document.getElementById('analytics-tag-row-' + section + '-' + entryId);
                                                            if (row) row.remove();
                                                            const empty = document.getElementById('analytics-tag-empty');
                                                            const listEl = document.getElementById('analytics-tag-list');
                                                            if (empty && listEl) empty.style.display = listEl.children.length === 0 ? 'block' : 'none';
                                                        }

                                                        function viewTargetDetails(target, targetId) {
                                                            const targetDetails = JSON.parse(targetSchema[target].ui_field_schema);
                                                            const displayName = targetSchema[target].display_name;
                                                            $('#detailsModalLabel').text(`${displayName}`);
                                                            const modalBody = $('#modal-body');
                                                            modalBody.empty();
                                                            cc = editor.get();

                                                            if (['wikiarms', 'gun.deals','gunammo.deals', 'ammoseek','dudedeals', 'ammohunter', 'ammobuy', 'caliberking', 'ammobrowser', 'armsagora', 'gunfeed', 'gunmade', 'bulletscout'].includes(target)) {
                                                                var feed_url = `https://garidium.s3.us-east-1.amazonaws.com/feeds/${window.gFFLCockpit.apiKey.slice(0, 4)}-${window.gFFLCockpit.apiKey.slice(-4)}/${target.replace(".","")}/feed.xml`;
                                                                if (target == "gunmade") {
                                                                    feed_url = `https://garidium.s3.us-east-1.amazonaws.com/feeds/${window.gFFLCockpit.apiKey.slice(0, 4)}-${window.gFFLCockpit.apiKey.slice(-4)}/${target.replace(".","")}/feed.json.gz`;
                                                                } else if (target == "ammoseek" || target == "dudedeals" || target == "bulletscout") {
                                                                    feed_url = `https://garidium.s3.us-east-1.amazonaws.com/feeds/${window.gFFLCockpit.apiKey.slice(0, 4)}-${window.gFFLCockpit.apiKey.slice(-4)}/${target.replace(".","")}/feed.xml.gz`;
                                                                }

                                                                // Initially show loading message
                                                                const feedSection = `
                                                                    <div id="feed-url-section" style="line-height: 1.25;padding:5px;margin-bottom:20px;">
                                                                        <div class="spinner" style="display: inline-block; margin-right: 10px;">
                                                                            <i class="fas fa-spinner fa-spin"></i>
                                                                        </div>
                                                                        Checking feed status...
                                                                    </div>`;
                                                                modalBody.append(feedSection);

                                                                // Check feed existence asynchronously
                                                                (async function() {
                                                                    let feedExists = false;
                                                                    try {
                                                                        const response = await fetch('/wp-json/fflcockpit/v1/remote-file-exists', {
                                                                            method: 'POST',
                                                                            headers: {
                                                                                'Content-Type': 'application/json',
                                                                            },
                                                                            body: JSON.stringify({ url: feed_url })
                                                                        });
                                                                        const result = await response.json();
                                                                        feedExists = result.exists;
                                                                    } catch (error) {
                                                                        console.warn('Could not check feed existence:', error);
                                                                        feedExists = false;
                                                                    }

                                                                    // Update the feed section with the result
                                                                    const feedSectionElement = document.getElementById('feed-url-section');
                                                                    if (feedSectionElement) {
                                                                        if (feedExists) {
                                                                            // Feed exists - show clickable URL
                                                                            feedSectionElement.innerHTML = `
                                                                                When you signup with ${displayName}, you will be asked for a Product Feed URL. Your feed is active and ready to use. The Product Feed URL is: 
                                                                                <a target="_blank" href="${feed_url}">${feed_url}</a>
                                                                                <i class="fa fa-copy copy-icon" style="cursor: pointer; margin-left: 2px;" title="Copy Feed URL to clipboard"></i>
                                                                            `;
                                                                        } else {
                                                                            // Feed doesn't exist - show activation message
                                                                            feedSectionElement.innerHTML = `
                                                                                When you signup with ${displayName}, you will be asked for a Product Feed URL. <span style="font-weight:bold;color:red;">${displayName} must be activated to create the product feed. After activating (and hitting Save Changes), check back in an hour and your feed URL will appear here.</span>
                                                                            `;
                                                                        }
                                                                    }
                                                                })();

                                                                if (target == "armsagora") {
                                                                    modalBody.append(`
                                                                    <div style="line-height: 1.25;padding:5px;margin-bottom:20px;">
                                                                        Armsagora has a signup page for FFL Cockpit Subscribers: <a target="_blank" href="https://www.armsagora.com/fflcockpit?feed_url=${feed_url}">Click Here to Signup</a> 
                                                                    </div>`);
                                                                }
                                                                if (target == "gunmade") {
                                                                    modalBody.append(`
                                                                    <div style="line-height: 1.25;padding:5px;margin-bottom:20px;">
                                                                        Find out more about GunMade product feed setup: <a target="_blank" href="https://www.gunmade.com/solutions/dealers/">Click Here to Signup</a> 
                                                                    </div>`);
                                                                }

                                                                //modalBody.append(`<hr>`);

                                                                // Add event listener using delegation for copy functionality
                                                                modalBody.on('click', '.copy-icon', function () {
                                                                    // Use the pre-defined `feed_url` variable directly
                                                                    navigator.clipboard.writeText(feed_url).then(() => {
                                                                        alert('Feed URL copied to clipboard!');
                                                                    }).catch(err => {
                                                                        console.error('Failed to copy: ', err);
                                                                        alert('Failed to copy the URL. Please try again.');
                                                                    });
                                                                });
                                                            }
                                                            
                                                            for (let key in targetDetails) {
                                                                const field = targetDetails[key];
                                                                if (field.helperText){
                                                                    modalBody.append(`
                                                                    <div class="helperDialog">
                                                                        ${field.helperText}
                                                                    </div>
                                                                    `);
                                                                }
                                                                if (field.type == "array") {
                                                                    modalBody.append(`
                                                                        <label for="${field.config_key}">${field.label}:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="${field.config_key}"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="promptAndAddItems(this, 'email', '${field.config_key}')">Add</span>
                                                                            </div>
                                                                        </div>`);
                                                                    addSelectedItemsToContainer(document.getElementById(field.config_key), getConfigValue(cc, field.config_key));
                                                                } else if (field.type == "rich_text") {
                                                                    modalBody.append(`
                                                                        <div class="textarea-wrapper">
                                                                        <label for="${field.config_key}">${field.label}:</label>
                                                                            <textarea style="height:150px;" id="${field.config_key}" name="${field.config_key}" class="modal-tinymce" data-autosave="true"></textarea>
                                                                        </div>
                                                                    `);
                                                                    
                                                                    if (typeof tinymce !== 'undefined') {
                                                                        tinymce.remove(`#${field.config_key}`);
                                                                        tinymce.init({
                                                                        selector: `#${field.config_key}`,
                                                                        plugins: 'image', // Remove plugins that require external files
                                                                        toolbar: "link bold italic underline forecolor backcolor alignleft aligncenter alignright bullist numlist image",
                                                                        license_key: 'gpl',
                                                                        menubar: false,
                                                                        branding: false,
                                                                        statusbar: false,
                                                                        convert_urls: false,
                                                                        relative_urls: false,
                                                                        paste_data_images: false,
                                                                        paste_block_drop: true,
                                                                        setup: function (mceeditor) {
                                                                            mceeditor.on('input', function () {
                                                                                clearTimeout(typingTimer);
                                                                                typingTimer = setTimeout(() => autoSave(mceeditor.getElement()), doneTypingInterval);
                                                                            });

                                                                            mceeditor.on('keydown', function () {
                                                                                clearTimeout(typingTimer);
                                                                            });

                                                                            mceeditor.on('blur', function () {
                                                                                autoSave(mceeditor.getElement());
                                                                            });

                                                                            mceeditor.on('init', function () {
                                                                                // Set the content of TinyMCE after initialization
                                                                                mceeditor.setContent(getConfigValue(cc, field.config_key));
                                                                            });

                                                                            // Prevent image pasting
                                                                            mceeditor.on('paste', function (e) {
                                                                                var clipboardData = e.clipboardData || window.clipboardData;
                                                                                if (clipboardData && clipboardData.items) {
                                                                                    for (var i = 0; i < clipboardData.items.length; i++) {
                                                                                        if (clipboardData.items[i].type.indexOf('image') !== -1) {
                                                                                            e.preventDefault();
                                                                                            return false;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            });
                                                                        }
                                                                    });
                                                                    }
                                                                } else if (field.type == "boolean") {
                                                                    var toggle_checked = getConfigValue(cc, field.config_key);
                                                                    if (toggle_checked == undefined){
                                                                        if (field.default){
                                                                            toggle_checked = field.default;
                                                                        }else{
                                                                            toggle_checked = false;
                                                                        }
                                                                    }

                                                                    modalBody.append(`<div class="form-group">
                                                                                        <label for="${field.config_key}">${field.label}</label>
                                                                                        <label class="toggle-switch">
                                                                                            <input type="checkbox" id="${field.config_key}" name="${field.config_key}" ${toggle_checked ? 'checked' : ''} data-autosave="true">
                                                                                            <span class="slider"></span>
                                                                                        </label>
                                                                                    </div>`);
                                                                } else {
                                                                    modalBody.append(`<div class="form-group">
                                                                                        <label for="${field.config_key}">${field.label}</label>
                                                                                        <input type="${field.type}" class="form-control" name="${field.config_key}" id="${field.config_key}" value="${getConfigValue(cc, field.config_key)}" data-autosave="true">
                                                                                    </div>`);
                                                                }
                                                            }

                                                            if (target !== 'gunsdotcom') {
                                                                if (['wikiarms', 'gun.deals', 'gunammo.deals', 'ammoseek', 'dudedeals', 'ammohunter', 'ammobuy', 'caliberking', 'ammobrowser', 'armsagora', 'gunfeed', 'gunmade', 'bulletscout'].includes(target)) {
                                                                    modalBody.append(`
                                                                    <div class="helperDialog">
                                                                        Specify <strong>Product Restrictions specific to ${displayName} </strong> in the section below. Expand the section and define which products you want to list on ${displayName} within each of their product groups.
                                                                    </div>`);
                                                                }else if (['liberty_gun_trader'].includes(target)) {
                                                                    modalBody.append(`
                                                                    <div class="helperDialog">
                                                                        Specify <strong>Product Restrictions specific to ${displayName} </strong> in the section below. Expand the section and define which products you want to list on ${displayName}, which has a product limit. You must put in at least one include filter for products to be listed.
                                                                    </div>`);
                                                                }else{
                                                                    modalBody.append(`
                                                                    <div class="helperDialog">
                                                                        Specify <strong>Product Restrictions specific to ${displayName} </strong> in the section below. Expand the section and define which products you want to list on ${displayName}. By default all products will be listed based on your global product restriction settings, so this is an optional configuration if you need to only show certain products on ${displayName}.
                                                                    </div>`);
                                                                }

                                                                modalBody.append(`
                                                                    <div class="accordion-header" id="pr_header" style="margin-top:20px;cursor:pointer;" onclick="toggleAccordion('${target}-product-restrictions', this)">
                                                                        <i class="fas fa-plus accordion-toggle-icon"></i>${displayName} Product Restrictions
                                                                    </div>
                                                                    <div style="margin-top:20px;display:none;" id="${target}-product-restrictions">
                                                                        <div class="other-restrictions-header"><strong>${displayName} Product Restrictions</strong></div>
                                                                        <div id="product-restrictions-container"></div>
                                                                `);
                                                            }

                                                            if (['gunbroker'].includes(target)) {
                                                                modalBody.append(`
                                                                    <div class="helperDialog" style="margin-top: 20px;">
                                                                        <strong>Gunbroker Shipping Profiles</strong> allow you to assign specific shipping profile IDs to different product groups. Each shipping profile can have its own set of product restrictions. If you do not use Gunbroker Shipping profiles, FFL Cockpit will use the default Distributor shipping costs defined in the Advanced tab under each distributor. Any changes to shipping profiles will only get applied to new listings. <a target="_new" href="https://support.gunbroker.com/hc/en-us/articles/223762568-Creating-and-Testing-Shipping-Profiles">How to created Gunbroker Shipping Profiles</a>
                                                                    </div>
                                                                    <div class="accordion-header" id="sp_header" style="margin-top:20px;cursor:pointer;" onclick="toggleAccordion('${target}-shipping-profiles', this)">
                                                                        <i class="fas fa-plus accordion-toggle-icon"></i>Gunbroker Shipping Profiles
                                                                    </div>
                                                                    <div style="margin-top:20px;display:none;" id="${target}-shipping-profiles">
                                                                        <div class="other-restrictions-header"><strong>Shipping Profiles Configuration</strong></div>
                                                                        <div id="shipping-profile-container-${target}"></div>
                                                                        <div class="add-item-container" style="margin-top: 15px;">
                                                                            <span class="add-group" onclick="addShippingProfile('${target}', null, null, true)">Add Shipping Profile</span>
                                                                        </div>
                                                                    </div>
                                                                    <button class="btn btn-primary" style="margin-top:50px;" id="delete_gunbroker_listings_button" onclick="remove_all_cockpit_gunbroker_listings()">Delete all FFL Cockpit-Generated Gunbroker Listings</button>
                                                                `);
                                                            }

                                                            // automatically open product restrictions for certain targets
                                                            if (['wikiarms', 'gun.deals', 'gunammo.deals', 'ammoseek', 'dudedeals', 'ammohunter', 'ammobuy', 'caliberking', 'ammobrowser', 'armsagora', 'gunfeed', 'gunmade', 'bulletscout'].includes(target)) {
                                                                document.getElementById('pr_header').click();
                                                            }
                                                           
                                                            const product_restrictions_container = document.getElementById('product-restrictions-container');
                                                            
                                                            if (['gunbroker', 'woo', 'odoo', 'bigcommerce', 'liberty_gun_trader'].includes(target)) {
                                                                // Product Restrictions Container for this target 
                                                                const productRestrictionsContainer = document.createElement('div');
                                                                productRestrictionsContainer.innerHTML = `
                                                                    <div style="margin-top:20px;" class="restriction-section">
                                                                        <!-- Legacy Conversion Notice -->
                                                                        <div id="target-legacy-conversion-notice-${target}" class="legacy-conversion-notice" style="display: none;">
                                                                            <div style="padding: 16px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 4px; margin-bottom: 16px;">
                                                                                <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
                                                                                    <i class="fas fa-exclamation-triangle" style="color: #856404; font-size: 18px;"></i>
                                                                                    <div>
                                                                                        <div style="font-weight: bold; color: #856404; margin-bottom: 4px;">Legacy Product Restrictions Detected</div>
                                                                                        <span style="color: #856404; font-size: 13px;">Convert them to the new Product Groups system for better management.</span>
                                                                                    </div>
                                                                                </div>
                                                                                <div style="display: flex; gap: 8px; justify-content: flex-start;">
                                                                                    <button type="button" onclick="convertTargetLegacyRestrictions('${target}'); return false;" class="btn btn-warning btn-sm">
                                                                                        <i class="fas fa-sync-alt"></i> Convert to New Format
                                                                                    </button>
                                                                                    <button type="button" onclick="dismissTargetLegacyNotice('${target}'); return false;" class="btn btn-outline-secondary btn-sm">
                                                                                        Continue with Legacy Format
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        <!-- New Product Groups Interface -->
                                                                        <div id="target-product-groups-section-${target}">
                                                                            <div style="margin-top:20px;" class="restriction-section">
                                                                                <div class="other-restrictions-header">Product Groups</div>
                                                                                <div id="target-product-groups-container-${target}" class="product-groups-container">
                                                                                    <!-- Product groups will be dynamically added here -->
                                                                                </div>
                                                                                <div class="add-group-container" style="margin-top: 15px;">
                                                                                    <button type="button" class="btn btn-primary" onclick="addTargetProductGroup('${target}')">
                                                                                        <i class="fas fa-plus"></i> Add Product Group
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        ${target === 'woo' ? `
                                                                        <!-- Import Out of Stock UPCs -->
                                                                        <div style="margin-top:20px;" class="restriction-section">
                                                                            <div class="other-restrictions-header">Import Out of Stock Products</div>
                                                                            <div style="padding:12px;">
                                                                                <div class="helperDialog" style="margin-bottom:12px;">
                                                                                    Products matching these UPCs will be imported even when they are out of stock at all distributors. This is useful for products you always want listed on your site regardless of current inventory availability.
                                                                                </div>
                                                                                <div class="form-row">
                                                                                    <label>UPC:</label>
                                                                                    <div class="field-container">
                                                                                        <div class="selected-items" id="import-out-of-stock-upc-include"></div>
                                                                                        <div class="add-item-container">
                                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'upc', 'import-out-of-stock-upc-include')">Add</span>&nbsp;|&nbsp;
                                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('import-out-of-stock-upc-include'))">Remove All</span>
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        ` : ''}

                                                                        <!-- Legacy container -->
                                                                        <div id="legacy-target-product-restrictions-container-${target}" style="display: none;"></div>
                                                                    </div>
                                                                `;
                                                                product_restrictions_container.appendChild(productRestrictionsContainer);

                                                                // Analytics Tag Mapping (woo only) — standalone collapsible section, outside Product Restrictions.
                                                                if (target === 'woo') {
                                                                    const analyticsSectionOptions = GFFC_ANALYTICS_SECTIONS
                                                                        .map(s => `<option value="${s.key}">${s.label}</option>`)
                                                                        .join('');
                                                                    modalBody.append(`
                                                                        <div class="helperDialog" style="margin-top: 20px;">
                                                                            <strong>Analytics Tag Mapping</strong> turns Analytics dashboard sections (Top Products, Trending, On Sale, New Arrivals) into WooCommerce product tags you can use for storefront sections, filters, and merchandising. Pick a section, click <em>Add</em>, then set a tag name, lookback window, and the Product Classes and/or Categories that scope it. Multiple tags per section are supported (e.g. "Trending Firearms" vs. "Trending Scopes"). A scheduled audit keeps each tag in sync &mdash; applying it to products that currently qualify and removing it from ones that no longer do. Each entry needs a tag name and at least one Product Class or Category.
                                                                        </div>
                                                                        <div class="accordion-header" id="atag_header" style="margin-top:20px;cursor:pointer;" onclick="toggleAccordion('${target}-analytics-tag-mapping', this)">
                                                                            <i class="fas fa-plus accordion-toggle-icon"></i>Analytics Tag Mapping
                                                                        </div>
                                                                        <div style="margin-top:20px;display:none;" id="${target}-analytics-tag-mapping">
                                                                            <div class="other-restrictions-header" style="display:flex; justify-content:space-between; align-items:center; gap:12px;">
                                                                                <strong style="white-space:nowrap;">Analytics Tag Mapping</strong>
                                                                                <button type="button" class="btn btn-secondary btn-sm" id="analytics-tag-process-now-btn" onclick="gffcAnalyticsTagProcessNow()" title="Save your changes first, then run the audit immediately." style="white-space:nowrap; flex-shrink:0;"><i class="fas fa-play"></i> Process Now</button>
                                                                            </div>
                                                                            <div id="analytics-tag-process-status" style="font-size:12px; color:#475569; padding:6px 12px 0; min-height:1em;"></div>
                                                                            <div style="padding:12px;">
                                                                                <div class="form-row" style="display:flex; gap:8px; align-items:center;">
                                                                                    <label style="white-space:nowrap;">Analytics Section:</label>
                                                                                    <select id="analytics-tag-section-select" style="flex:1; padding:6px 10px; border:1px solid #cbd5e1; border-radius:4px;">
                                                                                        <option value="">Select an Analytics section…</option>
                                                                                        ${analyticsSectionOptions}
                                                                                    </select>
                                                                                    <button type="button" class="btn btn-primary" onclick="gffcAnalyticsTagAddFromSelect()"><i class="fas fa-plus"></i> Add</button>
                                                                                </div>
                                                                                <div id="analytics-tag-empty" class="helperDialog" style="margin-top:12px; display:none;">No analytics tags configured yet. Pick a section above and click <em>Add</em> to create one.</div>
                                                                                <div id="analytics-tag-list" style="margin-top:8px;"></div>
                                                                            </div>
                                                                        </div>
                                                                    `);
                                                                }

                                                                // Initialize target configuration using the same pattern as distributors
                                                                const config = editor.get();

                                                                // Prevent duplicate initialization
                                                                if (window.targetInitialized && window.targetInitialized[target]) {
                                                                    return;
                                                                }
                                                                
                                                                if (!window.targetInitialized) {
                                                                    window.targetInitialized = {};
                                                                }
                                                                window.targetInitialized[target] = true;
                                                                
                                                                const waitForTargetContainer = () => {
                                                                    const container = document.getElementById(`legacy-target-product-restrictions-container-${target}`);
                                                                    if (!container) {
                                                                        // Container not ready yet, wait a bit and try again
                                                                        setTimeout(waitForTargetContainer, 100);
                                                                        return;
                                                                    }
                                                                    
                                                                    // Container is ready, proceed with initialization
                                                                    // Check if we have legacy format restrictions for this target
                                                                    if (hasTargetLegacyRestrictions(config, target)) {
                                                                        showTargetLegacyConversionNotice(target);
                                                                        createTargetLegacyInterface(target);
                                                                        hideTargetProductGroupsSection(target);
                                                                    } else {
                                                                        // Load existing product groups (read-only) - do not initialize empty structure
                                                                        loadTargetProductGroups(target);
                                                                        showTargetProductGroupsSection(target);
                                                                    }

                                                                    // Load import_out_of_stock UPCs for woo target
                                                                    if (target === 'woo') {
                                                                        var oosContainer = document.getElementById('import-out-of-stock-upc-include');
                                                                        if (oosContainer) {
                                                                            var oosConfig = config.targets && config.targets.woo && config.targets.woo.import_out_of_stock_product;
                                                                            var oosUpcs = (oosConfig && oosConfig.upc && oosConfig.upc.include) ? oosConfig.upc.include : [];
                                                                            if (oosUpcs.length > 0) {
                                                                                addSelectedItemsToContainer(oosContainer, oosUpcs);
                                                                            }
                                                                        }

                                                                        // Load analytics tag mapping (multi-entry per section)
                                                                        gffcAnalyticsTagsLoadFromConfig();
                                                                        gffcAnalyticsTagsRenderAll();
                                                                    }
                                                                };

                                                                // Start waiting for container
                                                                waitForTargetContainer();
                                                            } else if (['gun.deals', 'gunammo.deals', 'wikiarms', 'ammobrowser', 'ammohunter', 'ammobuy', 'ammoseek', 'dudedeals', 'caliberking','armsagora', 'gunfeed', 'gunmade', 'bulletscout'].includes(target)) {
                                                                var rss_field_categories = {
                                                                    "wikiarms": ["guns","brass","powder","bullets","primers","magazines","ammunition","reloading_misc"],
                                                                    "ammoseek": ["guns","brass","powder","bullets","primers","magazines","ammunition"],
                                                                    "dudedeals": ["guns","brass","powder","bullets","primers","magazines","ammunition"],
                                                                    "ammohunter": ["guns","brass","powder","bullets","primers","magazines","ammunition"],
                                                                    "ammobuy": ["ammunition", "magazines"],
                                                                    "caliberking": ["guns","brass","powder","bullets","primers","magazines","ammunition"],
                                                                    "ammobrowser": ["guns","brass","powder","bullets","primers","magazines","ammunition"],
                                                                    "gun.deals": ["guns","brass","other","parts","bullets","primers","reloading","ammunition"],
                                                                    "gunammo.deals": ["guns","parts", "ammunition","reloading","other"],
                                                                    "gunmade": ["guns","ammunition","accessories","nfa","knives","archery"],
                                                                    "armsagora": ["guns","brass","other","parts","bullets","primers","reloading","ammunition"],
                                                                    "gunfeed": ["guns","brass","other","parts","bullets","primers","reloading","ammunition"],
                                                                    "bulletscout": ["ammunition"]
                                                                }
                                                                const restrictions = [
                                                                    {"field": "category", "modal": "categoryModal", "name": "Categories", "select_text": "Select Categories"},
                                                                    {"field": "sku", "modal": "prompt", "name": "SKU", "select_text": "Add SKU"}
                                                                ];
                                                                
                                                                rss_field_categories[target].forEach(product_type => {
                                                                    const section = document.createElement('div');
                                                                    section.className = 'restriction-section';
                                                                    
                                                                    const header = document.createElement('div');
                                                                    header.className = 'g-ffl-restriction-header';
                                                                    header.innerHTML = `<strong>${product_type}</strong>`;
                                                                    section.appendChild(header);

                                                                    const container = document.createElement('div');
                                                                    container.className = 'restriction-container';

                                                                    const categoryDiv = document.createElement('div');
                                                                    categoryDiv.className = 'restriction-item';
                                                                    
                                                                    var launcher_category = `openModal('categoryModal', 'targets-${target}-listed_products-${product_type}-category-include')`;
                                                                    var launcher_sku = `promptAndAddItems(this, 'sku', 'targets-${target}-listed_products-${product_type}-sku-include')`;
                                                                        
                                                                    categoryDiv.innerHTML = `
                                                                        <label for="product_class">Categories:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="targets-${target}-listed_products-${product_type}-category-include"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="${launcher_category}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-listed_products-${product_type}-category-include'))">Remove All</span>
                                                                            </div>
                                                                        </div>`;
                                                                    container.appendChild(categoryDiv);

                                                                    const skuDiv = document.createElement('div');
                                                                    skuDiv.className = 'restriction-item';
                                                                    skuDiv.innerHTML = `
                                                                        <label for="product_class">SKU's:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="targets-${target}-listed_products-${product_type}-sku-include"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="${launcher_sku}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-listed_products-${product_type}-sku-include'))">Remove All</span>
                                                                            </div>
                                                                        </div>`;
                                                                    container.appendChild(skuDiv);

                                                                    section.appendChild(container);
                                                                    product_restrictions_container.appendChild(section);

                                                                    // Now load the data with existing values
                                                                    const restrictions_types = ["category","sku"];
                                                                    var config = editor.get();
                                                                    restrictions_types.forEach(restriction_type => {
                                                                        const selectedFilterContainer = document.getElementById(`targets-${target}-listed_products-${product_type}-${restriction_type}-include`);
                                                                        if (selectedFilterContainer != null) {
                                                                            selectedFilterContainer.replaceChildren();
                                                                            if (config.targets?.[target]?.listed_products?.[product_type]?.[restriction_type]?.['include']) {
                                                                                addSelectedItemsToContainer(selectedFilterContainer, config.targets[target].listed_products[product_type][restriction_type]['include']);
                                                                            }
                                                                        }
                                                                    });
                                                                  
                                                                });


                                                            }

                                                            // Add WooCommerce shipping classes section
                                                            if (['woo'].includes(target)) {
                                                                modalBody.append(`
                                                                    <div class="helperDialog" style="margin-top: 20px;">
                                                                        <strong>Custom WooCommerce Shipping Classes</strong> allow you to create custom shipping classes to apply to different product groups. FFL Cockpit will already create a free shipping, and firearms and non-firearms shipping class for each distributor you have configured. You would only need to add new shipping classes here if those defaults are not sufficient for your needs. Once products are updated with your customized shipping classes, you must assign a cost for each Shipping Class in the WooCommerce Shipping Configuration panel. This <a target="_new" href="https://fflcockpit.com/shipping-setup/">Shipping Setup Help Center Article</a> will guide you through how to do that.
                                                                    </div>
                                                                    <div class="accordion-header" id="sc_header" style="margin-top:20px;cursor:pointer;" onclick="toggleAccordion('${target}-shipping-classes', this)">
                                                                        <i class="fas fa-plus accordion-toggle-icon"></i>WooCommerce Shipping Classes
                                                                    </div>
                                                                    <div style="margin-top:20px;display:none;" id="${target}-shipping-classes">
                                                                        <div class="other-restrictions-header"><strong>Shipping Classes Configuration</strong></div>
                                                                        <div id="shipping-class-container-${target}"></div>
                                                                        <div class="add-item-container" style="margin-top: 15px;">
                                                                            <span class="add-group" onclick="addShippingClass('${target}', null, null, true)">Add Shipping Class</span>
                                                                        </div>
                                                                    </div>
                                                                `);
                                                            }
                                                            
                                                            // Load existing shipping profiles for gunbroker
                                                            if (['gunbroker'].includes(target)) {
                                                                const config = editor.get();
                                                                if (config.targets[target].shipping_profiles) {
                                                                    for (const profileName in config.targets[target].shipping_profiles) {
                                                                        addShippingProfile(target, profileName, config.targets[target].shipping_profiles[profileName], false);
                                                                    }
                                                                }
                                                            }

                                                            // Load existing shipping classes for WooCommerce
                                                            if (['woo'].includes(target)) {
                                                                const config = editor.get();
                                                                if (config.targets[target].shipping_classes) {
                                                                    for (const className in config.targets[target].shipping_classes) {
                                                                        addShippingClass(target, className, config.targets[target].shipping_classes[className], false);
                                                                    }
                                                                }
                                                            }
                                                            
                                                            setupAutoSave();
                                                            $('#detailsModal').modal('show');
                                                        }

                                                        function viewDistributorDetails(distributor, distributorId) {
                                                            const distributorDetails = JSON.parse(distributorsSchema[distributor].ui_field_schema);
                                                            $('#detailsModalLabel').text(`${distributor}`);
                                                            const modalBody = $('#modal-body');
                                                            modalBody.empty();
                                                            cc = editor.get();
                                                            
                                                            for (let key in distributorDetails) {
                                                                const field = distributorDetails[key];
                                                                const field_key = "distributors-" + distributor + "-" + field.config_key;
                                                                if (field.helperText){
                                                                    modalBody.append(`
                                                                    <div class="helperDialog">
                                                                        ${field.helperText}
                                                                    </div>
                                                                    `);
                                                                }
                                                                if (field.type == "array"){
                                                                    modalBody.append(`
                                                                    <label for="${field_key}">${field.label}:</label>
                                                                    <div class="field-container" style="padding-bottom:5px;margin-bottom:20px;border-bottom:solid #ccc 1px;">
                                                                        <div class="selected-items" id="${field_key}"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'email', '${field_key}')">Add Email</span>
                                                                        </div>
                                                                    </div>`);
                                                                    addSelectedItemsToContainer(document.getElementById(field_key), getConfigValue(cc, field_key));

                                                                } else if (field.type == "state-selector"){
                                                                    modalBody.append(`
                                                                        <div class="form-group">
                                                                            <label for="${field_key}">${field.label}</label>
                                                                            <select class="form-control" name="${field_key}" id="${field_key}" data-autosave="true"></select>
                                                                        </div>
                                                                    `);

                                                                    const selectedState = getConfigValue(cc, field_key);
                                                                    const dropdown = document.getElementById(field_key);
                                                                    statesAndTerritories.forEach(state => {
                                                                        const option = document.createElement('option');
                                                                        option.value = state.value;
                                                                        option.textContent = state.text;
                                                                        if (selectedState == state.value) {
                                                                            option.selected = true;
                                                                        }
                                                                        dropdown.appendChild(option);
                                                                    });

                                                                    addSelectedItemsToContainer(document.getElementById(field_key), getConfigValue(cc, field_key));

                                                                }else{
                                                                    modalBody.append(`<div class="form-group">
                                                                                        <label for="${field_key}">${field.label}</label>
                                                                                        <input type="${field.type}" class="form-control" name="${field_key}" id="${field_key}" value="${getConfigValue(cc, field_key)}" data-autosave="true">
                                                                                    </div>`);
                                                                }
        
                                                            }

                                                            modalBody.append(`
                                                                <div class="helperDialog">
                                                                    Specify <strong>Product Restrictions specific to ${distributor} </strong> in the section below. Expand the section and define which products you want to pull in from ${distributor}. By default all products will come through based on your global product restriction settings, so this is an optional configuration if you need to only pull certain products from ${distributor}.
                                                                </div>
                                                                <div class="accordion-header" style="margin-top:20px;cursor:pointer;" onclick="toggleAccordion('${distributor}-product-restrictions', this)">
                                                                    <i class="fas fa-plus accordion-toggle-icon"></i>${distributor} Product Restrictions
                                                                </div>
                                                                <div style="margin-top:20px;display:none;" id="${distributor}-product-restrictions">
                                                                    <div class="other-restrictions-header"><strong>${distributor} Product Restrictions</strong></div>
                                                                    <div style="margin-top:20px;" class="restriction-section">
                                                                        <div class="other-restrictions-header">List only products eligible for dropshipping</strong></div>
                                                                        <div class="helperDialog">
                                                                            If this is toggled on, only products elgible for dropshipping will be listed. If it's off, all items from the Distributor (whether or not they are elgible for dropshipping) will be listed
                                                                        </div>
                                                                        <div style="width:!00%;text-align:center;">
                                                                            <label for="sell_at_map">List only products eligible for dropshipping:&nbsp;</label>
                                                                            <label class="toggle-switch">
                                                                                <input type="checkbox" id="distributors-${distributor}-drop_ship_only_items" name="distributors-${distributor}-drop_ship_only_items" ${getConfigValue(cc, "distributors-" + distributor + "-drop_ship_only_items") ? 'checked' : ''}  data-autosave="true">
                                                                                <span class="slider"></span>
                                                                            </label>
                                                                        </div>
                                                                    </div>
                                                                    <div style="margin-top:20px;" class="restriction-section">
                                                                        <div class="other-restrictions-header">Product Cost Retrictions</strong></div>
                                                                        <div class="helperDialog">
                                                                            Some distributors have handling fees for orders below a certain amount. These cost controls give you the ability to set a minimum cost for items listed on your site from ${distributor}
                                                                        </div>
                                                                        <div class="cost-restrictions">
                                                                            <div class="cost-field">
                                                                                <label for="distributors-${distributor}-product_restrictions-cost-global_restrictions-min_distributor_cost">Min Cost:&nbsp;</label>
                                                                                <input class="form-control" type="number" id="distributors-${distributor}-product_restrictions-cost-global_restrictions-min_distributor_cost" name="distributors-${distributor}-product_restrictions-cost-global_restrictions-min_distributor_cost" data-autosave="true" value="${getConfigValue(cc, "distributors-" + distributor + "-product_restrictions-cost-global_restrictions-min_distributor_cost")}">
                                                                            </div>
                                                                            <div class="cost-field"> 
                                                                                <label for="distributors-${distributor}-product_restrictions-cost-global_restrictions-max_distributor_cost">Max Cost:</label>
                                                                                <input class="form-control" type="number" id="distributors-${distributor}-product_restrictions-cost-global_restrictions-max_distributor_cost" name="distributors-${distributor}-product_restrictions-cost-global_restrictions-max_distributor_cost" data-autosave="true" value="${getConfigValue(cc, "distributors-" + distributor + "-product_restrictions-cost-global_restrictions-max_distributor_cost")}">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <div id="distributor-product-restrictions-container">
                                                                        <!-- Legacy Format Detection and Conversion for Distributors -->
                                                                        <div id="distributor-legacy-conversion-notice-${distributor}" style="display: none; background: #fff3cd; border: 1px solid #ffeaa7; padding: 12px 15px; margin-bottom: 15px; border-radius: 4px;">
                                                                            <!-- Text Section -->
                                                                            <div style="margin-bottom: 12px;">
                                                                                <div style="display: flex; align-items: flex-start; margin-bottom: 8px;">
                                                                                    <i class="fas fa-exclamation-triangle" style="color: #856404; margin-right: 8px; margin-top: 2px; flex-shrink: 0;"></i>
                                                                                    <strong style="color: #856404;">Legacy ${distributor} Product Restrictions Detected</strong>
                                                                                </div>
                                                                                <div style="color: #856404; font-size: 13px; margin-left: 24px;">
                                                                                    Convert them to the new Product Groups system for better management.
                                                                                </div>
                                                                            </div>
                                                                            <!-- Button Section -->
                                                                            <div style="display: flex; gap: 8px; align-items: flex-start;">
                                                                                <button type="button" onclick="convertDistributorLegacyRestrictions('${distributor}')" class="btn btn-warning btn-sm">
                                                                                    <i class="fas fa-sync-alt"></i> Convert to New Format
                                                                                </button>
                                                                                <button type="button" onclick="dismissDistributorLegacyNotice('${distributor}')" class="btn btn-outline-secondary btn-sm">
                                                                                    Continue with Legacy Format
                                                                                </button>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        <!-- New Product Groups Interface -->
                                                                        <div id="distributor-product-groups-section-${distributor}">
                                                                            <div style="margin-top:20px;" class="restriction-section">
                                                                                <div class="other-restrictions-header">Product Groups</div>
                                                                                <div id="distributor-product-groups-container-${distributor}" class="product-groups-container">
                                                                                    <!-- Product groups will be dynamically added here -->
                                                                                </div>
                                                                                <div class="add-group-container" style="margin-top: 15px;">
                                                                                    <button type="button" class="btn btn-primary" onclick="addDistributorProductGroup('${distributor}')">
                                                                                        <i class="fas fa-plus"></i> Add Product Group
                                                                                    </button>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        
                                                                        <!-- Legacy container -->
                                                                        <div id="legacy-distributor-product-restrictions-container-${distributor}" style="display: none;"></div>
                                                                    </div>
                                                            `);
                                                            
                                                            // Initialize distributor product restrictions with a small delay to ensure DOM is ready
                                                            setTimeout(() => {
                                                                initializeDistributorProductRestrictions(distributor);
                                                            }, 100);
                                                            
                                                            setupAutoSave();
                                                            $('#detailsModal').modal('show');
                                                        }
                                                        
                                                        // Initialize distributor product restrictions
                                                        function initializeDistributorProductRestrictions(distributor) {
                                                            const config = editor.get();
                                                            
                                                            // Wait for the container to be available before proceeding
                                                            const waitForContainer = () => {
                                                                const container = document.getElementById(`distributor-product-groups-container-${distributor}`);
                                                                if (!container) {
                                                                    // Container not ready yet, wait a bit and try again
                                                                    setTimeout(waitForContainer, 100);
                                                                    return;
                                                                }
                                                                
                                                                // Container is ready, proceed with initialization
                                                                // Check if we have legacy format restrictions for this distributor
                                                                if (hasDistributorLegacyRestrictions(config, distributor)) {
                                                                    showDistributorLegacyConversionNotice(distributor);
                                                                    createDistributorLegacyInterface(distributor);
                                                                    hideDistributorProductGroupsSection(distributor);
                                                                } else {
                                                                    // Load existing product groups or initialize empty
                                                                    loadDistributorProductGroups(config, distributor);
                                                                    showDistributorProductGroupsSection(distributor);
                                                                }
                                                            };
                                                            
                                                            // Start waiting for container
                                                            waitForContainer();
                                                        }
                                                        
                                                        function hasDistributorLegacyRestrictions(config, distributor) {
                                                            if (!config.distributors || !config.distributors[distributor] || !config.distributors[distributor].product_restrictions) return false;
                                                            
                                                            const restrictions = config.distributors[distributor].product_restrictions;
                                                            const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                            return legacyFields.some(field => {
                                                                const restriction = restrictions[field];
                                                                return restriction && (
                                                                    (restriction.include && restriction.include.length > 0) ||
                                                                    (restriction.exclude && restriction.exclude.length > 0)
                                                                );
                                                            });
                                                        }
                                                        
                                                        function showDistributorLegacyConversionNotice(distributor) {
                                                            const conversionNotice = document.getElementById(`distributor-legacy-conversion-notice-${distributor}`);
                                                            const legacyContainer = document.getElementById(`legacy-distributor-product-restrictions-container-${distributor}`);
                                                            
                                                            if (conversionNotice) {
                                                                conversionNotice.style.display = 'block';
                                                            }
                                                            if (legacyContainer) {
                                                                legacyContainer.style.display = 'block';
                                                            }
                                                        }
                                                        
                                                        function dismissDistributorLegacyNotice(distributor) {
                                                            const conversionNotice = document.getElementById(`distributor-legacy-conversion-notice-${distributor}`);
                                                            if (conversionNotice) {
                                                                conversionNotice.style.display = 'none';
                                                            }
                                                        }
                                                        
                                                        function createDistributorLegacyInterface(distributor) {
                                                            const product_restrictions_container = document.getElementById(`legacy-distributor-product-restrictions-container-${distributor}`);
                                                            
                                                            // Return early if container doesn't exist
                                                            if (!product_restrictions_container) {
                                                                console.warn(`Legacy distributor container for ${distributor} not found`);
                                                                return;
                                                            }
                                                            
                                                            const restrictions = [
                                                                {"field": "product_class", "modal": "productClassModal", "name": "Product Classes", "select_text": "Select Product Classes"},
                                                                {"field": "category", "modal": "categoryModal", "name": "Categories", "select_text": "Select Categories"},
                                                                {"field": "brand", "modal": "brandModal", "name": "Brands", "select_text": "Select Brands"},
                                                                {"field": "sku", "modal": "prompt", "name": "SKU", "select_text": "Add SKU"},
                                                                {"field": "upc", "modal": "prompt", "name": "UPC", "select_text": "Add UPC"} 
                                                            ];

                                                            restrictions.forEach(restriction => {
                                                                const section = document.createElement('div');
                                                                section.className = 'restriction-section';
                                                                
                                                                const header = document.createElement('div');
                                                                header.className = 'g-ffl-restriction-header';
                                                                header.innerHTML = `<strong>${restriction.name}</strong>`;
                                                                section.appendChild(header);

                                                                const container = document.createElement('div');
                                                                container.className = 'restriction-container';

                                                                const includeDiv = document.createElement('div');
                                                                includeDiv.className = 'restriction-item';
                                                                
                                                                var launcher_include = `openModal('${restriction.modal}', 'distributors-${distributor}-product_restrictions-${restriction.field}-include')`;
                                                                var launcher_exclude = `openModal('${restriction.modal}', 'distributors-${distributor}-product_restrictions-${restriction.field}-exclude')`;
                                                                if (restriction.modal == "prompt"){
                                                                    launcher_include = `promptAndAddItems(this, '${restriction.field}', 'distributors-${distributor}-product_restrictions-${restriction.field}-include')`;
                                                                    launcher_exclude = `promptAndAddItems(this, '${restriction.field}', 'distributors-${distributor}-product_restrictions-${restriction.field}-exclude')`;
                                                                }
                                                                includeDiv.innerHTML = `
                                                                    <label for="product_class">Include - <span style="font-size:9pt !important;">
                                                                        <span id="distributors-${distributor}-product_restrictions-${restriction.field}-and-option" onclick="toggleOperandOption('distributors-${distributor}-product_restrictions-${restriction.field}', 'AND', true)">AND</span> | 
                                                                        <span id="distributors-${distributor}-product_restrictions-${restriction.field}-or-option" onclick="toggleOperandOption('distributors-${distributor}-product_restrictions-${restriction.field}', 'OR', true)">OR</span></span>:
                                                                    </label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="distributors-${distributor}-product_restrictions-${restriction.field}-include"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="${launcher_include}">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributors-${distributor}-product_restrictions-${restriction.field}-include'))">Remove All</span>
                                                                        </div>
                                                                    </div>`;
                                                                container.appendChild(includeDiv);

                                                                const excludeDiv = document.createElement('div');
                                                                excludeDiv.className = 'restriction-item';
                                                                excludeDiv.innerHTML = `
                                                                    <label for="product_class">Exclude:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="distributors-${distributor}-product_restrictions-${restriction.field}-exclude"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="${launcher_exclude}">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributors-${distributor}-product_restrictions-${restriction.field}-exclude'))">Remove All</span>
                                                                        </div>
                                                                    </div>`;
                                                                container.appendChild(excludeDiv);
                                                                section.appendChild(container);
                                                                product_restrictions_container.appendChild(section);

                                                                // Now load the data with existing values
                                                                var config = editor.get();
                                                                if (config.distributors[distributor].product_restrictions[restriction.field] && config.distributors[distributor].product_restrictions[restriction.field]['include_operand']){
                                                                    toggleOperandOption(`distributors-${distributor}-product_restrictions-${restriction.field}`, config.distributors[distributor].product_restrictions[restriction.field].include_operand);
                                                                }else{
                                                                    toggleOperandOption(`distributors-${distributor}-product_restrictions-${restriction.field}`, "AND");
                                                                }
                                                                
                                                                const include_excludes = ["include","exclude"];
                                                                include_excludes.forEach(include_exclude => {
                                                                    const selectedFilterContainer = document.getElementById(`distributors-${distributor}-product_restrictions-${restriction.field}-${include_exclude}`);
                                                                    if (selectedFilterContainer != null) {
                                                                        selectedFilterContainer.replaceChildren();
                                                                        if (config.distributors?.[distributor]?.product_restrictions?.[restriction.field]?.[include_exclude]) {
                                                                            addSelectedItemsToContainer(selectedFilterContainer, config.distributors[distributor].product_restrictions[restriction.field][include_exclude]);
                                                                        }
                                                                    }
                                                                });
                                                            });
                                                        }
                                                        
                                                        // Convert legacy distributor restrictions to product groups
                                                        function convertDistributorLegacyRestrictions(distributor) {
                                                            const config = editor.get();
                                                            
                                                            if (!config.distributors[distributor].product_restrictions.product_groups) {
                                                                config.distributors[distributor].product_restrictions.product_groups = [];
                                                            }
                                                            
                                                            const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                            
                                                            // First, collect all include groups
                                                            legacyFields.forEach(field => {
                                                                const restriction = config.distributors[distributor].product_restrictions[field];
                                                                if (!restriction) return;
                                                                
                                                                // Create include group if there are include items
                                                                if (restriction.include && restriction.include.length > 0) {
                                                                    // Create a descriptive name based on the values
                                                                    let descriptiveName = '';
                                                                    const values = restriction.include;
                                                                    const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                    
                                                                    if (values.length === 1) {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values[0]}`;
                                                                    } else if (values.length <= 3) {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values.join(', ')}`;
                                                                    } else {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                    }
                                                                    
                                                                    const includeGroup = {
                                                                        id: `distributor_${distributor}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                        name: descriptiveName,
                                                                        type: 'include',
                                                                        criteria: {
                                                                            [field]: restriction.include
                                                                        }
                                                                    };
                                                                    config.distributors[distributor].product_restrictions.product_groups.push(includeGroup);
                                                                }
                                                            });
                                                            
                                                            // Then, collect all exclude groups
                                                            legacyFields.forEach(field => {
                                                                const restriction = config.distributors[distributor].product_restrictions[field];
                                                                if (!restriction) return;
                                                                
                                                                // Create exclude group if there are exclude items
                                                                if (restriction.exclude && restriction.exclude.length > 0) {
                                                                    // Create a descriptive name based on the values
                                                                    let descriptiveName = '';
                                                                    const values = restriction.exclude;
                                                                    const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                    
                                                                    if (values.length === 1) {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values[0]}`;
                                                                    } else if (values.length <= 3) {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values.join(', ')}`;
                                                                    } else {
                                                                        descriptiveName = `${distributor} ${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                    }
                                                                    
                                                                    const excludeGroup = {
                                                                        id: `distributor_${distributor}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                        name: descriptiveName,
                                                                        type: 'exclude',
                                                                        criteria: {
                                                                            [field]: restriction.exclude
                                                                        }
                                                                    };
                                                                    config.distributors[distributor].product_restrictions.product_groups.push(excludeGroup);
                                                                }
                                                            });
                                                            
                                                            // Clear the legacy fields
                                                            legacyFields.forEach(field => {
                                                                delete config.distributors[distributor].product_restrictions[field];
                                                            });
                                                            
                                                            // Update the configuration
                                                            editor.set(config);
                                                            
                                                            // Hide legacy notice and container
                                                            document.getElementById(`distributor-legacy-conversion-notice-${distributor}`).style.display = 'none';
                                                            document.getElementById(`legacy-distributor-product-restrictions-container-${distributor}`).style.display = 'none';
                                                            
                                                            // Show Product Groups section and load the new product groups interface
                                                            showDistributorProductGroupsSection(distributor);
                                                            loadDistributorProductGroups(config, distributor);
                                                            
                                                            alert(`Legacy restrictions for ${distributor} have been successfully converted to Product Groups, please review for accuracy before Savings changes. To revert, refresh your browser.!`);
                                                        }
                                                        
                                                        function hideDistributorProductGroupsSection(distributor) {
                                                            const section = document.getElementById(`distributor-product-groups-section-${distributor}`);
                                                            if (section) {
                                                                section.style.display = 'none';
                                                            }
                                                        }
                                                        
                                                        function showDistributorProductGroupsSection(distributor) {
                                                            const section = document.getElementById(`distributor-product-groups-section-${distributor}`);
                                                            if (section) {
                                                                section.style.display = 'block';
                                                            }
                                                        }
                                                        
                                                        // Load existing distributor product groups
                                                        function loadDistributorProductGroups(config, distributor) {
                                                            const container = document.getElementById(`distributor-product-groups-container-${distributor}`);
                                                            
                                                            // Return early if container doesn't exist yet
                                                            if (!container) {
                                                                console.warn(`Container distributor-product-groups-container-${distributor} not found. The modal may not be fully rendered yet.`);
                                                                return;
                                                            }
                                                            
                                                            container.innerHTML = ''; // Clear existing content
                                                            
                                                            const distributorConfig = config.distributors && config.distributors[distributor] && config.distributors[distributor].product_restrictions;
                                                            
                                                            if (distributorConfig && distributorConfig.product_groups && distributorConfig.product_groups.length > 0) {
                                                                distributorConfig.product_groups.forEach(group => {
                                                                    addDistributorProductGroup(distributor, group.name, group.type, group.criteria, group.id, false);
                                                                });
                                                            } else {
                                                                // Show empty state
                                                                const emptyState = document.createElement('div');
                                                                emptyState.className = 'empty-state';
                                                                emptyState.innerHTML = `
                                                                    <div style="text-align: center; padding: 30px; color: #666;">
                                                                        <i class="fas fa-layer-group" style="font-size: 36px; margin-bottom: 15px; opacity: 0.3;"></i>
                                                                        <h4 style="margin: 0 0 8px 0; color: #333;">No ${distributor} Product Groups</h4>
                                                                        <p style="margin: 0; font-size: 14px;">Create product groups to apply specific restrictions to ${distributor} products. <span style="color:blue;font-style:italic">If no product groups are created here, all products will flow through from the main product restriction settings.</span></p>
                                                                    </div>
                                                                `;
                                                                container.appendChild(emptyState);
                                                            }
                                                        }
                                                        
                                                        // Add distributor product group
                                                        function addDistributorProductGroup(distributor, groupName = null, groupType = null, criteria = null, groupId = null, isNew = true) {
                                                            if (isNew) {
                                                                groupName = prompt(`Enter a name for your ${distributor} product group:`);
                                                                if (!groupName) return;
                                                                
                                                                groupName = groupName.trim();
                                                                groupId = `distributor_${distributor}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                                groupType = 'include'; // Default to include
                                                                criteria = {};
                                                            }
                                                            
                                                            const container = document.getElementById(`distributor-product-groups-container-${distributor}`);
                                                            
                                                            // Remove empty state if it exists
                                                            const emptyState = container.querySelector('.empty-state');
                                                            if (emptyState) {
                                                                emptyState.remove();
                                                            }
                                                            
                                                            const div = document.createElement('div');
                                                            div.className = 'group-container product-group';
                                                            div.setAttribute('data-group-id', groupId);
                                                            
                                                            div.innerHTML = `
                                                                <div class="group-header">
                                                                    <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${groupId}', this)">
                                                                        <i class="fas fa-plus accordion-toggle-icon"></i>
                                                                        <span class="group-type-badge ${groupType}">${groupType.toUpperCase()}</span>
                                                                        <span style="display: flex; align-items: center;">
                                                                            <span class="group-name">${groupName}</span>
                                                                            <i class="fas fa-edit edit-group-name" title="Edit group name" onclick="event.stopPropagation(); editDistributorGroupName('${distributor}', '${groupId}', this.previousElementSibling)" style="margin-left: 6px; color: #6c757d; cursor: pointer; font-size: 11px;"></i>
                                                                        </span>
                                                                    </div>
                                                                    <div class="group-actions">
                                                                        <i class="fas fa-copy copy-link" title="Duplicate Product Group" onclick="duplicateDistributorProductGroup('${distributor}', '${groupId}')"></i>
                                                                        <i class="fas fa-trash-alt remove-link" title="Delete Product Group" onclick="removeDistributorProductGroup('${distributor}', '${groupId}')"></i>
                                                                    </div>
                                                                </div>
                                                                <div class="accordion-content" id="${groupId}" style="display: ${isNew ? 'block' : 'none'};">
                                                                    <div id="group-summary-${groupId}" style="margin-bottom:12px;padding:10px 12px;background:#f0f9ff;border:1px solid #bae6fd;border-radius:6px;font-size:12px;color:#0c4a6e;display:none;">
                                                                    </div>

                                                                    <!-- Group Type Selection -->
                                                                    <div class="form-row">
                                                                        <label>Group Type:</label>
                                                                        <div class="group-type-selector">
                                                                            <label class="radio-label">
                                                                                <input type="radio" name="group_type_${groupId}" value="include" ${groupType === 'include' ? 'checked' : ''}
                                                                                       onchange="updateDistributorGroupType('${distributor}', '${groupId}', 'include')">
                                                                                <span class="radio-custom include"></span>
                                                                                Include - Products matching this group will be included
                                                                            </label>
                                                                            <label class="radio-label">
                                                                                <input type="radio" name="group_type_${groupId}" value="exclude" ${groupType === 'exclude' ? 'checked' : ''}
                                                                                       onchange="updateDistributorGroupType('${distributor}', '${groupId}', 'exclude')">
                                                                                <span class="radio-custom exclude"></span>
                                                                                Exclude - Products matching this group will be excluded
                                                                            </label>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Product Class -->
                                                                    <div class="form-row">
                                                                        <label>Product Class:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="distributor_group_${groupId}_product_class"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="openModal('productClassModal', 'distributor_group_${groupId}_product_class')">Select</span>&nbsp;|&nbsp;
                                                                                <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributor_group_${groupId}_product_class'))">Remove All</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Category -->
                                                                    <div class="form-row">
                                                                        <label>Category:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="distributor_group_${groupId}_category"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="openModal('categoryModal', 'distributor_group_${groupId}_category')">Select</span>&nbsp;|&nbsp;
                                                                                <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributor_group_${groupId}_category'))">Remove All</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Brand -->
                                                                    <div class="form-row">
                                                                        <label>Brand:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="distributor_group_${groupId}_brand"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="openModal('brandModal', 'distributor_group_${groupId}_brand')">Select</span>&nbsp;|&nbsp;
                                                                                <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributor_group_${groupId}_brand'))">Remove All</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- SKU -->
                                                                    <div class="form-row">
                                                                        <label>SKU:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="distributor_group_${groupId}_sku"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="promptAndAddItems(this, 'sku', 'distributor_group_${groupId}_sku')">Add</span>&nbsp;|&nbsp;
                                                                                <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributor_group_${groupId}_sku'))">Remove All</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- UPC -->
                                                                    <div class="form-row">
                                                                        <label>UPC:</label>
                                                                        <div class="field-container">
                                                                            <div class="selected-items" id="distributor_group_${groupId}_upc"></div>
                                                                            <div class="add-item-container">
                                                                                <span class="add-item" onclick="promptAndAddItems(this, 'upc', 'distributor_group_${groupId}_upc')">Add</span>&nbsp;|&nbsp;
                                                                                <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('distributor_group_${groupId}_upc'))">Remove All</span>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Cost Range -->
                                                                    <div class="form-row">
                                                                        <label>Cost:</label>
                                                                        <div class="field-container">
                                                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                                                <div style="flex: 1;">
                                                                                    <label for="distributor_group_${groupId}_min_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Min ($):</label>
                                                                                    <input type="number" id="distributor_group_${groupId}_min_cost" class="form-control" 
                                                                                           placeholder="0.00" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateDistributorGroupCostRange('${distributor}', '${groupId}')">
                                                                                </div>
                                                                                <div style="flex: 1;">
                                                                                    <label for="distributor_group_${groupId}_max_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Max ($):</label>
                                                                                    <input type="number" id="distributor_group_${groupId}_max_cost" class="form-control" 
                                                                                           placeholder="999999.99" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateDistributorGroupCostRange('${distributor}', '${groupId}')">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    
                                                                    <!-- Min Quantity to List -->
                                                                    <div class="form-row" id="distributor_group_${groupId}_min_quantity_section" style="display: ${groupType === 'include' ? '' : 'none'};">
                                                                        <label>Min Qty to List:</label>
                                                                        <div class="field-container">
                                                                            <div style="display: flex; align-items: center; gap: 8px;">
                                                                                <div style="flex: 1;">
                                                                                    <input type="number" id="distributor_group_${groupId}_min_quantity_to_list" class="form-control" 
                                                                                           placeholder="1" min="1" step="1" value="1" style="width: 60px; font-size: 12px; padding: 4px;" 
                                                                                           onchange="updateDistributorGroupMinQuantityToList('${distributor}', '${groupId}')" data-autosave="true">
                                                                                    <div style="font-size: 11px; color: #666; margin-top: 2px;">
                                                                                        Minimum quantity required for products to be listed (minimum value: 1)
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            `;
                                                            
                                                            container.appendChild(div);

                                                            // Load existing criteria if provided
                                                            if (criteria) {
                                                                loadDistributorGroupCriteria(groupId, criteria);
                                                            }

                                                            // If new group, save it to config
                                                            if (isNew) {
                                                                saveDistributorProductGroupToConfig(distributor, groupId, groupName, groupType, {});
                                                                // Expand the new group
                                                                expandGroup(groupId, div);
                                                            }

                                                            // Set up MutationObserver for dynamic filter summary
                                                            var accContent = document.getElementById(groupId);
                                                            if (accContent) {
                                                                var obs = new MutationObserver(function() { updateGroupFilterSummary(groupId, 'distributor_group_' + groupId + '_'); });
                                                                obs.observe(accContent, { childList: true, subtree: true, characterData: true });
                                                                setTimeout(function() { updateGroupFilterSummary(groupId, 'distributor_group_' + groupId + '_'); }, 100);
                                                            }
                                                        }
                                                        
                                                        // Load criteria into a distributor group
                                                        function loadDistributorGroupCriteria(groupId, criteria) {
                                                            const fields = ['product_class', 'category', 'brand', 'sku', 'upc'];
                                                            
                                                            fields.forEach(field => {
                                                                if (criteria[field] && Array.isArray(criteria[field])) {
                                                                    const container = document.getElementById(`distributor_group_${groupId}_${field}`);
                                                                    if (container) {
                                                                        addSelectedItemsToContainer(container, criteria[field]);
                                                                    }
                                                                }
                                                            });
                                                            
                                                            // Load cost range if present
                                                            if (criteria.cost) {
                                                                if (criteria.cost.min_cost !== undefined) {
                                                                    document.getElementById(`distributor_group_${groupId}_min_cost`).value = criteria.cost.min_cost;
                                                                }
                                                                if (criteria.cost.max_cost !== undefined) {
                                                                    document.getElementById(`distributor_group_${groupId}_max_cost`).value = criteria.cost.max_cost;
                                                                }
                                                            }
                                                            
                                                            // Load min quantity to list if present
                                                            if (criteria.min_quantity_to_list !== undefined) {
                                                                document.getElementById(`distributor_group_${groupId}_min_quantity_to_list`).value = criteria.min_quantity_to_list;
                                                            }
                                                        }
                                                        
                                                        // Update distributor group type
                                                        function updateDistributorGroupType(distributor, groupId, newType) {
                                                            const config = editor.get();
                                                            const group = config.distributors[distributor].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            if (group) {
                                                                group.type = newType;
                                                                
                                                                // If switching to exclude, remove min_quantity_to_list from criteria
                                                                if (newType === 'exclude' && group.criteria.min_quantity_to_list) {
                                                                    delete group.criteria.min_quantity_to_list;
                                                                    // Clear the input field as well
                                                                    const minQuantityInput = document.getElementById(`distributor_group_${groupId}_min_quantity_to_list`);
                                                                    if (minQuantityInput) {
                                                                        minQuantityInput.value = '';
                                                                    }
                                                                }
                                                                
                                                                editor.set(config);
                                                                
                                                                // Update the badge in the UI
                                                                const badge = document.querySelector(`[data-group-id="${groupId}"] .group-type-badge`);
                                                                if (badge) {
                                                                    badge.className = `group-type-badge ${newType}`;
                                                                    badge.textContent = newType.toUpperCase();
                                                                }
                                                                
                                                                // Show/hide min_quantity_to_list field based on group type
                                                                const minQuantitySection = document.getElementById(`distributor_group_${groupId}_min_quantity_section`);
                                                                if (minQuantitySection) {
                                                                    minQuantitySection.style.display = newType === 'include' ? '' : 'none';
                                                                }

                                                                updateGroupFilterSummary(groupId, 'distributor_group_' + groupId + '_');
                                                            }
                                                        }
                                                        
                                                        // Update cost range for a distributor group
                                                        function updateDistributorGroupCostRange(distributor, groupId) {
                                                            const minCost = document.getElementById(`distributor_group_${groupId}_min_cost`).value;
                                                            const maxCost = document.getElementById(`distributor_group_${groupId}_max_cost`).value;

                                                            const config = editor.get();
                                                            const group = config.distributors[distributor].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            if (group) {
                                                                if (!group.criteria.cost) {
                                                                    group.criteria.cost = {};
                                                                }

                                                                if (minCost) {
                                                                    group.criteria.cost.min_cost = parseFloat(minCost);
                                                                } else {
                                                                    delete group.criteria.cost.min_cost;
                                                                }

                                                                if (maxCost) {
                                                                    group.criteria.cost.max_cost = parseFloat(maxCost);
                                                                } else {
                                                                    delete group.criteria.cost.max_cost;
                                                                }

                                                                // Remove cost object if empty
                                                                if (Object.keys(group.criteria.cost).length === 0) {
                                                                    delete group.criteria.cost;
                                                                }

                                                                editor.set(config);
                                                                updateGroupFilterSummary(groupId, 'distributor_group_' + groupId + '_');
                                                            }
                                                        }
                                                        
                                                        // Update min quantity to list for a distributor group
                                                        function updateDistributorGroupMinQuantityToList(distributor, groupId) {
                                                            const minQuantity = document.getElementById(`distributor_group_${groupId}_min_quantity_to_list`).value;
                                                            
                                                            const config = editor.get();
                                                            const group = config.distributors[distributor].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            if (group) {
                                                                if (minQuantity && minQuantity !== '' && !isNaN(minQuantity)) {
                                                                    const quantity = parseInt(minQuantity);
                                                                    // Ensure minimum value is 1
                                                                    group.criteria.min_quantity_to_list = Math.max(1, quantity);
                                                                    // Update the input if value was adjusted
                                                                    if (quantity < 1) {
                                                                        document.getElementById(`distributor_group_${groupId}_min_quantity_to_list`).value = 1;
                                                                    }
                                                                } else {
                                                                    // Default to 1 if empty or invalid
                                                                    group.criteria.min_quantity_to_list = 1;
                                                                    document.getElementById(`distributor_group_${groupId}_min_quantity_to_list`).value = 1;
                                                                }
                                                                
                                                                editor.set(config);
                                                            }
                                                        }
                                                        
                                                        // Save distributor product group to configuration
                                                        function saveDistributorProductGroupToConfig(distributor, groupId, name, type, criteria) {
                                                            const config = editor.get();
                                                            
                                                            if (!config.distributors[distributor].product_restrictions.product_groups) {
                                                                config.distributors[distributor].product_restrictions.product_groups = [];
                                                            }
                                                            
                                                            const existingIndex = config.distributors[distributor].product_restrictions.product_groups.findIndex(g => g.id === groupId);
                                                            const groupData = { id: groupId, name: name, type: type, criteria: criteria };
                                                            
                                                            if (existingIndex >= 0) {
                                                                config.distributors[distributor].product_restrictions.product_groups[existingIndex] = groupData;
                                                            } else {
                                                                config.distributors[distributor].product_restrictions.product_groups.push(groupData);
                                                            }
                                                            
                                                            editor.set(config);
                                                        }
                                                        
                                                        // Duplicate a distributor product group
                                                        function duplicateDistributorProductGroup(distributor, sourceGroupId) {
                                                            const config = editor.get();
                                                            const sourceGroup = config.distributors[distributor].product_restrictions.product_groups.find(g => g.id === sourceGroupId);
                                                            
                                                            if (sourceGroup) {
                                                                const newName = prompt('Enter a name for the duplicated group:', sourceGroup.name + ' (Copy)');
                                                                if (newName) {
                                                                    const newGroupId = `distributor_${distributor}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                                    addDistributorProductGroup(distributor, newName, sourceGroup.type, JSON.parse(JSON.stringify(sourceGroup.criteria)), newGroupId, false);
                                                                    // Save the duplicated group to config since isNew=false won't trigger auto-save
                                                                    saveDistributorProductGroupToConfig(distributor, newGroupId, newName, sourceGroup.type, JSON.parse(JSON.stringify(sourceGroup.criteria)));
                                                                }
                                                            }
                                                        }
                                                        
                                                        // Remove a distributor product group
                                                        function removeDistributorProductGroup(distributor, groupId) {
                                                            if (confirm('Are you sure you want to delete this product group?')) {
                                                                const config = editor.get();
                                                                config.distributors[distributor].product_restrictions.product_groups = config.distributors[distributor].product_restrictions.product_groups.filter(g => g.id !== groupId);
                                                                editor.set(config);
                                                                
                                                                // Remove from UI
                                                                const groupElement = document.querySelector(`[data-group-id="${groupId}"]`);
                                                                if (groupElement) {
                                                                    groupElement.remove();
                                                                }
                                                                
                                                                // Show empty state if no groups left
                                                                const container = document.getElementById(`distributor-product-groups-container-${distributor}`);
                                                                if (container && !container.querySelector('.product-group')) {
                                                                    loadDistributorProductGroups({ distributors: { [distributor]: { product_restrictions: { product_groups: [] } } } }, distributor);
                                                                }
                                                            }
                                                        }
                                                        
                                                        function toggleDistributorSelectContainer() {
                                                            const selectContainer = $('#distributor-select-container');
                                                            if ($('#available-distributors option').length === 0) {
                                                                selectContainer.hide();
                                                            } else {
                                                                selectContainer.show();
                                                            }
                                                        }

                                                        function toggleTargetSelectContainer() {
                                                            const selectContainer = $('#target-select-container');
                                                            if ($('#available-targets option').length === 0) {
                                                                selectContainer.hide();
                                                            } else {
                                                                selectContainer.show();
                                                            }
                                                        }
                                                    </script>
                                            </div>

                                            <div class="tab-pane fade" id="product-restrictions" role="tabpanel" aria-labelledby="product-restrictions-tab">
                                                <!-- Product Restrictions Form Content -->

                                                <!-- Legacy Format Detection and Conversion - Header Notice -->
                                                <div id="legacy-conversion-notice" style="display: none; background: #fff3cd; border: 1px solid #ffeaa7; padding: 10px 15px; margin-bottom: 15px; border-radius: 4px;">
                                                    <div style="display: flex; align-items: center; justify-content: space-between;">
                                                        <div style="display: flex; align-items: flex-start;">
                                                            <i class="fas fa-exclamation-triangle" style="color: #856404; margin-right: 8px; margin-top: 2px;"></i>
                                                            <div>
                                                                <div style="font-weight: bold; color: #856404; margin-bottom: 4px;">Legacy Product Restrictions Detected</div>
                                                                <div style="color: #856404; font-size: 14px;">The new Product Groups system provides a more intuitive and capable way to manage your product restrictions.</div>
                                                            </div>
                                                        </div>
                                                        <div style="display: flex; gap: 10px;">
                                                            <button type="button" id="convert-legacy-restrictions" class="btn btn-warning btn-sm">
                                                                <i class="fas fa-sync-alt"></i> Convert to New Format
                                                            </button>
                                                            <button type="button" id="dismiss-legacy-notice" class="btn btn-outline-secondary btn-sm">
                                                                Continue with Legacy Format
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>

                                                <div class="main-container">

                                                    <div class="left-container">
                                                        <div class="other-restrictions-header"><strong>Product Restrictions</strong></div>
                                                        <details class="gffc-pr-help-details">
                                                            <summary class="gffc-pr-help-summary">Help Documentation</summary>
                                                            <div class="helperDialog">
                                                            <p>
                                                                This section controls <strong>which products are imported from your distributors</strong> by using 
                                                                <strong>Product Groups</strong>.
                                                            </p>

                                                            <ul style="list-style-type: disc; margin-left: 0.5rem;">
                                                                <li>
                                                                <strong>Include Groups</strong> define products you want to import. <span style="font-style:italic;color:blue;">You must create at least one Include Group, and you can have 1-to-many include groups.</span>.
                                                                </li>
                                                                <li>
                                                                <strong>Exclude Groups</strong> define which products you do not want to import. You can also defined many exclude groups.
                                                                </li>
                                                            </ul>

                                                            <p><strong>Set the filters within each Product Group to define what you want to include or exclude.</strong> You can select multiple options in each filter field (Product Class, Category, Brand, SKU, UPC, Cost). <strong>Key rule: A product must match at least one entry in ALL the filters you've populated.</strong></p>
                                            
                                            <div style="margin-top:10px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;">
                                                <p style="margin:0 0 10px;font-weight:700;font-size:13px;">The #1 thing to remember:</p>
                                                <div style="background:#e0e7ff;border-radius:6px;padding:10px 12px;margin-bottom:12px;font-size:13px;">
                                                    Filters <em>within</em> the same field are <strong style="color:#10b981;">OR</strong> &mdash; filters <em>across</em> different fields are <strong style="color:#4338ca;">AND</strong>.
                                                </div>
                                                <p style="margin:0 0 8px;font-size:12px;">If you need to include products that match Category A <strong style="color:#10b981;">OR</strong> Brand B (independently), put them in <strong>separate groups</strong> &mdash; not in the same group.</p>
                                                <table style="width:100%;border-collapse:collapse;font-size:12px;margin-bottom:10px;">
                                                    <tr style="background:#f1f5f9;"><th style="text-align:left;padding:6px 8px;border:1px solid #e2e8f0;">What you want</th><th style="text-align:left;padding:6px 8px;border:1px solid #e2e8f0;">How to set it up</th></tr>
                                                    <tr><td style="padding:6px 8px;border:1px solid #e2e8f0;">All Firearms <strong>and</strong> all Optics</td><td style="padding:6px 8px;border:1px solid #e2e8f0;">One group &rarr; Product Class = Firearms, Optics</td></tr>
                                                    <tr><td style="padding:6px 8px;border:1px solid #e2e8f0;">Only Glock and Sig Sauer Firearms</td><td style="padding:6px 8px;border:1px solid #e2e8f0;">One group &rarr; Product Class = Firearms <strong style="color:#4338ca;">AND</strong> Brand = Glock, Sig Sauer</td></tr>
                                                    <tr><td style="padding:6px 8px;border:1px solid #e2e8f0;">All Firearms <strong>plus</strong> all Vortex products</td><td style="padding:6px 8px;border:1px solid #e2e8f0;"><strong>Two separate groups:</strong><br>Group 1 &rarr; Product Class = Firearms<br>Group 2 &rarr; Brand = Vortex</td></tr>
                                                    <tr><td style="padding:6px 8px;border:1px solid #e2e8f0;">Exclude cheap guns</td><td style="padding:6px 8px;border:1px solid #e2e8f0;">Exclude group &rarr; Product Class = Firearms (FA) <strong style="color:#4338ca;">AND</strong> Cost Min = $300</td></tr>
                                                </table>
                                                <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:6px;padding:8px 10px;margin-bottom:8px;font-size:12px;color:#166534;">
                                                    <i class="fas fa-lightbulb" style="margin-right:4px;color:#16a34a;"></i><strong>Tip:</strong> Exclude groups only remove products from what your Include groups already match. If your Include groups don&rsquo;t bring in Ammunition, there&rsquo;s no need to create an Exclude group for Ammunition.
                                                </div>
                                                <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:6px;padding:8px 10px;margin-bottom:8px;font-size:12px;color:#1e40af;">
                                                    <i class="fas fa-sitemap" style="margin-right:4px;color:#3b82f6;"></i><strong>These restrictions are your master filter.</strong> The groups you define here apply across <strong>all your distributors</strong> and <strong>all your targets</strong> (WooCommerce, Gunbroker, etc.). Need more control?
                                                    <ul style="margin:6px 0 0 16px;padding:0;">
                                                        <li><strong>By distributor:</strong> Each distributor has its own product restrictions under the <strong>Distributors</strong> tab &mdash; use those to control what you pull from a specific distributor.</li>
                                                        <li><strong>By target:</strong> Each target (WooCommerce, Gunbroker) has its own restrictions under the <strong>Targets</strong> tab &mdash; use those to control what gets posted to each destination.</li>
                                                    </ul>
                                                    <div style="margin-top:6px;">Products flow through all three levels: <strong>Master (here)</strong> &rarr; <strong>Distributor</strong> &rarr; <strong>Target</strong>. If no restrictions are set at the distributor or target level, everything that passes the master filter flows straight through. You only need to add restrictions at those levels when you want to narrow things down further.</div>
                                                </div>
                                                <p style="margin:0;font-size:11px;color:#64748b;">As you edit each group, a live summary above the filters will show you exactly which products match.</p>
                                            </div>
                                                            
                                                            </div>
                                                        </details>

                                                        <script>
                                                            // Desktop: keep help visible. Mobile: collapsed by default.
                                                            // Also: if the viewport transitions from mobile -> desktop, ensure the help
                                                            // content is made visible (open) so it doesn't disappear when summary is hidden.
                                                            document.addEventListener('DOMContentLoaded', function () {
                                                                var detailsEls = document.querySelectorAll('#product-restrictions .gffc-pr-help-details');
                                                                if (!detailsEls || detailsEls.length === 0) return;

                                                                var mq = window.matchMedia('(max-width: 768px)');

                                                                // Initial state
                                                                if (mq.matches) {
                                                                    detailsEls.forEach(function (details) { details.open = false; });
                                                                } else {
                                                                    detailsEls.forEach(function (details) { details.open = true; });
                                                                }

                                                                function onViewportChange(e) {
                                                                    // Only force-open on desktop; don't force-close on mobile so the user can
                                                                    // keep it open if they want after resizing.
                                                                    if (!e.matches) {
                                                                        detailsEls.forEach(function (details) { details.open = true; });
                                                                    }
                                                                }

                                                                if (typeof mq.addEventListener === 'function') {
                                                                    mq.addEventListener('change', onViewportChange);
                                                                } else if (typeof mq.addListener === 'function') {
                                                                    mq.addListener(onViewportChange);
                                                                }
                                                            });
                                                        </script>



                                                        
                                                    </div>
                                                    
                                                    <div class="right-container">
                                                        <!-- Product Groups Interface -->
                                                        <div class="restriction-section" id="product-groups-section">
                                                            <div class="g-ffl-restriction-header"><strong>Product Groups</strong></div>
                                                            <div id="product-groups-interface">
                                                                <div class="other-restrictions-header">
                                                                </div>
                                                                
                                                                <!-- Warning banner for missing include groups -->
                                                                <div id="missing-include-groups-warning" class="alert alert-danger" style="display: none; margin-bottom: 5px;">
                                                                    <i class="fas fa-exclamation-triangle"></i>
                                                                    <strong>Warning:</strong> You must define at least one Include Product Group. <strong>Include Product Groups</strong>
                                                                     define which products will be imported from distributors.
                                                                </div>
                                                                
                                                                <div id="product-groups-container" class="product-groups-container">
                                                                    <!-- Product groups will be dynamically added here -->
                                                                </div>

                                                                <div style="margin-top: 5px;">
                                                                    <button type="button" class="btn btn-primary btn-sm" onclick="addProductGroup()">
                                                                        <i class="fas fa-plus"></i> Add Product Group
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Global Restrictions -->
                                                        <div class="restriction-section">
                                                            <div class="g-ffl-restriction-header"><strong>Global Cost Restrictions</strong></div>
                                                            <div class="pricing-assumptions-form-row">
                                                                <label for="product_restrictions-cost-global_restrictions-min_distributor_cost">Min Distributor Cost ($):</label>
                                                                <input type="number" id="product_restrictions-cost-global_restrictions-min_distributor_cost" name="product_restrictions-cost-global_restrictions-min_distributor_cost" data-autosave="true">
                                                            </div>
                                                            <div class="pricing-assumptions-form-row">
                                                                <label for="product_restrictions-cost-global_restrictions-max_distributor_cost">Max Distributor Cost ($):</label>
                                                                <input type="number" id="product_restrictions-cost-global_restrictions-max_distributor_cost" name="product_restrictions-cost-global_restrictions-max_distributor_cost" data-autosave="true">
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="restriction-section">
                                                            <div class="g-ffl-restriction-header"><strong>Global Quantity Restrictions</strong></div>
                                                            <div class="pricing-assumptions-form-row">
                                                                <label for="product_restrictions-min_quantity_to_list">Min Distributor Quantity to List:</label>
                                                                <input type="number" id="product_restrictions-min_quantity_to_list" name="product_restrictions-min_quantity_to_list" data-autosave="true">
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Legacy container - hidden by default in new format -->
                                                        <div id="legacy-product-restrictions-container" style="display: none;"></div>
                                                    </div>
                                                </div>
                                                <script>
                                                    // Product Groups Management System
                                                    
                                                    // Flag to track if product restrictions have been initialized
                                                    let productRestrictionsInitialized = false;
                                                    
                                                    // Function to initialize product restrictions when tab is accessed
                                                    window.ensureProductRestrictionsInitialized = function() {
                                                        if (!productRestrictionsInitialized) {
                                                            initializeProductRestrictions();
                                                            productRestrictionsInitialized = true;
                                                        }
                                                    };
                                                    
                                                    // Initialize legacy detection and conversion
                                                    function initializeProductRestrictions() {
                                                        try {
                                                            // Only initialize if the product restrictions tab/container exists
                                                            const productRestrictionsContainer = document.getElementById('product-groups-container');
                                                            if (!productRestrictionsContainer) {
                                                                console.log('Product restrictions container not found, skipping initialization');
                                                                return;
                                                            }
                                                            
                                                            const config = editor.get();
                                                            if (!config) {
                                                                console.log('No configuration available, skipping product restrictions initialization');
                                                                return;
                                                            }
                                                            
                                                            // Check if we have legacy format restrictions
                                                            if (hasLegacyRestrictions(config)) {
                                                                showLegacyConversionNotice();
                                                                createLegacyInterface();
                                                                hideProductGroupsInterface();
                                                            } else {
                                                                // Load existing product groups or initialize empty
                                                                loadProductGroups(config);
                                                                showProductGroupsInterface();
                                                            }
                                                        } catch (error) {
                                                            console.error('Error initializing product restrictions:', error);
                                                            // Don't throw the error, just log it
                                                        }
                                                    }
                                                    
                                                    function hasLegacyRestrictions(config) {
                                                        try {
                                                            if (!config || !config.product_restrictions) return false;
                                                            
                                                            // Check if we have the old format (field-based restrictions)
                                                            const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                            return legacyFields.some(field => {
                                                                const restriction = config.product_restrictions[field];
                                                                return restriction && (
                                                                    (restriction.include && restriction.include.length > 0) ||
                                                                    (restriction.exclude && restriction.exclude.length > 0)
                                                                );
                                                            });
                                                        } catch (error) {
                                                            console.error('Error checking legacy restrictions:', error);
                                                            return false;
                                                        }
                                                    }
                                                    
                                                    function showLegacyConversionNotice() {
                                                        try {
                                                            const legacyNotice = document.getElementById('legacy-conversion-notice');
                                                            const legacyContainer = document.getElementById('legacy-product-restrictions-container');
                                                            
                                                            if (!legacyNotice || !legacyContainer) {
                                                                console.log('Legacy conversion elements not found, skipping notice display');
                                                                return;
                                                            }
                                                            
                                                            legacyNotice.style.display = 'block';
                                                            legacyContainer.style.display = 'block';
                                                            
                                                            // Event handlers for conversion
                                                            const convertButton = document.getElementById('convert-legacy-restrictions');
                                                            const dismissButton = document.getElementById('dismiss-legacy-notice');
                                                            
                                                            if (convertButton) {
                                                                convertButton.onclick = function() {
                                                                    convertLegacyToProductGroups();
                                                                };
                                                            }
                                                            
                                                            if (dismissButton) {
                                                                dismissButton.onclick = function() {
                                                                    legacyNotice.style.display = 'none';
                                                                };
                                                            }
                                                        } catch (error) {
                                                            console.error('Error showing legacy conversion notice:', error);
                                                        }
                                                    }
                                                    
                                                    function hideProductGroupsInterface() {
                                                        const productGroupsSection = document.getElementById('product-groups-section');
                                                        if (productGroupsSection) {
                                                            productGroupsSection.style.display = 'none';
                                                        }
                                                    }
                                                    
                                                    function showProductGroupsInterface() {
                                                        const productGroupsSection = document.getElementById('product-groups-section');
                                                        if (productGroupsSection) {
                                                            productGroupsSection.style.display = 'block';
                                                        }
                                                    }
                                                    
                                                    function createLegacyInterface() {
                                                        const product_restrictions_container = document.getElementById('legacy-product-restrictions-container');
                                                        
                                                        if (!product_restrictions_container) {
                                                            console.log('Legacy product restrictions container not found, skipping interface creation');
                                                            return;
                                                        }
                                                        
                                                        const restrictions = [
                                                            {"field": "product_class", "modal": "productClassModal", "name": "Product Classes", "select_text": "Select Product Classes"},
                                                            {"field": "category", "modal": "categoryModal", "name": "Categories", "select_text": "Select Categories"},
                                                            {"field": "brand", "modal": "brandModal", "name": "Brands", "select_text": "Select Brands"},
                                                            {"field": "sku", "modal": "prompt", "name": "SKU", "select_text": "Add SKU"},
                                                            {"field": "upc", "modal": "prompt", "name": "UPC", "select_text": "Add UPC"} 
                                                        ];

                                                        restrictions.forEach(restriction => {
                                                            const section = document.createElement('div');
                                                            section.className = 'restriction-section';
                                                            
                                                            const header = document.createElement('div');
                                                            header.className = 'g-ffl-restriction-header';
                                                            header.innerHTML = `<strong>${restriction.name}</strong>`;
                                                            section.appendChild(header);

                                                            const container = document.createElement('div');
                                                            container.className = 'restriction-container';

                                                            const includeDiv = document.createElement('div');
                                                            includeDiv.className = 'restriction-item';
                                                            
                                                            var launcher_include = `openModal('${restriction.modal}', 'product_restrictions-${restriction.field}-include')`;
                                                            var launcher_exclude = `openModal('${restriction.modal}', 'product_restrictions-${restriction.field}-exclude')`;
                                                            if (restriction.modal == "prompt"){
                                                                launcher_include = `promptAndAddItems(this, '${restriction.field}', 'product_restrictions-${restriction.field}-include')`;
                                                                launcher_exclude = `promptAndAddItems(this, '${restriction.field}', 'product_restrictions-${restriction.field}-exclude')`;
                                                            }
                                                            
                                                            includeDiv.innerHTML = `
                                                                <label for="product_class"><span style="color:red">**</span>Include - <span style="font-size:9pt !important;">
                                                                    <span id="product_restrictions-${restriction.field}-and-option" onclick="toggleOperandOption('product_restrictions-${restriction.field}', 'AND', true)">AND</span> | 
                                                                    <span id="product_restrictions-${restriction.field}-or-option" onclick="toggleOperandOption('product_restrictions-${restriction.field}', 'OR', true)">OR</span></span>:
                                                                </label>
                                                                <div class="field-container">
                                                                    <div class="selected-items" id="product_restrictions-${restriction.field}-include"></div>
                                                                    <div class="add-item-container">
                                                                        <span class="add-item" onclick="${launcher_include}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('product_restrictions-${restriction.field}-include'))">Remove All</span>
                                                                    </div>
                                                                </div>`;
                                                            container.appendChild(includeDiv);

                                                            const excludeDiv = document.createElement('div');
                                                            excludeDiv.className = 'restriction-item';
                                                            excludeDiv.innerHTML = `
                                                                <label for="product_class">Exclude:</label>
                                                                <div class="field-container">
                                                                    <div class="selected-items" id="product_restrictions-${restriction.field}-exclude"></div>
                                                                    <div class="add-item-container">
                                                                        <span class="add-item" onclick="${launcher_exclude}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('product_restrictions-${restriction.field}-exclude'))">Remove All</span>
                                                                    </div>
                                                                </div>`;
                                                            container.appendChild(excludeDiv);
                                                            section.appendChild(container);
                                                            product_restrictions_container.appendChild(section);
                                                        });
                                                        
                                                        // After creating the interface, populate it with existing data
                                                        populateLegacyInterface();
                                                    }
                                                    
                                                    // Populate the legacy interface with existing configuration data
                                                    function populateLegacyInterface() {
                                                        try {
                                                            const config = editor.get();
                                                            if (!config || !config.product_restrictions) {
                                                                console.log('No product restrictions configuration found');
                                                                return;
                                                            }
                                                            
                                                            const restrictions = ["product_class", "category", "brand", "sku", "upc"];
                                                            const include_excludes = ["include", "exclude"];
                                                            
                                                            // Set operand options
                                                            restrictions.forEach(restriction => {
                                                                if (config.product_restrictions[restriction] && config.product_restrictions[restriction]['include_operand']) {
                                                                    toggleOperandOption(`product_restrictions-${restriction}`, config.product_restrictions[restriction].include_operand);
                                                                } else {
                                                                    toggleOperandOption(`product_restrictions-${restriction}`, "AND");
                                                                }
                                                            });
                                                            
                                                            // Populate include/exclude data
                                                            restrictions.forEach(restriction => {
                                                                include_excludes.forEach(include_exclude => {
                                                                    if (config.product_restrictions[restriction] && config.product_restrictions[restriction][include_exclude]) {
                                                                        const restrictionElement = document.getElementById(`product_restrictions-${restriction}-${include_exclude}`);
                                                                        if (restrictionElement) {
                                                                            // Clear existing content
                                                                            restrictionElement.innerHTML = '';
                                                                            // Add the items
                                                                            addSelectedItemsToContainer(restrictionElement, config.product_restrictions[restriction][include_exclude]);
                                                                        }
                                                                    }
                                                                });
                                                            });
                                                        } catch (error) {
                                                            console.error('Error populating legacy interface:', error);
                                                        }
                                                    }
                                                    
                                                    // Convert legacy restrictions to new product groups format
                                                    function convertLegacyToProductGroups() {
                                                        const config = editor.get();
                                                        
                                                        // Initialize product_groups array if it doesn't exist
                                                        if (!config.product_restrictions.product_groups) {
                                                            config.product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                        let groupCounter = 1;
                                                        
                                                        // First, collect all include groups
                                                        legacyFields.forEach(field => {
                                                            const restriction = config.product_restrictions[field];
                                                            if (!restriction) return;
                                                            
                                                            // Create include group if there are include items
                                                            if (restriction.include && restriction.include.length > 0) {
                                                                // Create a descriptive name based on the values
                                                                let descriptiveName = '';
                                                                const values = restriction.include;
                                                                const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                
                                                                if (values.length === 1) {
                                                                    descriptiveName = `${fieldDisplayName}: ${values[0]}`;
                                                                } else if (values.length <= 3) {
                                                                    descriptiveName = `${fieldDisplayName}: ${values.join(', ')}`;
                                                                } else {
                                                                    descriptiveName = `${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                }
                                                                
                                                                const includeGroup = {
                                                                    id: `main_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                    name: descriptiveName,
                                                                    type: 'include',
                                                                    criteria: {
                                                                        [field]: restriction.include
                                                                    }
                                                                };
                                                                config.product_restrictions.product_groups.push(includeGroup);
                                                            }
                                                        });
                                                        
                                                        // Then, collect all exclude groups
                                                        legacyFields.forEach(field => {
                                                            const restriction = config.product_restrictions[field];
                                                            if (!restriction) return;
                                                            
                                                            // Create exclude group if there are exclude items
                                                            if (restriction.exclude && restriction.exclude.length > 0) {
                                                                // Create a descriptive name based on the values
                                                                let descriptiveName = '';
                                                                const values = restriction.exclude;
                                                                const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                
                                                                if (values.length === 1) {
                                                                    descriptiveName = `${fieldDisplayName}: ${values[0]}`;
                                                                } else if (values.length <= 3) {
                                                                    descriptiveName = `${fieldDisplayName}: ${values.join(', ')}`;
                                                                } else {
                                                                    descriptiveName = `${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                }
                                                                
                                                                const excludeGroup = {
                                                                    id: `main_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                    name: descriptiveName,
                                                                    type: 'exclude',
                                                                    criteria: {
                                                                        [field]: restriction.exclude
                                                                    }
                                                                };
                                                                config.product_restrictions.product_groups.push(excludeGroup);
                                                            }
                                                        });
                                                        
                                                        // Clear the legacy fields
                                                        legacyFields.forEach(field => {
                                                            delete config.product_restrictions[field];
                                                        });
                                                        
                                                        // Update the configuration
                                                        editor.set(config);
                                                        
                                                        // Hide legacy notice and container
                                                        document.getElementById('legacy-conversion-notice').style.display = 'none';
                                                        document.getElementById('legacy-product-restrictions-container').style.display = 'none';
                                                        
                                                        // Show Product Groups interface and load the new product groups interface
                                                        showProductGroupsInterface();
                                                        loadProductGroups(config);
                                                        
                                                        alert('Legacy restrictions have been successfully converted to Product Groups! Please review for accuracy before Savings changes. To revert, refresh your browser.');
                                                    }
                                                    
                                                    // Load existing product groups
                                                    function loadProductGroups(config) {
                                                        try {
                                                            const container = document.getElementById('product-groups-container');
                                                            
                                                            if (!container) {
                                                                console.log('Product groups container not found, skipping load');
                                                                return;
                                                            }
                                                            
                                                            container.innerHTML = ''; // Clear existing content
                                                            
                                                            if (config.product_restrictions && config.product_restrictions.product_groups && config.product_restrictions.product_groups.length > 0) {
                                                            // Sort groups so include groups appear first, then exclude groups
                                                            const sortedGroups = [...config.product_restrictions.product_groups].sort((a, b) => {
                                                                // Include groups (type 'include') come first
                                                                if (a.type === 'include' && b.type === 'exclude') return -1;
                                                                if (a.type === 'exclude' && b.type === 'include') return 1;
                                                                // If same type, maintain original order
                                                                return 0;
                                                            });
                                                            
                                                            sortedGroups.forEach(group => {
                                                                addProductGroup(group.name, group.type, group.criteria, group.id, false);
                                                            });
                                                        } else {
                                                            // Show empty state
                                                            const emptyState = document.createElement('div');
                                                            emptyState.className = 'empty-state';
                                                            emptyState.innerHTML = `
                                                                <div style="text-align: center; padding: 40px; color: #666;">
                                                                    <i class="fas fa-layer-group" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
                                                                    <h3 style="margin: 0 0 10px 0; color: #333;">No Product Groups Defined</h3>
                                                                    <p style="margin: 0;">Create your first product group to start organizing your product restrictions.</p>
                                                                </div>
                                                            `;
                                                            container.appendChild(emptyState);
                                                        }
                                                        } catch (error) {
                                                            console.error('Error loading product groups:', error);
                                                        }
                                                        
                                                        // Check and show/hide the include groups warning
                                                        checkIncludeGroupsWarning(config);
                                                    }
                                                    
                                                    // Function to check if there are include groups and show warning if needed
                                                    function checkIncludeGroupsWarning(config) {
                                                        const warningBanner = document.getElementById('missing-include-groups-warning');
                                                        
                                                        if (!warningBanner) return;
                                                        
                                                        // Check if user has converted to product groups
                                                        const hasProductGroups = config.product_restrictions && 
                                                                                config.product_restrictions.product_groups && 
                                                                                config.product_restrictions.product_groups.length > 0;
                                                        
                                                        if (hasProductGroups) {
                                                            // Check if there are any include groups
                                                            const hasIncludeGroups = config.product_restrictions.product_groups.some(group => group.type === 'include');
                                                            
                                                            if (!hasIncludeGroups) {
                                                                // Show warning - has product groups but no include groups
                                                                warningBanner.style.display = 'block';
                                                            } else {
                                                                // Hide warning - has include groups
                                                                warningBanner.style.display = 'none';
                                                            }
                                                        } else {
                                                            // Hide warning - no product groups at all (still using legacy system)
                                                            warningBanner.style.display = 'none';
                                                        }
                                                    }
                                                    
                                                    // Add a new product group
                                                    function addProductGroup(groupName = null, groupType = null, criteria = null, groupId = null, isNew = true) {
                                                        if (isNew) {
                                                            groupName = prompt('Enter a name for your product group (e.g., "Firearms", "Hunting Gear"):');
                                                            if (!groupName) return;
                                                            
                                                            groupName = groupName.trim();
                                                            groupId = `main_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                            groupType = 'include'; // Default to include
                                                            criteria = {};
                                                        }
                                                        
                                                        const container = document.getElementById('product-groups-container');
                                                        
                                                        // Remove empty state if it exists
                                                        const emptyState = container.querySelector('.empty-state');
                                                        if (emptyState) {
                                                            emptyState.remove();
                                                        }
                                                        
                                                        const div = document.createElement('div');
                                                        div.className = 'group-container product-group';
                                                        div.setAttribute('data-group-id', groupId);
                                                        
                                                        div.innerHTML = `
                                                            <div class="group-header">
                                                                <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${groupId}', this)">
                                                                    <i class="fas fa-plus accordion-toggle-icon"></i>
                                                                    <span class="group-type-badge ${groupType}">${groupType.toUpperCase()}</span>
                                                                    <span style="display: flex; align-items: center;">
                                                                        <span class="group-name">${groupName}</span>
                                                                        <i class="fas fa-edit edit-group-name" title="Edit group name" onclick="event.stopPropagation(); editGroupName('${groupId}', this.previousElementSibling)" style="margin-left: 6px; color: #6c757d; cursor: pointer; font-size: 11px;"></i>
                                                                    </span>
                                                                </div>
                                                                <div class="group-actions">
                                                                    <i class="fas fa-copy copy-link" title="Duplicate Product Group" onclick="duplicateProductGroup('${groupId}')"></i>
                                                                    <i class="fas fa-trash-alt remove-link" title="Delete Product Group" onclick="removeProductGroup('${groupId}')"></i>
                                                                </div>
                                                            </div>
                                                            <div class="accordion-content" id="${groupId}" style="display: ${isNew ? 'block' : 'none'};">
                                                                <div id="group-summary-${groupId}" style="margin-bottom:12px;padding:10px 12px;background:#f0f9ff;border:1px solid #bae6fd;border-radius:6px;font-size:12px;color:#0c4a6e;display:none;">
                                                                </div>
                                                                
                                                                <!-- Group Type Selection -->
                                                                <div class="form-row">
                                                                    <label>Group Type:</label>
                                                                    <div class="group-type-selector">
                                                                        <label class="radio-label">
                                                                            <input type="radio" name="group_type_${groupId}" value="include" ${groupType === 'include' ? 'checked' : ''} 
                                                                                   onchange="updateGroupType('${groupId}', 'include')">
                                                                            <span class="radio-custom include"></span>
                                                                            Include - Products matching this group will be included
                                                                        </label>
                                                                        <label class="radio-label">
                                                                            <input type="radio" name="group_type_${groupId}" value="exclude" ${groupType === 'exclude' ? 'checked' : ''} 
                                                                                   onchange="updateGroupType('${groupId}', 'exclude')">
                                                                            <span class="radio-custom exclude"></span>
                                                                            Exclude - Products matching this group will be excluded
                                                                        </label>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Product Class -->
                                                                <div class="form-row gffc-filter-row" data-filter="product_class" data-group="${groupId}">
                                                                    <label>Product Class:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="group_${groupId}_product_class"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('productClassModal', 'group_${groupId}_product_class')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('group_${groupId}_product_class'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <!-- Category -->
                                                                <div class="form-row gffc-filter-row" data-filter="category" data-group="${groupId}">
                                                                    <label>Category:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="group_${groupId}_category"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('categoryModal', 'group_${groupId}_category')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('group_${groupId}_category'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <!-- Brand -->
                                                                <div class="form-row gffc-filter-row" data-filter="brand" data-group="${groupId}">
                                                                    <label>Brand:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="group_${groupId}_brand"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('brandModal', 'group_${groupId}_brand')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('group_${groupId}_brand'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <!-- SKU -->
                                                                <div class="form-row gffc-filter-row" data-filter="sku" data-group="${groupId}">
                                                                    <label>SKU:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="group_${groupId}_sku"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'sku', 'group_${groupId}_sku')">Add</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('group_${groupId}_sku'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <!-- UPC -->
                                                                <div class="form-row gffc-filter-row" data-filter="upc" data-group="${groupId}">
                                                                    <label>UPC:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="group_${groupId}_upc"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'upc', 'group_${groupId}_upc')">Add</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('group_${groupId}_upc'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <!-- Cost Range -->
                                                                <div class="form-row gffc-filter-row" data-filter="cost" data-group="${groupId}">
                                                                    <label>Cost:</label>
                                                                    <div class="field-container">
                                                                        <div style="display: flex; align-items: center; gap: 8px;">
                                                                            <div style="flex: 1;">
                                                                                <label for="group_${groupId}_min_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Min ($):</label>
                                                                                <input type="number" id="group_${groupId}_min_cost" class="form-control" 
                                                                                       placeholder="0.00" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateGroupCostRange('${groupId}')">
                                                                            </div>
                                                                            <div style="flex: 1;">
                                                                                <label for="group_${groupId}_max_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Max ($):</label>
                                                                                <input type="number" id="group_${groupId}_max_cost" class="form-control" 
                                                                                       placeholder="999999.99" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateGroupCostRange('${groupId}')">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Min Quantity to List -->
                                                                <div class="form-row" id="group_${groupId}_min_quantity_section" style="display: ${groupType === 'include' ? '' : 'none'};">
                                                                    <label>Min Qty to List:</label>
                                                                    <div class="field-container">
                                                                        <div style="display: flex; align-items: center; gap: 8px;">
                                                                            <div style="flex: 1;">
                                                                                <input type="number" id="group_${groupId}_min_quantity_to_list" class="form-control" 
                                                                                       placeholder="1" min="1" step="1" value="1" style="width: 60px; font-size: 12px; padding: 4px;" 
                                                                                       onchange="updateGroupMinQuantityToList('${groupId}')" data-autosave="true">
                                                                                <div style="font-size: 11px; color: #666; margin-top: 2px;">
                                                                                    Minimum quantity required for products to be listed (minimum value: 1)
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        `;
                                                        
                                                        container.appendChild(div);

                                                        // Load existing criteria if provided
                                                        if (criteria) {
                                                            loadGroupCriteria(groupId, criteria);
                                                        }

                                                        // If new group, save it to config
                                                        if (isNew) {
                                                            saveProductGroupToConfig(groupId, groupName, groupType, {});
                                                            // Expand the new group
                                                            expandGroup(groupId, div);
                                                        }

                                                        // Set up MutationObserver to watch for filter changes and update summary
                                                        var accordionContent = document.getElementById(groupId);
                                                        if (accordionContent) {
                                                            var observer = new MutationObserver(function() { updateGroupFilterSummary(groupId); });
                                                            observer.observe(accordionContent, { childList: true, subtree: true, characterData: true });
                                                            // Initial update
                                                            setTimeout(function() { updateGroupFilterSummary(groupId); }, 100);
                                                        }
                                                    }
                                                    
                                                    var _gffcSummaryUpdating = {};
                                                    function updateGroupFilterSummary(groupId, prefix, summaryKey, actionOverride) {
                                                        var sKey = summaryKey || groupId;
                                                        if (_gffcSummaryUpdating[sKey]) return;
                                                        _gffcSummaryUpdating[sKey] = true;
                                                        clearTimeout(_gffcSummaryUpdating[sKey + '_t']);
                                                        _gffcSummaryUpdating[sKey + '_t'] = setTimeout(function() { _gffcSummaryUpdating[sKey] = false; }, 50);
                                                        var pfx = prefix || ('group_' + groupId + '_');
                                                        var filters = [];
                                                        var filterLabels = {
                                                            product_class: 'Product Class',
                                                            category: 'Category',
                                                            brand: 'Brand',
                                                            distributor: 'Distributor',
                                                            sku: 'SKU',
                                                            upc: 'UPC',
                                                            cost: 'Cost'
                                                        };

                                                        // Check each filter field for values
                                                        ['product_class', 'category', 'brand', 'distributor', 'sku', 'upc'].forEach(function(field) {
                                                            var container = document.getElementById(pfx + field);
                                                            if (container) {
                                                                var items = container.querySelectorAll('.selected-item');
                                                                if (items.length > 0) {
                                                                    var values = [];
                                                                    items.forEach(function(item) {
                                                                        var text = item.textContent.replace(/\s*$/, '').replace(/\s+/g, ' ').trim();
                                                                        // Remove trailing trash icon text
                                                                        text = text.replace(/\s*\uf2ed\s*$/, '').replace(/\s*$/, '').trim();
                                                                        if (text) values.push(text);
                                                                    });
                                                                    if (values.length > 0) {
                                                                        filters.push({ field: field, label: filterLabels[field], values: values });
                                                                    }
                                                                }
                                                            }
                                                        });

                                                        // Check cost
                                                        var minCost = document.getElementById(pfx + 'min_cost');
                                                        var maxCost = document.getElementById(pfx + 'max_cost');
                                                        if (minCost && maxCost) {
                                                            var minV = parseFloat(minCost.value);
                                                            var maxV = parseFloat(maxCost.value);
                                                            var hasCustomCost = (!isNaN(minV) && minV > 0) || (!isNaN(maxV) && maxV < 999999);
                                                            if (hasCustomCost) {
                                                                var costDesc = '$' + (minV || 0).toFixed(2) + ' - $' + (maxV || 999999.99).toFixed(2);
                                                                filters.push({ field: 'cost', label: 'Cost', values: [costDesc] });
                                                            }
                                                        }

                                                        // Get group type — find the closest product-group container from the summary element
                                                        var summaryCheck = document.getElementById('group-summary-' + sKey);
                                                        var groupEl = summaryCheck ? summaryCheck.closest('.product-group, .group-container') : null;
                                                        var badge = groupEl ? groupEl.querySelector('.group-type-badge') : null;
                                                        var groupType = actionOverride || (badge ? badge.textContent.trim().toLowerCase() : 'exclude');

                                                        // Update plain-English summary
                                                        var summaryEl = document.getElementById('group-summary-' + sKey);
                                                        if (summaryEl) {
                                                            if (filters.length === 0) {
                                                                summaryEl.style.display = 'none';
                                                            } else {
                                                                var parts = filters.map(function(f) {
                                                                    var valStr = f.values.length <= 3 ? '<strong>' + f.values.join('</strong> or <strong>') + '</strong>' : '<strong>' + f.values.slice(0, 2).join('</strong> or <strong>') + '</strong> or <strong>' + (f.values.length - 2) + ' more</strong>';
                                                                    return f.label + ' is ' + valStr;
                                                                });
                                                                var andJoin = ' <span style="background:#e0e7ff;color:#4338ca;font-weight:800;padding:0 4px;border-radius:3px;font-size:10px;">AND</span> ';
                                                                var sentence;
                                                                if (actionOverride) {
                                                                    sentence = 'This margin will <strong>apply to</strong> products where ' + parts.join(andJoin) + '.';
                                                                } else {
                                                                    sentence = 'This group will <strong>' + groupType + '</strong> products where ' + parts.join(andJoin) + '.';
                                                                }
                                                                var html = '<i class="fas fa-info-circle" style="margin-right:6px;color:#3b82f6;"></i>' + sentence;
                                                                if (filters.length >= 2) {
                                                                    var splitAdvice = actionOverride
                                                                        ? 'To apply this margin to products matching <em>any</em> filter independently, create separate margin groups.'
                                                                        : 'To ' + groupType + ' products matching <em>any</em> filter independently, create separate groups.';
                                                                    html += '<div style="margin-top:8px;padding-top:8px;border-top:1px solid #fcd34d;color:#92400e;"><i class="fas fa-exclamation-triangle" style="margin-right:6px;color:#f59e0b;"></i><strong>Multiple filter types are set.</strong> Products must match ALL filters (AND logic). ' + splitAdvice + '</div>';
                                                                    summaryEl.style.background = '#fffbeb';
                                                                    summaryEl.style.borderColor = '#fcd34d';
                                                                } else {
                                                                    summaryEl.style.background = '#f0f9ff';
                                                                    summaryEl.style.borderColor = '#bae6fd';
                                                                }
                                                                summaryEl.innerHTML = html;
                                                                summaryEl.style.display = '';
                                                            }
                                                        }
                                                    }

                                                    // Load criteria into a group
                                                    function loadGroupCriteria(groupId, criteria) {
                                                        const fields = ['product_class', 'distributor', 'category', 'brand', 'sku', 'upc'];
                                                        
                                                        fields.forEach(field => {
                                                            if (criteria[field] && Array.isArray(criteria[field])) {
                                                                const container = document.getElementById(`group_${groupId}_${field}`);
                                                                if (container) {
                                                                    addSelectedItemsToContainer(container, criteria[field]);
                                                                }
                                                            }
                                                        });
                                                        
                                                        // Load cost range if present
                                                        if (criteria.cost) {
                                                            if (criteria.cost.min_cost !== undefined) {
                                                                document.getElementById(`group_${groupId}_min_cost`).value = criteria.cost.min_cost;
                                                            }
                                                            if (criteria.cost.max_cost !== undefined) {
                                                                document.getElementById(`group_${groupId}_max_cost`).value = criteria.cost.max_cost;
                                                            }
                                                        }
                                                        
                                                        // Load min quantity to list if present
                                                        if (criteria.min_quantity_to_list !== undefined) {
                                                            document.getElementById(`group_${groupId}_min_quantity_to_list`).value = criteria.min_quantity_to_list;
                                                        }
                                                    }
                                                    
                                                    // Update group type in the config and UI
                                                    function updateGroupType(groupId, newType) {
                                                        const config = editor.get();
                                                        const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            group.type = newType;
                                                            
                                                            // If switching to exclude, remove min_quantity_to_list from criteria
                                                            if (newType === 'exclude' && group.criteria.min_quantity_to_list) {
                                                                delete group.criteria.min_quantity_to_list;
                                                                // Clear the input field as well
                                                                const minQuantityInput = document.getElementById(`group_${groupId}_min_quantity_to_list`);
                                                                if (minQuantityInput) {
                                                                    minQuantityInput.value = '';
                                                                }
                                                            }
                                                            
                                                            editor.set(config);
                                                            
                                                            // Update the badge in the UI
                                                            const badge = document.querySelector(`[data-group-id="${groupId}"] .group-type-badge`);
                                                            if (badge) {
                                                                badge.className = `group-type-badge ${newType}`;
                                                                badge.textContent = newType.toUpperCase();
                                                            }
                                                            
                                                            // Show/hide min_quantity_to_list field based on group type
                                                            const minQuantitySection = document.getElementById(`group_${groupId}_min_quantity_section`);
                                                            if (minQuantitySection) {
                                                                minQuantitySection.style.display = newType === 'include' ? '' : 'none';
                                                            }
                                                            
                                                            // Check for include groups warning after type change
                                                            checkIncludeGroupsWarning(config);

                                                            // Refresh filter summary (updates plain-English sentence and warning)
                                                            updateGroupFilterSummary(groupId);
                                                        }
                                                    }

                                                    // Update cost range for a group
                                                    function updateGroupCostRange(groupId) {
                                                        const minCost = document.getElementById(`group_${groupId}_min_cost`).value;
                                                        const maxCost = document.getElementById(`group_${groupId}_max_cost`).value;

                                                        const config = editor.get();
                                                        const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            if (!group.criteria.cost) {
                                                                group.criteria.cost = {};
                                                            }

                                                            if (minCost) {
                                                                group.criteria.cost.min_cost = parseFloat(minCost);
                                                            } else {
                                                                delete group.criteria.cost.min_cost;
                                                            }

                                                            if (maxCost) {
                                                                group.criteria.cost.max_cost = parseFloat(maxCost);
                                                            } else {
                                                                delete group.criteria.cost.max_cost;
                                                            }

                                                            // Remove cost object if empty
                                                            if (Object.keys(group.criteria.cost).length === 0) {
                                                                delete group.criteria.cost;
                                                            }

                                                            editor.set(config);
                                                            updateGroupFilterSummary(groupId);
                                                        }
                                                    }
                                                    
                                                    // Update min quantity to list for a group
                                                    function updateGroupMinQuantityToList(groupId) {
                                                        const minQuantity = document.getElementById(`group_${groupId}_min_quantity_to_list`).value;
                                                        
                                                        const config = editor.get();
                                                        const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            if (minQuantity && minQuantity !== '' && !isNaN(minQuantity)) {
                                                                const quantity = parseInt(minQuantity);
                                                                // Ensure minimum value is 1
                                                                group.criteria.min_quantity_to_list = Math.max(1, quantity);
                                                                // Update the input if value was adjusted
                                                                if (quantity < 1) {
                                                                    document.getElementById(`group_${groupId}_min_quantity_to_list`).value = 1;
                                                                }
                                                            } else {
                                                                // Default to 1 if empty or invalid
                                                                group.criteria.min_quantity_to_list = 1;
                                                                document.getElementById(`group_${groupId}_min_quantity_to_list`).value = 1;
                                                            }
                                                            
                                                            editor.set(config);
                                                        }
                                                    }
                                                    
                                                    // Save product group to configuration
                                                    function saveProductGroupToConfig(groupId, name, type, criteria) {
                                                        const config = editor.get();
                                                        
                                                        if (!config.product_restrictions.product_groups) {
                                                            config.product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const existingIndex = config.product_restrictions.product_groups.findIndex(g => g.id === groupId);
                                                        const groupData = { id: groupId, name: name, type: type, criteria: criteria };
                                                        
                                                        if (existingIndex >= 0) {
                                                            config.product_restrictions.product_groups[existingIndex] = groupData;
                                                        } else {
                                                            config.product_restrictions.product_groups.push(groupData);
                                                        }
                                                        
                                                        editor.set(config);
                                                        
                                                        // Check for include groups warning after saving
                                                        checkIncludeGroupsWarning(config);
                                                    }
                                                    
                                                    // Duplicate a product group
                                                    function duplicateProductGroup(sourceGroupId) {
                                                        const config = editor.get();
                                                        const sourceGroup = config.product_restrictions.product_groups.find(g => g.id === sourceGroupId);
                                                        
                                                        if (sourceGroup) {
                                                            const newName = prompt('Enter a name for the duplicated group:', sourceGroup.name + ' (Copy)');
                                                            if (newName) {
                                                                const newGroupId = `main_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                                addProductGroup(newName, sourceGroup.type, JSON.parse(JSON.stringify(sourceGroup.criteria)), newGroupId, false);
                                                                // Save the duplicated group to config since isNew=false won't trigger auto-save
                                                                saveProductGroupToConfig(newGroupId, newName, sourceGroup.type, JSON.parse(JSON.stringify(sourceGroup.criteria)));
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Remove a product group
                                                    function removeProductGroup(groupId) {
                                                        if (confirm('Are you sure you want to delete this product group?')) {
                                                            const config = editor.get();
                                                            config.product_restrictions.product_groups = config.product_restrictions.product_groups.filter(g => g.id !== groupId);
                                                            editor.set(config);
                                                            
                                                            // Remove from UI
                                                            const groupElement = document.querySelector(`[data-group-id="${groupId}"]`);
                                                            if (groupElement) {
                                                                groupElement.remove();
                                                            }
                                                            
                                                            // Show empty state if no groups left
                                                            const container = document.getElementById('product-groups-container');
                                                            if (!container.querySelector('.product-group')) {
                                                                loadProductGroups({ product_restrictions: { product_groups: [] } });
                                                            }
                                                            
                                                            // Check for include groups warning after removal
                                                            checkIncludeGroupsWarning(config);
                                                        }
                                                    }
                                                    
                                                    // Function to edit product group name
                                                    function editGroupName(groupId, element) {
                                                        const currentName = element.textContent;
                                                        const newName = prompt('Edit group name:', currentName);
                                                        
                                                        if (newName && newName.trim() && newName.trim() !== currentName) {
                                                            const config = editor.get();
                                                            const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                            
                                                            if (group) {
                                                                group.name = newName.trim();
                                                                editor.set(config);
                                                                element.textContent = newName.trim();
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Function to edit distributor product group name
                                                    function editDistributorGroupName(distributor, groupId, element) {
                                                        const currentName = element.textContent;
                                                        const newName = prompt('Edit group name:', currentName);
                                                        
                                                        if (newName && newName.trim() && newName.trim() !== currentName) {
                                                            const config = editor.get();
                                                            const group = config.distributors[distributor].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            
                                                            if (group) {
                                                                group.name = newName.trim();
                                                                editor.set(config);
                                                                element.textContent = newName.trim();
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Override the addConfigArrayItem function to work with product groups
                                                    window.addConfigArrayItemToGroup = function(container, item) {
                                                        console.log('addConfigArrayItemToGroup called with:', { container, item, containerId: container.id, itemType: typeof item });
                                                        
                                                        const containerId = container.id;
                                                        // Updated regex to handle fields with underscores like product_class
                                                        // Match against known field names: product_class, sku, upc, category, brand, cost
                                                        const groupIdMatch = containerId.match(/^group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                                        
                                                        if (groupIdMatch) {
                                                            const groupId = groupIdMatch[1];
                                                            const field = groupIdMatch[2];
                                                            console.log('Main group match:', { groupId, field, fullContainerId: containerId });
                                                            
                                                            const config = editor.get();
                                                            console.log('Available groups in config:', config.product_restrictions?.product_groups?.map(g => g.id) || 'No groups found');
                                                            if (config.product_restrictions && config.product_restrictions.product_groups) {
                                                                const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                                
                                                                if (group) {
                                                                    if (!group.criteria) group.criteria = {};
                                                                    if (!group.criteria[field]) {
                                                                        group.criteria[field] = [];
                                                                    }
                                                                    
                                                                    // Extract text properly from item
                                                                    let itemText;
                                                                    if (item.querySelector) {
                                                                        // item is an element, use querySelector to get the text content of the span
                                                                        itemText = item.querySelector('span') ? item.querySelector('span').textContent : '';
                                                                    } else {
                                                                        // item is already text
                                                                        itemText = item;
                                                                    }
                                                                    
                                                                    console.log('Extracted itemText:', { itemText, originalItem: item, field });
                                                                    
                                                                    if (itemText && !group.criteria[field].includes(itemText)) {
                                                                        group.criteria[field].push(itemText);
                                                                        editor.set(config);
                                                                        console.log('Successfully added item to main group:', { groupId, field, itemText });
                                                                    } else if (!itemText) {
                                                                        console.log('Empty itemText, not adding to main group:', { groupId, field, item });
                                                                    } else {
                                                                        console.log('Item already exists in main group:', { groupId, field, itemText });
                                                                    }
                                                                } else {
                                                                    console.log('Main group not found with id:', groupId);
                                                                }
                                                            } else {
                                                                console.log('No product_restrictions.product_groups found in config');
                                                            }
                                                        }
                                                    };
                                                    
                                                    // Override the removeConfigArrayItem function to work with product groups
                                                    window.removeConfigArrayItemFromGroup = function(container, element) {
                                                        console.log('removeConfigArrayItemFromGroup called with:', { container, element, containerId: container.id });
                                                        
                                                        const containerId = container.id;
                                                        // Updated regex to handle fields with underscores like product_class
                                                        const groupIdMatch = containerId.match(/^group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                                        
                                                        if (groupIdMatch) {
                                                            const groupId = groupIdMatch[1];
                                                            const field = groupIdMatch[2];
                                                            const item = element.querySelector('span').textContent.trim();
                                                            console.log('Main group remove match:', { groupId, field, item });
                                                            
                                                            const config = editor.get();
                                                            if (config.product_restrictions && config.product_restrictions.product_groups) {
                                                                const group = config.product_restrictions.product_groups.find(g => g.id === groupId);
                                                                
                                                                if (group && group.criteria && group.criteria[field]) {
                                                                    group.criteria[field] = group.criteria[field].filter(i => i !== item);
                                                                    if (group.criteria[field].length === 0) {
                                                                        delete group.criteria[field];
                                                                    }
                                                                    editor.set(config);
                                                                    console.log('Successfully removed item from main group:', { groupId, field, item });
                                                                } else {
                                                                    console.log('Main group or criteria not found for removal:', { groupId, field });
                                                                }
                                                            } else {
                                                                console.log('No product_restrictions.product_groups found in config for removal');
                                                            }
                                                        }
                                                        
                                                        element.remove();
                                                    };
                                                    
                                                    // TARGET-SPECIFIC PRODUCT GROUPS FUNCTIONS
                                                    
                                                    // Check if target has legacy format restrictions
                                                    function hasTargetLegacyRestrictions(config, target) {
                                                        if (!config.targets || !config.targets[target] || !config.targets[target].product_restrictions) return false;
                                                        
                                                        const restrictions = config.targets[target].product_restrictions;
                                                        const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                        return legacyFields.some(field => {
                                                            const restriction = restrictions[field];
                                                            return restriction && (
                                                                (restriction.include && restriction.include.length > 0) ||
                                                                (restriction.exclude && restriction.exclude.length > 0)
                                                            );
                                                        });
                                                    }
                                                    
                                                    function showTargetLegacyConversionNotice(target) {
                                                        const conversionNotice = document.getElementById(`target-legacy-conversion-notice-${target}`);
                                                        const legacyContainer = document.getElementById(`legacy-target-product-restrictions-container-${target}`);
                                                        
                                                        if (conversionNotice) {
                                                            conversionNotice.style.display = 'block';
                                                        }
                                                        if (legacyContainer) {
                                                            legacyContainer.style.display = 'block';
                                                        }
                                                    }
                                                    
                                                    function createTargetLegacyInterface(target) {
                                                        const product_restrictions_container = document.getElementById(`legacy-target-product-restrictions-container-${target}`);
                                                        
                                                        // Return early if container doesn't exist
                                                        if (!product_restrictions_container) {
                                                            console.warn(`Legacy target container for ${target} not found`);
                                                            return;
                                                        }
                                                        
                                                        const restrictions = [
                                                            {"field": "product_class", "modal": "productClassModal", "name": "Product Classes", "select_text": "Select Product Classes"},
                                                            {"field": "category", "modal": "categoryModal", "name": "Categories", "select_text": "Select Categories"},
                                                            {"field": "brand", "modal": "brandModal", "name": "Brands", "select_text": "Select Brands"},
                                                            {"field": "sku", "modal": "prompt", "name": "SKU", "select_text": "Add SKU"},
                                                            {"field": "upc", "modal": "prompt", "name": "UPC", "select_text": "Add UPC"} 
                                                        ];

                                                        restrictions.forEach(restriction => {
                                                            const section = document.createElement('div');
                                                            section.className = 'restriction-section';
                                                            
                                                            const header = document.createElement('div');
                                                            header.className = 'g-ffl-restriction-header';
                                                            header.innerHTML = `<strong>${restriction.name}</strong>`;
                                                            section.appendChild(header);

                                                            const container = document.createElement('div');
                                                            container.className = 'restriction-container';

                                                            const includeDiv = document.createElement('div');
                                                            includeDiv.className = 'restriction-item';
                                                            
                                                            var launcher_include = `openModal('${restriction.modal}', 'targets-${target}-product_restrictions-${restriction.field}-include')`;
                                                            var launcher_exclude = `openModal('${restriction.modal}', 'targets-${target}-product_restrictions-${restriction.field}-exclude')`;
                                                            if (restriction.modal == "prompt"){
                                                                launcher_include = `promptAndAddItems(this, '${restriction.field}', 'targets-${target}-product_restrictions-${restriction.field}-include')`;
                                                                launcher_exclude = `promptAndAddItems(this, '${restriction.field}', 'targets-${target}-product_restrictions-${restriction.field}-exclude')`;
                                                            }
                                                            includeDiv.innerHTML = `
                                                                <label for="product_class">Include - <span style="font-size:9pt !important;">
                                                                    <span id="targets-${target}-product_restrictions-${restriction.field}-and-option" onclick="toggleOperandOption('targets-${target}-product_restrictions-${restriction.field}', 'AND', true)">AND</span> | 
                                                                    <span id="targets-${target}-product_restrictions-${restriction.field}-or-option" onclick="toggleOperandOption('targets-${target}-product_restrictions-${restriction.field}', 'OR', true)">OR</span></span>:
                                                                </label>
                                                                <div class="field-container">
                                                                    <div class="selected-items" id="targets-${target}-product_restrictions-${restriction.field}-include"></div>
                                                                    <div class="add-item-container">
                                                                        <span class="add-item" onclick="${launcher_include}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-product_restrictions-${restriction.field}-include'))">Remove All</span>
                                                                    </div>
                                                                </div>`;
                                                            container.appendChild(includeDiv);

                                                            const excludeDiv = document.createElement('div');
                                                            excludeDiv.className = 'restriction-item';
                                                            excludeDiv.innerHTML = `
                                                                <label for="product_class">Exclude:</label>
                                                                <div class="field-container">
                                                                    <div class="selected-items" id="targets-${target}-product_restrictions-${restriction.field}-exclude"></div>
                                                                    <div class="add-item-container">
                                                                        <span class="add-item" onclick="${launcher_exclude}">Select</span>&nbsp;|&nbsp;
                                                                        <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('targets-${target}-product_restrictions-${restriction.field}-exclude'))">Remove All</span>
                                                                    </div>
                                                                </div>`;
                                                            container.appendChild(excludeDiv);
                                                            section.appendChild(container);
                                                            product_restrictions_container.appendChild(section);

                                                            // Now load the data with existing values
                                                            var config = editor.get();
                                                            if (config.targets[target].product_restrictions[restriction.field] && config.targets[target].product_restrictions[restriction.field]['include_operand']){
                                                                toggleOperandOption(`targets-${target}-product_restrictions-${restriction.field}`, config.targets[target].product_restrictions[restriction.field].include_operand);
                                                            }else{
                                                                toggleOperandOption(`targets-${target}-product_restrictions-${restriction.field}`, "AND");
                                                            }
                                                            
                                                            const include_excludes = ["include","exclude"];
                                                            include_excludes.forEach(include_exclude => {
                                                                const selectedFilterContainer = document.getElementById(`targets-${target}-product_restrictions-${restriction.field}-${include_exclude}`);
                                                                if (selectedFilterContainer != null) {
                                                                    selectedFilterContainer.replaceChildren();
                                                                    if (config.targets?.[target]?.product_restrictions?.[restriction.field]?.[include_exclude]) {
                                                                        addSelectedItemsToContainer(selectedFilterContainer, config.targets[target].product_restrictions[restriction.field][include_exclude]);
                                                                    }
                                                                }
                                                            });
                                                        });
                                                    }
                                                    
                                                    function dismissTargetLegacyNotice(target) {
                                                        const conversionNotice = document.getElementById(`target-legacy-conversion-notice-${target}`);
                                                        if (conversionNotice) {
                                                            conversionNotice.style.display = 'none';
                                                        }
                                                    }
                                                    
                                                    function hideTargetProductGroupsSection(target) {
                                                        const section = document.getElementById(`target-product-groups-section-${target}`);
                                                        if (section) {
                                                            section.style.display = 'none';
                                                        }
                                                    }
                                                    
                                                    function showTargetProductGroupsSection(target) {
                                                        const section = document.getElementById(`target-product-groups-section-${target}`);
                                                        if (section) {
                                                            section.style.display = 'block';
                                                        }
                                                    }
                                                    
                                                    // Load existing product groups for a specific target
                                                    function loadTargetProductGroups(target) {
                                                        try {
                                                            const container = document.getElementById(`target-product-groups-container-${target}`);
                                                            
                                                            if (!container) {
                                                                console.log(`Target product groups container for ${target} not found, skipping load`);
                                                                return;
        
                                                            }
                                                            
                                                            container.innerHTML = ''; // Clear existing content
                                                            
                                                            const config = editor.get();
                                                            
                                                            // Check if product_groups exists and has items
                                                            const hasProductGroups = config.targets[target]?.product_restrictions?.product_groups?.length > 0;
                                                            
                                                            if (hasProductGroups) {
                                                                config.targets[target].product_restrictions.product_groups.forEach(group => {
                                                                    addTargetProductGroup(target, group.name, group.type, group.criteria, group.id, false);
                                                                });
                                                            } else {
                                                                // Show empty state
                                                                const emptyState = document.createElement('div');
                                                                emptyState.className = 'empty-state';
                                                                emptyState.innerHTML = `
                                                                    <div style="text-align: center; padding: 40px; color: #666;">
                                                                        <i class="fas fa-layer-group" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
                                                                        <h3 style="margin: 0 0 10px 0; color: #333;">No Product Groups Defined</h3>
                                                                        <p style="margin: 0;">Create your first product group to organize products for this target. <span style="color:blue;font-style:italic">If no product groups are created here, all products will flow through from the main product restriction settings.</span></p>
                                                                    </div>
                                                                `;
                                                                container.appendChild(emptyState);
                                                            }
                                                        } catch (error) {
                                                            console.error(`Error loading target product groups for ${target}:`, error);
                                                        }
                                                    }
                                                    
                                                    // Add a new product group for a specific target
                                                    function addTargetProductGroup(target, groupName = null, groupType = null, criteria = null, groupId = null, isNew = true) {
                                                        if (isNew) {
                                                            groupName = prompt('Enter a name for your product group (e.g., "Firearms", "Hunting Gear"):');
                                                            if (!groupName) return;
                                                            
                                                            groupName = groupName.trim();
                                                            groupId = `target_${target}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                            groupType = 'include'; // Default to include
                                                            criteria = {};
                                                        }
                                                        
                                                        const container = document.getElementById(`target-product-groups-container-${target}`);
                                                        
                                                        // Remove empty state if it exists
                                                        const emptyState = container.querySelector('.empty-state');
                                                        if (emptyState) {
                                                            emptyState.remove();
                                                        }
                                                        
                                                        const div = document.createElement('div');
                                                        div.className = 'group-container product-group';
                                                        div.setAttribute('data-group-id', groupId);
                                                        div.setAttribute('data-target', target);
                                                        
                                                        // Filter criteria based on target type
                                                        // Full criteria for other targets
                                                        let criteriaFields = `
                                                                <!-- Product Class -->
                                                                <div class="form-row">
                                                                    <label>Product Class:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="target_group_${target}_${groupId}_product_class"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('productClassModal', 'target_group_${target}_${groupId}_product_class')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('target_group_${target}_${groupId}_product_class'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Category -->
                                                                <div class="form-row">
                                                                    <label>Category:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="target_group_${target}_${groupId}_category"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('categoryModal', 'target_group_${target}_${groupId}_category')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('target_group_${target}_${groupId}_category'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Brand -->
                                                                <div class="form-row">
                                                                    <label>Brand:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="target_group_${target}_${groupId}_brand"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="openModal('brandModal', 'target_group_${target}_${groupId}_brand')">Select</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('target_group_${target}_${groupId}_brand'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- SKU -->
                                                                <div class="form-row">
                                                                    <label>SKU:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="target_group_${target}_${groupId}_sku"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'sku', 'target_group_${target}_${groupId}_sku')">Add</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('target_group_${target}_${groupId}_sku'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- UPC -->
                                                                <div class="form-row">
                                                                    <label>UPC:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="target_group_${target}_${groupId}_upc"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'upc', 'target_group_${target}_${groupId}_upc')">Add</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('target_group_${target}_${groupId}_upc'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            `;
                                                        
                                                        
                                                        div.innerHTML = `
                                                            <div class="group-header">
                                                                <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${target}_${groupId}', this)">
                                                                    <i class="fas fa-plus accordion-toggle-icon"></i>
                                                                    <span class="group-type-badge ${groupType}">${groupType.toUpperCase()}</span>
                                                                    <span style="display: flex; align-items: center;">
                                                                        <span class="group-name">${groupName}</span>
                                                                        <i class="fas fa-edit edit-group-name" title="Edit group name" onclick="event.stopPropagation(); editTargetGroupName('${target}', '${groupId}', this.previousElementSibling)" style="margin-left: 6px; color: #6c757d; cursor: pointer; font-size: 11px;"></i>
                                                                    </span>
                                                                </div>
                                                                <div class="group-actions">
                                                                    <i class="fas fa-copy copy-link" title="Duplicate Product Group" onclick="duplicateTargetProductGroup('${target}', '${groupId}')"></i>
                                                                    <i class="fas fa-trash-alt remove-link" title="Delete Product Group" onclick="removeTargetProductGroup('${target}', '${groupId}')"></i>
                                                                </div>
                                                            </div>
                                                            <div class="accordion-content" id="${target}_${groupId}" style="display: ${isNew ? 'block' : 'none'};">
                                                                <div id="group-summary-${target}_${groupId}" style="margin-bottom:12px;padding:10px 12px;background:#f0f9ff;border:1px solid #bae6fd;border-radius:6px;font-size:12px;color:#0c4a6e;display:none;">
                                                                </div>

                                                                <!-- Group Type Selection -->
                                                                <div class="form-row">
                                                                    <label>Group Type:</label>
                                                                    <div class="group-type-selector">
                                                                        <label class="radio-label">
                                                                            <input type="radio" name="target_group_type_${target}_${groupId}" value="include" ${groupType === 'include' ? 'checked' : ''} 
                                                                                   onchange="updateTargetGroupType('${target}', '${groupId}', 'include')">
                                                                            <span class="radio-custom include"></span>
                                                                            Include - Products matching this group will be included
                                                                        </label>
                                                                        <label class="radio-label">
                                                                            <input type="radio" name="target_group_type_${target}_${groupId}" value="exclude" ${groupType === 'exclude' ? 'checked' : ''} 
                                                                                   onchange="updateTargetGroupType('${target}', '${groupId}', 'exclude')">
                                                                            <span class="radio-custom exclude"></span>
                                                                            Exclude - Products matching this group will be excluded
                                                                        </label>
                                                                    </div>
                                                                </div>
                                                                
                                                                ${criteriaFields}
                                                                
                                                                <!-- Cost Range -->
                                                                <div class="form-row">
                                                                    <label>Cost:</label>
                                                                    <div class="field-container">
                                                                        <div style="display: flex; align-items: center; gap: 8px;">
                                                                            <div style="flex: 1;">
                                                                                <label for="target_group_${target}_${groupId}_min_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Min ($):</label>
                                                                                <input type="number" id="target_group_${target}_${groupId}_min_cost" class="form-control" 
                                                                                       placeholder="0.00" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateTargetGroupCostRange('${target}', '${groupId}')">
                                                                            </div>
                                                                            <div style="flex: 1;">
                                                                                <label for="target_group_${target}_${groupId}_max_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Max ($):</label>
                                                                                <input type="number" id="target_group_${target}_${groupId}_max_cost" class="form-control" 
                                                                                       placeholder="999999.99" step="0.01" style="width: 100%; font-size: 12px; padding: 4px;" onchange="updateTargetGroupCostRange('${target}', '${groupId}')">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Min Quantity to List -->
                                                                <div class="form-row" id="target_group_${target}_${groupId}_min_quantity_section" style="display: ${groupType === 'include' ? '' : 'none'};">
                                                                    <label>Min Qty to List:</label>
                                                                    <div class="field-container">
                                                                        <div style="display: flex; align-items: center; gap: 8px;">
                                                                            <div style="flex: 1;">
                                                                                <input type="number" id="target_group_${target}_${groupId}_min_quantity_to_list" class="form-control" 
                                                                                       placeholder="1" min="1" step="1" value="1" style="width: 60px; font-size: 12px; padding: 4px;" 
                                                                                       onchange="updateTargetGroupMinQuantityToList('${target}', '${groupId}')" data-autosave="true">
                                                                                <div style="font-size: 11px; color: #666; margin-top: 2px;">
                                                                                    Minimum quantity required for products to be listed (minimum value: 1)
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        `;
                                                        
                                                        container.appendChild(div);
                                                        
                                                        // Load existing criteria if provided
                                                        if (criteria) {
                                                            loadTargetGroupCriteria(target, groupId, criteria);
                                                        }
                                                        
                                                        // If new group, save it to config
                                                        if (isNew) {
                                                            saveTargetProductGroupToConfig(target, groupId, groupName, groupType, {});
                                                            // Expand the new group
                                                            const expandElement = div.querySelector('.accordion-header');
                                                            expandElement.click();
                                                        }

                                                        // Set up MutationObserver for dynamic filter summary
                                                        var tSummaryKey = target + '_' + groupId;
                                                        var tPrefix = 'target_group_' + target + '_' + groupId + '_';
                                                        var tAccContent = document.getElementById(tSummaryKey);
                                                        if (tAccContent) {
                                                            (function(sk, tp) {
                                                                var tObs = new MutationObserver(function() { updateGroupFilterSummary(sk, tp, sk); });
                                                                tObs.observe(tAccContent, { childList: true, subtree: true, characterData: true });
                                                                setTimeout(function() { updateGroupFilterSummary(sk, tp, sk); }, 100);
                                                            })(tSummaryKey, tPrefix);
                                                        }
                                                    }

                                                    // Load criteria into a target group
                                                    function loadTargetGroupCriteria(target, groupId, criteria) {
                                                        const fields = ['product_class', 'category', 'brand', 'sku', 'upc'];
                                                        
                                                        fields.forEach(field => {
                                                            if (criteria[field] && Array.isArray(criteria[field])) {
                                                                const container = document.getElementById(`target_group_${target}_${groupId}_${field}`);
                                                                if (container) {
                                                                    addSelectedItemsToContainer(container, criteria[field]);
                                                                }
                                                            }
                                                        });
                                                        
                                                        // Load cost range if present
                                                        if (criteria.cost) {
                                                            if (criteria.cost.min_cost !== undefined) {
                                                                const minCostInput = document.getElementById(`target_group_${target}_${groupId}_min_cost`);
                                                                if (minCostInput) minCostInput.value = criteria.cost.min_cost;
                                                            }
                                                            if (criteria.cost.max_cost !== undefined) {
                                                                const maxCostInput = document.getElementById(`target_group_${target}_${groupId}_max_cost`);
                                                                if (maxCostInput) maxCostInput.value = criteria.cost.max_cost;
                                                            }
                                                        }
                                                        
                                                        // Load min quantity to list if present
                                                        if (criteria.min_quantity_to_list !== undefined) {
                                                            const minQuantityInput = document.getElementById(`target_group_${target}_${groupId}_min_quantity_to_list`);
                                                            if (minQuantityInput) minQuantityInput.value = criteria.min_quantity_to_list;
                                                        }
                                                    }
                                                    
                                                    // Update target group type in the config and UI
                                                    function updateTargetGroupType(target, groupId, newType) {
                                                        const config = editor.get();
                                                        if (!config.targets[target].product_restrictions.product_groups) {
                                                            config.targets[target].product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            group.type = newType;
                                                            
                                                            // If switching to exclude, remove min_quantity_to_list from criteria
                                                            if (newType === 'exclude' && group.criteria.min_quantity_to_list) {
                                                                delete group.criteria.min_quantity_to_list;
                                                                // Clear the input field as well
                                                                const minQuantityInput = document.getElementById(`target_group_${target}_${groupId}_min_quantity_to_list`);
                                                                if (minQuantityInput) {
                                                                    minQuantityInput.value = '';
                                                                }
                                                            }
                                                            
                                                            editor.set(config);
                                                            
                                                            // Update the badge in the UI
                                                            const badge = document.querySelector(`[data-group-id="${groupId}"][data-target="${target}"] .group-type-badge`);
                                                            if (badge) {
                                                                badge.className = `group-type-badge ${newType}`;
                                                                badge.textContent = newType.toUpperCase();
                                                            }
                                                            
                                                            // Show/hide min_quantity_to_list field based on group type
                                                            const minQuantitySection = document.getElementById(`target_group_${target}_${groupId}_min_quantity_section`);
                                                            if (minQuantitySection) {
                                                                minQuantitySection.style.display = newType === 'include' ? '' : 'none';
                                                            }

                                                            updateGroupFilterSummary(target + '_' + groupId, 'target_group_' + target + '_' + groupId + '_', target + '_' + groupId);
                                                        }
                                                    }

                                                    // Update cost range for a target group
                                                    function updateTargetGroupCostRange(target, groupId) {
                                                        const minCostInput = document.getElementById(`target_group_${target}_${groupId}_min_cost`);
                                                        const maxCostInput = document.getElementById(`target_group_${target}_${groupId}_max_cost`);
                                                        
                                                        if (!minCostInput || !maxCostInput) return;
                                                        
                                                        const minCost = minCostInput.value;
                                                        const maxCost = maxCostInput.value;
                                                        
                                                        const config = editor.get();
                                                        if (!config.targets[target].product_restrictions.product_groups) {
                                                            config.targets[target].product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            if (!group.criteria.cost) {
                                                                group.criteria.cost = {};
                                                            }
                                                            
                                                            if (minCost) {
                                                                group.criteria.cost.min_cost = parseFloat(minCost);
                                                            } else {
                                                                delete group.criteria.cost.min_cost;
                                                            }
                                                            
                                                            if (maxCost) {
                                                                group.criteria.cost.max_cost = parseFloat(maxCost);
                                                            } else {
                                                                delete group.criteria.cost.max_cost;
                                                            }
                                                            
                                                            // Remove cost object if empty
                                                            if (Object.keys(group.criteria.cost).length === 0) {
                                                                delete group.criteria.cost;
                                                            }

                                                            editor.set(config);
                                                            updateGroupFilterSummary(target + '_' + groupId, 'target_group_' + target + '_' + groupId + '_', target + '_' + groupId);
                                                        }
                                                    }

                                                    // Update min quantity to list for a target group
                                                    function updateTargetGroupMinQuantityToList(target, groupId) {
                                                        const minQuantityInput = document.getElementById(`target_group_${target}_${groupId}_min_quantity_to_list`);
                                                        
                                                        if (!minQuantityInput) return;
                                                        
                                                        const minQuantity = minQuantityInput.value;
                                                        
                                                        const config = editor.get();
                                                        if (!config.targets[target].product_restrictions.product_groups) {
                                                            config.targets[target].product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                        if (group) {
                                                            if (minQuantity && minQuantity !== '' && !isNaN(minQuantity)) {
                                                                const quantity = parseInt(minQuantity);
                                                                // Ensure minimum value is 1
                                                                group.criteria.min_quantity_to_list = Math.max(1, quantity);
                                                                // Update the input if value was adjusted
                                                                if (quantity < 1) {
                                                                    minQuantityInput.value = 1;
                                                                }
                                                            } else {
                                                                // Default to 1 if empty or invalid
                                                                group.criteria.min_quantity_to_list = 1;
                                                                minQuantityInput.value = 1;
                                                            }
                                                            
                                                            editor.set(config);
                                                        }
                                                    }
                                                    
                                                    // Save target product group to configuration
                                                    function saveTargetProductGroupToConfig(target, groupId, name, type, criteria) {
                                                        const config = editor.get();
                                                        
                                                        if (!config.targets[target].product_restrictions.product_groups) {
                                                            config.targets[target].product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const group = {
                                                            id: groupId,
                                                            name: name,
                                                            type: type,
                                                            criteria: criteria
                                                        };
                                                        
                                                        config.targets[target].product_restrictions.product_groups.push(group);
                                                        editor.set(config);
                                                    }
                                                    
                                                    // Edit target group name
                                                    function editTargetGroupName(target, groupId, nameElement) {
                                                        const currentName = nameElement.textContent.trim();
                                                        const newName = prompt('Enter new group name:', currentName);
                                                        
                                                        if (newName && newName.trim() !== currentName) {
                                                            const config = editor.get();
                                                            const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            
                                                            if (group) {
                                                                group.name = newName.trim();
                                                                editor.set(config);
                                                                nameElement.textContent = newName.trim();
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Remove target product group
                                                    function removeTargetProductGroup(target, groupId) {
                                                        if (confirm('Are you sure you want to delete this product group?')) {
                                                            const config = editor.get();
                                                            if (config.targets[target].product_restrictions.product_groups) {
                                                                config.targets[target].product_restrictions.product_groups = config.targets[target].product_restrictions.product_groups.filter(g => g.id !== groupId);
                                                                editor.set(config);
                                                            }
                                                            
                                                            // Remove from UI
                                                            const groupElement = document.querySelector(`[data-group-id="${groupId}"][data-target="${target}"]`);
                                                            if (groupElement) {
                                                                groupElement.remove();
                                                            }
                                                            
                                                            // Show empty state if no groups left
                                                            const container = document.getElementById(`target-product-groups-container-${target}`);
                                                            if (container && container.children.length === 0) {
                                                                loadTargetProductGroups(target);
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Duplicate target product group
                                                    function duplicateTargetProductGroup(target, groupId) {
                                                        const config = editor.get();
                                                        const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                        
                                                        if (group) {
                                                            const newName = prompt('Enter a name for the duplicated group:', group.name + ' (Copy)');
                                                            if (newName) {
                                                                const newGroupId = `target_${target}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
                                                                const criteria = JSON.parse(JSON.stringify(group.criteria)); // Deep copy
                                                                
                                                                addTargetProductGroup(target, newName, group.type, criteria, newGroupId, false);
                                                                // Save the duplicated group to config since isNew=false won't trigger auto-save
                                                                saveTargetProductGroupToConfig(target, newGroupId, newName, group.type, criteria);
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Override the addSelectedItemToContainer function to work with target groups
                                                    window.addSelectedItemToTargetGroup = function(containerId, text, value = null) {
                                                        const container = document.getElementById(containerId);
                                                        if (!container) return;
                                                        
                                                        const targetGroupMatch = containerId.match(/target_group_([^_]+)_([^_]+)_(.+)/);
                                                        
                                                        if (targetGroupMatch) {
                                                            const target = targetGroupMatch[1];
                                                            const groupId = targetGroupMatch[2];
                                                            const field = targetGroupMatch[3];
                                                            const item = value || text;
                                                            
                                                            const config = editor.get();
                                                            if (!config.targets[target].product_restrictions.product_groups) {
                                                                config.targets[target].product_restrictions.product_groups = [];
                                                            }
                                                            
                                                            const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            
                                                            if (group) {
                                                                if (!group.criteria[field]) {
                                                                    group.criteria[field] = [];
                                                                }
                                                                
                                                                if (!group.criteria[field].includes(item)) {
                                                                    group.criteria[field].push(item);
                                                                    editor.set(config);
                                                                    
                                                                    // Add to UI
                                                                    const span = document.createElement('span');
                                                                    span.className = 'selected-item';
                                                                    span.innerHTML = `<span>${text}</span><i class="fas fa-times" onclick="removeConfigArrayItemFromTargetGroup(document.getElementById('${containerId}'), this.parentElement)"></i>`;
                                                                    container.appendChild(span);
                                                                }
                                                            }
                                                        }
                                                    };
                                                    
                                                    // Override the removeConfigArrayItem function for target groups
                                                    window.removeConfigArrayItemFromTargetGroup = function(container, element) {
                                                        const containerId = container.id;
                                                        const targetGroupMatch = containerId.match(/^target_group_([^_]+)_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                                        
                                                        if (targetGroupMatch) {
                                                            const target = targetGroupMatch[1];
                                                            const groupId = targetGroupMatch[2];
                                                            const field = targetGroupMatch[3];
                                                            const item = element.querySelector('span').textContent.trim();
                                                            
                                                            const config = editor.get();
                                                            if (config.targets[target].product_restrictions.product_groups) {
                                                                const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                                
                                                                if (group && group.criteria[field]) {
                                                                    group.criteria[field] = group.criteria[field].filter(i => i !== item);
                                                                    if (group.criteria[field].length === 0) {
                                                                        delete group.criteria[field];
                                                                    }
                                                                    editor.set(config);
                                                                }
                                                            }
                                                        }
                                                        
                                                        element.remove();
                                                    };
                                                    
                                                    // Target legacy conversion functions
                                                    function convertTargetLegacyRestrictions(target) {
                                                        const config = editor.get();
                                                        
                                                        if (!config.targets[target].product_restrictions.product_groups) {
                                                            config.targets[target].product_restrictions.product_groups = [];
                                                        }
                                                        
                                                        const legacyFields = ['sku', 'upc', 'brand', 'product_class', 'category'];
                                                        
                                                        // First, collect all include groups
                                                        legacyFields.forEach(field => {
                                                            const restriction = config.targets[target].product_restrictions[field];
                                                            if (!restriction) return;
                                                            
                                                            // Create include group if there are include items
                                                            if (restriction.include && restriction.include.length > 0) {
                                                                // Create a descriptive name based on the values
                                                                let descriptiveName = '';
                                                                const values = restriction.include;
                                                                const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                
                                                                if (values.length === 1) {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values[0]}`;
                                                                } else if (values.length <= 3) {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values.join(', ')}`;
                                                                } else {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                }
                                                                
                                                                const includeGroup = {
                                                                    id: `target_${target}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                    name: descriptiveName,
                                                                    type: 'include',
                                                                    criteria: {
                                                                        [field]: restriction.include
                                                                    }
                                                                };
                                                                config.targets[target].product_restrictions.product_groups.push(includeGroup);
                                                            }
                                                        });
                                                        
                                                        // Then, collect all exclude groups
                                                        legacyFields.forEach(field => {
                                                            const restriction = config.targets[target].product_restrictions[field];
                                                            if (!restriction) return;
                                                            
                                                            // Create exclude group if there are exclude items
                                                            if (restriction.exclude && restriction.exclude.length > 0) {
                                                                // Create a descriptive name based on the values
                                                                let descriptiveName = '';
                                                                const values = restriction.exclude;
                                                                const fieldDisplayName = field.charAt(0).toUpperCase() + field.slice(1).replace('_', ' ');
                                                                
                                                                if (values.length === 1) {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values[0]}`;
                                                                } else if (values.length <= 3) {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values.join(', ')}`;
                                                                } else {
                                                                    descriptiveName = `${target} ${fieldDisplayName}: ${values.slice(0, 2).join(', ')} + ${values.length - 2} more`;
                                                                }
                                                                
                                                                const excludeGroup = {
                                                                    id: `target_${target}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                                                                    name: descriptiveName,
                                                                    type: 'exclude',
                                                                    criteria: {
                                                                        [field]: restriction.exclude
                                                                    }
                                                                };
                                                                config.targets[target].product_restrictions.product_groups.push(excludeGroup);
                                                            }
                                                        });
                                                        
                                                        // Clear the legacy fields
                                                        legacyFields.forEach(field => {
                                                            delete config.targets[target].product_restrictions[field];
                                                        });
                                                        
                                                        // Update the configuration
                                                        editor.set(config);
                                                        
                                                        // Hide legacy notice and container
                                                        document.getElementById(`target-legacy-conversion-notice-${target}`).style.display = 'none';
                                                        document.getElementById(`legacy-target-product-restrictions-container-${target}`).style.display = 'none';
                                                        
                                                        // Show Product Groups section and load the new product groups interface
                                                        showTargetProductGroupsSection(target);
                                                        loadTargetProductGroups(target);
                                                        
                                                        alert(`Legacy restrictions for ${target} have been successfully converted to Product Groups! Please review for accuracy before Savings changes. To revert, refresh your browser.`);
                                                    }
                                                    
                                                    // Override the removeConfigArrayItem function for distributor groups
                                                    window.removeConfigArrayItemFromDistributorGroup = function(container, element) {
                                                        console.log('removeConfigArrayItemFromDistributorGroup called with:', { container, element, containerId: container.id });
                                                        
                                                        const containerId = container.id;
                                                        const distributorGroupMatch = containerId.match(/^distributor_group_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                                        
                                                        if (distributorGroupMatch) {
                                                            const groupIdPart = distributorGroupMatch[1];
                                                            const field = distributorGroupMatch[2];
                                                            const item = element.querySelector('span').textContent.trim();
                                                            console.log('Distributor group remove match:', { groupIdPart, field, item });
                                                            
                                                            const config = editor.get();
                                                            let targetDistributor = null;
                                                            
                                                            // Find the distributor by looking for the group in all distributors
                                                            for (const distributor in config.distributors) {
                                                                if (config.distributors[distributor].product_restrictions?.product_groups?.find(g => g.id === groupIdPart)) {
                                                                    targetDistributor = distributor;
                                                                    break;
                                                                }
                                                            }
                                                            
                                                            if (targetDistributor) {
                                                                const group = config.distributors[targetDistributor].product_restrictions.product_groups.find(g => g.id === groupIdPart);
                                                                
                                                                if (group && group.criteria && group.criteria[field]) {
                                                                    group.criteria[field] = group.criteria[field].filter(i => i !== item);
                                                                    if (group.criteria[field].length === 0) {
                                                                        delete group.criteria[field];
                                                                    }
                                                                    editor.set(config);
                                                                    console.log('Successfully removed item from distributor group:', { targetDistributor, groupId: groupIdPart, field, item });
                                                                } else {
                                                                    console.log('Distributor group or criteria not found for removal:', { targetDistributor, groupId: groupIdPart, field });
                                                                }
                                                            } else {
                                                                console.log('No distributor found with group id for removal:', groupIdPart);
                                                            }
                                                        }
                                                        
                                                        element.remove();
                                                    };
                                                    
                                                    // Add config array item to target group
                                                    function addConfigArrayItemToTargetGroup(container, item) {
                                                        console.log('addConfigArrayItemToTargetGroup called with:', { container, item, containerId: container.id });
                                                        
                                                        const containerId = container.id;
                                                        const targetGroupMatch = containerId.match(/^target_group_([^_]+)_(.+)_(product_class|sku|upc|category|brand|cost)$/);
                                                        
                                                        if (targetGroupMatch) {
                                                            const target = targetGroupMatch[1];
                                                            const groupId = targetGroupMatch[2];
                                                            const field = targetGroupMatch[3];
                                                            console.log('Target group match:', { target, groupId, field });
                                                            
                                                            var itemText = null;
                                                            if (item.querySelector) {
                                                                // item is an element, use querySelector to get the text content of the span
                                                                itemText = item.querySelector('span') ? item.querySelector('span').textContent : '';
                                                            } else {
                                                                // item is already text
                                                                itemText = item;
                                                            }
                                                            
                                                            const config = editor.get();
                                                            if (!config.targets) config.targets = {};
                                                            if (!config.targets[target]) config.targets[target] = {};
                                                            if (!config.targets[target].product_restrictions.product_groups) {
                                                                config.targets[target].product_restrictions.product_groups = [];
                                                            }
                                                            
                                                            const group = config.targets[target].product_restrictions.product_groups.find(g => g.id === groupId);
                                                            
                                                            if (group) {
                                                                if (!group.criteria) group.criteria = {};
                                                                if (!group.criteria[field]) {
                                                                    group.criteria[field] = [];
                                                                }
                                                                
                                                                if (!group.criteria[field].includes(itemText)) {
                                                                    group.criteria[field].push(itemText);
                                                                    editor.set(config);
                                                                    console.log('Successfully added item to target group:', { target, groupId, field, itemText });
                                                                }
                                                            } else {
                                                                console.log('Target group not found with id:', groupId);
                                                            }
                                                        }
                                                    }

                                                    
                                                    // Initialize the product restrictions interface when the page loads
                                                    // This will be called after the editor is initialized
                                                </script>
                                            </div>
                                            <div class="tab-pane fade" id="ai-product-info" role="tabpanel" aria-labelledby="ai-product-info-tab">
                                                <!-- AI Product Info Configuration Content -->
                                                
                                                <!-- Header Section with Tokens and Process Button -->
                                                <div class="row" style="margin: 10px 0 10px 0; position: relative;">
                                                    <div class="col-md-12">
                                                        <!-- AI Solution Summary with Full Width -->
                                                        <div class="helperDialog gffc-ai-summary" style="margin: 0; padding: 12px 280px 12px 15px; background: #f0f8ff; border-left: 4px solid #0073aa; position: relative;">
                                                            <strong style="color: #0073aa; display: flex; align-items: center; margin-bottom: 6px; font-size: 15px;">
                                                                <i class="fas fa-robot" style="margin-right: 6px;"></i>AI-Powered Product Info (Improved Titles, Descriptions, SEO, and add Related YouTube Videos!)
                                                            </strong>
                                                            <div style="font-size: 13px; line-height: 1.3; color: #333;">
                                                                Automatically enhance your product titles and descriptions with AI-generated content including detailed specifications, and features. 
                                                                <strong>Includes SEO optimization</strong>, <strong>Related Product YouTube Videos</strong>, Open Graph data, and structured schema markup to improve search engine visibility and <strong><u>Drive more traffic to your site</u></strong>.
                                                                <span id="try-for-free-prompt" style="display: none; margin-left: 12px; font-size: 11px; color: #ff6b35; font-weight: bold; animation: pulse 2s infinite;">
                                                                You can purchase Free Tokens to try it out, also checkout the video in the Help Center.
                                                                </span>
                                                            </div>
                                                            
                                                            <!-- Overlaid Token Count on Right -->
                                                            <div class="gffc-ai-token-card" style="position: absolute; top: 12px; right: 15px; width: 250px;">
                                                                <div class="g-ffl-metric-card blue" style="display: inline-flex; width: 100%; max-width: none;">
                                                                    <div class="metric-icon"><i class="fas fa-coins"></i></div>
                                                                    <div class="metric-content" style="width: 100%;">
                                                                        <div class="metric-number" id="ai-tokens-display">Loading...</div>
                                                                        <div class="metric-label" style="display: flex; flex-direction: column; gap: 4px;">
                                                                            <span>FFL Cockpit AI Tokens</span>
                                                                            <div style="display: flex; align-items: center; gap: 6px;">
                                                                                <a href="<?php echo esc_attr($this->get_purchase_url($gFFLCockpitKey)); ?>" target="_blank" style="font-size: 9px; color: #0073aa; text-decoration: none; font-weight: 500; white-space: nowrap;">
                                                                                    <i class="fas fa-shopping-cart" style="margin-right: 2px;"></i>Buy tokens
                                                                                </a>
                                                                                <span style="color:#cbd5e1;font-size:9px;">|</span>
                                                                                <a href="#" onclick="event.preventDefault();document.getElementById('gffc-earn-tokens-modal').style.display='flex';" style="font-size: 9px; color: #10b981; text-decoration: none; font-weight: 600; white-space: nowrap;">
                                                                                    <i class="fas fa-coins" style="margin-right: 2px;"></i>Earn tokens
                                                                                </a>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="main-container">
                                                    <div class="right-container" style="width: 100%;">
                                                        <div class="row" style="margin: 0;">
                                                            <div class="col-md-6 gffc-ai-col" style="padding: 0 15px 0 0;">
                                                                <div class="restriction-section">
                                                                    <div class="g-ffl-restriction-header" style="display: flex; justify-content: space-between; align-items: center;">
                                                                        <strong><span style="background-color: #0073aa; color: white; padding: 3px 8px; border-radius: 3px; font-size: 11px; margin-right: 8px;">STEP 1</span>Create AI Prompts</strong>
                                                                        <button type="button" class="button button-secondary" onclick="addAIPrompt(null, null, true)" style="font-size: 12px;">
                                                                            <i class="fas fa-plus"></i> Add AI Prompt
                                                                        </button>
                                                                    </div>
                                                                    <div class="helperDialog" style="margin-bottom: 15px; font-size: 13px;">
                                                                        <strong>Create AI prompts</strong> to enhance product descriptions and add specifications. 
                                                                        Focus your prompt on the specific content you want for the product description. All other prompt instructions are standardized to ensure the format returned is correct.
                                                                    </div>
                                                                    <div id="ai-prompt-container"></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6 gffc-ai-col" style="padding: 0 0 0 15px;">
                                                                <div class="restriction-section">
                                                                    <div class="g-ffl-restriction-header" style="display: flex; justify-content: space-between; align-items: center;">
                                                                        <strong><span style="background-color: #28a745; color: white; padding: 3px 8px; border-radius: 3px; font-size: 11px; margin-right: 8px;">STEP 2</span>Create Product Groups</strong>
                                                                        <button type="button" class="button button-secondary" onclick="addAIProductGroup(null, null, true)" style="font-size: 12px;">
                                                                            <i class="fas fa-plus"></i> Add Product Group
                                                                        </button>
                                                                    </div>
                                                                    <div class="helperDialog" style="margin-bottom: 15px; font-size: 13px;">
                                                                        <strong>Create product groups</strong> to define which products get enhanced. Use filters like brands, categories, SKUs, or UPCs to target specific products, then <strong>assign an AI prompt</strong> to each group.
                                                                    </div>
                                                                    <div id="ai-product-group-container"></div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- AI Prompt Test Modal -->
                                                <div id="aiPromptTestModal" class="modal">
                                                    <div class="cockpit-modal-content">
                                                        <span class="close" onclick="closeModal('aiPromptTestModal')">&times;</span>
                                                        <h2>Test AI Prompt</h2>
                                                        <div id="test-prompt-content">
                                                            <p><strong>Prompt:</strong> <span id="test-prompt-text"></span></p>
                                                            <p><strong>Product Restrictions:</strong> <span id="test-restrictions-text"></span></p>
                                                            
                                                            <div style="margin: 20px 0;">
                                                                <label for="test-sample-products">Select sample products to test (max 5):</label>
                                                                <select id="test-sample-products" multiple style="width: 100%; height: 120px; margin-top: 5px;">
                                                                    <!-- Options will be populated dynamically -->
                                                                </select>
                                                            </div>
                                                            
                                                            <button type="button" class="button button-primary" onclick="runAIPromptTest()" id="run-test-btn">
                                                                <i class="fas fa-play"></i> Run Test
                                                            </button>
                                                            
                                                            <div id="test-results-container" style="margin-top: 20px; display: none;">
                                                                <h3>Test Results</h3>
                                                                <div id="test-results-content" style="background-color: #f9f9f9; padding: 15px; border-radius: 5px; max-height: 400px; overflow-y: auto;">
                                                                    <!-- Test results will be displayed here -->
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <script>
                                                    let aiPromptCounter = 0;
                                                    let aiProductGroupCounter = 0;
                                                    let currentTestPromptId = null;
                                                    let currentTestGroupId = null;
                                                    let aiConfigurationLoaded = false; // Flag to prevent duplicate loading
                                                    let aiTabInitialized = false; // Flag to track if AI tab has been initialized
                                                    
                                                    // Function to initialize AI tab when accessed
                                                    window.ensureAITabInitialized = function() {
                                                        if (!aiTabInitialized) {
                                                            // Reset the configuration loaded flag to allow fresh loading
                                                            aiConfigurationLoaded = false;
                                                            loadExistingAIConfiguration();
                                                            loadAITokens(); // Load tokens when tab is accessed
                                                            aiTabInitialized = true;
                                                        }
                                                    };
                                                    
                                                    // Load AI tokens on tab load
                                                    async function loadAITokens() {
                                                        try {
                                                            // Get the current API key from the form field (which may be a loaded user's key)
                                                            const currentApiKey = document.getElementById('g_ffl_cockpit_key').value;
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({ "action": "get_ai_token_quota", "data": {
                                                                        "api_key": currentApiKey
                                                                    }})
                                                            });
                                                            
                                                            const data = await response.json();
                                                            if (data && data.quota !== undefined) {
                                                                const tokenCount = Math.round(data.quota);
                                                                const isLowTokenCount = tokenCount < 5000;
                                                                const hasZeroTokens = tokenCount === 0;
                                                                
                                                                // Update token display
                                                                const tokenDisplay = document.getElementById('ai-tokens-display');
                                                                const tryForFreePrompt = document.getElementById('try-for-free-prompt');
                                                                tokenDisplay.textContent = tokenCount.toLocaleString();
                                                                
                                                                // Show/hide "Try it for free" prompt based on token count
                                                                if (tryForFreePrompt) {
                                                                    tryForFreePrompt.style.display = hasZeroTokens ? 'inline' : 'none';
                                                                }
                                                                
                                                                // Update styling based on token count
                                                                const metricCard = tokenDisplay.closest('.g-ffl-metric-card');
                                                                const purchaseLink = metricCard.querySelector('a[href*="ai-tokens"]');
                                                                
                                                                if (isLowTokenCount) {
                                                                    // Make token count red
                                                                    tokenDisplay.style.color = '#dc3545';
                                                                    tokenDisplay.style.fontWeight = 'bold';
                                                                    
                                                                    // Change card to red theme
                                                                    metricCard.classList.remove('blue');
                                                                    metricCard.classList.add('red');
                                                                    
                                                                    // Highlight purchase link
                                                                    if (purchaseLink) {
                                                                        purchaseLink.style.color = '#fff';
                                                                        purchaseLink.style.backgroundColor = '#dc3545';
                                                                        purchaseLink.style.padding = '4px 8px';
                                                                        purchaseLink.style.borderRadius = '4px';
                                                                        purchaseLink.style.fontWeight = 'bold';
                                                                        purchaseLink.style.animation = 'pulse 2s infinite';
                                                                        purchaseLink.style.textDecoration = 'none';
                                                                        purchaseLink.title = 'Urgent: Purchase tokens to continue using AI features';
                                                                    }
                                                                } else {
                                                                    // Reset to normal styling for positive tokens
                                                                    tokenDisplay.style.color = '';
                                                                    tokenDisplay.style.fontWeight = '';
                                                                    
                                                                    // Reset card to blue theme
                                                                    metricCard.classList.remove('red');
                                                                    metricCard.classList.add('blue');
                                                                    
                                                                    // Reset purchase link
                                                                    if (purchaseLink) {
                                                                        purchaseLink.style.color = '#0073aa';
                                                                        purchaseLink.style.backgroundColor = '';
                                                                        purchaseLink.style.padding = '';
                                                                        purchaseLink.style.borderRadius = '';
                                                                        purchaseLink.style.fontWeight = '500';
                                                                        purchaseLink.style.animation = '';
                                                                        purchaseLink.style.textDecoration = 'none';
                                                                        purchaseLink.title = '';
                                                                    }
                                                                }
                                                                
                                                                // Store token count globally for use in other functions
                                                                window.currentTokenCount = tokenCount;
                                                                
                                                                // Update button states based on token count
                                                                updateButtonStates();
                                                            } else {
                                                                // No tokens available - treat the same as zero tokens
                                                                const tokenDisplay = document.getElementById('ai-tokens-display');
                                                                const tryForFreePrompt = document.getElementById('try-for-free-prompt');
                                                                tokenDisplay.textContent = '0';
                                                                
                                                                // Show "Try it for free" prompt
                                                                if (tryForFreePrompt) {
                                                                    tryForFreePrompt.style.display = 'inline';
                                                                }
                                                                
                                                                // Apply zero tokens styling
                                                                const metricCard = tokenDisplay.closest('.g-ffl-metric-card');
                                                                const purchaseLink = metricCard.querySelector('a[href*="ai-tokens"]');
                                                                
                                                                // Make token count red
                                                                tokenDisplay.style.color = '#dc3545';
                                                                tokenDisplay.style.fontWeight = 'bold';
                                                                
                                                                // Change card to red theme
                                                                metricCard.classList.remove('blue');
                                                                metricCard.classList.add('red');
                                                                
                                                                // Highlight purchase link
                                                                if (purchaseLink) {
                                                                    purchaseLink.style.color = '#fff';
                                                                    purchaseLink.style.backgroundColor = '#dc3545';
                                                                    purchaseLink.style.padding = '4px 8px';
                                                                    purchaseLink.style.borderRadius = '4px';
                                                                    purchaseLink.style.fontWeight = 'bold';
                                                                    purchaseLink.style.animation = 'pulse 2s infinite';
                                                                    purchaseLink.style.textDecoration = 'none';
                                                                    purchaseLink.title = 'Urgent: Purchase tokens to continue using AI features';
                                                                }
                                                                
                                                                // Store token count globally for use in other functions
                                                                window.currentTokenCount = 0;
                                                                
                                                                // Update button states based on token count
                                                                updateButtonStates();
                                                            }
                                                        } catch (error) {
                                                            console.error('Error loading AI tokens:', error);
                                                            document.getElementById('ai-tokens-display').textContent = 'Error loading';
                                                        }
                                                    }
                                                    
                                                    // Collapse all prompts except the specified one
                                                    function expandPrompt(promptId, promptElement) {
                                                        const promptContainer = document.getElementById('ai-prompt-container');
                                                        const allPrompts = promptContainer.querySelectorAll('.group-container .accordion-content');
                                                        const targetContent = document.getElementById(promptId);
                                                        
                                                        allPrompts.forEach(prompt => {
                                                            if (prompt !== targetContent) {
                                                                prompt.style.display = 'none';
                                                                const icon = prompt.previousElementSibling.querySelector('.accordion-toggle-icon');
                                                                if (icon) {
                                                                    icon.classList.add('fa-plus');
                                                                    icon.classList.remove('fa-minus');
                                                                }
                                                            }
                                                        });
                                                        
                                                        if (targetContent) {
                                                            targetContent.style.display = 'block';
                                                            const icon = promptElement.querySelector('.accordion-toggle-icon');
                                                            if (icon) {
                                                                icon.classList.remove('fa-plus');
                                                                icon.classList.add('fa-minus');
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Collapse all product groups except the specified one
                                                    function expandProductGroup(groupId, groupElement) {
                                                        const groupContainer = document.getElementById('ai-product-group-container');
                                                        const allGroups = groupContainer.querySelectorAll('.group-container .accordion-content');
                                                        const targetContent = document.getElementById(groupId);
                                                        
                                                        allGroups.forEach(group => {
                                                            if (group !== targetContent) {
                                                                group.style.display = 'none';
                                                                const icon = group.previousElementSibling.querySelector('.accordion-toggle-icon');
                                                                if (icon) {
                                                                    icon.classList.add('fa-plus');
                                                                    icon.classList.remove('fa-minus');
                                                                }
                                                            }
                                                        });
                                                        
                                                        if (targetContent) {
                                                            targetContent.style.display = 'block';
                                                            const icon = groupElement.querySelector('.accordion-toggle-icon');
                                                            if (icon) {
                                                                icon.classList.remove('fa-plus');
                                                                icon.classList.add('fa-minus');
                                                            }
                                                        }
                                                    }
                                                    
                                                    // Add new AI prompt (separate from product groups)
                                                    function addAIPrompt(promptName = null, promptConfig = null, isNew = false, parent = null) {
                                                        if (isNew && promptName == null) {
                                                            // If duplicating from a parent, suggest a default name
                                                            let suggestedName = parent ? `${parent}_copy` : '';
                                                            promptName = prompt(`Enter your AI prompt name (e.g., Enhanced Descriptions, SEO Content):`, suggestedName);
                                                            if (promptName == null) {
                                                                return;
                                                            } else {
                                                                promptName = promptName.replace(/[^a-zA-Z0-9-\s]/g, "").replace(/[-\s]/g, "_");
                                                            }
                                                            
                                                            var config = editor.get();
                                                            if (!config.ai_product_info) {
                                                                config.ai_product_info = {};
                                                            }
                                                            if (!config.ai_product_info.prompts) {
                                                                config.ai_product_info.prompts = {};
                                                            }
                                                            
                                                            // Ensure unique prompt name
                                                            let originalPromptName = promptName;
                                                            let counter = 1;
                                                            while (config.ai_product_info.prompts[promptName]) {
                                                                promptName = `${originalPromptName}_${counter}`;
                                                                counter++;
                                                            }
                                                            
                                                            if (parent != null) {
                                                                config.ai_product_info.prompts[promptName] = JSON.parse(JSON.stringify(config.ai_product_info.prompts[parent]));
                                                                config.ai_product_info.prompts[promptName].name = promptName.replace(/_/g, ' ');
                                                            } else {
                                                                config.ai_product_info.prompts[promptName] = {
                                                                    name: promptName.replace(/_/g, ' '),                                                                prompt: `### Copy Rules
- Tone: confident, professional, no fluff.
- Intro paragraph: factual, 2–4 sentences.
- Accurately reflect the product's function and appeal within a real-world context (e.g., EDC, home defense, precision shooting, hunting).
- Stay compliant with federal firearms regulations and U.S. e-commerce practices.
- Appeal to a core demographic of informed, no-nonsense, freedom-loving shooters who value high-performance gear and honest descriptions.
- Maintain a confident, professional, and knowledgeable tone. Avoid sensationalism but remain engaging and accurate.
- Key Specifications: an <h2>Key Specifications</h2> followed by <ul> of up to 10 items. 
    Each <li> is a single readable sentence that bolds the **value** (not the label) using <b>...</b> at least once. 
    Example: "The barrel measures <b>16.1 inches</b> for balanced handling."
- After the </ul> add a <br> line.
- Closing paragraph: Do not repeat the intro. Write a compelling, professional, and engaging paragraph that entices the customer to purchase the product. DO not include any language about confirming the product or contacting the dealer, just talk about the product`
                                                                };
                                                            }
                                                            editor.set(config);
                                                            config = editor.get();
                                                            promptConfig = config.ai_product_info.prompts[promptName];
                                                        }
                                                        
                                                        const container = document.getElementById('ai-prompt-container');
                                                        const div = document.createElement('div');
                                                        div.className = 'group-container';
                                                        var promptId = `ai-prompt-${promptName ? promptName : Date.now()}`;
                                                        
                                                        div.innerHTML = `
                                                            <div class="group-header">
                                                                <div style="cursor:pointer;" class="accordion-header" onclick="toggleAccordion('${promptId}', this)">
                                                                    <i class="fas fa-plus accordion-toggle-icon"></i><span id="prompt-header-${promptName}">${promptConfig ? promptConfig.name || promptName : promptName}</span>
                                                                </div>
                                                                <div class="group-actions">
                                                                    <i class="fas fa-copy copy-link" title="Duplicate AI Prompt" onclick="addAIPrompt(null, null, true, '${promptName}')"></i>
                                                                    <i class="fas fa-trash-alt remove-link" title="Delete AI Prompt" onclick="removeAIPrompt(this, '${promptName}')" style="cursor: pointer;"></i>
                                                                </div>
                                                            </div>
                                                            <div class="accordion-content" id="${promptId}" style="display: none;">
                                                                <div class="form-row" style="margin-bottom: 15px;">
                                                                    <label for="ai_product_info-prompts-${promptName}-prompt">AI Prompt:</label>
                                                                    <textarea id="ai_product_info-prompts-${promptName}-prompt" data-autosave="true" wrap="off"
                                                                              style="width: 100%; height: 400px;" 
                                                                              placeholder="Describe the specific content you want for enhanced product descriptions...">${promptConfig ? promptConfig.prompt || '' : ''}</textarea>
                                                                    <p class="description">Focus on describing the specific content and style you want for your enhanced product descriptions.</p>
                                                                </div>
                                                            </div>
                                                        `;
                                                        container.appendChild(div);
                                                        
                                                        // Setup autosave for all fields in this prompt
                                                        setupAutoSave();
                                                        
                                                        if (isNew) {
                                                            // Refresh prompt dropdowns to include new prompt
                                                            refreshPromptDropdowns();
                                                            // Expand the new prompt and collapse others
                                                            setTimeout(() => {
                                                                expandPrompt(promptId, div);
                                                            }, 400);
                                                        }
                                                        
                                                        return promptName;
                                                    }
                                                    
                                                    // Reset configuration loaded flag (called when config changes)
                                                    function resetAIConfigurationFlag() {
                                                        aiConfigurationLoaded = false;
                                                    }
                                                    
                                                    // Update prompt header when name changes
                                                    function updatePromptHeader(promptName, newName) {
                                                        const headerElement = document.getElementById(`prompt-header-${promptName}`);
                                                        if (headerElement) {
                                                            headerElement.textContent = newName || promptName;
                                                        }
                                                    }
                                                    
                                                    // Update product group header when name changes
                                                    function updateProductGroupHeader(groupName, newName) {
                                                        const headerElement = document.getElementById(`group-header-${groupName}`);
                                                        if (headerElement) {
                                                            headerElement.textContent = newName || groupName;
                                                        }
                                                    }
                                                    
                                                    // Update product group prompt indicator in header
                                                    function updateProductGroupPromptIndicator(groupName, promptId) {
                                                        const promptIndicator = document.getElementById(`group-prompt-${groupName}`);
                                                        if (promptIndicator) {
                                                            if (promptId && promptId !== '') {
                                                                const config = editor.get();
                                                                const promptConfig = config.ai_product_info?.prompts?.[promptId];
                                                                const promptName = promptConfig ? promptConfig.name || promptId : promptId;
                                                                promptIndicator.textContent = `${promptName}`;
                                                                promptIndicator.style.color = '#0073aa';
                                                            } else {
                                                                promptIndicator.textContent = 'No prompt assigned';
                                                                promptIndicator.style.color = '#666';
                                                            }
                                                        }
                                                    }
                                                    

                                                    
                                                    // Remove AI prompt
                                                    function removeAIPrompt(link, promptName) {
                                                        // Check if prompt is used by any product groups
                                                        const config = editor.get();
                                                        if (config.ai_product_info && config.ai_product_info.product_groups) {
                                                            const usedByGroups = [];
                                                            for (const groupName in config.ai_product_info.product_groups) {
                                                                const group = config.ai_product_info.product_groups[groupName];
                                                                if (group.assigned_prompt === promptName) {
                                                                    usedByGroups.push(group.name || groupName);
                                                                }
                                                            }
                                                            
                                                            if (usedByGroups.length > 0) {
                                                                alert(`Cannot delete this prompt. It is currently assigned to the following product group(s):\n\n• ${usedByGroups.join('\n• ')}\n\nPlease remove this prompt from all product groups before deleting it.`);
                                                                return;
                                                            }
                                                        }
                                                        
                                                        if (confirm('Are you sure you want to remove this AI prompt?')) {
                                                            if (config.ai_product_info && config.ai_product_info.prompts) {
                                                                delete config.ai_product_info.prompts[promptName];
                                                                editor.set(config);
                                                            }
                                                            const section = link.closest('.group-container');
                                                            section.parentNode.removeChild(section);
                                                            
                                                            // Refresh all prompt dropdowns to remove deleted prompt
                                                            refreshPromptDropdowns();
                                                        }
                                                    }
                                                    
                                                    // Refresh all prompt dropdowns in product groups
                                                    function refreshPromptDropdowns() {
                                                        const config = editor.get();
                                                        const availablePrompts = config.ai_product_info?.prompts || {};
                                                        
                                                        // Find all prompt dropdown selects
                                                        document.querySelectorAll('select[id*="assigned_prompt"]').forEach(dropdown => {
                                                            const currentValue = dropdown.value;
                                                            
                                                            // Clear and repopulate
                                                            dropdown.innerHTML = '<option value="">Select an AI Prompt...</option>';
                                                            Object.entries(availablePrompts).forEach(([promptId, promptConfig]) => {
                                                                const option = document.createElement('option');
                                                                option.value = promptId;
                                                                option.textContent = promptConfig.name || promptId;
                                                                dropdown.appendChild(option);
                                                            });
                                                            
                                                            // Restore previous value if it still exists
                                                            if (availablePrompts[currentValue]) {
                                                                dropdown.value = currentValue;
                                                            }
                                                            
                                                            // Update prompt indicator for this dropdown
                                                            const dropdownId = dropdown.id;
                                                            if (dropdownId.includes('product_groups')) {
                                                                const groupName = dropdownId.split('-')[3]; // Extract group name from ID
                                                                updateProductGroupPromptIndicator(groupName, dropdown.value);
                                                            }
                                                        });
                                                    }
                                                    
                                                    // Add new AI product group (similar to margin groups)
                                                    function addAIProductGroup(groupName = null, groupConfig = null, isNew = false, parent = null) {
                                                        if (isNew && groupName == null) {
                                                            // If duplicating from a parent, suggest a default name
                                                            let suggestedName = '';
                                                            if (parent) {
                                                                // Get current config to check for existing names
                                                                var config = editor.get();
                                                                if (!config.ai_product_info) {
                                                                    config.ai_product_info = {};
                                                                }
                                                                if (!config.ai_product_info.product_groups) {
                                                                    config.ai_product_info.product_groups = {};
                                                                }
                                                                
                                                                // Generate a unique suggested name
                                                                let baseName = `${parent}_copy`;
                                                                suggestedName = baseName;
                                                                let counter = 1;
                                                                while (config.ai_product_info.product_groups[suggestedName]) {
                                                                    suggestedName = `${baseName}_${counter}`;
                                                                    counter++;
                                                                }
                                                            }
                                                            
                                                            groupName = prompt(`Enter your product group name (e.g., Firearms, Ammunition, Optics):`, suggestedName);
                                                            if (groupName == null) {
                                                                return;
                                                            } else {
                                                                groupName = groupName.replace(/[^a-zA-Z0-9-\s]/g, "").replace(/[-\s]/g, "_");
                                                            }
                                                            
                                                            var config = editor.get();
                                                            if (!config.ai_product_info) {
                                                                config.ai_product_info = {};
                                                            }
                                                            if (!config.ai_product_info.product_groups) {
                                                                config.ai_product_info.product_groups = {};
                                                            }
                                                            
                                                            // Ensure unique group name
                                                            let originalGroupName = groupName;
                                                            let counter = 1;
                                                            while (config.ai_product_info.product_groups[groupName]) {
                                                                groupName = `${originalGroupName}_${counter}`;
                                                                counter++;
                                                            }
                                                            
                                                            if (parent != null) {
                                                                config.ai_product_info.product_groups[groupName] = JSON.parse(JSON.stringify(config.ai_product_info.product_groups[parent]));
                                                                config.ai_product_info.product_groups[groupName].name = groupName.replace(/_/g, ' ');
                                                            } else {
                                                                config.ai_product_info.product_groups[groupName] = {
                                                                    name: groupName.replace(/_/g, ' '),
                                                                    assigned_prompt: '', // Changed from array to single string
                                                                    product_restrictions: {
                                                                        product_class: [],
                                                                        distributor: [],
                                                                        category: [],
                                                                        brand: [],
                                                                        sku: [],
                                                                        upc: [],
                                                                        cost_restrictions: {
                                                                            min_cost: '',
                                                                            max_cost: ''
                                                                        }
                                                                    },
                                                                    related_videos: {
                                                                        active: false,
                                                                        video_count: 3,
                                                                        exclude_channel_names: []
                                                                    },
                                                                    disclaimer: {
                                                                        active: false,
                                                                        message: ''
                                                                    }
                                                                };
                                                            }
                                                            editor.set(config);
                                                            config = editor.get();
                                                            groupConfig = config.ai_product_info.product_groups[groupName];
                                                        }
                                                        
                                                        const container = document.getElementById('ai-product-group-container');
                                                        const div = document.createElement('div');
                                                        div.className = 'group-container';
                                                        var groupId = `ai-product-group-${groupName ? groupName : Date.now()}`;
                                                        
                                                        div.innerHTML = `
                                                            <div class="group-header" style="display: flex; align-items: center;">
                                                                <div style="cursor:pointer; display: flex; align-items: center; flex: 1; min-width: 0; margin-right: 8px;" class="accordion-header" onclick="toggleAccordion('${groupId}', this)">
                                                                    <i class="fas fa-plus accordion-toggle-icon" style="margin-right: 8px; flex-shrink: 0;"></i>
                                                                    <div style="display: flex; flex-direction: column; flex: 1; min-width: 0;">
                                                                        <span id="group-header-${groupName}" title="${groupConfig ? groupConfig.name || groupName : groupName}" style="font-weight: normal; font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block;">${groupConfig ? groupConfig.name || groupName : groupName}</span>
                                                                        <small id="group-prompt-${groupName}" title="${groupConfig && groupConfig.assigned_prompt ? (groupConfig.assigned_prompt || 'None') : 'No prompt assigned'}" style="color: #666; font-style: italic; font-size: 10px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block;">${groupConfig && groupConfig.assigned_prompt ? (groupConfig.assigned_prompt || 'None') : 'No prompt assigned'}</small>
                                                                    </div>
                                                                </div>
                                                                <div style="display: flex; align-items: center; flex-shrink: 0;">
                                                                    <button type="button" class="btn btn-sm btn-info" title="Test Product Group" style="margin-right: 4px; padding: 4px 8px;" onclick="testProductGroupWithMockData('${groupName}')">
                                                                        <i class="fas fa-flask"></i> Test
                                                                    </button>
                                                                    <button type="button" class="btn btn-sm btn-success" title="Create Product AI Info" style="margin-right: 4px; padding: 4px 8px;" onclick="processProductGroup('${groupName}')">
                                                                        <i class="fas fa-cogs"></i> Create
                                                                    </button>
                                                                    <button type="button" class="btn btn-sm btn-warning" title="Apply AI Changes to Products" style="margin-right: 4px; padding: 4px 8px;" onclick="showApplyDialog('${groupName}')">
                                                                        <i class="fas fa-check-circle"></i> Apply
                                                                    </button>
                                                                    <i class="fas fa-copy copy-link" title="Duplicate Product Group" style="margin-right: 4px;" onclick="addAIProductGroup(null, null, true, '${groupName}')"></i>
                                                                    <i class="fas fa-trash-alt remove-link" title="Delete Product Group" onclick="removeAIProductGroup(this, '${groupName}')"></i>
                                                                </div>
                                                            </div>
                                                            <div class="accordion-content" id="${groupId}">
                                                                <div class="helperDialog">Configure which products belong to this group and assign an AI prompt to enhance them.</div>
                                                                
                                                                <!-- Job Status Table Container -->
                                                                <div id="job-status-table-${groupName}">
                                                                    <!-- Job status table will be loaded here -->
                                                                </div>
                                                                
                                                                <div class="form-row">
                                                                    <label for="ai_product_info-product_groups-${groupName}-assigned_prompt">Assigned AI Prompt:</label>
                                                                    <select id="ai_product_info-product_groups-${groupName}-assigned_prompt" data-autosave="true" style="width: 100%;" onchange="updateProductGroupPromptIndicator('${groupName}', this.value); autoSave(this);">
                                                                        <option value="">Select an AI Prompt...</option>
                                                                    </select>
                    
                                                                </div>
                                                            </div>
                                                        `;
                                                        container.appendChild(div);
                                                        
                                                        if (groupConfig != null) {
                                                            // Add product restriction filters similar to margin groups
                                                            const filterElements = [
                                                                {"field": "product_class", "modal": "productClassModal", "name": "Product Classes", "select_text": "Select Product Classes"},
                                                                {"field": "category", "modal": "categoryModal", "name": "Categories", "select_text": "Select Categories"},
                                                                {"field": "brand", "modal": "brandModal", "name": "Brands", "select_text": "Select Brands"},
                                                                {"field": "distributor", "modal": "distributorModal", "name": "Distributors", "select_text": "Select Distributors"},
                                                                {"field": "sku", "modal": "prompt", "name": "SKU", "select_text": "Add SKU"},
                                                                {"field": "upc", "modal": "prompt", "name": "UPC", "select_text": "Add UPC"}
                                                            ];
                                                            
                                                            const accordionContent = document.getElementById(groupId);
                                                            
                                                            for (const filterElement of filterElements) {
                                                                const formRow = document.createElement('div');
                                                                formRow.className = 'form-row';
                                                                
                                                                let addItemAction = '';
                                                                if (filterElement.modal === 'prompt') {
                                                                    addItemAction = `promptAndAddItems(this, '${filterElement.field}', 'ai_product_info-product_groups-${groupName}-product_restrictions-${filterElement.field}')`;
                                                                } else {
                                                                    addItemAction = `openModal('${filterElement.modal}', 'ai_product_info-product_groups-${groupName}-product_restrictions-${filterElement.field}')`;
                                                                }
                                                                
                                                                formRow.innerHTML = `
                                                                    <label for="${filterElement.field}">${filterElement.name}:</label>
                                                                    <div class="field-container">
                                                                        <div class="selected-items" id="ai_product_info-product_groups-${groupName}-product_restrictions-${filterElement.field}"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="${addItemAction}">${filterElement.select_text}</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('ai_product_info-product_groups-${groupName}-product_restrictions-${filterElement.field}'))">Remove All</span>
                                                                        </div>
                                                                    </div>
                                                                `;
                                                                accordionContent.appendChild(formRow);
                                                                
                                                                // Load existing items for this filter
                                                                if (groupConfig.product_restrictions && groupConfig.product_restrictions[filterElement.field] && groupConfig.product_restrictions[filterElement.field].length > 0) {
                                                                    const container = document.getElementById(`ai_product_info-product_groups-${groupName}-product_restrictions-${filterElement.field}`);
                                                                    addSelectedItemsToContainer(container, groupConfig.product_restrictions[filterElement.field]);
                                                                }
                                                            }
                                                            
                                                            // Add cost restrictions after UPC field with two-column layout
                                                            const costFormRow = document.createElement('div');
                                                            costFormRow.className = 'form-row';
                                                            
                                                            costFormRow.innerHTML = `
                                                                <label>Cost:</label>
                                                                <div class="field-container">
                                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                                        <div style="flex: 1;">
                                                                            <label for="ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-min_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Min ($):</label>
                                                                            <input type="number" id="ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-min_cost" data-autosave="true" style="width: 100%; font-size: 12px; padding: 4px;" step="0.01" min="0" placeholder="0.00">
                                                                        </div>
                                                                        <div style="flex: 1;">
                                                                            <label for="ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-max_cost" style="font-size: 12px; display: block; margin-bottom: 2px;">Max ($):</label>
                                                                            <input type="number" id="ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-max_cost" data-autosave="true" style="width: 100%; font-size: 12px; padding: 4px;" step="0.01" min="0" placeholder="999999.99">
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            `;
                                                            accordionContent.appendChild(costFormRow);
                                                            
                                                            // Add helper section for Related Videos
                                                            const videoHelperDiv = document.createElement('div');
                                                            videoHelperDiv.className = 'helperDialog';
                                                            videoHelperDiv.innerHTML = '<strong>Related Videos:</strong> Configure how the AI will include relevant product videos and multimedia content in the enhanced descriptions. This can help create more engaging and informative product pages.';
                                                            accordionContent.appendChild(videoHelperDiv);
                                                            
                                                            // Add Related Videos configuration section
                                                            const videoConfigRow = document.createElement('div');
                                                            videoConfigRow.className = 'form-row';
                                                            videoConfigRow.innerHTML = `
                                                                <label>Related Videos:</label>
                                                                <div class="field-container" style="display: flex; flex-direction: column; gap: 2px;">
                                                                    <!-- Active Toggle -->
                                                                    <div style="align-items: center; gap: 8px;">
                                                                        <label class="toggle-switch" style="width: 50px !important; max-width: 50px !important; flex-shrink: 0 !important; display: inline-block !important;">
                                                                            <input type="checkbox" id="ai_product_info-product_groups-${groupName}-related_videos-active" data-autosave="true">
                                                                            <span class="slider"></span>
                                                                        </label>
                                                                    </div>
                                                                    
                                                                    <!-- Video Count -->
                                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                                        <input type="number" id="ai_product_info-product_groups-${groupName}-related_videos-video_count" data-autosave="true" 
                                                                               style="height:25px;width: 50px; padding: 4px;" min="0" max="9" value="3"
                                                                               title="Number of videos to include (0-9)">
                                                                        <span style="color: #666;font-style:italic;"># of videos to include (0-9)</span>
                                                                    </div>
                                                                    
                                                                    <!-- Exclude Channel Names -->
                                                                    <div style="display: flex; flex-direction: column;">
                                                                        <label style="margin-top:5px;flex: 0 0 0;">Excluded Channels:</label>
                                                                        <div class="selected-items" id="ai_product_info-product_groups-${groupName}-related_videos-exclude_channel_names" style="min-height: 30px; padding: 4px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;"></div>
                                                                        <div class="add-item-container">
                                                                            <span class="add-item" onclick="promptAndAddItems(this, 'exclude_channel_names', 'ai_product_info-product_groups-${groupName}-related_videos-exclude_channel_names')">Add Channel Name</span>&nbsp;|&nbsp;
                                                                            <span class="add-item" onclick="removeAllConfigArrayItems(document.getElementById('ai_product_info-product_groups-${groupName}-related_videos-exclude_channel_names'))">Remove All</span>
                                                                        </div>
                                                                        <small style="color: #666; font-style: italic;">Channel names to exclude from video searches (e.g., "UnwantedChannel", "BadContent")</small>
                                                                    </div>
                                                                </div>
                                                            `;
                                                            accordionContent.appendChild(videoConfigRow);
                                                            
                                                            // Add helper section for Disclaimer Message
                                                            const disclaimerHelperDiv = document.createElement('div');
                                                            disclaimerHelperDiv.className = 'helperDialog';
                                                            disclaimerHelperDiv.innerHTML = '<strong>Disclaimer Message:</strong> Configure custom disclaimer text that will be automatically appended to all AI-generated descriptions for products in this group. This is useful for legal disclaimers, safety warnings, or additional product information that should appear consistently across all enhanced descriptions.';
                                                            accordionContent.appendChild(disclaimerHelperDiv);
                                                            
                                                            // Add Disclaimer Message configuration section
                                                            const disclaimerConfigRow = document.createElement('div');
                                                            disclaimerConfigRow.className = 'form-row';
                                                            disclaimerConfigRow.innerHTML = `
                                                                <label>Disclaimer Message:</label>
                                                                <div class="field-container" style="flex-direction: column; gap: 2px;">
                                                                    <!-- Active Toggle -->
                                                                    <div style="display: flex; align-items: center; gap: 8px;">
                                                                        <label class="toggle-switch" style="width: 50px !important; max-width: 50px !important; flex-shrink: 0 !important; display: inline-block !important;">
                                                                            <input type="checkbox" id="ai_product_info-product_groups-${groupName}-disclaimer-active" data-autosave="true">
                                                                            <span class="slider"></span>
                                                                        </label>
                                                                    </div>
                                                                    
                                                                    <!-- Disclaimer Message Text -->
                                                                    <div style="flex-direction: column;">
                                                                        <textarea id="ai_product_info-product_groups-${groupName}-disclaimer-message" data-autosave="true" wrap="off"
                                                                                  style="width: 100%; height: 100px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" 
                                                                                  placeholder="Enter any disclaimer text to append to AI-generated descriptions for this product group..."></textarea>
                                                                        <small style="font-size: 10px; color: #666; font-style: italic;">This text will be automatically appended to all AI-generated product descriptions</small>
                                                                    </div>
                                                                </div>
                                                            `;
                                                            accordionContent.appendChild(disclaimerConfigRow);
                                                            
                                                            // Populate prompt dropdown and set selected value
                                                            const promptDropdown = document.getElementById(`ai_product_info-product_groups-${groupName}-assigned_prompt`);
                                                            const currentConfig = editor.get();
                                                            const availablePrompts = currentConfig.ai_product_info?.prompts || {};
                                                            
                                                            // Clear existing options except first one
                                                            promptDropdown.innerHTML = '<option value="">Select an AI Prompt...</option>';
                                                            
                                                            // Add available prompts
                                                            Object.entries(availablePrompts).forEach(([promptId, promptConfig]) => {
                                                                const option = document.createElement('option');
                                                                option.value = promptId;
                                                                option.textContent = promptConfig.name || promptId;
                                                                promptDropdown.appendChild(option);
                                                            });
                                                            
                                                            // Set selected prompt
                                                            if (groupConfig.assigned_prompt) {
                                                                promptDropdown.value = groupConfig.assigned_prompt;
                                                                // Update the prompt indicator in the header
                                                                updateProductGroupPromptIndicator(groupName, groupConfig.assigned_prompt);
                                                            }
                                                            
                                                            // Load cost restrictions if they exist
                                                            if (groupConfig.product_restrictions && groupConfig.product_restrictions.cost_restrictions) {
                                                                const minCostField = document.getElementById(`ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-min_cost`);
                                                                const maxCostField = document.getElementById(`ai_product_info-product_groups-${groupName}-product_restrictions-cost_restrictions-max_cost`);
                                                                if (minCostField) minCostField.value = groupConfig.product_restrictions.cost_restrictions.min_cost || '';
                                                                if (maxCostField) maxCostField.value = groupConfig.product_restrictions.cost_restrictions.max_cost || '';
                                                            }
                                                            
                                                            // Load related videos configuration
                                                            if (groupConfig.related_videos) {
                                                                const videoActiveField = document.getElementById(`ai_product_info-product_groups-${groupName}-related_videos-active`);
                                                                const videoCountField = document.getElementById(`ai_product_info-product_groups-${groupName}-related_videos-video_count`);
                                                                const excludeChannelsContainer = document.getElementById(`ai_product_info-product_groups-${groupName}-related_videos-exclude_channel_names`);
                                                                
                                                                if (videoActiveField) {
                                                                    videoActiveField.checked = groupConfig.related_videos.active || false;
                                                                }
                                                                if (videoCountField) {
                                                                    videoCountField.value = groupConfig.related_videos.video_count || 3;
                                                                }
                                                                if (excludeChannelsContainer && groupConfig.related_videos.exclude_channel_names && groupConfig.related_videos.exclude_channel_names.length > 0) {
                                                                    addSelectedItemsToContainer(excludeChannelsContainer, groupConfig.related_videos.exclude_channel_names);
                                                                }
                                                            } else {
                                                                // Handle migration from old include_related_videos field
                                                                const videoActiveField = document.getElementById(`ai_product_info-product_groups-${groupName}-related_videos-active`);
                                                                if (videoActiveField && groupConfig.include_related_videos !== undefined) {
                                                                    videoActiveField.checked = groupConfig.include_related_videos || false;
                                                                }
                                                            }
                                                            
                                                            // Load disclaimer message configuration
                                                            if (groupConfig.disclaimer) {
                                                                const disclaimerActiveField = document.getElementById(`ai_product_info-product_groups-${groupName}-disclaimer-active`);
                                                                const disclaimerMessageField = document.getElementById(`ai_product_info-product_groups-${groupName}-disclaimer-message`);
                                                                
                                                                if (disclaimerActiveField) {
                                                                    disclaimerActiveField.checked = groupConfig.disclaimer.active || false;
                                                                }
                                                                if (disclaimerMessageField) {
                                                                    disclaimerMessageField.value = groupConfig.disclaimer.message || '';
                                                                }
                                                            }
                                                            
                                                            // Setup autosave for all fields in this group
                                                            setupAutoSave();
                                                            
                                                            // Load job status table for existing groups
                                                            loadJobStatusTable(groupName);
                                                        }
                                                        
                                                        if (isNew) {
                                                            expandProductGroup(groupId, div);
                                                            setupAutoSave();
                                                        }
                                                        
                                                        return groupName;
                                                    }
                                                    
                                                    // Remove AI product group
                                                    function removeAIProductGroup(link, groupName) {
                                                        if (confirm('Are you sure you want to remove this product group?')) {
                                                            const config = editor.get();
                                                            if (config.ai_product_info && config.ai_product_info.product_groups) {
                                                                delete config.ai_product_info.product_groups[groupName];
                                                                editor.set(config);
                                                            }
                                                            const group = link.closest('.group-container');
                                                            group.parentNode.removeChild(group);
                                                        }
                                                    }
                                                    
                                                    // Check if there are unsaved changes
                                                    function hasUnsavedChanges() {
                                                        if (initialCockpitConfiguration == null) return false;
                                                        const currentConfig = editor.get();
                                                        return JSON.stringify(currentConfig) !== JSON.stringify(initialCockpitConfiguration);
                                                    }
                                                    
                                                    // Update button states based on unsaved changes
                                                    function updateButtonStates() {
                                                        const hasChanges = hasUnsavedChanges();
                                                        const tokenCount = isNaN(Number(window.currentTokenCount)) ? 0 : Number(window.currentTokenCount);
                                                        const hasInsufficientTokens = tokenCount <= 0;
                                                        const shouldDisable = hasChanges || hasInsufficientTokens;
                                                        
                                                        // Disable/enable main process button
                                                        const mainProcessBtn = document.getElementById('process-ai-prompts-btn');
                                                        if (mainProcessBtn) {
                                                            mainProcessBtn.disabled = shouldDisable;
                                                            if (hasChanges) {
                                                                mainProcessBtn.title = 'Save configuration changes before processing';
                                                                mainProcessBtn.style.opacity = '0.6';
                                                            } else if (hasInsufficientTokens) {
                                                                mainProcessBtn.title = 'Insufficient tokens. Please purchase additional tokens.';
                                                                mainProcessBtn.style.opacity = '0.5';
                                                                mainProcessBtn.style.cursor = 'not-allowed';
                                                            } else {
                                                                mainProcessBtn.title = '';
                                                                mainProcessBtn.style.opacity = '1';
                                                                mainProcessBtn.style.cursor = 'pointer';
                                                            }
                                                        }
                                                        
                                                        // Disable/enable individual test and process buttons
                                                        document.querySelectorAll('button[onclick*="testProductGroupWithMockData"], button[onclick*="processProductGroup"]').forEach(btn => {
                                                            const isProcessBtn = btn.onclick.toString().includes('processProductGroup');
                                                            const isTestBtn = btn.onclick.toString().includes('testProductGroupWithMockData');
                                                            
                                                            // Process buttons should be disabled for both unsaved changes and insufficient tokens
                                                            // Test buttons should only be disabled for unsaved changes (they can view historical tests)
                                                            const shouldDisableThisBtn = hasChanges || (isProcessBtn && hasInsufficientTokens);
                                                            
                                                            btn.disabled = shouldDisableThisBtn;
                                                            if (hasChanges) {
                                                                btn.style.opacity = '0.6';
                                                                btn.style.cursor = 'not-allowed';
                                                                if (isTestBtn) {
                                                                    btn.title = 'Save configuration changes before testing';
                                                                } else {
                                                                    btn.title = 'Save configuration changes before processing';
                                                                }
                                                            } else if (isProcessBtn && hasInsufficientTokens) {
                                                                btn.style.opacity = '0.5';
                                                                btn.style.cursor = 'not-allowed';
                                                                btn.title = 'Insufficient tokens. Please purchase additional tokens.';
                                                            } else {
                                                                btn.style.opacity = '1';
                                                                btn.style.cursor = 'pointer';
                                                                if (isTestBtn) {
                                                                    btn.title = 'Test Product Group';
                                                                } else {
                                                                    btn.title = 'Process Product Group';
                                                                }
                                                            }
                                                        });
                                                    }
                                                    
                                                    // Fetch and display job status for a product group
                                                    async function loadJobStatusTable(groupName) {
                                                        const tableContainer = document.getElementById(`job-status-table-${groupName}`);
                                                        if (!tableContainer) return;
                                                        
                                                        // Show loading state with refresh-specific message
                                                        const isRefresh = tableContainer.innerHTML.includes('Recent Processing Jobs');
                                                        tableContainer.innerHTML = `
                                                            <div style="text-align: center; padding: 10px; color: #666;">
                                                                <i class="fas fa-spinner fa-spin"></i> ${isRefresh ? 'Refreshing job history...' : 'Loading job history...'}
                                                            </div>
                                                        `;
                                                        
                                                        try {
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "get_ai_product_info_jobs",
                                                                    "data": {
                                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                                        "product_group_name": groupName
                                                                    }
                                                                })
                                                            });
                                                            
                                                            const data = await response.json();
                                                            
                                                            if (data.success && data.jobs && data.jobs.length > 0) {
                                                                // Create table with job data
                                                                let tableHTML = `
                                                                    <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; margin-bottom: 15px;">
                                                                        <div style="background: #e9ecef; padding: 8px 12px; border-bottom: 1px solid #dee2e6; font-weight: 600; color: #495057; font-size: 13px; display: flex; justify-content: space-between; align-items: center;">
                                                                            <span><i class="fas fa-history" style="margin-right: 6px;"></i>Recent Processing Jobs</span>
                                                                            <button onclick="loadJobStatusTable('${groupName}')" style="background: #007cba; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 4px;" title="Refresh job status" onmouseover="this.style.background='#005a87'" onmouseout="this.style.background='#007cba'">
                                                                                <i class="fas fa-sync-alt" style="font-size: 10px;"></i>Refresh
                                                                            </button>
                                                                        </div>
                                                                        <div style="max-height: 200px; overflow-y: auto;">
                                                                            <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                                                                                <thead style="background: #f1f3f4; position: sticky; top: 0;">
                                                                                    <tr>
                                                                                        <th style="padding: 6px 8px; text-align: left; border-bottom: 1px solid #dee2e6; font-weight: 600;">Status</th>
                                                                                        <th style="padding: 6px 8px; text-align: left; border-bottom: 1px solid #dee2e6; font-weight: 600;">Products</th>
                                                                                        <th style="padding: 6px 8px; text-align: left; border-bottom: 1px solid #dee2e6; font-weight: 600;">Started</th>
                                                                                        <th style="padding: 6px 8px; text-align: left; border-bottom: 1px solid #dee2e6; font-weight: 600;">Completed</th>
                                                                                        <th style="padding: 6px 8px; text-align: center; border-bottom: 1px solid #dee2e6; font-weight: 600;">Run Type</th>
                                                                                    </tr>
                                                                                </thead>
                                                                                <tbody>
                                                                `;
                                                                
                                                                // Sort jobs by start_time descending (most recent first)
                                                                const sortedJobs = data.jobs.sort((a, b) => new Date(b.start_time) - new Date(a.start_time));
                                                                
                                                                sortedJobs.slice(0, 10).forEach(job => { // Show last 10 jobs
                                                                    const startTime = new Date(job.start_time + 'Z').toLocaleString();
                                                                    const endTime = job.end_time ? new Date(job.end_time + 'Z').toLocaleString() : '-';
                                                                    const isTestRun = job.is_test_run ? true : false;
                                                                    
                                                                    // Enhanced status styling with better color coding
                                                                    let statusColor = '#6c757d';
                                                                    let statusBg = '#f8f9fa';
                                                                    let statusIcon = 'fas fa-question-circle';
                                                                    let statusText = job.status || 'Unknown';
                                                                    
                                                                    if (job.status === 'completed' || job.status === 'Succeeded') {
                                                                        statusColor = '#155724';
                                                                        statusBg = '#d4edda';
                                                                        statusIcon = 'fas fa-check-circle';
                                                                        statusText = 'Completed';
                                                                    } else if (job.status === 'running' || job.status === 'Running') {
                                                                        statusColor = '#004085';
                                                                        statusBg = '#cce7ff';
                                                                        statusIcon = 'fas fa-spinner';
                                                                        statusText = 'Running';
                                                                    } else if (job.status === 'failed' || job.status === 'Failed') {
                                                                        statusColor = '#721c24';
                                                                        statusBg = '#f8d7da';
                                                                        statusIcon = 'fas fa-exclamation-circle';
                                                                        statusText = 'Failed';
                                                                    } else if (job.status === 'pending' || job.status === 'Pending') {
                                                                        statusColor = '#856404';
                                                                        statusBg = '#fff3cd';
                                                                        statusIcon = 'fas fa-clock';
                                                                        statusText = 'Pending';
                                                                    }
                                                                    
                                                                    tableHTML += `
                                                                        <tr style="border-bottom: 1px solid #f1f3f4;">
                                                                            <td style="padding: 6px 8px;">
                                                                                <span style="display: inline-flex; flex-direction: column; align-items: flex-start; padding: 3px 8px; border-radius: 12px; background: ${statusBg}; color: ${statusColor}; font-weight: 500; font-size: 11px; line-height: 1.2;">
                                                                                    <div style="display: flex; align-items: center;">
                                                                                        <i class="${statusIcon}" style="font-size: 10px; margin-right: 4px;"></i>${statusText}
                                                                                    </div>
                                                                                    <div style="font-size: 8px; color: #666; font-style: italic; margin-top: 1px;">
                                                                                        Tokens: ${job.tokens_used || '-'}
                                                                                    </div>
                                                                                </span>
                                                                            </td>
                                                                            <td style="padding: 6px 8px; font-weight: 500;">${job.upc_processed_count || '-'}</td>
                                                                            <td style="padding: 6px 8px; font-size: 11px; color: #666;">${startTime}</td>
                                                                            <td style="padding: 6px 8px; font-size: 11px; color: #666;">${endTime}</td>
                                                                            <td style="padding: 6px 8px; text-align: center;">
                                                                                ${isTestRun ? 
                                                                                    '<span style="background: #e1f5fe; color: #01579b; padding: 2px 8px; border-radius: 8px; font-size: 10px; font-weight: 500; display: inline-flex; align-items: center; gap: 3px;" title="Test Run"><i class="fas fa-flask"></i>Test</span>' :
                                                                                    (job.missing_only ? 
                                                                                        '<span style="background: #e8f5e8; color: #2e7d32; padding: 2px 8px; border-radius: 8px; font-size: 10px; font-weight: 500; display: inline-flex; align-items: center; gap: 3px;" title="Live Processing - Missing Only: Processing products without existing AI descriptions"><i class="fas fa-plus-circle"></i>New</span>' : 
                                                                                        '<span style="background: #e8f5e8; color: #2e7d32; padding: 2px 8px; border-radius: 8px; font-size: 10px; font-weight: 500; display: inline-flex; align-items: center; gap: 3px;" title="Live Processing - Full Reprocess: Processing all products, replacing existing descriptions"><i class="fas fa-sync-alt"></i>All</span>'
                                                                                    )
                                                                                }
                                                                            </td>
                                                                        </tr>
                                                                    `;
                                                                });
                                                                
                                                                tableHTML += `
                                                                                </tbody>
                                                                            </table>
                                                                        </div>
                                                                        <div style="padding: 4px 8px; background: #f8f9fa; font-size: 10px; color: #6c757d; text-align: right; border-top: 1px solid #e9ecef;">
                                                                            Last updated: ${new Date().toLocaleTimeString()}
                                                                        </div>
                                                                    </div>
                                                                `;
                                                                
                                                                tableContainer.innerHTML = tableHTML;
                                                            } else {
                                                                // No jobs found
                                                                tableContainer.innerHTML = `
                                                                    <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px; margin-bottom: 15px;">
                                                                        <div style="background: #e9ecef; padding: 8px 12px; border-bottom: 1px solid #dee2e6; font-weight: 600; color: #495057; font-size: 13px; display: flex; justify-content: space-between; align-items: center;">
                                                                            <span><i class="fas fa-history" style="margin-right: 6px;"></i>Recent Processing Jobs</span>
                                                                            <button onclick="loadJobStatusTable('${groupName}')" style="background: #007cba; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 4px;" title="Refresh job status" onmouseover="this.style.background='#005a87'" onmouseout="this.style.background='#007cba'">
                                                                                <i class="fas fa-sync-alt" style="font-size: 10px;"></i>Refresh
                                                                            </button>
                                                                        </div>
                                                                        <div style="padding: 20px; text-align: center; color: #6c757d;">
                                                                            <i class="fas fa-info-circle" style="margin-right: 6px;"></i>No processing jobs found for this product group
                                                                        </div>
                                                                        <div style="padding: 4px 8px; background: #f8f9fa; font-size: 10px; color: #6c757d; text-align: right; border-top: 1px solid #e9ecef;">
                                                                            Last updated: ${new Date().toLocaleTimeString()}
                                                                        </div>
                                                                    </div>
                                                                `;
                                                            }
                                                            
                                                        } catch (error) {
                                                            console.error('Error loading job status:', error);
                                                            tableContainer.innerHTML = `
                                                                <div style="background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; margin-bottom: 15px;">
                                                                    <div style="background: #f1b0b7; padding: 8px 12px; border-bottom: 1px solid #f5c6cb; font-weight: 600; color: #721c24; font-size: 13px; display: flex; justify-content: space-between; align-items: center;">
                                                                        <span><i class="fas fa-history" style="margin-right: 6px;"></i>Recent Processing Jobs</span>
                                                                        <button onclick="loadJobStatusTable('${groupName}')" style="background: #dc3545; color: white; border: none; padding: 4px 8px; border-radius: 3px; font-size: 11px; cursor: pointer; display: flex; align-items: center; gap: 4px;" title="Retry loading job status" onmouseover="this.style.background='#c82333'" onmouseout="this.style.background='#dc3545'">
                                                                            <i class="fas fa-redo" style="font-size: 10px;"></i>Retry
                                                                        </button>
                                                                    </div>
                                                                    <div style="padding: 12px; color: #721c24;">
                                                                        <i class="fas fa-exclamation-triangle" style="margin-right: 6px;"></i>Failed to load job history
                                                                    </div>
                                                                </div>
                                                            `;
                                                        }
                                                    }
                                                    
                                                    // Process single product group
                                                    async function processProductGroup(groupName) {
                                                        if (hasUnsavedChanges()) {
                                                            alert('Please save your configuration changes before processing.');
                                                            return;
                                                        }
                                                        
                                                        // Check if tokens are sufficient before processing
                                                        const tokenCount = isNaN(Number(window.currentTokenCount)) ? 0 : Number(window.currentTokenCount);
                                                        if (tokenCount !== undefined && tokenCount <= 0) {
                                                            alert('Insufficient tokens to process this product group. Please purchase additional tokens.');
                                                            return;
                                                        }
                                                        
                                                        const config = editor.get();
                                                        const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                                        
                                                        if (!groupConfig) {
                                                            alert('Product group configuration not found.');
                                                            return;
                                                        }
                                                        
                                                        if (!groupConfig.assigned_prompt) {
                                                            alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                                            return;
                                                        }
                                                        
                                                        // Show process dialog
                                                        showProcessDialog(groupName, groupConfig);
                                                    }
                                                    
                                                    // Get processing estimates for product count and token cost
                                                    async function getProcessingEstimates(groupConfig, missingOnly = false, groupName = null) {
                                                        try {
                                          
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "get_ai_batch_processing_estimates",
                                                                    "data": {
                                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                                        "product_group_name": groupName,
                                                                        "missing_only": missingOnly
                                                                    }
                                                                })
                                                            });
                                                  
                                                            if (response.ok) {
                                                                const data = await response.json();
                                                                if (data.success) {
                                                                    return {
                                                                        productCount: data.product_count || 0,
                                                                        tokenCost: Math.round(data.estimated_tokens || 0)
                                                                    };
                                                                }
                                                            }
                                                        } catch (error) {
                                                            console.error('Error fetching processing estimates:', error);
                                                        }
                                                        
                                                        // Return default estimates if API call fails
                                                        return {
                                                            productCount: 'Unknown',
                                                            tokenCost: 'Unknown'
                                                        };
                                                    }
                                                    
                                                    // Show process dialog for product group
                                                    async function showProcessDialog(groupName, groupConfig) {
                                                        const modal = document.createElement('div');
                                                        modal.id = 'process-dialog-modal';
                                                        modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;';
                                                        
                                                        const restrictions = [];
                                                        if (groupConfig.product_restrictions?.brand?.length > 0) restrictions.push(`Brands: ${groupConfig.product_restrictions.brand.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.category?.length > 0) restrictions.push(`Categories: ${groupConfig.product_restrictions.category.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.product_class?.length > 0) restrictions.push(`Product Classes: ${groupConfig.product_restrictions.product_class.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.distributor?.length > 0) restrictions.push(`Distributors: ${groupConfig.product_restrictions.distributor.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.sku?.length > 0) restrictions.push(`SKUs: ${groupConfig.product_restrictions.sku.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.upc?.length > 0) restrictions.push(`UPCs: ${groupConfig.product_restrictions.upc.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.min_cost) restrictions.push(`Min Cost: $${groupConfig.product_restrictions.cost_restrictions.min_cost}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.max_cost) restrictions.push(`Max Cost: $${groupConfig.product_restrictions.cost_restrictions.max_cost}`);
                                                        
                                                        // Show modal with loading state first
                                                        modal.innerHTML = `
                                                            <div style="background: white; padding: 8px; border-radius: 12px; max-width: 800px; width: 95%; max-height: 90vh; overflow-y: auto; box-shadow: 0 10px 30px rgba(0,0,0,0.3); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; flex-direction: column;">
                                                                <!-- Header -->
                                                                <div style="background: #28a745; color: white; padding: 12px; margin: -8px -8px 12px -8px; border-radius: 12px 12px 0 0; display: flex; justify-content: space-between; align-items: center;">
                                                                    <div>
                                                                        <h2 style="margin: 0; font-size: 24px; font-weight: 600;color:white;">Create Product AI Info</h2>
                                                                        <p style="margin: 5px 0 0 0; opacity: 0.9; font-size: 14px;">${groupConfig.name || groupName}</p>
                                                                    </div>
                                                                    <button onclick="closeProcessDialog()" style="background: rgba(255,255,255,0.1); border: none; color: white; width: 28px; height: 28px; border-radius: 4px; cursor: pointer; font-size: 16px; display: flex; align-items: center; justify-content: center; transition: all 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">&times;</button>
                                                                </div>
                                                                
                                                                <!-- Processing Mode Toggle -->
                                                                <div style="background: #e8f4fd; border: 1px solid #bee3f8; padding: 12px; border-radius: 4px; margin-bottom: 10px;">
                                                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;">
                                                                        <h3 style="margin: 0; color: #2d3748; font-size: 15px; display: flex; align-items: center;">
                                                                            <span style="background: #4299e1; color: white; width: 18px; height: 18px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; margin-right: 8px;">⚙</span>
                                                                            Processing Mode
                                                                        </h3>
                                                                        <div style="display: flex; background: #f7fafc; border-radius: 6px; padding: 2px; border: 1px solid #e2e8f0;">
                                                                            <button id="missing-only-btn" type="button" onclick="setProcessingMode(true)" style="padding: 6px 12px; border: none; border-radius: 4px; font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.2s; background: #48bb78; color: white; border: 1px solid #48bb78;">
                                                                                Missing Only
                                                                            </button>
                                                                            <button id="process-all-btn" type="button" onclick="setProcessingMode(false)" style="padding: 6px 12px; border: none; border-radius: 4px; font-size: 12px; font-weight: 500; cursor: pointer; transition: all 0.2s; background: white; color: #4a5568; border: 1px solid #e2e8f0;">
                                                                                Process All
                                                                            </button>
                                                                            <input type="checkbox" id="missing-only-toggle" style="display: none;">
                                                                        </div>
                                                                    </div>
                                                                    <div style="font-size: 12px; color: #718096; line-height: 1.4;">
                                                                        <div id="mode-description" style="padding: 8px; background: white; border-radius: 3px; border-left: 3px solid #48bb78;">
                                                                            <strong>Missing Only:</strong> Only process products that don't currently have AI-generated descriptions, leaving existing content unchanged.
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Loading Estimates -->
                                                                <div id="estimates-loading" style="background: #f7fafc; border: 1px solid #e2e8f0; padding: 12px; border-radius: 4px; margin-bottom: 10px; text-align: center;">
                                                                    <div style="display: inline-flex; align-items: center; gap: 10px; color: #4a5568;">
                                                                        <div style="width: 20px; height: 20px; border: 2px solid #e2e8f0; border-top: 2px solid #4a5568; border-radius: 50%; animation: spin 1s linear infinite;"></div>
                                                                        <span>Loading processing estimates...</span>
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Processing Estimates (hidden initially) -->
                                                                <div id="estimates-content" style="display: none; background: #f7fafc; border: 1px solid #e2e8f0; padding: 10px; border-radius: 4px; margin-bottom: 10px;">
                                                                    <h3 style="margin: 0 0 8px 0; color: #2d3748; font-size: 16px; display: flex; align-items: center;">
                                                                        <span style="background: #718096; color: white; width: 20px; height: 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; margin-right: 8px;">📊</span>
                                                                        Processing Estimates
                                                                    </h3>
                                                                    <div id="estimates-data" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 6px;">
                                                                        <!-- Data will be populated here -->
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Configuration Summary -->
                                                                <div style="background: #f7fafc; border: 1px solid #e2e8f0; padding: 10px; border-radius: 4px; margin-bottom: 10px;">
                                                                    <h3 style="margin: 0 0 8px 0; color: #2d3748; font-size: 16px; display: flex; align-items: center;">
                                                                        <span style="background: #718096; color: white; width: 20px; height: 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; margin-right: 8px;">⚙</span>
                                                                        Configuration Summary
                                                                    </h3>
                                                                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 6px;">
                                                                        <div style="background: white; padding: 6px; border-radius: 3px; border-left: 2px solid #4299e1;">
                                                                            <strong style="color: #2d3748; font-size: 13px; display: block;">AI Prompt:</strong>
                                                                            <div style="color: #4a5568; font-size: 12px; margin-top: 1px; max-height: 32px; overflow: hidden; text-overflow: ellipsis;">${groupConfig.assigned_prompt}</div>
                                                                        </div>
                                                                        ${restrictions.length > 0 ? `
                                                                        <div style="background: white; padding: 6px; border-radius: 3px; border-left: 2px solid #ed8936;">
                                                                            <strong style="color: #2d3748; font-size: 13px; display: block;">Proguct Group Restrictions:</strong>
                                                                            <div style="color: #4a5568; font-size: 12px; margin-top: 1px; max-height: 24px; overflow: hidden; text-overflow: ellipsis;">${restrictions.join('; ')}</div>
                                                                        </div>
                                                                        ` : ''}
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Results -->
                                                                <div id="process-results" style="display: none; margin-bottom: 10px;">
                                                                    <h4 style="margin: 0 0 6px 0; color: #2d3748; display: flex; align-items: center; font-size: 15px;">
                                                                        <span style="background: #48bb78; color: white; width: 20px; height: 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; margin-right: 8px;">✓</span>
                                                                        Processing Results
                                                                    </h4>
                                                                    <div id="process-results-content" style="max-height: 150px; overflow-y: auto; border: 1px solid #e2e8f0; padding: 8px; border-radius: 3px; background: #f7fafc; font-size: 13px;">
                                                                    </div>
                                                                </div>
                                                                
                                                                <!-- Action Buttons -->
                                                                <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 8px; border-top: 1px solid #e2e8f0;">
                                                                    <button type="button" class="button" onclick="closeProcessDialog()" style="padding: 8px 16px; border-radius: 4px; font-size: 13px;">
                                                                        Close
                                                                    </button>
                                                                    <button id="start-process-btn" type="button" class="button button-primary" onclick="validateAndStartProcessing('${groupName}')" style="padding: 10px 20px; border-radius: 6px; background: #48bb78; border: none; color: white; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px; transition: all 0.2s;" disabled>
                                                                        <i class="fas fa-cogs" style="font-size: 13px;"></i>
                                                                        <span id="start-btn-text">Loading...</span>
                                                                    </button>
                                                                </div>
                                                            </div>
                                                            
                                                            <style>
                                                                @keyframes spin {
                                                                    0% { transform: rotate(0deg); }
                                                                    100% { transform: rotate(360deg); }
                                                                }
                                                                
                                                                #start-process-btn:disabled {
                                                                    opacity: 0.6;
                                                                    cursor: not-allowed;
                                                                    background: #a0aec0 !important;
                                                                }
                                                                
                                                                #start-process-btn:not(:disabled):hover {
                                                                    background: #38a169 !important;
                                                                    transform: translateY(-1px);
                                                                    box-shadow: 0 4px 8px rgba(72, 187, 120, 0.3);
                                                                    transition: all 0.2s ease;
                                                                }
                                                                
                                                                #missing-only-btn:hover:not(:disabled), #process-all-btn:hover:not(:disabled) {
                                                                    opacity: 0.9;
                                                                    transform: translateY(-1px);
                                                                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                                                                }
                                                                
                                                                #missing-only-btn:disabled, #process-all-btn:disabled {
                                                                    opacity: 0.5;
                                                                    cursor: not-allowed;
                                                                    transform: none;
                                                                    box-shadow: none;
                                                                }
                                                            </style>
                                                        `;
                                                        
                                                        document.body.appendChild(modal);
                                                        
                                                        // Store group data globally for toggle function
                                                        window.currentGroupName = groupName;
                                                        window.currentGroupConfig = groupConfig;
                                                        
                                                        // Add global function for button-style toggle
                                                        window.setProcessingMode = function(missingOnly) {
                                                            const toggle = document.getElementById('missing-only-toggle');
                                                            const description = document.getElementById('mode-description');
                                                            const missingOnlyBtn = document.getElementById('missing-only-btn');
                                                            const processAllBtn = document.getElementById('process-all-btn');
                                                            
                                                            // Don't allow changes while estimates are loading
                                                            if (missingOnlyBtn && missingOnlyBtn.disabled) return;
                                                            if (processAllBtn && processAllBtn.disabled) return;
                                                            
                                                            // Update the hidden checkbox state (inverted logic)
                                                            toggle.checked = !missingOnly;
                                                            
                                                            // Update button styles
                                                            if (missingOnly) {
                                                                // Missing Only mode
                                                                missingOnlyBtn.style.background = '#48bb78';
                                                                missingOnlyBtn.style.color = 'white';
                                                                missingOnlyBtn.style.border = '1px solid #48bb78';
                                                                
                                                                processAllBtn.style.background = 'white';
                                                                processAllBtn.style.color = '#4a5568';
                                                                processAllBtn.style.border = '1px solid #e2e8f0';
                                                                
                                                                description.innerHTML = `
                                                                    <strong>Missing Only:</strong> Only process products that don't currently have AI-generated descriptions, leaving existing content unchanged.
                                                                `;
                                                                description.style.borderLeftColor = '#48bb78';
                                                            } else {
                                                                // Process All mode
                                                                processAllBtn.style.background = '#48bb78';
                                                                processAllBtn.style.color = 'white';
                                                                processAllBtn.style.border = '1px solid #48bb78';
                                                                
                                                                missingOnlyBtn.style.background = 'white';
                                                                missingOnlyBtn.style.color = '#4a5568';
                                                                missingOnlyBtn.style.border = '1px solid #e2e8f0';
                                                                
                                                                description.innerHTML = `
                                                                    <strong>Process All Products:</strong> Generate AI descriptions for all products in this group, replacing any existing AI-generated content.
                                                                `;
                                                                description.style.borderLeftColor = '#ed8936';
                                                            }
                                                            
                                                            // Disable the Start Processing button while estimates reload
                                                            const startBtn = document.getElementById('start-process-btn');
                                                            const startBtnText = document.getElementById('start-btn-text');
                                                            if (startBtn) {
                                                                startBtn.disabled = true;
                                                                startBtn.title = 'Reloading estimates for new processing mode...';
                                                            }
                                                            if (startBtnText) {
                                                                startBtnText.textContent = 'Loading...';
                                                            }
                                                            
                                                            // Reload estimates with new mode using stored group data
                                                            reloadEstimates(window.currentGroupName, window.currentGroupConfig, missingOnly);
                                                        };
                                                        
                                                        // Keep the old function for compatibility but make it use the new button approach
                                                        window.toggleProcessingMode = function() {
                                                            const toggle = document.getElementById('missing-only-toggle');
                                                            const missingOnly = !toggle.checked;
                                                            setProcessingMode(missingOnly);
                                                        };
                                                        
                                                        // Add global function for reloading estimates
                                                        window.reloadEstimates = async function(groupName, groupConfig, missingOnly) {
                                                            const loadingElement = document.getElementById('estimates-loading');
                                                            const contentElement = document.getElementById('estimates-content');
                                                            const missingOnlyBtn = document.getElementById('missing-only-btn');
                                                            const processAllBtn = document.getElementById('process-all-btn');
                                                            
                                                            // Show loading state and disable buttons
                                                            if (loadingElement) loadingElement.style.display = 'block';
                                                            if (contentElement) contentElement.style.display = 'none';
                                                            if (missingOnlyBtn) missingOnlyBtn.disabled = true;
                                                            if (processAllBtn) processAllBtn.disabled = true;
                                                            
                                                            try {
                                                                const estimateData = await getProcessingEstimates(groupConfig, missingOnly, groupName);
                                                                updateEstimatesDisplay(estimateData);
                                                            } catch (error) {
                                                                console.error('Error reloading estimates:', error);
                                                                if (loadingElement) {
                                                                    loadingElement.innerHTML = `
                                                                        <div style="color: #e53e3e; text-align: center;">
                                                                            <span>⚠ Failed to reload estimates. Please try again.</span>
                                                                        </div>
                                                                    `;
                                                                }
                                                            } finally {
                                                                // Re-enable buttons after loading completes
                                                                if (missingOnlyBtn) missingOnlyBtn.disabled = false;
                                                                if (processAllBtn) processAllBtn.disabled = false;
                                                            }
                                                        };
                                                        
                                                        // Add global function for updating estimates display
                                                        window.updateEstimatesDisplay = function(estimateData) {
                                                            const loadingElement = document.getElementById('estimates-loading');
                                                            const contentElement = document.getElementById('estimates-content');
                                                            const estimatesDataDiv = document.getElementById('estimates-data');
                                                            
                                                            // Hide loading, show estimates
                                                            if (loadingElement) loadingElement.style.display = 'none';
                                                            if (contentElement) contentElement.style.display = 'block';
                                                            
                                                            // Populate estimates data
                                                            if (estimatesDataDiv) {
                                                                estimatesDataDiv.innerHTML = `
                                                                    <div style="background: white; padding: 10px; border-radius: 4px; border-left: 3px solid #4299e1;">
                                                                        <div style="font-size: 12px; color: #718096; margin-bottom: 2px;">Estimated Products</div>
                                                                        <div style="font-size: 16px; font-weight: 600; color: #2d3748;">${estimateData.productCount}</div>
                                                                    </div>
                                                                    <div style="background: white; padding: 10px; border-radius: 4px; border-left: 3px solid #48bb78;">
                                                                        <div style="font-size: 12px; color: #718096; margin-bottom: 2px;">Estimated Token Cost</div>
                                                                        <div style="font-size: 16px; font-weight: 600; color: #2d3748;">${typeof estimateData.tokenCost === 'number' ? estimateData.tokenCost.toLocaleString() : estimateData.tokenCost}</div>
                                                                    </div>
                                                                    <div style="background: white; padding: 10px; border-radius: 4px; border-left: 3px solid #ed8936;">
                                                                        <div style="font-size: 12px; color: #718096; margin-bottom: 2px;">Current Balance</div>
                                                                        <div style="font-size: 16px; font-weight: 600; color: ${window.currentTokenCount >= estimateData.tokenCost ? '#48bb78' : '#e53e3e'};">${(window.currentTokenCount || 0).toLocaleString()}</div>
                                                                    </div>
                                                                    ${window.currentTokenCount < estimateData.tokenCost ? `
                                                                    <div style="background: #fef5e7; padding: 10px; border-radius: 4px; border-left: 3px solid #e53e3e; grid-column: 1 / -1;">
                                                                        <div style="font-size: 12px; color: #742a2a; margin-bottom: 6px; font-weight: 600;">⚠️ Insufficient Tokens</div>
                                                                    <div style="font-size: 11px; color: #744210; margin-bottom: 8px; line-height: 1.4;">
                                                                        You need ${estimateData.tokenCost.toLocaleString()} tokens but only have ${(window.currentTokenCount || 0).toLocaleString()} available.
                                                                    </div>
                                                                    <a href="<?php echo esc_attr($this->get_purchase_url($gFFLCockpitKey)); ?>" target="_blank" style="background: #0073aa; color: white; padding: 6px 12px; border-radius: 4px; text-decoration: none; font-size: 11px; font-weight: 500; display: inline-flex; align-items: center; gap: 4px;">
                                                                        <i class="fas fa-shopping-cart"></i>Purchase Additional Tokens
                                                                    </a>
                                                                </div>` : ''}
                                                                `;
                                                            }
                                                            
                                                            // Check if estimates loaded successfully and enable button
                                                            const startBtn = document.getElementById('start-process-btn');
                                                            const startBtnText = document.getElementById('start-btn-text');
                                                            
                                                            if (estimateData.productCount !== 'Unknown' && estimateData.tokenCost !== 'Unknown') {
                                                                const currentTokens = window.currentTokenCount || 0;
                                                                const hasInsufficientTokens = estimateData.tokenCost > currentTokens;
                                                                const hasNoProducts = estimateData.productCount === 0;
                                                                
                                                                if (hasNoProducts) {
                                                                    // Hide the button when no products to process
                                                                    if (startBtn) startBtn.style.display = 'none';
                                                                } else if (hasInsufficientTokens) {
                                                                    if (startBtn) {
                                                                        startBtn.style.display = 'block';
                                                                        startBtn.disabled = true;
                                                                    }
                                                                    if (startBtnText) startBtnText.textContent = 'Insufficient Tokens';
                                                                    if (startBtn) startBtn.title = `Processing requires ${estimateData.tokenCost.toLocaleString()} tokens but you only have ${currentTokens.toLocaleString()} available. Please purchase additional tokens.`;
                                                                } else {
                                                                    // Show and enable the button for normal processing
                                                                    if (startBtn) {
                                                                        startBtn.style.display = 'block';
                                                                        startBtn.disabled = false;
                                                                    }
                                                                    if (startBtnText) startBtnText.textContent = 'Create Product AI Info';
                                                                }
                                                            } else {
                                                                if (startBtn) startBtn.style.display = 'block';
                                                                if (startBtnText) startBtnText.textContent = 'No Test Data Available';
                                                                if (startBtn) {
                                                                    startBtn.disabled = true;
                                                                    startBtn.title = 'Please run a test first to get processing estimates';
                                                                }
                                                            }
                                                        };
                                                        
                                                        // Close on background click
                                                        modal.addEventListener('click', function(e) {
                                                            if (e.target === modal) {
                                                                closeProcessDialog();
                                                            }
                                                        });
                                                        
                                                        // Load estimates asynchronously
                                                        try {
                                                            // Disable mode buttons during initial loading
                                                            const missingOnlyBtn = document.getElementById('missing-only-btn');
                                                            const processAllBtn = document.getElementById('process-all-btn');
                                                            if (missingOnlyBtn) missingOnlyBtn.disabled = true;
                                                            if (processAllBtn) processAllBtn.disabled = true;
                                                            
                                                            const estimateData = await getProcessingEstimates(groupConfig, true, groupName); // Default to missing only
                                                            updateEstimatesDisplay(estimateData);
                                                            
                                                            // Re-enable mode buttons after loading
                                                            if (missingOnlyBtn) missingOnlyBtn.disabled = false;
                                                            if (processAllBtn) processAllBtn.disabled = false;
                                                            
                                                            // Check if estimates loaded successfully and enable button
                                                            if (estimateData.productCount !== 'Unknown' && estimateData.tokenCost !== 'Unknown') {
                                                                const currentTokens = window.currentTokenCount || 0;
                                                                const hasInsufficientTokens = estimateData.tokenCost > currentTokens;
                                                                const hasNoProducts = estimateData.productCount === 0;
                                                                
                                                                if (hasNoProducts) {
                                                                    // Hide the button when no products to process
                                                                    const startBtn = document.getElementById('start-process-btn');
                                                                    if (startBtn) startBtn.style.display = 'none';
                                                                } else if (hasInsufficientTokens) {
                                                                    const startBtn = document.getElementById('start-process-btn');
                                                                    if (startBtn) startBtn.style.display = 'block';
                                                                    document.getElementById('start-btn-text').textContent = 'Insufficient Tokens';
                                                                    document.getElementById('start-process-btn').disabled = true;
                                                                    document.getElementById('start-process-btn').title = `Processing requires ${estimateData.tokenCost.toLocaleString()} tokens but you only have ${currentTokens.toLocaleString()} available. Please purchase additional tokens.`;
                                                                } else {
                                                                    const startBtn = document.getElementById('start-process-btn');
                                                                    if (startBtn) startBtn.style.display = 'block';
                                                                    document.getElementById('start-btn-text').textContent = 'Create Product AI Info';
                                                                    document.getElementById('start-process-btn').disabled = false;
                                                                }
                                                            } else {
                                                                const startBtn = document.getElementById('start-process-btn');
                                                                if (startBtn) startBtn.style.display = 'block';
                                                                document.getElementById('start-btn-text').textContent = 'No Test Data Available';
                                                                document.getElementById('start-process-btn').disabled = true;
                                                                document.getElementById('start-process-btn').title = 'Please run a test first to get processing estimates';
                                                            }
                                                            
                                                        } catch (error) {
                                                            console.error('Error loading estimates:', error);
                                                            
                                                            // Re-enable mode buttons on error
                                                            const missingOnlyBtn = document.getElementById('missing-only-btn');
                                                            const processAllBtn = document.getElementById('process-all-btn');
                                                            if (missingOnlyBtn) missingOnlyBtn.disabled = false;
                                                            if (processAllBtn) processAllBtn.disabled = false;
                                                            
                                                            document.getElementById('estimates-loading').innerHTML = `
                                                                <div style="color: #e53e3e; text-align: center;">
                                                                    <span>⚠ Failed to load estimates. Please try again.</span>
                                                                </div>
                                                            `;
                                                            document.getElementById('start-btn-text').textContent = 'Error Loading Data';
                                                            document.getElementById('start-process-btn').disabled = true;
                                                        }
                                                    }
                                                    
                                                    // Close process dialog
                                                    function closeProcessDialog() {
                                                        const modal = document.getElementById('process-dialog-modal');
                                                        if (modal) {
                                                            modal.remove();
                                                        }
                                                        
                                                        // Refresh token count after process dialog closes
                                                        loadAITokens();
                                                    }
                                                    
                                                    // Start processing for the product group
                                                    function validateAndStartProcessing(groupName) {
                                                        // Start the actual processing
                                                        startProductGroupProcessing(groupName);
                                                    }
                                                    
                                                    // Start processing for a specific product group
                                                    async function startProductGroupProcessing(groupName) {
                                                        const startBtn = document.getElementById('start-process-btn');
                                                        const resultsDiv = document.getElementById('process-results');
                                                        const resultsContent = document.getElementById('process-results-content');
                                                        
                                                        startBtn.disabled = true;
                                                        startBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
                                                        
                                                        try {
                                                            const config = editor.get();
                                                            
                                                            // Get the missing_only value from the toggle
                                                            const missingOnlyToggle = document.getElementById('missing-only-toggle');
                                                            const missingOnly = missingOnlyToggle ? !missingOnlyToggle.checked : true; // Default to missing only if toggle not found
                                                            
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "run_ai_product_info_job",
                                                                    "data": {
                                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                                        "product_group_name": groupName,
                                                                        "is_test_run": false,
                                                                        "missing_only": missingOnly
                                                                    }
                                                                })
                                                            });
                                                            
                                                            const data = await response.json();
                                                            
                                                            // Show results
                                                            resultsDiv.style.display = 'block';
                                                            
                                                            if (data.success) {
                                                                resultsContent.innerHTML = `
                                                                    <div style="color: #0ab00aff; font-weight: bold; margin-bottom: 15px;">
                                                                        <i class="fas fa-exclamation-triangle"></i> Processing started successfully, you will receive an email once processing has been completed.
                                                                    </div>
                                                                `;
                                                                // Hide the start button for successful processing
                                                                startBtn.style.display = 'none';
                                                                // Refresh the job status table to show the new job
                                                                setTimeout(() => {
                                                                    loadJobStatusTable(groupName);
                                                                }, 1000); // Small delay to ensure the job is saved in the API
                                                            } else {
                                                                resultsContent.innerHTML = `
                                                                    <div style="color: #f44336; font-weight: bold; margin-bottom: 15px;">
                                                                        <i class="fas fa-exclamation-triangle"></i> Processing failed
                                                                    </div>
                                                                    <p><strong>Error:</strong> ${data.message || 'Unknown error occurred'}</p>
                                                                `;
                                                                // Show "Process Again" button for failed processing
                                                                startBtn.disabled = false;
                                                                startBtn.innerHTML = '<i class="fas fa-redo"></i> Process Again';
                                                            }
                                                            
                                                        } catch (error) {
                                                            console.error('Error processing product group:', error);
                                                            
                                                            resultsDiv.style.display = 'block';
                                                            resultsContent.innerHTML = `
                                                                <div style="color: #f44336; font-weight: bold;">
                                                                    <i class="fas fa-exclamation-triangle"></i> Network Error
                                                                </div>
                                                                <p>Failed to communicate with the API. Please check your connection and try again.</p>
                                                            `;
                                                            // Show "Process Again" button for network errors
                                                            startBtn.disabled = false;
                                                            startBtn.innerHTML = '<i class="fas fa-redo"></i> Process Again';
                                                        }
                                                    }
                                                    
                                                    // Enhanced test function with API call
                                                    async function testProductGroupWithMockData(groupName) {
                                                        if (hasUnsavedChanges()) {
                                                            alert('Please save your configuration changes before testing.');
                                                            return;
                                                        }
                                                        
                                                        const config = editor.get();
                                                        const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                                        
                                                        if (!groupConfig) {
                                                            alert('Product group configuration not found.');
                                                            return;
                                                        }
                                                        
                                                        if (!groupConfig.assigned_prompt) {
                                                            alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                                            return;
                                                        }
                                                        
                                                        // Show test dialog with API call
                                                        showTestDialog(groupName, groupConfig);
                                                    }
                                                    
                                    // Show test dialog
                                    function showTestDialog(groupName, groupConfig) {
                                        const modal = document.createElement('div');
                                        modal.id = 'test-dialog-modal';
                                        modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 10000; display: flex; align-items: center; justify-content: center;';
                                        modal.innerHTML = `
                                            <div style="background: white; padding: 8px; border-radius: 12px; max-width: 1400px; width: 95%; max-height: 90vh; overflow-y: auto; box-shadow: 0 10px 30px rgba(0,0,0,0.3); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; flex-direction: column;">
                                                <!-- Header -->
                                                <div style="background: #17a2b8; color: white; padding: 12px; margin: -8px -8px 12px -8px; border-radius: 12px 12px 0 0; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0;">
                                                    <div>
                                                        <h2 style="margin: 0; font-size: 24px; font-weight: 600;color:white;">
                                                            <i class="fas fa-flask" style="margin-right: 10px;color:white;"></i>
                                                            Test Product Group
                                                        </h2>
                                                        <p style="margin: 5px 0 0 0; opacity: 0.9; font-size: 14px;">${groupConfig.name || groupName}</p>
                                                    </div>
                                                    <div style="display: flex; align-items: center; gap: 10px;">
                                                        <div id="success-indicator" style="display: none; background: rgba(255,255,255,0.1); padding: 6px 10px; border-radius: 6px; border-left: 3px solid rgba(255,255,255,0.5);">       
                                                            <!-- Test Run Selector -->
                                                            <div id="test-run-selector" style="margin-bottom: 15px; flex-shrink: 0; display: none;">
                                                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                                                    <div style="display: flex; align-items: center; gap: 15px;">
                                                                        <label for="test-run-dropdown" style="font-weight: 600; color: white;">Test Run:</label>
                                                                        <select id="test-run-dropdown" style="margin-right:10px;padding: 5px 5px; border: 1px solid rgba(255,255,255,0.3); border-radius: 4px; font-size: 14px; min-width: 200px;">
                                                                            <!-- Options will be populated dynamically -->
                                                                        </select>
                                                                    </div>
                                                                    <button id="new-test-button" onclick="startNewTestRun('${groupName}')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); padding: 8px 16px; border-radius: 4px; font-size: 14px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">
                                                                        <i class="fas fa-play" style="margin-right: 6px;"></i>Start New Test
                                                                    </button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <button onclick="closeTestDialog()" style="background: rgba(255,255,255,0.1); border: none; color: white; width: 28px; height: 28px; border-radius: 4px; cursor: pointer; font-size: 16px; display: flex; align-items: center; justify-content: center; transition: all 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.2)'" onmouseout="this.style.background='rgba(255,255,255,0.1)'">&times;</button>
                                                    </div>
                                                </div>
                                                

                                                
                                                <div id="test-summary-header" style="display: none; margin-bottom: 8px; flex-shrink: 0;">
                                                    <!-- Summary content will be inserted here -->
                                                </div>
                                                
                                                <div id="test-loading" style="text-align: center; padding: 60px 20px; color: #666;">
                                                    <div style="display: inline-block; position: relative;">
                                                        <div style="width: 60px; height: 60px; border: 4px solid #f3f3f3; border-top: 4px solid #0073aa; border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto 20px;"></div>
                                                        <div id="loading-text" style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">Loading test results...</div>
                                                        <div id="loading-subtext" style="font-size: 14px; color: #888;">Fetching the latest test data</div>
                                                    </div>
                                                </div>
                                                
                                                <div id="no-tests-message" style="display: none; text-align: center; padding: 60px 20px; color: #666;">
                                                    <div style="font-size: 24px; margin-bottom: 15px;">🧪</div>
                                                    <div style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">No Test Results Found</div>
                                                    <div style="font-size: 14px; color: #888; margin-bottom: 20px;">Start your first test run to see AI enhancement results</div>
                                                    <button onclick="startNewTestRun('${groupName}')" style="background: #0073aa; color: white; border: none; padding: 12px 24px; border-radius: 6px; font-size: 16px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#005a87'" onmouseout="this.style.background='#0073aa'">
                                                        <i class="fas fa-play" style="margin-right: 8px;"></i>Start First Test Run
                                                    </button>
                                                </div>
                                                
                                                <div id="test-results" style="display: none; flex: 1; overflow: hidden; flex-direction: column; min-height: 0;">
                                                    <div style="border-bottom: 2px solid #dee2e6; margin-bottom: 8px; flex-shrink: 0;">
                                                        <div id="product-tabs" style="display: flex; overflow-x: auto; margin-bottom: 0; background: #f8f9fa; border-radius: 8px 8px 0 0; padding: 5px;">
                                                            <!-- Product tabs will be populated here -->
                                                        </div>
                                                    </div>
                                                    
                                                    <div id="tab-content" style="flex: 1; overflow-y: auto; min-height: 0;">
                                                        <!-- Tab content will be populated here -->
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <style>
                                                @keyframes spin {
                                                    0% { transform: rotate(0deg); }
                                                    100% { transform: rotate(360deg); }
                                                }
                                                
                                                .product-tab {
                                                    padding: 8px 16px;
                                                    margin: 2px;
                                                    background: white;
                                                    border: 1px solid #dee2e6;
                                                    border-radius: 6px;
                                                    cursor: pointer;
                                                    transition: all 0.3s ease;
                                                    white-space: nowrap;
                                                    font-weight: 500;
                                                    min-width: 200px;
                                                    text-align: center;
                                                    display: flex;
                                                    align-items: center;
                                                    gap: 8px;
                                                    font-size: 13px;
                                                }
                                                
                                                .product-tab img {
                                                    width: 24px;
                                                    height: 24px;
                                                    border-radius: 4px;
                                                    object-fit: cover;
                                                    border: 1px solid #dee2e6;
                                                }
                                                
                                                .product-tab:hover {
                                                    background: #e9ecef;
                                                    transform: translateY(-1px);
                                                    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                                                }
                                                
                                                .product-tab.active {
                                                    background: linear-gradient(135deg, #007cba 0%, #0073aa 100%);
                                                    color: white;
                                                    border-color: #0073aa;
                                                    box-shadow: 0 4px 12px rgba(0,115,170,0.3);
                                                }
                                                
                                                .tab-content-item {
                                                    display: none;
                                                    animation: fadeIn 0.3s ease-in;
                                                }
                                                
                                                .tab-content-item.active {
                                                    display: block;
                                                }
                                                
                                                @keyframes fadeIn {
                                                    from { opacity: 0; transform: translateY(10px); }
                                                    to { opacity: 1; transform: translateY(0); }
                                                }
                                                
                                                .product-header {
                                                    display: flex;
                                                    align-items: center;
                                                    gap: 12px;
                                                    margin-bottom: 12px;
                                                    padding: 12px;
                                                    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
                                                    border-radius: 6px;
                                                    border: 1px solid #dee2e6;
                                                }
                                                
                                                .product-image {
                                                    width: 120px;
                                                    height: 120px;
                                                    border-radius: 6px;
                                                    object-fit: cover;
                                                    border: 1px solid #dee2e6;
                                                    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                                                    flex-shrink: 0;
                                                }
                                                
                                                .product-basic-info h3 {
                                                    margin: 0 0 4px 0;
                                                    color: #333;
                                                    font-size: 16px;
                                                    font-weight: 600;
                                                    line-height: 1.2;
                                                }
                                                
                                                .product-basic-info p {
                                                    margin: 2px 0;
                                                    color: #666;
                                                    font-size: 12px;
                                                    line-height: 1.3;
                                                }
                                                
                                                .tokens-used {
                                                    margin-top: 6px;
                                                    font-size: 11px;
                                                    color: #007cba;
                                                    font-weight: 600;
                                                }
                                                
                                                .tokens-used i {
                                                    margin-right: 4px;
                                                    font-size: 10px;
                                                }
                                                
                                                .product-header .needs-review-badge {
                                                    background: #f4bda6ff;
                                                    color: black;
                                                    margin-top: 4px;
                                                    padding: 3px 6px;
                                                    font-size: 10px;
                                                }
                                                
                                                .product-header .product-notes {
                                                    margin-top: 4px;
                                                    padding: 4px 8px;
                                                    font-size: 11px;
                                                }
                                                
                                                .field-sections {
                                                    display: grid;
                                                    grid-template-columns: 1fr 1fr;
                                                    gap: 20px;
                                                }
                                                
                                                .field-section {
                                                    background: #f8f9fa;
                                                    border-radius: 8px;
                                                    padding: 18px;
                                                    border: 1px solid #e9ecef;
                                                }
                                                
                                                .field-section h4 {
                                                    color: #495057;
                                                    margin: 0 0 15px 0;
                                                    font-size: 16px;
                                                    font-weight: 600;
                                                    border-bottom: 2px solid #007cba;
                                                    padding-bottom: 5px;
                                                    display: inline-block;
                                                }
                                                
                                                .field-row {
                                                    margin-bottom: 12px;
                                                }
                                                
                                                .field-label {
                                                    font-weight: 600;
                                                    color: #495057;
                                                    font-size: 13px;
                                                    margin-bottom: 4px;
                                                    display: block;
                                                }
                                                
                                                .field-value {
                                                    background: white;
                                                    padding: 10px 12px;
                                                    border-radius: 4px;
                                                    border: 1px solid #dee2e6;
                                                    font-size: 13px;
                                                    line-height: 1.4;
                                                    word-wrap: break-word;
                                                    width: 100%;
                                                    box-sizing: border-box;
                                                }
                                                
                                                .field-value.html-content {
                                                    /* Removed max-height and overflow to display full descriptions */
                                                }
                                                
                                                .char-count {
                                                    font-size: 11px;
                                                    color: #6c757d;
                                                    font-style: italic;
                                                    margin-top: 4px;
                                                    text-align: right;
                                                }
                                                
                                                .char-count.over-limit {
                                                    color: #dc3545;
                                                    font-weight: 600;
                                                }
                                                
                                                .char-count.good {
                                                    color: #28a745;
                                                }
                                                
                                                /* Summary Tab Styles */
                                                .summary-section {
                                                    padding: 20px;
                                                }
                                                
                                                .summary-section h3 {
                                                    color: #333;
                                                    margin-bottom: 20px;
                                                    font-size: 24px;
                                                    font-weight: 600;
                                                    display: flex;
                                                    align-items: center;
                                                    gap: 10px;
                                                }
                                                
                                                .summary-stats {
                                                    display: grid;
                                                    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                                                    gap: 20px;
                                                    margin-bottom: 30px;
                                                }
                                                
                                                .stat-card {
                                                    background: linear-gradient(135deg, #007cba 0%, #005a87 100%);
                                                    color: white;
                                                    padding: 20px;
                                                    border-radius: 12px;
                                                    text-align: center;
                                                    box-shadow: 0 4px 15px rgba(0,124,186,0.3);
                                                }
                                                
                                                .stat-number {
                                                    font-size: 32px;
                                                    font-weight: bold;
                                                    margin-bottom: 5px;
                                                }
                                                
                                                .stat-label {
                                                    font-size: 14px;
                                                    opacity: 0.9;
                                                }
                                                
                                                .estimated-totals {
                                                    background: #f8f9fa;
                                                    border-radius: 12px;
                                                    padding: 25px;
                                                    margin-bottom: 20px;
                                                    border: 1px solid #e9ecef;
                                                }
                                                
                                                .estimated-totals h4 {
                                                    color: #495057;
                                                    margin-bottom: 15px;
                                                    font-size: 18px;
                                                    display: flex;
                                                    align-items: center;
                                                    gap: 8px;
                                                }
                                                
                                                .estimate-stats {
                                                    display: grid;
                                                    gap: 15px;
                                                    margin-bottom: 20px;
                                                }
                                                
                                                .estimate-item {
                                                    display: flex;
                                                    justify-content: space-between;
                                                    align-items: center;
                                                    padding: 12px 16px;
                                                    background: white;
                                                    border-radius: 8px;
                                                    border: 1px solid #dee2e6;
                                                }
                                                
                                                .highlight {
                                                    font-size: 18px;
                                                    font-weight: bold;
                                                    color: #007cba;
                                                }
                                                
                                                .tokens-estimate {
                                                    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                                                    color: white;
                                                    padding: 4px 12px;
                                                    border-radius: 20px;
                                                    font-size: 16px;
                                                }
                                                
                                                .disclaimer {
                                                    background: #fff3cd;
                                                    border: 1px solid #ffeaa7;
                                                    color: #856404;
                                                    padding: 12px 16px;
                                                    border-radius: 8px;
                                                    font-size: 13px;
                                                    display: flex;
                                                    align-items: flex-start;
                                                    gap: 8px;
                                                }
                                                
                                                .action-section {
                                                    background: #e7f3ff;
                                                    border: 1px solid #b3d9ff;
                                                    color: #004085;
                                                    padding: 15px 20px;
                                                    border-radius: 8px;
                                                    font-size: 14px;
                                                }
                                                
                                                .summary-tab {
                                                    background: linear-gradient(135deg, #007cba 0%, #005a87 100%);
                                                    color: white;
                                                    border: 1px solid #005a87;
                                                }
                                                
                                                .summary-tab.active {
                                                    background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
                                                    box-shadow: 0 4px 8px rgba(0,86,179,0.3);
                                                }
                                                
                                                .description-tabs {
                                                    margin-top: 10px;
                                                }
                                                
                                                .description-tab-buttons {
                                                    display: flex;
                                                    border-bottom: 2px solid #f0f0f0;
                                                    margin-bottom: 15px;
                                                }
                                                
                                                .description-tab-btn {
                                                    background: none;
                                                    border: none;
                                                    outline: none;
                                                    padding: 8px 16px;
                                                    cursor: pointer;
                                                    font-size: 13px;
                                                    font-weight: 500;
                                                    color: #666;
                                                    border-bottom: 2px solid transparent;
                                                    transition: all 0.2s ease;
                                                }
                                                
                                                .description-tab-btn:hover {
                                                    color: #0073aa;
                                                    background: #f8f9fa;
                                                }
                                                
                                                .description-tab-btn.active {
                                                    color: #0073aa !important;
                                                    border-bottom-color: #0073aa !important;
                                                    font-weight: 600;
                                                }
                                                
                                                .description-tab-btn:focus {
                                                    outline: none !important;
                                                    border: none !important;
                                                    box-shadow: none !important;
                                                }
                                                
                                                .description-tab-btn:focus.active {
                                                    color: #0073aa !important;
                                                    border-bottom-color: #0073aa !important;
                                                }
                                                
                                                .description-tab-pane {
                                                    display: none;
                                                }
                                                
                                                .description-tab-pane.active {
                                                    display: block;
                                                    animation: fadeIn 0.3s ease-in;
                                                }
                                            </style>
                                        `;
                                        
                                        document.body.appendChild(modal);
                                        
                                        
                                        // Load existing test results instead of starting a new test
                                        setTimeout(() => {
                                            loadTestResults(groupName);
                                        }, 500);
                                        
                                        // Close on background click
                                        modal.addEventListener('click', function(e) {
                                            if (e.target === modal) {
                                                closeTestDialog();
                                            }
                                        });
                                    }
                                                    
                                    // Close test dialog
                                    function closeTestDialog() {
                                        // Clean up any polling operations
                                        hidePollingState();
                                        
                                        const modal = document.getElementById('test-dialog-modal');
                                        if (modal) {
                                            modal.remove();
                                        }
                                        
                                        // Refresh token count after test dialog closes
                                        loadAITokens();
                                    }
                                                    
                                    // Show apply dialog for product group
                                    async function showApplyDialog(groupName) {
                                        // console.log('showApplyDialog called with groupName:', groupName);
                                        
                                        if (hasUnsavedChanges()) {
                                            alert('Please save your configuration changes before applying.');
                                            return;
                                        }
                                        
                                        const config = editor.get();
                                        const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                        
                                        // console.log('Group config found:', groupConfig);
                                        
                                        if (!groupConfig) {
                                            alert('Product group configuration not found.');
                                            return;
                                        }
                                        
                                        if (!groupConfig.assigned_prompt) {
                                            alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                            return;
                                        }
                                        
                                        // Show apply dialog with product data from API
                                        showApplyModal(groupName, groupConfig);
                                    }
                                                    
                                    // Show apply modal
                                    function showApplyModal(groupName, groupConfig) {
                                        const modal = document.createElement('div');
                                        modal.id = 'apply-dialog-modal';
                                        modal.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 100000; display: flex; align-items: center; justify-content: center;';
                                        modal.innerHTML = `
                                            <div class="dialog-container" style="background: white; border-radius: 12px; max-width: 1400px; width: 95%; max-height: 95vh; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.3); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; flex-direction: column;">
                                                <!-- Header -->
                                                <div class="dialog-header" style="background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%); color: #212529; padding: 20px; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                                                    <div>
                                                        <h2 style="margin: 0; font-size: 24px; font-weight: 700; color: #212529;">
                                                            <i class="fas fa-check-circle" style="margin-right: 10px;"></i>
                                                            Review & Apply AI Changes
                                                        </h2>
                                                        <p style="margin: 5px 0 0 0; opacity: 0.8; font-size: 14px; font-weight: 500;">${groupConfig.name || groupName}</p>
                                                    </div>
                                                    <button onclick="closeApplyDialog()" style="background: rgba(33,37,41,0.1); border: none; color: #212529; width: 36px; height: 36px; border-radius: 6px; cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; transition: all 0.2s; font-weight: bold;" onmouseover="this.style.background='rgba(33,37,41,0.2)'" onmouseout="this.style.background='rgba(33,37,41,0.1)'">&times;</button>
                                                </div>
                                                
                                                <!-- Important Notice Full Screen -->
                                                <div id="apply-important-notice" style="flex: 1; display: flex; align-items: center; justify-content: center; padding: 40px;">
                                                    <div style="max-width: 600px; width: 100%; text-align: center;">
                                                        <div style="background: white; border: 1px solid #e9ecef; border-radius: 12px; padding: 40px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);">
                                                            <h3 style="margin: 0 0 24px 0; color: #495057; font-size: 22px; display: flex; align-items: center; justify-content: center; gap: 12px; font-weight: 600;">
                                                                <i class="fas fa-exclamation-triangle" style="color: #ffc107; font-size: 26px;"></i>
                                                                Important Notice
                                                            </h3>
                                                            
                                                            <div style="background: #f8f9fa; padding: 24px; border-radius: 8px; border-left: 4px solid #ffc107; margin-bottom: 32px;">
                                                                <p style="margin: 0; color: #495057; line-height: 1.6; font-size: 16px; text-align: left;">
                                                                    I acknowledge that I am updating my product data with AI-generated content and understand that while FFL Cockpit strives for accuracy, 
                                                                    AI technology may occasionally produce unexpected results. I accept responsibility for reviewing and verifying the generated content 
                                                                    for my specific use case and business requirements.
                                                                </p>
                                                            </div>
                                                            
                                                            <div style="display: flex; justify-content: center; gap: 16px;">
                                                                <button onclick="closeApplyDialog()" style="background: #6c757d; color: white; border: none; padding: 14px 28px; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: 500; transition: all 0.2s; min-width: 120px;" onmouseover="this.style.background='#5a6268'" onmouseout="this.style.background='#6c757d'">
                                                                    Cancel
                                                                </button>
                                                                <button id="acknowledge-and-continue-btn" onclick="acknowledgeAndContinue()" style="background: #ffc107; color: #212529; border: none; padding: 14px 28px; border-radius: 8px; cursor: pointer; font-size: 16px; font-weight: 600; transition: all 0.2s; min-width: 180px;" onmouseover="this.style.background='#e0a800'" onmouseout="this.style.background='#ffc107'">
                                                                    <i class="fas fa-check" style="margin-right: 8px;"></i>
                                                                    I Acknowledge & Continue
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- Main Content (Hidden Initially) -->
                                                <div class="dialog-content" id="apply-main-content" style="flex: 1; display: none; overflow: hidden;">
                                                    <!-- Navigation Panel -->
                                                    <div id="apply-nav-panel" style="width: 280px; background: #f8f9fa; border-right: 1px solid #dee2e6; display: flex; flex-direction: column; overflow: hidden;">
                                                        <!-- Loading State -->
                                                        <div id="apply-loading" style="padding: 40px 20px; text-align: center; display: block;">
                                                            <div style="display: inline-flex; align-items: center; gap: 10px; color: #4a5568;">
                                                                <i class="fas fa-spinner fa-spin" style="font-size: 20px;"></i>
                                                                <span style="font-size: 16px; font-weight: 500;">Loading...</span>
                                                            </div>
                                                            <p style="margin: 10px 0 0 0; color: #718096; font-size: 14px;">Fetching products</p>
                                                        </div>
                                                        
                                                        <!-- Product Navigation -->
                                                        <div id="apply-nav-content" style="display: none; flex-direction: column; flex: 1; overflow: hidden;">
                                                            <div style="padding: 15px; border-bottom: 1px solid #dee2e6; background: white; flex-shrink: 0;">
                                                                <div id="product-count" style="color: #6c757d; font-size: 14px;"></div>
                                                            </div>
                                                            <div id="product-nav-list" style="flex: 1; overflow-y: auto; padding: 10px; width: 100%; box-sizing: border-box;">
                                                                <!-- Product navigation will be populated here -->
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- No Products Message -->
                                                        <div id="no-apply-products" style="display: none; padding: 40px 20px; text-align: center;">
                                                            <i class="fas fa-info-circle" style="font-size: 48px; color: #6c757d; margin-bottom: 15px;"></i>
                                                            <h3 style="margin: 0 0 10px 0; color: #495057; font-size: 16px;">No Products Ready</h3>
                                                            <p style="margin: 0; color: #6c757d; font-size: 14px;">No AI-enhanced products found for this group with the current configuration. Please run the Create process first.</p>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Content Panel -->
                                                    <div id="apply-content-panel" style="flex: 1; background: white; display: flex; flex-direction: column; overflow: hidden;">
                                                        <div id="apply-content-container" style="flex: 1; overflow-y: auto; padding: 20px;">
                                                            <!-- Product details will be shown here -->
                                                            <div id="apply-welcome" style="text-align: center; padding: 60px 20px; color: #6c757d;">
                                                                <i class="fas fa-mouse-pointer" style="font-size: 48px; margin-bottom: 20px; color: #dee2e6;"></i>
                                                                <h3 style="margin: 0 0 10px 0; color: #495057;">Select a Product</h3>
                                                                <p style="margin: 0;">Choose a product from the left panel to review AI-generated content before applying changes.</p>
                                                            </div>
                                                        </div>
                                                        
                                                        <!-- Bottom Action Bar -->
                                                        <div id="apply-action-bar" style="display: none; border-top: 1px solid #dee2e6; padding: 15px 20px; background: #f8f9fa; flex-shrink: 0;">
                                                            <div style="display: flex; justify-content: flex-end; align-items: center; gap: 10px;">
                                                                <button onclick="closeApplyDialog()" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; transition: all 0.2s;" onmouseover="this.style.background='#5a6268'" onmouseout="this.style.background='#6c757d'">
                                                                    Cancel
                                                                </button>
                                                                <button id="apply-changes-btn" onclick="applyProductChanges('${groupName}')" style="background: #ffc107; color: #212529; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 600; transition: all 0.2s;" onmouseover="this.style.background='#e0a800'" onmouseout="this.style.background='#ffc107'">
                                                                    <i class="fas fa-check" style="margin-right: 6px;"></i>
                                                                    Apply Changes
                                                                </button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <style>
                                                .apply-product-nav-item {
                                                    display: flex;
                                                    align-items: center;
                                                    padding: 12px;
                                                    margin-bottom: 8px;
                                                    border-radius: 8px;
                                                    cursor: pointer;
                                                    transition: all 0.2s ease;
                                                    border: 1px solid transparent;
                                                    width: 100%;
                                                    box-sizing: border-box;
                                                    min-width: 0;
                                                    outline: none;
                                                }
                                                
                                                .apply-product-nav-item:hover {
                                                    background: #e9ecef;
                                                    border-color: #dee2e6;
                                                }
                                                
                                                .apply-product-nav-item:focus {
                                                    background: #f8f9fa;
                                                    border-color: #007cba;
                                                    box-shadow: 0 0 0 2px rgba(0, 124, 186, 0.2);
                                                }
                                                
                                                .apply-product-nav-item.active {
                                                    background: #e7f3ff;
                                                    border-color: #0073aa;
                                                    box-shadow: 0 2px 4px rgba(0, 115, 170, 0.2);
                                                }
                                                
                                                .apply-product-nav-item.active:focus {
                                                    box-shadow: 0 2px 4px rgba(0, 115, 170, 0.2), 0 0 0 2px rgba(0, 124, 186, 0.3);
                                                }
                                                
                                                .apply-product-nav-info {
                                                    flex: 1;
                                                    min-width: 0;
                                                }
                                                
                                                .apply-product-nav-title {
                                                    font-size: 13px;
                                                    font-weight: 600;
                                                    color: #333;
                                                    margin: 0 0 4px 0;
                                                    white-space: nowrap;
                                                    overflow: hidden;
                                                    text-overflow: ellipsis;
                                                }
                                                
                                                .apply-product-nav-upc {
                                                    font-size: 11px;
                                                    color: #6c757d;
                                                    font-family: monospace;
                                                    margin: 0;
                                                }
                                                
                                                .apply-product-nav-status {
                                                    font-size: 10px;
                                                    padding: 2px 6px;
                                                    border-radius: 10px;
                                                    font-weight: 500;
                                                    flex-shrink: 0;
                                                }
                                                
                                                .description-tabs {
                                                    margin-top: 15px;
                                                }
                                                
                                                .description-tab-buttons {
                                                    display: flex;
                                                    border-bottom: 2px solid #f0f0f0;
                                                    margin-bottom: 15px;
                                                }
                                                
                                                .description-tab-btn {
                                                    background: none;
                                                    border: none;
                                                    outline: none;
                                                    padding: 10px 16px;
                                                    cursor: pointer;
                                                    font-size: 14px;
                                                    font-weight: 500;
                                                    color: #666;
                                                    border-bottom: 2px solid transparent;
                                                    transition: all 0.2s ease;
                                                }
                                                
                                                .description-tab-btn:hover {
                                                    color: #0073aa;
                                                    background: #f0f8ff;
                                                }
                                                
                                                .description-tab-btn.active {
                                                    color: #0073aa !important;
                                                    border-bottom-color: #0073aa !important;
                                                    font-weight: 600;
                                                }
                                                
                                                .description-tab-btn:focus {
                                                    outline: none !important;
                                                    border: none !important;
                                                    box-shadow: none !important;
                                                }
                                                
                                                .description-tab-btn:focus.active {
                                                    color: #0073aa !important;
                                                    border-bottom-color: #0073aa !important;
                                                }
                                                
                                                .description-tab-pane {
                                                    display: none;
                                                }
                                                
                                                .description-tab-pane.active {
                                                    display: block;
                                                    animation: fadeIn 0.3s ease-in;
                                                }
                                                
                                                @keyframes fadeIn {
                                                    from { opacity: 0; transform: translateY(10px); }
                                                    to { opacity: 1; transform: translateY(0); }
                                                }
                                                
                                                .field-section {
                                                    background: #f8f9fa;
                                                    border: 1px solid #dee2e6;
                                                    border-radius: 8px;
                                                    padding: 20px;
                                                    margin-bottom: 20px;
                                                }
                                                
                                                .field-section h4 {
                                                    margin: 0 0 15px 0;
                                                    color: #495057;
                                                    font-size: 16px;
                                                    font-weight: 600;
                                                    display: flex;
                                                    align-items: center;
                                                    gap: 8px;
                                                    border-bottom: 2px solid #007cba;
                                                    padding-bottom: 5px;
                                                }
                                                
                                                .field-row {
                                                    margin-bottom: 12px;
                                                }
                                                
                                                .field-row:last-child {
                                                    margin-bottom: 0;
                                                }
                                                
                                                .field-label {
                                                    font-weight: 600;
                                                    color: #495057;
                                                    font-size: 13px;
                                                    display: block;
                                                    margin-bottom: 4px;
                                                }
                                                
                                                .field-value {
                                                    background: white;
                                                    border: 1px solid #dee2e6;
                                                    border-radius: 4px;
                                                    padding: 8px 12px;
                                                    font-size: 14px;
                                                    line-height: 1.5;
                                                    color: #333;
                                                }
                                                
                                                .html-content {
                                                    line-height: 1.6;
                                                }
                                                
                                                .html-content p {
                                                    margin: 0 0 10px 0;
                                                }
                                                
                                                .html-content ul, .html-content ol {
                                                    margin: 10px 0;
                                                    padding-left: 20px;
                                                }
                                                
                                                .html-content h2 {
                                                    color: #333;
                                                    margin: 15px 0 10px 0;
                                                    font-size: 18px;
                                                }
                                                
                                                .product-header {
                                                    background: #ffffff;
                                                    border: 1px solid #dee2e6;
                                                    border-radius: 10px;
                                                    padding: 20px;
                                                    margin-bottom: 20px;
                                                    display: flex;
                                                    gap: 20px;
                                                    align-items: flex-start;
                                                }
                                                
                                                .product-image {
                                                    width: 120px;
                                                    height: 120px;
                                                    border-radius: 8px;
                                                    object-fit: cover;
                                                    border: 2px solid #fff;
                                                    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                                                    flex-shrink: 0;
                                                }
                                                
                                                .product-basic-info {
                                                    flex: 1;
                                                }
                                                
                                                .product-basic-info h3 {
                                                    margin: 0 0 15px 0;
                                                    color: #333;
                                                    font-size: 20px;
                                                    font-weight: 700;
                                                    line-height: 1.3;
                                                }
                                                
                                                .product-details-row {
                                                    display: flex;
                                                    gap: 20px;
                                                    margin-bottom: 8px;
                                                    flex-wrap: wrap;
                                                }
                                                
                                                .product-details-row span {
                                                    font-size: 12px;
                                                    color: #495057;
                                                }
                                                
                                                .tokens-used {
                                                    margin-top: 6px;
                                                    font-size: 11px;
                                                    color: #007cba;
                                                    font-weight: 600;
                                                }
                                                
                                                .tokens-used i {
                                                    margin-right: 4px;
                                                    font-size: 10px;
                                                }
                                                
                                                .needs-review-badge {
                                                    background: #f4bda6ff;
                                                    color: black;
                                                    margin-top: 4px;
                                                    padding: 3px 6px;
                                                    font-size: 10px;
                                                    display: inline-flex;
                                                    align-items: center;
                                                    gap: 4px;
                                                    border-radius: 4px;
                                                }
                                                
                                                .product-notes {
                                                    background: #f8f9fa;
                                                    border: 1px solid #dee2e6;
                                                    border-radius: 6px;
                                                    padding: 10px;
                                                    margin-top: 10px;
                                                    font-size: 13px;
                                                    color: #495057;
                                                }
                                                
                                                #pagination-controls button {
                                                    transition: all 0.2s ease;
                                                    min-width: 28px;
                                                    height: 24px;
                                                    display: flex;
                                                    align-items: center;
                                                    justify-content: center;
                                                }
                                                
                                                #pagination-controls button:not(:disabled):hover {
                                                    background: #e9ecef !important;
                                                    border-color: #adb5bd !important;
                                                    color: #495057 !important;
                                                }
                                                
                                                #pagination-controls button:disabled {
                                                    cursor: not-allowed !important;
                                                }
                                            </style>
                                        `;
                                        
                                        document.body.appendChild(modal);
                                        
                                        // Close on background click
                                        modal.addEventListener('click', function(e) {
                                            if (e.target === modal) {
                                                closeApplyDialog();
                                            }
                                        });
                                        
                                        // Add global function for acknowledging and continuing
                                        window.acknowledgeAndContinue = function() {
                                            // Hide important notice
                                            const importantNotice = document.getElementById('apply-important-notice');
                                            const mainContent = document.getElementById('apply-main-content');
                                            
                                            if (importantNotice) importantNotice.style.display = 'none';
                                            if (mainContent) mainContent.style.display = 'flex';
                                            
                                            // Load product data with default pagination using stored group data
                                            loadApplyProducts(groupName, groupConfig);
                                        };
                                    }
                                                    
                                    // Close apply dialog
                                    function closeApplyDialog() {
                                        const modal = document.getElementById('apply-dialog-modal');
                                        if (modal) {
                                            modal.remove();
                                        }
                                    }
                                                    
                                    // Load products for apply dialog with pagination support
                                    async function loadApplyProducts(groupName, groupConfig, paginationParams = {}) {
                                        
                                        // console.log('loadApplyProducts called with:', { groupName, groupConfig, paginationParams });
                                        
                                        const loadingDiv = document.getElementById('apply-loading');
                                        const navContentDiv = document.getElementById('apply-nav-content');
                                        const noProductsDiv = document.getElementById('no-apply-products');
                                        const actionBarDiv = document.getElementById('apply-action-bar');
                                        const applyBtn = document.getElementById('apply-changes-btn');
                                        
                                        // Set default pagination parameters
                                        const pagination = {
                                            page: paginationParams.page || 1,
                                            page_size: paginationParams.page_size || 100,
                                            last_id: paginationParams.last_id || null,
                                            order_by: paginationParams.order_by || "last_updated",
                                            order_dir: paginationParams.order_dir || "DESC"
                                        };
                                     
                                        try {
                                            // Call API to get AI processed products for this group
                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify({
                                                    "action": "get_ai_product_info",
                                                    "data": {
                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                        "product_group_name": groupName,
                                                        ...pagination
                                                    }
                                                })
                                            });
                                            
                                            const responseText = await response.json();
                                            // console.log('Raw API Response:', responseText);
                                            
                                            let data;
                                            try {
                                                // Try to parse as JSON first
                                                data = JSON.parse(responseText);
                                            } catch (e) {
                                                // console.log('Response is not JSON, trying to parse as double-encoded JSON');
                                                try {
                                                    // If that fails, try parsing as double-encoded JSON string
                                                    const data_string = JSON.parse(responseText);
                                                    data = JSON.parse(data_string);
                                                } catch (e2) {
                                                    console.error('Failed to parse response as JSON:', e2);
                                                    throw new Error('Invalid JSON response from API');
                                                }
                                            }

                                            if (loadingDiv) loadingDiv.style.display = 'none';
                                            
                                            // Handle paginated response structure
                                            const products = data.success && data.product_info && data.product_info.product_info ? data.product_info.product_info : [];
                                            
                                            // Log the response for debugging
                                            // console.log('Apply Products API Response:', data);
                                            // console.log('Products array:', products);
                                            
                                            const hasValidProducts = products.length > 0 && products.some(product => product.upc); // Filter out incomplete entries
                                            // console.log('hasValidProducts:', hasValidProducts);
                                            
                                            if (hasValidProducts) {
                                                // Filter out products that only have product_group_name (incomplete entries)
                                                // Only require UPC, title is optional (might not be generated yet)
                                                const validProducts = products.filter(product => product.upc && product.upc.trim());
                                                
                                                // console.log('Valid products after filtering:', validProducts);
                                                // console.log('Valid products count:', validProducts.length);
                                                
                                                // Scroll navigation panel to top when products load
                                                if (navContentDiv) {
                                                    navContentDiv.scrollTop = 0;
                                                }
                                                
                                                // Show navigation content and action bar
                                                if (navContentDiv) navContentDiv.style.display = 'flex';
                                                if (actionBarDiv) actionBarDiv.style.display = 'block';
                                                if (applyBtn) applyBtn.style.display = 'inline-block';
                                                if (noProductsDiv) noProductsDiv.style.display = 'none';
                                                
                                                // Store pagination data globally
                                                const paginationData = data.product_info.pagination || {};
                                                window.applyPaginationData = {
                                                    ...paginationData,
                                                    groupName: groupName,
                                                    groupConfig: groupConfig
                                                };
                                                
                                                // Display product count and pagination info
                                                const productCountDiv = document.getElementById('product-count');
                                                if (productCountDiv) {
                                                    const summary = data.product_info.summary || {};
                                                    const totalItems = paginationData.total_items || summary.products_processed || validProducts.length;
                                                    const currentPage = paginationData.page || 1;
                                                    const pageSize = paginationData.page_size || 100;
                                                    
                                                    // Calculate range for current page
                                                    const startItem = ((currentPage - 1) * pageSize) + 1;
                                                    const endItem = Math.min(currentPage * pageSize, totalItems);
                                                    
                                                    let countText = `${startItem}-${endItem} of ${totalItems}`;
                                                    
                                                    productCountDiv.innerHTML = `
                                                        <div style="display: flex; justify-content: space-between; align-items: center;">
                                                            <span>${countText}</span>
                                                            <div id="pagination-controls" style="display: ${(paginationData.total_pages && paginationData.total_pages > 1) ? 'flex' : 'none'}; gap: 5px; align-items: center;">
                                                                <button id="prev-page-btn" onclick="loadApplyProductPage('prev')" style="background: #f8f9fa; border: 1px solid #dee2e6; color: #495057; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px; ${(paginationData.page <= 1) ? 'opacity: 0.5; cursor: not-allowed;' : ''}" ${(paginationData.page <= 1) ? 'disabled' : ''}>
                                                                    <i class="fas fa-chevron-left"></i>
                                                                </button>
                                                                <span style="font-size: 12px; color: #6c757d; padding: 0 8px;">${paginationData.page || 1} of ${paginationData.total_pages || 1}</span>
                                                                <button id="next-page-btn" onclick="loadApplyProductPage('next')" style="background: #f8f9fa; border: 1px solid #dee2e6; color: #495057; padding: 4px 8px; border-radius: 4px; cursor: pointer; font-size: 12px; ${(paginationData.page >= paginationData.total_pages) ? 'opacity: 0.5; cursor: not-allowed;' : ''}" ${(paginationData.page >= paginationData.total_pages) ? 'disabled' : ''}>
                                                                    <i class="fas fa-chevron-right"></i>
                                                                </button>
                                                            </div>
                                                        </div>
                                                    `;
                                                }
                                                
                                                // Store products data globally for apply function
                                                window.applyProductsData = validProducts;
                                                
                                                // Display products in navigation panel
                                                displayApplyProductsNavigation(validProducts);
                                                
                                            } else {
                                                // No products found
                                                // console.log('No valid products found. Products length:', products.length);
                                                // console.log('Raw products:', products);
                                                
                                                if (navContentDiv) navContentDiv.style.display = 'none';
                                                if (actionBarDiv) actionBarDiv.style.display = 'none';
                                                if (applyBtn) applyBtn.style.display = 'none';
                                                if (noProductsDiv) noProductsDiv.style.display = 'block';
                                            }
                                            
                                        } catch (error) {
                                            console.error('Error loading apply products:', error);
                                            if (loadingDiv) loadingDiv.style.display = 'none';
                                            if (navContentDiv) navContentDiv.style.display = 'none';
                                            if (actionBarDiv) actionBarDiv.style.display = 'none';
                                            if (applyBtn) applyBtn.style.display = 'none';
                                            if (noProductsDiv) {
                                                noProductsDiv.style.display = 'block';
                                                noProductsDiv.innerHTML = `
                                                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc3545; margin-bottom: 15px;"></i>
                                                    <h3 style="margin: 0 0 10px 0; color: #495057; font-size: 16px;">Error Loading Products</h3>
                                                    <p style="margin: 0; color: #6c757d;">Failed to load product data from the API. Please try again later.</p>
                                                `;
                                            }
                                        }
                                    }
                                    
                                    // Handle pagination for apply dialog
                                    async function loadApplyProductPage(direction) {
                                        if (!window.applyPaginationData) {
                                            console.error('No pagination data available');
                                            return;
                                        }
                                        
                                        const paginationData = window.applyPaginationData;
                                        let newPage = paginationData.page || 1;
                                        
                                        if (direction === 'prev' && newPage > 1) {
                                            newPage--;
                                        } else if (direction === 'next' && newPage < (paginationData.total_pages || 1)) {
                                            newPage++;
                                        } else {
                                            return; // No change needed
                                        }
                                        
                                        // Disable pagination buttons during loading
                                        const prevBtn = document.getElementById('prev-page-btn');
                                        const nextBtn = document.getElementById('next-page-btn');
                                        if (prevBtn) {
                                            prevBtn.disabled = true;
                                            prevBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                                        }
                                        if (nextBtn) {
                                            nextBtn.disabled = true;
                                            nextBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
                                        }
                                        
                                        // Show loading state in navigation
                                        const navContent = document.getElementById('apply-nav-content');
                                        const loading = document.getElementById('apply-loading');
                                        if (navContent) navContent.style.display = 'none';
                                        if (loading) {
                                            loading.style.display = 'block';
                                            loading.innerHTML = `
                                                <div style="display: inline-flex; align-items: center; gap: 10px; color: #4a5568;">
                                                    <i class="fas fa-spinner fa-spin" style="font-size: 20px;"></i>
                                                    <span style="font-size: 16px; font-weight: 500;">Loading Page ${newPage}...</span>
                                                </div>
                                                <p style="margin: 10px 0 0 0; color: #718096; font-size: 14px;">Fetching products</p>
                                            `;
                                        }
                                        
                                        try {
                                            // Load new page
                                            const paginationParams = {
                                                page: newPage,
                                                page_size: paginationData.page_size || 100,
                                                last_id: null, // Reset last_id for new page
                                                order_by: paginationData.order_by || "last_updated",
                                                order_dir: paginationData.order_dir || "DESC"
                                            };
                                            
                                            await loadApplyProducts(paginationData.groupName, paginationData.groupConfig, paginationParams);
                                            
                                            // Scroll to top of the navigation panel after page loads
                                            const navContent = document.getElementById('apply-nav-content');
                                            if (navContent) {
                                                navContent.scrollTop = 0;
                                            }
                                        } catch (error) {
                                            console.error('Error loading page:', error);
                                            // Re-enable buttons on error
                                            if (prevBtn) {
                                                prevBtn.disabled = false;
                                                prevBtn.innerHTML = '<i class="fas fa-chevron-left"></i>';
                                            }
                                            if (nextBtn) {
                                                nextBtn.disabled = false;
                                                nextBtn.innerHTML = '<i class="fas fa-chevron-right"></i>';
                                            }
                                        }
                                    }
                                    
                                    // Handle keyboard navigation for product list
                                    function handleNavigationKeydown(e, currentIndex) {
                                        // console.log('handleNavigationKeydown called with key:', e.key, 'currentIndex:', currentIndex);
                                        
                                        const navItems = document.querySelectorAll('.apply-product-nav-item');
                                        // console.log('Found navigation items:', navItems.length);
                                        
                                        switch(e.key) {
                                            case 'ArrowDown':
                                                e.preventDefault();
                                                e.stopPropagation();
                                                const nextIndex = (currentIndex + 1) % navItems.length;
                                                // console.log('Moving to next index:', nextIndex);
                                                navItems[nextIndex].focus();
                                                showApplyProductDetail(nextIndex);
                                                break;
                                                
                                            case 'ArrowUp':
                                                e.preventDefault();
                                                e.stopPropagation();
                                                const prevIndex = (currentIndex - 1 + navItems.length) % navItems.length;
                                                // console.log('Moving to previous index:', prevIndex);
                                                navItems[prevIndex].focus();
                                                showApplyProductDetail(prevIndex);
                                                break;
                                                
                                            case 'Enter':
                                            case ' ':
                                                e.preventDefault();
                                                e.stopPropagation();
                                                // console.log('Enter/Space pressed, selecting product:', currentIndex);
                                                showApplyProductDetail(currentIndex);
                                                break;
                                                
                                            case 'Home':
                                                e.preventDefault();
                                                e.stopPropagation();
                                                // console.log('Home pressed, moving to first product');
                                                navItems[0].focus();
                                                showApplyProductDetail(0);
                                                break;
                                                
                                            case 'End':
                                                e.preventDefault();
                                                e.stopPropagation();
                                                const lastIndex = navItems.length - 1;
                                                // console.log('End pressed, moving to last product:', lastIndex);
                                                navItems[lastIndex].focus();
                                                showApplyProductDetail(lastIndex);
                                                break;
                                        }
                                        
                                        // Ensure focused item is visible
                                        if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
                                            setTimeout(() => {
                                                const focusedItem = document.activeElement;
                                                if (focusedItem && focusedItem.classList.contains('apply-product-nav-item')) {
                                                    focusedItem.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                                                }
                                            }, 0);
                                        }
                                    }
                                                    
                                    // Display products navigation for apply dialog
                                    function displayApplyProductsNavigation(products) {
                                        // console.log('displayApplyProductsNavigation called with products:', products);
                                        
                                        const container = document.getElementById('product-nav-list');
                                        // console.log('Navigation container found:', container);
                                        
                                        if (!container) {
                                            console.error('product-nav-list container not found!');
                                            return;
                                        }
                                        
                                        container.innerHTML = '';
                                        
                                        // console.log('Processing', products.length, 'products for navigation');
                                        
                        products.forEach((product, index) => {
                            // Create navigation item
                            const navItem = document.createElement('div');
                            navItem.className = 'apply-product-nav-item';
                            navItem.tabIndex = 0; // Make focusable
                            navItem.setAttribute('data-index', index);
                            navItem.onclick = () => {
                                showApplyProductDetail(index);
                                navItem.focus(); // Set keyboard focus when clicked
                            };
                            
                            // Add keyboard navigation
                            navItem.onkeydown = (e) => handleNavigationKeydown(e, index);                                            navItem.innerHTML = `
                                                <div class="apply-product-nav-info">
                                                    <h4 class="apply-product-nav-title">${product.title || 'Unknown Product'}</h4>
                                                    <p class="apply-product-nav-upc">${product.upc || 'N/A'}</p>
                                                </div>
                                            `;
                                            
                                            // console.log(`Adding navigation item ${index}:`, product.title || 'Unknown Product');
                                            container.appendChild(navItem);
                                        });
                                        
                                        // console.log('Navigation population complete. Container children count:', container.children.length);
                                        
                                        // Debug DOM structure
                                        console.log('Navigation container HTML:', container.innerHTML.substring(0, 500));
                                        console.log('First navigation item:', container.firstElementChild);
                                        if (container.firstElementChild) {
                                            const firstItem = container.firstElementChild;
                                            console.log('First item computed style display:', window.getComputedStyle(firstItem).display);
                                            console.log('First item computed style visibility:', window.getComputedStyle(firstItem).visibility);
                                            console.log('First item offset dimensions:', {
                                                offsetWidth: firstItem.offsetWidth,
                                                offsetHeight: firstItem.offsetHeight,
                                                offsetTop: firstItem.offsetTop,
                                                offsetLeft: firstItem.offsetLeft
                                            });
                                        }
                                        
                                        // Debug container dimensions
                                        console.log('Container dimensions:', {
                                            offsetWidth: container.offsetWidth,
                                            offsetHeight: container.offsetHeight,
                                            clientWidth: container.clientWidth,
                                            scrollWidth: container.scrollWidth
                                        });
                                        console.log('Container computed style width:', window.getComputedStyle(container).width);
                                        console.log('Container parent dimensions:', {
                                            offsetWidth: container.parentElement.offsetWidth,
                                            clientWidth: container.parentElement.clientWidth
                                        });
                                        console.log('Navigation panel dimensions:', {
                                            offsetWidth: document.getElementById('apply-nav-panel').offsetWidth,
                                            clientWidth: document.getElementById('apply-nav-panel').clientWidth
                                        });
                                    }
                                    
                                    // Show product detail in apply dialog content panel
                                    function showApplyProductDetail(productIndex) {
                                        if (!window.applyProductsData || !window.applyProductsData[productIndex]) {
                                            console.error('Product data not found');
                                            return;
                                        }
                                        
                                        const product = window.applyProductsData[productIndex];
                                        const contentContainer = document.getElementById('apply-content-container');
                                        
                                        // Update navigation selection
                                        const navItems = document.querySelectorAll('.apply-product-nav-item');
                                        navItems.forEach((item, index) => {
                                            if (index === productIndex) {
                                                item.classList.add('active');
                                            } else {
                                                item.classList.remove('active');
                                            }
                                        });
                                        
                        // Extract original product info if available
                        let originalProductName = 'Unknown Product';
                        let imageUrl = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSIjZjNmNGY2Ii8+CjxwYXRoIGQ9Ik00MCA0MHY0MGg0MFY0MEg0MHptMzAgMzBINTBWNTBoMjB2MjB6IiBmaWxsPSIjOWNhM2FmIi8+Cjwvc3ZnPgo=';
                        let category = 'N/A';
                        let manufacturer = 'N/A';
                        let price = 'N/A';
                        let originalDescriptions = [];
                        
                        if (product.original_product_info) {
                            try {
                                const original_product_data = JSON.parse(product.original_product_info);
                                if (original_product_data.name) {
                                    const nameArray = JSON.parse(original_product_data.name);
                                    originalProductName = Array.isArray(nameArray) ? nameArray[0] : nameArray;
                                }
                                if (original_product_data.image_url) {
                                    const imageArray = JSON.parse(original_product_data.image_url);
                                    imageUrl = Array.isArray(imageArray) ? imageArray[0] : imageArray;
                                }
                                if (original_product_data.category) {
                                    const categoryArray = JSON.parse(original_product_data.category);
                                    category = Array.isArray(categoryArray) ? categoryArray[0] : categoryArray;
                                }
                                if (original_product_data.mfg_name) {
                                    const mfgArray = JSON.parse(original_product_data.mfg_name);
                                    manufacturer = Array.isArray(mfgArray) ? mfgArray[0] : mfgArray;
                                }
                                if (original_product_data.unit_price) {
                                    const priceArray = JSON.parse(original_product_data.unit_price);
                                    price = Array.isArray(priceArray) ? `$${priceArray[0]}` : `$${priceArray}`;
                                }
                                if (original_product_data.description) {
                                    const descArray = JSON.parse(original_product_data.description);
                                    if (Array.isArray(descArray)) {
                                        originalDescriptions = descArray.filter(desc => desc && desc.trim() !== '');
                                    } else if (descArray && descArray.trim() !== '') {
                                        originalDescriptions = [descArray];
                                    }
                                }
                            } catch (e) {
                                console.warn('Could not parse original product info:', e);
                            }
                        }
                        
                        if (originalDescriptions.length === 0) {
                            originalDescriptions = ['No original description available'];
                        }
                        
                        // Use AI-generated title for display, fallback to original if not available
                        let displayTitle = product.title_75 || originalProductName;
                        
                        // Check if title is AI-generated
                        const isAIGenerated = product.title && product.title !== originalProductName;
                        
                        // Display the product details
                                        contentContainer.innerHTML = `
                                            <div class="product-header">
                                                <img src="${imageUrl}" alt="${displayTitle}" class="product-image" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSIjZjNmNGY2Ii8+CjxwYXRoIGQ9Ik00MCA0MHY0MGg0MFY0MEg0MHptMzAgMzBINTBWNTBoMjB2MjB6IiBmaWxsPSIjOWNhM2FmIi8+Cjwvc3ZnPgo='">
                                                <div class="product-basic-info">
                                                    <h3 style="margin: 0; ${isAIGenerated ? 'background: linear-gradient(135deg, #e7f3ff 0%, #cce7ff 100%); padding: 8px 12px; border-radius: 6px; border-left: 4px solid #007cba; position: relative;' : ''}">${displayTitle}${isAIGenerated ? '<span style="display: inline-flex; align-items: center; margin-left: 8px; background: #007cba; color: white; font-size: 10px; padding: 2px 6px; border-radius: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;"><i class="fas fa-robot" style="margin-right: 3px; font-size: 9px;"></i>AI Generated</span>' : ''}</h3>
                                                    <div class="product-details-row">
                                                        <span><strong>Brand:</strong> ${manufacturer}</span>
                                                        <span><strong>UPC:</strong> ${product.upc || 'N/A'}</span>
                                                        <span><strong>Category:</strong> ${category}</span>
                                                        <span><strong>Updated:</strong> ${product.last_updated ? new Date(product.last_updated).toLocaleString() : 'N/A'}</span>
                                                    </div>
                                                    <div class="tokens-used">
                                                        <i class="fas fa-coins"></i> Tokens Used: ${Math.round(product.tokens_used || 0).toLocaleString()}
                                                    </div>
                                                    ${product.needs_review ? '<div class="needs-review-badge"><i class="fas fa-exclamation-triangle"></i>AI Notes</div>' : ''}
                                                    ${product.notes ? `<div class="product-notes">${product.notes}</div>` : ''}
                                                </div>
                                            </div>
                                            
                                            <div class="field-sections" style="height: 100%; margin-top: 10px;">
                                                <!-- Compact Tabbed Interface -->
                                                <div class="apply-tabs" style="display: flex; margin-bottom: 0px; background: #f8f9fa; border-radius: 6px 6px 0 0; padding: 2px; gap: 1px; justify-content: flex-start; width: fit-content;">
                                                    <button type="button" class="apply-tab-btn active" onclick="switchApplyTab(this, 'descriptions-${productIndex}')" style="padding: 6px 12px; border: 1px solid #dee2e6; background: white; border-radius: 4px; color: #007cba; font-weight: 600; cursor: pointer; transition: all 0.2s ease; box-shadow: 0 1px 2px rgba(0,0,0,0.1); font-size: 13px; white-space: nowrap;">
                                                        Descriptions
                                                    </button>
                                                    <button type="button" class="apply-tab-btn" onclick="switchApplyTab(this, 'titles-${productIndex}')" style="padding: 6px 12px; border: 1px solid transparent; background: transparent; border-radius: 4px; color: #666; font-weight: 500; cursor: pointer; transition: all 0.2s ease; font-size: 13px; white-space: nowrap;">
                                                        Titles & Meta
                                                    </button>
                                                </div>
                                                
                                                <!-- Tab Content -->
                                                <div class="apply-tab-content" style="flex: 1; overflow-y: auto; background: white; border: 1px solid #dee2e6; border-radius: 0 0 6px 6px; padding: 10px;">
                                                    <!-- Descriptions Tab -->
                                                    <div id="descriptions-${productIndex}" class="apply-tab-pane" style="display: block;">
                                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; height: 400px;">
                                                            <!-- AI Generated Description -->
                                                            <div style="border-right: 1px solid #dee2e6; padding-right: 10px;">
                                                                <h5 style="margin: 0 0 10px 0; color: #007cba; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; display: flex; align-items: center; gap: 8px;">AI Generated Description<span style="display: inline-flex; align-items: center; background: #007cba; color: white; font-size: 9px; padding: 2px 6px; border-radius: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px;"><i class="fas fa-robot" style="margin-right: 3px; font-size: 8px;"></i>AI Generated</span></h5>
                                                                <div style="height: calc(100% - 25px); padding: 10px; background: #e7f3ff; border-radius: 4px; border-left: 3px solid #007cba; overflow-y: auto; font-size: 13px; line-height: 1.4;">
                                                                    <div class="html-content">${product.description || 'Not generated'}</div>
                                                                </div>
                                                            </div>
                                                            
                                                            <!-- Current Description -->
                                                            <div style="padding-left: 10px;">
                                                                <h5 style="margin: 0 0 10px 0; color: #666; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px;">Distributor Descriptions</h5>
                                                                <div style="height: calc(100% - 25px); padding: 10px; background: #f8f9fa; border-radius: 4px; overflow-y: auto; font-size: 13px; line-height: 1.4;">
                                                                    ${originalDescriptions.length > 0 ? 
                                                                        originalDescriptions.map((desc, descIndex) => `
                                                                            <div style="margin-bottom: ${descIndex < originalDescriptions.length - 1 ? '15px' : '0'};">
                                                                                ${originalDescriptions.length > 1 ? `<strong>Description ${descIndex + 1}:</strong><br>` : ''}
                                                                                ${desc}
                                                                            </div>
                                                                        `).join('') : 
                                                                        '<em style="color: #666;">No Distributor Description</em>'
                                                                    }
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Titles & Meta Tab -->
                                                    <div id="titles-${productIndex}" class="apply-tab-pane" style="display: none;">
                                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; height: 100%;">
                                                            <!-- AI Generated -->
                                                            <div style="border-right: 1px solid #dee2e6; padding-right: 10px;">
                                                                <h5 style="margin: 0 0 10px 0; color: #007cba; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px;">AI Generated</h5>
                                                                
                                                                <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Title (<75 Characters):</div>
                                                                    <div style="font-size: 13px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba;">
                                                                        ${product.title_75 || 'Not generated'}
                                                                    </div>
                                                                </div>
                                                                <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Title (<150 Characters):</div>
                                                                    <div style="font-size: 13px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba;">
                                                                        ${product.title || 'Not generated'}
                                                                    </div>
                                                                </div>
                                                                
                                                                 <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Short Description:</div>
                                                                    <div style="font-size: 13px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba;">
                                                                        ${product.short_description || 'Not generated'}
                                                                    </div>
                                                                </div>

                                                                <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Meta Description:</div>
                                                                    <div style="font-size: 12px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba; max-height: 60px; overflow-y: auto;">
                                                                        ${product.meta_description || 'Not generated'}
                                                                    </div>
                                                                </div>
                                                                
                                                                <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Image Alt Text:</div>
                                                                    <div style="font-size: 12px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba;">
                                                                        ${product.image_alt_text || 'Not generated'}
                                                                    </div>
                                                                </div>
                                                                
                                                                <div style="margin-bottom: 8px;">
                                                                    <div style="font-size: 11px; color: #666; margin-bottom: 2px;">Slug:</div>
                                                                    <div style="font-size: 11px; padding: 6px; background: #e7f3ff; border-radius: 3px; border-left: 3px solid #007cba; font-family: monospace;">
                                                                        ${product.slug || 'Not generated'}
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                            <!-- Current Data -->
                                                            <div style="padding-left: 10px;">
                                                                <h5 style="margin: 0 0 10px 0; color: #666; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px;">Current</h5>
                                                                <div style="font-size: 13px; color: #333; padding: 8px; background: #f8f9fa; border-radius: 4px; margin-bottom: 8px;">
                                                                    <strong>Title:</strong><br>
                                                                    ${originalProductName || displayTitle || 'No current title'}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        `;
                                        
                                        // Scroll the content panel to the top
                                        contentContainer.scrollTop = 0;
                                    }
                                    
                                    // Switch apply dialog tabs
                                    function switchApplyTab(button, targetId) {
                                        const container = button.closest('.field-sections');
                                        
                                        // Update buttons - inactive state
                                        container.querySelectorAll('.apply-tab-btn').forEach(btn => {
                                            btn.style.border = '1px solid transparent';
                                            btn.style.background = 'transparent';
                                            btn.style.color = '#666';
                                            btn.style.fontWeight = '500';
                                            btn.style.boxShadow = 'none';
                                        });
                                        
                                        // Update active button
                                        button.style.border = '1px solid #dee2e6';
                                        button.style.background = 'white';
                                        button.style.color = '#007cba';
                                        button.style.fontWeight = '600';
                                        button.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                                        
                                        // Update content
                                        container.querySelectorAll('.apply-tab-pane').forEach(pane => {
                                            pane.style.display = 'none';
                                        });
                                        document.getElementById(targetId).style.display = 'block';
                                    }
                                    
                                    // Switch description tabs in apply dialog
                                    function switchApplyDescriptionTab(button, targetId) {
                                        const buttonsContainer = button.closest('.description-tab-buttons');
                                        const contentContainer = button.closest('.description-tabs').querySelector('.description-tab-content');
                                        
                                        // Remove active class from all buttons and panes
                                        buttonsContainer.querySelectorAll('.description-tab-btn').forEach(btn => btn.classList.remove('active'));
                                        contentContainer.querySelectorAll('.description-tab-pane').forEach(pane => pane.classList.remove('active'));
                                        
                                        // Add active class to clicked button and target pane
                                        button.classList.add('active');
                                        
                                        // Force blur to prevent focus state interference
                                        button.blur();
                                        
                                        const targetPane = document.getElementById(targetId);
                                        if (targetPane) {
                                            targetPane.classList.add('active');
                                        }
                                    }
                                    
                                    // Add global function for switching tabs
                                    window.switchApplyDescriptionTab = switchApplyDescriptionTab;
                                    
                                    // Show welcome screen in apply dialog
                                    function showApplyWelcomeScreen() {
                                        const contentContainer = document.getElementById('apply-content-container');
                                        
                                        // Remove active selection from navigation items
                                        const navItems = document.querySelectorAll('.apply-product-nav-item');
                                        navItems.forEach(item => item.classList.remove('active'));
                                        
                                        contentContainer.innerHTML = `
                                            <div style="text-align: center; padding: 80px 40px; color: #6c757d;">
                                                <i class="fas fa-clipboard-list" style="font-size: 48px; margin-bottom: 20px; color: #dee2e6;"></i>
                                                <h3 style="margin: 0 0 10px 0; color: #495057;">Select a Product</h3>
                                                <p style="margin: 0; line-height: 1.5;">Choose a product from the navigation panel to view and apply AI-generated product information.</p>
                                            </div>
                                        `;
                                    }
                                    
                                    // Add global function for showing welcome screen
                                    window.showApplyWelcomeScreen = showApplyWelcomeScreen;
                                    
                                    // Add global functions for navigation
                                    window.displayApplyProductsNavigation = displayApplyProductsNavigation;
                                    window.showApplyProductDetail = showApplyProductDetail;
                                                    
                                    // Apply product changes
                                    async function applyProductChanges(groupName) {
                                        const applyBtn = document.getElementById('apply-changes-btn');
                                        
                                        if (!window.applyProductsData || window.applyProductsData.length === 0) {
                                            alert('No products available to apply changes to.');
                                            return;
                                        }
                                        
                                        // Disable button and show loading state
                                        applyBtn.disabled = true;
                                        applyBtn.innerHTML = '<i class="fas fa-spinner fa-spin" style="margin-right: 6px;"></i>Applying Changes...';
                                        
                                        try {
                                            // Prepare data for API call
                                            const requestData = {
                                                "action": "run_ai_woocommerce_product_update",
                                                "data": {
                                                    "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                    "product_group_name": groupName
                                                }
                                            };
                                            
                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify(requestData)
                                            });
                                            
                                            const data = await response.json();
                                            
                                            if (data.success) {
                                                // Show success message
                                                const successMsg = document.createElement('div');
                                                successMsg.style.cssText = 'background: #d4edda; color: #155724; border: 1px solid #c3e6cb; padding: 15px; border-radius: 8px; margin-bottom: 15px;';
                                                successMsg.innerHTML = `
                                                    <i class="fas fa-check-circle" style="margin-right: 8px;"></i>
                                                    <strong>Success!</strong> A job to update the products has been started, check your email for updates.
                                                    ${data.message ? `<br><small>${data.message}</small>` : ''}
                                                `;
                                                applyBtn.parentElement.insertBefore(successMsg, applyBtn.parentElement.firstChild);
                                                
                                                // Replace the button container with just a Close button
                                                const buttonContainer = applyBtn.parentElement;
                                                buttonContainer.innerHTML = `
                                                    ${successMsg.outerHTML}
                                                    <div style="display: flex; justify-content: center;">
                                                        <button onclick="closeApplyDialog()" style="background: #28a745; color: white; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500; transition: all 0.2s;" onmouseover="this.style.background='#218838'" onmouseout="this.style.background='#28a745'">
                                                            <i class="fas fa-times" style="margin-right: 6px;"></i>
                                                            Close
                                                        </button>
                                                    </div>
                                                `;
                                               
                                                
                                            } else {
                                                throw new Error(data.message || 'Failed to apply changes');
                                            }
                                            
                                        } catch (error) {
                                            console.error('Error applying product changes:', error);
                                            
                                            // Reset button and show error
                                            applyBtn.disabled = false;
                                            applyBtn.innerHTML = '<i class="fas fa-check" style="margin-right: 6px;"></i>Apply Changes';
                                            applyBtn.style.background = '#ffc107';
                                            
                                            // Show error message
                                            const errorMsg = document.createElement('div');
                                            errorMsg.style.cssText = 'background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; padding: 15px; border-radius: 8px; margin-top: 15px;';
                                            errorMsg.innerHTML = `
                                                <i class="fas fa-exclamation-triangle" style="margin-right: 8px;"></i>
                                                <strong>Error:</strong> ${error.message}
                                            `;
                                            applyBtn.parentElement.insertBefore(errorMsg, applyBtn.parentElement.firstChild);
                                        }
                                    }                                                    // Load test results for product group
                                                    async function loadTestResults(groupName) {
                                        const loadingDiv = document.getElementById('test-loading');
                                        const resultsDiv = document.getElementById('test-results');
                                        const noTestsDiv = document.getElementById('no-tests-message');
                                        const testRunSelector = document.getElementById('test-run-selector');
                                        
                                        // Show loading state
                                        if (loadingDiv) loadingDiv.style.display = 'block';
                                        if (resultsDiv) resultsDiv.style.display = 'none';
                                        if (noTestsDiv) noTestsDiv.style.display = 'none';
                                        if (testRunSelector) testRunSelector.style.display = 'none';
                                        
                                        const loadingText = document.getElementById('loading-text');
                                        const loadingSubtext = document.getElementById('loading-subtext');
                                        if (loadingText) loadingText.textContent = 'Loading test results...';
                                        if (loadingSubtext) loadingSubtext.textContent = 'Fetching the latest test data';
                                        
                                        try {
                                            // First, get all test jobs for this product group
                                            const config = editor.get();
                                            const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                            
                                            if (!groupConfig) {
                                                throw new Error('Product group configuration not found');
                                            }
                                            
                                            if (loadingSubtext) loadingSubtext.textContent = 'Fetching available test jobs...';
                                            
                                            // Get all test jobs for this product group
                                            const jobsResponse = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify({
                                                    "action": "get_ai_product_info_jobs",
                                                    "data": {
                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                        "product_group_name": groupName
                                                    }
                                                })
                                            });

                                            const jobsData = await jobsResponse.json();
                                            const jobs = jobsData.jobs || [];
                                            
                                            if (jobs.length === 0) {
                                                // No jobs found, show no tests message
                                                if (loadingDiv) loadingDiv.style.display = 'none';
                                                if (noTestsDiv) noTestsDiv.style.display = 'block';
                                                return;
                                            }
                                            
                                            // Find the most recent completed test job
                                            const completedJobs = jobs.filter(job => job.status === 'Succeeded' && job.is_test_run);

                                            if (completedJobs.length === 0) {
                                                // No completed test jobs, check for running test jobs
                                                const runningJobs = jobs.filter(job => job.status === 'Running' && job.is_test_run);
                                                if (runningJobs.length > 0) {
                                                    showRunningJobStatus(runningJobs[0]);
                                                    return;
                                                } else {
                                                    // No running or completed jobs
                                                    if (loadingDiv) loadingDiv.style.display = 'none';
                                                    if (noTestsDiv) noTestsDiv.style.display = 'block';
                                                    return;
                                                }
                                            }
                                            
                                            // Sort completed jobs by created date (most recent first)
                                            completedJobs.sort((a, b) => new Date(b.start_time) - new Date(a.start_time));
                                            const latestJob = completedJobs[0];
                                            
                                            // Populate job selector dropdown
                                            if (testRunSelector && completedJobs.length > 0) {
                                                const select = testRunSelector.querySelector('select');
                                                if (select) {
                                                    select.innerHTML = '';
                                                    completedJobs.forEach(job => {
                                                        const option = document.createElement('option');
                                                        option.value = job.id;
                                                        // Assume start_time is UTC and convert to local browser time
                                                        let jobDate;
                                                        if (job.start_time.includes('Z') || job.start_time.includes('+')) {
                                                            // Already has timezone info
                                                            jobDate = new Date(job.start_time);
                                                        } else {
                                                            // Assume UTC and append 'Z' to ensure UTC parsing
                                                            jobDate = new Date(job.start_time + 'Z');
                                                        }
                                                        const formattedDate = jobDate.toLocaleDateString('en-US', {
                                                            month: 'short',
                                                            day: 'numeric',
                                                            year: 'numeric'
                                                        });
                                                        const formattedTime = jobDate.toLocaleTimeString('en-US', {
                                                            hour: 'numeric',
                                                            minute: '2-digit',
                                                            hour12: true
                                                        });
                                                        option.textContent = `${formattedDate} at ${formattedTime}`;
                                                        if (job.id === latestJob.id) {
                                                            option.selected = true;
                                                        }
                                                        select.appendChild(option);
                                                    });
                                                    
                                                    // Add change handler for dropdown
                                                    select.onchange = function() {
                                                        const selectedJob = completedJobs.find(job => job.id === this.value);
                                                        loadSpecificTestResult(groupName, this.value, selectedJob);
                                                    };
                                                }
                                                testRunSelector.style.display = 'block';
                                            }
                                            
                                            // Load the latest test results
                                            await loadSpecificTestResult(groupName, latestJob.id, latestJob);
                                            
                                        } catch (error) {
                                            console.error('Error loading test results:', error);
                                            if (loadingDiv) loadingDiv.style.display = 'none';
                                            if (noTestsDiv) {
                                                noTestsDiv.style.display = 'block';
                                                noTestsDiv.innerHTML = '<p>Error loading test results. Please try again.</p>';
                                            }
                                        }
                                    }
                                    
                                    // Load specific test result by job ID
                                    async function loadSpecificTestResult(groupName, jobId, jobData = null) {
                                        const loadingDiv = document.getElementById('test-loading');
                                        const resultsDiv = document.getElementById('test-results');
                                        const loadingSubtext = document.getElementById('loading-subtext');
                                        
                                        // Show loading state
                                        if (loadingDiv) loadingDiv.style.display = 'block';
                                        if (resultsDiv) resultsDiv.style.display = 'none';
                                        if (loadingSubtext) loadingSubtext.textContent = 'Loading test data...';
                                        
                                        try {
                                            // Get specific test results
                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify({
                                                    "action": "get_ai_product_info",
                                                    "data": {
                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                        "ai_job_id": jobId
                                                    }
                                                })
                                            });
                                            
                                            const response_data = await response.json();
                                            // Handle both direct response and wrapped response
                                            const data = response_data.product_info || (typeof response_data === 'string' ? JSON.parse(response_data).product_info : response_data);
                                            
                                            if (!data || !data.summary || !data.product_info) {
                                                throw new Error('Invalid response from API');
                                            }
                                            
                                            // Extract data from API response
                                            const results = data.product_info;
                                            const summary = data.summary;
                                            
                                            // Hide loading state and render results
                                            displayTestResults(results, summary, groupName, jobData);
                                            
                                        } catch (error) {
                                            console.error('Error loading specific test result:', error);
                                            if (loadingDiv) loadingDiv.style.display = 'none';
                                            const noTestsDiv = document.getElementById('no-tests-message');
                                            if (noTestsDiv) {
                                                noTestsDiv.style.display = 'block';
                                                noTestsDiv.innerHTML = '<p>Error loading test results. Please try again.</p>';
                                            }
                                        }
                                    }
                                    
                                    // Display test results in the UI
                                    function displayTestResults(results, summary, groupName, jobData = null) {
                                        const loadingDiv = document.getElementById('test-loading');
                                        const resultsDiv = document.getElementById('test-results');
                                        
                                        // Get prompt information from job configuration (preferred) or current configuration (fallback)
                                        let promptInfo = null;
                                        if (summary && summary.job_config) {
                                            // Extract prompt from job configuration in summary
                                            try {
                                                const jobConfig = typeof summary.job_config === 'string' ? JSON.parse(summary.job_config) : summary.job_config;
                                                if (jobConfig.prompt) {
                                                    // Direct prompt structure in job_config
                                                    promptInfo = {
                                                        name: jobConfig.prompt.name || 'Unnamed Prompt',
                                                        content: jobConfig.prompt.prompt || 'Prompt content not available'
                                                    };
                                                }
                                            } catch (error) {
                                                console.warn('Error parsing job config for prompt info:', error);
                                            }
                                        }
                                        
                                        // Fallback to current configuration if job config doesn't have prompt info
                                        if (!promptInfo && groupName) {
                                            const config = editor.get();
                                            const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                            if (groupConfig && groupConfig.assigned_prompt) {
                                                const promptConfig = config.ai_product_info?.prompts?.[groupConfig.assigned_prompt];
                                                if (promptConfig) {
                                                    promptInfo = {
                                                        name: promptConfig.name || groupConfig.assigned_prompt,
                                                        content: promptConfig.prompt || 'Prompt content not available'
                                                    };
                                                }
                                            }
                                        }
                                        
                                        // Hide loading state   // Create tabs with product images
                                        const tabsContainer = document.getElementById('product-tabs');
                                        const contentContainer = document.getElementById('tab-content');
                                        const summaryHeaderContainer = document.getElementById('test-summary-header');
                                        
                                        if (tabsContainer && contentContainer && summaryHeaderContainer) {
                                            tabsContainer.innerHTML = '';
                                            contentContainer.innerHTML = '';
                                            
                                            // Add summary to header instead of as a tab
                                            summaryHeaderContainer.innerHTML = `
                                                <div class="test-summary-header">
                                                    <div class="metrics-header-row">
                                                    <div class="metrics-section">
                                                            <h4 class="metrics-section-title">Test Run Metrics</h4>
                                                            <div class="metrics-cards">
                                                                <div class="g-ffl-metric-card blue">
                                                                    <div class="metric-icon"><i class="fas fa-box"></i></div>
                                                                    <div class="metric-content">
                                                                        <div class="metric-number">${summary.products_processed}</div>
                                                                        <div class="metric-label">Products Tested</div>
                                                                    </div>
                                                                </div>
                                                                <div class="g-ffl-metric-card blue">
                                                                    <div class="metric-icon"><i class="fas fa-coins"></i></div>
                                                                    <div class="metric-content">
                                                                        <div class="metric-number">${Math.round(summary.tokens_used).toLocaleString()}</div>
                                                                        <div class="metric-label">Tokens used for Test</div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="metrics-section">
                                                            <h4 class="metrics-section-title">Full Run Estimates</h4>
                                                            <div class="metrics-cards">
                                                                <div class="g-ffl-metric-card green">
                                                                    <div class="metric-icon"><i class="fas fa-database"></i></div>
                                                                    <div class="metric-content">
                                                                        <div class="metric-number">${summary.estimated_full_run.products_affected.toLocaleString()}</div>
                                                                        <div class="metric-label">Total products in Group</div>
                                                                    </div>
                                                                </div>
                                                                <div class="metrics-divider"></div>
                                                                <div class="g-ffl-metric-card green">
                                                                    <div class="metric-icon"><i class="fas fa-coins"></i></div>
                                                                    <div class="metric-content">
                                                                        <div class="metric-number">${Math.round(summary.estimated_full_run.estimated_tokens).toLocaleString()}</div>
                                                                        <div class="metric-label">Estimated Tokens to run full Group</div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>      
                                                    </div>
                                                </div>
                                            `;
                                            summaryHeaderContainer.style.display = 'block';
                                            
                                            results.forEach((product, index) => {
                                                // Create tab button with image
                                                const tab = document.createElement('div');
                                                const original_product_data = JSON.parse(product.original_product_info);
                                                
                                                // Extract image URL from original product data (handles both array and string formats)
                                                let imageUrl = '';
                                                if (original_product_data.image_url) {
                                                    const imageArray = JSON.parse(original_product_data.image_url);
                                                    imageUrl = Array.isArray(imageArray) ? imageArray[0] : imageArray;
                                                }
                                                
                                                // Extract product name from original data (handles array format)
                                                let originalProductName = 'Product';
                                                if (original_product_data.name) {
                                                    const nameArray = JSON.parse(original_product_data.name);
                                                    originalProductName = Array.isArray(nameArray) ? nameArray[0] : nameArray;
                                                }
                                                
                                                // Use AI-generated title for display, fallback to original if not available
                                                let displayTitle = product.title_75 || originalProductName;
                                                
                                                tab.className = `product-tab${index === 0 ? ' active' : ''}`;
                                                tab.innerHTML = `
                                                    <img src="${imageUrl}" alt="${displayTitle}" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjZjNmNGY2Ii8+CjxwYXRoIGQ9Ik04IDh2OGg4VjhoLTh6bTYgNmgtNHYtNGg0djR6IiBmaWxsPSIjOWNhM2FmIi8+Cjwvc3ZnPgo='">
                                                    <span>${displayTitle.length > 15 ? displayTitle.substring(0, 15) + '...' : displayTitle}</span>
                                                `;
                                                tab.onclick = () => switchTab(index);
                                                tabsContainer.appendChild(tab);
                                                
                                                // Create tab content with all fields
                                                const content = document.createElement('div');
                                                content.className = `tab-content-item${index === 0 ? ' active' : ''}`;
                                                content.id = `tab-${index}`;
                                                
                                                // Extract additional data from original product info
                                                let category = 'N/A';
                                                let manufacturer = 'N/A';
                                                let price = 'N/A';
                                                
                                                if (original_product_data.category) {
                                                    const categoryArray = JSON.parse(original_product_data.category);
                                                    category = Array.isArray(categoryArray) ? categoryArray[0] : categoryArray;
                                                }
                                                
                                                if (original_product_data.mfg_name) {
                                                    const mfgArray = JSON.parse(original_product_data.mfg_name);
                                                    manufacturer = Array.isArray(mfgArray) ? mfgArray[0] : mfgArray;
                                                }
                                                
                                                if (original_product_data.unit_price) {
                                                    const priceArray = JSON.parse(original_product_data.unit_price);
                                                    price = Array.isArray(priceArray) ? `$${priceArray[0]}` : `$${priceArray}`;
                                                }
                                                
                                                // Extract original description - keep all versions
                                                let originalDescriptions = [];
                                                if (original_product_data.description) {
                                                    const descArray = JSON.parse(original_product_data.description);
                                                    if (Array.isArray(descArray)) {
                                                        originalDescriptions = descArray.filter(desc => desc && desc.trim() !== '');
                                                    } else if (descArray && descArray.trim() !== '') {
                                                        originalDescriptions = [descArray];
                                                    }
                                                }
                                                if (originalDescriptions.length === 0) {
                                                    originalDescriptions = ['No original description available'];
                                                }
                                                
                                                content.innerHTML = `
                                                    <div class="product-header">
                                                        <img src="${imageUrl}" alt="${displayTitle}" class="product-image" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTIwIiBoZWlnaHQ9IjEyMCIgdmlld0JveD0iMCAwIDEyMCAxMjAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiBmaWxsPSIjZjNmNGY2Ii8+CjxwYXRoIGQ9Ik00MCA0MHY0MGg0MFY0MEg0MHptMzAgMzBINTBWNTBoMjB2MjB6IiBmaWxsPSIjOWNhM2FmIi8+Cjwvc3ZnPgo='">
                                                        <div class="product-basic-info">
                                                            <h3>${displayTitle}</h3>
                                                            <div class="product-details-row">
                                                                <span><strong>Brand:</strong> ${manufacturer}</span>
                                                                <span><strong>UPC:</strong> ${product.upc || 'N/A'}</span>
                                                                <span><strong>Price:</strong> ${price}</span>
                                                            </div>
                                                            <div class="product-details-row">
                                                                <span><strong>Category:</strong> ${category}</span>
                                                            </div>
                                                            <div class="tokens-used">
                                                                <i class="fas fa-coins"></i> Tokens Used: ${Math.round(product.tokens_used || 0).toLocaleString()}
                                                            </div>
                                                            ${product.needs_review ? '<div class="needs-review-badge"><i class="fas fa-exclamation-triangle"></i>AI Notes</div>' : ''}
                                                            ${product.notes ? `<div class="product-notes">${product.notes}</div>` : ''}
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="field-sections">
                                                        <div class="field-section">
                                                            <h4><i class="fas fa-tag"></i> AI-Generated Titles & Metadata</h4>
                                                            
                                                            <div class="field-row">
                                                                <span class="field-label">Title (<75 Characters):</span>
                                                                <div class="field-value">${product.title_75 || 'Not generated'}</div>
                                                                ${originalProductName ? `<div style="font-style: italic; color: #dc3545; font-size: 11px; margin-top: 4px; opacity: 0.8;">Original: ${originalProductName}</div>` : ''}
                                                            </div>
                                                            
                                                            <div class="field-row">
                                                                <span class="field-label">Title (<150 Characters):</span>
                                                                <div class="field-value">${product.title || 'Not generated'}</div>
                                                            </div>

                                                            <div class="field-row">
                                                                <span class="field-label">Short Description:</span>
                                                                <div class="field-value">${product.short_description || 'Not generated'}</div>
                                                            </div>

                                                            <div class="field-row">
                                                                <span class="field-label">Meta Description:</span>
                                                                <div class="field-value">${product.meta_description || 'Not generated'}</div>
                                                            </div>
                                                            
                                                            <div class="field-row">
                                                                <span class="field-label">Image Alt Text:</span>
                                                                <div class="field-value">${product.image_alt_text || 'Not generated'}</div>
                                                            </div>
                                                            
                                                            <div class="field-row">
                                                                <span class="field-label">Slug:</span>
                                                                <div class="field-value" style="font-family: monospace; font-size: 12px;">${product.slug || 'Not generated'}</div>
                                                            </div>
                                                            
                                                            <div class="field-row">
                                                                <span class="field-label">YouTube Search Term:</span>
                                                                <div class="field-value">${product.youtube_search_term || 'Not generated'}</div>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="field-section">
                                                            <h4><i class="fas fa-align-left"></i> Description</h4>
                                                            <div class="description-tabs">
                                                                <div class="description-tab-buttons">
                                                                    <button type="button" class="description-tab-btn active" onclick="switchDescriptionTab(this, 'enhanced-${index}')">AI-Generated</button>
                                                                    <button type="button" class="description-tab-btn" onclick="switchDescriptionTab(this, 'original-${index}')">Original</button>
                                                                    ${promptInfo ? `<button type="button" class="description-tab-btn" onclick="switchDescriptionTab(this, 'prompt-${index}')"><i class="fas fa-robot"></i> Prompt Used</button>` : ''}
                                                                </div>
                                                                <div class="description-tab-content">
                                                                    <div id="enhanced-${index}" class="description-tab-pane active">
                                                                        <div class="field-row">
                                                                            <div class="field-value html-content">${product.description || 'Not generated'}</div>
                                                                        </div>
                                                                    </div>
                                                                    <div id="original-${index}" class="description-tab-pane">
                                                                        ${originalDescriptions.map((desc, descIndex) => `
                                                                            <div class="field-row" style="margin-bottom: ${descIndex < originalDescriptions.length - 1 ? '15px' : '0'};">
                                                                                <span class="field-label">${originalDescriptions.length > 1 ? `Original Description ${descIndex + 1}:` : 'Original Description:'}</span>
                                                                                <div class="field-value" style="background-color: ${descIndex % 2 === 0 ? '#f9f9f9' : '#f3f3f3'}; padding: 10px; border-radius: 4px; border-left: 3px solid #ddd;">${desc}</div>
                                                                            </div>
                                                                        `).join('')}
                                                                    </div>
                                                                    ${promptInfo ? `
                                                                    <div id="prompt-${index}" class="description-tab-pane">
                                                                        <div class="field-row">
                                                                            <span class="field-label">Prompt Name:</span>
                                                                            <div class="field-value" style="font-weight: bold; color: #0073aa; margin-bottom: 10px;"></div>
                                                                        </div>
                                                                        <div class="field-row">
                                                                            <span class="field-label">Prompt Content:</span>
                                                                            <div class="field-value prompt-content" style="background-color: #f8f9fa; padding: 15px; border-radius: 6px; border-left: 4px solid #0073aa; font-family: 'Consolas', 'Monaco', monospace; font-size: 13px; line-height: 1.5; white-space: pre-wrap; max-height: 300px; overflow-y: auto;"></div>
                                                                        </div>
                                                                    </div>
                                                                    ` : ''}
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                `;
                                                    contentContainer.appendChild(content);
                                                    
                                                    // Safely set prompt content as text (not HTML) if available
                                                    if (promptInfo) {
                                                        const promptNameDiv = content.querySelector(`#prompt-${index} .field-value:first-of-type`);
                                                        const promptContentDiv = content.querySelector(`#prompt-${index} .prompt-content`);
                                                        if (promptNameDiv) {
                                                            promptNameDiv.textContent = promptInfo.name;
                                                        }
                                                        if (promptContentDiv) {
                                                            promptContentDiv.textContent = promptInfo.content;
                                                        }
                                                    }
                                            });
                                        }
                                        
                                        // Show results
                                        if (loadingDiv) loadingDiv.style.display = 'none';
                                        if (resultsDiv) {
                                            resultsDiv.style.display = 'flex';
                                            resultsDiv.style.flexDirection = 'column';
                                        }
                                        
                                        // Show success indicator in header
                                        const successIndicator = document.getElementById('success-indicator');
                                        if (successIndicator) {
                                            successIndicator.style.display = 'block';
                                        }
                                    }
                                    
                                    // Show running job status
                                    function showRunningJobStatus(job) {
                                        const loadingDiv = document.getElementById('test-loading');
                                        const resultsDiv = document.getElementById('test-results');
                                        const noTestsDiv = document.getElementById('no-tests-message');
                                        const loadingText = document.getElementById('loading-text');
                                        const loadingSubtext = document.getElementById('loading-subtext');
                                        
                                        if (loadingDiv) loadingDiv.style.display = 'block';
                                        if (resultsDiv) resultsDiv.style.display = 'none';
                                        if (noTestsDiv) noTestsDiv.style.display = 'none';
                                        
                                        if (loadingText) loadingText.textContent = 'Test job is running...';
                                        if (loadingSubtext) {
                                            // Assume created_at is UTC and convert to local browser time
                                            let jobDate;
                                            if (job.created_at.includes('Z') || job.created_at.includes('+')) {
                                                // Already has timezone info
                                                jobDate = new Date(job.created_at);
                                            } else {
                                                // Assume UTC and append 'Z' to ensure UTC parsing
                                                jobDate = new Date(job.created_at + 'Z');
                                            }
                                            const formattedDate = jobDate.toLocaleDateString('en-US', {
                                                month: 'short',
                                                day: 'numeric',
                                                year: 'numeric'
                                            });
                                            const formattedTime = jobDate.toLocaleTimeString('en-US', {
                                                hour: 'numeric',
                                                minute: '2-digit',
                                                hour12: true
                                            });
                                            loadingSubtext.textContent = `Started: ${formattedDate} at ${formattedTime}`;
                                        }
                                        
                                        // Poll for completion every 30 seconds
                                        setTimeout(() => {
                                            loadTestResults(job.group_name);
                                        }, 30000);
                                    }
                                    
                                    // Global variables for polling control
                                    let pollingInterval = null;
                                    let pollingTimeout = null;
                                    let pollingStartTime = null;
                                    
                                    // Start a new test run
                                    async function startNewTestRun(groupName) {
                                        // Check if tokens are sufficient before starting new test
                                        
                                        
                                        const tokenCount = isNaN(Number(window.currentTokenCount)) ? 0 : Number(window.currentTokenCount);
                                        if (tokenCount !== undefined && tokenCount < 2500) {
                                            alert('Insufficient tokens to start a new test. Please purchase additional tokens. You can still view historical test results.');
                                            return;
                                        }
                                        
                                        try {
                                            const config = editor.get();
                                            const groupConfig = config.ai_product_info?.product_groups?.[groupName];
                                            
                                            if (!groupConfig || !groupConfig.assigned_prompt) {
                                                alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                                return;
                                            }
                                            
                                            // Show initial loading state
                                            showPollingState(groupName, 'Starting new test run...');
                                            
                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify({
                                                    "action": "run_ai_product_info_job",
                                                    "data": {
                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                        "product_group_name": groupName,
                                                        "is_test_run": true,
                                                        "missing_only": false
                                                    }
                                                })
                                            });
                                            
                                            const result = await response.json();
                                            if (result.success && result.ai_job_id) {
                                                // Start polling for job completion
                                                startPollingForJobCompletion(groupName, result.ai_job_id);
                                            } else {
                                                hidePollingState();
                                                alert('Failed to start test run: ' + (result.message || 'Unknown error'));
                                                // Reload existing results if any
                                                loadTestResults(groupName);
                                            }
                                            
                                        } catch (error) {
                                            console.error('Error starting test run:', error);
                                            hidePollingState();
                                            alert('Failed to start test run. Please try again.');
                                            // Reload existing results if any
                                            loadTestResults(groupName);
                                        }
                                    }
                                    
                                    // Show polling state with spinner and abort option
                                    function showPollingState(groupName, message = 'Processing test run...') {
                                        const loadingDiv = document.getElementById('test-loading');
                                        const resultsDiv = document.getElementById('test-results');
                                        const noTestsDiv = document.getElementById('no-tests-message');
                                        const testRunSelector = document.getElementById('test-run-selector');
                                        const summaryHeader = document.getElementById('test-summary-header');
                                        
                                        // Hide other sections
                                        if (resultsDiv) resultsDiv.style.display = 'none';
                                        if (noTestsDiv) noTestsDiv.style.display = 'none';
                                        if (testRunSelector) testRunSelector.style.display = 'none';
                                        if (summaryHeader) summaryHeader.style.display = 'none';
                                        
                                        // Show loading div with polling-specific content
                                        if (loadingDiv) {
                                            loadingDiv.style.display = 'block';
                                            loadingDiv.innerHTML = `
                                                <div style="display: inline-block; position: relative; text-align: center;">
                                                    <div style="font-size: 48px; margin-bottom: 15px; display: flex; gap: 5px; justify-content: center;">
                                                        <span style="display: inline-block; animation: bounce1 1.2s ease-in-out infinite;">🔫</span>
                                                        <span style="display: inline-block; animation: bounce2 1.8s ease-in-out infinite;">🤖</span>
                                                        <span style="display: inline-block; animation: bounce3 2.1s ease-in-out infinite;">⚙️</span>
                                                        <span style="display: inline-block; animation: bounce4 1.5s ease-in-out infinite;">🎯</span>
                                                        <span style="display: inline-block; animation: bounce5 2.3s ease-in-out infinite;">🛠️</span>
                                                    </div>
                                                    <div id="polling-text" style="font-size: 18px; font-weight: 500; margin-bottom: 10px; color: #333;">${message}</div>
                                                    <div id="polling-subtext" style="font-size: 14px; color: #666; margin-bottom: 15px;">The AI robot is analyzing your product data... This usually takes 2-4 minutes! �⚙️</div>
                                                    <div style="background: #f0f8ff; border: 2px dashed #0073aa; border-radius: 8px; padding: 10px; margin-bottom: 15px; font-style: italic; color: #0073aa; font-size: 13px;">
                                                        <span id="robot-status">Analyzing firearm specifications with AI precision...</span>
                                                    </div>
                                                    <div id="polling-timer" style="font-size: 12px; color: #666; margin-bottom: 20px;">Elapsed: 0:00</div>
                                                    <button id="abort-polling-btn" onclick="abortPolling('${groupName}')" style="background: #dc3545; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.background='#c82333'" onmouseout="this.style.background='#dc3545'">
                                                        <i class="fas fa-times" style="margin-right: 6px;"></i>Close and Check Later
                                                    </button>
                                                </div>
                                                <style>
                                                    @keyframes robotBob {
                                                        0%, 100% { transform: translateY(0px) rotate(0deg); }
                                                        25% { transform: translateY(-3px) rotate(-2deg); }
                                                        50% { transform: translateY(0px) rotate(0deg); }
                                                        75% { transform: translateY(-3px) rotate(2deg); }
                                                    }
                                                    @keyframes bounce1 {
                                                        0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
                                                        40% { transform: translateY(-8px); }
                                                        60% { transform: translateY(-4px); }
                                                    }
                                                    @keyframes bounce2 {
                                                        0%, 30%, 60%, 90%, 100% { transform: translateY(0); }
                                                        15% { transform: translateY(-6px); }
                                                        45% { transform: translateY(-10px); }
                                                        75% { transform: translateY(-5px); }
                                                    }
                                                    @keyframes bounce3 {
                                                        0%, 25%, 55%, 85%, 100% { transform: translateY(0); }
                                                        12% { transform: translateY(-7px); }
                                                        40% { transform: translateY(-9px); }
                                                        70% { transform: translateY(-6px); }
                                                    }
                                                    @keyframes bounce4 {
                                                        0%, 35%, 65%, 95%, 100% { transform: translateY(0); }
                                                        18% { transform: translateY(-9px); }
                                                        50% { transform: translateY(-7px); }
                                                        82% { transform: translateY(-4px); }
                                                    }
                                                    @keyframes bounce5 {
                                                        0%, 28%, 58%, 88%, 100% { transform: translateY(0); }
                                                        14% { transform: translateY(-5px); }
                                                        43% { transform: translateY(-8px); }
                                                        72% { transform: translateY(-10px); }
                                                    }
                                                </style>
                                            `;
                                        }
                                    }
                                    
                                    // Hide polling state
                                    function hidePollingState() {
                                        // Clear any running intervals/timeouts
                                        if (pollingInterval) {
                                            clearInterval(pollingInterval);
                                            pollingInterval = null;
                                        }
                                        if (pollingTimeout) {
                                            clearTimeout(pollingTimeout);
                                            pollingTimeout = null;
                                        }
                                        pollingStartTime = null;
                                    }
                                    
                                    // Start polling for job completion
                                    function startPollingForJobCompletion(groupName, jobId) {
                                        pollingStartTime = Date.now();
                                        const maxPollingTime = 10 * 60 * 1000; // 10 minutes in milliseconds
                                        const pollingIntervalMs = 10000; // Poll every 10 seconds
                                        
                                        // Update the message to show we're waiting for completion
                                        const pollingText = document.getElementById('polling-text');
                                        if (pollingText) {
                                            pollingText.textContent = 'Waiting for test completion...';
                                        }
                                        
                                        // Fun robot status messages that rotate
                                        const robotStatusMessages = [
                                            "Analyzing product specifications with AI precision... 🔍",
                                            "Cross-referencing product data in the digital database... 🎯",
                                            "Calibrating product descriptions for maximum impact... �",
                                            "Loading product details into neural networks... 🔫",
                                            "Optimizing product specs for human readability... 👥",
                                            "Consulting the digital firearms encyclopedia... �",
                                            "Fine-tuning tactical product descriptions... 🔧",
                                            "Processing product data at light speed... ⚡",
                                            "Enhancing product and accessory information... 🔭",
                                            "Running quality calculations through AI cores... 🎯",
                                            "Organizing ammunition by caliber and grain weight... �",
                                            "Applying military-grade AI to your inventory... 🪖"
                                        ];
                                        
                                        let statusIndex = 0;
                                        const statusRotation = setInterval(() => {
                                            const robotStatus = document.getElementById('robot-status');
                                            if (robotStatus && pollingInterval) {
                                                robotStatus.textContent = robotStatusMessages[statusIndex];
                                                statusIndex = (statusIndex + 1) % robotStatusMessages.length;
                                            } else {
                                                clearInterval(statusRotation);
                                            }
                                        }, 3000);
                                        
                                        // Start the timer display
                                        const timerInterval = setInterval(() => {
                                            if (!pollingStartTime) {
                                                clearInterval(timerInterval);
                                                return;
                                            }
                                            
                                            const elapsed = Date.now() - pollingStartTime;
                                            const minutes = Math.floor(elapsed / 60000);
                                            const seconds = Math.floor((elapsed % 60000) / 1000);
                                            const timerDiv = document.getElementById('polling-timer');
                                            if (timerDiv) {
                                                timerDiv.textContent = `Elapsed: ${minutes}:${seconds.toString().padStart(2, '0')}`;
                                            }
                                        }, 1000);
                                        
                                        // Set 10-minute timeout
                                        pollingTimeout = setTimeout(() => {
                                            if (pollingInterval) {
                                                clearInterval(pollingInterval);
                                                pollingInterval = null;
                                            }
                                            clearInterval(timerInterval);
                                            
                                            const loadingDiv = document.getElementById('test-loading');
                                            if (loadingDiv) {
                                                loadingDiv.innerHTML = `
                                                    <div style="text-align: center; padding: 40px 20px; color: #dc3545;">
                                                        <div style="font-size: 24px; margin-bottom: 15px;">⏰</div>
                                                        <div style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">Polling Timeout</div>
                                                        <div style="font-size: 14px; color: #666; margin-bottom: 20px;">The test is still running but taking longer than expected.<br>Please check back later for results.</div>
                                                        <button onclick="loadTestResults('${groupName}')" style="background: #0073aa; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer;">
                                                            <i class="fas fa-refresh" style="margin-right: 6px;"></i>Check for Results Now
                                                        </button>
                                                    </div>
                                                `;
                                            }
                                            
                                            pollingStartTime = null;
                                        }, maxPollingTime);
                                        
                                        // Start polling
                                        pollingInterval = setInterval(async () => {
                                            try {
                                                await checkJobStatus(groupName, jobId, timerInterval);
                                            } catch (error) {
                                                console.error('Error checking job status:', error);
                                            }
                                        }, pollingIntervalMs);
                                        
                                        // Do an immediate check
                                        setTimeout(() => {
                                            checkJobStatus(groupName, jobId, timerInterval);
                                        }, 2000);
                                    }
                                    
                                    // Check job status
                                    async function checkJobStatus(groupName, jobId, timerInterval) {
                                        try {
                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                method: "POST",
                                                headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                },
                                                body: JSON.stringify({
                                                    "action": "get_ai_product_info_jobs",
                                                    "data": {
                                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                        "product_group_name": groupName
                                                    }
                                                })
                                            });
                                            
                                            const result = await response.json();
                                            const jobs = result.jobs || [];
                                            
                                            // Find our specific job
                                            const targetJob = jobs.find(job => job.id === jobId);
                                            
                                            if (targetJob) {
                                                if (targetJob.status === 'Succeeded') {
                                                    // Job completed successfully
                                                    hidePollingState();
                                                    clearInterval(timerInterval);
                                                    
                                                    // Load test results to properly set up dropdown and show completed results
                                                    loadTestResults(groupName);
                                                    
                                                    // Refresh the job status table to show the completed test
                                                    setTimeout(() => {
                                                        loadJobStatusTable(groupName);
                                                    }, 500); // Small delay to ensure the job status is updated
                                                } else if (targetJob.status === 'Failed') {
                                                    // Job failed
                                                    hidePollingState();
                                                    clearInterval(timerInterval);
                                                    
                                                    const loadingDiv = document.getElementById('test-loading');
                                                    if (loadingDiv) {
                                                        loadingDiv.innerHTML = `
                                                            <div style="text-align: center; padding: 40px 20px; color: #dc3545;">
                                                                <div style="font-size: 24px; margin-bottom: 15px;">❌</div>
                                                                <div style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">Test Run Failed</div>
                                                                <div style="font-size: 14px; color: #666; margin-bottom: 20px;">The test run encountered an error and could not complete.</div>
                                                                <button onclick="startNewTestRun('${groupName}')" style="background: #0073aa; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer; margin-right: 10px;">
                                                                    <i class="fas fa-redo" style="margin-right: 6px;"></i>Try Again
                                                                </button>
                                                                <button onclick="loadTestResults('${groupName}')" style="background: #6c757d; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer;">
                                                                    <i class="fas fa-list" style="margin-right: 6px;"></i>View Previous Results
                                                                </button>
                                                            </div>
                                                        `;
                                                    }
                                                }
                                                // If status is still 'Running' or 'Pending', continue polling
                                            }
                                            
                                        } catch (error) {
                                            console.error('Error checking job status:', error);
                                            // Continue polling on error, don't abort
                                        }
                                    }
                                    
                                    // Abort polling and return to previous state
                                    function abortPolling(groupName) {
                                        hidePollingState();
                                        
                                        const loadingDiv = document.getElementById('test-loading');
                                        if (loadingDiv) {
                                            loadingDiv.innerHTML = `
                                                <div style="text-align: center; padding: 40px 20px; color: #666;">
                                                    <div style="font-size: 24px; margin-bottom: 15px;">⏸️</div>
                                                    <div style="font-size: 18px; font-weight: 500; margin-bottom: 10px;">Polling Stopped</div>
                                                    <div style="font-size: 14px; color: #666; margin-bottom: 20px;">Your test is still running in the background.<br>Check back later to see the results.</div>
                                                    <button onclick="loadTestResults('${groupName}')" style="background: #0073aa; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer; margin-right: 10px;">
                                                        <i class="fas fa-refresh" style="margin-right: 6px;"></i>Check for Results Now
                                                    </button>
                                                    <button onclick="startNewTestRun('${groupName}')" style="background: #28a745; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; cursor: pointer;">
                                                        <i class="fas fa-play" style="margin-right: 6px;"></i>Start Another Test
                                                    </button>
                                                </div>
                                            `;
                                        }
                                    }
                                    
                                    // Switch between product tabs
                                    function switchTab(index) {
                                        // Remove active class from all tabs and content
                                        document.querySelectorAll('.product-tab').forEach(tab => tab.classList.remove('active'));
                                        document.querySelectorAll('.tab-content-item').forEach(pane => pane.classList.remove('active'));
                                        
                                        // Add active class to selected tab and content (0-based indexing)
                                        const tabs = document.querySelectorAll('.product-tab');
                                        const content = document.getElementById(`tab-${index}`);
                                        
                                        if (tabs[index]) tabs[index].classList.add('active');
                                        if (content) content.classList.add('active');
                                    }
                                    
                                    // Switch between description tabs (Enhanced vs Original)
                                    function switchDescriptionTab(button, targetId) {
                                        // Find the parent tab buttons container
                                        const buttonsContainer = button.parentElement;
                                        const contentContainer = buttonsContainer.nextElementSibling;
                                        
                                        // Remove active class from all buttons and panes in this container
                                        buttonsContainer.querySelectorAll('.description-tab-btn').forEach(btn => btn.classList.remove('active'));
                                        contentContainer.querySelectorAll('.description-tab-pane').forEach(pane => pane.classList.remove('active'));
                                        
                                        // Add active class to clicked button and target pane
                                        button.classList.add('active');
                                        
                                        // Force blur to prevent focus state interference
                                        button.blur();
                                        
                                        const targetPane = document.getElementById(targetId);
                                        if (targetPane) {
                                            targetPane.classList.add('active');
                                        }
                                    }
                                                    
                                                    // Test AI product group
                                                    async function testAIProductGroup(groupName) {
                                                        const config = editor.get();
                                                        const groupConfig = config.ai_product_info?.product_groups?.[groupName] || {};
                                                        
                                                        if (!groupConfig.assigned_prompt) {
                                                            alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                                            return;
                                                        }
                                                        
                                                        currentTestGroupId = groupName;
                                                        const promptName = groupConfig.assigned_prompt;
                                                        const restrictions = [];
                                                        
                                                        if (groupConfig.product_restrictions?.brand?.length > 0) restrictions.push(`Brands: ${groupConfig.product_restrictions.brand.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.category?.length > 0) restrictions.push(`Categories: ${groupConfig.product_restrictions.category.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.product_class?.length > 0) restrictions.push(`Product Classes: ${groupConfig.product_restrictions.product_class.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.distributor?.length > 0) restrictions.push(`Distributors: ${groupConfig.product_restrictions.distributor.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.min_cost) restrictions.push(`Min Cost: $${groupConfig.product_restrictions.cost_restrictions.min_cost}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.max_cost) restrictions.push(`Max Cost: $${groupConfig.product_restrictions.cost_restrictions.max_cost}`);
                                                        
                                                        document.getElementById('test-prompt-text').textContent = `Testing prompt: ${promptName}`;
                                                        document.getElementById('test-restrictions-text').textContent = restrictions.length > 0 ? restrictions.join('; ') : 'No restrictions';
                                                        
                                                        // Load sample products
                                                        await loadSampleProducts(groupConfig);
                                                        
                                                        // Show modal
                                                        document.getElementById('aiPromptTestModal').style.display = 'block';
                                                        document.getElementById('test-results-container').style.display = 'none';
                                                    }
                                                    
                                                    // Load sample products for testing
                                                    async function loadSampleProducts(promptConfig) {
                                                        try {
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({ 
                                                                    "action": "get_sample_products_for_ai_test",
                                                                    "restrictions": promptConfig
                                                                })
                                                            });
                                                            
                                                            const data = await response.json();
                                                            const select = document.getElementById('test-sample-products');
                                                            select.innerHTML = '';
                                                            
                                                            if (data && data.products && data.products.length > 0) {
                                                                data.products.slice(0, 20).forEach(product => {
                                                                    const option = document.createElement('option');
                                                                    option.value = product.id || product.sku;
                                                                    option.textContent = `${product.name || product.sku} (${product.brand || 'Unknown Brand'})`;
                                                                    select.appendChild(option);
                                                                });
                                                            } else {
                                                                const option = document.createElement('option');
                                                                option.value = '';
                                                                option.textContent = 'No products found matching restrictions';
                                                                option.disabled = true;
                                                                select.appendChild(option);
                                                            }
                                                        } catch (error) {
                                                            console.error('Error loading sample products:', error);
                                                            const select = document.getElementById('test-sample-products');
                                                            select.innerHTML = '<option disabled>Error loading products</option>';
                                                        }
                                                    }
                                                    
                                                    // Run AI prompt test
                                                    async function runAIPromptTest() {
                                                        if (!currentTestPromptId && !currentTestGroupId) return;
                                                        
                                                        const select = document.getElementById('test-sample-products');
                                                        const selectedProducts = Array.from(select.selectedOptions).map(option => option.value);
                                                        
                                                        if (selectedProducts.length === 0) {
                                                            alert('Please select at least one product to test.');
                                                            return;
                                                        }
                                                        
                                                        if (selectedProducts.length > 5) {
                                                            alert('Please select no more than 5 products for testing.');
                                                            return;
                                                        }
                                                        
                                                        const config = editor.get();
                                                        let promptsToTest = [];
                                                        
                                                        if (currentTestGroupId) {
                                                            // Testing a product group - get all assigned prompts
                                                            const groupConfig = config.ai_product_info?.product_groups?.[currentTestGroupId] || {};
                                                            const assignedPromptIds = groupConfig.assigned_prompts || [];
                                                            promptsToTest = assignedPromptIds.map(promptId => {
                                                                const promptConfig = config.ai_product_info?.prompts?.[promptId];
                                                                return {
                                                                    id: promptId,
                                                                    prompt: promptConfig?.prompt || '',
                                                                    name: promptConfig?.name || promptId
                                                                };
                                                            });
                                                        } else {
                                                            // Testing a single prompt
                                                            const promptConfig = config.ai_product_info?.prompts?.[currentTestPromptId];
                                                            if (promptConfig) {
                                                                promptsToTest = [{
                                                                    id: currentTestPromptId,
                                                                    prompt: promptConfig.prompt,
                                                                    name: promptConfig.name || currentTestPromptId
                                                                }];
                                                            }
                                                        }
                                                        
                                                        if (promptsToTest.length === 0) {
                                                            alert('No valid prompts to test.');
                                                            return;
                                                        }
                                                        
                                                        const runTestBtn = document.getElementById('run-test-btn');
                                                        const resultsContainer = document.getElementById('test-results-container');
                                                        const resultsContent = document.getElementById('test-results-content');
                                                        
                                                        runTestBtn.disabled = true;
                                                        runTestBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Testing...';
                                                        resultsContainer.style.display = 'block';
                                                        resultsContent.innerHTML = '<p>Processing test request...</p>';
                                                        
                                                        try {
                                                            const response = await fetch("https://ffl-api.garidium.com", {
                                                                method: "POST",
                                                                headers: {
                                                                    "Accept": "application/json",
                                                                    "Content-Type": "application/json",
                                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                                },
                                                                body: JSON.stringify({
                                                                    "action": "test_ai_prompts",
                                                                    "prompts": promptsToTest,
                                                                    "products": selectedProducts
                                                                })
                                                            });
                                                            
                                                            const data = await response.json();
                                                            let resultsHtml = '';
                                                            
                                                            if (data && data.results) {
                                                                resultsHtml = '<h3>AI Prompt Test Results</h3>';
                                                                data.results.forEach((result, index) => {
                                                                    resultsHtml += `
                                                                        <div style="margin-bottom: 25px; padding: 20px; border: 1px solid #ddd; border-radius: 8px; background-color: #fafafa;">
                                                                            <h4 style="margin-bottom: 15px; color: #0073aa;">Test ${index + 1}: ${result.prompt_name}</h4>
                                                                            
                                                                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 15px;">
                                                                                <div style="background-color: #fff; padding: 15px; border-radius: 5px; border-left: 4px solid #0073aa;">
                                                                                    <h5 style="margin: 0 0 10px 0; color: #0073aa; font-size: 14px;">📝 Prompt Used:</h5>
                                                                                    <div style="font-size: 13px; line-height: 1.4; color: #555; max-height: 120px; overflow-y: auto;">${result.prompt}</div>
                                                                                </div>
                                                                                
                                                                                <div style="background-color: #fff; padding: 15px; border-radius: 5px; border-left: 4px solid #28a745;">
                                                                                    <h5 style="margin: 0 0 10px 0; color: #28a745; font-size: 14px;">🤖 AI Generated Description:</h5>
                                                                                    <div style="font-size: 13px; line-height: 1.4; color: #333; max-height: 120px; overflow-y: auto;">${result.enhanced_content}</div>
                                                                                </div>
                                                                            </div>
                                                                            
                                                                            <div style="text-align: right; padding-top: 10px; border-top: 1px solid #eee;">
                                                                                <span style="background-color: #f0f0f0; padding: 5px 10px; border-radius: 15px; font-size: 12px; color: #666;">
                                                                                    💰 Tokens Used: ${Math.round(result.tokens_used).toLocaleString()}
                                                                                </span>
                                                                            </div>
                                                                        </div>
                                                                    `;
                                                                });
                                                            } else {
                                                                resultsContent.innerHTML = '<p style="color: red;">Error: Invalid response from AI service</p>';
                                                            }
                                                            
                                                            resultsContent.innerHTML = resultsHtml;
                                                            
                                                            // Refresh tokens display
                                                            loadAITokens();
                                                        } catch (error) {
                                                            console.error('Error testing AI prompts:', error);
                                                            resultsContent.innerHTML = '<p style="color: red;">Error: Failed to test AI prompts</p>';
                                                        } finally {
                                                            runTestBtn.disabled = false;
                                                            runTestBtn.innerHTML = '<i class="fas fa-play"></i> Run Test';
                                                        }
                                                    }
                                    
                                    // Switch between product tabs
                                    function switchTab(index) {
                                        // Remove active class from all tabs and content
                                        document.querySelectorAll('.product-tab').forEach(tab => tab.classList.remove('active'));
                                        document.querySelectorAll('.tab-content-item').forEach(pane => pane.classList.remove('active'));
                                        
                                        // Add active class to selected tab and content
                                        document.querySelectorAll('.product-tab')[index].classList.add('active');
                                        document.getElementById(`tab-${index}`).classList.add('active');
                                    }
                                                    
                                                    // Test AI product group
                                                    async function testAIProductGroup(groupName) {
                                                        const config = editor.get();
                                                        const groupConfig = config.ai_product_info?.product_groups?.[groupName] || {};
                                                        
                                                        if (!groupConfig.assigned_prompt) {
                                                            alert('No AI prompt assigned to this product group. Please assign a prompt first.');
                                                            return;
                                                        }
                                                        
                                                        currentTestGroupId = groupName;
                                                        const promptName = groupConfig.assigned_prompt;
                                                        const restrictions = [];
                                                        
                                                        if (groupConfig.product_restrictions?.brand?.length > 0) restrictions.push(`Brands: ${groupConfig.product_restrictions.brand.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.category?.length > 0) restrictions.push(`Categories: ${groupConfig.product_restrictions.category.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.product_class?.length > 0) restrictions.push(`Product Classes: ${groupConfig.product_restrictions.product_class.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.distributor?.length > 0) restrictions.push(`Distributors: ${groupConfig.product_restrictions.distributor.join(', ')}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.min_cost) restrictions.push(`Min Cost: $${groupConfig.product_restrictions.cost_restrictions.min_cost}`);
                                                        if (groupConfig.product_restrictions?.cost_restrictions?.max_cost) restrictions.push(`Max Cost: $${groupConfig.product_restrictions.cost_restrictions.max_cost}`);
                                                        
                                                        document.getElementById('test-prompt-text').textContent = `Testing prompt: ${promptName}`;
                                                        document.getElementById('test-restrictions-text').textContent = restrictions.length > 0 ? restrictions.join('; ') : 'No restrictions';
                                                        
                                                        // Load sample products
                                                        await loadSampleProducts(groupConfig);
                                                        
                                                        // Show modal
                                                        document.getElementById('aiPromptTestModal').style.display = 'block';
                                                        document.getElementById('test-results-container').style.display = 'none';
                                                    }
                                                    
                                                    // Load existing AI prompts and product groups when tab opens
                                                    function loadExistingAIConfiguration() {
                                                        try {
                                                            // Prevent duplicate loading
                                                            if (aiConfigurationLoaded) {
                                                                return;
                                                            }
                                                            
                                                            const config = editor.get();
                                                            if (!config) {
                                                                console.log('No configuration available for AI loading');
                                                                return;
                                                            }
                                                            
                                                            // Check if AI tab elements exist before proceeding
                                                            const promptContainer = document.getElementById('ai-prompt-container');
                                                            const groupContainer = document.getElementById('ai-product-group-container');
                                                            
                                                            if (!promptContainer || !groupContainer) {
                                                                console.log('AI tab elements not found, skipping AI configuration loading');
                                                                return;
                                                            }
                                                            
                                                            // Clear existing UI elements to prevent duplicates
                                                            promptContainer.innerHTML = '';
                                                            groupContainer.innerHTML = '';
                                                        
                                                        // Load prompts
                                                        if (config.ai_product_info?.prompts) {
                                                            Object.entries(config.ai_product_info.prompts).forEach(([promptName, promptConfig]) => {
                                                                addAIPrompt(promptName, promptConfig, false);
                                                            });
                                                        }
                                                        
                                                        // Load product groups
                                                        if (config.ai_product_info?.product_groups) {
                                                            Object.entries(config.ai_product_info.product_groups).forEach(([groupName, groupConfig]) => {
                                                                addAIProductGroup(groupName, groupConfig, false);
                                                            });
                                                        }
                                                        
                                                        // Mark as loaded
                                                        aiConfigurationLoaded = true;
                                                        
                                                        // Update button states after loading AI configuration
                                                        setTimeout(() => {
                                                            if (typeof updateButtonStates === 'function') {
                                                                updateButtonStates();
                                                            }
                                                        }, 500);
                                                        } catch (error) {
                                                            console.error('Error loading AI configuration:', error);
                                                            // Don't mark as loaded if there was an error
                                                        }
                                                    }
                                                </script>
                                            </div>
                                            
                                            <div class="tab-pane fade" id="classic-configurator" role="tabpanel" aria-labelledby="classic-configurator-tab">
                                                <!-- Advanced Configuration Content -->
                                                <div class="helperDialog"><strong>Advanced Configuration</strong> is where the magic happens. All changes you make with the fancy UI (User Interface) in the other tabs, ultimately change what's set in here. If your brave, you can decide to only use the Advanced Tab. Feel free to switch the mode to Text as well to enter the wonderful word of JSON editing. This configuration panel includes some options not available in other tabs. It will also highlight any errors that may exist within your current configuration.</div>
                                                <div id="jsoneditor" style="width: 100%; height: 500px;margin-top:20px;"></div>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="hidden" name="g_ffl_cockpit_configuration" id="g_ffl_cockpit_configuration">
                                    <script>
                                        function maskApiKeyForDiagnostic(apiKey) {
                                            try {
                                                const key = String(apiKey || '');
                                                if (!key) {
                                                    return 'none';
                                                }
                                                if (key.length <= 8) {
                                                    return key.substring(0, 2) + '***' + key.substring(Math.max(key.length - 2, 2));
                                                }
                                                return key.substring(0, 8) + '...' + key.substring(key.length - 5);
                                            } catch (e) {
                                                return 'unavailable';
                                            }
                                        }

                                        function getConfigurationLoadDiagnostic(error) {
                                            try {
                                                const details = [];
                                                const configLoadContext = window.gffcCurrentConfigLoadContext || {};
                                                const savedApiKey = window.gFFLCockpit && window.gFFLCockpit.apiKey ? window.gFFLCockpit.apiKey : '';
                                                const lookupApiKey = configLoadContext.lookupApiKey || window.gffcCurrentConfigLoadKey || savedApiKey;
                                                const requestHeaderApiKey = configLoadContext.requestHeaderApiKey || lookupApiKey;
                                                details.push('Saved API key: ' + maskApiKeyForDiagnostic(savedApiKey));
                                                details.push('Lookup API key: ' + maskApiKeyForDiagnostic(lookupApiKey));
                                                details.push('Request header API key: ' + maskApiKeyForDiagnostic(requestHeaderApiKey));
                                                details.push('Admin load request: ' + (configLoadContext.isAdminRequest ? 'yes' : 'no'));
                                                if (error && error.message) {
                                                    details.push('Error: ' + error.message);
                                                }
                                                if (error && error.gffcHttpStatus) {
                                                    details.push('HTTP status: ' + error.gffcHttpStatus);
                                                }
                                                if (error && error.gffcResponseText) {
                                                    details.push('Response: ' + String(error.gffcResponseText).substring(0, 1000));
                                                }
                                                if (error && error.gffcRetryAttempted) {
                                                    details.push('Retry attempted: yes');
                                                }
                                                if (error && error.gffcOriginalErrorMessage) {
                                                    details.push('First error: ' + error.gffcOriginalErrorMessage);
                                                }
                                                if (error && error.gffcFirstHttpStatus) {
                                                    details.push('First HTTP status: ' + error.gffcFirstHttpStatus);
                                                }
                                                if (error && error.name) {
                                                    details.push('Error type: ' + error.name);
                                                }
                                                details.push('Browser: ' + navigator.userAgent);
                                                details.push('Page URL: ' + window.location.href);
                                                details.push('Site URL: ' + window.location.origin);
                                                details.push('WP home URL: ' + (window.gFFLCockpit && window.gFFLCockpit.wpHomeUrl ? window.gFFLCockpit.wpHomeUrl : 'unknown'));
                                                details.push('WP site URL: ' + (window.gFFLCockpit && window.gFFLCockpit.wpSiteUrl ? window.gFFLCockpit.wpSiteUrl : 'unknown'));
                                                details.push('WP admin URL: ' + (window.gFFLCockpit && window.gFFLCockpit.wpAdminUrl ? window.gFFLCockpit.wpAdminUrl : 'unknown'));
                                                details.push('Current tab/hash: ' + (window.location.hash || 'none'));
                                                details.push('Plugin version: ' + (window.gFFLCockpit && window.gFFLCockpit.pluginVersion ? window.gFFLCockpit.pluginVersion : 'unknown'));
                                                details.push('Key just saved: ' + (window.gFFLCockpit && window.gFFLCockpit.keyJustSaved === true ? 'yes' : 'no'));
                                                details.push('Online: ' + (navigator.onLine ? 'yes' : 'no'));
                                                details.push('Referrer: ' + (document.referrer || 'none'));
                                                details.push('Time: ' + new Date().toISOString());
                                                return details.join('\n');
                                            } catch (e) {
                                                return 'Unable to build diagnostic details.';
                                            }
                                        }

                                        function submitInvalidKeyOverlayKey() {
                                            try {
                                                const overlayInput = document.getElementById('gffc_invalid_key_overlay_key');
                                                const keyInput = document.getElementById('g_ffl_cockpit_key');
                                                const setKeyContainer = document.getElementById('set_key_form');
                                                const setKeyButton = document.getElementById('confirm_set_key_button_actual');
                                                const keyForm = document.getElementById('g_ffl_cockpit_key_form');

                                                if (overlayInput && keyInput) {
                                                    keyInput.value = overlayInput.value;
                                                    keyInput.dispatchEvent(new Event('input', { bubbles: true }));
                                                }
                                                if (setKeyContainer) {
                                                    setKeyContainer.style.display = 'inline';
                                                }
                                                if (setKeyButton) {
                                                    setKeyButton.click();
                                                } else if (keyForm) {
                                                    keyForm.submit();
                                                }
                                            } catch (e) {
                                                console.log(e);
                                            }
                                        }

                                        function positionInvalidKeyOverlay() {
                                            try {
                                                const overlay = document.getElementById('gffc_invalid_key_overlay');
                                                if (!overlay) {
                                                    return;
                                                }

                                                let leftOffset = 0;
                                                const adminMenu = document.getElementById('adminmenuwrap') || document.getElementById('adminmenuback');
                                                if (adminMenu) {
                                                    const menuStyles = window.getComputedStyle(adminMenu);
                                                    const menuRect = adminMenu.getBoundingClientRect();
                                                    if (menuStyles.display !== 'none' && menuStyles.visibility !== 'hidden' && menuRect.right > 0) {
                                                        leftOffset = Math.max(0, Math.round(menuRect.right));
                                                    }
                                                }

                                                overlay.style.left = leftOffset + 'px';
                                            } catch (e) {
                                                // no-op
                                            }
                                        }

                                        function showInvalidKeyOverlay(message, diagnosticDetails) {
                                            try {
                                                let overlay = document.getElementById('gffc_invalid_key_overlay');
                                                if (!overlay) {
                                                    overlay = document.createElement('div');
                                                    overlay.id = 'gffc_invalid_key_overlay';
                                                    overlay.style.cssText = 'display:none; position:fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.45); z-index: 10000; align-items:flex-start; justify-content:center; padding: 20px; box-sizing:border-box; pointer-events:none;';
                                                    overlay.innerHTML = `
                                                        <div style="position:relative; z-index:10002; background: #fff; max-width: 720px; width: 100%; border-radius: 10px; padding: 18px 18px 14px 18px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); border-left: 4px solid #b32d2e; margin-top: 60px; pointer-events:auto;">
	                                                            <div style="font-size: 16px; font-weight: 700; color: #b32d2e; margin-bottom: 6px;">API Key/Site URL/Account Status Issue</div>
	                                                            <div id="gffc_invalid_key_overlay_message" style="font-size: 13px; color: #1d2327; line-height: 1.5;"></div>
	                                                            <div style="display:flex; gap:8px; align-items:center; margin-top:12px;">
                                                                <label for="gffc_invalid_key_overlay_key" style="font-weight:600; white-space:nowrap;">FFL Cockpit Key:</label>
                                                                <input type="password" id="gffc_invalid_key_overlay_key" autocomplete="off" style="flex:1; min-width:0; height:32px;">
                                                                <button type="button" id="gffc_invalid_key_overlay_set_key" class="button button-primary">Set Key</button>
                                                            </div>
	                                                            <details style="margin-top: 12px; font-size: 12px; color: #1d2327;">
	                                                                <summary style="cursor: pointer; font-weight: 600;">Diagnostic details</summary>
	                                                                <pre id="gffc_invalid_key_overlay_diagnostic" style="white-space: pre-wrap; word-break: break-word; background: #f6f7f7; border: 1px solid #dcdcde; border-radius: 4px; padding: 10px; margin: 8px 0 0 0; max-height: 220px; overflow: auto;"></pre>
	                                                            </details>
	                                                        </div>
	                                                    `;
	                                                    document.body.appendChild(overlay);
                                                    const overlaySetKeyButton = document.getElementById('gffc_invalid_key_overlay_set_key');
                                                    if (overlaySetKeyButton) {
                                                        overlaySetKeyButton.addEventListener('click', submitInvalidKeyOverlayKey);
                                                    }
                                                }

                                                const msgEl = document.getElementById('gffc_invalid_key_overlay_message');
                                                if (msgEl) {
                                                    msgEl.innerHTML = `<span style="color:#1d2327;">${message}</span>`;
                                                }

                                                const diagnosticEl = document.getElementById('gffc_invalid_key_overlay_diagnostic');
                                                if (diagnosticEl) {
                                                    diagnosticEl.textContent = diagnosticDetails || 'No diagnostic details were provided.';
                                                }

                                                positionInvalidKeyOverlay();
                                                overlay.style.display = 'flex';

                                                const overlayKeyInput = document.getElementById('gffc_invalid_key_overlay_key');
                                                const sourceKeyInput = document.getElementById('g_ffl_cockpit_key');
                                                if (overlayKeyInput && sourceKeyInput) {
                                                    overlayKeyInput.value = sourceKeyInput.value;
                                                }

                                                // Keep the original key field behind the popup so it does not cover diagnostics.
                                                const keyForm = document.getElementById('g_ffl_cockpit_key_form');
                                                if (keyForm) {
                                                    keyForm.style.position = 'relative';
                                                    keyForm.style.zIndex = '';
                                                }
                                                const keyInput = document.getElementById('g_ffl_cockpit_key');
                                                if (keyInput) {
                                                    keyInput.style.position = 'relative';
                                                    keyInput.style.zIndex = '';
                                                }
                                                const setKeyContainer = document.getElementById('set_key_form');
                                                if (setKeyContainer) {
                                                    setKeyContainer.style.position = 'relative';
                                                    setKeyContainer.style.zIndex = '';
                                                }
                                            } catch (e) {
                                                // no-op
                                            }
                                        }

                                        function hideInvalidKeyOverlay() {
                                            try {
                                                const overlay = document.getElementById('gffc_invalid_key_overlay');
                                                if (overlay) {
                                                    overlay.style.display = 'none';
                                                }
                                            } catch (e) {
                                                // no-op
                                            }
                                        }

                                        function setConfigurationLoading(isLoading) {
                                            try {
                                                const overlay = document.getElementById('configuration_loading_overlay');
                                                if (overlay) {
                                                    overlay.style.display = isLoading ? 'flex' : 'none';
                                                }
                                            } catch (e) {
                                                // no-op
                                            }
                                        }

                                        function ensureApiKeyFieldEditable() {
                                            try {
                                                setConfigurationLoading(false);

                                                const keyInput = document.getElementById('g_ffl_cockpit_key');
                                                if (keyInput) {
                                                    keyInput.disabled = false;
                                                    keyInput.readOnly = false;
                                                    keyInput.style.pointerEvents = 'auto';
                                                    keyInput.style.opacity = '1';
                                                }

                                                const keyForm = document.getElementById('g_ffl_cockpit_key_form');
                                                if (keyForm) {
                                                    keyForm.style.display = 'flex';
                                                    keyForm.style.visibility = 'visible';
                                                }

                                                const keyLabel = document.getElementById('gffc-cockpit-key-label');
                                                if (keyLabel) {
                                                    keyLabel.style.display = '';
                                                    keyLabel.style.visibility = 'visible';
                                                }

                                                const setKeyContainer = document.getElementById('set_key_form');
                                                if (setKeyContainer) {
                                                    // Make it easy to fix a bad key without needing extra clicks.
                                                    setKeyContainer.style.display = 'inline';
                                                }

                                                if (keyInput) {
                                                    keyInput.focus();
                                                    keyInput.select?.();
                                                }
                                            } catch (e) {
                                                // no-op
                                            }
                                        }

                                        function get_and_set_cockpit_configuration(api_key, isAdminRequest){
                                            // Prevent duplicate concurrent loads (which can cause repeated alerts).
                                            if (window.gffcConfigLoadInProgress) {
                                                return;
                                            }
                                            window.gffcConfigLoadInProgress = true;
                                            window.gffcCurrentConfigLoadKey = api_key;

                                            const currentSiteBaseUrl = window.location.origin;
                                            const errorMessage = `The API Key entered could not be found, the API Key is not associated with this Site URL: <b>${currentSiteBaseUrl}</b>, or the account tied to this API Key may be canceled/inactive. Please re-enter your API Key, or send the exact site URL to support@garidium.com to get it on the approved list for your API Key.`;

                                            const finish = () => {
                                                window.gffcConfigLoadInProgress = false;
                                                setConfigurationLoading(false);
                                            };

                                            const handleFailure = (error) => {
                                                try {
                                                    console.log(error);

                                                    const isKeyIssue = error && error.gffcKeyIssue === true;
                                                    if (isKeyIssue) {
                                                        showInvalidKeyOverlay(errorMessage, getConfigurationLoadDiagnostic(error));
                                                        ensureApiKeyFieldEditable();
                                                    } else {
                                                        hideInvalidKeyOverlay();
                                                        try {
                                                            editor.set({
                                                                "Configuration Load Issue": "FFL Cockpit could not load the configuration right now. This may be a temporary API, network, or server response issue. Your saved API key was not changed. Please refresh and try again; if it continues, contact support@garidium.com."
                                                            });
                                                        } catch (e) {
                                                            // no-op
                                                        }
                                                    }

                                                    // Only default to a blank configuration when the key/subscription is actually invalid.
                                                    if (isKeyIssue) {
                                                        try {
                                                            if (typeof loadDefaultConfiguration === 'function') {
                                                                loadDefaultConfiguration();
                                                            }
                                                        } catch (e) {
                                                            console.log(e);
                                                        }
                                                    }
                                                } finally {
                                                    finish();
                                                }
                                            };

                                            try {
                                                if (!api_key || api_key.length === 0) {
                                                    const missingKeyError = new Error('Missing API key');
                                                    missingKeyError.gffcKeyIssue = true;
                                                    handleFailure(missingKeyError);
                                                    return;
                                                }

                                                setConfigurationLoading(true);

                                                var admin_key = api_key;
                                                if (isAdminRequest){
                                                    admin_key = "<?php echo esc_attr($gFFLCockpitKey);?>";
                                                }
                                                window.gffcCurrentConfigLoadContext = {
                                                    lookupApiKey: api_key,
                                                    requestHeaderApiKey: admin_key,
                                                    isAdminRequest: !!isAdminRequest
                                                };

                                                const fetchSubscriptionConfiguration = () => {
                                                    return fetch("https://ffl-api.garidium.com", {
                                                        method: "POST",
                                                        cache: "no-store",
                                                        headers: {
                                                            "Accept": "application/json",
                                                            "Content-Type": "application/json",
                                                            "x-api-key": admin_key,
                                                        },
                                                        body: JSON.stringify({"action": "get_subscription", "data": {"api_key": api_key}})
                                                    })
                                                    .then(response => {
                                                        if (!response.ok) {
                                                            return response.text().then(responseText => {
                                                                const requestError = new Error('Configuration request failed with HTTP ' + response.status);
                                                                requestError.gffcKeyIssue = response.status === 401 || response.status === 403;
                                                                requestError.gffcHttpStatus = response.status;
                                                                requestError.gffcResponseText = responseText;
                                                                throw requestError;
                                                            });
                                                        }
                                                        return response.json();
                                                    })
                                                    .then(data => {
                                                        if (!data || !Array.isArray(data) || !data[0] || !data[0].cockpit_configuration) {
                                                            const keyError = new Error('No configuration found for key');
                                                            keyError.gffcKeyIssue = isAdminRequest || (window.gFFLCockpit && window.gFFLCockpit.keyJustSaved === true);
                                                            throw keyError;
                                                        }
                                                        return data;
                                                    });
                                                };

                                                fetchSubscriptionConfiguration()
                                                .catch(firstError => {
                                                    return new Promise(resolve => setTimeout(resolve, 750))
                                                        .then(fetchSubscriptionConfiguration)
                                                        .catch(retryError => {
                                                            retryError.gffcRetryAttempted = true;
                                                            retryError.gffcOriginalErrorMessage = firstError && firstError.message ? firstError.message : '';
                                                            if (firstError && firstError.gffcHttpStatus) {
                                                                retryError.gffcFirstHttpStatus = firstError.gffcHttpStatus;
                                                            }
                                                            throw retryError;
                                                        });
                                                })
                                                .then(data=>{
                                                    try{
                                                        console.log(">Retreived Configuration");
                                                        cockpit_configuration = JSON.parse(data[0].cockpit_configuration);
                                                        console.log(">Parsed Configuration");
                                                        editor.set(cockpit_configuration);
                                                        console.log(">Set Configuration");
                                                        initialCockpitConfiguration = editor.get();
                                                        console.log(">Initialied initial Configuration");
                                                        load_fancy_editor(cockpit_configuration);
                                                        console.log(">Loaded Fancy Editor");
                                                        loadExistingAIConfiguration();
                                                        console.log(">Loaded AI Configuration");
                                                        setupAutoSave();
                                                        console.log(">AutoSave Setup");

                                                        // Success: allow full UI again
                                                        hideInvalidKeyOverlay();

                                                        <?php if (!(function_exists('g_ffl_is_fflcockpit_multisite_domain') ? g_ffl_is_fflcockpit_multisite_domain() : is_multisite())) : ?>
                                                            try {
                                                                if (isAdminRequest) {
                                                                    window.gFFLCockpit.loadSiteHealth(null, api_key);
                                                                } else {
                                                                    window.gFFLCockpit.loadSiteHealth(api_key);
                                                                }
                                                            } catch (error) {
                                                                console.log("Site Health Update Failed");
                                                            }
                                                        <?php endif; ?>

                                                        finish();
                                                    } catch (error) {
                                                        handleFailure(error);
                                                    }
                                                })
                                                .catch(handleFailure);
                                            }catch(error){
                                                handleFailure(error);
                                            }
                                        }
                                    </script>
                                    <script>
                                        var editor = new JSONEditor(document.getElementById("jsoneditor"));
                                        editor.set({"Loading Configuration": "Please wait..."});
                                        
                                        // Wait for all dependencies to load
                                        function waitForDependencies(callback) {
                                            var checkCount = 0;
                                            var maxChecks = 50; // 5 seconds max wait
                                            
                                            function checkDependencies() {
                                                checkCount++;
                                                
                                                // Check if jQuery is available
                                                if (typeof jQuery === 'undefined') {
                                                    if (checkCount < maxChecks) {
                                                        setTimeout(checkDependencies, 100);
                                                        return;
                                                    } else {
                                                        console.warn('jQuery not loaded after 5 seconds');
                                                        return;
                                                    }
                                                }
                                                
                                                // Check if Select2 is available (if needed)
                                                if (typeof jQuery.fn.select2 === 'undefined' && checkCount < maxChecks) {
                                                    setTimeout(checkDependencies, 100);
                                                    return;
                                                }
                                                
                                                // Check if TinyMCE is available
                                                if (typeof tinymce === 'undefined' && checkCount < maxChecks) {
                                                    setTimeout(checkDependencies, 100);
                                                    return;
                                                }
                                                
                                                // All dependencies loaded, run callback
                                                callback();
                                            }
                                            
                                            checkDependencies();
                                        }
                                        
                                        waitForDependencies(function() {
                                            jQuery(document).ready(function($) {
                                            
                                            async function initialize() {
                                                var tschema = await get_target_schema();
                                                if (tschema == null || !window.gFFLCockpit || window.gFFLCockpit.apiKey == null || window.gFFLCockpit.apiKey == undefined || window.gFFLCockpit.apiKey.length < 40){
                                                    document.getElementById('configuration').innerHTML='<b>There was a problem retreiving your FFL Cockpit configuration</b>. If you have not purchased a key for FFL Cockpit, you can do so here: <a target=_blank href="https://fflcockpit.com">Subscribe to FFL Cockpit</a>. If you have a key, and believe you entered it properly below, please contact support@garidium.com for assistance. This error can also appear if there was a temporary system outage. In that case please check back later.';
                                                    document.getElementById('configuration').style.background = "#e7bec5";
                                                    document.getElementById('configuration').style.margin = "20px";
                                                    document.getElementById('configuration').style.border = "solid black 2px";

                                                    // Missing/invalid key: hide all cockpit tabs and show only the warning + key entry field.
                                                    var tabs = document.getElementById('cockpit_main_tab_control');
                                                    if (tabs) tabs.style.display = 'none';

                                                    // Mobile tab accordions: hide them too (we don't want any tab navigation without a key).
                                                    var accordions = document.querySelectorAll('button.accordion');
                                                    accordions.forEach(function (btn) {
                                                        btn.style.display = 'none';
                                                    });

                                                    // Ensure no other tab content is visible.
                                                    var tabcontent = document.getElementsByClassName('tabcontent');
                                                    for (var i = 0; i < tabcontent.length; i++) {
                                                        tabcontent[i].style.display = 'none';
                                                    }

                                                    // Force the configuration panel visible for the warning message.
                                                    var cfg = document.getElementById('configuration');
                                                    if (cfg) cfg.style.display = 'block';
                                                    return;
                                                }

                                                await get_distributors_schema();
                                                await reset_validated_distributors();

                                                fetch("https://ffl-api.garidium.com", {
                                                    method: "POST",
                                                    headers: {
                                                        "Accept": "application/json",
                                                        "Content-Type": "application/json",
                                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>",
                                                    },
                                                    body: JSON.stringify({
                                                        "action": "get_configuration_schema",
                                                        "data": {
                                                            "api_key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                                        }
                                                    })
                                                })
                                                .then(response => response.json())
                                                .then(data => { 
                                                    if (data != null) {
                                                        build_grid(data.schema);
                                                        $('#add-distributor').on('click', function () {
                                                                const selectedDistributor = $('#available-distributors').val();
                                                                if (selectedDistributor) {
                                                                    addDistributorForm(selectedDistributor, {});

                                                                    // Now add the distributor info to the configuration
                                                                    config = editor.get();
                                                                    config.distributors[selectedDistributor] = JSON.parse(distributorsSchema[selectedDistributor]['default_config']);
                                                                    editor.set(config);
                                                                }
                                                            });

                                                        $('#add-target').on('click', function () {
                                                            const selectedTarget = $('#available-targets').val();
                                                            if (selectedTarget) {
                                                                addTargetForm(selectedTarget, {});

                                                                // Now add the distributor info to the configuration
                                                                config = editor.get();
                                                                config.targets[selectedTarget] = JSON.parse(targetSchema[selectedTarget]['default_config']);
                                                                editor.set(config);
                                                            }
                                                        });
                                                        return true;
                                                    }
                                                });
                                                return false;
                                            }
                                            initialize();
                                        });

                                        // Clean up target initialization state when modal is hidden
                                        $('#detailsModal').on('hidden.bs.modal', function (e) {
                                            if (window.targetInitialized) {
                                                // Clear all target initialization flags to allow proper re-initialization
                                                window.targetInitialized = {};
                                            }
                                        });

                                        function getValidationErrorMessage(errors) {
                                            let messages = [];
                                            if (Array.isArray(errors)) {
                                                errors.forEach(error => {
                                                    if (error.message) {
                                                        messages.push({"dataPath": error.dataPath, "message": error.message, "data": error.data ? `(${error.data}) ` : ""});
                                                    } else if (error.error) {
                                                        messages.push({"dataPath": error.error.dataPath, "message": error.error.message, "data": error.error.data ? `(${error.error.data}) ` : ""});
                                                    } else if (error.errors) {
                                                        error.errors.forEach(innerError => {
                                                            if (innerError.message) {
                                                                messages.push({"dataPath": innerError.dataPath, "message": innerError.message, "data": innerError.data ? `(${innerError.data}) ` : ""});
                                                            }
                                                        });
                                                    }
                                                });
                                            } else if (typeof errors === 'object' && errors !== null) {
                                                if (errors.message) {
                                                    messages.push({"dataPath": errors.dataPath, "message": errors.message, "data": errors.data ? `(${errors.data}) ` : ""});
                                                } else if (errors.errors) {
                                                    errors.errors.forEach(innerError => {
                                                        if (innerError.message) {
                                                            messages.push({"dataPath": innerError.dataPath, "message": innerError.message, "data": innerError.data ? `(${innerError.data}) ` : ""});
                                                        }
                                                    });
                                                }
                                            }

                                            if (messages.length === 0) {
                                                messages.push('An unknown error occurred.');
                                            }

                                            // Display messages to the user
                                            let returnMessage = "";
                                            messages.forEach(message => {
                                                let errorMessage = message.message;
                                                if (message.message.includes("1791")) {
                                                    errorMessage = "One or more of your selected brands " + message.data + " is invalid, or has been removed and consolidated with another brand name.";
                                                } else if (message.message.includes("AR Rifles")) {
                                                    errorMessage = "One of your selected categories " + message.data + " is invalid.";
                                                } else {
                                                    errorMessage = message.data + errorMessage;
                                                }
                                                returnMessage += `<li>${message.dataPath} - ${errorMessage}</li>`;
                                            });
                                            return returnMessage;
                                        }
``

                                        function build_grid(config_schema){
                                            const onChangeHandler = function () {
                                                const currentJson = editor.get();
                                                const isChanged = initialCockpitConfiguration !=null && JSON.stringify(currentJson) !== JSON.stringify(initialCockpitConfiguration);
                                                document.getElementById('unsaved-indicator').style.display = isChanged ? 'block' : 'none';
                                                
                                                // Update button states based on unsaved changes
                                                if (typeof updateButtonStates === 'function') {
                                                    updateButtonStates();
                                                }
                                                
                                                const errors = editor.validate();
                                                // Assume 'editor' is your jsoneditor instance
                                                editor.validate().then((results) => {
                                                    const errorContainer = document.getElementById("validation-errors");
                                                    if (results.length === 0) {
                                                        errorContainer.innerHTML = '';
                                                    } else {
                                                        let errorMessages = 'There are <span style="color:red;text-decoration:underline;">' + results.length + ' errors detected</span> in your configuration. Please review and resolve these errors or you will not be able to save your changes.<br><br><span style="margin-left:5px;color:red;font-weight:bold;">Errors:</span><ul style="margin-top:5px;margin-bottom:0px;padding-bottom:0px;color:red;padding-left: 30px;list-style-type: disc;">';
                                                        errorMessages += getValidationErrorMessage(results);
                                                        errorMessages += '</ul>';
                                                        errorContainer.innerHTML = errorMessages;
                                                    }
                                                }).catch((err) => {
                                                    console.error("Validation failed:", err);
                                                });

                                            };

                                            const options = {
                                                modes: ['text','tree'],
                                                mode: 'tree',
                                                ace: ace,
                                                schema: config_schema,
                                                onChange: onChangeHandler
                                            };
                                            editor.destroy();
                                            editor = new JSONEditor(document.getElementById("jsoneditor"), options);
                                           
                                            editor.set({"Loading Configuration": "Please wait..."});
                                            get_and_set_cockpit_configuration("<?php echo esc_attr($gFFLCockpitKey);?>", false);
                                
                                            // Override the set function to include onChangeHandler
                                            const originalSet = editor.set.bind(editor);
                                            editor.set = function (json) {
                                                originalSet(json);
                                                onChangeHandler();
                                            };

                                            if (window.location.host == 'garidium.com' || window.location.host == 'localhost:8000'){
                                                document.getElementById('g-ffl-admin-buttons').style.display = '';
                                            }

                                            // Warn user before leaving the page with unsaved changes
                                            window.addEventListener('beforeunload', function (e) {
                                                if (initialCockpitConfiguration!=null && JSON.stringify(editor.get()) !== JSON.stringify(initialCockpitConfiguration)) {
                                                    const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
                                                    e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
                                                    return confirmationMessage; // Gecko, WebKit, Chrome <34
                                                }
                                            });

                                            
                                        }
                                        });
                                    </script>
                                </td>
                            </tr>
                            <tr valign="top" id="white_label_settings_name" style="display:none;">
                                <th scope="row">Plugin Name:</th>
                                <td>
                                    <input type="text" style="width: 30%" name="g_ffl_cockpit_plugin_name" maxlength=20
                                            value="<?php echo esc_attr(get_option('g_ffl_cockpit_plugin_name') != '' ? get_option('g_ffl_cockpit_plugin_name') : 'g-FFL Cockpit'); ?>"/>
                                </td>
                            </tr>
                            <tr valign="top" id="white_label_settings_url" style="display:none;">
                                <th scope="row">Plugin Logo URL:</th>
                                <td>
                                    <input type="text" style="width: 500px;" name="g_ffl_cockpit_plugin_logo_url"
                                            value="<?php echo esc_attr(get_option('g_ffl_cockpit_plugin_logo_url') != '' ? get_option('g_ffl_cockpit_plugin_logo_url') : plugin_dir_url(__FILE__) . 'images/ffl-cockpit-logo.svg');?>"/>
                                </td>
                            </tr>
                        </table>
                        <a style="cursor:pointer;" onclick="document.getElementById('white_label_settings_name').style.display='';document.getElementById('white_label_settings_url').style.display='';">&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;</a>
                </div>
                <style>
                    @media screen and (max-width: 768px) {
                        .gffc-admin-action-table,
                        .gffc-admin-action-table tbody,
                        .gffc-admin-action-table tr,
                        .gffc-admin-action-table td {
                            display: block;
                            width: 100% !important;
                            box-sizing: border-box;
                        }

                        .gffc-admin-action-table td[align="right"] {
                            text-align: left !important;
                        }

                        .gffc-admin-action-table button.btn {
                            display: block;
                            width: 100%;
                            margin: 0 0 10px 0;
                            white-space: normal;
                        }

                        .gffc-admin-action-stack {
                            display: flex;
                            flex-direction: column;
                            gap: 10px;
                        }

                        .gffc-admin-action-stack button.btn {
                            margin: 0;
                        }
                    }

                    /* Match the green "Validated" ribbon style */
                    #validate_configuration_button.btn {
                        background-color: #b5ffd2 !important;
                        border-color: #cbd5e1 !important;
                        color: #000 !important;
                        font-weight: 700;
                        border-width: 2px;
                        border-style: solid;
                        box-shadow: 0 0 0 1px #cbd5e1, 0 1px 5px rgba(0, 0, 0, 0.2);
                    }
                    #validate_configuration_button.btn:hover {
                        background-color: #b5ffd2 !important;
                        border-color: #cbd5e1 !important;
                        color: #000 !important;
                        filter: brightness(0.97);
                    }
                </style>

                <table class="gffc-admin-action-table" style="width:100%;">
                            <tr>
                                <td>
                                    <div>
                                        <button class="btn btn-primary" id="save_cockpit_configuration_button">Save Changes</button>
                                        
                                        <!-- Save Progress Modal -->
                                        <div id="gffc_save_modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.5); z-index: 10000; align-items:center; justify-content:center; padding: 20px; box-sizing:border-box;">
                                            <div style="background: #fff; max-width: 500px; width: 100%; border-radius: 10px; padding: 24px; box-shadow: 0 10px 30px rgba(0,0,0,0.25); position: relative;">
                                                <div id="gffc_save_modal_header" style="font-size: 18px; font-weight: 700; color: #1d2327; margin-bottom: 16px; display: flex; align-items: center; gap: 10px;">
                                                    <span id="gffc_save_modal_icon"></span>
                                                    <span id="gffc_save_modal_title">Saving Configuration...</span>
                                                </div>
                                                <div id="gffc_save_modal_content" style="font-size: 14px; color: #1d2327; line-height: 1.6;">
                                                    <div id="gffc_save_modal_progress" style="text-align: center; padding: 20px 0;">
                                                        <div style="display: inline-block; width: 40px; height: 40px; border: 4px solid #e0e0e0; border-top-color: #2271b1; border-radius: 50%; animation: gffc-spin 1s linear infinite;"></div>
                                                        <div style="margin-top: 12px; color: #666;">Please wait while your changes are being saved...</div>
                                                    </div>
                                                    <div id="gffc_save_modal_message" style="display: none;"></div>
                                                </div>
                                                <div id="gffc_save_modal_footer" style="margin-top: 20px; text-align: right; display: none;">
                                                    <button id="gffc_save_modal_close" class="btn btn-primary" style="padding: 8px 20px;">OK</button>
                                                </div>
                                            </div>
                                        </div>
                                        <style>
                                            @keyframes gffc-spin {
                                                to { transform: rotate(360deg); }
                                            }
                                            .gffc-save-success { background: #d4edda; border-left: 4px solid #28a745; padding: 12px 16px; border-radius: 4px; }
                                            .gffc-save-error { background: #f8d7da; border-left: 4px solid #dc3545; padding: 12px 16px; border-radius: 4px; }
                                            .gffc-save-warning { background: #fff3cd; border-left: 4px solid #ffc107; padding: 12px 16px; border-radius: 4px; margin-top: 12px; }
                                            .gffc-save-info { background: #e7f3ff; border-left: 4px solid #2271b1; padding: 12px 16px; border-radius: 4px; }
                                        </style>
                                        
                                        <script type="text/javascript">
                                            (function() {
                                                const modal = document.getElementById('gffc_save_modal');
                                                const modalTitle = document.getElementById('gffc_save_modal_title');
                                                const modalIcon = document.getElementById('gffc_save_modal_icon');
                                                const modalProgress = document.getElementById('gffc_save_modal_progress');
                                                const modalMessage = document.getElementById('gffc_save_modal_message');
                                                const modalFooter = document.getElementById('gffc_save_modal_footer');
                                                const closeBtn = document.getElementById('gffc_save_modal_close');
                                                
                                                function showModal() {
                                                    modalTitle.textContent = 'Saving Configuration...';
                                                    modalIcon.innerHTML = '';
                                                    modalProgress.style.display = 'block';
                                                    modalMessage.style.display = 'none';
                                                    modalMessage.innerHTML = '';
                                                    modalFooter.style.display = 'none';
                                                    modal.style.display = 'flex';
                                                }
                                                
                                                function showResult(result) {
                                                    modalProgress.style.display = 'none';
                                                    modalMessage.style.display = 'block';
                                                    modalFooter.style.display = 'block';
                                                    
                                                    let messageHtml = '';
                                                    
                                                    console.log('Save result:', result);
                                                    
                                                    if (result.error_message) {
                                                        // Error state
                                                        modalTitle.textContent = 'Save Failed';
                                                        modalIcon.innerHTML = '<span style="color: #dc3545; font-size: 24px;">✕</span>';
                                                        messageHtml += '<div class="gffc-save-error"><strong>Error:</strong> ' + result.error_message + '</div>';
                                                    } else if (result.no_changes) {
                                                        // No changes detected (success=false but no error)
                                                        modalTitle.textContent = 'No Changes Detected';
                                                        modalIcon.innerHTML = '<span style="color: #2271b1; font-size: 24px;">ℹ</span>';
                                                        messageHtml += '<div class="gffc-save-info">No changes were detected in your configuration.</div>';
                                                    } else {
                                                        // Success state - changes were saved
                                                        modalTitle.textContent = 'Changes Saved Successfully';
                                                        modalIcon.innerHTML = '<span style="color: #28a745; font-size: 24px;">✓</span>';
                                                        messageHtml += '<div class="gffc-save-success">Your FFL Cockpit configuration has been updated successfully.</div>';
                                                    }
                                                    
                                                    // Add warning if present (can appear with success or other states)
                                                    if (result.warning_message) {
                                                        messageHtml += '<div class="gffc-save-warning"><strong>Warning:</strong> ' + result.warning_message + '</div>';
                                                    }
                                                    
                                                    modalMessage.innerHTML = messageHtml;
                                                }
                                                
                                                function hideModal() {
                                                    modal.style.display = 'none';
                                                }
                                                
                                                closeBtn.addEventListener('click', hideModal);
                                                
                                                // Close modal when clicking outside
                                                modal.addEventListener('click', function(e) {
                                                    if (e.target === modal) {
                                                        hideModal();
                                                    }
                                                });
                                                
                                                document.getElementById("save_cockpit_configuration_button").addEventListener("click", function(event){
                                                    event.preventDefault();
                                                    document.getElementById("save_cockpit_configuration_button").disabled = true;

                                                    showModal();

                                                    setConfig(window.gFFLCockpit.apiKey).then(function(result) {
                                                        showResult(result);
                                                        if (result.success && !result.error_message) {
                                                            refreshEditor();
                                                        }
                                                        document.getElementById("save_cockpit_configuration_button").disabled = false;
                                                    }).catch(function(error) {
                                                        console.error('Save error:', error);
                                                        showResult({
                                                            success: false,
                                                            error_message: 'An unexpected error occurred. Please try again.',
                                                            warning_message: null
                                                        });
                                                        document.getElementById("save_cockpit_configuration_button").disabled = false;
                                                    });
                                                });
                                            })();
                                        </script>
                                    </div>
                                </td>
                                <td align="right">
                                    <div class="gffc-admin-action-stack">
                                    <button class="btn btn-secondary" id="validate_configuration_button">Validate Configuration</button>
                                        <script>
                                            document.getElementById("validate_configuration_button").addEventListener("click", function(){
                                            document.getElementById("validate_configuration_button").disabled = true;
                                            document.getElementById('validate_configuration_button').innerText = 'Request Sent';
                                            fetch("https://ffl-api.garidium.com", {
                                                    method: "POST",
                                                    headers: {
                                                    "Accept": "application/json",
                                                    "Content-Type": "application/json",
                                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                                    },
                                                    body: JSON.stringify({"action": "validate_cockpit_configuration", "data": {"api_key": document.getElementById('g_ffl_cockpit_key').value}})
                                                })
                                                .then(response=>response.json())
                                                .then(data=>{ 
                                                    alert("Your request for validation was submitted. You should receive an email within 5-minutes summarizing any critical configurations issues (if you have any).");
                                                    document.getElementById("validate_configuration_button").disabled = false; 
                                                    document.getElementById('validate_configuration_button').innerText = 'Validate Configuration';     
                                                });
                                            });
                                        </script>

                                        <button class="btn btn-secondary" id="send_test_fulfillment_emails_button">Send Test Fulfillment Emails</button>
                                        <script>
                                            document.getElementById("send_test_fulfillment_emails_button").addEventListener("click", function(){
                                                document.getElementById("send_test_fulfillment_emails_button").disabled = true;
                                                document.getElementById('send_test_fulfillment_emails_button').innerText = 'Please Wait...';
                                                fetch("https://ffl-api.garidium.com", {
                                                        method: "POST",
                                                        headers: {
                                                        "Accept": "application/json",
                                                        "Content-Type": "application/json",
                                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                                        },
                                                        body: JSON.stringify({"action": "send_test_emails", "data": {"api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"}})
                                                    })
                                                    .then(response=>response.json())
                                                    .then(data=>{ 
                                                        document.getElementById("send_test_fulfillment_emails_button").disabled = false; 
                                                        document.getElementById('send_test_fulfillment_emails_button').innerText = 'Send Test Fulfillment Emails';     
                                                    });
                                            });
                                        </script>
                                    </div>
                                </td>
                            </tr>
                        </table>
            </div>
            
            <button class="accordion">Product Search</button>
            <div id="product_feed" class="tabcontent">
                <style>
                    /* Hide WordPress admin notices on G-FFL Cockpit plugin pages only */
                    .toplevel_page_g-ffl-cockpit-settings .notice,
                    .toplevel_page_g-ffl-cockpit-settings .update-nag,
                    .toplevel_page_g-ffl-cockpit-settings .error,
                    .toplevel_page_g-ffl-cockpit-settings .updated,
                    .toplevel_page_g-ffl-cockpit-settings .notice-error,
                    .toplevel_page_g-ffl-cockpit-settings .notice-warning,
                    .toplevel_page_g-ffl-cockpit-settings .notice-success,
                    .toplevel_page_g-ffl-cockpit-settings .notice-info {
                        display: none !important;
                    }
                </style>
                <!-- The Modal -->
                <div id="productDetailsModal" class="modal">
                    <!-- Modal content -->
                    <div class="cockpit-modal-content modal-content">
                        <span id="productDetailImageModalCloser" class="close">&times;</span>
                        <div align="center" id="product_detail_div"></div>
                    </div>
                    <script>
                        // Get the modal
                        var modal = document.getElementById("productDetailsModal");

                        // Get the button that opens the modal
                        var btn = document.getElementById("myBtn");

                        // Get the <span> element that closes the modal
                        var span = document.getElementById("productDetailImageModalCloser");

                        function load_product_data(title, distributor, sku, img_url){
                            modal.style.display = "block";
                            document.getElementById("product_detail_div").innerHTML = "<h5>" + title + "</h5><br><img class='responsive-image' src='" + img_url + "'/><br><img style='height:75px;' src='" + get_distributor_logo(distributor) + "' onerror='this.style.display=\"none\";'/><br>" + sku;
                        }

                        // When the user clicks on <span> (x), close the modal
                        span.onclick = function() {
                            modal.style.display = "none";
                        }

                    </script>
                </div>

                <!-- Wishlist: Add Item Modal -->
                <div id="gffc-wishlist-add-modal" onclick="if(event.target===this)this.style.display='none';" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:100001;align-items:center;justify-content:center;">
                    <div style="background:#fff;border-radius:12px;max-width:460px;width:90%;padding:24px;box-shadow:0 8px 32px rgba(0,0,0,0.2);position:relative;">
                        <button onclick="document.getElementById('gffc-wishlist-add-modal').style.display='none';" style="position:absolute;top:10px;right:14px;background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
                        <div style="display:flex;align-items:center;gap:10px;margin-bottom:16px;">
                            <i class="fas fa-bell" style="color:#ff6b35;font-size:22px;"></i>
                            <h3 id="gffc-wishlist-modal-title" style="margin:0;font-size:18px;color:#1e293b;">Add to Wishlist</h3>
                        </div>
                        <div style="font-size:12px;color:#64748b;margin-bottom:14px;">Adding UPC <b id="gffc-wishlist-add-upc" style="color:#1e293b;"></b>. Optional fields below help track who's waiting on this item.</div>
                        <div style="display:flex;flex-direction:column;gap:10px;">
                            <div>
                                <label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:3px;">Customer Name <span style="color:#94a3b8;font-weight:400;">(optional)</span></label>
                                <input type="text" id="gffc-wishlist-add-name" placeholder="John Smith" style="width:100%;padding:8px 12px;font-size:14px;border:1px solid #e2e8f0;border-radius:6px;box-sizing:border-box;">
                            </div>
                            <div>
                                <label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:3px;">Customer Phone <span style="color:#94a3b8;font-weight:400;">(optional)</span></label>
                                <input type="tel" id="gffc-wishlist-add-phone" placeholder="555-1234" style="width:100%;padding:8px 12px;font-size:14px;border:1px solid #e2e8f0;border-radius:6px;box-sizing:border-box;">
                            </div>
                            <div>
                                <label style="font-size:12px;font-weight:600;color:#334155;display:block;margin-bottom:3px;">Notes <span style="color:#94a3b8;font-weight:400;">(optional)</span></label>
                                <textarea id="gffc-wishlist-add-notes" rows="3" placeholder="Any details to remember..." style="width:100%;padding:8px 12px;font-size:14px;border:1px solid #e2e8f0;border-radius:6px;box-sizing:border-box;font-family:inherit;resize:vertical;"></textarea>
                            </div>
                        </div>
                        <div style="display:flex;gap:8px;justify-content:space-between;align-items:center;margin-top:16px;flex-wrap:wrap;">
                            <button id="gffc-wishlist-remove-btn" onclick="gffcWishlistModalRemove()" style="display:none;padding:8px 14px;background:#fef2f2;color:#991b1b;border:1px solid #fecaca;border-radius:6px;font-weight:600;cursor:pointer;align-items:center;"><i class="fas fa-trash" style="margin-right:5px;"></i>Remove</button>
                            <div style="display:flex;gap:8px;margin-left:auto;">
                                <button onclick="document.getElementById('gffc-wishlist-add-modal').style.display='none';" style="padding:8px 18px;background:#f1f5f9;color:#64748b;border:1px solid #e2e8f0;border-radius:6px;font-weight:600;cursor:pointer;">Cancel</button>
                                <button id="gffc-wishlist-submit-btn" onclick="gffcWishlistAddSubmit()" style="padding:8px 18px;background:#ff6b35;color:#fff;border:none;border-radius:6px;font-weight:600;cursor:pointer;"><i class="fas fa-bell" style="margin-right:5px;"></i>Add to Wishlist</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Wishlist: View Modal -->
                <div id="gffc-wishlist-viewer-modal" onclick="if(event.target===this)this.style.display='none';" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:100001;align-items:center;justify-content:center;">
                    <div style="background:#fff;border-radius:12px;max-width:720px;width:92%;max-height:85vh;display:flex;flex-direction:column;box-shadow:0 8px 32px rgba(0,0,0,0.2);position:relative;">
                        <div style="padding:20px 24px 12px;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;justify-content:space-between;">
                            <div style="display:flex;align-items:center;gap:10px;">
                                <i class="fas fa-bell" style="color:#ff6b35;font-size:22px;"></i>
                                <h3 style="margin:0;font-size:18px;color:#1e293b;">Your Wishlist</h3>
                            </div>
                            <button onclick="document.getElementById('gffc-wishlist-viewer-modal').style.display='none';" style="background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
                        </div>
                        <div id="gffc-wishlist-viewer-body" style="padding:16px 24px;overflow-y:auto;flex:1;"></div>
                    </div>
                </div>

                <div style="background: #fff; padding: 10px; overflow-x: scroll; min-height: 90vh; display: flex; flex-direction: column;">
                    <style>
                        .gffc-header-area { position: relative; min-height: 60px; margin-bottom: 20px; }
                        .gffc-toggle-section { position: absolute; top: 0; right: 0; z-index: 10; }

                        .gffc-search-wrapper { transition: all 0.5s ease; width: 100%; }
                        
                        /* Initial State: Centered vertically and horizontally */
                        .gffc-search-wrapper.initial {
                            padding-top: 25vh;
                            display: flex; 
                            justify-content: center;
                        }
                        .gffc-search-wrapper.initial .g-ffl-cockpit-product-search-container {
                            flex-direction: column; width: auto !important; gap: 20px; justify-content: center;
                        }
                        .gffc-search-wrapper.initial #cockpit-product-search-input {
                            width: 750px !important; height: 50px; font-size: 1.2em; box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                        }
                        .gffc-search-wrapper.initial .btn-primary {
                            padding: 0 30px; height: 50px; font-size: 1.1em;
                        }

                        /* Active State: Top Left */
                        .gffc-search-wrapper.active {
                            padding-top: 0;
                        }
                        .gffc-search-wrapper.active .g-ffl-cockpit-product-search-container {
                            justify-content: flex-start !important; /* Align left */
                        }
                        .gffc-search-wrapper.active .g-ffl-cockpit-product-search-container > div {
                            justify-content: flex-start !important; /* Align inner div left */
                            flex-grow: 0 !important; /* Don't grow to fill */
                        }
                        
                        .gffc-footer { display: flex; gap: 20px; margin-top: auto; padding-top: 20px; border-top: 1px solid #f0f0f1; }
                        .gffc-footer-col { flex: 1; }
                        .gffc-footer-right { display: flex; flex-direction: column; justify-content: space-between; align-items: flex-end; gap: 10px; }

                        .gffc-btn-add {
                            background-color: transparent;
                            border: 1px solid #2271b1;
                            color: #2271b1;
                            border-radius: 4px;
                            padding: 6px 12px;
                            font-size: 13px;
                            font-weight: 600;
                            cursor: pointer;
                            transition: all 0.2s ease;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 6px;
                            width: 100%;
                            line-height: 1.2;
                        }
                        .gffc-btn-add:hover {
                            background-color: #2271b1;
                            color: white;
                            box-shadow: 0 2px 4px rgba(34, 113, 177, 0.3);
                            transform: translateY(-1px);
                        }
                        .gffc-btn-add:active {
                            transform: translateY(0);
                            box-shadow: none;
                        }

                        /* Distributor Site button label: desktop vs mobile */
                        #product_feed .gffc-view-dist-site-short { display: none; }
                        #product_feed .gffc-view-dist-site-full { display: inline; }

                        /* Product Search results (desktop): slightly stronger row separators */
                        @media screen and (min-width: 769px) {
                            #product_feed .gridjs-table tbody tr td.gridjs-td {
                                border-bottom: 2px solid #e2e8f0 !important;
                            }
                            #product_feed .gridjs-table tbody tr:last-child td.gridjs-td {
                                border-bottom: 0 !important;
                            }
                            #product_feed .gridjs-table tbody tr:hover td.gridjs-td {
                                background: #f8fafc;
                            }
                        }

                        /* Hide mobile-only icons by default */
                        .gffc-mobile-icon { display: none !important; }

                        /* Wishlist button: keep aligned on the recent searches row */
                        @media screen and (max-width: 768px) {
                            #product_feed .gffc-recent-row { flex-direction: column; align-items: stretch; }
                            #product_feed #gffc-wishlist-btn { width: 100%; justify-content: center; }
                        }

                        /* Narrow desktop/tablet widths: prevent toggle overlap with search controls */
                        @media screen and (max-width: 1400px) and (min-width: 769px) {
                            #product_feed .gffc-header-area {
                                display: flex;
                                flex-direction: column;
                                gap: 8px;
                            }
                            #product_feed .gffc-toggle-section {
                                position: relative;
                                top: auto;
                                right: auto;
                                width: 100%;
                                display: flex;
                                justify-content: flex-end;
                                margin: 0;
                            }
                            #product_feed #gffc-search-wrapper {
                                width: 100%;
                            }
                            #product_feed .g-ffl-cockpit-product-search-container {
                                width: 100% !important;
                            }
                            #product_feed .g-ffl-cockpit-product-search-container > div {
                                width: 100% !important;
                                justify-content: flex-start !important;
                            }
                            #product_feed #gffc-search-wrapper .gffc-search-input-wrap {
                                flex: 1 1 520px;
                                min-width: 320px;
                                max-width: 750px;
                                width: 100%;
                            }
                            #product_feed #gffc-search-wrapper #cockpit-product-search-input {
                                width: 100% !important;
                                max-width: 100% !important;
                            }
                            #product_feed #gffc-search-wrapper button.btn.btn-primary {
                                flex: 0 0 auto;
                                white-space: nowrap;
                            }
                        }

                        /* Mobile Optimizations */
                        @media screen and (max-width: 768px) {
                            /* Header & Search */
                            .gffc-header-area {
                                display: flex;
                                flex-direction: column;
                                margin-bottom: 10px;
                            }
                            .gffc-toggle-section {
                                position: relative;
                                top: auto;
                                right: auto;
                                width: 100%;
                                display: flex;
                                justify-content: flex-start;
                                margin-top: 0;
                                margin-bottom: 10px;
                                order: -1; /* Show toggles above search/recent on mobile */
                            }

                            /* Add breathing room between Search controls and the toggle section */
                            .gffc-search-wrapper {
                                margin-bottom: 12px;
                            }
                            
                            .gffc-search-wrapper.initial {
                                padding-top: 0 !important;
                                display: block !important;
                                justify-content: flex-start !important;
                            }

                            /* Override higher-specificity initial styles */
                            .gffc-search-wrapper.initial .g-ffl-cockpit-product-search-container {
                                width: 100% !important;
                                justify-content: flex-start !important;
                            }
                            /* Force stacked layout for both initial and active on mobile */
                            .gffc-search-wrapper .g-ffl-cockpit-product-search-container {
                                flex-direction: column !important;
                                align-items: stretch !important;
                                width: 100% !important;
                            }
                            .gffc-search-wrapper .g-ffl-cockpit-product-search-container > div {
                                width: 100% !important;
                                flex-direction: column !important;
                                gap: 10px !important;
                                display: flex !important;
                                align-items: stretch !important;
                            }

                            /* Unified Mobile Search Input Styling */
                            .gffc-search-wrapper #cockpit-product-search-input,
                            .gffc-search-wrapper.initial #cockpit-product-search-input {
                                width: 100% !important;
                                max-width: 100% !important;
                                background-color: #f0f6fc !important; /* Light blue background to match active state */
                                border: 1px solid #d0d7de !important;
                                border-radius: 6px !important;
                                padding: 8px 54px 8px 12px !important;
                                height: 40px !important;
                                margin-bottom: 8px !important;
                                box-shadow: none !important;
                                box-sizing: border-box !important;
                            }

                            /* Search input wrapper: don't flex-grow vertically on mobile */
                            .gffc-search-wrapper .gffc-search-input-wrap {
                                width: 100% !important;
                                max-width: 100% !important;
                                min-width: 0 !important;
                                flex: 0 0 auto !important;
                            }
                            .gffc-search-wrapper .gffc-search-input-wrap #cockpit-product-search-input {
                                margin-bottom: 0 !important;
                            }
                            
                            /* Unified Mobile Search Button Styling */
                            .gffc-search-wrapper .btn-primary {
                                width: 100% !important;
                                margin-left: 0 !important;
                                margin-bottom: 12px !important;
                                background-color: #2271b1 !important;
                                border-color: #2271b1 !important;
                                color: #fff !important;
                                height: 40px !important;
                                border-radius: 6px !important;
                                box-sizing: border-box !important;
                            }

                            /* Product images: use full width on mobile */
                            #product_feed .gffc-search-thumb-cell {
                                width: 100% !important;
                                display: block;
                                padding-right: 0 !important;
                            }
                            #product_feed .gffc-search-product-thumb {
                                width: 100% !important;
                                max-width: 100% !important;
                                height: auto !important;
                                max-height: none !important;
                                display: block;
                            }
                            #product_feed #g_ffl_cockpit_dashboard_product_image {
                                width: 100% !important;
                                min-width: 0 !important;
                            }
                            #product_feed #dashboard-main-image {
                                width: 100% !important;
                                max-width: 100% !important;
                                height: auto !important;
                                max-height: none !important;
                            }

                            /* Single UPC (customUPC) dashboard: mobile-friendly layout */
                            #product_feed #g_ffl_cockpit_single_upc_dashboard {
                                max-width: 100%;
                            }

                            #product_feed #g_ffl_cockpit_single_upc_dashboard .g-ffl-cockpit-single-upc-header,
                            #product_feed #g_ffl_cockpit_single_upc_dashboard .g-ffl-cockpit-price-comparison-section,
                            #product_feed #g_ffl_cockpit_single_upc_dashboard .g-ffl-cockpit-detailed-comparison-section {
                                padding: 16px !important;
                                border-radius: 12px;
                                box-sizing: border-box;
                            }

                            #product_feed #g_ffl_cockpit_single_upc_dashboard .g-ffl-cockpit-single-upc-header > div {
                                flex-direction: column !important;
                                align-items: stretch !important;
                                gap: 14px !important;
                            }

                            #product_feed #g_ffl_cockpit_dashboard_product_name {
                                font-size: 20px !important;
                                margin-bottom: 10px !important;
                                text-align: left;
                                word-break: break-word;
                            }

                            #product_feed #g_ffl_cockpit_dashboard_product_details {
                                font-size: 14px !important;
                                line-height: 1.35 !important;
                            }

                            #product_feed #g_ffl_cockpit_dashboard_product_image {
                                width: 100% !important;
                                min-width: 0 !important;
                                justify-content: center;
                            }

                            /* Chart container: keep content inside and allow internal scroll if needed */
                            #product_feed #g_ffl_cockpit_price_comparison_chart {
                                max-width: 100%;
                                overflow-x: visible;
                                -webkit-overflow-scrolling: touch;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart {
                                padding: 12px !important;
                                box-sizing: border-box;
                                max-width: 100%;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart-legend {
                                flex-wrap: wrap;
                                gap: 10px !important;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart-row {
                                gap: 10px !important;
                                flex-wrap: wrap;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart-logo {
                                width: 36px !important;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart-total {
                                width: auto !important;
                                text-align: left !important;
                            }

                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-chart-stock {
                                width: auto !important;
                                text-align: left !important;
                            }

                            /* Mobile-only vertical chart variant */
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart {
                                display: flex;
                                gap: 12px;
                                overflow-x: auto;
                                overflow-y: hidden;
                                padding: 6px 2px 2px;
                                -webkit-overflow-scrolling: touch;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-item {
                                flex: 0 0 110px;
                                border: 2px solid #e1e5e9;
                                border-radius: 10px;
                                background: #fafbfc;
                                padding: 10px;
                                box-sizing: border-box;
                                position: relative;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-item.is-best {
                                border-color: #2ecc71;
                                background: #f8fffe;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-badge {
                                position: absolute;
                                top: -10px;
                                left: 10px;
                                background: #2ecc71;
                                color: #fff;
                                padding: 2px 8px;
                                font-size: 10px;
                                font-weight: 600;
                                border-radius: 12px;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-top {
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                gap: 8px;
                                margin-bottom: 8px;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-logo {
                                width: 44px;
                                height: 28px;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                flex: 0 0 auto;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-logo img {
                                max-width: 44px;
                                max-height: 28px;
                                object-fit: contain;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-stock {
                                display: flex;
                                align-items: center;
                                justify-content: flex-end;
                                gap: 6px;
                                font-size: 11px;
                                font-weight: 600;
                                color: #666;
                                white-space: nowrap;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-stock-dot {
                                width: 8px;
                                height: 8px;
                                border-radius: 50%;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-plot {
                                height: 150px;
                                display: flex;
                                align-items: flex-end;
                                justify-content: center;
                                padding: 8px 0 6px;
                                box-sizing: border-box;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-bar {
                                width: 46px;
                                border: 1px solid #ddd;
                                border-radius: 6px;
                                overflow: hidden;
                                background: #f5f6f7;
                                display: flex;
                                flex-direction: column;
                                justify-content: flex-end;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-seg.unit {
                                background: #4a90e2;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-seg.shipping {
                                background: #ff6b6b;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-total {
                                text-align: center;
                                font-size: 14px;
                                font-weight: 700;
                                color: #333;
                                margin-top: 6px;
                            }
                            #product_feed #g_ffl_cockpit_price_comparison_chart .gffc-upc-vchart-total.is-best {
                                color: #2ecc71;
                            }

                            /* Distributor cards: single column on mobile */
                            #product_feed #g_ffl_cockpit_distributor_cards_container {
                                grid-template-columns: 1fr !important;
                            }

                            /* Detailed comparison table: desktop look + horizontal scroll */
                            #product_feed #g_ffl_cockpit_comparison_table_container {
                                max-width: 100%;
                                overflow-x: auto;
                                -webkit-overflow-scrolling: touch;
                            }
                            #product_feed #g_ffl_cockpit_comparison_table_container table {
                                width: max-content;
                                min-width: 640px;
                            }

                            /* Back button: full width */
                            #product_feed #g_ffl_cockpit_back_to_search {
                                width: 100%;
                                max-width: 100%;
                                box-sizing: border-box;
                            }

                            /* Grid.js Mobile Card View - Structured List Layout */
                            .gridjs-head,
                            .gridjs-thead,
                            .gridjs-table thead,
                            th.gridjs-th { 
                                display: none !important; 
                                height: 0 !important;
                                width: 0 !important;
                                padding: 0 !important;
                                margin: 0 !important;
                                border: none !important;
                                overflow: hidden !important;
                            }
                            .gridjs-wrapper { box-shadow: none !important; border: none !important; }
                            .gridjs-table { display: block; }
                            .gridjs-tbody { display: block; }
                            
                            .gridjs-tr {
                                display: flex;
                                flex-direction: column;
                                background: #fff;
                                border: 1px solid #e2e8f0;
                                border-radius: 12px;
                                margin-bottom: 16px;
                                padding: 16px;
                                box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
                            }

                            /* Logs tab: keep desktop table styling on mobile, with internal horizontal scroll */
                            #logs .gridjs-head {
                                display: block !important;
                                height: auto !important;
                                width: auto !important;
                                padding: 0 !important;
                                margin: 0 !important;
                                border: none !important;
                                overflow: visible !important;
                            }
                            #logs .gridjs-table thead {
                                display: table-header-group !important;
                                height: auto !important;
                                width: auto !important;
                                padding: 0 !important;
                                margin: 0 !important;
                                border: none !important;
                                overflow: visible !important;
                            }
                            #logs th.gridjs-th {
                                display: table-cell !important;
                                height: auto !important;
                                width: auto !important;
                                overflow: visible !important;
                            }

                            #logs .gridjs-wrapper {
                                display: block !important;
                                width: 100% !important;
                                max-width: 100% !important;
                                min-width: 0 !important;
                                overflow-x: auto !important;
                                -webkit-overflow-scrolling: touch;
                            }
                            #logs #log_table,
                            #logs #log_table .gridjs-container {
                                display: block !important;
                                width: 100% !important;
                                max-width: 100% !important;
                                min-width: 0 !important;
                            }
                            #logs .gridjs-table {
                                display: table !important;
                                width: 100% !important;
                                min-width: 100% !important;
                            }
                            #logs .gridjs-tbody { display: table-row-group !important; }
                            #logs .gridjs-tr {
                                display: table-row !important;
                                background: transparent !important;
                                border: none !important;
                                border-radius: 0 !important;
                                margin: 0 !important;
                                padding: 0 !important;
                                box-shadow: none !important;
                            }
                            #logs td.gridjs-td,
                            #logs th.gridjs-th {
                                white-space: nowrap;
                            }

                            /* PRODUCT SEARCH TAB STYLES */
                            /* 1. Distributor Logo (Top) */
                            #product_feed .gridjs-td:nth-child(1) {
                                order: 1;
                                padding: 0 0 12px 0 !important;
                                border: none !important;
                                border-bottom: 1px solid #f1f5f9 !important;
                                margin-bottom: 12px;
                                display: flex !important;
                                justify-content: center;
                                align-items: center;
                            }
                            #product_feed .gridjs-td:nth-child(1) img { max-height: 32px; max-width: 140px; }

                            /* 2. Product Summary (Title Top, Image Bottom) */
                            #product_feed .gridjs-td:nth-child(2) {
                                order: 2;
                                padding: 0 0 16px 0 !important;
                                border: none !important;
                                border-bottom: 1px solid #f1f5f9 !important;
                                margin-bottom: 12px;
                            }
                            /* Reorder Title and Image */
                            #product_feed .gridjs-td:nth-child(2) table tr {
                                display: flex !important;
                                flex-direction: column-reverse !important;
                                align-items: center !important;
                            }
                            #product_feed .gridjs-td:nth-child(2) td {
                                display: block !important;
                                width: 100% !important;
                                text-align: center !important;
                                padding: 0 !important;
                            }
                            /* Image */
                            #product_feed .gridjs-td:nth-child(2) img.responsive-image {
                                width: 100% !important;
                                height: auto !important;
                                object-fit: contain;
                                border-radius: 8px;
                                border: 1px solid #e2e8f0;
                                background: #fff;
                                margin: 12px auto 0 auto !important;
                            }
                            /* Title & Link */
                            #product_feed .gridjs-td:nth-child(2) > div {
                                display: block;
                            }
                            #product_feed .gridjs-td:nth-child(2) { font-size: 15px; line-height: 1.4; color: #334155; }
                            #product_feed .gridjs-td:nth-child(2) b { color: #0f172a; font-weight: 600; display: block; font-size: 16px; margin-bottom: 4px; }
                            #product_feed .gridjs-td:nth-child(2) a { 
                                display: inline-block !important; 
                                font-size: 13px; 
                                color: #3b82f6; 
                                text-decoration: none;
                            }

                            /* 3. Specs */
                            #product_feed .gridjs-td:nth-child(3) { 
                                order: 3; 
                                margin-bottom: 12px; 
                                padding: 0 !important;
                                border: none !important;
                            }

                            /* 4. Pricing */
                            #product_feed .gridjs-td:nth-child(4) { 
                                order: 4; 
                                margin-bottom: 16px; 
                                padding: 0 !important;
                                border: none !important;
                            }

                            #product_feed .gridjs-td:nth-child(3) table,
                            #product_feed .gridjs-td:nth-child(4) table { width: 100%; border-collapse: collapse; }
                            
                            #product_feed .gridjs-td:nth-child(3) tbody,
                            #product_feed .gridjs-td:nth-child(4) tbody { display: block; }

                            #product_feed .gridjs-td:nth-child(3) tr,
                            #product_feed .gridjs-td:nth-child(4) tr {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                padding: 6px 0;
                                border-bottom: 1px dashed #f1f5f9;
                            }
                            #product_feed .gridjs-td:nth-child(3) tr:last-child,
                            #product_feed .gridjs-td:nth-child(4) tr:last-child { border-bottom: none; }

                            #product_feed .gridjs-td:nth-child(3) td:first-child,
                            #product_feed .gridjs-td:nth-child(4) td:first-child {
                                color: #64748b;
                                font-size: 12px;
                                font-weight: 600;
                                text-transform: uppercase;
                                letter-spacing: 0.5px;
                                text-align: left;
                                padding-right: 10px;
                                white-space: nowrap;
                            }
                            #product_feed .gridjs-td:nth-child(3) td:last-child,
                            #product_feed .gridjs-td:nth-child(4) td:last-child {
                                text-align: right;
                                font-weight: 500;
                                color: #334155;
                                font-size: 13px;
                                word-break: break-word;
                            }

                            /* Total Cost Styling */
                            #product_feed .gridjs-td:nth-child(4) tr:nth-child(3) {
                                background: #f0fdf4;
                                margin-top: 8px;
                                padding: 12px;
                                border-radius: 8px;
                                border-bottom: none;
                                border: 1px solid #bbf7d0;
                            }
                            #product_feed .gridjs-td:nth-child(4) tr:nth-child(3) td:first-child {
                                color: #166534;
                                font-weight: 700;
                            }
                            #product_feed .gridjs-td:nth-child(4) tr:nth-child(3) td:last-child {
                                font-size: 18px;
                                font-weight: 800;
                                color: #16a34a;
                            }

                            /* 5. Availability (Qty + Button) - Bottom of Card */
                            #product_feed .gridjs-td:nth-child(5) {
                                order: 5;
                                padding: 16px 0 0 0 !important;
                                border: none !important;
                                border-top: 1px solid #e2e8f0 !important;
                                margin-top: 8px;
                            }
                            #product_feed .gridjs-td:nth-child(5) table { width: 100%; }
                            #product_feed .gridjs-td:nth-child(5) tbody { display: block; }
                            
                            /* Qty Row */
                            #product_feed .gridjs-td:nth-child(5) tr:first-child {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                margin-bottom: 12px;
                            }
                            #product_feed .gridjs-td:nth-child(5) tr:first-child td:first-child {
                                font-size: 14px;
                                font-weight: 600;
                                color: #64748b;
                                text-transform: uppercase;
                            }
                            #product_feed .gridjs-td:nth-child(5) tr:first-child td:last-child {
                                font-size: 16px;
                                font-weight: 700;
                                color: #0f172a;
                            }

                            /* Qty Row (mobile): show centered "Quantity Available: X" */
                            #product_feed .gridjs-td:nth-child(5) tr.gffc-qty-row {
                                display: block;
                                text-align: center;
                                justify-content: center;
                            }
                            #product_feed .gridjs-td:nth-child(5) tr.gffc-qty-row td {
                                display: block;
                                width: 100%;
                                text-align: center;
                            }
                            #product_feed .gridjs-td:nth-child(5) .gffc-qty-desktop { display: none !important; }
                            #product_feed .gridjs-td:nth-child(5) .gffc-qty-mobile {
                                display: block !important;
                                font-size: 14px;
                                font-weight: 700;
                                color: #64748b;
                                text-transform: none;
                                letter-spacing: 0;
                            }
                            #product_feed .gridjs-td:nth-child(5) .gffc-qty-mobile strong {
                                font-size: 18px;
                                font-weight: 800;
                                color: #0f172a;
                                margin-left: 6px;
                            }

                            /* Button Row */
                            #product_feed .gridjs-td:nth-child(5) tr:last-child {
                                display: block;
                                width: 100%;
                            }
                            #product_feed .gridjs-td:nth-child(5) tr:last-child td {
                                display: block;
                                width: 100%;
                                padding: 0 !important;
                            }
                            #product_feed .gridjs-wrapper .gffc-btn-add {
                                width: 100%;
                                justify-content: center;
                                padding: 12px;
                                font-size: 16px;
                                border-radius: 8px;
                                background-color: #2271b1;
                                color: white;
                            }
                            #product_feed .gridjs-wrapper .gffc-btn-add:hover {
                                background-color: #135e96;
                            }

                            /* UPC dashboard: keep Distributor Site button on one line */
                            #product_feed .gffc-view-dist-site-full { display: none; }
                            #product_feed .gffc-view-dist-site-short { display: inline; }
                            #product_feed .gffc-view-dist-site-btn { white-space: nowrap; }

                            /* FULFILLMENT TAB STYLES */
                            #fulfillment .gridjs-tr {
                                position: relative;
                                padding: 16px;
                                display: flex;
                                flex-direction: column;
                                margin-bottom: 16px; /* Add spacing between cards */
                                width: 100%; /* Ensure full width */
                                box-sizing: border-box;
                            }
                            
                            /* 1. Source (Top Left) */
                            #fulfillment .gridjs-td:nth-child(1) {
                                order: 1;
                                font-size: 11px;
                                text-transform: uppercase;
                                color: #94a3b8;
                                font-weight: 700;
                                letter-spacing: 0.5px;
                                padding: 0 !important;
                                border: none !important;
                                margin-bottom: 4px;
                            }

                            /* 5. Status (Top Right Badge) */
                            #fulfillment .gridjs-td:nth-child(5) {
                                position: absolute;
                                top: 16px;
                                right: 16px;
                                order: 0;
                                padding: 4px 10px !important;
                                background: #f1f5f9;
                                border-radius: 20px;
                                font-size: 12px;
                                font-weight: 700;
                                color: #475569;
                                border: none !important;
                                text-transform: uppercase;
                                letter-spacing: 0.5px;
                                z-index: 10;
                            }

                            /* 2. Order ID (Large Title) */
                            #fulfillment .gridjs-td:nth-child(2) {
                                order: 2;
                                font-size: 20px;
                                font-weight: 700;
                                color: #0f172a;
                                padding: 0 !important;
                                border: none !important;
                                margin-bottom: 8px;
                                width: 100%;
                                padding-right: 120px !important; /* Prevent overlap with right-side elements */
                            }
                            #fulfillment .gridjs-td:nth-child(2):before {
                                content: "#";
                                color: #94a3b8;
                                margin-right: 2px;
                            }
                            #fulfillment .gridjs-td:nth-child(2) a { 
                                color: #0f172a; 
                                text-decoration: none; 
                                pointer-events: auto; /* Ensure clickable */
                                position: relative;
                                z-index: 2;
                            }

                            /* 8 & 9. Dates (Ordered / Shipped) - Below Order ID */
                            #fulfillment .gridjs-td:nth-child(8),
                            #fulfillment .gridjs-td:nth-child(9) {
                                order: 3;
                                display: block;
                                width: auto;
                                font-size: 13px;
                                color: #64748b;
                                padding: 0 !important;
                                border: none !important;
                                margin-bottom: 2px;
                                margin-right: 16px;
                            }
                            #fulfillment .gridjs-td:nth-child(8):before { content: "Ordered: "; font-weight: 600; color: #475569; }
                            #fulfillment .gridjs-td:nth-child(9):not(:empty):before { content: "Shipped: "; font-weight: 600; color: #475569; }
                            
                            /* Store Icon in Ordered Date */
                            #fulfillment .gffc-store-icon {
                                margin-right: 6px;
                                vertical-align: middle;
                                margin-bottom: 2px;
                            }

                            /* CUSTOMER SECTION */
                            /* 6. Customer Name */
                            #fulfillment .gridjs-td:nth-child(6) {
                                order: 4;
                                margin-top: 8px;
                                padding: 12px 12px 4px 12px !important;
                                background: #f8fafc;
                                border: 1px solid #e2e8f0 !important;
                                border-bottom: none !important;
                                border-radius: 8px 8px 0 0;
                                font-size: 15px;
                                font-weight: 600;
                                color: #334155;
                            }
                            #fulfillment .gridjs-td:nth-child(6):before {
                                content: "Customer";
                                display: block;
                                font-size: 11px;
                                text-transform: uppercase;
                                color: #94a3b8;
                                font-weight: 700;
                                margin-bottom: 4px;
                            }

                            /* 7. Contact (Phone + Email) */
                            #fulfillment .gridjs-td:nth-child(7) {
                                order: 5;
                                padding: 0 12px 12px 12px !important;
                                background: #f8fafc;
                                border: 1px solid #e2e8f0 !important;
                                border-right: 1px solid #e2e8f0 !important;
                                border-bottom: 1px solid #e2e8f0 !important;
                                border-top: none !important;
                                border-radius: 0 0 8px 8px;
                                font-size: 14px;
                                color: #475569;
                                margin-bottom: 16px;
                            }
                            /* Phone icon handled in HTML now */
                            #fulfillment .gridjs-td:nth-child(7):not(:empty):before {
                                content: none;
                            }
                            /* Show mobile icon on mobile */
                            #fulfillment .gffc-mobile-icon {
                                display: inline-block !important;
                                margin-right: 8px;
                                color: #94a3b8;
                                width: 16px;
                            }

                            /* DISTRIBUTOR / FULFILLMENT SECTION */
                            /* 3. Dist Logo - Moved to Top Right */
                            #fulfillment .gridjs-td:nth-child(3) {
                                position: absolute;
                                top: 50px;
                                right: 16px;
                                width: 120px;
                                padding: 0 !important;
                                border: none !important;
                                display: flex;
                                justify-content: center;
                                overflow: hidden;
                                z-index: 5;
                            }
                            #fulfillment .gridjs-td:nth-child(3) img {
                                max-height: 35px;
                                width: 100%;
                                max-width: 100%;
                                height: auto;
                                object-fit: contain;
                                display: block;
                                mix-blend-mode: multiply;
                            }

                            /* 4. Dist Order ID - Moved to Top Right below Logo */
                            #fulfillment .gridjs-td:nth-child(4) {
                                position: absolute;
                                top: 88px;
                                right: 16px;
                                width: auto;
                                max-width: calc(100% - 32px);
                                padding: 0 !important;
                                border: none !important;
                                font-size: 13px;
                                color: #64748b;
                                white-space: nowrap;
                                text-align: right;
                                z-index: 5;
                            }
                            #fulfillment .gridjs-td:nth-child(4):before {
                                content: none; /* Remove label */
                            }

                            /* Fulfillment: Gunbroker Orders footer (mobile) */
                            @media screen and (max-width: 768px) {
                                /* Stack footer controls (Download + Gunbroker section) */
                                #fulfillment #order_fulfillment_table + div {
                                    flex-direction: column;
                                    gap: 12px;
                                    align-items: stretch !important;
                                }

                                #fulfillment #download_fulfillment_history_button {
                                    width: 100%;
                                    box-sizing: border-box;
                                }

                                #fulfillment #gunbroker_processor_section {
                                    width: 100%;
                                }

                                #fulfillment #gunbroker_processor_section table,
                                #fulfillment #gunbroker_processor_section tbody,
                                #fulfillment #gunbroker_processor_section tr,
                                #fulfillment #gunbroker_processor_section td {
                                    display: block;
                                    width: 100% !important;
                                    box-sizing: border-box;
                                }

                                #fulfillment #gunbroker_processor_section td[align="right"] {
                                    text-align: left !important;
                                }

                                #fulfillment #gunbroker_processor_section select {
                                    display: block;
                                    width: 100% !important;
                                    max-width: 100% !important;
                                    box-sizing: border-box;
                                    margin-top: 6px;
                                }

                                #fulfillment #gunbroker_processor_section button {
                                    display: block;
                                    width: 100% !important;
                                    box-sizing: border-box;
                                    margin-top: 10px;
                                }
                            }

                            /* 10. Ship Status (Tracking) */
                            #fulfillment .gridjs-td:nth-child(10) {
                                order: 9;
                                margin-top: 8px;
                                padding: 0 !important;
                                border: none !important;
                                background: transparent;
                                width: 100%;
                                box-sizing: border-box;
                            }
                            
                            #fulfillment .gffc-ship-status-container {
                                display: flex;
                                gap: 12px;
                                width: 100%;
                            }

                            /* Tracking Button (Left, Flex Grow) */
                            #fulfillment .gffc-tracking-link, 
                            #fulfillment .gffc-tracking-text {
                                flex: 1;
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                padding: 12px;
                                background: #f0f9ff;
                                border: 1px solid #bae6fd;
                                border-radius: 8px;
                                color: #0284c7;
                                font-weight: 700;
                                text-decoration: none;
                                font-size: 14px;
                                min-height: 44px;
                                box-sizing: border-box;
                            }
                            #fulfillment .gffc-tracking-link.status-delivered, 
                            #fulfillment .gffc-tracking-text.status-delivered {
                                background: #f0fdf4;
                                border-color: #bbf7d0;
                                color: #16a34a;
                            }
                            #fulfillment .gffc-tracking-link.status-return, 
                            #fulfillment .gffc-tracking-text.status-return {
                                background: #fef2f2;
                                border-color: #fecaca;
                                color: #dc2626;
                            }
                            #fulfillment .gffc-tracking-link.status-waiting, 
                            #fulfillment .gffc-tracking-text.status-waiting {
                                background: #f8fafc;
                                border-color: #e2e8f0;
                                color: #64748b;
                            }

                            /* Hide Button (Right) */
                            #fulfillment .gffc-hide-order-btn {
                                display: flex;
                                align-items: center;
                                justify-content: center;
                                padding: 12px 16px;
                                background: #f1f5f9;
                                border: 1px solid #e2e8f0;
                                border-radius: 8px;
                                color: #64748b;
                                font-weight: 600;
                                text-decoration: none;
                                font-size: 14px;
                                cursor: pointer;
                                min-height: 44px;
                                box-sizing: border-box;
                            }
                            #fulfillment .gffc-hide-order-btn:hover {
                                background: #e2e8f0;
                                color: #475569;
                            }
                            
                            #fulfillment .gffc-hide-label {
                                display: inline !important; /* Show label on mobile */
                                margin-left: 6px;
                            }
                            
                            #fulfillment .gridjs-td:nth-child(11) i {
                                font-size: 16px;
                            }
                            
                            /* Footer Stacking */
                            .gffc-footer {
                                flex-direction: column;
                            }
                            .gffc-footer-right {
                                align-items: center;
                                text-align: center;
                            }
                            #gffc-product-search-disclaimer {
                                text-align: center !important;
                            }
                            #download_inventory_button {
                                width: 100%;
                            }

                            /* Product Search: full-width controls on mobile */
                            #product_feed #gffc-search-wrapper .g-ffl-cockpit-product-search-container > div {
                                width: 100% !important;
                                flex-direction: column;
                                align-items: stretch !important;
                            }
                            #product_feed #cockpit-product-search-input {
                                width: 100% !important;
                            }
                            #product_feed #gffc-search-wrapper button.btn.btn-primary {
                                width: 100% !important;
                                margin-left: 0 !important;
                                margin-top: 10px;
                            }
                            #product_feed #gffc-search-wrapper .gffc-search-input-wrap {
                                width: 100% !important;
                            }
                        }

                        /* Product Search: scan icon inside input */
                        #product_feed #gffc-search-wrapper .gffc-search-row {
                            display: flex;
                            align-items: center;
                            flex-grow: 0;
                            justify-content: flex-start;
                            flex-wrap: wrap;
                            gap: 10px;
                            width: auto;
                            max-width: 100%;
                        }
                        #product_feed #gffc-search-wrapper.initial .gffc-search-row {
                            justify-content: center;
                        }
                        #product_feed #gffc-search-wrapper .gffc-search-input-wrap {
                            position: relative;
                            width: 750px;
                            max-width: 100%;
                            flex: 1 1 520px;
                            min-width: 320px;
                        }
                        #product_feed #gffc-search-wrapper #cockpit-product-search-input {
                            width: 100%;
                            padding-right: 54px;
                        }
                        #product_feed #gffc-search-wrapper .gffc-scan-icon-btn {
                            position: absolute;
                            top: 50%;
                            right: 10px;
                            transform: translateY(-50%);
                            width: 35px;
                            height: 35px;
                            border-radius: 6px;
                            border: 1px solid rgba(0,0,0,0.15);
                            background: #ffffff;
                            color: rgba(0,0,0,0.6);
                            display: inline-flex;
                            align-items: center;
                            justify-content: center;
                            padding: 0;
                            line-height: 1;
                            cursor: pointer;
                        }
                        #product_feed #gffc-search-wrapper .gffc-scan-icon-btn svg {
                            width: 32px;
                            height: 32px;
                            display: block;
                        }
                        #product_feed #gffc-search-wrapper .gffc-scan-icon-btn:hover {
                            background: rgba(0,0,0,0.04);
                        }

                        /* Product Search: UPC scanner modal (native camera) */
                        #gffc-upc-scanner-modal {
                            position: fixed;
                            inset: 0;
                            display: none;
                            align-items: center;
                            justify-content: center;
                            padding: 16px;
                            background: rgba(0,0,0,0.75);
                            z-index: 100000;
                            box-sizing: border-box;
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-card {
                            width: min(720px, 100%);
                            background: #fff;
                            border-radius: 12px;
                            overflow: hidden;
                            border: 1px solid #e5e7eb;
                            box-shadow: 0 20px 60px rgba(0,0,0,0.35);
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-header {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            gap: 12px;
                            padding: 12px 14px;
                            background: #f8fafc;
                            border-bottom: 1px solid #e5e7eb;
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-title {
                            margin: 0;
                            font-weight: 800;
                            font-size: 14px;
                            color: #111827;
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-body {
                            padding: 12px 14px 14px;
                        }
                        #gffc-upc-scanner-video {
                            width: 100%;
                            height: auto;
                            background: #0b1220;
                            border-radius: 10px;
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-help {
                            margin-top: 10px;
                            font-size: 12px;
                            color: #475569;
                            line-height: 1.35;
                        }
                        #gffc-upc-scanner-modal .gffc-scanner-error {
                            display: none;
                            margin-top: 10px;
                            font-size: 12px;
                            color: #991b1b;
                            background: #fee2e2;
                            border: 1px solid #fecaca;
                            padding: 10px 12px;
                            border-radius: 10px;
                        }
                    </style>

                    <div class="gffc-header-area">
                        <!-- Top Right Controls -->
                        <div class="gffc-toggle-section">
                            <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
                                <div style="display: flex; align-items: center;">
                                    <label for="ignore-product-restrictions-toggle" style="margin-right: 10px;">Ignore Restrictions:</label>
                                    <label class="g-ffl-cockpit-toggle-switch">
                                        <input type="checkbox" id="ignore-product-restrictions-toggle">
                                        <span class="g-ffl-cockpit-slider"></span>
                                    </label>
                                </div>
                                <div style="display: flex; align-items: center;">
                                    <label for="gffc-in-stock-toggle" style="margin-right: 10px;">In Stock:</label>
                                    <label class="g-ffl-cockpit-toggle-switch">
                                        <input type="checkbox" id="gffc-in-stock-toggle">
                                        <span class="g-ffl-cockpit-slider"></span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div id="gffc-search-wrapper" class="gffc-search-wrapper initial">
                            <div class="g-ffl-cockpit-product-search-container" style="width: 100%; display: flex; align-items: center; justify-content: center; flex-wrap: wrap; gap: 10px;">
                                <!-- Search Section -->
                                <div class="gffc-search-row">
                                    <div class="gffc-search-input-wrap">
                                        <input 
                                            class="form-control" 
                                            type="text" 
                                            id="cockpit-product-search-input" 
                                            placeholder="Enter Search Terms, separated by commas (ex: Glock, Semi Auto Handguns, MOS)" 
                                            onkeypress="if (event.key === 'Enter') loadGrid()"
                                        />
                                        <button class="gffc-scan-icon-btn" type="button" onclick="gffcOpenProductSearchScanner()" aria-label="Scan barcode" title="Scan barcode">
                                            <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                                                <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                    <!-- Corner brackets -->
                                                    <path d="M5 9V6a1 1 0 0 1 1-1h3" />
                                                    <path d="M16 5h3a1 1 0 0 1 1 1v3" />
                                                    <path d="M20 15v3a1 1 0 0 1-1 1h-3" />
                                                    <path d="M8 19H6a1 1 0 0 1-1-1v-3" />
                                                    <!-- Barcode lines -->
                                                    <path d="M8 10v4" />
                                                    <path d="M10.5 10v4" />
                                                    <path d="M13.5 10v4" />
                                                    <path d="M16 10v4" />
                                                    <path d="M7 16h10" />
                                                </g>
                                            </svg>
                                        </button>
                                    </div>
                                    <button id="gffc-product-search-button" style="margin-left: 5px;" class="btn btn-primary" onclick="loadGrid()">Search</button>
                                </div>

                                <!-- Recent searches (pills) + Wishlist button -->
                                <div class="gffc-recent-row" style="width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap;">
                                    <div id="gffc-recent-searches" style="flex: 1; min-width: 0; max-width: 750px; display: none;"></div>
                                    <button type="button" id="gffc-wishlist-btn" onclick="gffcOpenWishlistViewer()" style="padding: 3px 10px; font-size: 12px; background:#fff; color:#ff6b35; border:1px solid #fed7aa; border-radius:5px; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:4px; white-space: nowrap; flex-shrink: 0;" title="View your wishlist">
                                        <i class="fas fa-bell" style="font-size:11px;"></i> Wishlist
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div id="gffc-product-search-blocker" style="display:none; position:absolute; inset:0; z-index:40; background: rgba(107, 114, 128, 0.62); backdrop-filter: blur(2px); align-items:center; justify-content:center; padding:20px;">
                        <div style="width:100%; max-width:640px; background:#fff; border:1px solid #fca5a5; border-radius:14px; box-shadow:0 20px 55px rgba(15,23,42,0.24); overflow:hidden;">
                            <div style="padding:14px 16px; border-bottom:1px solid #fecaca; background:linear-gradient(180deg,#fff1f2,#ffffff);">
                                <div style="font-size:18px; font-weight:700; color:#991b1b;">Product Search Unavailable</div>
                            </div>
                            <div id="gffc-product-search-blocker-message" style="padding:14px 16px; font-size:14px; line-height:1.55; color:#7f1d1d;">
                                No validated distributors are currently available. Enter distributor credentials, save your changes, and run Validate Configuration to enable Product Search.
                            </div>
                            <div style="padding:12px 16px; border-top:1px solid #fecaca; display:flex; justify-content:flex-end;">
                                <button type="button" class="button button-primary" style="background:#b91c1c; border-color:#b91c1c;" onclick="gffcOpenConfigurationTab()">Go to Configuration</button>
                            </div>
                        </div>
                    </div>

                    <!-- Product Search: native UPC scanner modal -->
                    <div id="gffc-upc-scanner-modal" role="dialog" aria-modal="true" aria-label="Scan barcode">
                        <div class="gffc-scanner-card">
                            <div class="gffc-scanner-header">
                                <h3 class="gffc-scanner-title">Scan Barcode / QR</h3>
                                <button type="button" class="button" onclick="gffcCloseProductSearchScanner()">Close</button>
                            </div>
                            <div class="gffc-scanner-body">
                                <video id="gffc-upc-scanner-video" playsinline></video>
                                <div class="gffc-scanner-help">Point your camera at the barcode. When detected, the UPC will be placed into the search field automatically.</div>
                                <div id="gffc-upc-scanner-error" class="gffc-scanner-error"></div>
                            </div>
                        </div>
                    </div>

                    <div id="product_feed_table_container" style="flex-grow: 1; display: flex; flex-direction: column;">
                        <div id="g_ffl_cockpit_single_upc_dashboard" style="display: none;">
                            <!-- Single UPC Dashboard -->
                            <div class="g-ffl-cockpit-single-upc-header" style="background: white; color: #333; padding: 30px; border-radius: 15px; margin-bottom: 25px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #e9ecef;">
                                <div style="display: flex; align-items: center; justify-content: space-between; gap: 30px;">
                                    <div style="flex: 1;">
                                        <h1 id="g_ffl_cockpit_dashboard_product_name" style="margin: 0 0 15px 0; font-size: 28px; font-weight: 600; line-height: 1.2; color: #333;"></h1>
                                        <div id="g_ffl_cockpit_dashboard_product_details" style="font-size: 16px; opacity: 0.8; line-height: 1.4; color: #666;">
                                            <!-- Product details will be inserted here -->
                                        </div>
                                    </div>
                                    <div id="g_ffl_cockpit_dashboard_product_image" style="background: white; padding: 15px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); min-width: 200px; display: flex; align-items: center; justify-content: center;">
                                        <!-- Product image will be inserted here -->
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Price Comparison Chart -->
                            <div class="g-ffl-cockpit-price-comparison-section" style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); margin-bottom: 25px;">
                                <div style="display:flex; align-items:center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 20px;">
                                    <h3 style="margin: 0; color: #333; font-size: 20px;">Price Comparison Across Distributors</h3>
                                    <div style="display: flex; align-items: center;">
                                        <label for="gffc_upc_ignore_shipping_toggle" style="margin-right: 10px; font-size: 13px; font-weight: 600; color: #333; user-select:none;">Ignore Shipping:</label>
                                        <label class="g-ffl-cockpit-toggle-switch">
                                            <input type="checkbox" id="gffc_upc_ignore_shipping_toggle">
                                            <span class="g-ffl-cockpit-slider"></span>
                                        </label>
                                    </div>
                                </div>
                                <div id="g_ffl_cockpit_price_comparison_chart" style="position: relative;">
                                    <!-- Chart will be rendered here -->
                                </div>
                            </div>
                            
                            <!-- Distributor Cards -->
                            <div id="g_ffl_cockpit_distributor_cards_container" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 20px;">
                                <!-- Distributor cards will be dynamically generated here -->
                            </div>
                            
                            <!-- Detailed Comparison Table -->
                            <div class="g-ffl-cockpit-detailed-comparison-section" style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.1);">
                                <h3 style="margin-top: 0; color: #333; font-size: 20px; margin-bottom: 20px;">Detailed Comparison</h3>
                                <div id="g_ffl_cockpit_comparison_table_container">
                                    <!-- Comparison table will be rendered here -->
                                </div>
                            </div>
                            
                            <!-- Product History Section -->
                            <div class="g-ffl-cockpit-history-section" style="background: white; padding: 25px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); margin-top: 25px;">
                                <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; margin-bottom: 10px;">
                                    <h3 style="margin: 0; color: #333; font-size: 20px;">Inventory and Pricing History</h3>
                                    <div id="g_ffl_cockpit_history_controls" style="display: none; align-items: center; gap: 10px; flex-wrap: wrap;">
                                        <div class="g-ffl-cockpit-history-view-toggle" style="display: flex; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
                                            <button type="button" id="g_ffl_cockpit_history_chart_btn" class="g-ffl-cockpit-view-btn active" onclick="switchHistoryView('chart')" style="padding: 8px 16px; border: none; background: #0073aa; color: white; cursor: pointer; font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 6px;">
                                                <i class="fas fa-chart-line"></i> Chart
                                            </button>
                                            <button type="button" id="g_ffl_cockpit_history_table_btn" class="g-ffl-cockpit-view-btn" onclick="switchHistoryView('table')" style="padding: 8px 16px; border: none; background: #f5f5f5; color: #666; cursor: pointer; font-size: 13px; font-weight: 600; display: flex; align-items: center; gap: 6px;">
                                                <i class="fas fa-table"></i> Table
                                            </button>
                                        </div>
                                        <div id="g_ffl_cockpit_history_chart_data_toggle" class="g-ffl-cockpit-history-view-toggle" style="display: flex; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
                                            <button type="button" id="g_ffl_cockpit_history_show_both_btn" class="g-ffl-cockpit-chart-data-btn active" onclick="switchHistoryChartData('both')" style="padding: 8px 12px; border: none; background: #0073aa; color: white; cursor: pointer; font-size: 12px; font-weight: 600;">
                                                Both
                                            </button>
                                            <button type="button" id="g_ffl_cockpit_history_show_price_btn" class="g-ffl-cockpit-chart-data-btn" onclick="switchHistoryChartData('price')" style="padding: 8px 12px; border: none; background: #f5f5f5; color: #666; cursor: pointer; font-size: 12px; font-weight: 600;">
                                                <i class="fas fa-dollar-sign"></i> Price
                                            </button>
                                            <button type="button" id="g_ffl_cockpit_history_show_qty_btn" class="g-ffl-cockpit-chart-data-btn" onclick="switchHistoryChartData('qty')" style="padding: 8px 12px; border: none; background: #f5f5f5; color: #666; cursor: pointer; font-size: 12px; font-weight: 600;">
                                                <i class="fas fa-boxes"></i> Qty
                                            </button>
                                        </div>
                                        <div id="g_ffl_cockpit_chart_zoom_controls" style="display: flex; align-items: center; gap: 4px; border-radius: 8px; overflow: hidden; border: 1px solid #e0e0e0;">
                                            <button type="button" onclick="zoomChart('out')" id="g_ffl_cockpit_zoom_out_btn" title="Zoom Out" style="padding: 8px 10px; border: none; border-right: 1px solid #e0e0e0; background: #f5f5f5; cursor: pointer; font-size: 12px;" disabled>
                                                <i class="fas fa-search-minus"></i>
                                            </button>
                                            <span id="g_ffl_cockpit_zoom_label" style="font-size: 11px; color: #666; padding: 0 8px; min-width: 70px; text-align: center;">All</span>
                                            <button type="button" onclick="zoomChart('in')" id="g_ffl_cockpit_zoom_in_btn" title="Zoom In" style="padding: 8px 10px; border: none; border-left: 1px solid #e0e0e0; border-right: 1px solid #e0e0e0; background: #f5f5f5; cursor: pointer; font-size: 12px;">
                                                <i class="fas fa-search-plus"></i>
                                            </button>
                                            <button type="button" onclick="zoomChart('reset')" id="g_ffl_cockpit_zoom_reset_btn" title="Reset Zoom" style="padding: 8px 10px; border: none; background: #f5f5f5; cursor: pointer; font-size: 12px;" disabled>
                                                <i class="fas fa-undo"></i>
                                            </button>
                                        </div>
                                        <select id="g_ffl_cockpit_history_distributor_filter" onchange="filterHistoryByDistributor()" style="display: none; padding: 8px 12px; border-radius: 8px; border: 1px solid #e0e0e0; font-size: 13px; min-width: 150px;">
                                            <option value="all">All Distributors</option>
                                        </select>
                                    </div>
                                </div>
                                <!-- Scroll trigger placeholder (will auto-load when visible) -->
                                <div id="g_ffl_cockpit_history_load_prompt" style="text-align: center; padding: 30px;">
                                    <div style="display: inline-block; width: 30px; height: 30px; border: 3px solid #f3f3f3; border-top: 3px solid #ccc; border-radius: 50%; animation: g-ffl-cockpit-spin 1s linear infinite;"></div>
                                    <p style="color: #888; margin-top: 10px; font-size: 13px;">Scroll to load history...</p>
                                </div>
                                <div id="g_ffl_cockpit_history_disclaimer" style="display: none; color: #888; font-size: 12px; font-style: italic; margin-bottom: 15px;">
                                    <i class="fas fa-info-circle" style="margin-right: 4px;"></i>
                                    Prices shown are distributor base prices and do not reflect your custom pricing. All times shown in local timezone.
                                </div>
                                <div id="g_ffl_cockpit_history_loading" style="display: none; text-align: center; padding: 40px;">
                                    <div style="display: inline-block; width: 40px; height: 40px; border: 3px solid #f3f3f3; border-top: 3px solid #0073aa; border-radius: 50%; animation: g-ffl-cockpit-spin 1s linear infinite;"></div>
                                    <p style="margin-top: 15px; color: #666;">Loading product history...</p>
                                </div>
                                <div id="g_ffl_cockpit_history_empty" style="display: none; text-align: center; padding: 40px; color: #666;">
                                    <i class="fas fa-history" style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;"></i>
                                    <p style="margin: 0; font-size: 16px;">No history data available for this product.</p>
                                </div>
                                <div id="g_ffl_cockpit_history_chart_container" style="position: relative; min-height: 300px;">
                                    <!-- Chart will be rendered here -->
                                </div>
                                <div id="g_ffl_cockpit_history_table_container" style="display: none;">
                                    <!-- Table will be rendered here -->
                                </div>
                            </div>
                            
                            <?php 
                            // Hide diagnosis section in multisite mode
                            $gffc_is_multisite = function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain();
                            if (!$gffc_is_multisite) : 
                            ?>
                            <!-- UPC Diagnosis Section - Only shown when product has no website link -->
                            <div id="g_ffl_cockpit_diagnosis_section" class="g-ffl-cockpit-diagnosis-section" style="display: none; background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%); padding: 25px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); margin-top: 25px; border: 1px solid #fbbf24;">
                                <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; margin-bottom: 20px;">
                                    <div style="display: flex; align-items: center; gap: 12px;">
                                        <div style="width: 40px; height: 40px; background: #f59e0b; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                            <i class="fas fa-question-circle" style="color: white; font-size: 20px;"></i>
                                        </div>
                                        <div>
                                            <h3 style="margin: 0; color: #92400e; font-size: 18px; font-weight: 700;">Why Isn't This Product on Your Site?</h3>
                                            <p style="margin: 4px 0 0 0; font-size: 13px; color: #a16207;">Diagnosis results help identify why this product hasn't been listed</p>
                                        </div>
                                    </div>
                                    <button type="button" onclick="gffcToggleDiagnosisPanel()" id="g_ffl_cockpit_diagnosis_toggle_btn" class="g-ffl-cockpit-btn" style="background: #f59e0b; color: white; padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: none; cursor: pointer; display: flex; align-items: center; gap: 8px;">
                                        <i class="fas fa-stethoscope"></i>
                                        <span id="g_ffl_cockpit_diagnosis_toggle_text">Run Diagnosis</span>
                                        <i class="fas fa-chevron-down" id="g_ffl_cockpit_diagnosis_chevron"></i>
                                    </button>
                                </div>
                                
                                <!-- Collapsible Diagnosis Content -->
                                <div id="g_ffl_cockpit_diagnosis_content" style="display: none;">
                                    <!-- Loading State -->
                                    <div id="g_ffl_cockpit_diagnosis_loading" style="display: none; text-align: center; padding: 40px;">
                                        <div style="display: inline-block; width: 40px; height: 40px; border: 3px solid #fef3c7; border-top: 3px solid #f59e0b; border-radius: 50%; animation: g-ffl-cockpit-spin 1s linear infinite;"></div>
                                        <p style="margin-top: 15px; color: #92400e; font-weight: 500;">Analyzing product listing status...</p>
                                    </div>
                                    
                                    <!-- Error State -->
                                    <div id="g_ffl_cockpit_diagnosis_error" style="display: none; background: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; padding: 20px; text-align: center;">
                                        <i class="fas fa-exclamation-triangle" style="font-size: 32px; color: #dc2626; margin-bottom: 10px;"></i>
                                        <p id="g_ffl_cockpit_diagnosis_error_message" style="margin: 0; color: #991b1b; font-weight: 500;">Unable to fetch diagnosis</p>
                                        <button type="button" onclick="gffcRunDiagnosis()" class="g-ffl-cockpit-btn" style="margin-top: 15px; background: #dc2626; color: white; padding: 8px 16px; border-radius: 6px; border: none; cursor: pointer; font-size: 13px;">
                                            <i class="fas fa-redo"></i> Retry
                                        </button>
                                    </div>
                                    
                                    <!-- Diagnosis Results -->
                                    <div id="g_ffl_cockpit_diagnosis_results" style="display: none;">
                                        <!-- Primary Reason Banner -->
                                        <div id="g_ffl_cockpit_diagnosis_primary_reason" style="background: white; border-radius: 10px; padding: 20px; margin-bottom: 20px; border-left: 4px solid #dc2626;">
                                            <div style="display: flex; align-items: flex-start; gap: 15px;">
                                                <div id="g_ffl_cockpit_diagnosis_reason_icon" style="width: 48px; height: 48px; background: #fef2f2; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                                                    <i class="fas fa-ban" style="color: #dc2626; font-size: 24px;"></i>
                                                </div>
                                                <div style="flex: 1;">
                                                    <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #6b7280; font-weight: 600; margin-bottom: 6px;">Primary Reason</div>
                                                    <div id="g_ffl_cockpit_diagnosis_primary_message" style="font-size: 16px; font-weight: 600; color: #1f2937; line-height: 1.4;"></div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Check Summary Grid -->
                                        <div style="background: white; border-radius: 10px; padding: 20px; margin-bottom: 20px;">
                                            <h4 style="margin: 0 0 15px 0; color: #374151; font-size: 15px; font-weight: 700;">
                                                <i class="fas fa-clipboard-check" style="margin-right: 8px; color: #6b7280;"></i>
                                                Diagnostic Checks
                                            </h4>
                                            <div id="g_ffl_cockpit_diagnosis_checks_grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 12px;">
                                                <!-- Check items will be rendered here -->
                                            </div>
                                        </div>
                                        
                                        <!-- Expanded Check Details (shown when a failed check is clicked) -->
                                        <div id="g_ffl_cockpit_diagnosis_check_details" style="display: none; background: white; border-radius: 10px; padding: 20px; margin-bottom: 20px; border: 1px solid #e5e7eb;">
                                            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                                                <h4 id="g_ffl_cockpit_diagnosis_detail_title" style="margin: 0; color: #374151; font-size: 15px; font-weight: 700;"></h4>
                                                <button type="button" onclick="gffcCloseDiagnosisDetails()" style="background: none; border: none; cursor: pointer; padding: 4px;">
                                                    <i class="fas fa-times" style="color: #9ca3af; font-size: 16px;"></i>
                                                </button>
                                            </div>
                                            <div id="g_ffl_cockpit_diagnosis_detail_content"></div>
                                        </div>
                                        
                                        <!-- Product Info Card (when available) -->
                                        <div id="g_ffl_cockpit_diagnosis_product_info" style="display: none; background: white; border-radius: 10px; padding: 20px; margin-bottom: 20px;">
                                            <h4 style="margin: 0 0 15px 0; color: #374151; font-size: 15px; font-weight: 700;">
                                                <i class="fas fa-box" style="margin-right: 8px; color: #6b7280;"></i>
                                                Product Information from Catalog
                                            </h4>
                                            <div id="g_ffl_cockpit_diagnosis_product_info_content" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px;">
                                                <!-- Product info will be rendered here -->
                                            </div>
                                        </div>
                                        
                                        <!-- Recommendations Section -->
                                        <div id="g_ffl_cockpit_diagnosis_recommendations" style="display: none; background: #ecfdf5; border-radius: 10px; padding: 20px; border: 1px solid #a7f3d0;">
                                            <h4 style="margin: 0 0 15px 0; color: #065f46; font-size: 15px; font-weight: 700;">
                                                <i class="fas fa-lightbulb" style="margin-right: 8px; color: #10b981;"></i>
                                                Recommendations
                                            </h4>
                                            <div id="g_ffl_cockpit_diagnosis_recommendations_list">
                                                <!-- Recommendations will be rendered here -->
                                            </div>
                                        </div>
                                        
                                        <!-- Clear Posting Errors Section (shown when posting_errors check fails) -->
                                        <div id="g_ffl_cockpit_diagnosis_clear_errors" style="display: none; background: #fef2f2; border-radius: 10px; padding: 20px; margin-top: 20px; border: 1px solid #fecaca;">
                                            <div style="display: flex; align-items: flex-start; gap: 15px; flex-wrap: wrap;">
                                                <div style="flex: 1; min-width: 250px;">
                                                    <h4 style="margin: 0 0 10px 0; color: #991b1b; font-size: 15px; font-weight: 700;">
                                                        <i class="fas fa-exclamation-circle" style="margin-right: 8px;"></i>
                                                        Posting Errors Detected
                                                    </h4>
                                                    <p id="g_ffl_cockpit_diagnosis_posting_error_msg" style="margin: 0; color: #7f1d1d; font-size: 14px; line-height: 1.5;"></p>
                                                </div>
                                                <button type="button" onclick="gffcClearPostingErrors()" id="g_ffl_cockpit_clear_errors_btn" class="g-ffl-cockpit-btn" style="background: #dc2626; color: white; padding: 12px 20px; border-radius: 8px; border: none; cursor: pointer; font-size: 14px; font-weight: 600; white-space: nowrap; display: flex; align-items: center; gap: 8px;">
                                                    <i class="fas fa-trash-alt"></i>
                                                    Clear Errors & Retry
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; // End multisite check ?>
                            
                            <div style="margin-top: 20px; text-align: center;">
                                <button id="g_ffl_cockpit_back_to_search" class="g-ffl-cockpit-btn g-ffl-cockpit-btn-secondary" onclick="showRegularSearchResults()">← Back to Search Results</button>
                            </div>
                        </div>
                        
                        <!-- Image Modal -->
                        <div id="g_ffl_cockpit_productImageModal" style="display: none; position: fixed; z-index: 10000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.9);">
                            <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: 90%; max-height: 90%; text-align: center;">
                                <img id="g_ffl_cockpit_modalProductImage" style="max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 8px; box-shadow: 0 4px 20px rgba(0,0,0,0.5);" />
                                <div style="color: white; margin-top: 15px; font-size: 18px; font-weight: 500;" id="g_ffl_cockpit_modalProductName"></div>
                            </div>
                            <span style="position: absolute; top: 15px; right: 35px; color: #f1f1f1; font-size: 40px; font-weight: bold; cursor: pointer; user-select: none;" onclick="closeImageModal()">&times;</span>
                        </div>
                        
                        <div style="display:flex; justify-content:flex-end; margin: 0 0 6px 0;">
                            <div id="gffc-product-search-sort-ui" style="display:none; align-items:center; position: relative;">
                                <button id="gffc-product-search-sort-button" type="button" class="button-link" style="display:flex; align-items:center; gap:6px; padding:0; font-size:14px; line-height:1.1; text-decoration:none;">
                                    <span style="color:#64748b; font-weight:600;">Sort by</span>
                                    <span id="gffc-product-search-sort-indicator" style="font-weight:700;">UPC</span>
                                    <span id="gffc-product-search-sort-arrow" aria-hidden="true" style="font-size: 14px;">▲</span>
                                </button>
                                <div id="gffc-product-search-sort-panel" style="display:none; position:absolute; top: 22px; right: 0; z-index: 5; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 8px;">
                                    <div style="display:flex; align-items:center; gap: 8px; flex-wrap: wrap;">
                                        <select id="gffc-product-search-sort-column" class="regular-text" style="min-width: 120px; width: 120px;">
                                            <option value="upc" selected>UPC</option>
                                            <option value="distid">Distributor</option>
                                            <option value="qty_on_hand">Quantity</option>
                                            <option value="mfg_name">Manufacturer</option>
                                            <option value="unit_price">Cost</option>
                                            <option value="total_cost">Total Cost</option>
                                            <option value="item_gb_cat_name">Category</option>
                                        </select>

                                        <select id="gffc-product-search-sort-direction" class="regular-text" style="min-width: 100px; width: 100px;">
                                            <option value="asc" selected>Ascending</option>
                                            <option value="desc">Descending</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div id="product_feed_table"></div>
                    </div>

                <div class="gffc-footer">
                    <div class="gffc-footer-col">
                    <?php if (current_user_can('manage_options')): ?>
                    <?php
                        $allowlist_ids = $this->get_product_search_allowlist_user_ids();
                        $all_users = get_users(array(
                            'orderby' => 'display_name',
                            'order' => 'ASC',
                            'fields' => array('ID', 'display_name', 'user_login', 'user_email'),
                        ));
                        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- UI message only
                        $allowlist_saved = isset($_GET['gffc_allowlist_saved']) && $_GET['gffc_allowlist_saved'] === '1';
                    ?>

                    <style>
                        /* Scoped styles for the kiosk user management panel (admin-only) */
                        .gffc-user-mgmt {
                            margin-top: 0;
                            border: 1px solid #e5e7eb;
                            border-radius: 8px;
                            background: #fff;
                            overflow: hidden;
                            width: 100%;
                        }
                        .gffc-user-mgmt__summary {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            gap: 14px;
                            cursor: pointer;
                            padding: 12px 16px;
                            background: linear-gradient(180deg, #fff 0%, #f8fafc 100%);
                            border-bottom: 1px solid #eef2f7;
                            user-select: none;
                        }
                        .gffc-user-mgmt__summary::-webkit-details-marker { display:none; }
                        .gffc-user-mgmt__title {
                            font-weight: 800;
                            font-size: 14px;
                            color: #0f172a;
                        }
                        .gffc-user-mgmt__sub {
                            margin-top: 2px;
                            font-size: 11px;
                            color: #475569;
                            line-height: 1.35;
                        }
                        .gffc-user-mgmt__chev {
                            width: 28px; height: 28px;
                            border-radius: 999px;
                            border: 1px solid #e5e7eb;
                            display: flex; align-items: center; justify-content: center;
                            background: #fff; flex: 0 0 auto;
                        }
                        .gffc-user-mgmt[open] .gffc-user-mgmt__chev { transform: rotate(180deg); }
                        .gffc-user-mgmt__body { padding: 12px 16px; }
                        .gffc-user-mgmt__saved {
                            display: inline-flex; align-items: center; gap: 6px;
                            padding: 4px 8px; border-radius: 999px;
                            background: #ecfdf5; color: #065f46;
                            font-weight: 800; font-size: 11px;
                            border: 1px solid #a7f3d0;
                            margin-top: 6px;
                        }
                        .gffc-user-mgmt__kiosk-info {
                            background: #fffbeb; border: 1px solid #fde68a;
                            border-radius: 6px; padding: 8px 10px;
                            font-size: 11px; color: #92400e; line-height: 1.4;
                            margin-bottom: 10px;
                        }
                        .gffc-user-mgmt__kiosk-info strong { color: #78350f; }
                        .gffc-user-mgmt__kiosk-info ul {
                            margin: 4px 0 0 16px; padding: 0;
                        }
                        .gffc-user-mgmt__kiosk-info li { margin-bottom: 1px; }
                        .gffc-user-mgmt__select { width: 100%; }
                        .gffc-user-mgmt__hint {
                            color: #64748b; font-size: 11px; margin-top: 4px;
                        }
                        .gffc-user-mgmt__table {
                            border: 1px solid #e5e7eb;
                            border-radius: 8px; overflow: hidden;
                        }
                        .gffc-user-mgmt__thead {
                            display: flex; align-items: center;
                            justify-content: space-between;
                            padding: 8px 12px;
                            background: #f8fafc;
                            border-bottom: 1px solid #eef2f7;
                            font-size: 13px;
                        }
                        .gffc-user-mgmt__thead strong { color: #0f172a; }
                        .gffc-user-mgmt__count { color: #64748b; font-size: 11px; }
                        .gffc-user-mgmt__list {
                            margin: 0; padding: 0; list-style: none;
                            max-height: 180px; overflow: auto; background: #fff;
                        }
                        .gffc-user-mgmt__row {
                            display: flex; align-items: center;
                            justify-content: space-between; gap: 10px;
                            padding: 8px 12px;
                            border-bottom: 1px solid #eef2f7;
                        }
                        .gffc-user-mgmt__row:last-child { border-bottom: none; }
                        .gffc-user-mgmt__who { display: flex; flex-direction: column; gap: 1px; min-width: 0; }
                        .gffc-user-mgmt__name {
                            font-weight: 700; color: #0f172a; font-size: 13px;
                            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
                        }
                        .gffc-user-mgmt__meta {
                            color: #64748b; font-size: 11px;
                            white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
                        }
                        .gffc-user-mgmt__trash {
                            display: inline-flex; align-items: center; justify-content: center;
                            width: 28px; height: 28px; border-radius: 8px;
                            border: 1px solid #fecaca; background: #fff5f5;
                            color: #dc2626; cursor: pointer;
                            transition: all 0.15s ease-in-out; flex: 0 0 auto;
                        }
                        .gffc-user-mgmt__trash:hover { background: #fee2e2; border-color: #fca5a5; }
                        .gffc-user-mgmt__empty { padding: 10px 12px; color: #64748b; font-size: 12px; }
                        @keyframes gffc-flash-saved {
                            0%   { opacity: 1; transform: scale(1); }
                            20%  { opacity: 1; transform: scale(1.08); }
                            100% { opacity: 0; transform: scale(0.95); }
                        }
                        .gffc-user-mgmt__saved--animate {
                            animation: gffc-flash-saved 1.8s ease-out forwards;
                        }
                    </style>

                    <details class="gffc-user-mgmt" <?php echo $allowlist_saved ? 'open' : ''; ?>>
                        <summary class="gffc-user-mgmt__summary">
                            <div>
                                <div class="gffc-user-mgmt__title">🖥️ Kiosk Mode Users</div>
                                <div class="gffc-user-mgmt__sub">Lock users to a full-screen Product Search experience — no WordPress access.</div>
                                <?php if ($allowlist_saved): ?>
                                    <div class="gffc-user-mgmt__saved gffc-user-mgmt__saved--animate" id="gffc-saved-badge">✓ Saved</div>
                                <?php endif; ?>
                            </div>
                            <div class="gffc-user-mgmt__chev" aria-hidden="true">
                                <span style="font-size: 14px; line-height: 1;">⌄</span>
                            </div>
                        </summary>
                        <?php if ($allowlist_saved): ?>
                        <script type="text/javascript">
                            (function() {
                                var badge = document.getElementById('gffc-saved-badge');
                                var details = badge ? badge.closest('details.gffc-user-mgmt') : null;
                                if (badge) {
                                    // Remove badge after animation finishes, then collapse
                                    badge.addEventListener('animationend', function() {
                                        badge.remove();
                                        if (details) {
                                            setTimeout(function() { details.removeAttribute('open'); }, 300);
                                        }
                                    });
                                }
                            })();
                        </script>
                        <?php endif; ?>
                        <div class="gffc-user-mgmt__body">
                            <div class="gffc-user-mgmt__kiosk-info">
                                <strong>⚠️ What is Kiosk Mode?</strong>
                                <ul>
                                    <li>The user sees <strong>only</strong> the Product Search screen — nothing else.</li>
                                    <li>No WordPress Dashboard, admin menu, WooCommerce, or admin bar.</li>
                                    <li>No Add to Cart or ordering capabilities.</li>
                                    <li>Ideal for in-store search terminals or employee lookup stations.</li>
                                </ul>
                            </div>
                            <form method="post" id="gffc-allowlist-form">
                                <input type="hidden" name="g_ffl_cockpit_action" value="save_product_search_allowlist" />
                                <?php wp_nonce_field('g_ffl_cockpit_save_product_search_allowlist', 'g_ffl_cockpit_allowlist_nonce'); ?>

                                <div style="display: flex; gap: 8px; align-items: center; margin-bottom: 10px;">
                                    <div style="flex: 1;">
                                        <select id="gffc-user-picker" class="gffc-user-mgmt__select" style="width: 100%;">
                                            <option value="">Select a user...</option>
                                                    <?php foreach ($all_users as $u): ?>
                                                        <?php
                                                            $label = $u->display_name . ' (' . $u->user_login . ')';
                                                            if (!empty($u->user_email)) {
                                                                $label .= ' - ' . $u->user_email;
                                                            }
                                                            $is_selected = in_array((int) $u->ID, $allowlist_ids, true);
                                                        ?>
                                                        <?php if (!$is_selected): ?>
                                                            <option value="<?php echo esc_attr((string) $u->ID); ?>"><?php echo esc_html($label); ?></option>
                                                        <?php endif; ?>
                                                    <?php endforeach; ?>
                                                </select>
                                    </div>
                                    <button type="button" class="button" id="gffc-allowlist-add">Add</button>
                                </div>

                                <!-- Hidden inputs for save handler -->
                                <div id="gffc-allowed-hidden"></div>

                                <div class="gffc-user-mgmt__table">
                                    <div class="gffc-user-mgmt__thead">
                                        <strong>Kiosk users</strong>
                                        <span class="gffc-user-mgmt__count" id="gffc-allowed-count"></span>
                                    </div>
                                    <ul class="gffc-user-mgmt__list" id="gffc-allowed-list">
                                        <?php if (empty($allowlist_ids)): ?>
                                            <li class="gffc-user-mgmt__empty" id="gffc-empty-row">No users added yet.</li>
                                        <?php endif; ?>

                                        <?php foreach ($all_users as $u): ?>
                                            <?php
                                                $label = $u->display_name . ' (' . $u->user_login . ')';
                                                if (!empty($u->user_email)) {
                                                    $label .= ' - ' . $u->user_email;
                                                }
                                            ?>
                                            <?php if (in_array((int) $u->ID, $allowlist_ids, true)): ?>
                                                <li class="gffc-user-mgmt__row" data-user-id="<?php echo esc_attr((string) $u->ID); ?>">
                                                    <div class="gffc-user-mgmt__who">
                                                        <div class="gffc-user-mgmt__name"><?php echo esc_html($u->display_name); ?></div>
                                                        <div class="gffc-user-mgmt__meta"><?php echo esc_html($u->user_login . (!empty($u->user_email) ? ' - ' . $u->user_email : '')); ?></div>
                                                    </div>
                                                    <button type="button" class="gffc-user-mgmt__trash" title="Remove" aria-label="Remove">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </li>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>

                                <div style="margin-top: 10px; display: flex; justify-content: flex-end;">
                                    <button type="submit" class="button button-primary">Save changes</button>
                                </div>

                                <script type="text/javascript">
                                    jQuery(function($) {
                                        // Initialize Select2
                                        if ($.fn.select2) {
                                            $('#gffc-user-picker').select2({
                                                placeholder: 'Select a user...',
                                                allowClear: true,
                                                width: '100%'
                                            });
                                        }

                                        function getAllowedIds() {
                                            var ids = [];
                                            $('#gffc-allowed-list .gffc-user-mgmt__row').each(function() {
                                                var id = parseInt($(this).attr('data-user-id') || '0', 10);
                                                if (id) ids.push(id);
                                            });
                                            // Unique
                                            return Array.from(new Set(ids));
                                        }

                                        function renderHiddenInputs() {
                                            var ids = getAllowedIds();
                                            var $wrap = $('#gffc-allowed-hidden');
                                            $wrap.empty();
                                            ids.forEach(function(id) {
                                                $('<input/>', {
                                                    type: 'hidden',
                                                    name: 'g_ffl_cockpit_product_search_allow_users[]',
                                                    value: id
                                                }).appendTo($wrap);
                                            });

                                            // Empty state
                                            if (ids.length === 0) {
                                                if ($('#gffc-empty-row').length === 0) {
                                                    $('#gffc-allowed-list').prepend('<li class="gffc-user-mgmt__empty" id="gffc-empty-row">No users added yet.</li>');
                                                }
                                            } else {
                                                $('#gffc-empty-row').remove();
                                            }

                                            $('#gffc-allowed-count').text(ids.length + (ids.length === 1 ? ' user' : ' users'));
                                        }

                                        function addSelectedUser() {
                                            var $select = $('#gffc-user-picker');
                                            var id = parseInt($select.val() || '0', 10);
                                            if (!id) return;

                                            // Already allowed?
                                            if ($('#gffc-allowed-list .gffc-user-mgmt__row[data-user-id="' + id + '"]').length) {
                                                return;
                                            }

                                            // Get text from selected option
                                            var $opt = $select.find('option:selected');
                                            var text = ($opt.text() || '').trim();
                                            var displayName = text;
                                            var meta = '';
                                            var dashIdx = text.indexOf(' - ');
                                            if (dashIdx !== -1) {
                                                displayName = text.substring(0, dashIdx);
                                                meta = text.substring(dashIdx + 3);
                                            }

                                            var row = $(
                                                '<li class="gffc-user-mgmt__row" data-user-id="' + id + '">' +
                                                    '<div class="gffc-user-mgmt__who">' +
                                                        '<div class="gffc-user-mgmt__name"></div>' +
                                                        '<div class="gffc-user-mgmt__meta"></div>' +
                                                    '</div>' +
                                                    '<button type="button" class="gffc-user-mgmt__trash" title="Remove" aria-label="Remove">' +
                                                        '<i class="fas fa-trash"></i>' +
                                                    '</button>' +
                                                '</li>'
                                            );
                                            row.find('.gffc-user-mgmt__name').text(displayName);
                                            row.find('.gffc-user-mgmt__meta').text(meta);
                                            $('#gffc-allowed-list').append(row);

                                            // Remove from picker and reset
                                            $opt.remove();
                                            $select.val(null).trigger('change');

                                            renderHiddenInputs();
                                        }

                                        // Add button click
                                        $('#gffc-allowlist-add').on('click', addSelectedUser);

                                        // Remove via trash icon (event delegation)
                                        $(document).on('click', '#gffc-allowed-list .gffc-user-mgmt__trash', function() {
                                            var $row = $(this).closest('.gffc-user-mgmt__row');
                                            var id = parseInt($row.attr('data-user-id') || '0', 10);
                                            if (!id) return;

                                            // Re-add to picker
                                            var displayName = ($row.find('.gffc-user-mgmt__name').text() || '').trim();
                                            var meta = ($row.find('.gffc-user-mgmt__meta').text() || '').trim();
                                            var label = displayName;
                                            if (meta) {
                                                label = displayName + ' - ' + meta;
                                            }
                                            
                                            var $select = $('#gffc-user-picker');
                                            $select.append(
                                                $('<option/>', {
                                                    value: id,
                                                    text: label
                                                })
                                            );
                                            
                                            $row.remove();
                                            renderHiddenInputs();
                                        });

                                        // On submit, ensure hidden inputs reflect latest state.
                                        $('#gffc-allowlist-form').on('submit', function() {
                                            renderHiddenInputs();
                                        });

                                        // Initial render
                                        renderHiddenInputs();
                                    });
                                </script>
                            </form>
                        </div>
                    </details>
                <?php endif; ?>
                    </div>
                    <div class="gffc-footer-col gffc-footer-right">
                        <div id="gffc-product-search-disclaimer" style="font-size: 11px; color: #666; text-align: right;">
                            <span style="font-weight:bold;color:red;">**</span> Results limited to Validated Distributors. (Check Configuration tab)
                        </div>
                        <button id="download_inventory_button" class="button" data-marker-id="">Download Catalog</button>
                    </div>
                </div>
                    <script>
                        // Make the plugin image base URL globally available for all cockpit scripts.
                        window.imageBaseUrl = window.imageBaseUrl || "<?php echo esc_url(plugin_dir_url(__FILE__) . 'images/'); ?>";

                        const window_height = (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) * 0.8;
                        const imageBaseUrl = window.imageBaseUrl;
                        const gffcRestBase = "<?php echo esc_url_raw(rest_url('fflcockpit/v1')); ?>";
                        const gffcRestNonce = "<?php echo esc_attr(wp_create_nonce('wp_rest')); ?>";
                        const gffcApiKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";
                        const gffcFflApiUrl = "https://ffl-api.garidium.com";
                        const gffcCurrentUser = <?php echo json_encode([
                            'id' => get_current_user_id(),
                            'user_login' => wp_get_current_user()->user_login,
                            'user_email' => wp_get_current_user()->user_email,
                            'display_name' => wp_get_current_user()->display_name,
                        ]); ?>;
                        const gffcIsAdmin = <?php
                            $is_privileged = current_user_can('manage_options') || in_array('shop_manager', (array) wp_get_current_user()->roles, true);
                            // Kiosk-mode users never get cart access, even if they are a Shop Manager.
                            echo ($is_privileged && !$this->is_restricted_user()) ? 'true' : 'false';
                        ?>;
                        const gffcCurrentIp = "<?php echo esc_js($_SERVER['REMOTE_ADDR'] ?? ''); ?>";

                        window.gffcSelectedFFL = window.gffcSelectedFFL || null;
                        window.gffcFflSearchResults = window.gffcFflSearchResults || [];
                        window.gffcCartHasFirearm = window.gffcCartHasFirearm || false;

                        async function gffcCartApi(path, body = null) {
                            const url = gffcRestBase + path;
                            const opts = {
                                method: body ? 'POST' : 'GET',
                                credentials: 'same-origin',
                                headers: {
                                    'Accept': 'application/json',
                                    'X-WP-Nonce': gffcRestNonce,
                                }
                            };
                            if (body) {
                                opts.headers['Content-Type'] = 'application/json';
                                opts.body = JSON.stringify(body);
                            }
                            const resp = await fetch(url, opts);
                            const data = await resp.json().catch(() => ({}));
                            if (!resp.ok) {
                                const msg = data && (data.error || data.message) ? (data.error || data.message) : ('Request failed: ' + resp.status);
                                throw new Error(msg);
                            }
                            return data;
                        }

                        function gffcFormatCurrency(val) {
                            const n = Number(val || 0);
                            return '$' + n.toFixed(2);
                        }

                        function gffcUpdateCartBadge(summary) {
                            const btn = document.getElementById('gffc_cart_tab_btn');
                            const badge = document.getElementById('gffc_cart_badge');
                            
                            // Mobile accordion elements
                            const btnMobile = document.getElementById('gffc_cart_accordion_btn');
                            const badgeMobile = document.getElementById('gffc_cart_badge_mobile');

                            const lineCount = summary?.line_count || 0;
                            const itemCount = summary?.item_count || 0;
                            if (badge) {
                                badge.textContent = String(itemCount);
                            }
                            if (btn) {
                                btn.style.display = lineCount > 0 ? '' : 'none';
                            }
                            
                            if (badgeMobile) {
                                badgeMobile.textContent = String(itemCount);
                            }
                            if (btnMobile) {
                                btnMobile.style.display = lineCount > 0 ? '' : 'none';
                            }
                        }

                        function gffcIsTabActive(tabName) {
                            const el = document.getElementById(tabName);
                            return !!(el && el.style.display === 'block');
                        }

                        function gffcSwitchToProductSearchTab() {
                            const productFeedTab = document.querySelector('#cockpit_main_tab_control button[onclick*="product_feed"]');
                            if (!productFeedTab) return;

                            if (typeof window.openTab === 'function') {
                                try {
                                    window.openTab({ currentTarget: productFeedTab, preventDefault: function(){} }, 'product_feed');
                                    return;
                                } catch (e) {
                                    // fall through to click
                                }
                            }
                            productFeedTab.click();
                        }

                        async function gffcRefreshCartUI() {
                            try {
                                const data = await gffcCartApi('/cart');
                                gffcUpdateCartBadge(data.summary);
                                gffcRenderCart(data.cart, data.summary, data.adjustments);

                                // If the cart is emptied while the Cart tab is active, bounce back to Product Search.
                                const lineCount = data && data.summary && data.summary.line_count ? Number(data.summary.line_count) : 0;
                                if (lineCount <= 0 && gffcIsTabActive('cart')) {
                                    gffcSwitchToProductSearchTab();
                                }
                            } catch (e) {
                                // If user isn't allowed or any issue, keep UI quiet.
                                console.warn('Cart refresh failed:', e);
                            }
                        }

                        function gffcGetCartRoot() {
                            return document.getElementById('gffc_cart_root');
                        }

                        function gffcCaptureCheckoutState() {
                            const checkoutExists = !!(
                                document.getElementById('gffc_checkout_submit') ||
                                document.getElementById('gffc_customer_name')
                            );
                            if (!checkoutExists) return null;

                            const fflResultsEl = document.getElementById('gffc_ffl_results');
                            const fflSelectedEl = document.getElementById('gffc_ffl_selected');

                            const getCheckedRadio = (name) => {
                                const el = document.querySelector(`input[name="${name}"]:checked`);
                                return el ? el.value : null;
                            };

                            const ids = [
                                'gffc_customer_name',
                                'gffc_customer_email',
                                'gffc_customer_phone',
                                'gffc_customer_address1',
                                'gffc_customer_address2',
                                'gffc_customer_city',
                                'gffc_customer_state',
                                'gffc_customer_zip',
                                'gffc_ffl_license_number',
                                'gffc_ffl_zip',
                                'gffc_ffl_name',
                                'gffc_ffl_radius',
                            ];

                            const values = {};
                            ids.forEach((id) => {
                                const el = document.getElementById(id);
                                if (!el) return;
                                values[id] = el.value;
                            });

                            return {
                                orderType: getCheckedRadio('gffc_order_type'),
                                shippingDest: getCheckedRadio('gffc_shipping_dest'),
                                values,
                                selectedFfl: window.gffcSelectedFFL || null,
                                fflSearchResults: Array.isArray(window.gffcFflSearchResults) ? window.gffcFflSearchResults : [],
                                fflResultsHtml: fflResultsEl ? fflResultsEl.innerHTML : '',
                                fflSelectedHtml: fflSelectedEl ? fflSelectedEl.innerHTML : '',
                            };
                        }

                        function gffcRestoreCheckoutState(state) {
                            if (!state) return;

                            // Restore FFL search results list (so qty edits don't wipe it).
                            window.gffcFflSearchResults = Array.isArray(state.fflSearchResults) ? state.fflSearchResults : [];

                            const fflResultsEl = document.getElementById('gffc_ffl_results');
                            if (fflResultsEl && typeof state.fflResultsHtml === 'string' && state.fflResultsHtml) {
                                fflResultsEl.innerHTML = state.fflResultsHtml;
                            }

                            const fflSelectedEl = document.getElementById('gffc_ffl_selected');
                            if (fflSelectedEl && typeof state.fflSelectedHtml === 'string' && state.fflSelectedHtml) {
                                fflSelectedEl.innerHTML = state.fflSelectedHtml;
                            }

                            const setRadioIfPossible = (name, value) => {
                                if (!value) return;
                                const radios = document.querySelectorAll(`input[name="${name}"]`);
                                let set = false;
                                radios.forEach((r) => {
                                    if (!set && r && r.value === value && !r.disabled) {
                                        r.checked = true;
                                        set = true;
                                    }
                                });
                            };

                            setRadioIfPossible('gffc_order_type', state.orderType);
                            setRadioIfPossible('gffc_shipping_dest', state.shippingDest);

                            const values = state.values || {};
                            Object.keys(values).forEach((id) => {
                                const el = document.getElementById(id);
                                if (!el) return;
                                el.value = values[id];
                            });

                            // Restore selected FFL card (if user previously selected one).
                            if (state.selectedFfl && typeof state.selectedFfl === 'object') {
                                window.gffcSelectedFFL = state.selectedFfl;
                                const lic = document.getElementById('gffc_ffl_license_number');
                                if (lic && state.selectedFfl.license_number) {
                                    lic.value = state.selectedFfl.license_number;
                                }

                                // If we didn't restore an existing selected HTML block, render a default one.
                                const selectedWrap = document.getElementById('gffc_ffl_selected');
                                if (selectedWrap && !selectedWrap.innerHTML && state.selectedFfl.license_number) {
                                    selectedWrap.innerHTML = `
                                        <div style="padding: 10px; border: 1px solid #e5e7eb; border-radius: 10px; background: #fff;">
                                            <div style="font-weight:700; margin-bottom:4px;">Selected FFL</div>
                                            <div style="font-family:monospace; margin-bottom:6px;">${state.selectedFfl.license_number}</div>
                                            <div style="font-size:12px; color:#475569; line-height:1.3;">${gffcFormatFflDisplay(state.selectedFfl)}</div>
                                        </div>
                                    `;
                                }
                            }
                        }

                        function gffcRenderCart(cart, summary, adjustments) {
                            const root = gffcGetCartRoot();
                            const topClearBtn = document.getElementById('gffc_cart_clear_top_btn');
                            const gunbrokerNotice = document.getElementById('gffc_gunbroker_cart_notice');
                            if (!root) return;

                            // Banner: one-time notice that one or more cart lines were reduced because
                            // the requested qty exceeded the distributor's on-hand for that line.
                            // `adjustments` is sent only on the first /cart load after a clamp; once
                            // the corrected cart is persisted server-side, the banner won't reappear.
                            const adjList = Array.isArray(adjustments) ? adjustments : [];
                            let adjBannerHtml = '';
                            if (adjList.length > 0) {
                                const rowsHtml = adjList.map(a => {
                                    const label = (a.name || a.distsku || a.upc || 'item').replace(/</g, '&lt;');
                                    return `<li style="margin: 2px 0;"><strong>${label}</strong>: ${a.requested_qty} &rarr; <strong>${a.adjusted_qty}</strong> (${a.qty_on_hand} available at ${a.distid || 'distributor'})</li>`;
                                }).join('');
                                adjBannerHtml = `
                                    <div id="gffc_cart_adjustment_banner" style="margin-bottom: 12px; padding: 12px 14px; background:#fffbeb; border:1px solid #f59e0b; border-radius:8px; color:#78350f; display:flex; gap:12px; align-items:flex-start;">
                                        <div style="flex-shrink:0; width:28px; height:28px; background:#f59e0b; border-radius:50%; display:flex; align-items:center; justify-content:center; color:#fff; font-weight:700;">!</div>
                                        <div style="flex:1; font-size:13px; line-height:1.5;">
                                            <div style="font-weight:700; margin-bottom: 4px;">${adjList.length === 1 ? '1 cart line was' : adjList.length + ' cart lines were'} reduced to match distributor availability.</div>
                                            <ul style="margin: 6px 0 0 18px; padding: 0;">${rowsHtml}</ul>
                                        </div>
                                        <button type="button" onclick="(function(){var b=document.getElementById('gffc_cart_adjustment_banner');if(b)b.style.display='none';})();" style="background:transparent; border:none; color:#92400e; font-size:18px; cursor:pointer; line-height:1; padding:0;" title="Dismiss">&times;</button>
                                    </div>
                                `;
                            }

                            const prevCheckoutState = gffcCaptureCheckoutState();

                            const items = cart?.items || [];
                            
                            // Toggle top clear button
                            if (topClearBtn) {
                                topClearBtn.style.display = items.length > 0 ? '' : 'none';
                            }

                            if (!items.length) {
                                if (gunbrokerNotice) {
                                    gunbrokerNotice.style.display = 'none';
                                    gunbrokerNotice.innerHTML = '';
                                }
                                if (typeof gffcClearCartOrderContext === 'function') {
                                    gffcClearCartOrderContext();
                                }
                                root.innerHTML = adjBannerHtml + `
                                    <div style="padding: 14px; background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 10px; color: #475569;">
                                        Your cart is empty. Go to <strong>Product Search</strong> and click <strong>Add to Cart</strong>.
                                    </div>
                                `;
                                return;
                            }

                            const rows = items.map(it => {
                                const imgSrc = (it.images && it.images.length > 0 && it.images[0].src) ? it.images[0].src : '';
                                return `
                                    <tr class="gffc-cart-row">
                                        <td class="gffc-cart-dist" style="padding: 10px; border-bottom: 1px solid #e5e7eb; width: 60px; text-align:center;">
                                            <img src="${get_distributor_logo(it.distid)}" style="max-width: 50px; max-height: 26px; object-fit: contain;" onerror="this.style.display='none';" />
                                        </td>
                                        <td class="gffc-cart-item" style="padding: 10px; border-bottom: 1px solid #e5e7eb;">
                                            <div style="display:flex; gap:10px; align-items:center;">
                                                ${imgSrc ? `<img src="${imgSrc}" style="width:48px;height:48px;object-fit:contain;border:1px solid #e5e7eb;border-radius:6px;" onerror="this.style.display='none';"/>` : ''}
                                                <div>
                                                    <div style="font-weight:700;">${it.name || ''}</div>
                                                    <div style="color:#64748b;font-size:12px;">UPC: <span style="font-family:monospace;">${it.upc || ''}</span> | SKU: <span style="font-family:monospace;">${it.distsku || ''}</span>${it.mpn ? (' | MPN: ' + it.mpn) : ''}</div>
                                                    <div style="margin-top:4px; font-size:12px;">
                                                        <span style="color:#165e7e; font-style: italic;">Product Pages:</span> 
                                                        ${it.product_url ? `<a href="${it.product_url}" target="_blank">Distributor</a>` : ''}
                                                        ${it.permalink ? ` ${it.product_url ? '|' : ''} <a href="${it.permalink}" target="_blank">Website</a>` : ''}
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="gffc-cart-price" style="padding: 10px; border-bottom: 1px solid #e5e7eb; width: 120px; text-align:right; white-space:nowrap;">
                                            <div style="font-size:12px; color:#64748b;">${gffcFormatCurrency(it.unit_price || 0)} ea &times; ${it.qty || 1}</div>
                                            <div style="font-weight:800; font-size:15px; color:#0f172a; margin-top:3px; padding-top:3px; border-top:1px solid #e5e7eb;">${gffcFormatCurrency((Number(it.unit_price) || 0) * (Number(it.qty) || 1))}</div>
                                        </td>
                                        <td class="gffc-cart-qty" style="padding: 10px; border-bottom: 1px solid #e5e7eb; width: 90px; text-align:center;">
                                            <input type="number" min="1" max="${it.qty_on_hand || 999}" value="${it.qty || 1}" style="width:70px; padding:2px; height:28px;" onchange="gffcCartUpdateQty('${it.key}', this.value, ${it.qty_on_hand || 999})" />
                                            <div style="font-size:10px; color:#64748b; margin-top:4px;">${it.qty_on_hand || 0} in stock</div>
                                        </td>
                                        <td class="gffc-cart-actions" style="padding: 10px; border-bottom: 1px solid #e5e7eb; width: 80px; text-align:center;">
                                            <i class="fas fa-trash-alt" style="color: #ef4444; cursor: pointer; font-size: 1.2em;" onclick="gffcCartRemove('${it.key}')" title="Remove"></i>
                                        </td>
                                    </tr>
                                `;
                            }).join('');

                            // Used to toggle FFL requirements for firearm drop-ship orders.
                            window.gffcCartHasFirearm = !!(summary && summary.has_firearm);
                            
                            // Check if ANY item requires FFL
                            const anyItemRequiresFfl = items.length > 0 && items.some(it => !!it.ffl_req);
                            // Check if ALL items require FFL
                            const allItemsRequireFfl = items.length > 0 && items.every(it => !!it.ffl_req);

                            root.innerHTML = adjBannerHtml + `
                                <div style="overflow:auto; border:1px solid #e5e7eb; border-radius:10px; background:#fff;">
                                    <table class="gffc-cart-table" style="width:100%; border-collapse: collapse;">
                                        <thead>
                                            <tr style="background:#f8fafc;">
                                                <th style="text-align:center; padding:10px; border-bottom:1px solid #e5e7eb;">Dist</th>
                                                <th style="text-align:left; padding:10px; border-bottom:1px solid #e5e7eb;">Item</th>
                                                <th style="text-align:right; padding:10px; border-bottom:1px solid #e5e7eb;">Price</th>
                                                <th style="text-align:center; padding:10px; border-bottom:1px solid #e5e7eb;">Qty</th>
                                                <th style="text-align:center; padding:10px; border-bottom:1px solid #e5e7eb;">Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            ${rows}
                                        </tbody>
                                    </table>
                                </div>
                                <div style="display:flex; justify-content: flex-end; align-items:center; gap: 10px; margin-top: 10px; margin-bottom: 10px;">
                                    <div style="color:#334155; font-weight:700;">${summary?.line_count || items.length} lines / ${summary?.item_count || 0} items</div>
                                </div>

                                <div style="margin-top: 14px; padding: 14px; border: 1px solid #e5e7eb; border-radius: 10px; background: #fff;">
                                    <h4 style="margin:0 0 10px 0;">Checkout</h4>
                                    <div style="display:flex; gap: 18px; flex-wrap: wrap; align-items:flex-start;">
                                        <div style="flex: 1; min-width: 320px;">
                                            <div style="margin-bottom: 10px;">
                                                <label style="margin-right: 12px;"><input type="radio" name="gffc_order_type" value="ship_to_store" checked onchange="gffcToggleCheckoutMode()" /> Ship to Store</label>
                                                <label><input type="radio" name="gffc_order_type" value="drop_ship" onchange="gffcToggleCheckoutMode()" /> Drop Ship</label>
                                            </div>

                                            <div id="gffc_drop_ship_options" style="margin-bottom: 15px; padding: 10px; background: #f1f5f9; border-radius: 6px; display:none;">
                                                <div style="font-weight:600; margin-bottom:5px; font-size:12px;">Shipping Destination:</div>
                                                <label style="margin-right: 10px; font-size:12px; ${anyItemRequiresFfl ? 'color:#999;' : ''}">
                                                    <input type="radio" name="gffc_shipping_dest" value="customer" ${anyItemRequiresFfl ? 'disabled' : 'checked'} onchange="gffcToggleCheckoutMode()"> Customer Address
                                                </label>
                                                <label style="margin-right: 10px; font-size:12px;">
                                                    <input type="radio" name="gffc_shipping_dest" value="ffl" ${anyItemRequiresFfl ? 'checked' : ''} onchange="gffcToggleCheckoutMode()"> FFL
                                                </label>
                                                <label style="font-size:12px; ${(allItemsRequireFfl || items.length < 2) ? 'color:#999;' : ''}">
                                                    <input type="radio" name="gffc_shipping_dest" value="mixed" ${(allItemsRequireFfl || items.length < 2) ? 'disabled' : ''} onchange="gffcToggleCheckoutMode()"> Mixed (Both)
                                                </label>
                                                ${anyItemRequiresFfl ? '<div style="margin-top:5px; font-size:11px; color:#d97706;">* Cart contains FFL items. Customer Address shipping is unavailable.</div>' : ''}
                                            </div>

                                            <div id="gffc_customer_contact_fields">
                                                <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                                                    <div>
                                                        <label>Customer Name *</label>
                                                        <input id="gffc_customer_name" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                    <div>
                                                        <label>Customer Email</label>
                                                        <input id="gffc_customer_email" type="email" class="regular-text" style="width:100%;" />
                                                    </div>
                                                    <div>
                                                        <label>Customer Phone</label>
                                                        <input id="gffc_customer_phone" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                </div>
                                            </div>
                                            <div id="gffc_customer_address_fields">
                                                <div style="margin-top:10px; display:grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                                                    <div>
                                                        <label>Address 1 *</label>
                                                        <input id="gffc_customer_address1" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                    <div>
                                                        <label>Address 2</label>
                                                        <input id="gffc_customer_address2" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                    <div>
                                                        <label>City *</label>
                                                        <input id="gffc_customer_city" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                    <div>
                                                        <label>State *</label>
                                                        <select id="gffc_customer_state" class="regular-text" style="width:100%;">
                                                            <option value="">Select</option>
                                                            <option value="AL">Alabama</option>
                                                            <option value="AK">Alaska</option>
                                                            <option value="AZ">Arizona</option>
                                                            <option value="AR">Arkansas</option>
                                                            <option value="CA">California</option>
                                                            <option value="CO">Colorado</option>
                                                            <option value="CT">Connecticut</option>
                                                            <option value="DE">Delaware</option>
                                                            <option value="DC">District of Columbia</option>
                                                            <option value="FL">Florida</option>
                                                            <option value="GA">Georgia</option>
                                                            <option value="HI">Hawaii</option>
                                                            <option value="ID">Idaho</option>
                                                            <option value="IL">Illinois</option>
                                                            <option value="IN">Indiana</option>
                                                            <option value="IA">Iowa</option>
                                                            <option value="KS">Kansas</option>
                                                            <option value="KY">Kentucky</option>
                                                            <option value="LA">Louisiana</option>
                                                            <option value="ME">Maine</option>
                                                            <option value="MD">Maryland</option>
                                                            <option value="MA">Massachusetts</option>
                                                            <option value="MI">Michigan</option>
                                                            <option value="MN">Minnesota</option>
                                                            <option value="MS">Mississippi</option>
                                                            <option value="MO">Missouri</option>
                                                            <option value="MT">Montana</option>
                                                            <option value="NE">Nebraska</option>
                                                            <option value="NV">Nevada</option>
                                                            <option value="NH">New Hampshire</option>
                                                            <option value="NJ">New Jersey</option>
                                                            <option value="NM">New Mexico</option>
                                                            <option value="NY">New York</option>
                                                            <option value="NC">North Carolina</option>
                                                            <option value="ND">North Dakota</option>
                                                            <option value="OH">Ohio</option>
                                                            <option value="OK">Oklahoma</option>
                                                            <option value="OR">Oregon</option>
                                                            <option value="PA">Pennsylvania</option>
                                                            <option value="RI">Rhode Island</option>
                                                            <option value="SC">South Carolina</option>
                                                            <option value="SD">South Dakota</option>
                                                            <option value="TN">Tennessee</option>
                                                            <option value="TX">Texas</option>
                                                            <option value="UT">Utah</option>
                                                            <option value="VT">Vermont</option>
                                                            <option value="VA">Virginia</option>
                                                            <option value="WA">Washington</option>
                                                            <option value="WV">West Virginia</option>
                                                            <option value="WI">Wisconsin</option>
                                                            <option value="WY">Wyoming</option>
                                                            <option value="AS">American Samoa</option>
                                                            <option value="GU">Guam</option>
                                                            <option value="MP">Northern Mariana Islands</option>
                                                            <option value="PR">Puerto Rico</option>
                                                            <option value="VI">U.S. Virgin Islands</option>
                                                            <option value="UM">U.S. Minor Outlying Islands</option>
                                                        </select>
                                                    </div>
                                                    <div>
                                                        <label>Zip *</label>
                                                        <input id="gffc_customer_zip" type="text" class="regular-text" style="width:100%;" />
                                                    </div>
                                                </div>
                                                <div id="gffc_customer_note" style="margin-top: 8px; color:#64748b; font-size:12px;">* Required for Drop Ship.</div>
                                            </div>

                                            <div id="gffc_ffl_fields" style="margin-top: 20px; padding: 15px; background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;">
                                                <div style="font-weight:700; margin-bottom: 6px;">FFL Selection</div>
                                                <div style="color:#64748b; font-size:12px; margin-bottom: 10px;">Enter an FFL license number, or search by ZIP code and select one.</div>

                                                <div class="gffc-ffl-license-row">
                                                    <div>
                                                        <label>FFL License Number *</label>
                                                        <input id="gffc_ffl_license_number" type="text" class="regular-text" style="width:100%;" placeholder="FFL license number" oninput="gffcOnManualFflLicenseChange()" />
                                                    </div>
                                                    <div>
                                                        <button class="button" type="button" onclick="gffcClearSelectedFFL()">Clear</button>
                                                    </div>
                                                </div>

                                                <div class="gffc-ffl-search-row">
                                                    <div>
                                                        <label>ZIP *</label>
                                                        <input id="gffc_ffl_zip" type="text" class="regular-text" style="width:100%;" placeholder="e.g. 90210" maxlength="5" />
                                                    </div>
                                                    <div>
                                                        <label>Name (optional)</label>
                                                        <input id="gffc_ffl_name" name="gffc_ffl_search_dealer_name" type="text" class="regular-text" style="width:100%;" placeholder="dealer name" autocomplete="new-password" />
                                                    </div>
                                                    <div>
                                                        <label>Radius</label>
                                                        <select id="gffc_ffl_radius" class="regular-text" style="width:100%;">
                                                            <option value="10">10</option>
                                                            <option value="25" selected>25</option>
                                                            <option value="50">50</option>
                                                            <option value="100">100</option>
                                                        </select>
                                                    </div>
                                                    <div>
                                                        <button class="button" type="button" onclick="gffcSearchFFL()">Search</button>
                                                    </div>
                                                </div>

                                                <div id="gffc_ffl_selected" style="margin-top: 10px;"></div>
                                                <div id="gffc_ffl_results" style="margin-top: 10px;"></div>
                                            </div>
                                        </div>

                                        <div style="width: 325px; flex: 0 0 auto; font-size: 15px;">
                                            <div style="padding: 12px; background: #f8fafc; border: 1px solid #e5e7eb; border-radius: 10px;">
                                                <div style="display:flex; justify-content: space-between; margin-bottom: 8px;">
                                                    <span>Items subtotal</span>
                                                    <strong>${gffcFormatCurrency(items.reduce((acc, item) => acc + (Number(item.unit_price || 0) * Number(item.qty || 1)), 0))}</strong>
                                                </div>
                                                <div style="display:flex; justify-content: space-between; margin-bottom: 8px;">
                                                    <span>Estimated shipping</span>
                                                    <strong>${gffcFormatCurrency(summary?.shipping_estimate || 0)}</strong>
                                                </div>
                                                <div style="display:flex; justify-content: space-between; margin: 10px 0 8px; padding-top: 8px; border-top: 1px solid #e5e7eb;">
                                                    <span style="font-weight:800;">Estimated total</span>
                                                    <strong style="font-weight:800;">${gffcFormatCurrency((items.reduce((acc, item) => acc + (Number(item.unit_price || 0) * Number(item.qty || 1)), 0)) + (summary?.shipping_estimate || 0))}</strong>
                                                </div>
                                                <div style="margin-bottom: 10px; font-size: 11px; color:#64748b; line-height: 1.3;">
                                                    ${summary?.shipping_estimate_disclaimer || 'Shipping is estimated and is counted once per distributor and class (firearm vs non-firearm). Final shipping may differ.'}
                                                </div>
                                                ${(summary?.shipping_estimate_groups && summary.shipping_estimate_groups.length) ? `
                                                    <div style="margin-bottom: 10px; font-size: 11px; color:#64748b; line-height: 1.3;">
                                                        <div style="font-weight:700; color:#475569; margin-bottom: 4px;">Shipping groups used for estimate</div>
                                                        <ul style="margin: 0 0 0 18px;">
                                                            ${summary.shipping_estimate_groups.map(g => `<li>${g.distid} (${g.ship_class}) — ${gffcFormatCurrency(g.shipping_cost || 0)}</li>`).join('')}
                                                        </ul>
                                                    </div>
                                                ` : ''}
                                                <button class="button button-primary" style="width:100%;" id="gffc_checkout_submit" onclick="gffcCheckout()">Submit Order</button>
                                                <div id="gffc_checkout_status" style="margin-top:10px; font-size:12px; color:#334155;"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;

                            // Restore user-entered checkout info after re-render (e.g. qty updates).
                            gffcRestoreCheckoutState(prevCheckoutState);
                            gffcToggleCheckoutMode();
                        }

                        async function gffcCartUpdateQty(key, qty, max) {
                            try {
                                let q = parseInt(qty || '1', 10);
                                if (max && q > max) {
                                    q = max;
                                    alert('Quantity limited to available stock: ' + max);
                                }
                                await gffcCartApi('/cart/update', { key, qty: q });
                                await gffcRefreshCartUI();
                            } catch (e) {
                                alert('Failed to update quantity: ' + e.message);
                            }
                        }

                        async function gffcCartRemove(key) {
                            if (!window.confirm('Remove this item from cart?')) return;
                            try {
                                await gffcCartApi('/cart/remove', { key });
                                await gffcRefreshCartUI();
                            } catch (e) {
                                alert('Failed to remove: ' + e.message);
                            }
                        }

                        async function gffcCartClear() {
                            if (!window.confirm('Clear the cart?')) return;
                            try {
                                await gffcCartApi('/cart/clear', {});
                                await gffcRefreshCartUI();
                            } catch (e) {
                                alert('Failed to clear cart: ' + e.message);
                            }
                        }

                        function gffcToggleCheckoutMode() {
                            const type = (document.querySelector('input[name="gffc_order_type"]:checked') || {}).value || 'drop_ship';
                            const isShipToStore = type === 'ship_to_store';
                            
                            // Drop Ship Options
                            const dropShipOptions = document.getElementById('gffc_drop_ship_options');
                            if (dropShipOptions) dropShipOptions.style.display = isShipToStore ? 'none' : 'block';

                            // Determine Shipping Destination
                            const dest = (document.querySelector('input[name="gffc_shipping_dest"]:checked') || {}).value || 'customer';
                            
                            // Visibility Flags
                            const showAddress = !isShipToStore && (dest === 'customer' || dest === 'mixed');
                            const showFfl = !isShipToStore && (dest === 'ffl' || dest === 'mixed');

                            const msg = document.getElementById('gffc_checkout_status');
                            if (msg) msg.textContent = '';

                            const addressWrap = document.getElementById('gffc_customer_address_fields');
                            const customerNote = document.getElementById('gffc_customer_note');
                            if (addressWrap) {
                                addressWrap.style.display = showAddress ? '' : 'none';
                            }
                            if (customerNote) {
                                customerNote.style.display = showAddress ? '' : 'none';
                            }

                            // Address Fields
                            const fields = ['gffc_customer_address1','gffc_customer_city','gffc_customer_state','gffc_customer_zip'];
                            fields.forEach(id => {
                                const el = document.getElementById(id);
                                if (!el) return;
                                el.disabled = !showAddress;
                                el.style.borderColor = showAddress ? '#94a3b8' : '#e5e7eb';
                            });
                            
                            // Ensure contact fields are enabled
                            ['gffc_customer_name', 'gffc_customer_email', 'gffc_customer_phone'].forEach(id => {
                                const el = document.getElementById(id);
                                if (el) el.disabled = false;
                            });

                            // FFL section
                            const fflWrap = document.getElementById('gffc_ffl_fields');
                            if (fflWrap) {
                                fflWrap.style.display = showFfl ? '' : 'none';
                                // Disable inputs when hidden.
                                ['gffc_ffl_license_number', 'gffc_ffl_zip', 'gffc_ffl_name', 'gffc_ffl_radius'].forEach(id => {
                                    const el = document.getElementById(id);
                                    if (el) el.disabled = !showFfl;
                                });
                            }
                        }

                        function gffcGetElValue(id) {
                            const el = document.getElementById(id);
                            return el ? (el.value || '') : '';
                        }

                        function gffcSetHtml(id, html) {
                            const el = document.getElementById(id);
                            if (el) el.innerHTML = html;
                        }

                        function gffcFormatFflDisplay(ffl) {
                            if (!ffl) return '';
                            const parts = [];
                            if (ffl.name) parts.push(ffl.name);
                            if (ffl.address) parts.push(ffl.address);
                            const loc = [ffl.city, ffl.state].filter(Boolean).join(', ');
                            const zip = ffl.zip || '';
                            if (loc || zip) parts.push((loc ? loc : '') + (zip ? (' ' + zip) : ''));
                            return parts.filter(Boolean).join('<br/>');
                        }

                        function gffcNormalizeFfl(raw) {
                            if (!raw || typeof raw !== 'object') return null;
                            const license_number = raw.license_number || raw.license || raw.licenseNumber || '';

                            // Prefer business name for display + order payload, then fall back to license name.
                            const businessName = raw.business_name || raw.businessName || '';
                            const licenseName = raw.license_name || raw.licenseName || '';
                            const name = businessName || licenseName || raw.name || raw.ffl_name || raw.premise_name || raw.licensee_name || '';

                            const street = raw.premise_street || raw.street || raw.address1 || '';
                            const city = raw.premise_city || raw.city || '';
                            const state = raw.premise_state || raw.state || '';
                            const zip = raw.premise_zip_code || raw.zip || raw.zip_code || '';
                            const address = raw.address || (street ? street : '');

                            return {
                                license_number: String(license_number || ''),
                                name: String(name || ''),
                                address: String(address || ''),
                                city: String(city || ''),
                                state: String(state || ''),
                                zip: String(zip || ''),
                                phone: String(raw.voice_phone || raw.phone || ''),
                                email: String(raw.email || ''),
                            };
                        }

                        function gffcOnManualFflLicenseChange() {
                            // If the user types a license manually, treat it as overriding any selected record.
                            window.gffcSelectedFFL = null;
                            gffcSetHtml('gffc_ffl_selected', '');
                        }

                        function gffcClearSelectedFFL() {
                            window.gffcSelectedFFL = null;
                            window.gffcFflSearchResults = [];
                            const lic = document.getElementById('gffc_ffl_license_number');
                            if (lic) lic.value = '';
                            gffcSetHtml('gffc_ffl_selected', '');
                            gffcSetHtml('gffc_ffl_results', '');
                        }

                        function gffcSelectFFL(index) {
                            const raw = (window.gffcFflSearchResults || [])[index];
                            const ffl = gffcNormalizeFfl(raw);
                            if (!ffl || !ffl.license_number) return;
                            window.gffcSelectedFFL = ffl;
                            const lic = document.getElementById('gffc_ffl_license_number');
                            if (lic) lic.value = ffl.license_number;

                            gffcSetHtml('gffc_ffl_selected', `
                                <div style="padding: 10px; border: 1px solid #e5e7eb; border-radius: 10px; background: #fff;">
                                    <div style="font-weight:700; margin-bottom:4px;">Selected FFL</div>
                                    <div style="font-family:monospace; margin-bottom:6px;">${ffl.license_number}</div>
                                    <div style="font-size:12px; color:#475569; line-height:1.3;">${gffcFormatFflDisplay(ffl)}</div>
                                </div>
                            `);
                            gffcSetHtml('gffc_ffl_results', '');
                        }

                        async function gffcSearchFFL() {
                            const zip = gffcGetElValue('gffc_ffl_zip').trim();
                            const radius = parseInt(gffcGetElValue('gffc_ffl_radius') || '25', 10);
                            const name = gffcGetElValue('gffc_ffl_name').trim();
                            const license = gffcGetElValue('gffc_ffl_license_number').trim();

                            if (!license && !/^\d{5}$/.test(zip)) {
                                alert('Please enter a valid 5-digit ZIP code or a License Number.');
                                return;
                            }
                            if (!gffcApiKey) {
                                alert('Missing Cockpit API key.');
                                return;
                            }

                            gffcSetHtml('gffc_ffl_results', '<div style="color:#64748b; font-size:12px;">Searching…</div>');
                            window.gffcFflSearchResults = [];

                            const payload = {
                                action: 'get_ffl_list',
                                data: {
                                    zipcode: zip,
                                    radius: isNaN(radius) ? 25 : radius,
                                    api_key: gffcApiKey,
                                }
                            };
                            if (name) payload.data.ffl_name = name;
                            if (license) payload.data.license_number = license;

                            try {
                                const resp = await fetch(gffcFflApiUrl, {
                                    method: 'POST',
                                    headers: {
                                        'Accept': 'application/json',
                                        'Content-Type': 'application/json',
                                        'x-api-key': gffcApiKey,
                                    },
                                    body: JSON.stringify(payload),
                                });

                                const data = await resp.json().catch(() => null);
                                if (!resp.ok) {
                                    throw new Error('FFL search failed: ' + resp.status);
                                }
                                if (!Array.isArray(data)) {
                                    throw new Error('Unexpected FFL search response');
                                }

                                window.gffcFflSearchResults = data;

                                if (!data.length) {
                                    gffcSetHtml('gffc_ffl_results', '<div style="color:#64748b; font-size:12px;">No FFLs found.</div>');
                                    return;
                                }

                                gffcSetHtml('gffc_ffl_results', `
                                    <div style="padding: 10px; border: 1px solid #e5e7eb; border-radius: 10px; background: #fff;">
                                        <div style="font-weight:700; margin-bottom:6px;">Search Results</div>
                                        <div style="overflow:auto; max-height: 260px;">
                                            <table style="width:100%; border-collapse: collapse; font-size: 12px;">
                                                <thead>
                                                    <tr style="background:#f8fafc;">
                                                        <th style="text-align:left; padding:6px; border-bottom:1px solid #e5e7eb;">FFL</th>
                                                        <th style="text-align:left; padding:6px; border-bottom:1px solid #e5e7eb;">Name / Address</th>
                                                        <th style="text-align:center; padding:6px; border-bottom:1px solid #e5e7eb; width:80px;">Select</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    ${data.map((raw, idx) => {
                                                        const ffl = gffcNormalizeFfl(raw) || {};
                                                        const lic = (ffl.license_number || '').replace(/</g, '&lt;');
                                                        return `
                                                            <tr>
                                                                <td style="padding:6px; border-bottom:1px solid #f1f5f9; font-family:monospace;">${lic}</td>
                                                                <td style="padding:6px; border-bottom:1px solid #f1f5f9; color:#475569; line-height:1.3;">${gffcFormatFflDisplay(ffl) || ''}</td>
                                                                <td style="padding:6px; border-bottom:1px solid #f1f5f9; text-align:center;"><button class="button" type="button" onclick="gffcSelectFFL(${idx})">Select</button></td>
                                                            </tr>
                                                        `;
                                                    }).join('')}
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                `);
                            } catch (e) {
                                gffcSetHtml('gffc_ffl_results', '<div style="color:#b91c1c; font-size:12px;">FFL search failed.</div>');
                                console.error(e);
                            }
                        }

                        async function gffcCheckout() {
                            const btn = document.getElementById('gffc_checkout_submit');
                            const status = document.getElementById('gffc_checkout_status');
                            if (status) status.textContent = '';

                            const type = (document.querySelector('input[name="gffc_order_type"]:checked') || {}).value || 'drop_ship';
                            const ship_to_store = type === 'ship_to_store';

                            const customer = {
                                name: gffcGetElValue('gffc_customer_name').trim(),
                                email: gffcGetElValue('gffc_customer_email').trim(),
                                phone: gffcGetElValue('gffc_customer_phone').trim(),
                                address1: gffcGetElValue('gffc_customer_address1').trim(),
                                address2: gffcGetElValue('gffc_customer_address2').trim(),
                                city: gffcGetElValue('gffc_customer_city').trim(),
                                state: gffcGetElValue('gffc_customer_state').trim(),
                                zip: gffcGetElValue('gffc_customer_zip').trim(),
                            };

                            const dest = (document.querySelector('input[name="gffc_shipping_dest"]:checked') || {}).value || 'customer';
                            const finalDest = ship_to_store ? 'store' : dest;
                            const cartOrderContext = (typeof gffcGetCartOrderContext === 'function') ? gffcGetCartOrderContext() : null;

                            let ffl = null;
                            
                            if (!customer.name) {
                                alert('Customer Name is required.');
                                return;
                            }

                            if (!ship_to_store) {
                                // 1. Check FFL Requirement vs Destination
                                if (window.gffcCartHasFirearm && dest === 'customer') {
                                    alert('Your cart contains items requiring FFL. Please select "FFL" or "Mixed" shipping.');
                                    return;
                                }

                                // 2. Validate Address
                                if (dest === 'customer' || dest === 'mixed') {
                                    if (!customer.address1 || !customer.city || !customer.state || !customer.zip) {
                                        alert('Customer Address is required.');
                                        return;
                                    }
                                }

                                // 3. Validate FFL
                                if (dest === 'ffl' || dest === 'mixed') {
                                    // Require contact info for FFL orders
                                    if (!customer.phone || !customer.email) {
                                        alert('Customer Phone and Email are required for FFL orders.');
                                        return;
                                    }

                                    if (window.gffcSelectedFFL && window.gffcSelectedFFL.license_number) {
                                        ffl = window.gffcSelectedFFL;
                                    }

                                    if (!ffl || !ffl.license_number) {
                                        alert('Please search for and select an FFL.');
                                        return;
                                    }
                                }
                            }

                            // Fetch Cart Items for Preview
                            let cartItems = [];
                            try {
                                if (btn) btn.disabled = true;
                                if (status) status.textContent = 'Preparing confirmation...';
                                
                                const cartData = await gffcCartApi('/cart');
                                cartItems = cartData.cart.items || [];
                            } catch (e) {
                                alert('Failed to fetch cart for preview: ' + e.message);
                                if (btn) btn.disabled = false;
                                if (status) status.textContent = '';
                                return;
                            } finally {
                                if (btn) btn.disabled = false;
                                if (status) status.textContent = '';
                            }

                            if (cartItems.length === 0) {
                                alert('Cart is empty.');
                                return;
                            }

                            // Fetch Payload Preview from Server
                            let payloadPreview = {};
                            try {
                                if (btn) btn.disabled = true;
                                if (status) status.textContent = 'Fetching preview...';
                                const previewPayload = {
                                    ship_to_store,
                                    destination: finalDest,
                                    customer,
                                    ffl: ffl || {},
                                    preview: true
                                };
                                if (cartOrderContext) {
                                    previewPayload.gunbroker_order_id = cartOrderContext.gunbroker_order_id;
                                }
                                
                                const previewResp = await gffcCartApi('/cart/checkout', previewPayload);
                                payloadPreview = previewResp.preview || {};
                                if (cartOrderContext) {
                                    if (!payloadPreview || typeof payloadPreview !== 'object') {
                                        payloadPreview = {};
                                    }
                                    if (!payloadPreview.data || typeof payloadPreview.data !== 'object') {
                                        payloadPreview.data = {};
                                    }
                                    payloadPreview.data.gunbroker_order_id = cartOrderContext.gunbroker_order_id;
                                }
                                
                                // Obfuscate API Key for display
                                if (payloadPreview.data && payloadPreview.data.api_key) {
                                    const k = payloadPreview.data.api_key;
                                    if (k.length > 8) {
                                        payloadPreview.data.api_key = k.substring(0, 4) + '...' + k.substring(k.length - 4);
                                    } else {
                                        payloadPreview.data.api_key = '***';
                                    }
                                }
                            } catch (e) {
                                alert('Failed to fetch preview: ' + e.message);
                                if (btn) btn.disabled = false;
                                if (status) status.textContent = '';
                                return;
                            } finally {
                                if (btn) btn.disabled = false;
                                if (status) status.textContent = '';
                            }

                            // Build Confirmation HTML
                            const contentDiv = document.getElementById('gffcConfirmationContent');
                            
                            let html = `
                                <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #e2e8f0;">
                                    <div>
                                        <h3 style="margin: 0 0 8px 0; font-size: 15px; color: #1e293b;">Customer</h3>
                                        <div style="font-size: 13px; color: #475569;">
                                            <div style="font-weight:600; color:#0f172a; margin-bottom:2px;">${customer.name || 'N/A'}</div>
                                            ${!ship_to_store ? `<div style="margin-bottom:4px; line-height:1.3;">${customer.address1}<br>${customer.city}, ${customer.state} ${customer.zip}</div>` : ''}
                                            ${customer.email ? `<div style="margin-bottom:1px;">${customer.email}</div>` : ''}
                                            ${customer.phone ? `<div style="margin-bottom:1px;">${customer.phone}</div>` : ''}
                                        </div>
                                    </div>
                                    <div>
                                        <h3 style="margin: 0 0 8px 0; font-size: 15px; color: #1e293b;">Order Details</h3>
                                        <div style="font-size: 13px; color: #475569;">
                                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                <span style="color:#64748b;">Type:</span>
                                                <span style="font-weight:600; color:#0f172a;">${ship_to_store ? 'Ship to Store' : 'Drop Ship'}</span>
                                            </div>
                                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                <span style="color:#64748b;">Destination:</span>
                                                <span style="font-weight:600; color:#0f172a;">${ship_to_store ? 'Store' : (dest === 'customer' ? 'Customer Address' : (dest === 'ffl' ? 'FFL' : (dest === 'mixed' ? 'Mixed (Both)' : dest)))}</span>
                                            </div>
                                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                <span style="color:#64748b;">Items:</span>
                                                <span style="font-weight:600; color:#0f172a;">${cartItems.length}</span>
                                            </div>
                                            ${cartOrderContext ? `
                                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                <span style="color:#64748b;">Order Source:</span>
                                                <span style="font-weight:600; color:#0f172a;">GunBroker</span>
                                            </div>
                                            <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                <span style="color:#64748b;">GunBroker Order:</span>
                                                <span style="font-weight:600; color:#0f172a; font-family:monospace;">${cartOrderContext.gunbroker_order_id}</span>
                                            </div>` : ''}
                                        </div>
                                    </div>
                                </div>
                            `;

                            if (ffl) {
                                html += `
                                    <div style="margin-bottom: 16px; padding: 12px; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;">
                                        <h3 style="margin: 0 0 8px 0; font-size: 15px; color: #1e293b;">FFL Information</h3>
                                        <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 13px; color: #475569;">
                                            <div>
                                                ${ffl.name ? `
                                                <div style="margin-bottom: 4px;">
                                                    <span style="font-weight:600; color:#0f172a;">${ffl.name}</span>
                                                </div>` : ''}
                                                ${(ffl.address || ffl.city) ? `
                                                <div style="line-height:1.3;">
                                                    ${ffl.address ? ffl.address + '<br>' : ''}
                                                    ${[ffl.city, ffl.state].filter(Boolean).join(', ')} ${ffl.zip || ''}
                                                </div>` : ''}
                                            </div>
                                            <div>
                                                <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                    <span style="color:#64748b;">License:</span>
                                                    <span style="font-family:monospace; font-weight:600; color:#0f172a;">${ffl.license_number}</span>
                                                </div>
                                                ${ffl.phone ? `
                                                <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                    <span style="color:#64748b;">Phone:</span>
                                                    <span style="font-weight:600; color:#0f172a;">${ffl.phone}</span>
                                                </div>` : ''}
                                                ${ffl.email ? `
                                                <div style="display:flex; justify-content:space-between; margin-bottom:4px;">
                                                    <span style="color:#64748b;">Email:</span>
                                                    <span style="font-weight:600; color:#0f172a;">${ffl.email}</span>
                                                </div>` : ''}
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }

                            html += `
                                <div style="margin-bottom: 16px;">
                                    <h3 style="margin: 0 0 8px 0; font-size: 15px; color: #1e293b;">Items</h3>
                                    <div style="border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;">
                                        <table class="widefat striped" style="width:100%; border:none; box-shadow:none;">
                                            <thead>
                                                <tr style="background:#f1f5f9;">
                                                    <th style="color:#475569; font-weight:600;">Distributor</th>
                                                    <th style="color:#475569; font-weight:600;">SKU</th>
                                                    <th style="color:#475569; font-weight:600;">UPC</th>
                                                    <th style="color:#475569; font-weight:600; text-align:center;">Qty</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                ${cartItems.map(it => `
                                                    <tr>
                                                        <td style="color:#334155;">${it.distid}</td>
                                                        <td style="color:#334155; font-family:monospace;">${it.distsku}</td>
                                                        <td style="color:#334155; font-family:monospace;">${it.upc}</td>
                                                        <td style="color:#334155; text-align:center;">${it.qty}</td>
                                                    </tr>
                                                `).join('')}
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            `;

                            html += `
                                <div>
                                    <h3 style="margin: 0 0 6px 0; font-size: 13px; color: #64748b;">Payload Preview</h3>
                                    <pre style="background: #1e293b; color: #e2e8f0; padding: 12px; overflow: auto; max-height: 150px; font-size: 11px; border-radius: 6px; font-family: 'Menlo', 'Monaco', monospace;">${JSON.stringify(payloadPreview, null, 2)}</pre>
                                </div>
                            `;

                            contentDiv.innerHTML = html;

                            // Show Modal and Bind Confirm Button
                            const modal = document.getElementById('gffcCheckoutConfirmationModal');
                            const confirmBtn = document.getElementById('gffcConfirmOrderBtn');
                            
                            modal.style.display = 'flex';

                            // Remove old listeners to avoid duplicates
                            const newConfirmBtn = confirmBtn.cloneNode(true);
                            confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);
                            
                            newConfirmBtn.addEventListener('click', async () => {
                                const contentDiv = document.getElementById('gffcConfirmationContent');
                                const originalContent = contentDiv.innerHTML;
                                
                                try {
                                    if (btn) btn.disabled = true;
                                    if (status) status.textContent = 'Submitting order…';
                                    
                                    // Show loading state
                                    contentDiv.innerHTML = '<div style="padding: 40px; text-align: center; color: #64748b;"><div class="spinner is-active" style="float:none; margin: 0 auto 10px;"></div>Submitting order to distributors...</div>';
                                    newConfirmBtn.disabled = true;
                                    const checkoutPayload = {
                                        ship_to_store,
                                        destination: finalDest,
                                        customer,
                                        ffl: ffl || {},
                                    };
                                    if (cartOrderContext) {
                                        checkoutPayload.gunbroker_order_id = cartOrderContext.gunbroker_order_id;
                                    }

                                    const data = await gffcCartApi('/cart/checkout', checkoutPayload);

                                    // Check for business logic failure in the response
                                    const result = data.result || {};
                                    const checkoutError = (() => {
                                        if (!result || typeof result !== 'object') return '';
                                        const direct = result.Error || result.error || result.message;
                                        if (typeof direct === 'string' && direct.trim()) return direct.trim();
                                        const nested = result.result && (result.result.Error || result.result.error || result.result.message);
                                        if (typeof nested === 'string' && nested.trim()) return nested.trim();
                                        return '';
                                    })();
                                    // If status is explicitly false, treat as failure even if HTTP was 200
                                    if (result.status === false || !!checkoutError) {
                                        if (status) status.textContent = 'Checkout failed.';
                                        
                                        let ordersHtml = '';
                                        let orders = result.fulfillment_orders;
                                        if (typeof orders === 'string') {
                                            try { orders = JSON.parse(orders); } catch(e) {}
                                        }

                                        if (Array.isArray(orders) && orders.length > 0) {
                                            ordersHtml += `
                                                <div style="margin-bottom: 15px;">
                                                    <h4 style="margin-top:0;">Fulfillment Orders</h4>
                                                    <table style="width:100%; border-collapse: collapse; font-size: 12px;">
                                                        <thead>
                                                            <tr style="background:#eeeeee; color:#6b7280; text-align:left;">
                                                                <th style="padding: 5px; border: 1px solid #e5e7eb;">Dist</th>
                                                                <th style="padding: 5px; border: 1px solid #e5e7eb;">Order ID</th>
                                                                <th style="padding: 5px; border: 1px solid #e5e7eb;">Order Details</th>
                                                                <th style="padding: 5px; border: 1px solid #e5e7eb;">Ordered</th>
                                                                <th style="padding: 5px; border: 1px solid #e5e7eb;">Status</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                            `;
                                            
                                            orders.forEach(order => {
                                                // Dist Logo
                                                const distLogo = `<img src="${get_distributor_logo(order.distid)}" style="max-width: 40px;" onerror="this.style.display='none';"/>`;
                                                
                                                // Order Details (Nested Table)
                                                let orderDetails = `<span style="font-size:8pt;">PO: ${order.po_number || ''}</span>`;
                                                if (order.dist_order_items) {
                                                    let items = order.dist_order_items;
                                                    if (typeof items === 'string') {
                                                        try { items = JSON.parse(items); } catch(e) {}
                                                    }
                                                    if (Array.isArray(items)) {
                                                        orderDetails += `<table style="width:95%; margin:5px; border: 1px solid #e5e7eb; font-size:8pt;">
                                                            <tr style="background:#dddddd;"><td>SKU</td><td>UPC</td><td>QTY</td></tr>`;
                                                        items.forEach(item => {
                                                            orderDetails += `<tr><td>${item.distsku}</td><td>${item.upc}</td><td>${item.qty}</td></tr>`;
                                                        });
                                                        orderDetails += `</table>`;
                                                    }
                                                }

                                                // Ship to store icon
                                                const shipToStore = order.ship_to_store ? `&nbsp;<img title="Shipped to Store" width="20" src="${imageBaseUrl}store.png"/>` : '';

                                                ordersHtml += `
                                                    <tr>
                                                        <td style="padding: 5px; border: 1px solid #e5e7eb; text-align:center;">${distLogo}</td>
                                                        <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.distributor_order_id || ''}${shipToStore}</td>
                                                        <td style="padding: 5px; border: 1px solid #e5e7eb;">${orderDetails}</td>
                                                        <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.order_date || ''}</td>
                                                        <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.order_status || ''}</td>
                                                    </tr>
                                                `;
                                            });
                                            
                                            ordersHtml += `
                                                        </tbody>
                                                    </table>
                                                </div>
                                            `;
                                        }

                                        contentDiv.innerHTML = `
                                            <div style="padding: 10px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 6px; color: #991b1b; margin-bottom: 15px;">
                                                <strong>Checkout Failed</strong><br/>
                                                ${checkoutError || result.Error || 'Order submission failed.'}
                                            </div>
                                            ${ordersHtml}
                                            <div>
                                                <h4 style="margin-top:0;">Server Response</h4>
                                                <pre style="background: #f8fafc; padding: 10px; overflow: auto; max-height: 300px; font-size: 11px; border: 1px solid #e2e8f0;">${JSON.stringify(data, null, 2)}</pre>
                                            </div>
                                            <div style="margin-top:10px; font-size:12px;">
                                                <a href="#" onclick="return false;" id="gffcRetryLink">Return to Preview</a>
                                            </div>
                                        `;
                                        
                                        const retryLink = document.getElementById('gffcRetryLink');
                                        if (retryLink) {
                                            retryLink.onclick = () => {
                                                contentDiv.innerHTML = originalContent;
                                                newConfirmBtn.disabled = false;
                                            };
                                        }
                                        
                                        newConfirmBtn.disabled = false;
                                        return;
                                    }

                                    if (status) status.textContent = 'Order submitted.';
                                    // refresh cart (cart clears on success server-side)
                                    gffcRefreshCartUI();
                                    
                                    // Calculate fulfillment status
                                    let totalRequested = cartItems.reduce((sum, item) => sum + (parseInt(item.qty) || 0), 0);
                                    let totalFulfilled = 0;
                                    
                                    let orders = result.fulfillment_orders;
                                    if (typeof orders === 'string') {
                                        try { orders = JSON.parse(orders); } catch(e) {}
                                    }
                                    
                                    let ordersHtml = '';
                                    const imgBase = window.imageBaseUrl || '';

                                    if (Array.isArray(orders) && orders.length > 0) {
                                        orders.forEach(o => {
                                            let items = o.dist_order_items;
                                            if (typeof items === 'string') {
                                                try { items = JSON.parse(items); } catch(e) {}
                                            }
                                            if (Array.isArray(items)) {
                                                totalFulfilled += items.reduce((sum, item) => sum + (parseInt(item.qty) || 0), 0);
                                            }
                                        });

                                        ordersHtml += `
                                            <div style="margin-bottom: 15px;">
                                                <h4 style="margin-top:0;">Fulfillment Orders</h4>
                                                <table style="width:100%; border-collapse: collapse; font-size: 12px;">
                                                    <thead>
                                                        <tr style="background:#eeeeee; color:#6b7280; text-align:left;">
                                                            <th style="padding: 5px; border: 1px solid #e5e7eb;">Dist</th>
                                                            <th style="padding: 5px; border: 1px solid #e5e7eb;">Order ID</th>
                                                            <th style="padding: 5px; border: 1px solid #e5e7eb;">Order Details</th>
                                                            <th style="padding: 5px; border: 1px solid #e5e7eb;">Ordered</th>
                                                            <th style="padding: 5px; border: 1px solid #e5e7eb;">Status</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                        `;
                                        
                                        orders.forEach(order => {
                                            // Dist Logo
                                            const distLogo = `<img src="${get_distributor_logo(order.distid)}" style="max-width: 40px;" onerror="this.style.display='none';"/>`;
                                            
                                            // Order Details (Nested Table)
                                            let orderDetails = `<span style="font-size:8pt;">PO: ${order.po_number || ''}</span>`;
                                            if (order.dist_order_items) {
                                                let items = order.dist_order_items;
                                                if (typeof items === 'string') {
                                                    try { items = JSON.parse(items); } catch(e) {}
                                                }
                                                if (Array.isArray(items)) {
                                                    orderDetails += `<table style="width:95%; margin:5px; border: 1px solid #e5e7eb; font-size:8pt;">
                                                        <tr style="background:#dddddd;"><td>SKU</td><td>UPC</td><td>QTY</td></tr>`;
                                                    items.forEach(item => {
                                                        orderDetails += `<tr><td>${item.distsku}</td><td>${item.upc}</td><td>${item.qty}</td></tr>`;
                                                    });
                                                    orderDetails += `</table>`;
                                                }
                                            }

                                            // Ship to store icon
                                            const shipToStore = order.ship_to_store ? `&nbsp;<img title="Shipped to Store" width="20" src="${imgBase}store.png"/>` : '';

                                            ordersHtml += `
                                                <tr>
                                                    <td style="padding: 5px; border: 1px solid #e5e7eb; text-align:center;">${distLogo}</td>
                                                    <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.distributor_order_id || ''}${shipToStore}</td>
                                                    <td style="padding: 5px; border: 1px solid #e5e7eb;">${orderDetails}</td>
                                                    <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.order_date || ''}</td>
                                                    <td style="padding: 5px; border: 1px solid #e5e7eb;">${order.order_status || ''}</td>
                                                </tr>
                                            `;
                                        });
                                        
                                        ordersHtml += `
                                                    </tbody>
                                                </table>
                                            </div>
                                        `;
                                    }

                                    const isFullyFulfilled = totalFulfilled >= totalRequested;
                                    const fulfillmentStatusHtml = isFullyFulfilled 
                                        ? '<div style="margin-top:5px; font-size:13px; color: #166534;"><strong>Status:</strong> Fully Fulfilled</div>'
                                        : `<div style="margin-top:5px; font-size:13px; color: #ca8a04;"><strong>Status:</strong> Partially Fulfilled (${totalFulfilled}/${totalRequested} items)</div>`;

                                    // Show success response
                                    contentDiv.innerHTML = `
                                        <div style="padding: 10px; background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 6px; color: #166534; margin-bottom: 15px;">
                                            <strong>Order Submitted Successfully!</strong>
                                            ${fulfillmentStatusHtml}
                                        </div>
                                        ${ordersHtml}
                                        <div>
                                            <h4 style="margin-top:0;">Server Response</h4>
                                            <pre style="background: #f8fafc; padding: 10px; overflow: auto; max-height: 300px; font-size: 11px; border: 1px solid #e2e8f0;">${JSON.stringify(data, null, 2)}</pre>
                                        </div>
                                    `;
                                    
                                    // Change button to Close
                                    newConfirmBtn.textContent = 'Close';
                                    newConfirmBtn.disabled = false;
                                    
                                    // Replace button to change action to close
                                    const closeBtn = newConfirmBtn.cloneNode(true);
                                    newConfirmBtn.parentNode.replaceChild(closeBtn, newConfirmBtn);
                                    closeBtn.addEventListener('click', () => {
                                        modal.style.display = 'none';
                                        // Reset button text for next time
                                        closeBtn.textContent = 'Submit Order';
                                    });

                                } catch (e) {
                                    if (status) status.textContent = 'Checkout failed.';
                                    contentDiv.innerHTML = `
                                        <div style="padding: 10px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 6px; color: #991b1b; margin-bottom: 15px;">
                                            <strong>Checkout Failed</strong><br/>
                                            ${e.message || 'Unknown error'}
                                        </div>
                                        <div style="margin-top:10px; font-size:12px;">
                                            <a href="#" onclick="return false;" id="gffcRetryLink">Return to Preview</a>
                                        </div>
                                    `;
                                    
                                    const retryLink = document.getElementById('gffcRetryLink');
                                    if (retryLink) {
                                        retryLink.onclick = () => {
                                            contentDiv.innerHTML = originalContent;
                                            newConfirmBtn.disabled = false;
                                        };
                                    }
                                    
                                    newConfirmBtn.disabled = false;
                                } finally {
                                    if (btn) btn.disabled = false;
                                }
                            });
                        }

                        function gffcBuildCartItemFromGridRow(row) {
                            // Row cell mapping from renderProductGrid() server mapping. Keep this in sync with the grid's data array.
                            // NOTE: Some restricted/filtered catalog responses may omit or shift hidden columns.
                            // We defensively read product_class fields from multiple possible cell positions.
                            const safeCell = (idx) => (row && row.cells && row.cells[idx]) ? row.cells[idx].data : undefined;

                            const productClass = safeCell(13) ?? safeCell(14); // expected: 13
                            const productClassDesc = safeCell(14) ?? safeCell(13); // expected: 14

                            return {
                                distid: safeCell(0),
                                distsku: safeCell(1),
                                images: safeCell(2) || [],
                                name: safeCell(3),
                                mfg_name: safeCell(4),
                                upc: safeCell(5),
                                mpn: safeCell(6),
                                qty_on_hand: safeCell(7) || 0,
                                unit_price: safeCell(8) || 0,
                                shipping_cost: safeCell(9) || 0,
                                total_cost: safeCell(10) || 0,
                                map_price: safeCell(11) || 0,
                                msrp: safeCell(12) || 0,
                                product_class: productClass,
                                product_class_description: productClassDesc,
                                category: safeCell(15),
                                drop_ship_flg: safeCell(16),
                                product_url: safeCell(17),
                                permalink: safeCell(18),
                                qty: 1,
                                ffl_req: safeCell(21),
                            };
                        }

                        function gffcEncodeItemPayload(item) {
                            // Use base64 so the value is safe inside HTML attributes and can't break template literals.
                            try {
                                const json = JSON.stringify(item || {});
                                return btoa(unescape(encodeURIComponent(json)));
                            } catch (e) {
                                return '';
                            }
                        }

                        // Helpers to open/close the Add-to-Cart inline qty controls.
                        function _gffcAddSetState(wrap, state) {
                            if (!wrap) return;
                            wrap.setAttribute('data-gffc-add-state', state);
                            const toggle = wrap.querySelector('.gffc-add-toggle');
                            const qtyInput = wrap.querySelector('[data-gffc-cart-qty-input="1"]');
                            const confirm = wrap.querySelector('.gffc-add-confirm');
                            if (state === 'open') {
                                if (toggle) toggle.style.display = 'none';
                                if (qtyInput) qtyInput.style.display = '';
                                if (confirm) confirm.style.display = '';
                            } else {
                                if (toggle) toggle.style.display = '';
                                if (qtyInput) { qtyInput.style.display = 'none'; qtyInput.value = 1; }
                                if (confirm) confirm.style.display = 'none';
                            }
                        }
                        function _gffcAddCloseAll(except) {
                            document.querySelectorAll('.gffc-add-wrap[data-gffc-add-state="open"]').forEach(function (w) {
                                if (w !== except) _gffcAddSetState(w, 'closed');
                            });
                        }

                        // Delegated handler for the "Add" trigger — expands the wrap to show qty + confirm.
                        document.addEventListener('click', function (e) {
                            const trigger = e.target && e.target.closest ? e.target.closest('.gffc-add-toggle') : null;
                            if (!trigger) return;
                            const wrap = trigger.closest('.gffc-add-wrap');
                            if (!wrap) return;
                            e.preventDefault();
                            _gffcAddCloseAll(wrap);
                            _gffcAddSetState(wrap, 'open');
                            const qtyInput = wrap.querySelector('[data-gffc-cart-qty-input="1"]');
                            if (qtyInput) { qtyInput.focus(); qtyInput.select(); }
                        });

                        // Click-away: clicking anywhere outside an open wrap collapses it back.
                        document.addEventListener('click', function (e) {
                            if (!e.target) return;
                            const inWrap = e.target.closest ? e.target.closest('.gffc-add-wrap') : null;
                            _gffcAddCloseAll(inWrap);
                        });

                        // Escape key: close all open wraps.
                        document.addEventListener('keydown', function (e) {
                            if (e.key === 'Escape') _gffcAddCloseAll(null);
                        });

                        // Delegated handler for Add-to-Cart buttons rendered inside Grid.js HTML.
                        document.addEventListener('click', function (e) {
                            const btn = e.target && e.target.closest ? e.target.closest('[data-gffc-add-to-cart="1"]') : null;
                            if (!btn) return;
                            e.preventDefault();

                            try {
                                const payload = btn.getAttribute('data-item');
                                const json = payload ? decodeURIComponent(escape(atob(payload))) : '';
                                const item = json ? JSON.parse(json) : null;
                                if (!item) throw new Error('Missing item payload');

                                // Read qty from sibling input; clamp 1..qty_on_hand. The input is
                                // rendered next to the button by both the card and grid renderers.
                                const qtyInput = btn.parentElement
                                    ? btn.parentElement.querySelector('[data-gffc-cart-qty-input="1"]')
                                    : null;
                                if (qtyInput) {
                                    const maxQty = Math.max(1, Number(qtyInput.max || item.qty_on_hand || 1));
                                    let requested = parseInt(qtyInput.value, 10);
                                    if (!Number.isFinite(requested) || requested < 1) requested = 1;
                                    if (requested > maxQty) requested = maxQty;
                                    qtyInput.value = requested;
                                    item.qty = requested;
                                }
                                (async () => {
                                    try {
                                        const data = await gffcCartApi('/cart/add', { item });
                                        gffcUpdateCartBadge(data.summary);
                                        
                                        // Visual feedback on button
                                        const originalHtml = btn.innerHTML;
                                        const originalBg = btn.style.backgroundColor;
                                        const originalBorder = btn.style.borderColor;
                                        const originalColor = btn.style.color;
                                        
                                        btn.innerHTML = '<i class="fas fa-check"></i> Added!';
                                        btn.style.backgroundColor = '#10b981'; // Green
                                        btn.style.borderColor = '#10b981';
                                        btn.style.color = '#ffffff';
                                        btn.disabled = true;

                                        // Reset qty input back to 1 so the next add doesn't repeat the chosen quantity by accident.
                                        if (qtyInput) qtyInput.value = 1;

                                        // Collapse the qty input/confirm back to the single "Add" trigger after a short pause.
                                        const wrap = btn.closest ? btn.closest('.gffc-add-wrap') : null;

                                        setTimeout(() => {
                                            btn.innerHTML = originalHtml;
                                            btn.style.backgroundColor = originalBg;
                                            btn.style.borderColor = originalBorder;
                                            btn.style.color = originalColor;
                                            btn.disabled = false;
                                            if (wrap) _gffcAddSetState(wrap, 'closed');
                                        }, 2000);
                                    } catch (err) {
                                        alert('Failed to add to cart: ' + err.message);
                                    }
                                })();
                            } catch (err) {
                                alert('Failed to add to cart: ' + err.message);
                            }
                        });

                        // When the Cart tab is opened, fetch and render cart contents.
                        // (DOMContentLoaded might fire before the Cart tab is ever shown.)
                        document.addEventListener('click', function (e) {
                            const tabBtn = e.target && e.target.closest ? e.target.closest('#gffc_cart_tab_btn') : null;
                            if (!tabBtn) return;
                            // let openTab run first, then render
                            setTimeout(() => {
                                gffcRefreshCartUI();
                            }, 0);
                        });
                        
                        function get_distributor_logo(code){
                            if (code == "ZND"){
                                return imageBaseUrl + "distributor_logo_zanders.jpeg";
                            }else if (code == "2AW"){
                                return imageBaseUrl + "distributor_logo_2AW.png";
                            }else if (code == "CSSI"){
                                return imageBaseUrl + "distributor_logo_CSSI.png";
                            }else if (code == "DAV"){
                                return imageBaseUrl + "distributor_logo_davidsons.jpeg";
                            }else if (code == "LIP"){
                                return imageBaseUrl + "distributor_logo_lipseys.jpeg";
                            }else if (code == "RSR"){
                                return imageBaseUrl + "distributor_logo_RSR.png";
                            }else if (code == "TSW"){
                                return imageBaseUrl + "distributor_logo_sports_south.png";
                            }else{
                                return imageBaseUrl + "distributor_logo_" + code + ".png";
                            }
                            return "";
                        }
                        
                        function renderPriceComparisonChart(products) {
                            const chartContainer = document.getElementById('g_ffl_cockpit_price_comparison_chart');
                            chartContainer.innerHTML = '';
                            
                            if (!products || products.length === 0) return;

                            const ignoreShipping = gffcUpcIsIgnoreShippingEnabled();

                            const isMobileChart = !!(window.matchMedia && window.matchMedia('(max-width: 768px)').matches);
                            
                            // Find maximum total cost for scaling
                            const totalCosts = products.map(p => gffcUpcGetEffectiveTotal(p)).filter(p => p > 0);
                            const maxTotal = Math.max(...totalCosts, 1);
                            const minTotal = Math.min(...totalCosts);
                            
                            // Find best available (lowest price among in-stock products)
                            const inStockProducts = products.filter(p => (p.qty_on_hand || 0) > 0);
                            const inStockCosts = inStockProducts.map(p => gffcUpcGetEffectiveTotal(p)).filter(p => p > 0);
                            const minInStockTotal = inStockCosts.length > 0 ? Math.min(...inStockCosts) : null;

                            // Mobile-only: horizontal bar list for readability (no horizontal scroll)
                            if (isMobileChart) {
                                let chartHTML = `
                                    <div class="gffc-upc-chart" style="background: white; padding: 14px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                        <div class="gffc-upc-chart-legend" style="display: flex; gap: 16px; align-items: center; margin-bottom: 12px; font-size: 12px; color: #666; flex-wrap: wrap;">
                                            <div style="display: flex; align-items: center; gap: 6px;">
                                                <div style="width: 12px; height: 12px; background: #4a90e2; border-radius: 2px;"></div>
                                                <span>Unit</span>
                                            </div>
                                            <div style="display: flex; align-items: center; gap: 6px;">
                                                <div style="width: 12px; height: 12px; background: #ff6b6b; border-radius: 2px;"></div>
                                                <span>Ship${ignoreShipping ? ' (ignored)' : ''}</span>
                                            </div>
                                            <div style="font-weight: 600; color: #2ecc71;">★ Best</div>
                                        </div>

                                        <div class="gffc-upc-mlist" aria-label="Price comparison list">
                                `;

                                products.forEach((product) => {
                                    const totalCost = gffcUpcGetEffectiveTotal(product);
                                    const unitPrice = product.unit_price || 0;
                                    const shippingCost = gffcUpcGetEffectiveShipping(product);
                                    const quantity = product.qty_on_hand || 0;
                                    const inStock = quantity > 0;
                                    const isBestAvailable = inStock && minInStockTotal && totalCost === minInStockTotal && totalCost > 0;

                                    // Bar widths as percent of the longest total
                                    const totalPercent = maxTotal > 0 ? (totalCost / maxTotal) * 100 : 0;
                                    const unitOfTotal = totalCost > 0 ? (unitPrice / totalCost) * totalPercent : totalPercent;
                                    const shipOfTotal = totalCost > 0 ? (shippingCost / totalCost) * totalPercent : 0;

                                    const dotColor = inStock ? '#2ecc71' : '#ff6b6b';
                                    const stockText = inStock ? (quantity + ' in stock') : 'Out of stock';
                                    const rowBorder = isBestAvailable ? '2px solid #2ecc71' : '1px solid #e1e5e9';
                                    const rowBg = isBestAvailable ? '#f0fdf4' : '#fff';

                                    chartHTML += `
                                        <div class="gffc-upc-mlist-item" style="display:flex;align-items:center;gap:10px;padding:10px;border:${rowBorder};border-radius:8px;background:${rowBg};margin-bottom:8px;">
                                            <div style="width:48px;height:32px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                                                <img src="${get_distributor_logo(product.distid)}" style="max-width:48px;max-height:32px;object-fit:contain;" onerror="this.style.display='none';">
                                            </div>
                                            <div style="flex:1;min-width:0;">
                                                <div style="display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:5px;">
                                                    <div style="display:flex;align-items:center;gap:6px;font-size:11px;">
                                                        <span style="width:7px;height:7px;border-radius:50%;background:${dotColor};display:inline-block;"></span>
                                                        <span style="color:${dotColor};font-weight:600;">${stockText}</span>
                                                        ${isBestAvailable ? '<span style="font-size:10px;font-weight:700;color:#fff;background:#2ecc71;padding:1px 6px;border-radius:8px;">BEST ★</span>' : ''}
                                                    </div>
                                                    <div style="font-size:15px;font-weight:800;color:${isBestAvailable ? '#2ecc71' : '#1e293b'};white-space:nowrap;">$${totalCost.toFixed(2)}</div>
                                                </div>
                                                <div title="Unit $${unitPrice.toFixed(2)} | Ship $${shippingCost.toFixed(2)}" style="position:relative;background:#f1f5f9;height:14px;border-radius:7px;overflow:hidden;">
                                                    <div style="position:absolute;top:0;left:0;height:100%;width:${unitOfTotal}%;background:#4a90e2;"></div>
                                                    <div style="position:absolute;top:0;left:${unitOfTotal}%;height:100%;width:${shipOfTotal}%;background:#ff6b6b;"></div>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                                });

                                chartHTML += `
                                        </div>

                                        <div style="margin-top: 12px; padding: 10px; background: #f8f9fa; border-radius: 6px; border: 1px solid #e9ecef;">
                                            <div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; text-align: center;">
                                                <div>
                                                    <div style="font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 3px; font-weight: 600;">Range</div>
                                                    <div style="font-size: 13px; font-weight: 700; color: #333;">$${minTotal.toFixed(2)} - $${Math.max(...totalCosts).toFixed(2)}</div>
                                                </div>
                                                <div>
                                                    <div style="font-size: 10px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 3px; font-weight: 600;">Options</div>
                                                    <div style="font-size: 13px; font-weight: 700; color: #333;">${products.length}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                `;

                                chartContainer.innerHTML = chartHTML;
                                return;
                            }
                            
                            let chartHTML = `
                                <div class="gffc-upc-chart" style="background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <div style="margin-bottom: 20px;">
                                        <h4 style="margin: 0 0 15px 0; color: #333; font-size: 18px; font-weight: 600;"></h4>
                                        <div class="gffc-upc-chart-legend" style="display: flex; gap: 20px; align-items: center; margin-bottom: 15px; font-size: 13px; color: #666;">
                                            <div style="display: flex; align-items: center; gap: 6px;">
                                                <div style="width: 12px; height: 12px; background: #4a90e2; border-radius: 2px;"></div>
                                                <span>Unit Price</span>
                                            </div>
                                            <div style="display: flex; align-items: center; gap: 6px;">
                                                <div style="width: 12px; height: 12px; background: #ff6b6b; border-radius: 2px;"></div>
                                                <span>Shipping Cost${ignoreShipping ? ' (ignored)' : ''}</span>
                                            </div>
                                            <div style="font-weight: 600; color: #2ecc71;">★ = Best Available</div>
                                        </div>
                                    </div>
                                    
                                    <div style="display: flex; flex-direction: column; gap: 8px;">
                            `;
                            
                            products.forEach((product, index) => {
                                const totalCost = gffcUpcGetEffectiveTotal(product);
                                const unitPrice = product.unit_price || 0;
                                const shippingCost = gffcUpcGetEffectiveShipping(product);
                                const quantity = product.qty_on_hand || 0;
                                const inStock = quantity > 0;
                                const isBestAvailable = inStock && minInStockTotal && totalCost === minInStockTotal && totalCost > 0;
                                
                                // Determine border and background colors
                                let borderColor = '#e1e5e9';
                                let backgroundColor = '#fafbfc';
                                let badgeHTML = '';
                                
                                if (isBestAvailable) {
                                    borderColor = '#2ecc71';
                                    backgroundColor = '#f8fffe';
                                    badgeHTML = '<div style="position: absolute; top: -8px; left: 12px; background: #2ecc71; color: white; padding: 2px 8px; font-size: 10px; font-weight: 600; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.2);">BEST AVAILABLE ★</div>';
                                }
                                
                                // Calculate percentages for the stacked bar
                                const unitPercent = totalCost > 0 ? (unitPrice / totalCost) * 100 : 0;
                                const shippingPercent = totalCost > 0 ? (shippingCost / totalCost) * 100 : 0;
                                
                                // Calculate bar width relative to max cost
                                const barWidth = maxTotal > 0 ? (totalCost / maxTotal) * 100 : 0;

                                // Label placement: use effective segment width (relative to full container)
                                // so small shipping % can still render inside when the bar is long.
                                const shippingEffectiveWidth = (barWidth * shippingPercent) / 100;
                                const showShippingInside = shippingCost > 0 && shippingEffectiveWidth >= 8;
                                
                                chartHTML += `
                                    <div class="gffc-upc-chart-row" style="display: flex; align-items: center; gap: 12px; padding: 8px 12px; background: ${backgroundColor}; border: 2px solid ${borderColor}; border-radius: 6px; position: relative;">
                                        ${badgeHTML}
                                        
                                        <!-- Distributor Logo -->
                                        <div class="gffc-upc-chart-logo" style="flex-shrink: 0; width: 45px; text-align: center;">
                                            <img src="${get_distributor_logo(product.distid)}" style="max-width: 40px; max-height: 24px; object-fit: contain;" onerror="this.style.display='none';">
                                        </div>
                                        
                                        <!-- Stacked Bar Chart -->
                                        <div class="gffc-upc-chart-bar" style="flex: 1; min-width: 0;">
                                            <!-- Bar Container -->
                                            <div style="position: relative; background: #f5f6f7; height: 20px; overflow: hidden; border: 1px solid #ddd; border-radius: 3px;">
                                                <!-- Actual cost bar -->
                                                <div style="position: absolute; left: 0; top: 0; height: 100%; width: ${barWidth}%; display: flex; overflow: hidden; border-radius: 2px;">
                                                    <!-- Unit price section -->
                                                    <div style="background: #4a90e2; width: ${unitPercent}%; height: 100%; position: relative;">
                                                        ${unitPercent > 25 ? `<span style="position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); color: white; font-size: 10px; font-weight: 600;">$${unitPrice.toFixed(2)}</span>` : ''}
                                                    </div>
                                                    <!-- Shipping section -->
                                                    ${shippingCost > 0 ? `
                                                        <div style="background: #ff6b6b; width: ${shippingPercent}%; height: 100%; position: relative;">
                                                            ${showShippingInside ? `<span style="position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); color: white; font-size: 10px; font-weight: 600;">+$${shippingCost.toFixed(2)}</span>` : ''}
                                                        </div>
                                                    ` : ''}
                                                </div>
                                                
                                                <!-- Cost breakdown labels for smaller segments -->
                                                ${unitPercent <= 25 ? `<span style="position: absolute; left: 4px; top: 50%; transform: translateY(-50%); color: #555; font-size: 9px; font-weight: 600;">$${unitPrice.toFixed(2)}</span>` : ''}
                                                ${shippingCost > 0 && !showShippingInside ? `<span style="position: absolute; right: 4px; top: 50%; transform: translateY(-50%); color: #555; font-size: 9px; font-weight: 600;">+$${shippingCost.toFixed(2)}</span>` : ''}
                                            </div>
                                        </div>
                                        
                                        <!-- Total Cost -->
                                        <div class="gffc-upc-chart-total" style="flex-shrink: 0; width: 80px; text-align: right;">
                                            <span style="font-size: 14px; font-weight: 600; color: ${isBestAvailable ? '#2ecc71' : '#333'};">$${totalCost.toFixed(2)}</span>
                                        </div>
                                        
                                        <!-- Stock indicator -->
                                        <div class="gffc-upc-chart-stock" style="flex-shrink: 0; width: 40px; text-align: center;">
                                            <div style="display: flex; align-items: center; justify-content: center; gap: 4px;">
                                                <div style="width: 7px; height: 7px; border-radius: 50%; background: ${quantity > 0 ? '#2ecc71' : '#ff6b6b'};"></div>
                                                <span style="font-size: 11px; font-weight: 600; color: ${quantity > 0 ? '#2ecc71' : '#ff6b6b'};">
                                                    ${quantity > 0 ? quantity : 'Out'}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            });
                            
                            chartHTML += `
                                    </div>
                                    
                                    <!-- Summary Stats -->
                                    <div style="margin-top: 20px; padding: 16px; background: #f8f9fa; border-radius: 6px; border: 1px solid #e9ecef;">
                                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 20px; text-align: center;">
                                            <div>
                                                <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 6px; font-weight: 600;">Price Range</div>
                                                <div style="font-size: 15px; font-weight: 600; color: #333;">$${minTotal.toFixed(2)} - $${Math.max(...totalCosts).toFixed(2)}</div>
                                            </div>
                                            <div>
                                                <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 6px; font-weight: 600;">Potential Savings</div>
                                                <div style="font-size: 15px; font-weight: 600; color: #2ecc71;">$${(Math.max(...totalCosts) - minTotal).toFixed(2)}</div>
                                            </div>
                                            <div>
                                                <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; color: #666; margin-bottom: 6px; font-weight: 600;">Options</div>
                                                <div style="font-size: 15px; font-weight: 600; color: #333;">${products.length} Distributors</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                            
                            chartContainer.innerHTML = chartHTML;
                        }

                        // Keep cart UI in sync on initial load. Then, if the page was opened
                        // with ?open_tab=cart (e.g. via the "View Cart" link from an order's
                        // FFL Cockpit metabox), switch to the Cart tab once cart data is in.
                        document.addEventListener('DOMContentLoaded', function () {
                            (async function () {
                                await gffcRefreshCartUI();
                                try {
                                    var params = new URLSearchParams(window.location.search);
                                    if (params.get('open_tab') === 'cart') {
                                        var cartTab = document.getElementById('gffc_cart_tab_btn');
                                        if (cartTab) {
                                            // gffcUpdateCartBadge hides the cart tab when empty; force-show
                                            // so the click works even if the cart load is still in flight.
                                            cartTab.style.display = '';
                                            if (typeof window.openTab === 'function') {
                                                window.openTab({ currentTarget: cartTab, preventDefault: function(){} }, 'cart');
                                            } else {
                                                cartTab.click();
                                            }
                                            try {
                                                var url = new URL(window.location.href);
                                                url.searchParams.delete('open_tab');
                                                window.history.replaceState({}, document.title, url.toString());
                                            } catch (e) {}
                                        }
                                    }
                                } catch (e) {
                                    console.warn('open_tab=cart handling failed:', e);
                                }
                            })();
                        });
                        
                        function renderDistributorCards(products) {
                            const container = document.getElementById('g_ffl_cockpit_distributor_cards_container');
                            container.innerHTML = '';

                            const ignoreShipping = gffcUpcIsIgnoreShippingEnabled();
                            
                            // Find best available (lowest price among in-stock products)
                            const inStockProducts = products.filter(p => (p.qty_on_hand || 0) > 0);
                            const inStockCosts = inStockProducts.map(p => gffcUpcGetEffectiveTotal(p)).filter(p => p > 0);
                            const minInStockTotal = inStockCosts.length > 0 ? Math.min(...inStockCosts) : null;
                            
                            products.forEach((product, index) => {
                                const price = gffcUpcGetEffectiveTotal(product);
                                const shipping = product.shipping_cost || 0;
                                const unitPrice = product.unit_price || 0;
                                const mapPrice = product.map_price || 0;
                                const msrp = product.msrp || 0;
                                const qty = product.qty_on_hand || 0;
                                const inStock = qty > 0;
                                const isDropship = product.drop_ship_flg === 1;
                                const isBestAvailable = inStock && minInStockTotal && price === minInStockTotal && price > 0;

                                // Logic for Add to Cart button
                                const noOrderDistributors = ["MGE", "AMC", "CAM4", "CWS"];
                                const isFulfillable = !noOrderDistributors.includes(product.distid);
                                let addToCartBtn = '';
                                
                                if (gffcIsAdmin && qty > 0 && isFulfillable) {
                                        // Construct item payload
                                        const itemPayload = {
                                            distid: product.distid,
                                            distsku: product.distsku,
                                            images: JSON.parse(product.images || '[]'),
                                            name: product.name,
                                            mfg_name: product.mfg_name,
                                            upc: product.upc,
                                            mpn: product.mpn,
                                            qty_on_hand: product.qty_on_hand || 0,
                                            unit_price: product.unit_price || 0,
                                            shipping_cost: product.shipping_cost || 0,
                                            total_cost: product.total_cost || 0,
                                            map_price: product.map_price || 0,
                                            msrp: product.msrp || 0,
                                            product_class: product.product_class,
                                            product_class_description: product.product_class_description,
                                            category: product.item_gb_cat_name,
                                            drop_ship_flg: product.drop_ship_flg,
                                            product_url: product.product_url,
                                            permalink: product.permalink,
                                            qty: 1,
                                            ffl_req: product.ffl_req
                                        };
                                        
                                        addToCartBtn = `<span class="gffc-add-wrap" data-gffc-add-state="closed" style="flex: 1; min-width: 120px; display:inline-flex; gap:6px; align-items:center; height:36px;">
    <button type="button" class="gffc-btn-add gffc-add-toggle" style="flex:1; height:36px; white-space:nowrap;"><i class="fas fa-cart-plus"></i> Add</button>
    <input type="number" class="gffc-cart-qty-input" data-gffc-cart-qty-input="1" min="1" max="${qty}" value="1" title="Quantity" aria-label="Quantity to add to cart" style="display:none; width:56px; height:36px; padding:4px 6px; border:1px solid #ccc; border-radius:4px; box-sizing:border-box; font-size:13px; text-align:center;">
    <button type="button" class="gffc-btn-add gffc-add-confirm" data-gffc-add-to-cart="1" data-item="${gffcEncodeItemPayload(itemPayload)}" style="display:none; flex:1; height:36px; white-space:nowrap;"><i class="fas fa-check"></i> Add</button>
</span>`;
                                }
                                
                                const cardHTML = `
                                    <div style="
                                        background: white; 
                                        border-radius: 8px; 
                                        padding: 20px; 
                                        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                                        border: ${isBestAvailable ? '2px solid #2ecc71' : '1px solid #e1e5e9'};
                                        position: relative;
                                    ">
                                        ${isBestAvailable ? '<div style="position: absolute; top: -10px; left: 20px; background: #2ecc71; color: white; padding: 4px 12px; border-radius: 12px; font-size: 11px; font-weight: 600; box-shadow: 0 1px 3px rgba(0,0,0,0.2);">BEST AVAILABLE</div>' : ''}
                                        
                                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                                            <img src="${get_distributor_logo(product.distid)}" style="max-width: 100px;max-height: 40px; object-fit: contain;" onerror="this.style.display='none';">
                                            <div style="text-align: right;">
                                                <div style="font-size: 24px; font-weight: bold; color: #333;">$${price.toFixed(2)}</div>
                                                <div style="font-size: 12px; color: #666;">Total Cost</div>
                                            </div>
                                        </div>
                                        
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">
                                            <div>
                                                <div style="font-size: 12px; color: #666;">Unit Price</div>
                                                <div style="font-weight: bold;">$${unitPrice.toFixed(2)}</div>
                                            </div>
                                            <div>
                                                <div style="font-size: 12px; color: #666;">Shipping${ignoreShipping ? ' (ignored)' : ''}</div>
                                                <div style="font-weight: bold;">${shipping > 0 ? '$' + shipping.toFixed(2) : 'Free'}</div>
                                            </div>
                                            <div>
                                                <div style="font-size: 12px; color: #666;">MAP Price</div>
                                                <div style="font-weight: bold;">${mapPrice > 0 ? '$' + mapPrice.toFixed(2) : 'N/A'}</div>
                                            </div>
                                            <div>
                                                <div style="font-size: 12px; color: #666;">MSRP</div>
                                                <div style="font-weight: bold;">${msrp > 0 ? '$' + msrp.toFixed(2) : 'N/A'}</div>
                                            </div>
                                        </div>
                                        
                                        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">
                                            <div style="display: flex; align-items: center; gap: 5px;">
                                                <div style="
                                                    width: 10px; 
                                                    height: 10px; 
                                                    border-radius: 50%; 
                                                    background: ${inStock ? '#2ecc71' : '#e74c3c'};
                                                "></div>
                                                <span style="font-size: 14px; font-weight: 600;">
                                                    ${inStock ? `${qty} in stock` : 'Out of stock'}
                                                </span>
                                            </div>
                                            <div style="font-size: 12px; color: #666;">
                                                <strong>SKU:</strong> ${product.distsku || 'N/A'}
                                            </div>
                                        </div>
                                        
                                        <div style="display: flex; gap: 8px; flex-wrap: wrap;">
                                            ${product.product_url ? `
                                                <a href="${product.product_url}" target="_blank" style="
                                                    background: #007cba; 
                                                    color: white; 
                                                    padding: 8px 16px; 
                                                    text-decoration: none; 
                                                    border-radius: 4px; 
                                                    font-size: 12px; 
                                                    font-weight: 600;
                                                    flex: 1;
                                                    text-align: center;
                                                    min-width: 120px;
                                                    display: flex;
                                                    align-items: center;
                                                    justify-content: center;
                                                " class="gffc-view-dist-site-btn"><span class="gffc-view-dist-site-full">Distributor Site</span><span class="gffc-view-dist-site-short">View on Distributor</span></a>
                                            ` : ''}
                                            ${addToCartBtn}
                                            ${product.permalink ? `
                                                <a href="${product.permalink}" target="_blank" style="
                                                    background: #2ecc71; 
                                                    color: white; 
                                                    padding: 8px 16px; 
                                                    text-decoration: none; 
                                                    border-radius: 4px; 
                                                    font-size: 12px; 
                                                    font-weight: 600;
                                                    flex: 1;
                                                    text-align: center;
                                                    min-width: 120px;
                                                ">View on Website</a>
                                            ` : ''}
                                        </div>
                                    </div>
                                `;
                                
                                container.innerHTML += cardHTML;
                            });
                        }
                        
                        function renderDetailedComparisonTable(products) {
                            const container = document.getElementById('g_ffl_cockpit_comparison_table_container');

                            const ignoreShipping = gffcUpcIsIgnoreShippingEnabled();
                            
                            // Find best available (lowest price among in-stock products)
                            const inStockProducts = products.filter(p => (p.qty_on_hand || 0) > 0);
                            const inStockCosts = inStockProducts.map(p => gffcUpcGetEffectiveTotal(p)).filter(p => p > 0);
                            const minInStockTotal = inStockCosts.length > 0 ? Math.min(...inStockCosts) : null;
                            
                            let tableHTML = `
                                <style>
                                    .g-ffl-cockpit-sortable-table th {
                                        cursor: pointer;
                                        user-select: none;
                                        position: relative;
                                        transition: background-color 0.2s;
                                        padding-right: 30px !important;
                                    }
                                    .g-ffl-cockpit-sortable-table th:hover {
                                        background-color: #e9ecef !important;
                                    }
                                    .g-ffl-cockpit-sortable-table th[data-sort]:after {
                                        content: '⇅';
                                        position: absolute;
                                        right: 8px;
                                        top: 50%;
                                        transform: translateY(-50%);
                                        color: #bbb;
                                        font-size: 14px;
                                        font-weight: normal;
                                        opacity: 0.6;
                                    }
                                    .g-ffl-cockpit-sortable-table th[data-sort]:hover:after {
                                        color: #007cba;
                                        opacity: 1;
                                    }
                                    .g-ffl-cockpit-sortable-table th.sorted-asc:after {
                                        content: '▲';
                                        color: #007cba !important;
                                        opacity: 1 !important;
                                        font-size: 12px;
                                    }
                                    .g-ffl-cockpit-sortable-table th.sorted-desc:after {
                                        content: '▼';
                                        color: #007cba !important;
                                        opacity: 1 !important;
                                        font-size: 12px;
                                    }
                                </style>
                                <table class="g-ffl-cockpit-sortable-table" style="width: 100%; border-collapse: collapse; font-size: 14px;">
                                    <thead>
                                        <tr style="background: #f5f5f5;">
                                            <th data-sort="distributor" style="padding: 12px 30px 12px 12px; text-align: center; border: 1px solid #ddd; font-weight: 600; position: relative;">Distributor</th>
                                            <th data-sort="unit_price" style="padding: 12px 30px 12px 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; position: relative;">Unit Price</th>
                                            <th data-sort="shipping" style="padding: 12px 30px 12px 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; position: relative;">Shipping</th>
                                            <th data-sort="total_cost" style="padding: 12px 30px 12px 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; position: relative;">Total Cost</th>
                                            <th data-sort="map_price" style="padding: 12px 30px 12px 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; position: relative;">MAP</th>
                                            <th data-sort="msrp" style="padding: 12px 30px 12px 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; position: relative;">MSRP</th>
                                            <th data-sort="stock" style="padding: 12px 30px 12px 12px; text-align: center; border: 1px solid #ddd; font-weight: 600; position: relative;">Stock</th>
                                            <th data-sort="sku" style="padding: 12px 30px 12px 12px; text-align: center; border: 1px solid #ddd; font-weight: 600; position: relative;">SKU</th>
                                        </tr>
                                    </thead>
                                    <tbody id="table-body">
                            `;
                            
                            products.forEach((product, index) => {
                                const price = gffcUpcGetEffectiveTotal(product);
                                const shipping = product.shipping_cost || 0;
                                const unitPrice = product.unit_price || 0;
                                const mapPrice = product.map_price || 0;
                                const msrp = product.msrp || 0;
                                const qty = product.qty_on_hand || 0;
                                const inStock = qty > 0;
                                const isDropship = product.drop_ship_flg === 1;
                                const isBestAvailable = inStock && minInStockTotal && price === minInStockTotal && price > 0;
                                
                                tableHTML += `
                                    <tr style="background: ${isBestAvailable ? '#f8fff8' : (index % 2 === 0 ? '#fafafa' : 'white')};" 
                                        data-unit-price="${unitPrice}" 
                                        data-shipping="${shipping}" 
                                        data-total-cost="${price}" 
                                        data-map-price="${mapPrice}" 
                                        data-msrp="${msrp}" 
                                        data-stock="${qty}" 
                                        data-distributor="${product.distid || ''}"
                                        data-sku="${product.distsku || ''}">
                                        <td style="padding: 12px; border: 1px solid #ddd; text-align: center; vertical-align: middle;">
                                            <img src="${get_distributor_logo(product.distid)}" style="max-width: 80px; max-height: 30px; object-fit: contain; display: block; margin: 0 auto;" onerror="this.style.display='none';">
                                        </td>
                                        <td style="padding: 12px; text-align: right; border: 1px solid #ddd; font-weight: 600;">$${unitPrice.toFixed(2)}</td>
                                        <td style="padding: 12px; text-align: right; border: 1px solid #ddd;">${shipping > 0 ? '$' + shipping.toFixed(2) : 'Free'}</td>
                                        <td style="padding: 12px; text-align: right; border: 1px solid #ddd; font-weight: 600; ${isBestAvailable ? 'background: #e8f5e8; color: #2e7d32;' : ''}">$${price.toFixed(2)}</td>
                                        <td style="padding: 12px; text-align: right; border: 1px solid #ddd;">${mapPrice > 0 ? '$' + mapPrice.toFixed(2) : 'N/A'}</td>
                                        <td style="padding: 12px; text-align: right; border: 1px solid #ddd;">${msrp > 0 ? '$' + msrp.toFixed(2) : 'N/A'}</td>
                                        <td style="padding: 12px; text-align: center; border: 1px solid #ddd;">
                                            <div style="display: flex; align-items: center; justify-content: center; gap: 5px;">
                                                <div style="width: 8px; height: 8px; border-radius: 50%; background: ${inStock ? '#2ecc71' : '#e74c3c'};"></div>
                                                <span style="font-weight: 600; color: ${inStock ? '#2ecc71' : '#e74c3c'};">
                                                    ${inStock ? qty : 'Out'}
                                                </span>
                                            </div>
                                        </td>
                                        <td style="padding: 12px; text-align: center; border: 1px solid #ddd; font-family: monospace; font-size: 12px;">${product.distsku || 'N/A'}</td>
                                    </tr>
                                `;
                            });
                            
                            tableHTML += `
                                    </tbody>
                                </table>
                            `;
                            
                            container.innerHTML = tableHTML;
                            
                            // Add sorting functionality after the table is rendered
                            setTimeout(() => {
                                const table = document.querySelector('.g-ffl-cockpit-sortable-table');
                                if (!table) return;
                                
                                const tbody = table.querySelector('tbody');
                                let currentSort = { column: null, direction: 'asc' };
                                
                                // Add click handlers to sortable headers
                                table.querySelectorAll('th[data-sort]').forEach(th => {
                                    th.addEventListener('click', () => {
                                        const column = th.getAttribute('data-sort');
                                        
                                        // Toggle direction if clicking same column
                                        if (currentSort.column === column) {
                                            currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
                                        } else {
                                            currentSort.column = column;
                                            currentSort.direction = 'asc';
                                        }
                                        
                                        // Update header classes
                                        table.querySelectorAll('th').forEach(header => {
                                            header.classList.remove('sorted-asc', 'sorted-desc');
                                        });
                                        th.classList.add(currentSort.direction === 'asc' ? 'sorted-asc' : 'sorted-desc');
                                        
                                        // Sort the table
                                        sortTableRows(tbody, column, currentSort.direction);
                                    });
                                });
                                
                                function sortTableRows(tbody, column, direction) {
                                    const rows = Array.from(tbody.querySelectorAll('tr'));
                                    
                                    rows.sort((a, b) => {
                                        let aVal, bVal;
                                        
                                        switch(column) {
                                            case 'unit_price':
                                                aVal = parseFloat(a.getAttribute('data-unit-price')) || 0;
                                                bVal = parseFloat(b.getAttribute('data-unit-price')) || 0;
                                                break;
                                            case 'shipping':
                                                aVal = parseFloat(a.getAttribute('data-shipping')) || 0;
                                                bVal = parseFloat(b.getAttribute('data-shipping')) || 0;
                                                break;
                                            case 'total_cost':
                                                aVal = parseFloat(a.getAttribute('data-total-cost')) || 0;
                                                bVal = parseFloat(b.getAttribute('data-total-cost')) || 0;
                                                break;
                                            case 'map_price':
                                                aVal = parseFloat(a.getAttribute('data-map-price')) || 0;
                                                bVal = parseFloat(b.getAttribute('data-map-price')) || 0;
                                                break;
                                            case 'msrp':
                                                aVal = parseFloat(a.getAttribute('data-msrp')) || 0;
                                                bVal = parseFloat(b.getAttribute('data-msrp')) || 0;
                                                break;
                                            case 'stock':
                                                aVal = parseInt(a.getAttribute('data-stock')) || 0;
                                                bVal = parseInt(b.getAttribute('data-stock')) || 0;
                                                break;
                                            case 'distributor':
                                                aVal = a.getAttribute('data-distributor') || '';
                                                bVal = b.getAttribute('data-distributor') || '';
                                                return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
                                            case 'sku':
                                                aVal = a.getAttribute('data-sku') || '';
                                                bVal = b.getAttribute('data-sku') || '';
                                                return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
                                            default:
                                                return 0;
                                        }
                                        
                                        return direction === 'asc' ? (aVal - bVal) : (bVal - aVal);
                                    });
                                    
                                    // Re-append sorted rows
                                    rows.forEach((row, index) => {
                                        // Update alternating row colors while preserving best available highlighting
                                        const isBestAvailable = row.style.background.includes('f8fff8');
                                        if (!isBestAvailable) {
                                            row.style.background = index % 2 === 0 ? '#fafafa' : 'white';
                                        }
                                        tbody.appendChild(row);
                                    });
                                }
                            }, 100);
                        }
                        
                        function analyzeForDashboard(products) {
                            if (!products || products.length === 0) {
                                return;
                            }
                            
                            // Check if all products have the same UPC
                            const uniqueUPCs = [...new Set(products.map(p => p.upc))];
                            
                            if (uniqueUPCs.length === 1) {
                                // Single UPC - show dashboard (works with one or more distributors)
                                showSingleUPCDashboard(products, uniqueUPCs[0]);
                            }
                            // Otherwise, keep showing the regular grid
                        }

                        // =====================================================
                        // Product History Section Functions
                        // =====================================================
                        
                        // Store history data globally for filtering/view switching
                        window.gffcProductHistoryData = [];
                        window.gffcProductHistoryCurrentView = 'chart';
                        window.gffcProductHistorySelectedDistributor = 'all';
                        window.gffcProductHistoryChartDataType = 'both'; // 'both', 'price', or 'qty'
                        window.gffcChartZoom = { level: 0, startDate: null, endDate: null }; // Zoom state
                        
                        // Get user's timezone
                        function gffcGetUserTimezone() {
                            try {
                                return Intl.DateTimeFormat().resolvedOptions().timeZone;
                            } catch (e) {
                                return 'America/New_York'; // Default fallback
                            }
                        }
                        
                        // Get short timezone abbreviation (e.g., EST, PST, CST)
                        function gffcGetTimezoneAbbr() {
                            try {
                                const date = new Date();
                                const options = { timeZoneName: 'short' };
                                const parts = new Intl.DateTimeFormat('en-US', options).formatToParts(date);
                                const tzPart = parts.find(p => p.type === 'timeZoneName');
                                return tzPart ? tzPart.value : gffcGetUserTimezone();
                            } catch (e) {
                                return gffcGetUserTimezone();
                            }
                        }
                        
                        // Decode gzip+base64 encoded response body
                        async function gffcDecodeGzipBase64(base64String) {
                            try {
                                // Decode base64 to binary
                                const binaryString = atob(base64String);
                                const bytes = new Uint8Array(binaryString.length);
                                for (let i = 0; i < binaryString.length; i++) {
                                    bytes[i] = binaryString.charCodeAt(i);
                                }
                                
                                // Decompress gzip using DecompressionStream API
                                const ds = new DecompressionStream('gzip');
                                const decompressedStream = new Response(
                                    new Blob([bytes]).stream().pipeThrough(ds)
                                ).arrayBuffer();
                                
                                const decompressedData = await decompressedStream;
                                const text = new TextDecoder().decode(decompressedData);
                                return JSON.parse(text);
                            } catch (error) {
                                console.error('Error decoding gzip+base64:', error);
                                throw error;
                            }
                        }
                        
                        // =====================================================
                        // UPC Diagnosis Widget Functions
                        // =====================================================
                        
                        // Store diagnosis data globally
                        window.gffcDiagnosisData = null;
                        window.gffcDiagnosisExpanded = false;
                        window.gffcDiagnosisLoaded = false;
                        
                        // Check labels for display (ordered by priority)
                        const gffcDiagnosisCheckLabels = {
                            'catalog_existence': { name: 'Catalog Lookup', icon: 'fa-box', order: 1 },
                            'active_distributors': { name: 'Active Distributors', icon: 'fa-store', order: 2 },
                            'validated_distributors': { name: 'Validation Status', icon: 'fa-check-circle', order: 3 },
                            'stock_status': { name: 'Stock Status', icon: 'fa-boxes', order: 4 },
                            'product_restrictions': { name: 'Product Restrictions', icon: 'fa-ban', order: 5 },
                            'uncategorized': { name: 'Category Status', icon: 'fa-folder-open', order: 6 },
                            'posting_errors': { name: 'Posting Errors', icon: 'fa-exclamation-triangle', order: 7 },
                            'distsku_ignore': { name: 'Ignored SKUs', icon: 'fa-eye-slash', order: 8 },
                            'target_restrictions': { name: 'Target Restrictions', icon: 'fa-bullseye', order: 9 }
                        };
                        
                        // Reason icons mapping
                        const gffcDiagnosisReasonIcons = {
                            'catalog_existence': 'fa-box',
                            'active_distributors': 'fa-store',
                            'validated_distributors': 'fa-check-circle',
                            'product_restrictions': 'fa-ban',
                            'posting_errors': 'fa-exclamation-triangle',
                            'distsku_ignore': 'fa-eye-slash',
                            'stock_status': 'fa-boxes',
                            'uncategorized': 'fa-folder-open',
                            'target_restrictions': 'fa-bullseye'
                        };
                        
                        // Toggle diagnosis panel visibility
                        function gffcToggleDiagnosisPanel() {
                            const content = document.getElementById('g_ffl_cockpit_diagnosis_content');
                            const chevron = document.getElementById('g_ffl_cockpit_diagnosis_chevron');
                            const toggleText = document.getElementById('g_ffl_cockpit_diagnosis_toggle_text');
                            
                            window.gffcDiagnosisExpanded = !window.gffcDiagnosisExpanded;
                            
                            if (window.gffcDiagnosisExpanded) {
                                content.style.display = 'block';
                                chevron.classList.remove('fa-chevron-down');
                                chevron.classList.add('fa-chevron-up');
                                toggleText.textContent = 'Hide Diagnosis';
                                
                                // Load diagnosis if not already loaded
                                if (!window.gffcDiagnosisLoaded) {
                                    gffcRunDiagnosis();
                                }
                            } else {
                                content.style.display = 'none';
                                chevron.classList.remove('fa-chevron-up');
                                chevron.classList.add('fa-chevron-down');
                                toggleText.textContent = window.gffcDiagnosisLoaded ? 'Show Diagnosis' : 'Run Diagnosis';
                            }
                        }
                        
                        // Run diagnosis API call
                        function gffcRunDiagnosis() {
                            const upc = window.gffcUpcDashboardUpc;
                            if (!upc) {
                                console.error('No UPC available for diagnosis');
                                return;
                            }
                            
                            const loadingEl = document.getElementById('g_ffl_cockpit_diagnosis_loading');
                            const errorEl = document.getElementById('g_ffl_cockpit_diagnosis_error');
                            const resultsEl = document.getElementById('g_ffl_cockpit_diagnosis_results');
                            
                            // Show loading state
                            loadingEl.style.display = 'block';
                            errorEl.style.display = 'none';
                            resultsEl.style.display = 'none';
                            
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({
                                    "action": "diagnose_missing_upc",
                                    "data": {
                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        "upc": upc,
                                        "target": "woo"
                                    }
                                })
                            })
                            .then(response => response.json())
                            .then(async (responseData) => {
                                loadingEl.style.display = 'none';
                                
                                let data;
                                
                                // Handle different response formats from the API
                                // Case 1: Response has a 'body' property that's a gzip+base64 encoded string
                                if (responseData.body && typeof responseData.body === 'string') {
                                    try {
                                        // Try to decode as gzip+base64 first
                                        data = await gffcDecodeGzipBase64(responseData.body);
                                    } catch (e) {
                                        // Fallback to plain JSON parse
                                        try {
                                            data = JSON.parse(responseData.body);
                                        } catch (e2) {
                                            console.error('Failed to parse response body:', e2);
                                            data = responseData;
                                        }
                                    }
                                }
                                // Case 2: Response is already the data we need
                                else if (responseData.success !== undefined || responseData.diagnosis) {
                                    data = responseData;
                                }
                                // Case 3: Response might be double-stringified
                                else if (typeof responseData === 'string') {
                                    try {
                                        data = JSON.parse(responseData);
                                    } catch (e) {
                                        console.error('Failed to parse string response:', e);
                                        data = { success: false, message: 'Invalid response format' };
                                    }
                                }
                                // Case 4: Unknown format
                                else {
                                    data = responseData;
                                }
                                
                                console.log('Diagnosis API response (parsed):', data);
                                
                                if (data.success) {
                                    window.gffcDiagnosisData = data;
                                    window.gffcDiagnosisLoaded = true;
                                    gffcRenderDiagnosisResults(data);
                                    resultsEl.style.display = 'block';
                                } else {
                                    const errorMsg = document.getElementById('g_ffl_cockpit_diagnosis_error_message');
                                    errorMsg.textContent = data.message || 'Unable to fetch diagnosis';
                                    errorEl.style.display = 'block';
                                }
                            })
                            .catch(error => {
                                console.error('Diagnosis API error:', error);
                                loadingEl.style.display = 'none';
                                const errorMsg = document.getElementById('g_ffl_cockpit_diagnosis_error_message');
                                errorMsg.textContent = 'Network error: ' + error.message;
                                errorEl.style.display = 'block';
                            });
                        }
                        
                        // Render diagnosis results
                        function gffcRenderDiagnosisResults(data) {
                            const diagnosis = data.diagnosis;
                            
                            // Render primary reason
                            const primaryReasonEl = document.getElementById('g_ffl_cockpit_diagnosis_primary_reason');
                            const primaryMessageEl = document.getElementById('g_ffl_cockpit_diagnosis_primary_message');
                            const reasonIconEl = document.getElementById('g_ffl_cockpit_diagnosis_reason_icon');
                            
                            primaryMessageEl.textContent = diagnosis.primary_message || 'Unknown reason';
                            
                            // Update icon based on primary reason
                            const reasonIcon = gffcDiagnosisReasonIcons[diagnosis.primary_reason] || 'fa-question-circle';
                            reasonIconEl.innerHTML = `<i class="fas ${reasonIcon}" style="color: #dc2626; font-size: 24px;"></i>`;
                            
                            // Color-code based on is_loadable
                            if (diagnosis.is_loadable) {
                                primaryReasonEl.style.borderLeftColor = '#10b981';
                                reasonIconEl.style.background = '#d1fae5';
                                reasonIconEl.querySelector('i').style.color = '#059669';
                            }
                            
                            // Render checks grid (ordered by priority)
                            const checksGrid = document.getElementById('g_ffl_cockpit_diagnosis_checks_grid');
                            checksGrid.innerHTML = '';
                            
                            if (diagnosis.checks) {
                                // Sort checks by priority order
                                const sortedChecks = Object.entries(diagnosis.checks).sort((a, b) => {
                                    const orderA = (gffcDiagnosisCheckLabels[a[0]] || {}).order || 99;
                                    const orderB = (gffcDiagnosisCheckLabels[b[0]] || {}).order || 99;
                                    return orderA - orderB;
                                });
                                
                                for (const [checkKey, checkData] of sortedChecks) {
                                    const checkInfo = gffcDiagnosisCheckLabels[checkKey] || { name: checkKey, icon: 'fa-check', order: 99 };
                                    const passed = checkData.passed;
                                    
                                    // Determine status class: passed (green), failed (red), or warning (yellow for null)
                                    let statusClass = 'passed';
                                    let statusIcon = 'fa-check';
                                    let isClickable = false;
                                    
                                    if (passed === false) {
                                        statusClass = 'failed';
                                        statusIcon = 'fa-times';
                                        isClickable = true;
                                    } else if (passed === null) {
                                        statusClass = 'warning';
                                        statusIcon = 'fa-exclamation';
                                        isClickable = true;
                                    }
                                    
                                    // Generate detail text based on check type
                                    let detailText = gffcGetCheckDetailText(checkKey, checkData);
                                    
                                    const checkHTML = `
                                        <div class="g-ffl-cockpit-diagnosis-check-item ${statusClass}" 
                                             ${isClickable ? `onclick="gffcShowCheckDetails('${checkKey}')"` : ''}>
                                            <div class="g-ffl-cockpit-diagnosis-check-icon ${statusClass}">
                                                <i class="fas ${statusIcon}" style="font-size: 14px;"></i>
                                            </div>
                                            <div class="g-ffl-cockpit-diagnosis-check-content">
                                                <div class="g-ffl-cockpit-diagnosis-check-name">
                                                    <i class="fas ${checkInfo.icon}" style="margin-right: 6px; color: #6b7280;"></i>
                                                    ${checkInfo.name}
                                                </div>
                                                <div class="g-ffl-cockpit-diagnosis-check-detail">${detailText}</div>
                                            </div>
                                            ${isClickable ? '<div class="g-ffl-cockpit-diagnosis-check-arrow"><i class="fas fa-chevron-right"></i></div>' : ''}
                                        </div>
                                    `;
                                    checksGrid.innerHTML += checkHTML;
                                }
                            }
                            
                            // Render product info if available
                            const productInfoEl = document.getElementById('g_ffl_cockpit_diagnosis_product_info');
                            const productInfoContentEl = document.getElementById('g_ffl_cockpit_diagnosis_product_info_content');
                            
                            if (diagnosis.checks?.catalog_existence?.passed && diagnosis.checks.catalog_existence.product_info) {
                                const info = diagnosis.checks.catalog_existence.product_info;
                                const categoryDisplay = info.category 
                                    ? `<span style="color: #1f2937;">${info.category}</span>`
                                    : `<span style="display: inline-flex; align-items: center; gap: 4px; background: #fef3c7; color: #92400e; padding: 2px 8px; border-radius: 4px; font-size: 12px; font-weight: 600;"><i class="fas fa-exclamation-triangle" style="font-size: 10px;"></i> Uncategorized</span>`;
                                
                                productInfoContentEl.innerHTML = `
                                    <div>
                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">Product Name</div>
                                        <div style="font-size: 14px; font-weight: 500; color: #1f2937;">${info.name || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">Manufacturer</div>
                                        <div style="font-size: 14px; font-weight: 500; color: #1f2937;">${info.mfg_name || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">Product Class</div>
                                        <div style="font-size: 14px; font-weight: 500; color: #1f2937;">${info.product_class || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">Category</div>
                                        <div style="font-size: 14px; font-weight: 500;">${categoryDisplay}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">Unit Price</div>
                                        <div style="font-size: 14px; font-weight: 500; color: #1f2937;">${info.unit_price ? '$' + parseFloat(info.unit_price).toFixed(2) : 'N/A'}</div>
                                    </div>
                                `;
                                productInfoEl.style.display = 'block';
                            } else {
                                productInfoEl.style.display = 'none';
                            }
                            
                            // Render recommendations (deduplicated)
                            const recommendationsEl = document.getElementById('g_ffl_cockpit_diagnosis_recommendations');
                            const recommendationsListEl = document.getElementById('g_ffl_cockpit_diagnosis_recommendations_list');
                            
                            if (data.recommendations && data.recommendations.length > 0) {
                                // Deduplicate recommendations by action + location
                                const seen = new Set();
                                const uniqueRecommendations = data.recommendations.filter(rec => {
                                    const key = `${rec.action}|${rec.location || ''}`;
                                    if (seen.has(key)) return false;
                                    seen.add(key);
                                    return true;
                                });
                                
                                recommendationsListEl.innerHTML = uniqueRecommendations.map(rec => `
                                    <div class="g-ffl-cockpit-diagnosis-recommendation">
                                        <div class="g-ffl-cockpit-diagnosis-recommendation-icon">
                                            <i class="fas fa-arrow-right"></i>
                                        </div>
                                        <div class="g-ffl-cockpit-diagnosis-recommendation-content">
                                            <div class="g-ffl-cockpit-diagnosis-recommendation-action">${rec.action}</div>
                                            ${rec.location ? `<div class="g-ffl-cockpit-diagnosis-recommendation-location"><i class="fas fa-map-marker-alt" style="margin-right: 4px;"></i>${rec.location}</div>` : ''}
                                        </div>
                                    </div>
                                `).join('');
                                recommendationsEl.style.display = 'block';
                            } else {
                                recommendationsEl.style.display = 'none';
                            }
                            
                            // Handle posting errors special case
                            const clearErrorsEl = document.getElementById('g_ffl_cockpit_diagnosis_clear_errors');
                            const postingErrorMsgEl = document.getElementById('g_ffl_cockpit_diagnosis_posting_error_msg');
                            
                            if (diagnosis.checks?.posting_errors && !diagnosis.checks.posting_errors.passed) {
                                const errors = diagnosis.checks.posting_errors.errors || [];
                                if (errors.length > 0) {
                                    const errorMessages = errors.map(e => e.error || e.message || 'Unknown error').join('<br>');
                                    postingErrorMsgEl.innerHTML = errorMessages;
                                    clearErrorsEl.style.display = 'block';
                                } else {
                                    clearErrorsEl.style.display = 'none';
                                }
                            } else {
                                clearErrorsEl.style.display = 'none';
                            }
                        }
                        
                        // Get detail text for a check
                        function gffcGetCheckDetailText(checkKey, checkData) {
                            // Handle null (error during check)
                            if (checkData.passed === null) {
                                return 'Error occurred during check';
                            }
                            
                            if (checkData.passed) {
                                switch (checkKey) {
                                    case 'catalog_existence':
                                        return checkData.found_in_distributors ? `Found in ${checkData.found_in_distributors.length} distributor(s)` : 'Product found in catalog';
                                    case 'active_distributors':
                                        return checkData.active_with_product ? `${checkData.active_with_product.length} active distributor(s)` : 'Active distributors available';
                                    case 'validated_distributors':
                                        return checkData.validated ? `${checkData.validated.length} validated` : 'Distributors validated';
                                    case 'stock_status':
                                        return checkData.current_qty_on_hand !== undefined ? `${checkData.current_qty_on_hand} in stock` : 'In stock';
                                    case 'uncategorized':
                                        return checkData.product_category ? `Category: ${checkData.product_category}` : 'Category check passed';
                                    case 'posting_errors':
                                        return 'No posting errors';
                                    case 'distsku_ignore':
                                        return 'No ignored SKUs';
                                    case 'target_restrictions':
                                        return 'No target restrictions';
                                    case 'product_restrictions':
                                        return 'No blocking restrictions';
                                    default:
                                        return 'Passed';
                                }
                            } else {
                                switch (checkKey) {
                                    case 'catalog_existence':
                                        return 'UPC not found in any distributor catalog';
                                    case 'active_distributors':
                                        return checkData.inactive_with_product && checkData.inactive_with_product.length > 0 
                                            ? `Only in disabled: ${checkData.inactive_with_product.join(', ')}` 
                                            : 'No active distributors';
                                    case 'validated_distributors':
                                        return checkData.not_validated && checkData.not_validated.length > 0 
                                            ? `Not validated: ${checkData.not_validated.join(', ')}` 
                                            : 'Validation incomplete';
                                    case 'product_restrictions':
                                        const restrictions = checkData.blocking_restrictions || [];
                                        return restrictions.length > 0 ? restrictions[0].message : 'Blocked by restrictions';
                                    case 'posting_errors':
                                        return `${(checkData.errors || []).length} error(s) found`;
                                    case 'distsku_ignore':
                                        return checkData.ignored_items && checkData.ignored_items.length > 0 
                                            ? `${checkData.ignored_items.length} SKU(s) ignored` 
                                            : 'SKU in ignore list';
                                    case 'stock_status':
                                        if (!checkData.in_stock) return 'Out of stock';
                                        if (!checkData.meets_min_quantity) return `Below minimum (${checkData.current_qty_on_hand}/${checkData.min_quantity_to_list})`;
                                        return 'Stock issue';
                                    case 'uncategorized':
                                        const uncatRestrictions = checkData.blocking_restrictions || [];
                                        return uncatRestrictions.length > 0 ? uncatRestrictions[0].message : 'Product is uncategorized';
                                    case 'target_restrictions':
                                        const targetRestrictions = checkData.blocking_restrictions || [];
                                        return targetRestrictions.length > 0 ? targetRestrictions[0].message : 'Target restriction';
                                    default:
                                        return 'Failed';
                                }
                            }
                        }
                        
                        // Show expanded check details
                        function gffcShowCheckDetails(checkKey) {
                            if (!window.gffcDiagnosisData || !window.gffcDiagnosisData.diagnosis.checks) return;
                            
                            const checkData = window.gffcDiagnosisData.diagnosis.checks[checkKey];
                            if (!checkData) return;
                            
                            const detailsEl = document.getElementById('g_ffl_cockpit_diagnosis_check_details');
                            const titleEl = document.getElementById('g_ffl_cockpit_diagnosis_detail_title');
                            const contentEl = document.getElementById('g_ffl_cockpit_diagnosis_detail_content');
                            
                            const checkInfo = gffcDiagnosisCheckLabels[checkKey] || { name: checkKey, icon: 'fa-check' };
                            titleEl.innerHTML = `<i class="fas ${checkInfo.icon}" style="margin-right: 8px; color: #dc2626;"></i>${checkInfo.name} - Details`;
                            
                            let detailHTML = '';
                            
                            switch (checkKey) {
                                case 'product_restrictions':
                                case 'uncategorized':
                                case 'target_restrictions':
                                    const restrictions = checkData.blocking_restrictions || [];
                                    if (restrictions.length > 0) {
                                        detailHTML = restrictions.map(r => `
                                            <div class="g-ffl-cockpit-diagnosis-detail-restriction" style="background: #fff; border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; margin-bottom: 12px;">
                                                <div style="display: flex; align-items: flex-start; gap: 12px; margin-bottom: 12px;">
                                                    <div style="width: 32px; height: 32px; background: #fef2f2; border-radius: 8px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                                                        <i class="fas fa-exclamation-triangle" style="color: #dc2626; font-size: 14px;"></i>
                                                    </div>
                                                    <div style="flex: 1;">
                                                        <div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; color: #6b7280; font-weight: 600; margin-bottom: 4px;">${r.source || 'Unknown'} - ${r.type || 'Restriction'}</div>
                                                        <div style="font-size: 14px; font-weight: 500; color: #1f2937;">${r.message}</div>
                                                    </div>
                                                </div>
                                                ${r.location ? `
                                                    <div style="display: flex; align-items: center; gap: 8px; padding: 10px 12px; background: #f9fafb; border-radius: 6px; margin-bottom: 8px;">
                                                        <i class="fas fa-map-marker-alt" style="color: #6b7280; font-size: 12px;"></i>
                                                        <span style="font-size: 13px; color: #374151;"><strong>Location:</strong> ${r.location}</span>
                                                    </div>
                                                ` : ''}
                                                ${r.fix ? `
                                                    <div style="display: flex; align-items: flex-start; gap: 8px; padding: 10px 12px; background: #ecfdf5; border-radius: 6px; border: 1px solid #a7f3d0;">
                                                        <i class="fas fa-lightbulb" style="color: #10b981; font-size: 12px; margin-top: 2px;"></i>
                                                        <span style="font-size: 13px; color: #065f46;"><strong>Fix:</strong> ${r.fix}</span>
                                                    </div>
                                                ` : ''}
                                            </div>
                                        `).join('');
                                    }
                                    break;
                                    
                                case 'posting_errors':
                                    const errors = checkData.errors || [];
                                    if (errors.length > 0) {
                                        detailHTML = errors.map(e => `
                                            <div class="g-ffl-cockpit-diagnosis-detail-restriction">
                                                <div class="g-ffl-cockpit-diagnosis-detail-restriction-source">
                                                    <i class="fas fa-exclamation-circle" style="margin-right: 4px;"></i>
                                                    Target: ${checkData.target_checked || 'Unknown'} | ${e.timestamp ? new Date(e.timestamp).toLocaleString() : 'Recent'}
                                                </div>
                                                <div class="g-ffl-cockpit-diagnosis-detail-restriction-message">${e.error || e.message || 'Unknown error'}</div>
                                            </div>
                                        `).join('');
                                    }
                                    break;
                                    
                                case 'distsku_ignore':
                                    const ignored = checkData.ignored_items || [];
                                    if (ignored.length > 0) {
                                        detailHTML = `
                                            <div style="color: #374151; font-size: 14px;">
                                                The following distributor SKUs are in the global ignore list:
                                                <ul style="margin: 10px 0 0 0; padding-left: 20px;">
                                                    ${ignored.map(item => `<li><strong>${item.distid}</strong>: ${item.distsku}</li>`).join('')}
                                                </ul>
                                            </div>
                                        `;
                                    }
                                    break;
                                    
                                case 'stock_status':
                                    detailHTML = `
                                        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 15px;">
                                            <div style="background: #f9fafb; padding: 12px; border-radius: 6px; text-align: center;">
                                                <div style="font-size: 24px; font-weight: 700; color: ${checkData.in_stock ? '#10b981' : '#ef4444'};">${checkData.current_qty_on_hand ?? 'N/A'}</div>
                                                <div style="font-size: 11px; text-transform: uppercase; color: #6b7280; font-weight: 600;">Current Qty</div>
                                            </div>
                                            <div style="background: #f9fafb; padding: 12px; border-radius: 6px; text-align: center;">
                                                <div style="font-size: 24px; font-weight: 700; color: #374151;">${checkData.min_quantity_to_list ?? 1}</div>
                                                <div style="font-size: 11px; text-transform: uppercase; color: #6b7280; font-weight: 600;">Min Required</div>
                                            </div>
                                            <div style="background: #f9fafb; padding: 12px; border-radius: 6px; text-align: center;">
                                                <div style="font-size: 24px; font-weight: 700; color: ${checkData.was_ever_in_stock ? '#10b981' : '#ef4444'};">
                                                    <i class="fas ${checkData.was_ever_in_stock ? 'fa-check' : 'fa-times'}"></i>
                                                </div>
                                                <div style="font-size: 11px; text-transform: uppercase; color: #6b7280; font-weight: 600;">Previously In Stock</div>
                                            </div>
                                        </div>
                                    `;
                                    break;
                                    
                                case 'active_distributors':
                                    detailHTML = `
                                        <div style="color: #374151; font-size: 14px;">
                                            ${checkData.active_with_product && checkData.active_with_product.length > 0 ? `
                                                <div style="margin-bottom: 10px;">
                                                    <strong style="color: #10b981;">Active distributors with this product:</strong>
                                                    <div>${checkData.active_with_product.join(', ')}</div>
                                                </div>
                                            ` : ''}
                                            ${checkData.inactive_with_product && checkData.inactive_with_product.length > 0 ? `
                                                <div>
                                                    <strong style="color: #ef4444;">Disabled distributors with this product:</strong>
                                                    <div>${checkData.inactive_with_product.join(', ')}</div>
                                                    <div style="margin-top: 8px; font-size: 12px; color: #6b7280;">
                                                        <i class="fas fa-info-circle" style="margin-right: 4px;"></i>
                                                        Enable these distributors in Cockpit to list products from them.
                                                    </div>
                                                </div>
                                            ` : ''}
                                        </div>
                                    `;
                                    break;
                                    
                                default:
                                    detailHTML = `<div style="color: #374151; font-size: 14px;">No additional details available.</div>`;
                            }
                            
                            contentEl.innerHTML = detailHTML;
                            detailsEl.style.display = 'block';
                            
                            // Scroll to details
                            detailsEl.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        }
                        
                        // Close check details panel
                        function gffcCloseDiagnosisDetails() {
                            document.getElementById('g_ffl_cockpit_diagnosis_check_details').style.display = 'none';
                        }
                        
                        // Clear posting errors
                        function gffcClearPostingErrors() {
                            const upc = window.gffcUpcDashboardUpc;
                            if (!upc) return;
                            
                            const btn = document.getElementById('g_ffl_cockpit_clear_errors_btn');
                            const originalHTML = btn.innerHTML;
                            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Clearing...';
                            btn.disabled = true;
                            
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({
                                    "action": "clear_posting_error",
                                    "data": {
                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        "upc": upc,
                                        "target": "woo"
                                    }
                                })
                            })
                            .then(response => response.json())
                            .then(async (responseData) => {
                                // Handle different response formats
                                let data;
                                if (responseData.body && typeof responseData.body === 'string') {
                                    try {
                                        // Try to decode as gzip+base64 first
                                        data = await gffcDecodeGzipBase64(responseData.body);
                                    } catch (e) {
                                        // Fallback to plain JSON parse
                                        try {
                                            data = JSON.parse(responseData.body);
                                        } catch (e2) {
                                            data = responseData;
                                        }
                                    }
                                } else if (responseData.success !== undefined) {
                                    data = responseData;
                                } else {
                                    data = responseData;
                                }
                                
                                if (data.success) {
                                    // Show success message
                                    btn.innerHTML = '<i class="fas fa-check"></i> Errors Cleared!';
                                    btn.style.background = '#10b981';
                                    
                                    // Re-run diagnosis after a short delay
                                    setTimeout(() => {
                                        btn.innerHTML = originalHTML;
                                        btn.style.background = '';
                                        btn.disabled = false;
                                        
                                        // Reset and re-run diagnosis
                                        window.gffcDiagnosisLoaded = false;
                                        gffcRunDiagnosis();
                                    }, 1500);
                                } else {
                                    btn.innerHTML = '<i class="fas fa-times"></i> Failed';
                                    btn.style.background = '#dc2626';
                                    setTimeout(() => {
                                        btn.innerHTML = originalHTML;
                                        btn.style.background = '';
                                        btn.disabled = false;
                                    }, 2000);
                                }
                            })
                            .catch(error => {
                                console.error('Clear posting errors error:', error);
                                btn.innerHTML = '<i class="fas fa-times"></i> Error';
                                setTimeout(() => {
                                    btn.innerHTML = originalHTML;
                                    btn.style.background = '';
                                    btn.disabled = false;
                                }, 2000);
                            });
                        }
                        
                        // Reset diagnosis section (called when leaving dashboard)
                        function gffcResetDiagnosisSection() {
                            window.gffcDiagnosisData = null;
                            window.gffcDiagnosisExpanded = false;
                            window.gffcDiagnosisLoaded = false;
                            
                            const section = document.getElementById('g_ffl_cockpit_diagnosis_section');
                            const content = document.getElementById('g_ffl_cockpit_diagnosis_content');
                            const chevron = document.getElementById('g_ffl_cockpit_diagnosis_chevron');
                            const toggleText = document.getElementById('g_ffl_cockpit_diagnosis_toggle_text');
                            const detailsEl = document.getElementById('g_ffl_cockpit_diagnosis_check_details');
                            
                            if (section) section.style.display = 'none';
                            if (content) content.style.display = 'none';
                            if (chevron) {
                                chevron.classList.remove('fa-chevron-up');
                                chevron.classList.add('fa-chevron-down');
                            }
                            if (toggleText) toggleText.textContent = 'Run Diagnosis';
                            if (detailsEl) detailsEl.style.display = 'none';
                        }
                        
                        // Show diagnosis section if product has no website link
                        function gffcShowDiagnosisSectionIfNeeded(products) {
                            const section = document.getElementById('g_ffl_cockpit_diagnosis_section');
                            if (!section) return;
                            
                            // Check if ANY product has a permalink (website link)
                            const hasWebsiteLink = products.some(p => p.permalink && p.permalink.trim() !== '');
                            
                            if (!hasWebsiteLink) {
                                // No products have a website link - show diagnosis section
                                section.style.display = 'block';
                            } else {
                                // At least one product has a website link - hide diagnosis section
                                section.style.display = 'none';
                            }
                        }
                        
                        // Reset history section to initial state (show Load History button)
                        function resetHistorySection() {
                            const loadPrompt = document.getElementById('g_ffl_cockpit_history_load_prompt');
                            const controls = document.getElementById('g_ffl_cockpit_history_controls');
                            const disclaimer = document.getElementById('g_ffl_cockpit_history_disclaimer');
                            const loadingEl = document.getElementById('g_ffl_cockpit_history_loading');
                            const emptyEl = document.getElementById('g_ffl_cockpit_history_empty');
                            const chartContainer = document.getElementById('g_ffl_cockpit_history_chart_container');
                            const tableContainer = document.getElementById('g_ffl_cockpit_history_table_container');
                            
                            // Show load prompt, hide everything else
                            if (loadPrompt) loadPrompt.style.display = 'block';
                            if (controls) controls.style.display = 'none';
                            if (disclaimer) disclaimer.style.display = 'none';
                            if (loadingEl) loadingEl.style.display = 'none';
                            if (emptyEl) emptyEl.style.display = 'none';
                            if (chartContainer) chartContainer.innerHTML = '';
                            if (tableContainer) tableContainer.innerHTML = '';
                            
                            // Reset state
                            window.gffcProductHistoryData = [];
                            window.gffcProductHistoryLoaded = false;
                            
                            // Setup lazy loading observer
                            setupHistoryLazyLoad();
                        }
                        
                        // Load product history on demand (called by Intersection Observer)
                        function loadProductHistory() {
                            // Prevent duplicate loads
                            if (window.gffcProductHistoryLoaded) return;
                            
                            const upc = window.gffcUpcDashboardUpc;
                            if (!upc) {
                                console.error('No UPC available to load history');
                                return;
                            }
                            
                            window.gffcProductHistoryLoaded = true;
                            
                            // Hide load prompt, show controls
                            const loadPrompt = document.getElementById('g_ffl_cockpit_history_load_prompt');
                            const controls = document.getElementById('g_ffl_cockpit_history_controls');
                            const disclaimer = document.getElementById('g_ffl_cockpit_history_disclaimer');
                            
                            if (loadPrompt) loadPrompt.style.display = 'none';
                            if (controls) controls.style.display = 'flex';
                            if (disclaimer) disclaimer.style.display = 'block';
                            
                            // Fetch the history data
                            fetchProductHistory(upc);
                        }
                        
                        // Setup Intersection Observer to load history when scrolled into view
                        function setupHistoryLazyLoad() {
                            const loadPrompt = document.getElementById('g_ffl_cockpit_history_load_prompt');
                            if (!loadPrompt) return;
                            
                            // Disconnect existing observer if any
                            if (window.gffcHistoryObserver) {
                                window.gffcHistoryObserver.disconnect();
                            }
                            
                            window.gffcHistoryObserver = new IntersectionObserver((entries) => {
                                entries.forEach(entry => {
                                    if (entry.isIntersecting && !window.gffcProductHistoryLoaded) {
                                        loadProductHistory();
                                        window.gffcHistoryObserver.disconnect();
                                    }
                                });
                            }, {
                                root: null,
                                rootMargin: '100px', // Start loading 100px before it's visible
                                threshold: 0
                            });
                            
                            window.gffcHistoryObserver.observe(loadPrompt);
                        }
                        
                        // Fetch inventory history from API
                        function fetchProductHistory(upc) {
                            const loadingEl = document.getElementById('g_ffl_cockpit_history_loading');
                            const emptyEl = document.getElementById('g_ffl_cockpit_history_empty');
                            const chartContainer = document.getElementById('g_ffl_cockpit_history_chart_container');
                            const tableContainer = document.getElementById('g_ffl_cockpit_history_table_container');
                            
                            // Show loading state
                            loadingEl.style.display = 'block';
                            emptyEl.style.display = 'none';
                            chartContainer.innerHTML = '';
                            tableContainer.innerHTML = '';
                            
                            const timezone = gffcGetUserTimezone();
                            
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({
                                    "action": "get_inventory_history",
                                    "data": {
                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        "upc": upc,
                                        "timezone": timezone
                                    }
                                })
                            })
                            .then(response => response.json())
                            .then(async (responseData) => {
                                let data;
                                
                                // Check if response has a gzip+base64 encoded body
                                if (responseData.body && typeof responseData.body === 'string') {
                                    // Decode the gzip+base64 encoded body
                                    data = await gffcDecodeGzipBase64(responseData.body);
                                } else {
                                    // Response is already decoded JSON
                                    data = responseData;
                                }
                                
                                loadingEl.style.display = 'none';
                                
                                // Check for success flag
                                if (data.success === false) {
                                    console.error('API returned error:', data.error || data.message);
                                    emptyEl.style.display = 'block';
                                    return;
                                }
                                
                                // Parse history - it comes as a JSON string from json.dumps
                                let historyData = data.history || data.data || [];
                                if (typeof historyData === 'string') {
                                    try {
                                        historyData = JSON.parse(historyData);
                                    } catch (e) {
                                        console.error('Error parsing history JSON:', e);
                                        historyData = [];
                                    }
                                }
                                
                                if (!Array.isArray(historyData) || historyData.length === 0) {
                                    emptyEl.style.display = 'block';
                                    return;
                                }
                                
                                // Store data globally
                                window.gffcProductHistoryData = historyData;
                                
                                // Reset hidden distributors when loading new product
                                window.gffcHiddenDistributors = new Set();
                                window.gffcProductHistorySelectedDistributor = 'all';
                                window.gffcHistoryTablePage = 1; // Reset pagination
                                const defaultWindow = getDefaultHistoryWindow(historyData);
                                window.gffcChartZoom = { level: 0, startDate: defaultWindow.startDate, endDate: defaultWindow.endDate }; // Reset zoom
                                
                                // Reset zoom UI
                                const zoomLabel = document.getElementById('g_ffl_cockpit_zoom_label');
                                const zoomInBtn = document.getElementById('g_ffl_cockpit_zoom_in_btn');
                                const zoomOutBtn = document.getElementById('g_ffl_cockpit_zoom_out_btn');
                                const resetBtn = document.getElementById('g_ffl_cockpit_zoom_reset_btn');
                                if (zoomLabel) zoomLabel.textContent = defaultWindow.label;
                                if (zoomInBtn) zoomInBtn.disabled = false;
                                if (zoomOutBtn) zoomOutBtn.disabled = true;
                                if (resetBtn) resetBtn.disabled = true;
                                
                                // Populate distributor filter for table view
                                populateHistoryDistributorFilter(historyData);
                                
                                // Render based on current view
                                renderProductHistory();
                            })
                            .catch(error => {
                                console.error('Error fetching product history:', error);
                                loadingEl.style.display = 'none';
                                emptyEl.style.display = 'block';
                            });
                        }
                        
                        // Filter history data - returns all data, visibility controlled by legend
                        function getFilteredHistoryData() {
                            return window.gffcProductHistoryData || [];
                        }
                        
                        // Toggle distributor visibility from legend click
                        function toggleDistributorVisibility(distid) {
                            if (!window.gffcHiddenDistributors) {
                                window.gffcHiddenDistributors = new Set();
                            }
                            
                            // Get all distributors from data
                            const allDistributors = [...new Set((window.gffcProductHistoryData || []).map(h => h.distid))];
                            const hiddenCount = window.gffcHiddenDistributors.size;
                            const visibleCount = allDistributors.length - hiddenCount;
                            
                            // If all are visible and user clicks one, hide all others (focus mode)
                            if (hiddenCount === 0) {
                                allDistributors.forEach(d => {
                                    if (d !== distid) {
                                        window.gffcHiddenDistributors.add(d);
                                    }
                                });
                            }
                            // If only one is visible and it's the clicked one, show all
                            else if (visibleCount === 1 && !window.gffcHiddenDistributors.has(distid)) {
                                window.gffcHiddenDistributors.clear();
                            }
                            // Otherwise, normal toggle behavior
                            else {
                                if (window.gffcHiddenDistributors.has(distid)) {
                                    window.gffcHiddenDistributors.delete(distid);
                                } else {
                                    window.gffcHiddenDistributors.add(distid);
                                }
                            }
                            
                            renderProductHistory();
                        }
                        
                        // Check if distributor is visible
                        function isDistributorVisible(distid) {
                            if (!window.gffcHiddenDistributors) return true;
                            return !window.gffcHiddenDistributors.has(distid);
                        }
                        
                        // Populate distributor filter dropdown for table view
                        function populateHistoryDistributorFilter(historyData) {
                            const filterEl = document.getElementById('g_ffl_cockpit_history_distributor_filter');
                            if (!filterEl) return;
                            
                            const distributors = [...new Set(historyData.map(h => h.distid))].sort();
                            
                            filterEl.innerHTML = '<option value="all">All Distributors</option>';
                            distributors.forEach(dist => {
                                const option = document.createElement('option');
                                option.value = dist;
                                option.textContent = dist;
                                filterEl.appendChild(option);
                            });
                            
                            // Restore previous selection if valid
                            if (window.gffcProductHistorySelectedDistributor !== 'all' && 
                                distributors.includes(window.gffcProductHistorySelectedDistributor)) {
                                filterEl.value = window.gffcProductHistorySelectedDistributor;
                            }
                        }
                        
                        // Handle distributor filter change for table view
                        function filterHistoryByDistributor() {
                            const filterEl = document.getElementById('g_ffl_cockpit_history_distributor_filter');
                            window.gffcProductHistorySelectedDistributor = filterEl.value;
                            window.gffcHistoryTablePage = 1; // Reset to first page
                            renderProductHistory();
                        }
                        
                        // Switch between chart and table views
                        function switchHistoryView(view) {
                            window.gffcProductHistoryCurrentView = view;
                            
                            const chartBtn = document.getElementById('g_ffl_cockpit_history_chart_btn');
                            const tableBtn = document.getElementById('g_ffl_cockpit_history_table_btn');
                            const chartContainer = document.getElementById('g_ffl_cockpit_history_chart_container');
                            const tableContainer = document.getElementById('g_ffl_cockpit_history_table_container');
                            const chartDataToggle = document.getElementById('g_ffl_cockpit_history_chart_data_toggle');
                            const zoomControls = document.getElementById('g_ffl_cockpit_chart_zoom_controls');
                            
                            if (view === 'chart') {
                                chartBtn.classList.add('active');
                                chartBtn.style.background = '#0073aa';
                                chartBtn.style.color = 'white';
                                tableBtn.classList.remove('active');
                                tableBtn.style.background = '#f5f5f5';
                                tableBtn.style.color = '#666';
                                chartContainer.style.display = 'block';
                                tableContainer.style.display = 'none';
                                // Show chart data type toggle and zoom controls, hide distributor filter
                                if (chartDataToggle) chartDataToggle.style.display = 'flex';
                                if (zoomControls) zoomControls.style.display = 'flex';
                                const distFilter = document.getElementById('g_ffl_cockpit_history_distributor_filter');
                                if (distFilter) distFilter.style.display = 'none';
                            } else {
                                tableBtn.classList.add('active');
                                tableBtn.style.background = '#0073aa';
                                tableBtn.style.color = 'white';
                                chartBtn.classList.remove('active');
                                chartBtn.style.background = '#f5f5f5';
                                chartBtn.style.color = '#666';
                                tableContainer.style.display = 'block';
                                chartContainer.style.display = 'none';
                                // Hide chart data type toggle and zoom controls, show distributor filter when in table view
                                if (chartDataToggle) chartDataToggle.style.display = 'none';
                                if (zoomControls) zoomControls.style.display = 'none';
                                const distFilter = document.getElementById('g_ffl_cockpit_history_distributor_filter');
                                if (distFilter) distFilter.style.display = 'block';
                            }
                            
                            renderProductHistory();
                        }
                        
                        // Switch chart data display type (both, price, qty)
                        function switchHistoryChartData(dataType) {
                            window.gffcProductHistoryChartDataType = dataType;
                            
                            const bothBtn = document.getElementById('g_ffl_cockpit_history_show_both_btn');
                            const priceBtn = document.getElementById('g_ffl_cockpit_history_show_price_btn');
                            const qtyBtn = document.getElementById('g_ffl_cockpit_history_show_qty_btn');
                            
                            // Reset all buttons
                            [bothBtn, priceBtn, qtyBtn].forEach(btn => {
                                if (btn) {
                                    btn.classList.remove('active');
                                    btn.style.background = '#f5f5f5';
                                    btn.style.color = '#666';
                                }
                            });
                            
                            // Activate selected button
                            let activeBtn = null;
                            if (dataType === 'both') activeBtn = bothBtn;
                            else if (dataType === 'price') activeBtn = priceBtn;
                            else if (dataType === 'qty') activeBtn = qtyBtn;
                            
                            if (activeBtn) {
                                activeBtn.classList.add('active');
                                activeBtn.style.background = '#0073aa';
                                activeBtn.style.color = 'white';
                            }
                            
                            // Re-render chart if in chart view
                            if (window.gffcProductHistoryCurrentView === 'chart') {
                                renderProductHistory();
                            }
                        }

                        function getDefaultHistoryWindow(historyData) {
                            const now = new Date().getTime();
                            const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000;
                            const safeData = Array.isArray(historyData) ? historyData : [];
                            if (!safeData.length) {
                                return { startDate: now - ninetyDaysMs, endDate: now, label: '90d' };
                            }
                            const allDates = safeData
                                .map(d => new Date(d.changed_on).getTime())
                                .filter(t => !isNaN(t));
                            const dataMinDate = Math.min(...allDates);
                            const dataMaxDate = Math.max(Math.max(...allDates), now);
                            const useFullRange = (dataMaxDate - dataMinDate) > ninetyDaysMs;
                            return {
                                startDate: useFullRange ? dataMinDate : (now - ninetyDaysMs),
                                endDate: dataMaxDate,
                                label: useFullRange ? 'All' : '90d'
                            };
                        }
                        
                        // Zoom chart function
                        function zoomChart(action) {
                            const historyData = window.gffcProductHistoryData;
                            if (!historyData || historyData.length === 0) return;
                            
                            // Get full date range from data
                            const allDates = historyData.map(d => new Date(d.changed_on).getTime());
                            const today = new Date().getTime();
                            
                            // Define zoom levels (in days): All, 30d, 14d, 7d, 3d, 1d
                            const zoomLevels = [
                                { days: null, label: 'All' },
                                { days: 30, label: '30d' },
                                { days: 14, label: '14d' },
                                { days: 7, label: '7d' },
                                { days: 3, label: '3d' },
                                { days: 1, label: '24h' }
                            ];
                            
                            let currentLevel = window.gffcChartZoom.level || 0;
                            
                            if (action === 'in') {
                                currentLevel = Math.min(currentLevel + 1, zoomLevels.length - 1);
                            } else if (action === 'out') {
                                currentLevel = Math.max(currentLevel - 1, 0);
                            } else if (action === 'reset') {
                                currentLevel = 0;
                            }
                            
                            const zoomConfig = zoomLevels[currentLevel];
                            
                            if (zoomConfig.days === null) {
                                // Default range: at least 90 days, or full span when data exceeds 90 days.
                                const defaultWindow = getDefaultHistoryWindow(historyData);
                                window.gffcChartZoom = { level: currentLevel, startDate: defaultWindow.startDate, endDate: defaultWindow.endDate };
                            } else {
                                // Zoom to last N days from today
                                const endDate = today;
                                const startDate = today - (zoomConfig.days * 24 * 60 * 60 * 1000);
                                window.gffcChartZoom = { level: currentLevel, startDate: startDate, endDate: endDate };
                            }
                            
                            // Update zoom label
                            const zoomLabel = document.getElementById('g_ffl_cockpit_zoom_label');
                            if (zoomLabel) {
                                zoomLabel.textContent = zoomConfig.days === null
                                    ? getDefaultHistoryWindow(historyData).label
                                    : zoomConfig.label;
                            }
                            
                            // Update button states
                            const zoomInBtn = document.getElementById('g_ffl_cockpit_zoom_in_btn');
                            const zoomOutBtn = document.getElementById('g_ffl_cockpit_zoom_out_btn');
                            const resetBtn = document.getElementById('g_ffl_cockpit_zoom_reset_btn');
                            
                            if (zoomInBtn) zoomInBtn.disabled = (currentLevel >= zoomLevels.length - 1);
                            if (zoomOutBtn) zoomOutBtn.disabled = (currentLevel <= 0);
                            if (resetBtn) resetBtn.disabled = (currentLevel === 0);
                            
                            // Re-render chart
                            renderProductHistory();
                        }

                        
                        // Main render function
                        function renderProductHistory() {
                            const filteredData = getFilteredHistoryData();
                            const emptyEl = document.getElementById('g_ffl_cockpit_history_empty');
                            
                            if (filteredData.length === 0) {
                                emptyEl.style.display = 'block';
                                document.getElementById('g_ffl_cockpit_history_chart_container').innerHTML = '';
                                document.getElementById('g_ffl_cockpit_history_table_container').innerHTML = '';
                                return;
                            }
                            
                            emptyEl.style.display = 'none';
                            
                            if (window.gffcProductHistoryCurrentView === 'chart') {
                                renderHistoryChart(filteredData);
                            } else {
                                // Apply distributor filter for table view
                                let tableData = filteredData;
                                if (window.gffcProductHistorySelectedDistributor && window.gffcProductHistorySelectedDistributor !== 'all') {
                                    tableData = filteredData.filter(h => h.distid === window.gffcProductHistorySelectedDistributor);
                                }
                                renderHistoryTable(tableData);
                            }
                        }
                        
                        // Render history as table
                        function renderHistoryTable(historyData) {
                            const container = document.getElementById('g_ffl_cockpit_history_table_container');
                            
                            // Store data for pagination
                            window.gffcHistoryTableData = historyData;
                            window.gffcHistoryTablePage = window.gffcHistoryTablePage || 1;
                            const rowsPerPage = 100;
                            
                            // Sort by date descending (most recent first)
                            const sortedData = [...historyData].sort((a, b) => 
                                new Date(b.changed_on) - new Date(a.changed_on)
                            );
                            
                            // Pagination calculations
                            const totalRows = sortedData.length;
                            const totalPages = Math.ceil(totalRows / rowsPerPage);
                            
                            // Ensure current page is valid
                            if (window.gffcHistoryTablePage > totalPages) {
                                window.gffcHistoryTablePage = totalPages || 1;
                            }
                            
                            const startIndex = (window.gffcHistoryTablePage - 1) * rowsPerPage;
                            const endIndex = Math.min(startIndex + rowsPerPage, totalRows);
                            const pageData = sortedData.slice(startIndex, endIndex);
                            
                            const tzAbbr = gffcGetTimezoneAbbr();
                            let tableHTML = `
                                <div style="overflow-x: auto;">
                                    <table class="g-ffl-cockpit-history-table" style="width: 100%; min-width: 650px;">
                                        <thead>
                                            <tr>
                                                <th data-sort="date" style="width: 140px;">Date & Time (${tzAbbr})</th>
                                                <th data-sort="distributor" style="width: 100px;">Distributor</th>
                                                <th data-sort="price" style="text-align: right; width: 90px;">Unit Price</th>
                                                <th data-sort="price_change" style="text-align: right; width: 90px;">Price Change</th>
                                                <th data-sort="qty" style="text-align: right; width: 70px;">Quantity</th>
                                                <th data-sort="qty_change" style="text-align: right; width: 80px;">Qty Change</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                            `;
                            
                            pageData.forEach(record => {
                                const date = new Date(record.changed_on);
                                const formattedDate = date.toLocaleDateString('en-US', {
                                    year: 'numeric',
                                    month: 'short',
                                    day: 'numeric'
                                });
                                const formattedTime = date.toLocaleTimeString('en-US', {
                                    hour: '2-digit',
                                    minute: '2-digit'
                                });
                                
                                const unitPrice = parseFloat(record.unit_price) || 0;
                                const priceChange = parseFloat(record.price_change) || 0;
                                const qtyOnHand = parseInt(record.qty_on_hand) || 0;
                                const qtyChange = parseInt(record.qty_change) || 0;
                                
                                // Price change styling
                                let priceChangeClass = 'g-ffl-cockpit-price-same';
                                let priceChangeIcon = '';
                                if (priceChange > 0) {
                                    priceChangeClass = 'g-ffl-cockpit-price-up';
                                    priceChangeIcon = '<i class="fas fa-arrow-up" style="margin-right: 6px;"></i>';
                                } else if (priceChange < 0) {
                                    priceChangeClass = 'g-ffl-cockpit-price-down';
                                    priceChangeIcon = '<i class="fas fa-arrow-down" style="margin-right: 6px;"></i>';
                                }
                                
                                // Qty change styling
                                let qtyChangeClass = 'g-ffl-cockpit-price-same';
                                let qtyChangeIcon = '';
                                if (qtyChange > 0) {
                                    qtyChangeClass = 'g-ffl-cockpit-stock-up';
                                    qtyChangeIcon = '<i class="fas fa-arrow-up" style="margin-right: 6px;"></i>';
                                } else if (qtyChange < 0) {
                                    qtyChangeClass = 'g-ffl-cockpit-stock-down';
                                    qtyChangeIcon = '<i class="fas fa-arrow-down" style="margin-right: 6px;"></i>';
                                }
                                
                                tableHTML += `
                                    <tr data-date="${date.getTime()}" 
                                        data-distributor="${record.distid}"
                                        data-price="${unitPrice}"
                                        data-price-change="${priceChange}"
                                        data-qty="${qtyOnHand}"
                                        data-qty-change="${qtyChange}">
                                        <td>
                                            <div style="font-weight: 600; font-size: 13px;">${formattedDate}</div>
                                            <div style="font-size: 11px; color: #888;">${formattedTime}</div>
                                        </td>
                                        <td style="text-align: center;">
                                            <img src="${get_distributor_logo(record.distid)}" title="${record.distid}" alt="${record.distid}" style="max-width: 45px; max-height: 20px; object-fit: contain;" onerror="this.outerHTML='<span style=\\'font-size: 12px;\\'>${record.distid}</span>';">
                                        </td>
                                        <td style="text-align: right; font-weight: 600; font-size: 13px;">$${unitPrice.toFixed(2)}</td>
                                        <td style="text-align: right; font-size: 13px;" class="${priceChangeClass}">
                                            ${priceChange !== 0 ? priceChangeIcon + '$' + Math.abs(priceChange).toFixed(2) : '—'}
                                        </td>
                                        <td style="text-align: right; font-weight: 600; font-size: 13px;">${qtyOnHand}</td>
                                        <td style="text-align: right; font-size: 13px;" class="${qtyChangeClass}">
                                            ${qtyChange !== 0 ? qtyChangeIcon + Math.abs(qtyChange) : '—'}
                                        </td>
                                    </tr>
                                `;
                            });
                            
                            tableHTML += `
                                        </tbody>
                                    </table>
                                </div>
                            `;
                            
                            // Add pagination controls if more than one page
                            if (totalPages > 1) {
                                const currentPage = window.gffcHistoryTablePage;
                                tableHTML += `
                                    <div class="g-ffl-cockpit-history-pagination" style="display: flex; justify-content: space-between; align-items: center; padding: 15px 5px; margin-top: 10px; border-top: 1px solid #eee;">
                                        <div style="color: #666; font-size: 13px;">
                                            Showing ${startIndex + 1}–${endIndex} of ${totalRows} records
                                        </div>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <button type="button" onclick="changeHistoryTablePage(1)" ${currentPage === 1 ? 'disabled' : ''} style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; background: ${currentPage === 1 ? '#f5f5f5' : 'white'}; cursor: ${currentPage === 1 ? 'not-allowed' : 'pointer'}; color: ${currentPage === 1 ? '#aaa' : '#333'};">
                                                <i class="fas fa-angle-double-left"></i>
                                            </button>
                                            <button type="button" onclick="changeHistoryTablePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''} style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; background: ${currentPage === 1 ? '#f5f5f5' : 'white'}; cursor: ${currentPage === 1 ? 'not-allowed' : 'pointer'}; color: ${currentPage === 1 ? '#aaa' : '#333'};">
                                                <i class="fas fa-angle-left"></i>
                                            </button>
                                            <span style="padding: 6px 12px; font-size: 13px; font-weight: 500;">
                                                Page ${currentPage} of ${totalPages}
                                            </span>
                                            <button type="button" onclick="changeHistoryTablePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''} style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; background: ${currentPage === totalPages ? '#f5f5f5' : 'white'}; cursor: ${currentPage === totalPages ? 'not-allowed' : 'pointer'}; color: ${currentPage === totalPages ? '#aaa' : '#333'};">
                                                <i class="fas fa-angle-right"></i>
                                            </button>
                                            <button type="button" onclick="changeHistoryTablePage(${totalPages})" ${currentPage === totalPages ? 'disabled' : ''} style="padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; background: ${currentPage === totalPages ? '#f5f5f5' : 'white'}; cursor: ${currentPage === totalPages ? 'not-allowed' : 'pointer'}; color: ${currentPage === totalPages ? '#aaa' : '#333'};">
                                                <i class="fas fa-angle-double-right"></i>
                                            </button>
                                        </div>
                                    </div>
                                `;
                            }
                            
                            container.innerHTML = tableHTML;
                            
                            // Add sorting functionality
                            setupHistoryTableSorting(container);
                        }
                        
                        // Change table page
                        function changeHistoryTablePage(page) {
                            window.gffcHistoryTablePage = page;
                            renderProductHistory();
                        }
                        
                        // Setup table sorting
                        function setupHistoryTableSorting(container) {
                            const table = container.querySelector('.g-ffl-cockpit-history-table');
                            if (!table) return;
                            
                            const tbody = table.querySelector('tbody');
                            let currentSort = { column: null, direction: 'desc' };
                            
                            table.querySelectorAll('th[data-sort]').forEach(th => {
                                th.addEventListener('click', () => {
                                    const column = th.getAttribute('data-sort');
                                    
                                    if (currentSort.column === column) {
                                        currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
                                    } else {
                                        currentSort.column = column;
                                        currentSort.direction = column === 'date' ? 'desc' : 'asc';
                                    }
                                    
                                    table.querySelectorAll('th').forEach(header => {
                                        header.classList.remove('sorted-asc', 'sorted-desc');
                                    });
                                    th.classList.add(currentSort.direction === 'asc' ? 'sorted-asc' : 'sorted-desc');
                                    
                                    sortHistoryTableRows(tbody, column, currentSort.direction);
                                });
                            });
                        }
                        
                        // Sort history table rows
                        function sortHistoryTableRows(tbody, column, direction) {
                            const rows = Array.from(tbody.querySelectorAll('tr'));
                            
                            rows.sort((a, b) => {
                                let aVal, bVal;
                                
                                switch(column) {
                                    case 'date':
                                        aVal = parseInt(a.getAttribute('data-date')) || 0;
                                        bVal = parseInt(b.getAttribute('data-date')) || 0;
                                        break;
                                    case 'distributor':
                                        aVal = a.getAttribute('data-distributor') || '';
                                        bVal = b.getAttribute('data-distributor') || '';
                                        return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
                                    case 'price':
                                        aVal = parseFloat(a.getAttribute('data-price')) || 0;
                                        bVal = parseFloat(b.getAttribute('data-price')) || 0;
                                        break;
                                    case 'price_change':
                                        aVal = parseFloat(a.getAttribute('data-price-change')) || 0;
                                        bVal = parseFloat(b.getAttribute('data-price-change')) || 0;
                                        break;
                                    case 'qty':
                                        aVal = parseInt(a.getAttribute('data-qty')) || 0;
                                        bVal = parseInt(b.getAttribute('data-qty')) || 0;
                                        break;
                                    case 'qty_change':
                                        aVal = parseInt(a.getAttribute('data-qty-change')) || 0;
                                        bVal = parseInt(b.getAttribute('data-qty-change')) || 0;
                                        break;
                                    default:
                                        return 0;
                                }
                                
                                return direction === 'asc' ? (aVal - bVal) : (bVal - aVal);
                            });
                            
                            rows.forEach((row, index) => {
                                row.style.background = index % 2 === 0 ? '#fafafa' : 'white';
                                tbody.appendChild(row);
                            });
                        }
                        
                        // Render history as chart
                        function renderHistoryChart(historyData) {
                            const container = document.getElementById('g_ffl_cockpit_history_chart_container');
                            
                            // Sort by date ascending for chart
                            const sortedData = [...historyData].sort((a, b) => 
                                new Date(a.changed_on) - new Date(b.changed_on)
                            );
                            
                            // Group data by distributor for multi-line chart
                            const distributorData = {};
                            sortedData.forEach(record => {
                                if (!distributorData[record.distid]) {
                                    distributorData[record.distid] = [];
                                }
                                distributorData[record.distid].push({
                                    date: new Date(record.changed_on),
                                    price: parseFloat(record.unit_price) || 0,
                                    qty: parseInt(record.qty_on_hand) || 0
                                });
                            });
                            
                            // Get chart data type setting
                            const chartDataType = window.gffcProductHistoryChartDataType || 'both';
                            const showPrice = chartDataType === 'both' || chartDataType === 'price';
                            const showQty = chartDataType === 'both' || chartDataType === 'qty';

                            // Mobile-optimized dimensions: tighter margins, shorter height
                            const isMobileChart = !!(window.matchMedia && window.matchMedia('(max-width: 768px)').matches);
                            const margin = isMobileChart
                                ? { top: 14, right: (showPrice && showQty ? 38 : 12), bottom: 36, left: 42 }
                                : { top: 20, right: 80, bottom: 60, left: 60 };
                            const width = container.offsetWidth - margin.left - margin.right;
                            const height = isMobileChart ? 240 : 400;
                            const labelFontSize = isMobileChart ? 9 : 10;
                            const axisTitleFontSize = isMobileChart ? 9 : 11;
                            
                            // Filter data to only visible distributors for range calculations
                            const visibleData = sortedData.filter(d => isDistributorVisible(d.distid));
                            
                            // Find data ranges based on visible distributors only
                            const allDates = visibleData.length > 0 
                                ? visibleData.map(d => new Date(d.changed_on))
                                : sortedData.map(d => new Date(d.changed_on));
                            const allPrices = visibleData.length > 0
                                ? visibleData.map(d => parseFloat(d.unit_price) || 0)
                                : sortedData.map(d => parseFloat(d.unit_price) || 0);
                            const allQtys = visibleData.length > 0
                                ? visibleData.map(d => parseInt(d.qty_on_hand) || 0)
                                : sortedData.map(d => parseInt(d.qty_on_hand) || 0);
                            
                            // Calculate date range with zoom support
                            const dataMinDate = Math.min(...allDates);
                            const maxDateFromData = Math.max(...allDates);
                            const today = new Date().getTime();
                            const dataMaxDate = Math.max(maxDateFromData, today);
                            
                            // Apply zoom if set
                            const zoom = window.gffcChartZoom || { level: 0, startDate: null, endDate: null };
                            let minDate, maxDate;
                            if (zoom.startDate !== null && zoom.endDate !== null) {
                                minDate = zoom.startDate;
                                maxDate = zoom.endDate;
                            } else {
                                minDate = dataMinDate;
                                maxDate = dataMaxDate;
                            }
                            
                            // Calculate if we're zoomed in enough to show times (less than 3 days visible)
                            const visibleRangeMs = maxDate - minDate;
                            const threeDaysMs = 3 * 24 * 60 * 60 * 1000;
                            const oneDayMs = 24 * 60 * 60 * 1000;
                            const showTimestamps = visibleRangeMs <= threeDaysMs;
                            
                            // Filter price/qty data to visible range for proper scaling
                            const visibleRangeData = visibleData.filter(d => {
                                const t = new Date(d.changed_on).getTime();
                                return t >= minDate && t <= maxDate;
                            });
                            
                            // Use full data if no data in visible range, otherwise use visible range
                            const priceData = visibleRangeData.length > 0 ? visibleRangeData : visibleData;
                            const rangePrices = priceData.map(d => parseFloat(d.unit_price) || 0);
                            const rangeQtys = priceData.map(d => parseInt(d.qty_on_hand) || 0);
                            
                            const minPrice = rangePrices.length > 0 ? Math.min(...rangePrices) * 0.95 : Math.min(...allPrices) * 0.95;
                            const maxPrice = rangePrices.length > 0 ? Math.max(...rangePrices) * 1.05 : Math.max(...allPrices) * 1.05;
                            const maxQty = rangeQtys.length > 0 ? Math.max(...rangeQtys) * 1.1 : Math.max(...allQtys) * 1.1;
                            
                            // Color palette for distributors - bright colors for dark mode
                            const colors = [
                                '#FF6B6B', // Bright Red
                                '#4ECB71', // Bright Green
                                '#5B9CFF', // Bright Blue
                                '#FF6BFF', // Bright Magenta
                                '#FFB347', // Bright Orange
                                '#4ECBCB', // Bright Cyan
                                '#FFD93D', // Bright Yellow
                                '#B96BFF', // Bright Purple
                                '#6BFFB3', // Bright Mint
                                '#FF6BB3', // Bright Pink
                                '#6BB3FF', // Bright Sky Blue
                                '#B3FF6B', // Bright Lime
                                '#FF9E6B', // Bright Coral
                                '#6BFFF0', // Bright Aqua
                                '#FFB3E6', // Light Pink
                                '#C9FF6B'  // Bright Chartreuse
                            ];
                            
                            // Assign colors sequentially to distributors in this chart to avoid collisions
                            const distColorMap = {};
                            const allDistributors = Object.keys(distributorData).sort();
                            allDistributors.forEach((distid, idx) => {
                                distColorMap[distid] = colors[idx % colors.length];
                            });
                            
                            // Get color for a distributor
                            function getDistributorColor(distid) {
                                return distColorMap[distid] || colors[0];
                            }
                            
                            const distributors = Object.keys(distributorData);
                            
                            // Scale functions
                            const scaleX = (date) => {
                                const range = maxDate - minDate || 1;
                                return margin.left + ((date - minDate) / range) * width;
                            };
                            
                            const scaleYPrice = (price) => {
                                const range = maxPrice - minPrice || 1;
                                return margin.top + height - ((price - minPrice) / range) * height;
                            };
                            
                            const scaleYQty = (qty) => {
                                const max = maxQty || 1;
                                return margin.top + height - (qty / max) * height;
                            };
                            
                            // Build SVG - Dark mode
                            let svg = `
                                <svg width="100%" height="${height + margin.top + margin.bottom}" viewBox="0 0 ${width + margin.left + margin.right} ${height + margin.top + margin.bottom}" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #1a1a2e; border-radius: 8px;">
                                    <!-- Clip path to constrain chart lines -->
                                    <defs>
                                        <clipPath id="chart-area-clip">
                                            <rect x="${margin.left}" y="${margin.top}" width="${width}" height="${height}"/>
                                        </clipPath>
                                    </defs>
                                    <!-- Grid lines -->
                                    <g stroke="#333355" stroke-width="1" stroke-dasharray="3,3">
                            `;

                            const yTickCount = 6;
                            const xAxisY = margin.top + height;

                            // Horizontal grid lines + Y-axis tick labels
                            for (let i = 0; i < yTickCount; i++) {
                                const ratio = i / (yTickCount - 1);
                                const y = margin.top + (height * ratio);
                                svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left + width}" y2="${y}"/>`;
                            }
                            svg += `</g>`;

                            // Axis lines
                            svg += `
                                <g stroke="#d5d8e1" stroke-width="1.6">
                                    <line x1="${margin.left}" y1="${margin.top}" x2="${margin.left}" y2="${xAxisY}"/>
                                    <line x1="${margin.left}" y1="${xAxisY}" x2="${margin.left + width}" y2="${xAxisY}"/>
                                </g>
                            `;
                            if (showPrice && showQty) {
                                svg += `
                                    <g stroke="#d5d8e1" stroke-width="1.6">
                                        <line x1="${margin.left + width}" y1="${margin.top}" x2="${margin.left + width}" y2="${xAxisY}"/>
                                    </g>
                                `;
                            }

                            // Y-axis ticks + labels (left)
                            if (showPrice || showQty) {
                                svg += `
                                    <g stroke="#d5d8e1" stroke-width="1.2">
                                `;
                                for (let i = 0; i < yTickCount; i++) {
                                    const ratio = i / (yTickCount - 1);
                                    const y = margin.top + (height * ratio);
                                    const tickValue = showPrice
                                        ? (maxPrice - ((maxPrice - minPrice) * ratio))
                                        : (maxQty - (maxQty * ratio));
                                    const label = showPrice
                                        ? `$${tickValue.toFixed(2)}`
                                        : `${Math.round(tickValue)}`;
                                    svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left - 6}" y2="${y}"/>`;
                                    svg += `<text x="${margin.left - 10}" y="${y}" text-anchor="end" dominant-baseline="middle" fill="#e0e0e0" font-size="${labelFontSize}">${label}</text>`;
                                }
                                svg += `</g>`;

                                // Left axis title (hidden on mobile to save space)
                                if (!isMobileChart) {
                                    svg += `
                                        <g fill="#e0e0e0" font-size="${axisTitleFontSize}" font-weight="600">
                                            <text x="${margin.left - 45}" y="${margin.top + height/2}" text-anchor="middle" dominant-baseline="middle" transform="rotate(-90, ${margin.left - 45}, ${margin.top + height/2})">${showPrice ? 'Price ($)' : 'Quantity'}</text>
                                        </g>
                                    `;
                                }
                            }

                            // Y-axis ticks + labels (right quantity when both are shown)
                            if (showPrice && showQty) {
                                svg += `
                                    <g stroke="#d5d8e1" stroke-width="1.2">
                                `;
                                for (let i = 0; i < yTickCount; i++) {
                                    const ratio = i / (yTickCount - 1);
                                    const y = margin.top + (height * ratio);
                                    const tickValue = maxQty - (maxQty * ratio);
                                    svg += `<line x1="${margin.left + width}" y1="${y}" x2="${margin.left + width + 6}" y2="${y}"/>`;
                                    svg += `<text x="${margin.left + width + 10}" y="${y}" text-anchor="start" dominant-baseline="middle" fill="#e0e0e0" font-size="${labelFontSize}">${Math.round(tickValue)}</text>`;
                                }
                                svg += `</g>`;
                                if (!isMobileChart) {
                                    svg += `
                                        <g fill="#e0e0e0" font-size="${axisTitleFontSize}" font-weight="600">
                                            <text x="${margin.left + width + 46}" y="${margin.top + height/2}" text-anchor="middle" dominant-baseline="middle" transform="rotate(90, ${margin.left + width + 46}, ${margin.top + height/2})">Quantity</text>
                                        </g>
                                    `;
                                }
                            }

                            // X-axis ticks + labels
                            const dateRange = maxDate - minDate;
                            const xTickSpacing = isMobileChart ? 60 : 110;
                            const xTickMax = isMobileChart ? 4 : 8;
                            const xTickCount = Math.max(2, Math.min(xTickMax, Math.floor(width / xTickSpacing)));
                            svg += `<g fill="#e0e0e0" font-size="${labelFontSize}" font-weight="500" stroke="#d5d8e1" stroke-width="1.2">`;
                            for (let i = 0; i < xTickCount; i++) {
                                const date = new Date(minDate + (dateRange / (xTickCount - 1 || 1)) * i);
                                const x = scaleX(date.getTime());
                                let label;
                                if (showTimestamps) {
                                    if (visibleRangeMs <= oneDayMs) {
                                        label = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
                                    } else {
                                        label = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) +
                                                (isMobileChart ? '' : ' ' + date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true }));
                                    }
                                } else {
                                    label = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                                }
                                svg += `<line x1="${x}" y1="${xAxisY}" x2="${x}" y2="${xAxisY + 6}"/>`;
                                svg += `<text x="${x}" y="${xAxisY + (isMobileChart ? 14 : 20)}" text-anchor="middle" stroke="none">${label}</text>`;
                            }
                            if (!isMobileChart) {
                                svg += `<text x="${margin.left + (width / 2)}" y="${xAxisY + 42}" text-anchor="middle" font-size="${axisTitleFontSize}" font-weight="600" stroke="none">Date / Time</text>`;
                            }
                            svg += `</g>`;
                            
                            // Start clipped group for chart lines
                            svg += `<g clip-path="url(#chart-area-clip)">`;
                            
                            // Draw lines for each distributor
                            distributors.forEach((distid, index) => {
                                // Skip hidden distributors
                                if (!isDistributorVisible(distid)) return;
                                
                                const color = getDistributorColor(distid);
                                const data = distributorData[distid];
                                
                                // Price line (solid) - stepwise - only if showing price
                                if (showPrice) {
                                    let pricePath = '';
                                    data.forEach((d, i) => {
                                        const x = scaleX(d.date.getTime());
                                        const y = scaleYPrice(d.price);
                                        if (i === 0) {
                                            pricePath += `M${x},${y}`;
                                        } else {
                                            // Step: horizontal line to new x, then vertical to new y
                                            pricePath += `H${x}V${y}`;
                                        }
                                    });
                                    // Extend line to the right edge of the chart
                                    pricePath += `H${margin.left + width}`;
                                    svg += `<path d="${pricePath}" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>`;
                                }
                                
                                // Quantity line - stepwise - only if showing qty
                                if (showQty) {
                                    let qtyPath = '';
                                    data.forEach((d, i) => {
                                        const x = scaleX(d.date.getTime());
                                        // If showing only qty (not both), use the left axis scale which goes from 0 to maxQty
                                        const y = (showPrice && showQty) ? scaleYQty(d.qty) : scaleYQty(d.qty);
                                        if (i === 0) {
                                            qtyPath += `M${x},${y}`;
                                        } else {
                                            // Step: horizontal line to new x, then vertical to new y
                                            qtyPath += `H${x}V${y}`;
                                        }
                                    });
                                    // Extend line to the right edge of the chart
                                    qtyPath += `H${margin.left + width}`;
                                    // If showing both, use dashed line for qty; if only qty, use solid line
                                    if (showPrice && showQty) {
                                        svg += `<path d="${qtyPath}" fill="none" stroke="${color}" stroke-width="2" stroke-dasharray="5,5" opacity="0.6"/>`;
                                    } else {
                                        svg += `<path d="${qtyPath}" fill="none" stroke="${color}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>`;
                                    }
                                }
                            });
                            
                            // Close clipped group
                            svg += `</g>`;
                            
                            // Add vertical marker line (hidden initially) and interactive overlay
                            svg += `
                                <line id="g_ffl_cockpit_chart_marker" x1="0" y1="${margin.top}" x2="0" y2="${margin.top + height}" stroke="#ffffff" stroke-width="2" stroke-dasharray="4,4" style="display: none; pointer-events: none;"/>
                                <rect id="g_ffl_cockpit_chart_overlay" x="${margin.left}" y="${margin.top}" width="${width}" height="${height}" fill="transparent" style="cursor: crosshair;"/>
                            `;
                            
                            svg += `</svg>`;
                            
                            // Store chart data for marker tooltip
                            window.gffcChartData = {
                                distributorData: distributorData,
                                margin: margin,
                                width: width,
                                height: height,
                                minDate: minDate,
                                maxDate: maxDate,
                                minPrice: minPrice,
                                maxPrice: maxPrice,
                                maxQty: maxQty,
                                showPrice: showPrice,
                                showQty: showQty,
                                showTimestamps: showTimestamps,
                                getDistributorColor: getDistributorColor
                            };
                            
                            // Legend - clickable to toggle distributor visibility
                            let legendHTML = '<div class="g-ffl-cockpit-chart-legend">';
                            distributors.forEach((distid, index) => {
                                const color = getDistributorColor(distid);
                                const isVisible = isDistributorVisible(distid);
                                const opacity = isVisible ? '1' : '0.35';
                                legendHTML += `
                                    <div class="g-ffl-cockpit-legend-item" onclick="toggleDistributorVisibility('${distid}')" style="cursor: pointer; opacity: ${opacity}; flex-direction: column; align-items: center; justify-content: flex-end;" title="${distid}">
                                        <div style="height: 28px; display: flex; align-items: center; justify-content: center;">
                                            <img src="${get_distributor_logo(distid)}" alt="${distid}" style="max-width: 60px; max-height: 28px; object-fit: contain;" onerror="this.outerHTML='<span style=\\'font-size: 13px; font-weight: 500;\\'>${distid}</span>';">
                                        </div>
                                        <div class="g-ffl-cockpit-legend-color" style="background: ${color}; width: 32px; margin-top: 4px;"></div>
                                    </div>
                                `;
                            });
                            legendHTML += '</div>';
                            
                            // Marker tooltip container
                            const markerTooltipHTML = '<div id="g_ffl_cockpit_marker_tooltip" class="g-ffl-cockpit-marker-tooltip" style="display: none;"></div>';
                            
                            container.innerHTML = svg + legendHTML + markerTooltipHTML;
                            
                            // Setup marker interactivity
                            setupChartMarker();
                        }
                        
                        // Setup chart marker interactivity
                        function setupChartMarker() {
                            const overlay = document.getElementById('g_ffl_cockpit_chart_overlay');
                            const marker = document.getElementById('g_ffl_cockpit_chart_marker');
                            const tooltip = document.getElementById('g_ffl_cockpit_marker_tooltip');
                            const container = document.getElementById('g_ffl_cockpit_history_chart_container');
                            
                            if (!overlay || !marker || !tooltip || !window.gffcChartData) return;
                            
                            const data = window.gffcChartData;
                            
                            function getDateFromX(x) {
                                const ratio = (x - data.margin.left) / data.width;
                                return new Date(data.minDate + ratio * (data.maxDate - data.minDate));
                            }
                            
                            function getValuesAtDate(targetDate) {
                                const results = [];
                                const targetTime = targetDate.getTime();
                                
                                for (const [distid, records] of Object.entries(data.distributorData)) {
                                    if (!isDistributorVisible(distid)) continue;
                                    
                                    // Find the most recent record before or at the target date
                                    let closestRecord = null;
                                    for (const record of records) {
                                        if (record.date.getTime() <= targetTime) {
                                            if (!closestRecord || record.date > closestRecord.date) {
                                                closestRecord = record;
                                            }
                                        }
                                    }
                                    
                                    if (closestRecord) {
                                        results.push({
                                            distid: distid,
                                            price: closestRecord.price,
                                            qty: closestRecord.qty,
                                            color: data.getDistributorColor(distid)
                                        });
                                    }
                                }
                                
                                // Sort by price descending
                                results.sort((a, b) => b.price - a.price);
                                return results;
                            }
                            
                            function updateMarker(e) {
                                const rect = overlay.getBoundingClientRect();
                                const x = e.clientX - rect.left + data.margin.left;
                                
                                // Clamp x to chart area
                                const clampedX = Math.max(data.margin.left, Math.min(data.margin.left + data.width, x));
                                
                                // Update marker line position
                                marker.setAttribute('x1', clampedX);
                                marker.setAttribute('x2', clampedX);
                                marker.style.display = 'block';
                                
                                // Get date at this position
                                const dateAtX = getDateFromX(clampedX);
                                const values = getValuesAtDate(dateAtX);
                                
                                // Build tooltip content - show time when zoomed in
                                let dateStr;
                                dateStr = dateAtX.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) +
                                          ' ' + dateAtX.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true });
                                
                                let tooltipHTML = `<div style="font-weight: 600; margin-bottom: 8px; color: #fff; border-bottom: 1px solid #444; padding-bottom: 6px;">${dateStr}</div>`;
                                
                                if (values.length === 0) {
                                    tooltipHTML += '<div style="color: #888; font-size: 12px;">No data at this point</div>';
                                } else {
                                    values.forEach(v => {
                                        tooltipHTML += `
                                            <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 4px; font-size: 12px;">
                                                <div style="width: 10px; height: 10px; border-radius: 2px; background: ${v.color}; flex-shrink: 0;"></div>
                                                <span style="color: #ccc; min-width: 45px;">${v.distid}</span>
                                                ${data.showPrice ? `<span style="color: #fff; font-weight: 500;">$${v.price.toFixed(2)}</span>` : ''}
                                                ${data.showQty ? `<span style="color: #aaa; margin-left: 8px;">Qty: ${v.qty}</span>` : ''}
                                            </div>
                                        `;
                                    });
                                }
                                
                                tooltip.innerHTML = tooltipHTML;
                                tooltip.style.display = 'block';
                                
                                // Position tooltip
                                const containerRect = container.getBoundingClientRect();
                                let tooltipX = e.clientX - containerRect.left + 15;
                                
                                // If tooltip would go off right edge, show on left of cursor
                                if (tooltipX + 200 > container.offsetWidth) {
                                    tooltipX = e.clientX - containerRect.left - 215;
                                }
                                
                                tooltip.style.left = tooltipX + 'px';
                                tooltip.style.top = '10px';
                            }
                            
                            function hideMarker() {
                                marker.style.display = 'none';
                                tooltip.style.display = 'none';
                            }
                            
                            overlay.addEventListener('mousemove', updateMarker);
                            overlay.addEventListener('mouseleave', hideMarker);
                        }
                        
                        // Show chart tooltip
                        function showHistoryTooltip(event, distid, date, time, price, qty, dataType) {
                            const tooltip = document.getElementById('g_ffl_cockpit_history_tooltip');
                            if (!tooltip) return;
                            
                            const showPrice = !dataType || dataType === 'both' || dataType === 'price';
                            const showQty = !dataType || dataType === 'both' || dataType === 'qty';
                            
                            let contentHTML = `
                                <div class="g-ffl-cockpit-chart-tooltip-header">${distid}</div>
                                <div style="font-size: 12px; color: #aaa; margin-bottom: 8px;">${date} at ${time}</div>
                            `;
                            
                            if (showPrice) {
                                contentHTML += `
                                    <div class="g-ffl-cockpit-chart-tooltip-row">
                                        <span>Price:</span>
                                        <span style="font-weight: 600;">$${price}</span>
                                    </div>
                                `;
                            }
                            if (showQty) {
                                contentHTML += `
                                    <div class="g-ffl-cockpit-chart-tooltip-row">
                                        <span>Quantity:</span>
                                        <span style="font-weight: 600;">${qty}</span>
                                    </div>
                                `;
                            }
                            
                            tooltip.innerHTML = contentHTML;
                            
                            const container = document.getElementById('g_ffl_cockpit_history_chart_container');
                            const containerRect = container.getBoundingClientRect();
                            
                            let left = event.clientX - containerRect.left + 15;
                            let top = event.clientY - containerRect.top - 10;
                            
                            // Keep tooltip within container
                            if (left + 200 > container.offsetWidth) {
                                left = event.clientX - containerRect.left - 220;
                            }
                            
                            tooltip.style.left = left + 'px';
                            tooltip.style.top = top + 'px';
                            tooltip.style.display = 'block';
                        }
                        
                        // Hide chart tooltip
                        function hideHistoryTooltip() {
                            const tooltip = document.getElementById('g_ffl_cockpit_history_tooltip');
                            if (tooltip) {
                                tooltip.style.display = 'none';
                            }
                        }
                        
                        // Clear history section when leaving dashboard
                        function clearProductHistory() {
                            window.gffcProductHistoryData = [];
                            window.gffcProductHistorySelectedDistributor = 'all';
                            window.gffcProductHistoryChartDataType = 'both';
                            window.gffcHiddenDistributors = new Set();
                            
                            const loadingEl = document.getElementById('g_ffl_cockpit_history_loading');
                            const emptyEl = document.getElementById('g_ffl_cockpit_history_empty');
                            const chartContainer = document.getElementById('g_ffl_cockpit_history_chart_container');
                            const tableContainer = document.getElementById('g_ffl_cockpit_history_table_container');
                            
                            if (loadingEl) loadingEl.style.display = 'none';
                            if (emptyEl) emptyEl.style.display = 'none';
                            if (chartContainer) chartContainer.innerHTML = '';
                            if (tableContainer) tableContainer.innerHTML = '';
                            
                            // Reset chart data type buttons
                            const bothBtn = document.getElementById('g_ffl_cockpit_history_show_both_btn');
                            const priceBtn = document.getElementById('g_ffl_cockpit_history_show_price_btn');
                            const qtyBtn = document.getElementById('g_ffl_cockpit_history_show_qty_btn');
                            [priceBtn, qtyBtn].forEach(btn => {
                                if (btn) {
                                    btn.classList.remove('active');
                                    btn.style.background = '#f5f5f5';
                                    btn.style.color = '#666';
                                }
                            });
                            if (bothBtn) {
                                bothBtn.classList.add('active');
                                bothBtn.style.background = '#0073aa';
                                bothBtn.style.color = 'white';
                            }
                        }
                        
                        // =====================================================
                        // End Product History Section Functions
                        // =====================================================

                        function openCategoryChangeModal(upc, site_product_id, distsku, distid) {
                            const modal = document.getElementById('categoryChangeModal');
                            modal.style.display = 'flex';

                            // Fetch category list and populate modal
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "get_category_list", "data": { "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>" } })
                            })
                            .then(response => response.json())
                            .then(data => {
                                const container = document.getElementById('categoryList');
                                container.innerHTML = ""; // Clear previous content
                                if (data.categories.length > 0) {
                                    data.categories.forEach(item => {
                                        const label = document.createElement("label");
                                        label.style.display = "block";
                                        label.style.marginBottom = "5px";

                                        const radio = document.createElement("input");
                                        radio.type = "radio";
                                        radio.name = "category";
                                        radio.value = item.id;
                                        radio.style.marginRight = "10px";

                                        label.appendChild(radio);
                                        label.appendChild(document.createTextNode(item.name + (item.parent ? ` (${item.parent})` : "")));
                                        container.appendChild(label);
                                    });
                                    document.getElementById("categoryChangeModalSearch").dispatchEvent(new Event("input", { bubbles: true }));
                                }
                            });

                            // Update category button logic
                            document.getElementById('updateCategoryButton').onclick = function () {
                                const selected = document.querySelector('input[name="category"]:checked');
                                if (!selected) {
                                    alert("You must select a valid category");
                                    return;
                                }

                                document.getElementById("updateCategoryButton").disabled = true;
                                document.getElementById('updateCategoryButton').innerText = 'Please Wait...';
                            
                                fetch("https://ffl-api.garidium.com", {
                                    method: "POST",
                                    headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                    },
                                    body: JSON.stringify({
                                        "action": "update_product_category",
                                        "data": {
                                            "product_id": site_product_id,
                                            "category_id": selected.value,
                                            "upc": upc,
                                            "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"
                                        }
                                    })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    if (data.success) {
                                        closeCategoryChangeModal();
                                        document.getElementById(distid + "_" + upc + "_category").innerHTML='Pending Change';
                                    } else {
                                        alert("There was a problem updating the category");
                                    }
                                });
                            };
                            document.getElementById("updateCategoryButton").disabled = false;
                            document.getElementById('updateCategoryButton').innerText = 'Apply Category Update';
                            //document.getElementById('categoryChangeModalSearch').value = "";

                        }

                        function closeCategoryChangeModal() {
                            const modal = document.getElementById('categoryChangeModal');
                            modal.style.display = 'none';
                        }

                        function openDashboardCategoryChangeModal(upc, site_product_id, distsku, distid) {
                            const modal = document.getElementById('categoryChangeModal');
                            modal.style.display = 'flex';

                            // Fetch category list and populate modal
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "get_category_list", "data": { "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>" } })
                            })
                            .then(response => response.json())
                            .then(data => {
                                const container = document.getElementById('categoryList');
                                container.innerHTML = ""; // Clear previous content
                                if (data.categories.length > 0) {
                                    data.categories.forEach(item => {
                                        const label = document.createElement("label");
                                        label.style.display = "block";
                                        label.style.marginBottom = "5px";

                                        const radio = document.createElement("input");
                                        radio.type = "radio";
                                        radio.name = "category";
                                        radio.value = item.id;
                                        radio.style.marginRight = "10px";

                                        label.appendChild(radio);
                                        label.appendChild(document.createTextNode(item.name + (item.parent ? ` (${item.parent})` : "")));
                                        container.appendChild(label);
                                    });
                                    document.getElementById("categoryChangeModalSearch").dispatchEvent(new Event("input", { bubbles: true }));
                                }
                            });

                            // Update category button logic for dashboard
                            document.getElementById('updateCategoryButton').onclick = function () {
                                const selected = document.querySelector('input[name="category"]:checked');
                                if (!selected) {
                                    alert("You must select a valid category");
                                    return;
                                }

                                document.getElementById("updateCategoryButton").disabled = true;
                                document.getElementById('updateCategoryButton').innerText = 'Please Wait...';
                            
                                fetch("https://ffl-api.garidium.com", {
                                    method: "POST",
                                    headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                    },
                                    body: JSON.stringify({
                                        "action": "update_product_category",
                                        "data": {
                                            "product_id": site_product_id,
                                            "category_id": selected.value,
                                            "upc": upc,
                                            "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"
                                        }
                                    })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    if (data.success) {
                                        closeCategoryChangeModal();
                                        // Update the dashboard category display
                                        const categoryElement = document.getElementById('g_ffl_cockpit_dashboard_product_category');
                                        if (categoryElement) {
                                            const selectedCategoryText = document.querySelector('input[name="category"]:checked').parentNode.textContent.trim();
                                            categoryElement.textContent = selectedCategoryText;
                                        }
                                        
                                        // Show success message
                                        alert('Category updated successfully! Changes may take up to an hour to apply.');
                                    } else {
                                        alert("There was a problem updating the category");
                                    }
                                    document.getElementById("updateCategoryButton").disabled = false;
                                    document.getElementById('updateCategoryButton').innerText = 'Apply Category Update';
                                });
                            };
                            
                            document.getElementById("updateCategoryButton").disabled = false;
                            document.getElementById('updateCategoryButton').innerText = 'Apply Category Update';
                        }

                        function searchByUPC(upc) {
                            if (upc && upc !== 'N/A') {
                                // Set the search input field to the UPC
                                document.getElementById('cockpit-product-search-input').value = upc;
                                // Trigger the search
                                loadGrid();
                            }
                        }

                        function toggleStockAlert(upc, newStatus, iconElement) {
                            if (!upc || upc === 'N/A') {
                                alert('Invalid UPC');
                                return;
                            }
                            // When enabling (currently OFF), open the wishlist modal to optionally collect customer info
                            if (newStatus) {
                                gffcOpenWishlistAddModal(upc, iconElement, null);
                                return;
                            }
                            // When clicking an active bell, fetch existing details and open the edit modal
                            gffcOpenWishlistEditModal(upc, iconElement);
                        }

                        function gffcOpenWishlistEditModal(upc, iconElement) {
                            // Fetch current wishlist to find this item's details
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "get_upc_in_stock_alert_list", "data": { "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>" } })
                            })
                            .then(function(r) { return r.text(); })
                            .then(function(text) {
                                var obj = text;
                                for (var i = 0; i < 5; i++) {
                                    if (typeof obj !== 'string') break;
                                    try { obj = JSON.parse(obj); } catch(e) { break; }
                                }
                                return obj;
                            })
                            .then(function(data) {
                                var existing = null;
                                if (data && data.alerts) {
                                    for (var i = 0; i < data.alerts.length; i++) {
                                        if (String(data.alerts[i].upc) === String(upc)) {
                                            existing = data.alerts[i];
                                            break;
                                        }
                                    }
                                }
                                gffcOpenWishlistAddModal(upc, iconElement, existing);
                            })
                            .catch(function(e) {
                                console.error('Failed to load wishlist entry:', e);
                                gffcOpenWishlistAddModal(upc, iconElement, null);
                            });
                        }

                        function gffcSubmitStockAlert(upc, newStatus, customerName, customerPhone, notes, iconElement) {
                            // Optimistic UI update
                            const originalColor = iconElement ? iconElement.style.color : null;
                            if (iconElement) {
                                iconElement.style.color = newStatus ? '#ff6b35' : '#ccc';
                                iconElement.title = newStatus ? 'On wishlist - Click to remove' : 'Add to wishlist';
                            }
                            const payload = {
                                "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                "upc": upc,
                                "active": newStatus
                            };
                            if (customerName) payload.customer_name = customerName;
                            if (customerPhone) payload.customer_phone = customerPhone;
                            if (notes) payload.notes = notes;
                            return fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "set_upc_in_stock_alert", "data": payload })
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    updateAllUPCAlertIcons(upc, data.alert_active);
                                    return true;
                                } else {
                                    if (iconElement) {
                                        iconElement.style.color = originalColor;
                                        iconElement.title = !newStatus ? 'On wishlist - Click to remove' : 'Add to wishlist';
                                    }
                                    alert('Failed to update wishlist. Please try again.');
                                    return false;
                                }
                            })
                            .catch(error => {
                                if (iconElement) {
                                    iconElement.style.color = originalColor;
                                    iconElement.title = !newStatus ? 'On wishlist - Click to remove' : 'Add to wishlist';
                                }
                                alert('Error updating wishlist. Please try again.');
                                console.error('Error:', error);
                                return false;
                            });
                        }

                        function gffcOpenWishlistAddModal(upc, iconElement, existing) {
                            // Store the icon reference for use after submit
                            window._gffcWishlistAddCtx = { upc: upc, icon: iconElement, isEdit: !!existing };
                            document.getElementById('gffc-wishlist-add-upc').textContent = upc;
                            document.getElementById('gffc-wishlist-add-name').value = (existing && existing.customer_name) ? existing.customer_name : '';
                            document.getElementById('gffc-wishlist-add-phone').value = (existing && existing.customer_phone) ? existing.customer_phone : '';
                            document.getElementById('gffc-wishlist-add-notes').value = (existing && existing.notes) ? existing.notes : '';

                            // Toggle title, button label, and Remove button visibility
                            document.getElementById('gffc-wishlist-modal-title').textContent = existing ? 'Edit Wishlist Item' : 'Add to Wishlist';
                            document.getElementById('gffc-wishlist-submit-btn').innerHTML = existing
                                ? '<i class="fas fa-save" style="margin-right:5px;"></i>Save Changes'
                                : '<i class="fas fa-bell" style="margin-right:5px;"></i>Add to Wishlist';
                            document.getElementById('gffc-wishlist-remove-btn').style.display = existing ? 'inline-flex' : 'none';

                            document.getElementById('gffc-wishlist-add-modal').style.display = 'flex';
                            setTimeout(function() { document.getElementById('gffc-wishlist-add-name').focus(); }, 50);
                        }

                        function gffcWishlistAddSubmit() {
                            const ctx = window._gffcWishlistAddCtx || {};
                            const name = document.getElementById('gffc-wishlist-add-name').value.trim();
                            const phone = document.getElementById('gffc-wishlist-add-phone').value.trim();
                            const notes = document.getElementById('gffc-wishlist-add-notes').value.trim();
                            gffcSubmitStockAlert(ctx.upc, true, name || null, phone || null, notes || null, ctx.icon);
                            document.getElementById('gffc-wishlist-add-modal').style.display = 'none';
                        }

                        function gffcWishlistModalRemove() {
                            const ctx = window._gffcWishlistAddCtx || {};
                            if (!ctx.upc) return;
                            if (!confirm('Remove this item from your wishlist?')) return;
                            gffcSubmitStockAlert(ctx.upc, false, null, null, null, ctx.icon);
                            document.getElementById('gffc-wishlist-add-modal').style.display = 'none';
                        }

                        function gffcOpenWishlistViewer() {
                            document.getElementById('gffc-wishlist-viewer-modal').style.display = 'flex';
                            const body = document.getElementById('gffc-wishlist-viewer-body');
                            body.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8;"><i class="fas fa-spinner fa-spin" style="font-size:24px;"></i><div style="margin-top:8px;">Loading wishlist...</div></div>';
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "get_upc_in_stock_alert_list", "data": { "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>" } })
                            })
                            .then(function(r) { return r.text(); })
                            .then(function(text) {
                                // Handle gzipped/base64 responses or plain JSON
                                var obj = text;
                                for (var i = 0; i < 5; i++) {
                                    if (typeof obj !== 'string') break;
                                    try { obj = JSON.parse(obj); } catch(e) { break; }
                                }
                                return obj;
                            })
                            .then(function(data) {
                                gffcRenderWishlist(data && data.alerts ? data.alerts : []);
                            })
                            .catch(function(e) {
                                body.innerHTML = '<div style="text-align:center;padding:40px;color:#ef4444;">Failed to load wishlist.</div>';
                                console.error('Wishlist load error:', e);
                            });
                        }

                        function gffcRenderWishlist(alerts) {
                            const body = document.getElementById('gffc-wishlist-viewer-body');
                            if (!alerts || alerts.length === 0) {
                                body.innerHTML = '<div style="text-align:center;padding:40px;color:#94a3b8;"><i class="far fa-bell" style="font-size:36px;display:block;margin-bottom:8px;"></i>Your wishlist is empty.<div style="font-size:12px;margin-top:6px;">Click the bell icon next to any product to add it.</div></div>';
                                return;
                            }
                            var html = '<div style="font-size:12px;color:#64748b;margin-bottom:10px;"><b>' + alerts.length + '</b> item' + (alerts.length === 1 ? '' : 's') + ' on your wishlist</div>';
                            html += '<div style="display:flex;flex-direction:column;gap:10px;">';
                            for (var i = 0; i < alerts.length; i++) {
                                var a = alerts[i];
                                var imgHtml = a.image_url
                                    ? '<img src="' + a.image_url + '" style="width:60px;height:60px;object-fit:contain;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;flex-shrink:0;" onerror="this.style.display=\'none\';">'
                                    : '<div style="width:60px;height:60px;border:1px solid #e2e8f0;border-radius:6px;background:#f8fafc;display:flex;align-items:center;justify-content:center;color:#cbd5e1;flex-shrink:0;"><i class="fas fa-image"></i></div>';
                                var qty = (a.total_qty && Number(a.total_qty) > 0) ? '<span style="color:#10b981;font-weight:600;"><i class="fas fa-check-circle"></i> ' + a.total_qty + ' in stock</span>' : '<span style="color:#64748b;">Out of stock</span>';
                                html += '<div style="display:flex;gap:12px;padding:10px;border:1px solid #e2e8f0;border-radius:8px;background:#fff;">';
                                html += imgHtml;
                                html += '<div style="flex:1;min-width:0;">';
                                html += '<div style="font-size:13px;font-weight:700;line-height:1.3;margin-bottom:3px;"><a href="#" onclick="event.preventDefault();gffcWishlistSearchUPC(\'' + a.upc + '\');" style="color:#0073aa;text-decoration:none;" title="Click to search for this product">' + (a.product_name || 'Unknown Product') + '</a></div>';
                                html += '<div style="font-size:11px;color:#64748b;"><b>UPC:</b> <a href="#" onclick="event.preventDefault();gffcWishlistSearchUPC(\'' + a.upc + '\');" style="color:#0073aa;">' + a.upc + '</a>' + (a.mfg_name ? ' &nbsp;&middot;&nbsp; <b>Mfg:</b> ' + a.mfg_name : '') + ' &nbsp;&middot;&nbsp; ' + qty + '</div>';
                                if (a.customer_name || a.customer_phone) {
                                    html += '<div style="font-size:11px;color:#475569;margin-top:3px;"><i class="fas fa-user" style="margin-right:3px;color:#94a3b8;"></i>' + (a.customer_name || '') + (a.customer_phone ? ' &middot; ' + a.customer_phone : '') + '</div>';
                                }
                                if (a.notes) {
                                    html += '<div style="font-size:11px;color:#475569;margin-top:3px;font-style:italic;"><i class="fas fa-sticky-note" style="margin-right:3px;color:#f59e0b;"></i>' + a.notes + '</div>';
                                }
                                html += '</div>';
                                html += '<div style="display:flex;flex-direction:column;gap:4px;align-items:flex-end;flex-shrink:0;">';
                                html += '<button onclick="gffcWishlistRemove(\'' + a.upc + '\')" style="padding:4px 10px;font-size:11px;background:#fef2f2;color:#991b1b;border:1px solid #fecaca;border-radius:6px;cursor:pointer;font-weight:600;"><i class="fas fa-times"></i> Remove</button>';
                                html += '</div>';
                                html += '</div>';
                            }
                            html += '</div>';
                            body.innerHTML = html;
                        }

                        function gffcWishlistSearchUPC(upc) {
                            document.getElementById('gffc-wishlist-viewer-modal').style.display = 'none';
                            searchByUPC(upc);
                        }

                        function gffcWishlistRemove(upc) {
                            if (!confirm('Remove this item from your wishlist?')) return;
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({ "action": "delete_upc_in_stock_alert", "data": { "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>", "upc": upc } })
                            })
                            .then(function() {
                                updateAllUPCAlertIcons(upc, false);
                                gffcOpenWishlistViewer(); // Refresh
                            })
                            .catch(function(e) {
                                alert('Failed to remove item.');
                                console.error(e);
                            });
                        }

                        function updateAllUPCAlertIcons(upc, alertStatus) {
                            // Find all alert icons for this UPC in the current page
                            const allRows = document.querySelectorAll('[data-upc="' + upc + '"]');
                            
                            allRows.forEach(row => {
                                const alertIcon = row.querySelector('.fa-bell');
                                if (alertIcon) {
                                    // Update icon appearance
                                    alertIcon.style.color = alertStatus ? '#ff6b35' : '#ccc';
                                    alertIcon.title = alertStatus ? 'On wishlist - Click to remove' : 'Add to wishlist';
                                    // Update onclick handler for the new state
                                    alertIcon.setAttribute('onclick', `toggleStockAlert('${upc}', ${!alertStatus}, this)`);
                                }
                            });

                            // Also check for dashboard alert icon if it exists
                            const dashboardIcon = document.getElementById('dashboard-stock-alert-' + upc);
                            if (dashboardIcon) {
                                dashboardIcon.style.color = alertStatus ? '#ff6b35' : '#ccc';
                                dashboardIcon.title = alertStatus ? 'On wishlist - Click to remove' : 'Add to wishlist';
                                dashboardIcon.setAttribute('onclick', `toggleDashboardStockAlert('${upc}', ${!alertStatus}, this)`);
                            }
                        }

                        function toggleDashboardStockAlert(upc, newStatus, iconElement) {
                            // Delegate to the unified flow which handles the wishlist modal on enable
                            toggleStockAlert(upc, newStatus, iconElement);
                        }

                        // https://unpkg.com/browse/gridjs@5.1.0/dist/
                        let productGrid;

                        function gffcSetCookie(name, value, days) {
                            const maxAge = (typeof days === 'number') ? (days * 24 * 60 * 60) : (365 * 24 * 60 * 60);
                            let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; SameSite=Lax`;
                            if (window.location && window.location.protocol === 'https:') {
                                cookie += '; Secure';
                            }
                            document.cookie = cookie;
                        }

                        function gffcGetCookie(name) {
                            const needle = encodeURIComponent(name) + '=';
                            const parts = (document.cookie || '').split(';');
                            for (let i = 0; i < parts.length; i++) {
                                const part = parts[i].trim();
                                if (part.startsWith(needle)) {
                                    return decodeURIComponent(part.substring(needle.length));
                                }
                            }
                            return null;
                        }

                        function gffcNormalizeSearchTerm(term) {
                            return String(term || '')
                                .trim()
                                .toLowerCase()
                                .replace(/\s+/g, ' ');
                        }

                        function gffcSplitSearchTerms(value) {
                            return String(value || '')
                                .split(',')
                                .map(t => t.trim())
                                .filter(Boolean);
                        }

                        function gffcApplyInStockToSearchTermsForRequest(value, enabled) {
                            const terms = gffcSplitSearchTerms(value);
                            const withoutInStock = terms.filter(t => gffcNormalizeSearchTerm(t) !== 'in stock');
                            if (enabled) {
                                withoutInStock.push('in stock');
                            }
                            return withoutInStock.join(',');
                        }

                        // --- Product Search: sorting ---
                        const GFFC_PRODUCT_SEARCH_SORT_COL_COOKIE = 'gffc_product_search_sort_column';
                        const GFFC_PRODUCT_SEARCH_SORT_DIR_COOKIE = 'gffc_product_search_sort_direction';
                        const GFFC_PRODUCT_SEARCH_SORT_ALLOWED_COLS = new Set([
                            'upc',
                            'distid',
                            'qty_on_hand',
                            'mfg_name',
                            'unit_price',
                            'total_cost',
                            'item_gb_cat_name'
                        ]);

                        const GFFC_PRODUCT_SEARCH_SORT_LABELS = {
                            upc: 'UPC',
                            distid: 'Distributor',
                            qty_on_hand: 'Quantity',
                            mfg_name: 'Manufacturer',
                            unit_price: 'Cost',
                            total_cost: 'Total Cost',
                            item_gb_cat_name: 'Category'
                        };

                        function gffcSetProductSearchSortUiVisible(visible) {
                            const ui = document.getElementById('gffc-product-search-sort-ui');
                            if (!ui) return;
                            ui.style.display = visible ? 'flex' : 'none';

                            if (!visible) {
                                const panel = document.getElementById('gffc-product-search-sort-panel');
                                if (panel) panel.style.display = 'none';
                            }
                        }

                        function gffcUpdateProductSearchSortIndicator() {
                            const indicator = document.getElementById('gffc-product-search-sort-indicator');
                            const arrow = document.getElementById('gffc-product-search-sort-arrow');
                            if (!indicator || !arrow) return;

                            const settings = gffcGetProductSearchSortSettings();
                            indicator.textContent = GFFC_PRODUCT_SEARCH_SORT_LABELS[settings.orderColumn] || String(settings.orderColumn || '').toUpperCase();
                            arrow.textContent = settings.orderDirection === 'desc' ? '▼' : '▲';
                        }

                        function gffcApplyOrderParams(url, orderColumn, orderDirection) {
                            try {
                                const u = new URL(String(url));
                                if (orderColumn) u.searchParams.set('order_column', orderColumn);
                                if (orderDirection) u.searchParams.set('order_direction', orderDirection);
                                return u.toString();
                            } catch (e) {
                                // Fallback: best-effort append if URL parsing fails
                                const glue = String(url).includes('?') ? '&' : '?';
                                return `${url}${glue}order_column=${encodeURIComponent(orderColumn || '')}&order_direction=${encodeURIComponent(orderDirection || '')}`;
                            }
                        }

                        function gffcGetProductSearchSortSettings() {
                            const colSelect = document.getElementById('gffc-product-search-sort-column');
                            const dirSelect = document.getElementById('gffc-product-search-sort-direction');

                            let orderColumn = (colSelect && colSelect.value) ? String(colSelect.value) : (gffcGetCookie(GFFC_PRODUCT_SEARCH_SORT_COL_COOKIE) || 'upc');
                            let orderDirection = (dirSelect && dirSelect.value) ? String(dirSelect.value) : (gffcGetCookie(GFFC_PRODUCT_SEARCH_SORT_DIR_COOKIE) || 'asc');

                            if (!GFFC_PRODUCT_SEARCH_SORT_ALLOWED_COLS.has(orderColumn)) {
                                orderColumn = 'upc';
                            }
                            if (orderDirection !== 'asc' && orderDirection !== 'desc') {
                                orderDirection = 'asc';
                            }

                            return { orderColumn, orderDirection };
                        }

                        function gffcInitProductSearchSortControls() {
                            // Default to hidden; it will appear once results load.
                            gffcSetProductSearchSortUiVisible(false);

                            const colSelect = document.getElementById('gffc-product-search-sort-column');
                            const dirSelect = document.getElementById('gffc-product-search-sort-direction');
                            const button = document.getElementById('gffc-product-search-sort-button');
                            const panel = document.getElementById('gffc-product-search-sort-panel');
                            const wrapper = document.getElementById('gffc-product-search-sort-ui');
                            if (!colSelect || !dirSelect) return;

                            const colCookie = gffcGetCookie(GFFC_PRODUCT_SEARCH_SORT_COL_COOKIE);
                            const dirCookie = gffcGetCookie(GFFC_PRODUCT_SEARCH_SORT_DIR_COOKIE);

                            if (colCookie && GFFC_PRODUCT_SEARCH_SORT_ALLOWED_COLS.has(colCookie)) {
                                colSelect.value = colCookie;
                            } else {
                                colSelect.value = 'upc';
                            }
                            if (dirCookie === 'asc' || dirCookie === 'desc') {
                                dirSelect.value = dirCookie;
                            } else {
                                dirSelect.value = 'asc';
                            }

                            gffcUpdateProductSearchSortIndicator();

                            function closePanel() {
                                if (panel) panel.style.display = 'none';
                            }

                            function togglePanel() {
                                if (!panel) return;
                                panel.style.display = (panel.style.display === 'none' || !panel.style.display) ? 'block' : 'none';
                            }

                            if (button && button.dataset.bound !== '1') {
                                button.dataset.bound = '1';
                                button.addEventListener('click', function (e) {
                                    e.preventDefault();
                                    togglePanel();
                                });
                            }

                            if (document.documentElement.dataset.gffcSortOutsideBound !== '1') {
                                document.documentElement.dataset.gffcSortOutsideBound = '1';
                                document.addEventListener('click', function (e) {
                                    if (!panel || panel.style.display !== 'block') return;
                                    const target = e && e.target;
                                    if (!target || typeof target.closest !== 'function') return;
                                    if (wrapper && target.closest('#gffc-product-search-sort-ui')) return;
                                    closePanel();
                                }, true);
                            }

                            if (colSelect.dataset.bound === '1') return;
                            colSelect.dataset.bound = '1';
                            dirSelect.dataset.bound = '1';

                            function onSortChanged() {
                                const settings = gffcGetProductSearchSortSettings();
                                gffcSetCookie(GFFC_PRODUCT_SEARCH_SORT_COL_COOKIE, settings.orderColumn, 365);
                                gffcSetCookie(GFFC_PRODUCT_SEARCH_SORT_DIR_COOKIE, settings.orderDirection, 365);

                                gffcUpdateProductSearchSortIndicator();

                                if (panel) panel.style.display = 'none';

                                // If we have already run a search, re-run it to refresh ordering.
                                if (window.gffcLastProductSearchValue && String(window.gffcLastProductSearchValue).trim().length > 0) {
                                    loadGrid();
                                }
                            }

                            colSelect.addEventListener('change', onSortChanged);
                            dirSelect.addEventListener('change', onSortChanged);
                        }

                        // --- Product Search: recent searches (pills) ---
                        const GFFC_RECENT_SEARCHES_KEY = 'gffc_recent_product_searches_v1';
                        const GFFC_RECENT_SEARCHES_MAX = 8;

                        function gffcGetRecentSearches() {
                            try {
                                const raw = window.localStorage ? localStorage.getItem(GFFC_RECENT_SEARCHES_KEY) : null;
                                if (!raw) return [];
                                const parsed = JSON.parse(raw);
                                if (!Array.isArray(parsed)) return [];

                                // Normalize shape: [{ q: string, ignore: boolean, inStock: boolean }]
                                return parsed
                                    .map(item => {
                                        const q = (item && typeof item.q === 'string') ? item.q : '';
                                        const ignore = !!(item && item.ignore);
                                        const inStock = !!(item && item.inStock);
                                        return { q: q.trim(), ignore, inStock };
                                    })
                                    .filter(item => item.q.length > 0);
                            } catch (e) {
                                return [];
                            }
                        }

                        function gffcSetRecentSearches(items) {
                            try {
                                if (!window.localStorage) return;
                                localStorage.setItem(GFFC_RECENT_SEARCHES_KEY, JSON.stringify(items || []));
                            } catch (e) {
                                // ignore
                            }
                        }

                        function gffcFormatRecentSearchLabel(item) {
                            const q = (item && item.q) ? item.q : '';
                            // Keep pills readable; avoid huge buttons.
                            const max = 42;
                            const trimmed = q.trim();
                            if (trimmed.length <= max) return trimmed;
                            return trimmed.slice(0, max - 1) + '…';
                        }

                        function gffcAlignRecentSearchesToInput() {
                            const container = document.getElementById('gffc-recent-searches');
                            const input = document.getElementById('cockpit-product-search-input');
                            if (!container || !input) return;

                            const wrapper = document.getElementById('gffc-search-wrapper');
                            const isSearchActive = !!(wrapper && wrapper.classList && wrapper.classList.contains('active'));

                            // When results are shown, let the recent row expand to full width.
                            // Also expand immediately after the search button is clicked (wrapper becomes active),
                            // so we don't have to wait for the results request to complete.
                            if (window.gffcProductSearchHasResults || isSearchActive) {
                                container.style.marginLeft = '0';
                                container.style.marginRight = '0';
                                container.style.width = '100%';
                                container.style.maxWidth = 'none';
                                return;
                            }

                            // Parent is the flex container that holds input row + recent searches.
                            const parent = container.parentElement;
                            if (!parent || typeof parent.getBoundingClientRect !== 'function') return;

                            const inputRect = input.getBoundingClientRect();
                            const parentRect = parent.getBoundingClientRect();

                            if (!inputRect.width || !parentRect.width) return;

                            const left = Math.max(0, inputRect.left - parentRect.left);
                            const maxWidth = Math.max(0, Math.min(inputRect.width, parentRect.width - left));

                            // Make the recent searches row start at the input's left edge and match its width.
                            container.style.marginLeft = left + 'px';
                            container.style.marginRight = '0';
                            container.style.width = maxWidth + 'px';
                            container.style.maxWidth = maxWidth + 'px';
                        }

                        function gffcSetProductSearchHasResults(hasResults) {
                            window.gffcProductSearchHasResults = !!hasResults;
                            // Reflow any rendered recent searches row.
                            const c = document.getElementById('gffc-recent-searches');
                            if (c && c.style.display !== 'none') {
                                gffcAlignRecentSearchesToInput();
                            }
                        }

                        function gffcRenderRecentSearches() {
                            const container = document.getElementById('gffc-recent-searches');
                            if (!container) return;

                            const items = gffcGetRecentSearches();
                            if (!items.length) {
                                container.style.display = 'none';
                                container.innerHTML = '';
                                return;
                            }

                            container.style.display = 'block';
                            container.innerHTML = '';

                            const wrap = document.createElement('div');
                            wrap.style.display = 'flex';
                            wrap.style.alignItems = 'center';
                            wrap.style.gap = '8px';
                            wrap.style.flexWrap = 'wrap';
                            wrap.style.marginTop = '8px';

                            const label = document.createElement('div');
                            label.textContent = 'Recent:';
                            label.style.fontSize = '12px';
                            label.style.fontWeight = '600';
                            label.style.color = '#64748b';
                            wrap.appendChild(label);

                            const clearBtn = document.createElement('button');
                            clearBtn.type = 'button';
                            clearBtn.className = 'gffc-search-pill gffc-search-pill--clear';
                            clearBtn.setAttribute('data-gffc-recent-search-action', 'clear');
                            clearBtn.textContent = 'Clear';
                            clearBtn.title = 'Clear recent searches';
                            wrap.appendChild(clearBtn);

                            items.forEach((item, idx) => {
                                const btn = document.createElement('button');
                                btn.type = 'button';
                                btn.className = 'gffc-search-pill';
                                btn.setAttribute('data-gffc-recent-search-index', String(idx));
                                btn.title = item.q;
                                btn.textContent = gffcFormatRecentSearchLabel(item);
                                wrap.appendChild(btn);
                            });

                            container.appendChild(wrap);

                            // Align the row with the search input (input+button row is wider than input).
                            gffcAlignRecentSearchesToInput();

                            // Bind click handler once (delegated).
                            if (container.dataset.bound !== '1') {
                                container.dataset.bound = '1';
                                container.addEventListener('click', function (e) {
                                    const actionBtn = e && e.target && typeof e.target.closest === 'function'
                                        ? e.target.closest('button[data-gffc-recent-search-action]')
                                        : null;
                                    if (actionBtn) {
                                        const action = actionBtn.getAttribute('data-gffc-recent-search-action');
                                        if (action === 'clear') {
                                            gffcSetRecentSearches([]);
                                            gffcRenderRecentSearches();
                                            return;
                                        }
                                    }

                                    const target = e && e.target && typeof e.target.closest === 'function'
                                        ? e.target.closest('button[data-gffc-recent-search-index]')
                                        : null;
                                    if (!target) return;
                                    const idx = parseInt(target.getAttribute('data-gffc-recent-search-index') || '-1', 10);
                                    const list = gffcGetRecentSearches();
                                    const item = (idx >= 0 && idx < list.length) ? list[idx] : null;
                                    if (!item || !item.q) return;

                                    const input = document.getElementById('cockpit-product-search-input');
                                    if (input) input.value = item.q;

                                    const ignoreToggle = document.getElementById('ignore-product-restrictions-toggle');
                                    const inStockToggle = document.getElementById('gffc-in-stock-toggle');

                                    if (ignoreToggle) {
                                        ignoreToggle.checked = !!item.ignore;
                                        gffcSetCookie('gffc_ignore_restrictions', ignoreToggle.checked ? '1' : '0', 365);
                                    }
                                    if (inStockToggle) {
                                        inStockToggle.checked = !!item.inStock;
                                        gffcSetCookie('gffc_in_stock', inStockToggle.checked ? '1' : '0', 365);
                                    }

                                    loadGrid();
                                });
                            }
                        }

                        function gffcAddRecentSearch(searchValue, ignore, inStock) {
                            const q = String(searchValue || '').trim();
                            if (!q) return;

                            const normalized = gffcNormalizeSearchTerm(q);
                            let items = gffcGetRecentSearches();
                            items = items.filter(item => gffcNormalizeSearchTerm(item.q) !== normalized);
                            items.unshift({ q, ignore: !!ignore, inStock: !!inStock });
                            if (items.length > GFFC_RECENT_SEARCHES_MAX) {
                                items = items.slice(0, GFFC_RECENT_SEARCHES_MAX);
                            }
                            gffcSetRecentSearches(items);
                            gffcRenderRecentSearches();
                        }

                        function gffcInitRecentSearchesUI() {
                            // Inject minimal styles for pills (scoped via class).
                            if (!document.getElementById('gffc-search-pill-style')) {
                                const style = document.createElement('style');
                                style.id = 'gffc-search-pill-style';
                                style.textContent = `
                                    #product_feed .gffc-search-pill {
                                        appearance: none;
                                        border: 1px solid #d0d7de;
                                        background: #fff;
                                        color: #2271b1;
                                        border-radius: 999px;
                                        padding: 4px 10px;
                                        font-size: 12px;
                                        font-weight: 600;
                                        cursor: pointer;
                                        line-height: 1.2;
                                    }
                                    #product_feed .gffc-search-pill:hover {
                                        background: #f0f6fc;
                                        border-color: #b6c2cf;
                                    }
                                    #product_feed .gffc-search-pill--clear {
                                        color: #64748b;
                                    }
                                `;
                                document.head.appendChild(style);
                            }

                            if (!window.gffcRecentSearchResizeBound) {
                                window.gffcRecentSearchResizeBound = true;
                                window.addEventListener('resize', function () {
                                    // Only matters when visible.
                                    const c = document.getElementById('gffc-recent-searches');
                                    if (c && c.style.display !== 'none') {
                                        gffcAlignRecentSearchesToInput();
                                    }
                                });
                            }
                            gffcRenderRecentSearches();
                        }

                        function gffcInitProductSearchToggles() {
                            const ignoreToggle = document.getElementById('ignore-product-restrictions-toggle');
                            const inStockToggle = document.getElementById('gffc-in-stock-toggle');

                            if (!ignoreToggle || !inStockToggle) return;

                            const ignoreCookie = gffcGetCookie('gffc_ignore_restrictions');
                            const inStockCookie = gffcGetCookie('gffc_in_stock');

                            if (ignoreCookie !== null) {
                                ignoreToggle.checked = (ignoreCookie === '1');
                            }
                            if (inStockCookie !== null) {
                                inStockToggle.checked = (inStockCookie === '1');
                            }

                            ignoreToggle.addEventListener('change', function () {
                                gffcSetCookie('gffc_ignore_restrictions', ignoreToggle.checked ? '1' : '0', 365);
                            });
                            inStockToggle.addEventListener('change', function () {
                                gffcSetCookie('gffc_in_stock', inStockToggle.checked ? '1' : '0', 365);
                            });
                        }

                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', gffcInitProductSearchToggles);
                            document.addEventListener('DOMContentLoaded', gffcInitRecentSearchesUI);
                            document.addEventListener('DOMContentLoaded', gffcInitProductSearchSortControls);
                        } else {
                            gffcInitProductSearchToggles();
                            gffcInitRecentSearchesUI();
                            gffcInitProductSearchSortControls();
                        }

                        // Product Search: native barcode/QR scanner
                        window.gffcProductSearchScanner = window.gffcProductSearchScanner || {
                            stream: null,
                            intervalId: null,
                            detector: null,
                            detecting: false,
                            running: false,
                            zxingReader: null,
                            zxingControls: null,
                        };

                        function gffcLoadScriptOnce(id, src) {
                            return new Promise((resolve, reject) => {
                                const existing = document.getElementById(id);
                                if (existing) {
                                    // If it already loaded, resolve; otherwise wait.
                                    if (existing.dataset.loaded === '1') return resolve(true);
                                    existing.addEventListener('load', () => resolve(true), { once: true });
                                    existing.addEventListener('error', () => reject(new Error('Script load failed')), { once: true });
                                    return;
                                }

                                const s = document.createElement('script');
                                s.id = id;
                                s.src = src;
                                s.async = true;
                                s.defer = true;
                                s.addEventListener('load', () => {
                                    s.dataset.loaded = '1';
                                    resolve(true);
                                }, { once: true });
                                s.addEventListener('error', () => reject(new Error('Script load failed')), { once: true });
                                document.head.appendChild(s);
                            });
                        }

                        async function gffcEnsureZXingLoaded() {
                            if (window.ZXing && window.ZXing.BrowserMultiFormatReader) return true;
                            // Load vendored (local) ZXing UMD bundle for WordPress plugin compliance.
                            const localZXingUrl = <?php echo wp_json_encode( plugin_dir_url( __FILE__ ) . 'js/vendor/zxing-library-0.21.3-umd.min.js' ); ?>;
                            await gffcLoadScriptOnce('gffc-zxing-umd', localZXingUrl);
                            return !!(window.ZXing && window.ZXing.BrowserMultiFormatReader);
                        }

                        function gffcSetProductSearchScannerError(message) {
                            const el = document.getElementById('gffc-upc-scanner-error');
                            if (!el) return;
                            el.textContent = String(message || 'Unable to start scanner.');
                            el.style.display = 'block';
                        }

                        function gffcClearProductSearchScannerError() {
                            const el = document.getElementById('gffc-upc-scanner-error');
                            if (!el) return;
                            el.textContent = '';
                            el.style.display = 'none';
                        }

                        function gffcStopProductSearchScannerStream() {
                            const state = window.gffcProductSearchScanner;
                            state.running = false;

                            // Stop ZXing controls (if used)
                            if (state.zxingControls && typeof state.zxingControls.stop === 'function') {
                                try { state.zxingControls.stop(); } catch (e) {}
                            }
                            state.zxingControls = null;
                            if (state.zxingReader && typeof state.zxingReader.reset === 'function') {
                                try { state.zxingReader.reset(); } catch (e) {}
                            }
                            state.zxingReader = null;

                            if (state.intervalId) {
                                clearInterval(state.intervalId);
                                state.intervalId = null;
                            }
                            state.detecting = false;

                            const video = document.getElementById('gffc-upc-scanner-video');
                            if (video) {
                                try { video.pause(); } catch (e) {}
                                try { video.srcObject = null; } catch (e) {}
                            }

                            if (state.stream && state.stream.getTracks) {
                                try {
                                    state.stream.getTracks().forEach(t => {
                                        try { t.stop(); } catch (e) {}
                                    });
                                } catch (e) {}
                            }
                            state.stream = null;
                        }

                        function gffcCloseProductSearchScanner() {
                            gffcStopProductSearchScannerStream();
                            const modal = document.getElementById('gffc-upc-scanner-modal');
                            if (modal) modal.style.display = 'none';
                        }

                        async function gffcOpenProductSearchScanner() {
                            const modal = document.getElementById('gffc-upc-scanner-modal');
                            const video = document.getElementById('gffc-upc-scanner-video');

                            if (!modal || !video) return;

                            // Reset any prior session.
                            gffcStopProductSearchScannerStream();
                            gffcClearProductSearchScannerError();

                            modal.style.display = 'flex';

                            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                                gffcSetProductSearchScannerError('Camera access is not available in this browser. Please enter the UPC manually.');
                                return;
                            }

                            const state = window.gffcProductSearchScanner;

                            try {
                                state.running = true;

                                if ('BarcodeDetector' in window) {
                                    // Prefer rear camera.
                                    state.stream = await navigator.mediaDevices.getUserMedia({
                                        video: { facingMode: { ideal: 'environment' } },
                                        audio: false
                                    });

                                    video.srcObject = state.stream;
                                    await video.play();

                                    // Some browsers throw on unsupported formats; fall back to default ctor.
                                    try {
                                        state.detector = new BarcodeDetector({
                                            formats: ['upc_a', 'upc_e', 'ean_13', 'ean_8', 'code_128', 'code_39', 'qr_code']
                                        });
                                    } catch (e) {
                                        state.detector = new BarcodeDetector();
                                    }

                                    state.intervalId = setInterval(async function () {
                                        if (!state.running || state.detecting || !state.detector) return;
                                        if (!video || video.readyState < 2) return;

                                        state.detecting = true;
                                        try {
                                            const results = await state.detector.detect(video);
                                            if (results && results.length) {
                                                const raw = String(results[0].rawValue || '').trim();
                                                const digitsOnly = raw.replace(/[^0-9]/g, '');
                                                const value = digitsOnly.length >= 6 ? digitsOnly : raw;

                                                const input = document.getElementById('cockpit-product-search-input');
                                                if (input) {
                                                    input.value = value;
                                                    try { input.focus(); } catch (e) {}
                                                }

                                                gffcCloseProductSearchScanner();
                                                if (typeof loadGrid === 'function') {
                                                    loadGrid();
                                                }
                                            }
                                        } catch (e) {
                                            // Ignore transient detection errors.
                                        } finally {
                                            state.detecting = false;
                                        }
                                    }, 250);
                                } else {
                                    // iOS / unsupported browsers: load ZXing and decode from video.
                                    const ok = await gffcEnsureZXingLoaded();
                                    if (!ok) {
                                        gffcSetProductSearchScannerError('Barcode scanning is not supported in this browser. Please enter the UPC manually.');
                                        return;
                                    }

                                    const ZX = window.ZXing;
                                    let hints;
                                    try {
                                        hints = new Map();
                                        if (ZX && ZX.DecodeHintType && ZX.BarcodeFormat) {
                                            hints.set(ZX.DecodeHintType.POSSIBLE_FORMATS, [
                                                ZX.BarcodeFormat.UPC_A,
                                                ZX.BarcodeFormat.UPC_E,
                                                ZX.BarcodeFormat.EAN_13,
                                                ZX.BarcodeFormat.EAN_8,
                                                ZX.BarcodeFormat.CODE_128,
                                                ZX.BarcodeFormat.CODE_39,
                                                ZX.BarcodeFormat.QR_CODE,
                                            ]);
                                        }
                                    } catch (e) {
                                        hints = undefined;
                                    }

                                    state.zxingReader = new ZX.BrowserMultiFormatReader(hints, 250);
                                    state.zxingControls = await state.zxingReader.decodeFromVideoDevice(
                                        null,
                                        video,
                                        function (result, err) {
                                            if (!state.running) return;
                                            if (result && typeof result.getText === 'function') {
                                                const raw = String(result.getText() || '').trim();
                                                const digitsOnly = raw.replace(/[^0-9]/g, '');
                                                const value = digitsOnly.length >= 6 ? digitsOnly : raw;

                                                const input = document.getElementById('cockpit-product-search-input');
                                                if (input) {
                                                    input.value = value;
                                                    try { input.focus(); } catch (e) {}
                                                }

                                                gffcCloseProductSearchScanner();
                                                if (typeof loadGrid === 'function') {
                                                    loadGrid();
                                                }
                                            }
                                        }
                                    );
                                }
                            } catch (e) {
                                gffcStopProductSearchScannerStream();
                                const msg = (e && e.name === 'NotAllowedError')
                                    ? 'Camera permission was denied. Please allow camera access or enter the UPC manually.'
                                    : 'Unable to start the camera. Please enter the UPC manually.';
                                gffcSetProductSearchScannerError(msg);
                            }
                        }

                        if (!window.gffcProductSearchScannerUnloadBound) {
                            window.gffcProductSearchScannerUnloadBound = true;
                            window.addEventListener('beforeunload', function () {
                                try { gffcStopProductSearchScannerStream(); } catch (e) {}
                            });
                        }

                        function gffcOpenConfigurationTab() {
                            const tabBtn = document.querySelector('#cockpit_main_tab_control .tablinks[onclick*="configuration"]');
                            if (tabBtn && typeof window.openTab === 'function') {
                                try {
                                    window.openTab({ currentTarget: tabBtn, preventDefault: function(){} }, 'configuration');
                                    return;
                                } catch (e) {}
                            }
                            if (tabBtn) {
                                tabBtn.click();
                                return;
                            }
                            const accordionBtn = document.querySelector('button.accordion');
                            if (accordionBtn) accordionBtn.click();
                        }

                        function gffcSetProductSearchEnabledState(enabled, message) {
                            const searchInput = document.getElementById('cockpit-product-search-input');
                            const searchButton = document.getElementById('gffc-product-search-button');
                            const scanButton = document.querySelector('#product_feed .gffc-scan-icon-btn');
                            const ignoreToggle = document.getElementById('ignore-product-restrictions-toggle');
                            const inStockToggle = document.getElementById('gffc-in-stock-toggle');
                            const blocker = document.getElementById('gffc-product-search-blocker');
                            const blockerMessage = document.getElementById('gffc-product-search-blocker-message');
                            const productTab = document.getElementById('product_feed');
                            const dashboard = document.getElementById('g_ffl_cockpit_single_upc_dashboard');

                            if (searchInput) searchInput.disabled = !enabled;
                            if (searchButton) searchButton.disabled = !enabled;
                            if (scanButton) scanButton.disabled = !enabled;
                            if (ignoreToggle) ignoreToggle.disabled = !enabled;
                            if (inStockToggle) inStockToggle.disabled = !enabled;

                            if (productTab && !enabled) {
                                productTab.style.position = 'relative';
                            }
                            if (blocker) {
                                blocker.style.display = enabled ? 'none' : 'flex';
                            }
                            if (blockerMessage && !enabled) {
                                blockerMessage.innerHTML = message || 'No validated distributors are currently available. Enter distributor credentials, save your changes, and run Validate Configuration to enable Product Search.';
                            }

                            if (!enabled) {
                                gffcSetProductSearchSortUiVisible(false);
                                if (dashboard) dashboard.style.display = 'none';
                            }
                        }

                        async function gffcHasActiveValidatedDistributors() {
                            if (!window.currentConfiguration || !window.currentConfiguration.distributors) {
                                // Don't lock search until configuration is loaded.
                                return true;
                            }

                            const activeDistributorNames = Object.keys(window.currentConfiguration.distributors || {}).filter(name => {
                                const cfg = window.currentConfiguration.distributors[name];
                                return !!(cfg && cfg.active);
                            });
                            if (!activeDistributorNames.length) return false;

                            window.gffcProductSearchDistributorSchemaCache = window.gffcProductSearchDistributorSchemaCache || null;
                            if (!window.gffcProductSearchDistributorSchemaCache) {
                                try {
                                    const schemaResp = await fetch("https://ffl-api.garidium.com", {
                                        method: "POST",
                                        headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                        },
                                        body: JSON.stringify({ "action": "get_distributors_schema" })
                                    });
                                    window.gffcProductSearchDistributorSchemaCache = await schemaResp.json();
                                } catch (e) {
                                    // If schema lookup fails, don't hard-block search.
                                    return true;
                                }
                            }

                            const schema = window.gffcProductSearchDistributorSchemaCache || {};
                            const activeDistIds = activeDistributorNames
                                .map(name => schema && schema[name] ? String(schema[name].distid || '').trim() : '')
                                .filter(Boolean);
                            if (!activeDistIds.length) return false;

                            try {
                                const validatedResp = await fetch("https://ffl-api.garidium.com", {
                                    method: "POST",
                                    headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey);?>"
                                    },
                                    body: JSON.stringify({ "action": "get_validated_distributors", "data": {"api_key": document.getElementById('g_ffl_cockpit_key').value}})
                                });
                                const validated = await validatedResp.json();
                                const validatedSet = new Set(
                                    (Array.isArray(validated) ? validated : [])
                                        .filter(item => String(item && item.status ? item.status : '').toLowerCase() === 'validated')
                                        .map(item => String(item && item.distid ? item.distid : '').trim())
                                        .filter(Boolean)
                                );
                                return activeDistIds.some(distid => validatedSet.has(distid));
                            } catch (e) {
                                // If validation lookup fails, don't hard-block search.
                                return true;
                            }
                        }

                        window.gffcRefreshProductSearchAvailability = async function(forceCheck = false) {
                            if (!forceCheck && window.gffcProductSearchAvailabilityLocked === true) {
                                return false;
                            }

                            const hasValidated = await gffcHasActiveValidatedDistributors();
                            if (!hasValidated) {
                                window.gffcProductSearchAvailabilityLocked = true;
                                gffcSetProductSearchEnabledState(false, 'No validated distributors are available. Enter distributor credentials, save your changes, and run Validate Configuration to enable Product Search.');
                                return false;
                            }

                            window.gffcProductSearchAvailabilityLocked = false;
                            gffcSetProductSearchEnabledState(true, '');
                            return true;
                        };

                        async function loadGrid() {
                            const available = await window.gffcRefreshProductSearchAvailability(true);
                            if (!available) {
                                return;
                            }

                            const searchInput = document.getElementById('cockpit-product-search-input');
                            const searchValue = searchInput ? (searchInput.value || '') : '';

                            // Require at least 3 user-entered characters (ignore whitespace and commas).
                            // Note: the auto-appended 'in stock' term must NOT satisfy this requirement.
                            const userCharCount = (searchValue || '').replace(/[\s,]+/g, '').length;
                            if (userCharCount < 3) {
                                alert("Enter a Search Term with at least 3 characters.");
                                return;
                            }

                            const wrapper = document.getElementById('gffc-search-wrapper');
                            if (wrapper) {
                                wrapper.classList.remove('initial');
                                wrapper.classList.add('active');
                            }

                            // Expand recent searches row immediately (before results load).
                            gffcAlignRecentSearchesToInput();

                            const ignoreToggle = document.getElementById('ignore-product-restrictions-toggle');
                            const inStockToggle = document.getElementById('gffc-in-stock-toggle');

                            const ignoreChecked = !!(ignoreToggle && ignoreToggle.checked);
                            const inStockChecked = !!(inStockToggle && inStockToggle.checked);

                            // Keep last search around so sort changes can re-run it.
                            window.gffcLastProductSearchValue = searchValue;

                            // Save recent search (before request augmentation/encoding).
                            gffcAddRecentSearch(searchValue, ignoreChecked, inStockChecked);

                            const ignore_product_restrictions = ignoreChecked ? "on" : "off";

                            // Runtime-only: augment the API request terms based on the In Stock toggle.
                            // - ON  => ensure 'in stock' exists (appended)
                            // - OFF => ensure 'in stock' is removed from the request (even if typed)
                            const requestSearchValue = gffcApplyInStockToSearchTermsForRequest(searchValue, inStockChecked);
                            const keyword = encodeURIComponent(requestSearchValue);

                            // Scroll to top of page when search is initiated
                            window.scrollTo({ top: 0, behavior: 'smooth' });

                            // Always show regular search results first, then analyze for dashboard
                            showRegularSearchResults();
                            renderProductGrid(keyword, ignore_product_restrictions);
                        }

                        if (document.readyState === 'loading') {
                            document.addEventListener('DOMContentLoaded', function() {
                                if (typeof window.gffcRefreshProductSearchAvailability === 'function') {
                                    window.gffcRefreshProductSearchAvailability(true);
                                }
                            });
                        } else if (typeof window.gffcRefreshProductSearchAvailability === 'function') {
                            window.gffcRefreshProductSearchAvailability(true);
                        }
                        
                        function showSingleUPCDashboard(products, upc) {
                            const g_ffl_is_restricted = <?php echo $this->is_restricted_user() ? 'true' : 'false'; ?>;
                            document.getElementById("g_ffl_cockpit_single_upc_dashboard").style.display = "block";
                            document.getElementById("product_feed_table").style.display = "none";

                            window.gffcUpcDashboardProducts = products;
                            window.gffcUpcDashboardUpc = upc;
                            gffcInitUpcIgnoreShippingToggle();
                            
                            // Sort products by total cost for better comparison
                            products.sort((a, b) => (gffcUpcGetEffectiveTotal(a) || 999999) - (gffcUpcGetEffectiveTotal(b) || 999999));
                            
                            // Clear and update header with product information
                            const firstProduct = products[0];
                            const productNameElement = document.getElementById("g_ffl_cockpit_dashboard_product_name");
                            const productDetailsElement = document.getElementById("g_ffl_cockpit_dashboard_product_details");
                            
                            // Clear any existing content completely
                            productNameElement.innerHTML = '';
                            productDetailsElement.innerHTML = '';
                            
                            // Set clean product name
                            productNameElement.textContent = firstProduct.name || 'Product Name';
                            
                            // Create cleaner product details layout
                            const detailsHTML = `
                                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; margin-top: 10px;">
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">UPC CODE</div>
                                        <div style="font-size: 18px; font-weight: 600; font-family: 'Courier New', monospace; color: #2c3e50; display: flex; align-items: center; gap: 10px;">
                                            <a href="#" onclick="searchByUPC('${upc}'); return false;" style="color: #0073aa; text-decoration: underline;" title="Click to search for this UPC">${upc}</a>
                                            <i class="fas fa-bell" 
                                               id="dashboard-stock-alert-${upc}" 
                                               style="cursor: pointer; color: ${firstProduct.upc_in_stock_alert ? '#ff6b35' : '#ccc'}; font-size: 16px;" 
                                               title="${firstProduct.upc_in_stock_alert ? 'Stock alert is ON - Click to turn OFF' : 'Stock alert is OFF - Click to turn ON'}"
                                               onclick="toggleDashboardStockAlert('${upc}', ${!firstProduct.upc_in_stock_alert}, this)"></i>
                                        </div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">MANUFACTURER</div>
                                        <div style="font-size: 16px; font-weight: 500; color: #34495e;">${firstProduct.mfg_name || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">MPN</div>
                                        <div style="font-size: 16px; font-weight: 500; color: #34495e;">${firstProduct.mpn || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">PRODUCT CLASS</div>
                                        <div style="font-size: 16px; font-weight: 500; color: #34495e;">${firstProduct.product_class || 'N/A'}</div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">CATEGORY</div>
                                        <div style="font-size: 16px; font-weight: 500; color: #34495e; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
                                            <span id="g_ffl_cockpit_dashboard_product_category" style="color: ${firstProduct.item_gb_cat_name || firstProduct.category ? '#34495e' : '#e74c3c'};">
                                                ${firstProduct.item_gb_cat_name || firstProduct.category || '<span style="color: #e74c3c; font-weight: 600;">Uncategorized</span>'}
                                            </span>
                                            ${ g_ffl_is_restricted ? '' : `<button onclick="openDashboardCategoryChangeModal('${upc}', '${firstProduct.site_product_id}', '${firstProduct.distsku}', '${firstProduct.distid}')" 
                                                    style="padding: 3px 6px; font-size: 10px; background: #3498db; color: white; border: none; border-radius: 3px; cursor: pointer; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; transition: background 0.2s ease;"
                                                    onmouseover="this.style.background='#2980b9'" 
                                                    onmouseout="this.style.background='#3498db'"
                                                    title="Change product category">
                                                CHANGE
                                            </button>` }
                                        </div>
                                    </div>
                                    <div>
                                        <div style="font-size: 12px; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 4px; color: #7f8c8d; font-weight: 500;">AVAILABLE FROM</div>
                                        <div style="font-size: 16px; font-weight: 600; color: #3498db;">${products.length} DISTRIBUTORS</div>
                                    </div>
                                </div>
                            `;
                            productDetailsElement.innerHTML = detailsHTML;
                            
                            // Add larger product image
                            const images = JSON.parse(firstProduct.images || '[]');
                            const imageContainer = document.getElementById("g_ffl_cockpit_dashboard_product_image");
                            imageContainer.innerHTML = ''; // Clear existing content
                            
                            if (images.length > 0 && images[0].src) {
                                imageContainer.innerHTML = `<img src="${images[0].src}" style="max-width: 180px; max-height: 140px; object-fit: contain; border-radius: 8px; cursor: pointer; transition: transform 0.2s ease;" alt="Product Image" id="dashboard-main-image" onerror="this.style.display='none';">`;
                                
                                // Add click event listener for modal
                                const img = imageContainer.querySelector('img');
                                img.addEventListener('click', () => {
                                    openImageModal(images[0].src, firstProduct.name || '');
                                });
                                
                                // Add hover effect
                                img.addEventListener('mouseenter', () => {
                                    img.style.transform = 'scale(1.05)';
                                });
                                img.addEventListener('mouseleave', () => {
                                    img.style.transform = 'scale(1)';
                                });
                            } else {
                                imageContainer.innerHTML = `
                                    <div style="width: 180px; height: 140px; background: #f8f9fa; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #6c757d; font-size: 14px; border-radius: 8px; border: 2px dashed #dee2e6;">
                                        <div style="font-size: 24px; margin-bottom: 8px;">📦</div>
                                        <div>No Image Available</div>
                                    </div>
                                `;
                            }
                            
                            // Render price comparison chart
                            renderPriceComparisonChart(products);
                            
                            // Render distributor cards
                            renderDistributorCards(products);
                            
                            // Render detailed comparison table
                            renderDetailedComparisonTable(products);
                            
                            // Reset history section to show Load History button
                            resetHistorySection();
                            
                            // Show diagnosis section if product has no website link
                            gffcShowDiagnosisSectionIfNeeded(products);
                        }

                        function gffcUpcIsIgnoreShippingEnabled() {
                            return gffcGetCookie('gffc_upc_ignore_shipping') === '1';
                        }

                        function gffcUpcGetEffectiveShipping(product) {
                            if (gffcUpcIsIgnoreShippingEnabled()) return 0;
                            return Number((product && product.shipping_cost) || 0);
                        }

                        function gffcUpcGetEffectiveTotal(product) {
                            const unit = Number((product && product.unit_price) || 0);
                            const ship = gffcUpcGetEffectiveShipping(product);
                            const total = unit + ship;
                            return total > 0 ? total : 0;
                        }

                        function gffcInitUpcIgnoreShippingToggle() {
                            const el = document.getElementById('gffc_upc_ignore_shipping_toggle');
                            if (!el) return;

                            const cookieVal = gffcGetCookie('gffc_upc_ignore_shipping');
                            if (cookieVal !== null) {
                                el.checked = (cookieVal === '1');
                            } else {
                                el.checked = false;
                            }

                            if (el.dataset.bound === '1') return;
                            el.dataset.bound = '1';

                            el.addEventListener('change', function () {
                                gffcSetCookie('gffc_upc_ignore_shipping', el.checked ? '1' : '0', 365);

                                const products = window.gffcUpcDashboardProducts;
                                if (!Array.isArray(products) || !products.length) return;

                                products.sort((a, b) => (gffcUpcGetEffectiveTotal(a) || 999999) - (gffcUpcGetEffectiveTotal(b) || 999999));
                                renderPriceComparisonChart(products);
                                renderDistributorCards(products);
                                renderDetailedComparisonTable(products);
                            });
                        }
                        
                        function showRegularSearchResults() {
                            document.getElementById("g_ffl_cockpit_single_upc_dashboard").style.display = "none";
                            document.getElementById("product_feed_table").style.display = "block";
                            
                            // Clear product history when leaving dashboard
                            clearProductHistory();
                            
                            // Reset diagnosis section when leaving dashboard
                            gffcResetDiagnosisSection();
                            
                            // Scroll to top when returning to search results
                            window.scrollTo({ top: 0, behavior: 'smooth' });
                        }
                        
                        function openImageModal(imageSrc, productName) {
                            const modal = document.getElementById('g_ffl_cockpit_productImageModal');
                            const modalImage = document.getElementById('g_ffl_cockpit_modalProductImage');
                            const modalProductName = document.getElementById('g_ffl_cockpit_modalProductName');
                            
                            modalImage.src = imageSrc;
                            modalProductName.textContent = productName || '';
                            modal.style.display = 'block';
                            
                            // Close modal when clicking outside the image
                            modal.onclick = function(event) {
                                if (event.target === modal) {
                                    closeImageModal();
                                }
                            };
                            
                            // Close modal on Escape key
                            document.addEventListener('keydown', function(event) {
                                if (event.key === 'Escape') {
                                    closeImageModal();
                                }
                            });
                        }
                        
                        function closeImageModal() {
                            const modal = document.getElementById('g_ffl_cockpit_productImageModal');
                            modal.style.display = 'none';
                        }

                        // Product Search: when the Grid.js page changes, scroll back to the top.
                        // (Prevents users from being stuck at the bottom after clicking pagination.)
                        (function installProductSearchPaginationScroll() {
                            if (window.gffcProductSearchPaginationScrollInstalled) return;
                            window.gffcProductSearchPaginationScrollInstalled = true;

                            document.addEventListener('click', function (e) {
                                if (!e || !e.target || typeof e.target.closest !== 'function') return;
                                const paginationButton = e.target.closest('#product_feed .gridjs-pagination .gridjs-pages button');
                                if (!paginationButton || paginationButton.disabled) return;
                                window.scrollTo(0, 0);
                            }, true);
                        })();
                        
                        function renderProductGrid(keyword, ignore_product_restrictions) {
                            const g_ffl_is_restricted = <?php echo $this->is_restricted_user() ? 'true' : 'false'; ?>;

                            const sortSettings = gffcGetProductSearchSortSettings();
                            const baseUrl = `https://ffl-api.garidium.com/product?action=get_filtered_catalog&search=${keyword}&ignore_product_restrictions=${ignore_product_restrictions}&load_site_map=True`;
                            const sortedBaseUrl = gffcApplyOrderParams(baseUrl, sortSettings.orderColumn, sortSettings.orderDirection);

                            if (productGrid) {
                                productGrid.updateConfig({
                                    server: {
                                        url: sortedBaseUrl,
                                        method: 'GET',
                                        headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        },
                                        then: data => {
                                            const parsedData = JSON.parse(data);
                                            console.log("Server Response:", parsedData);

                                            const hasResults = !!(parsedData && Number(parsedData.count || 0) > 0);
                                            gffcSetProductSearchSortUiVisible(hasResults);
                                            gffcSetProductSearchHasResults(hasResults);
                                            gffcUpdateProductSearchSortIndicator();
                                            
                                            // Check if we should show dashboard after data is loaded
                                            setTimeout(() => analyzeForDashboard(parsedData.products), 100);
                                            
                                            return parsedData.products.map(product => [
                                                product.distid,
                                                product.distsku,
                                                JSON.parse(product.images || '[]'),
                                                product.name,
                                                product.mfg_name,
                                                product.upc,
                                                product.mpn,
                                                product.qty_on_hand || 0,
                                                product.unit_price || 0,
                                                product.shipping_cost || 0,
                                                product.total_cost || 0,
                                                product.map_price || 0,
                                                product.msrp,
                                                product.product_class,
                                                product.product_class_description,
                                                product.item_gb_cat_name,
                                                product.drop_ship_flg,
                                                product.product_url,
                                                product.permalink,
                                                product.site_product_id,
                                                product.upc_in_stock_alert,
                                                product.ffl_req
                                            ]);
                                        },
                                        total: data => JSON.parse(data).count
                                    }
                                }).forceRender();
                            } else {
                                productGrid = new gridjs.Grid({
                                    columns: [
                                        {
                                            sort: false,
                                            name: 'Dist',
                                            width: '60px',
                                            formatter: (_, row) => gridjs.html(`<img align="center" width="50px" src="${get_distributor_logo(row.cells[0]?.data)}" onerror="this.style.display='none';">`)
                                        },
                                        {
                                            name: 'Product Summary',
                                            sort: false,
                                            width: '400px',
                                            formatter: (_, row) => gridjs.html(`
                                                <div>
                                                    <table>
                                                        <tr>
                                                            <td class="gffc-search-thumb-cell" style="width:150px;">
                                                                <a style="align:center;cursor:pointer;" 
                                                                onclick="load_product_data('${row.cells[3]?.data.replaceAll("'", "\\'").replaceAll('\"','&quot;')}', '${row.cells[0]?.data}', '${row.cells[1]?.data}', '${row.cells[2]?.data.length > 0 ? row.cells[2].data[0]['src'] : ""}')">
                                                                    <img class="gffc-search-product-thumb" style="max-height:80px;max-width:150px;height:auto;width:auto;" 
                                                                        src="${row.cells[2]?.data.length > 0 ? row.cells[2].data[0]['src'] : ""}" onerror="this.style.display='none';">
                                                                </a>
                                                            </td>
                                                            <td style="min-width:250px;">
                                                                <strong>${row.cells[4]?.data || 'Unknown'}</strong>${row.cells[16].data === 1 ? `<i class="fas fa-truck" title="This item is dropshippable" style="color: gray; font-size: 12px; vertical-align: middle; margin-left: 5px;"></i>`: ''}<br>
                                                                ${row.cells[3]?.data || 'Unknown'}<hr style="margin:5px;padding:2px;"/>
                                                                <span class="grid_cell_label">Product Pages:</span> ${row.cells[17]?.data? `<a target="_blank" href="${row.cells[17].data}" title="View Product on Distributor Site">Distributor</a>` : ''}${row.cells[18]?.data? ` | <a target="_blank" href="${row.cells[18].data}" title="View Product on Your Site">Website</a>` : ''}
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </div>
                                            `)
                                        },  
                                                    
                                        {
                                            name: 'Product Info',
                                            width: '300px',
                                            sort: false,
                                            formatter: (_, row) => gridjs.html(`
                                                <table style="width: 100%; border-collapse: collapse;" data-upc="${row.cells[5]?.data || ''}">
                                                    <tr>
                                                        <td class="grid_cell_label">UPC:</td>
                                                        <td>
                                                            <a href="#" onclick="searchByUPC('${row.cells[5]?.data || ''}'); return false;" style="color: #0073aa; text-decoration: underline; cursor: pointer;" title="Click to search for this UPC">${row.cells[5]?.data || 'N/A'}</a>
                                                            <i class="fas fa-bell"
                                                               style="margin-left: 8px; cursor: pointer; color: ${row.cells[20]?.data ? '#ff6b35' : '#ccc'}; font-size: 14px;"
                                                               title="${row.cells[20]?.data ? 'On wishlist - Click to remove' : 'Add to wishlist'}"
                                                               onclick="toggleStockAlert('${row.cells[5]?.data || ''}', ${!row.cells[20]?.data}, this)"></i>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="grid_cell_label">SKU:</td>
                                                        <td>${row.cells[1]?.data || 'N/A'}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="grid_cell_label">MPN:</td>
                                                        <td>${row.cells[6]?.data || 'N/A'}</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="grid_cell_label">Class:</td>
                                                        <td>${row.cells[14]?.data || 'N/A'} (${row.cells[13]?.data || ''})</td>
                                                    </tr>
                                                    <tr>
                                                        <td class="grid_cell_label">Category:</td>
                                                        <td>
                                                            <span id="${row.cells[0].data}_${row.cells[5].data}_category">${row.cells[15]?.data || '<span style="color:red;">Uncategorized</span>'}</span>
                                                            ${ g_ffl_is_restricted ? '' : `<i class="fas fa-edit" style="cursor: pointer; margin-left: 5px; color: #BBBBBB;" 
                                                                title="Edit Category"
                                                                onclick="openCategoryChangeModal('${row.cells[5]?.data}', '${row.cells[19]?.data}', '${row.cells[1]?.data}', '${row.cells[0]?.data}')"></i>` }
                                                        </td>
                                                    </tr>
                                                </table>
                                            `)
                                        },
                                        {
                                            name: 'Pricing Data',
                                            width: '210px',
                                            sort: false,
                                            formatter: (_, row) => gridjs.html(`
                                            <table style="width: 100%; border-collapse: collapse;">
                                                <tr>
                                                    <td class="grid_cell_label">Cost:</td>
                                                    <td>${row.cells[8]?.data ? `$${row.cells[8].data.toFixed(2)}` : '--'}</td>
                                                </tr>
                                                <tr>
                                                    <td class="grid_cell_label">Shipping:</td>
                                                    <td>${row.cells[9]?.data ? `$${row.cells[9].data.toFixed(2)}` : 'Free'}</td>
                                                </tr>
                                                <tr>
                                                    <td class="grid_cell_label">Total Cost:</td>
                                                    <td><strong>${row.cells[10]?.data ? `$${row.cells[10].data.toFixed(2)}` : '--'}</strong></td>
                                                </tr>
                                                <tr>
                                                    <td class="grid_cell_label">MSRP:</td>
                                                    <td>${row.cells[12]?.data ? `$${row.cells[12].data.toFixed(2)}` : '--'}</td>
                                                </tr>
                                                <tr>
                                                    <td class="grid_cell_label">MAP:</td>
                                                    <td>${row.cells[11]?.data ? `$${row.cells[11].data.toFixed(2)}` : '--'}</td>
                                                </tr>
                                            </table>
                                            `)
                                        },
                                        {
                                            name: 'Availability',
                                            width: '100px',
                                            sort: false,
                                            formatter: (_, row) => gridjs.html(`
                                            <table style="width: 100%; border-collapse: collapse;">
                                                ${(() => {
                                                    const qty = Number(row.cells[7]?.data || 0);
                                                    if (qty > 0) {
                                                        return `
                                                        <tr class="gffc-qty-row">
                                                            <td colspan="2">
                                                                <div class="gffc-qty-desktop" style="display:flex; flex-direction:column; align-items:center; text-align:center; gap: 2px;">
                                                                    <div style="font-size: 11px; font-weight: 500;">Quantity Available</div>
                                                                    <div style="font-size: 18px; font-weight: 800; line-height: 1.1;">${qty}</div>
                                                                </div>
                                                                <div class="gffc-qty-mobile" style="display:none;">Quantity Available:<strong>${qty}</strong></div>
                                                            </td>
                                                        </tr>`;
                                                    } else {
                                                        return `
                                                        <tr style="justify-content: center;">
                                                            <td colspan="2" style="text-align: center; color: #dc3545; font-weight: bold; padding: 5px 0; width: 100%;">Out of Stock</td>
                                                        </tr>`;
                                                    }
                                                })()}
                                                <tr>
                                                    <td colspan="2" style="padding-top: 6px;">
                                                        <div style="display:flex; justify-content:center;">
                                                        ${(() => {
                                                            // Only show buttons if user is admin
                                                            if (typeof gffcIsAdmin === 'undefined' || !gffcIsAdmin) return '';

                                                            const q = Number(row.cells[7]?.data || 0);
                                                            const distid = row.cells[0]?.data;
                                                            
                                                            // Hardcoded list of distributors that do not allow ordering
                                                            const noOrderDistributors = ["MGE", "AMC", "CAM4", "CWS"];
                                                            const isFulfillable = !noOrderDistributors.includes(distid);

                                                            if (q > 0 && isFulfillable) {
                                                                // Narrow Availability column (~100px): stack qty input above
                                                                // the Add confirm button when the wrap is expanded so neither
                                                                // element gets squished into letter-by-letter wrapping.
                                                                return `<span class="gffc-add-wrap" data-gffc-add-state="closed" style="display:inline-flex; flex-direction:column; gap:4px; align-items:stretch; min-width:90px;">
    <button type="button" class="gffc-btn-add gffc-add-toggle" style="white-space:nowrap; padding:4px 8px;"><i class="fas fa-cart-plus"></i> Add</button>
    <input type="number" class="gffc-cart-qty-input" data-gffc-cart-qty-input="1" min="1" max="${q}" value="1" title="Quantity" aria-label="Quantity to add to cart" style="display:none; width:100%; padding:3px 5px; border:1px solid #ccc; border-radius:4px; box-sizing:border-box; font-size:12px; text-align:center;">
    <button type="button" class="gffc-btn-add gffc-add-confirm" data-gffc-add-to-cart="1" data-item="${gffcEncodeItemPayload(gffcBuildCartItemFromGridRow(row))}" style="display:none; white-space:nowrap; padding:4px 8px;"><i class="fas fa-check"></i> Add</button>
</span>`;
                                                            }
                                                            return '';
                                                        })()}
                                                        </div>
                                                    </td>
                                                </tr>
                                            </table>
                                            `)
                                        },
                                        {name: "Qty2", hidden: true},
                                        {name: "Image", hidden: true},
                                        {name: "unit_price", hidden: true},
                                        {name: "shipping_cost", hidden: true},
                                        {name: "total_cost", hidden: true},
                                        {name: "map_price", hidden: true},
                                        {name: "msrp", hidden: true},
                                        {name: "product_class", hidden: true},
                                        {name: "category", hidden: true},
                                        {name: "product_class_description", hidden: true},
                                        {name: "item_gb_cat_name", hidden: true},
                                        {name: "drop_ship_flag", hidden: true},
                                        {name: "product_url", hidden: true},
                                        {name: "permalink", hidden: true},
                                        {name: "site_product_id", hidden: true},
                                        {name: "upc_in_stock_alert", hidden: true},
                                        {name: "ffl_req", hidden: true}

                                    ],
                                    sort: {
                                        multiColumn: false,
                                        server: {
                                            url: (prev, columns) => {
                                                if (!columns.length) return prev;
                                                const col = columns[0];
                                                const dir = col.direction === 1 ? 'asc' : 'desc';
                                                let colName = [
                                                    'distid', 'distsku', 'images', 'name', 
                                                    'mfg_name', 'upc', 'mpn', 'qty_on_hand', 
                                                    'unit_price', 'shipping_cost', 'total_cost', 'map_price'
                                                ][col.index];
                                                if (!colName) return prev;
                                                return gffcApplyOrderParams(prev, colName, dir);
                                            }
                                        }
                                    },
                                    resizable: true,
                                    pagination: {
                                        limit: 100,
                                        server: {
                                            url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
                                        }
                                    },
                                    fixedHeader: true,
                                    style: {
                                        td: {
                                            'padding': '3px',
                                            'word-break': 'break-word'
                                        },
                                        th: {
                                            'padding': '3px',
                                            'word-break': 'break-word'
                                        }
                                    },
                                    server: {
                                        url: sortedBaseUrl,
                                        method: 'GET',
                                        headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        },
                                        then: data => {
                                            const parsedData = JSON.parse(data);

                                            const hasResults = !!(parsedData && Number(parsedData.count || 0) > 0);
                                            gffcSetProductSearchSortUiVisible(hasResults);
                                            gffcSetProductSearchHasResults(hasResults);
                                            gffcUpdateProductSearchSortIndicator();
                                            
                                            // Check if we should show dashboard after data is loaded
                                            setTimeout(() => analyzeForDashboard(parsedData.products), 100);
                                            
                                            return parsedData.products.map(product => [
                                                product.distid,
                                                product.distsku,
                                                JSON.parse(product.images || '[]'),
                                                product.name,
                                                product.mfg_name,
                                                product.upc,
                                                product.mpn,
                                                product.qty_on_hand || 0,
                                                product.unit_price || 0,
                                                product.shipping_cost || 0,
                                                product.total_cost || 0,
                                                product.map_price || 0,
                                                product.msrp,
                                                product.product_class,
                                                product.product_class_description,
                                                product.item_gb_cat_name,
                                                product.drop_ship_flg,
                                                product.product_url,
                                                product.permalink,
                                                product.site_product_id,
                                                product.upc_in_stock_alert,
                                                product.ffl_req
                                            ]);
                                        },
                                        total: data => JSON.parse(data).count
                                    }
                                }).render(document.getElementById('product_feed_table'));
                            }
                        }
                        document.getElementById("download_inventory_button").addEventListener("click", function(){
                            document.getElementById("download_inventory_button").disabled = true;
                            document.getElementById('download_inventory_button').innerText = 'Please Wait...';
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                "Accept": "application/json",
                                "Content-Type": "application/json",
                                "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({"action": "create_catalog_extract", "data": {"api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"}})
                            })
                            .then(response=>response.json())
                            .then(data=>{ 
                                alert("Your request has been submitted. You will be emailed a link to download the Catalog once it has been generated. This may take a few minutes.")  
                                //document.getElementById("download_inventory_button").disabled = false; 
                                document.getElementById('download_inventory_button').innerText = 'Your Catalog Extract will be emailed in a few minutes';     
                            });
                        });
                    </script>
                 

                </div>
            </div>
            <button class="accordion">Fulfillment</button>
            <div id="fulfillment" class="tabcontent">
                <div style="background: #fff; padding: 10px;">
                    <!-- <p>The Product Feed is based on your Configuration. The synchronization process will run every 15-minutes, at which point any changes you make to your configuration will be applied. This list will show items from all distributors configured, and with quantities less than your minimum listing quantity. We list one product per UPC, based on availability and price.</p> -->
                    <div id="order_fulfillment_table"></div>
                    <div style="padding:5px;display: flex;width: 100%;justify-content: space-between;align-items: flex-start;">
                        <div style="flex: 1;">
                            <button id="download_fulfillment_history_button" class="button alt" data-marker-id="">Download Fulfillment History</button>
                        </div>
                        <div id="gunbroker_processor_section" style="display:none;">
                            <table style="width:100%;" align="right">
                                <tr>
                                    <td align="right">
                                        Gunbroker Orders (Beta):
                                        <select id="gunbroker_order_id" class="input-input"></select>
                                        <button id="process_gunbroker_order_button" class="button alt" data-marker-id="">Fulfill</button>
                                        <button id="import_gunbroker_order_button" class="button alt" data-marker-id="">Import</button>
                                        <button id="generate_gunbroker_cart_button" class="button alt" data-marker-id="">Generate Cart</button>
                                    </td>
                                </tr>
                            </table>
                         </div>
                    </div>
                    <script>
                        const gffcAllowZandersCancel = <?php echo (is_multisite() && stripos(home_url(), 'fflcockpit') !== false) ? 'true' : 'false'; ?>;
                        window.gffcSyncGunbrokerProcessorVisibility = function() {
                            if (window.gffcHasGunbrokerTargetInConfig !== true) {
                                return;
                            }
                            const section = document.getElementById("gunbroker_processor_section");
                            const dropdown = document.getElementById('gunbroker_order_id');
                            const processButton = document.getElementById("process_gunbroker_order_button");
                            const importButton = document.getElementById("import_gunbroker_order_button");
                            const generateCartButton = document.getElementById("generate_gunbroker_cart_button");
                            if (!section || !dropdown || !processButton || !importButton || !generateCartButton) {
                                return;
                            }
                            section.style.display = "";
                            if (!dropdown.options.length) {
                                processButton.disabled = true;
                                importButton.disabled = true;
                                generateCartButton.disabled = true;
                            }
                        };
                        window.gffcSyncGunbrokerProcessorVisibility();

                        // https://unpkg.com/browse/gridjs@5.1.0/dist/
                        var of_grid = new gridjs.Grid({
                            columns: [
                                {name: 'Source', width: '90px',
                                    formatter: (_, row) => {
                                        if (row.cells[0].data == "gunbroker"){
                                            return gridjs.html(`Gunbroker`);
                                        }else if (row.cells[0].data == "woocommerce"){
                                            return gridjs.html(`Website`);
                                        }else if (row.cells[0].data == "cockpit_cart"){
                                            return gridjs.html(`FFL-QM`);
                                        }

                                        return gridjs.html(`${row.cells[0].data ?? ''}`);
                                    }
                                }, 
                                {name: 'Order', width: '110px',
                                    formatter: (_, row) => {
                                        if (row.cells[0].data == "cockpit_cart"){
                                            return gridjs.html(`${row.cells[1].data ?? ''}`);
                                        }

                                        if (row.cells[0].data == "gunbroker"){
                                            return gridjs.html(`<a target=_blank href="https://www.gunbroker.com/order?orderid=${row.cells[1].data}">${row.cells[1].data}</a>`);
                                        }else{
                                            return gridjs.html(`<a target=_blank href="/wp-admin/post.php?post=${row.cells[1].data}&action=edit">${row.cells[1].data}</a>`);
                                        }
                                    }
                                },
                                {name: 'Dist', width: '60px',
                                    formatter: (_, row) => gridjs.html(`<img align="center" width="50px" src="${get_distributor_logo(row.cells[2].data)}" onerror="this.style.display='none';">`)
                                },
                                {name: 'Dist. Order',
                                    formatter: (_, row) => {
                                        const storeIcon = row.cells[13].data ? `<img title="Shipped to Store" width="20" src="${imageBaseUrl}store.png" class="gffc-store-icon" style="margin-left:5px;" onerror="this.style.display='none';"/>` : '';
                                        const distOrder = row.cells[3].data;
                                        const orderUrl = row.cells[12].data;
                                        const orderItems = row.cells[14].data;
                                        const distOrderLink = orderUrl ? `<a target=_blank href="${orderUrl}">${distOrder}</a>` : distOrder;
                                        return gridjs.html(`<div style="white-space:nowrap;position:relative;" class="gffc-dist-order-cell" onmouseenter="gffcShowOrderTooltip(event, this)" onmouseleave="gffcHideOrderTooltip()" data-order-items='${orderItems ? String(orderItems).replace(/'/g, "&#39;") : ""}'>${distOrderLink}${storeIcon}</div>`);
                                    }
                                },
                                {name: 'Status', width: '100px'}, 
                                {name: 'Customer Name'}, 
                                {name: 'Contact', width: '160px',
                                    formatter: (_, row) => {
                                        const phone = row.cells[6].data ? row.cells[6].data.replace(/\D/g, '').slice(-10).replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3') : '';
                                        const email = row.cells[7].data ? row.cells[7].data.trim() : '';
                                        const emailHtml = email ? ` <a href="mailto:${email}" title="${email}" class="gffc-email-link"><i class="fas fa-envelope"></i><span class="gffc-email-text">${email}</span></a>` : '';
                                        return gridjs.html(`<div class="gffc-contact-cell"><span class="gffc-phone-wrapper"><i class="fas fa-phone gffc-mobile-icon"></i> ${phone}</span>${emailHtml}</div>`);
                                    }
                                },
                                {name: 'Email', hidden: true},
                                {name: 'Ordered', width: '125px',
                                    formatter: (_, row) => {
                                        const date = new Date(new Date(row.cells[8].data.replace(" ", "T") + "Z").getTime() - (new Date(row.cells[8].data.replace(" ", "T") + "Z").getTimezoneOffset() * 60000)).toISOString().split('T')[0];
                                        return gridjs.html(`${date}`);
                                    }
                                },
                                {name: 'Shipped', width: '100px',
                                    formatter: (cell) => `${cell!=null?new Date(new Date(cell.replace(" ", "T") + "Z").getTime() - (new Date(cell.replace(" ", "T") + "Z").getTimezoneOffset() * 60000)).toISOString().split('T')[0]:""}`
                                },
                                {name: "Ship Status", width: '200px',
                                    formatter: (_, row) => {
                                        const dist = row.cells[2].data;
                                        const order = row.cells[1].data;
                                        const distOrder = row.cells[3].data;
                                        const shipDate = row.cells[9].data;
                                        const trackingUrl = row.cells[10].data;
                                        const status = row.cells[11].data;

                                        let statusHtml = '';
                                        let statusClass = '';
                                        let icon = '';

                                        if (status == "delivered") {
                                            statusClass = 'status-delivered';
                                            icon = '<i class="fas fa-check-circle"></i>';
                                            statusHtml = 'Delivered';
                                        } else if (status == "return_to_sender") {
                                            statusClass = 'status-return';
                                            icon = '<i class="fas fa-exclamation-circle"></i>';
                                            statusHtml = 'Return to Sender';
                                        } else if (!shipDate && (!trackingUrl || trackingUrl.length <= 1)) {
                                            statusClass = 'status-waiting';
                                            icon = '<i class="fas fa-clock"></i>';
                                            statusHtml = 'Pending';
                                        } else {
                                            statusClass = 'status-transit';
                                            icon = '<i class="fas fa-truck"></i>';
                                            // Default to "In Transit" if status is empty, otherwise capitalize
                                            if (status == 'in_transit') {
                                                statusHtml = 'In Transit';
                                            } else {
                                                statusHtml = status ? (status.charAt(0).toUpperCase() + status.slice(1)) : 'In Transit';
                                            }
                                        }

                                        let trackingLink = '';
                                        // Check for valid tracking URL
                                        if (trackingUrl && trackingUrl.length > 1) {
                                            trackingLink = `<a target="_blank" href="${trackingUrl}" class="gffc-tracking-link ${statusClass}" style="cursor:pointer;">${icon} ${statusHtml}</a>`;
                                        } else {
                                            trackingLink = `<span class="gffc-tracking-text ${statusClass}">${icon} ${statusHtml}</span>`;
                                        }

                                        const distLower = String(dist ?? '').toLowerCase();
                                        const isZanders = distLower === 'znd';
                                        const notShippedYet = !shipDate && (!trackingUrl || trackingUrl.length <= 1);
                                        const orderStatus = row.cells[4].data;
                                        const cancelBtn = (gffcAllowZandersCancel && isZanders && notShippedYet)
                                            ? `<a class="gffc-cancel-order-btn" onclick="cancelOrder('${dist}', '${order}', '${distOrder}')" title="Cancel Order" style="margin-left:10px;text-decoration:underline;cursor:pointer;">Cancel</a>`
                                            : '';
                                        const hideBtn = `<a class="gffc-hide-order-btn" onclick="hideOrder('${dist}', '${order}', '${distOrder}')" title="Hide Order"><i class="fas fa-eye-slash"></i> <span class="gffc-hide-label">Hide</span></a>`;

                                        // For Emailed orders or pending_notification (tracking added but not yet processed), show tracking input
                                        const isPendingNotification = status === 'pending_notification';
                                        if ((orderStatus === 'Emailed' && notShippedYet) || isPendingNotification) {
                                            const existingTracking = isPendingNotification ? (row.cells[10].data ? row.cells[10].data.split('=').pop() : '') : '';
                                            const inputStyle = isPendingNotification
                                                ? 'font-size:11px;padding:3px 6px;width:120px;min-width:80px;border:2px solid #f59e0b;border-radius:4px;background:#fffbeb;'
                                                : 'font-size:11px;padding:3px 6px;width:120px;min-width:80px;border:1px solid #d1d5db;border-radius:4px;';
                                            const trackingInput = `<div style="display:flex;gap:3px;align-items:center;flex-wrap:nowrap;">
                                                <input type="text" id="tracking-${dist}-${distOrder}" placeholder="Tracking #" value="${existingTracking}" title="${isPendingNotification ? 'Awaiting notification — edit tracking if needed' : ''}" onkeydown="if(event.key==='Enter'){gffcSubmitTracking('${dist}','${order}','${distOrder}')}" style="${inputStyle}">
                                                <button onclick="gffcSubmitTracking('${dist}', '${order}', '${distOrder}')" style="font-size:11px;padding:3px 6px;background:#10b981;color:#fff;border:none;border-radius:4px;cursor:pointer;white-space:nowrap;flex-shrink:0;" title="${isPendingNotification ? 'Update Tracking' : 'Mark as Shipped'}"><i class="fas fa-shipping-fast"></i></button>
                                            </div>`;
                                            return gridjs.html(`<div class="gffc-ship-status-container">${trackingInput}${hideBtn}</div>`);
                                        }

                                        return gridjs.html(`<div class="gffc-ship-status-container">${trackingLink}${cancelBtn}${hideBtn}</div>`);
                                    }
                                },
                                {name: "Order URL", hidden: true},
                                {name: "Tracking URL", hidden: true},
                                {name: "Ship-to-Store", hidden: true},
                                {name: "Order Items", hidden: true},
                                
                            ],
                            sort: {
                                multiColumn: false,
                                server: {
                                    url: (prev, columns) => {
                                        if (!columns.length) return prev;
                                        const col = columns[0];
                                        const dir = col.direction === 1 ? 'asc' : 'desc';
                                        let colName = ["order_source","order_id", "distid", "distributor_order_id", "order_status", "customer_name", "customer_phone", "customer_email", "order_date", "ship_date", "ship_status"][col.index];
                                        let sortUrl = `${prev}&order_column=${colName}&order_direction=${dir}`;
                                        return sortUrl;
                                    }
                                }
                            },
                            search: {
                                server: {
                                    url: (prev, keyword) => `${prev}&search=${keyword}`
                                }
                            },
                            resizable: true,
                            pagination: {
                                limit: 100,
                                server: {
                                    url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
                                }
                            },
                            fixedHeader: true,
                            style: {
                                td: {
                                    'padding': '3px'
                                },
                                th: {
                                    'padding': '3px'
                                }
                            },
                            server: {
                                url: 'https://ffl-api.garidium.com/product?action=get_order_history',
                                method: 'GET',
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
			                    },                                
                                then: data => JSON.parse(data).orders.map(order => [
                                                                   order.order_source,
                                                                   order.order_id,
                                                                   order.distid,
                                                                   order.distributor_order_id,
                                                                   order.order_status,
                                                                   order.customer_name,
                                                                   order.customer_phone,
                                                                   order.customer_email,
                                                                   order.order_date,
                                                                   order.ship_date,
                                                                   order.ship_tracking_url,
                                                                   order.ship_status,
                                                                   order.order_url,
                                                                   order.ship_to_store,
                                                                   order.dist_order_items
                                                                ]),  
                                                                 
                                total: data => JSON.parse(data).count
                            } 
                        });
                  
                        function hideOrder(distid, order_id, distributor_order_id){
                            if (window.confirm("Are you sure you want to hide this distributor order, disassociating it from this Order? It will be erased from your view (but still in the database). It will be ignored from Cockpit from now until the end of time. This action WILL NOT CANCEL the order with the distributor.")){
                                if (window.confirm("Are you REALLY SURE?? We will not take requests to unhide an order because you did it by mistake..., and again.. this WILl NOT CANCEL the order with your distributor.")){
                                    try{
                                        fetch("https://ffl-api.garidium.com", {
                                            method: "POST",
                                            headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                            },
                                            body: JSON.stringify({"action": "hide_distributor_order", "data": {"distid": distid,"order_id": order_id, "distributor_order_id":distributor_order_id, "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"}})
                                        })
                                        .then(response=>response.json())
                                        .then(data=>{  
                                            if (!data.success){
                                                alert("Failed to Hide the Order, contact support@garidium.com so we can address the problem ASAP.");
                                            }  
                                            of_grid.forceRender();
                                        });
                                    } catch (error) {
                                        console.error(error);
                                    }
                                }
                            }
                        }

                        function cancelOrder(distid, order_id, distributor_order_id){
                            if (window.confirm("Are you sure you want to cancel order: " + distributor_order_id)){
                                try{
                                    fetch("https://ffl-api.garidium.com", {
                                        method: "POST",
                                        headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        },
                                        body: JSON.stringify({"action": "cancel_distributor_order", "data": {"api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>", "distid": distid, "order_id": order_id, "distributor_order_id": distributor_order_id}})
                                    })
                                    .then(response=>response.json())
                                    .then(data=>{  
                                        if (!data.success){
                                            alert("Failed to Cancel the Order, please try again, and if it continues to fail email the cancellation request to your distributor sales rep and contact support@garidium.com so we can address the problem ASAP.");
                                        }
                                        of_grid.forceRender();
                                    });
                                } catch (error) {
                                    console.error(error);
                                }
                            }
                        }
                        
                        // Order details tooltip
                        var gffcOrderTooltip = null;
                        function gffcShowOrderTooltip(event, el) {
                            var raw = el.getAttribute('data-order-items');
                            if (!raw) return;
                            var items;
                            try { items = JSON.parse(raw); } catch(e) {
                                try { items = JSON.parse(JSON.parse(raw)); } catch(e2) { return; }
                            }
                            if (!items || (!Array.isArray(items) && typeof items !== 'object')) return;
                            var arr = Array.isArray(items) ? items : [items];
                            if (arr.length === 0) return;

                            if (gffcOrderTooltip) gffcOrderTooltip.remove();
                            var tip = document.createElement('div');
                            tip.id = 'gffc-order-tooltip';
                            tip.style.cssText = 'position:fixed;z-index:99999;background:#fff;border:1px solid #e2e8f0;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.15);padding:12px;max-width:420px;max-height:350px;overflow-y:auto;font-size:12px;';

                            var html = '<div style="font-weight:700;font-size:13px;margin-bottom:8px;color:#1e293b;border-bottom:1px solid #e2e8f0;padding-bottom:6px;">Order Items (' + arr.length + ')</div>';
                            html += '<table style="width:100%;border-collapse:collapse;font-size:11px;">';
                            html += '<tr style="background:#f8fafc;"><th style="text-align:left;padding:4px 6px;border-bottom:1px solid #e2e8f0;">Item</th><th style="text-align:right;padding:4px 6px;border-bottom:1px solid #e2e8f0;">Qty</th><th style="text-align:right;padding:4px 6px;border-bottom:1px solid #e2e8f0;">Cost</th></tr>';
                            arr.forEach(function(item) {
                                var name = item.name || item.product_name || item.description || item.sku || 'Item';
                                var qty = item.quantity || item.qty || 1;
                                var cost = item.cost || item.price || item.unit_cost || '';
                                var upc = item.upc || '';
                                var sku = item.sku || item.item_number || '';
                                html += '<tr style="border-bottom:1px solid #f1f5f9;">';
                                html += '<td style="padding:4px 6px;"><div style="font-weight:600;color:#1e293b;">' + name + '</div>';
                                if (sku) html += '<div style="color:#94a3b8;font-size:10px;">SKU: ' + sku + '</div>';
                                if (upc) html += '<div style="color:#94a3b8;font-size:10px;">UPC: ' + upc + '</div>';
                                html += '</td>';
                                html += '<td style="padding:4px 6px;text-align:right;">' + qty + '</td>';
                                html += '<td style="padding:4px 6px;text-align:right;">' + (cost ? '$' + Number(cost).toFixed(2) : '') + '</td>';
                                html += '</tr>';
                            });
                            html += '</table>';
                            tip.innerHTML = html;
                            document.body.appendChild(tip);
                            gffcOrderTooltip = tip;

                            var rect = el.getBoundingClientRect();
                            var tipRect = tip.getBoundingClientRect();
                            var left = rect.left;
                            var top = rect.bottom + 4;
                            if (left + tipRect.width > window.innerWidth - 10) left = window.innerWidth - tipRect.width - 10;
                            if (top + tipRect.height > window.innerHeight - 10) top = rect.top - tipRect.height - 4;
                            tip.style.left = left + 'px';
                            tip.style.top = top + 'px';
                        }
                        function gffcHideOrderTooltip() {
                            if (gffcOrderTooltip) { gffcOrderTooltip.remove(); gffcOrderTooltip = null; }
                        }

                        // Submit tracking number
                        function gffcSubmitTracking(distid, order_id, distributor_order_id) {
                            var trackingEl = document.getElementById('tracking-' + distid + '-' + distributor_order_id);
                            if (!trackingEl) return;
                            var tracking = trackingEl.value.trim();
                            if (!tracking) { alert('Please enter a tracking number.'); return; }
                            var carrier = '';

                            if (!confirm('Mark order ' + distributor_order_id + ' as Shipped with tracking: ' + tracking + '?')) return;

                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({
                                    "action": "update_fulfillment_tracking",
                                    "data": {
                                        "api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                        "order_id": order_id,
                                        "distributor_order_id": distributor_order_id,
                                        "tracking_number": tracking,
                                        "carrier": carrier
                                    }
                                })
                            })
                            .then(function(r) { return r.json(); })
                            .then(function(data) {
                                if (data.success) {
                                    of_grid.forceRender();
                                } else {
                                    alert('Failed to update tracking. Please try again.');
                                }
                            })
                            .catch(function(err) {
                                console.error(err);
                                alert('Error updating tracking: ' + err.message);
                            });
                        }

                        document.getElementById("download_fulfillment_history_button").addEventListener("click", function(){
                            document.getElementById("download_fulfillment_history_button").disabled = true;
                            document.getElementById('download_fulfillment_history_button').innerText = 'Please Wait...';
                            fetch("https://ffl-api.garidium.com/download", {
                                method: "POST",
                                headers: {
                                "Accept": "application/json",
                                "Content-Type": "application/json",
                                "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                                },
                                body: JSON.stringify({"action": "download_fulfillment_history"})
                            })
                            .then(response=>response.json())
                            .then(data=>{ 
                                window.open(data);  
                                document.getElementById("download_fulfillment_history_button").disabled = false; 
                                document.getElementById('download_fulfillment_history_button').innerText = 'Download Fulfillment History';     
                            });
                        });

                        function gffcParseGunbrokerSku(sku) {
                            const raw = String(sku || '').trim();
                            if (!raw || raw.indexOf('|') === -1) {
                                return { distid: '', distsku: raw };
                            }
                            const parts = raw.split('|');
                            return {
                                distid: String(parts[0] || '').trim().toUpperCase(),
                                distsku: String(parts.slice(1).join('|') || '').trim()
                            };
                        }

                        function gffcParseProductImages(imagesRaw) {
                            if (Array.isArray(imagesRaw)) return imagesRaw;
                            if (typeof imagesRaw === 'string') {
                                try {
                                    const parsed = JSON.parse(imagesRaw);
                                    return Array.isArray(parsed) ? parsed : [];
                                } catch (e) {
                                    return [];
                                }
                            }
                            return [];
                        }

                        async function gffcFetchFilteredCatalogProducts(searchTerm) {
                            const term = String(searchTerm || '').trim();
                            if (!term) return [];
                            const apiKey = (typeof gffcApiKey !== 'undefined' && gffcApiKey) ? gffcApiKey : "<?php echo esc_attr($gFFLCockpitKey); ?>";
                            const url = `https://ffl-api.garidium.com/product?action=get_filtered_catalog&search=${encodeURIComponent(term)}&ignore_product_restrictions=true&load_site_map=True`;
                            const resp = await fetch(url, {
                                method: 'GET',
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": apiKey
                                }
                            });
                            const parsed = await resp.json().catch(() => null);
                            if (!resp.ok || !parsed) {
                                return [];
                            }
                            if (Array.isArray(parsed.products)) {
                                return parsed.products;
                            }
                            if (Array.isArray(parsed)) {
                                return parsed;
                            }
                            return [];
                        }

                        function gffcNormalizeCatalogProduct(product) {
                            return {
                                distid: String(product?.distid || '').trim().toUpperCase(),
                                distsku: String(product?.distsku || '').trim(),
                                upc: String(product?.upc || '').trim(),
                                name: String(product?.name || '').trim(),
                                mfg_name: String(product?.mfg_name || '').trim(),
                                mpn: String(product?.mpn || '').trim(),
                                qty_on_hand: parseInt(product?.qty_on_hand || 0, 10) || 0,
                                unit_price: Number(product?.unit_price || 0),
                                shipping_cost: Number(product?.shipping_cost || 0),
                                total_cost: Number(product?.total_cost || 0),
                                drop_ship_flg: Number(product?.drop_ship_flg || 0),
                                product_url: product?.product_url || '',
                                permalink: product?.permalink || '',
                                product_class: product?.product_class || '',
                                product_class_description: product?.product_class_description || '',
                                order_line_item_sku: String(product?.order_line_item_sku || '').trim(),
                                ffl_req: (typeof product?.ffl_req === 'boolean')
                                    ? product.ffl_req
                                    : (product?.ffl_req === 1 || product?.ffl_req === '1'),
                                images: gffcParseProductImages(product?.images)
                            };
                        }

                        function gffcPickBestGunbrokerCatalogCandidate(candidates, gbItem, parsedSku) {
                            const requestedQty = Math.max(1, parseInt(gbItem?.quantity || 1, 10) || 1);
                            const upc = String(gbItem?.upc || '').trim();
                            const exactDist = String(parsedSku?.distid || '').trim().toUpperCase();
                            const exactSku = String(parsedSku?.distsku || '').trim();

                            const normalized = candidates.map(gffcNormalizeCatalogProduct);
                            const shippable = normalized.filter(p => p.drop_ship_flg && p.qty_on_hand >= requestedQty);

                            if (!shippable.length) return null;

                            const exactSkuMatches = (exactDist && exactSku)
                                ? shippable.filter(p => p.distid === exactDist && p.distsku === exactSku)
                                : [];
                            const upcMatches = upc ? shippable.filter(p => p.upc === upc) : [];
                            const pool = exactSkuMatches.length ? exactSkuMatches : (upcMatches.length ? upcMatches : shippable);

                            pool.sort((a, b) => {
                                const at = Number.isFinite(a.total_cost) ? a.total_cost : Number.MAX_SAFE_INTEGER;
                                const bt = Number.isFinite(b.total_cost) ? b.total_cost : Number.MAX_SAFE_INTEGER;
                                if (at !== bt) return at - bt;
                                const au = Number.isFinite(a.unit_price) ? a.unit_price : Number.MAX_SAFE_INTEGER;
                                const bu = Number.isFinite(b.unit_price) ? b.unit_price : Number.MAX_SAFE_INTEGER;
                                return au - bu;
                            });
                            return pool[0] || null;
                        }

                        function gffcPickBestGunbrokerFulfillmentOption(fulfillmentOptions, gbItem, parsedSku) {
                            const requestedQty = Math.max(1, parseInt(gbItem?.quantity || 1, 10) || 1);
                            const upc = String(gbItem?.upc || '').trim();
                            const exactDist = String(parsedSku?.distid || '').trim().toUpperCase();
                            const exactSku = String(parsedSku?.distsku || '').trim();

                            const normalized = (Array.isArray(fulfillmentOptions) ? fulfillmentOptions : []).map(gffcNormalizeCatalogProduct);
                            const shippable = normalized.filter(p => p.drop_ship_flg && p.qty_on_hand >= requestedQty);
                            if (!shippable.length) return null;

                            const exactSkuMatches = (exactDist && exactSku)
                                ? shippable.filter(p => {
                                    const optionLineSku = String(p?.order_line_item_sku || '').trim();
                                    return p.distid === exactDist && (p.distsku === exactSku || optionLineSku === exactSku);
                                })
                                : [];
                            const upcMatches = upc ? shippable.filter(p => p.upc === upc) : [];
                            const pool = exactSkuMatches.length ? exactSkuMatches : (upcMatches.length ? upcMatches : shippable);

                            pool.sort((a, b) => {
                                const at = Number.isFinite(a.total_cost) ? a.total_cost : Number.MAX_SAFE_INTEGER;
                                const bt = Number.isFinite(b.total_cost) ? b.total_cost : Number.MAX_SAFE_INTEGER;
                                if (at !== bt) return at - bt;
                                const au = Number.isFinite(a.unit_price) ? a.unit_price : Number.MAX_SAFE_INTEGER;
                                const bu = Number.isFinite(b.unit_price) ? b.unit_price : Number.MAX_SAFE_INTEGER;
                                return au - bu;
                            });
                            return pool[0] || null;
                        }

                        function gffcBuildCartItemFromCatalogProduct(product, requestedQty, gbItem) {
                            return {
                                distid: product.distid,
                                distsku: product.distsku,
                                upc: product.upc,
                                name: product.name,
                                mfg_name: product.mfg_name,
                                mpn: product.mpn,
                                qty_on_hand: product.qty_on_hand,
                                unit_price: product.unit_price,
                                shipping_cost: product.shipping_cost,
                                total_cost: product.total_cost,
                                drop_ship_flg: product.drop_ship_flg,
                                product_url: product.product_url,
                                permalink: product.permalink,
                                product_class: product.product_class,
                                product_class_description: product.product_class_description,
                                images: product.images,
                                qty: requestedQty,
                                ffl_req: typeof product.ffl_req === 'boolean' ? product.ffl_req : !!gbItem?.isFFLRequired
                            };
                        }

                        function gffcBuildGunbrokerCheckoutPrefill(orderData, checkoutType) {
                            const zipFromBill = String(orderData?.billToPostalCode || '').split('-')[0];
                            const shipAddress = [orderData?.shipToAddress1 || '', orderData?.shipToAddress2 || ''].filter(Boolean).join(', ');
                            const selectedFfl = {
                                license_number: String(orderData?.fflNumber || '').trim(),
                                name: String(orderData?.shipToName || '').trim(),
                                address: shipAddress,
                                city: String(orderData?.shipToCity || '').trim(),
                                state: String(orderData?.shipToState || '').trim(),
                                zip: String(orderData?.shipToPostalCode || '').trim(),
                                phone: String(orderData?.shipToPhone || '').trim(),
                                email: String(orderData?.shipToEmail || '').trim()
                            };
                            const isShipToStore = checkoutType === 'ship_to_store';
                            const isDropShip = !isShipToStore;
                            return {
                                orderType: isShipToStore ? 'ship_to_store' : 'drop_ship',
                                shippingDest: isDropShip ? (selectedFfl.license_number ? 'ffl' : 'customer') : 'customer',
                                values: {
                                    gffc_customer_name: String(orderData?.billToName || orderData?.shipToName || '').trim(),
                                    gffc_customer_email: String(orderData?.billToEmail || '').trim(),
                                    gffc_customer_phone: String(orderData?.billToPhone || '').trim(),
                                    gffc_customer_address1: isShipToStore ? '' : String(orderData?.billToAddress1 || '').trim(),
                                    gffc_customer_address2: isShipToStore ? '' : String(orderData?.billToAddress2 || '').trim(),
                                    gffc_customer_city: isShipToStore ? '' : String(orderData?.billToCity || '').trim(),
                                    gffc_customer_state: isShipToStore ? '' : String(orderData?.billToState || '').trim(),
                                    gffc_customer_zip: isShipToStore ? '' : zipFromBill,
                                    gffc_ffl_license_number: isDropShip ? selectedFfl.license_number : '',
                                    gffc_ffl_zip: isDropShip ? String(orderData?.shipToPostalCode || '').split('-')[0] : '',
                                    gffc_ffl_name: isDropShip ? selectedFfl.name : '',
                                    gffc_ffl_radius: '25'
                                },
                                selectedFfl: (isDropShip && selectedFfl.license_number) ? selectedFfl : null,
                                fflSearchResults: [],
                                fflResultsHtml: '',
                                fflSelectedHtml: ''
                            };
                        }

                        function gffcOpenCartTabFromGunbroker() {
                            const cartTab = document.getElementById('gffc_cart_tab_btn');
                            if (!cartTab) return;
                            let opened = false;
                            if (typeof window.openTab === 'function') {
                                try {
                                    window.openTab({ currentTarget: cartTab, preventDefault: function(){} }, 'cart');
                                    opened = true;
                                } catch (e) {}
                            }
                            if (!opened) {
                                cartTab.click();
                            }
                            setTimeout(() => {
                                try { window.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); } catch (e) { window.scrollTo(0, 0); }
                                const wpBodyContent = document.getElementById('wpbody-content');
                                if (wpBodyContent && typeof wpBodyContent.scrollTo === 'function') {
                                    try { wpBodyContent.scrollTo({ top: 0, left: 0, behavior: 'smooth' }); } catch (e) { wpBodyContent.scrollTop = 0; }
                                }
                            }, 75);
                        }

                        function gffcSetGunbrokerCartDisclaimer(orderId, checkoutType) {
                            const notice = document.getElementById('gffc_gunbroker_cart_notice');
                            if (!notice) return;
                            const modeLabel = checkoutType === 'ship_to_store' ? 'Ship-to-Store' : 'Drop-Ship';
                            notice.innerHTML = `
                                <div style="font-weight:700; margin-bottom:4px;">GunBroker Cart Created: Order #${orderId} (${modeLabel})</div>
                                <div>Please validate all customer, shipping, FFL, item, quantity, and pricing details before submitting. Confirm they match the GunBroker order exactly.</div>
                            `;
                            notice.style.display = '';
                        }

                        function gffcSetGunbrokerCartContext(orderId) {
                            const parsed = parseInt(orderId, 10);
                            if (!Number.isInteger(parsed) || parsed <= 0) return;
                            window.gffcCartOrderContext = {
                                gunbroker_order_id: parsed
                            };
                        }

                        function gffcGetCartOrderContext() {
                            const ctx = window.gffcCartOrderContext || null;
                            if (!ctx) return null;
                            const parsed = parseInt(ctx.gunbroker_order_id, 10);
                            if (!Number.isInteger(parsed) || parsed <= 0) return null;
                            return {
                                gunbroker_order_id: parsed
                            };
                        }

                        function gffcClearCartOrderContext() {
                            window.gffcCartOrderContext = null;
                        }

                        function gffcRunGunbrokerGenerateFlow(orderId, onGenerate) {
                            return new Promise((resolve) => {
                                const existing = document.getElementById('gffc-gunbroker-generate-modal');
                                if (existing) existing.remove();
                                if (!document.getElementById('gffc-gb-progress-style')) {
                                    const style = document.createElement('style');
                                    style.id = 'gffc-gb-progress-style';
                                    style.textContent = '@keyframes gffcGbProgress { 0% { background-position: 0% 0; } 100% { background-position: 200% 0; } }';
                                    document.head.appendChild(style);
                                }

                                let stage = 'select';
                                let settled = false;
                                const overlay = document.createElement('div');
                                overlay.id = 'gffc-gunbroker-generate-modal';
                                overlay.style.cssText = 'position:fixed; inset:0; background:rgba(15,23,42,0.55); backdrop-filter: blur(2px); z-index:100000; display:flex; align-items:center; justify-content:center; padding:20px;';
                                overlay.innerHTML = `
                                    <div role="dialog" aria-modal="true" aria-label="Generate GunBroker Cart" style="width:100%; max-width:560px; background:#fff; border-radius:14px; box-shadow:0 18px 55px rgba(15,23,42,0.28); overflow:hidden;">
                                        <div style="padding:16px 18px; border-bottom:1px solid #e2e8f0; background:linear-gradient(180deg,#f8fafc,#ffffff);">
                                            <div style="font-size:18px; font-weight:700; color:#0f172a;">Generate Cart From GunBroker</div>
                                            <div style="margin-top:4px; color:#475569; font-size:13px;">Order #${orderId}</div>
                                        </div>
                                        <div id="gffc_gb_modal_body" style="padding:16px 18px;">
                                            <div style="color:#334155; margin-bottom:10px;">Choose checkout mode and confirm cart generation.</div>
                                            <label style="display:flex; align-items:flex-start; gap:10px; padding:10px 12px; border:1px solid #cbd5e1; border-radius:10px; background:#f8fafc; margin-bottom:10px; cursor:pointer;">
                                                <input type="radio" name="gffc_gb_checkout_type" value="ship_to_store" checked style="margin-top:3px;" />
                                                <span><strong>Ship-to-Store</strong><br><span style="font-size:12px; color:#64748b;">Preselect store shipment and preload customer/FFL details from the GunBroker order.</span></span>
                                            </label>
                                            <label style="display:flex; align-items:flex-start; gap:10px; padding:10px 12px; border:1px solid #cbd5e1; border-radius:10px; background:#f8fafc; cursor:pointer;">
                                                <input type="radio" name="gffc_gb_checkout_type" value="drop_ship" style="margin-top:3px;" />
                                                <span><strong>Drop-Ship</strong><br><span style="font-size:12px; color:#64748b;">Preselect drop-ship checkout and preload customer/FFL details from the GunBroker order.</span></span>
                                            </label>
                                            <div style="margin-top:12px; padding:10px 12px; border:1px solid #fecaca; border-radius:10px; background:#fff1f2; color:#881337; font-size:12px;">
                                                This action clears the current Search cart and rebuilds it from the selected GunBroker order.
                                            </div>
                                        </div>
                                        <div id="gffc_gb_modal_footer" style="padding:12px 18px; border-top:1px solid #e2e8f0; display:flex; justify-content:flex-end; gap:8px;">
                                            <button type="button" id="gffc_gb_modal_cancel" class="button">Cancel</button>
                                            <button type="button" id="gffc_gb_modal_confirm" class="button button-primary">Generate Cart</button>
                                        </div>
                                    </div>
                                `;
                                document.body.appendChild(overlay);

                                const close = (result) => {
                                    if (settled) return;
                                    settled = true;
                                    const modal = document.getElementById('gffc-gunbroker-generate-modal');
                                    if (modal) modal.remove();
                                    document.removeEventListener('keydown', onEscape);
                                    resolve(result);
                                };

                                const onEscape = (e) => {
                                    if (e.key === 'Escape' && stage !== 'progress') {
                                        close(null);
                                    }
                                };
                                document.addEventListener('keydown', onEscape);

                                overlay.addEventListener('click', (e) => {
                                    if (e.target === overlay && stage !== 'progress') {
                                        close(null);
                                    }
                                });

                                const cancelBtn = overlay.querySelector('#gffc_gb_modal_cancel');
                                const confirmBtn = overlay.querySelector('#gffc_gb_modal_confirm');
                                const bodyEl = overlay.querySelector('#gffc_gb_modal_body');
                                const footerEl = overlay.querySelector('#gffc_gb_modal_footer');

                                const escapeHtml = function(input) {
                                    return String(input == null ? '' : input)
                                        .replace(/&/g, '&amp;')
                                        .replace(/</g, '&lt;')
                                        .replace(/>/g, '&gt;')
                                        .replace(/"/g, '&quot;')
                                        .replace(/'/g, '&#39;');
                                };

                                const renderProgress = function(checkoutType) {
                                    stage = 'progress';
                                    if (bodyEl) {
                                        bodyEl.innerHTML = `
                                            <div style="font-size:15px; font-weight:700; color:#0f172a; margin-bottom:6px;">Building cart...</div>
                                            <div style="font-size:13px; color:#475569; margin-bottom:12px;">Mode: ${checkoutType === 'drop_ship' ? 'Drop-Ship' : 'Ship-to-Store'}. Matching items and preloading checkout details.</div>
                                            <div style="height:12px; border:1px solid #cbd5e1; border-radius:999px; overflow:hidden; background:#f1f5f9;">
                                                <div style="height:100%; width:100%; background:linear-gradient(90deg,#2563eb,#38bdf8,#2563eb); background-size:200% 100%; animation:gffcGbProgress 1.2s linear infinite;"></div>
                                            </div>
                                        `;
                                    }
                                    if (footerEl) {
                                        footerEl.innerHTML = `<button type="button" class="button" disabled>Please wait...</button>`;
                                    }
                                };

                                const renderResult = function(ok, message, detailsText) {
                                    stage = 'result';
                                    const resultTitle = ok ? 'Cart Created' : 'Cart Creation Failed';
                                    const borderColor = ok ? '#bfdbfe' : '#fecaca';
                                    const bgColor = ok ? '#eff6ff' : '#fff1f2';
                                    const textColor = ok ? '#1e3a8a' : '#881337';
                                    const detailsBlock = detailsText
                                        ? `<div style="margin-top:10px; font-size:12px; color:#334155; white-space:pre-wrap; border:1px solid #e2e8f0; border-radius:8px; background:#f8fafc; padding:8px 10px;">${escapeHtml(detailsText)}</div>`
                                        : '';
                                    if (bodyEl) {
                                        bodyEl.innerHTML = `
                                            <div style="font-size:16px; font-weight:700; color:#0f172a; margin-bottom:10px;">${resultTitle}</div>
                                            <div style="padding:10px 12px; border:1px solid ${borderColor}; border-radius:10px; background:${bgColor}; color:${textColor}; white-space:pre-wrap;">${escapeHtml(message)}</div>
                                            ${detailsBlock}
                                        `;
                                    }
                                    if (footerEl) {
                                        footerEl.innerHTML = `<button type="button" id="gffc_gb_modal_done" class="button button-primary">${ok ? 'Open Cart' : 'Close'}</button>`;
                                        const doneBtn = footerEl.querySelector('#gffc_gb_modal_done');
                                        if (doneBtn) {
                                            doneBtn.addEventListener('click', () => close({ ok }));
                                        }
                                    }
                                };

                                if (cancelBtn) {
                                    cancelBtn.addEventListener('click', () => {
                                        close(null);
                                    });
                                }
                                if (confirmBtn) {
                                    confirmBtn.addEventListener('click', async () => {
                                        const selectedType = overlay.querySelector('input[name="gffc_gb_checkout_type"]:checked');
                                        const checkoutType = selectedType ? selectedType.value : 'ship_to_store';
                                        renderProgress(checkoutType);
                                        try {
                                            const result = await onGenerate(checkoutType);
                                            const missingItems = Array.isArray(result?.missingItems) ? result.missingItems : [];
                                            if (missingItems.length) {
                                                const missingText = missingItems.map(m => `${m.title} (UPC: ${m.upc || 'n/a'}, SKU: ${m.sku || 'n/a'}, Qty: ${m.qty})`).join('\n');
                                                renderResult(
                                                    true,
                                                    `Cart generated for GunBroker Order #${orderId} with ${result.selectedCount || 0} matched item(s). Some items were not added automatically.`,
                                                    missingText
                                                );
                                            } else {
                                                renderResult(
                                                    true,
                                                    `Cart generated for GunBroker Order #${orderId}. The cart has been prefilled for ${checkoutType === 'drop_ship' ? 'Drop-Ship' : 'Ship-to-Store'} checkout.`
                                                );
                                            }
                                        } catch (error) {
                                            const fallbackError = (error && error.message) ? error.message : 'Failed to generate cart from GunBroker order.';
                                            renderResult(
                                                false,
                                                'There was an error finding fulfillment options for this order. You will need to fulfill this order manually.',
                                                fallbackError
                                            );
                                        }
                                    });
                                }
                            });
                        }

                        async function gffcGenerateGunbrokerCart(orderId, checkoutType, sourceApiKey = null) {
                            const normalizedOrderId = parseInt(orderId, 10);
                            if (!Number.isInteger(normalizedOrderId) || normalizedOrderId <= 0) {
                                throw new Error('No GunBroker order selected.');
                            }
                            if (typeof gffcCartApi !== 'function') {
                                throw new Error('Cart API is unavailable on this page.');
                            }

                            const apiKey = (sourceApiKey && String(sourceApiKey).trim())
                                ? String(sourceApiKey).trim()
                                : ((typeof gffcApiKey !== 'undefined' && gffcApiKey) ? gffcApiKey : "<?php echo esc_attr($gFFLCockpitKey); ?>");
                            const detailsResp = await fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json",
                                    "x-api-key": apiKey
                                },
                                body: JSON.stringify({
                                    action: "get_gunbroker_order_and_fulfillment_options",
                                    data: {
                                        api_key: apiKey,
                                        gunbroker_order_id: normalizedOrderId
                                    }
                                })
                            });
                            const detailsData = await detailsResp.json().catch(() => null);
                            const orderData = (detailsData && (detailsData.gunbroker_order || detailsData.order_data)) ? (detailsData.gunbroker_order || detailsData.order_data) : null;
                            const fulfillmentOptions = Array.isArray(detailsData?.fulfillment_options) ? detailsData.fulfillment_options : [];
                            if (!detailsResp.ok || !detailsData || !detailsData.success || !orderData) {
                                throw new Error('Failed to load GunBroker order details.');
                            }

                            const orderItems = Array.isArray(orderData.items) ? orderData.items : [];
                            if (!orderItems.length) {
                                throw new Error('GunBroker order has no line items.');
                            }

                            const selectedCartItems = [];
                            const missingItems = [];

                            for (let idx = 0; idx < orderItems.length; idx++) {
                                const gbItem = orderItems[idx];
                                const requestedQty = Math.max(1, parseInt(gbItem?.quantity || 1, 10) || 1);
                                const parsedSku = gffcParseGunbrokerSku(gbItem?.sku || '');

                                let best = gffcPickBestGunbrokerFulfillmentOption(fulfillmentOptions, gbItem, parsedSku);
                                if (!best) {
                                    // Fallback to legacy catalog lookup if fulfillment options did not return a match.
                                    let candidates = [];
                                    if (gbItem?.upc) {
                                        candidates = await gffcFetchFilteredCatalogProducts(gbItem.upc);
                                    }
                                    if (!candidates.length && parsedSku.distsku) {
                                        candidates = await gffcFetchFilteredCatalogProducts(parsedSku.distsku);
                                    }
                                    if (!candidates.length && gbItem?.title) {
                                        candidates = await gffcFetchFilteredCatalogProducts(gbItem.title);
                                    }
                                    best = gffcPickBestGunbrokerCatalogCandidate(candidates, gbItem, parsedSku);
                                }
                                if (!best) {
                                    missingItems.push({
                                        title: gbItem?.title || ('Item #' + (idx + 1)),
                                        upc: gbItem?.upc || '',
                                        sku: gbItem?.sku || '',
                                        qty: requestedQty
                                    });
                                    continue;
                                }

                                selectedCartItems.push(gffcBuildCartItemFromCatalogProduct(best, requestedQty, gbItem));
                            }

                            if (!selectedCartItems.length) {
                                throw new Error('No shippable fulfillment options were found for this GunBroker order.');
                            }

                            await gffcCartApi('/cart/clear', {});
                            for (const item of selectedCartItems) {
                                await gffcCartApi('/cart/add', { item: item });
                            }

                            if (typeof gffcRefreshCartUI === 'function') {
                                await gffcRefreshCartUI();
                            }

                            const checkoutPrefill = gffcBuildGunbrokerCheckoutPrefill(orderData, checkoutType);
                            if (typeof gffcRestoreCheckoutState === 'function') {
                                gffcRestoreCheckoutState(checkoutPrefill);
                            }
                            if (typeof gffcToggleCheckoutMode === 'function') {
                                gffcToggleCheckoutMode();
                            }
                            gffcSetGunbrokerCartContext(normalizedOrderId);
                            gffcOpenCartTabFromGunbroker();
                            gffcSetGunbrokerCartDisclaimer(normalizedOrderId, checkoutType);
                            return {
                                orderId: normalizedOrderId,
                                selectedCount: selectedCartItems.length,
                                missingItems
                            };
                        }
                        
                        fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: {
                            "Accept": "application/json",
                            "Content-Type": "application/json",
                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                            },
                            body: JSON.stringify({"action": "list_gunbroker_orders", "data": {"api_key": "<?php echo esc_attr($gFFLCockpitKey); ?>"}})
                        })
                        .then(response=>response.json())
                        .then(data=>{ 
                            // Get the dropdown element
                            const dropdown = document.getElementById('gunbroker_order_id');
                            function gffcGetSelectedGunbrokerContext() {
                                const selectedOption = dropdown && dropdown.options ? dropdown.options[dropdown.selectedIndex] : null;
                                const selectedValue = String((dropdown && dropdown.value) ? dropdown.value : '').trim();
                                const orderIdRaw = (selectedOption && selectedOption.dataset && selectedOption.dataset.orderId)
                                    ? String(selectedOption.dataset.orderId).trim()
                                    : selectedValue;
                                const parsedOrderId = parseInt(orderIdRaw, 10);
                                const defaultApiKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";
                                const selectedApiKey = (selectedOption && selectedOption.dataset && selectedOption.dataset.apiKey)
                                    ? String(selectedOption.dataset.apiKey).trim()
                                    : defaultApiKey;
                                return { orderId: Number.isInteger(parsedOrderId) && parsedOrderId > 0 ? parsedOrderId : null, apiKey: selectedApiKey };
                            }
                            const excludedGunbrokerOrderIds = new Set(['29181082']);
                            const rawGunbrokerOrders = Array.isArray(data.order_data) ? data.order_data : [];
                            const gunbrokerOrders = rawGunbrokerOrders.filter(item => {
                                const orderId = String(item && item.orderID ? item.orderID : '').trim();
                                return orderId && !excludedGunbrokerOrderIds.has(orderId);
                            });
                            const hasGunbrokerOrders = gunbrokerOrders.length > 0;
                            const hasGunbrokerConfiguredTarget = window.gffcHasGunbrokerTargetInConfig === true;
                            if (hasGunbrokerOrders){
                                // Loop through the data and create an option for each item
                                gunbrokerOrders.forEach(item => {
                                    const option = document.createElement('option');
                                    option.value = item.orderID;
                                    timestamp = new Date(item.orderDateUTC).toLocaleString('en-US', {timeZone: 'UTC'});
                                    option.text = item.orderID + " - " + timestamp + " - " + item.billToName;
                                    dropdown.appendChild(option);
                                });

                            } else if (hasGunbrokerConfiguredTarget) {
                                dropdown.innerHTML = '';
                            }

                            if (dropdown) {
                                const processButton = document.getElementById("process_gunbroker_order_button");
                                const importButton = document.getElementById("import_gunbroker_order_button");
                                const generateCartButton = document.getElementById("generate_gunbroker_cart_button");
                                const section = document.getElementById("gunbroker_processor_section");
                                if (!processButton || !importButton || !generateCartButton || !section) {
                                    return;
                                }
                                const shouldShowGunbrokerSection = hasGunbrokerOrders || hasGunbrokerConfiguredTarget || (dropdown.options && dropdown.options.length > 0);
                                if (shouldShowGunbrokerSection) {
                                    section.style.display = "";
                                }
                                const hasValidSelectedOrder = function() {
                                    if (!dropdown) return false;
                                    const selected = gffcGetSelectedGunbrokerContext();
                                    return Number.isInteger(selected.orderId) && selected.orderId > 0;
                                };
                                const updateGunbrokerActionButtonsState = function() {
                                    const enabled = hasValidSelectedOrder();
                                    processButton.disabled = !enabled;
                                    importButton.disabled = !enabled;
                                    generateCartButton.disabled = !enabled;
                                };

                                updateGunbrokerActionButtonsState();
                                if (!dropdown.dataset.gffcGunbrokerChangeBound) {
                                    dropdown.addEventListener('change', updateGunbrokerActionButtonsState);
                                    dropdown.dataset.gffcGunbrokerChangeBound = '1';
                                }

                                if (!processButton.dataset.gffcGunbrokerClickBound) {
                                    processButton.addEventListener("click", function(){
                                    const selected = gffcGetSelectedGunbrokerContext();
                                    if (!Number.isInteger(selected.orderId) || selected.orderId <= 0) {
                                        alert('Select a valid GunBroker order first.');
                                        return;
                                    }
                                    if (window.confirm("This will place a new distributor order, fulfilling GunBroker Order#" + selected.orderId + ". Are you sure you need a new order placed, and do you want to proceed?")){
                                        document.getElementById("process_gunbroker_order_button").disabled = true;
                                        document.getElementById('process_gunbroker_order_button').innerText = 'Please Wait...';
                                        fetch("https://ffl-api.garidium.com", {
                                            method: "POST",
                                            headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": selected.apiKey,
                                            },
                                            body: JSON.stringify({"action": "place_distributor_order", "data": {"api_key": selected.apiKey , "order_source": "gunbroker", "order_id": selected.orderId}})
                                        })
                                        .then(response=>response.json())
                                        .then(data=>{ 
                                            document.getElementById("process_gunbroker_order_button").disabled = false; 
                                            document.getElementById('process_gunbroker_order_button').innerText = 'Fulfill';     
                                            if (data.Error != null && data.Error != undefined){
                                                alert(data.Error);
                                            }else{
                                                of_grid.forceRender();
                                            }
                                        });
                                    }
                                });
                                    processButton.dataset.gffcGunbrokerClickBound = '1';
                                }

                                if (!importButton.dataset.gffcGunbrokerClickBound) {
                                    importButton.addEventListener("click", function(){
                                    const selected = gffcGetSelectedGunbrokerContext();
                                    if (!Number.isInteger(selected.orderId) || selected.orderId <= 0) {
                                        alert('Select a valid GunBroker order first.');
                                        return;
                                    }
                                    if (window.confirm("This will import GunBroker Order#" + selected.orderId + ", creating an equivalent WooCommerce Order. The order will come over with the email and selected FFL in the order comments section, so that the customer isn't emailed. This is a beta feature in testing, Are you sure you want to proceed?")){
                                        document.getElementById("import_gunbroker_order_button").disabled = true;
                                        document.getElementById('import_gunbroker_order_button').innerText = 'Please Wait...';
                                        fetch("https://ffl-api.garidium.com", {
                                            method: "POST",
                                            headers: {
                                            "Accept": "application/json",
                                            "Content-Type": "application/json",
                                            "x-api-key": selected.apiKey,
                                            },
                                            body: JSON.stringify({"action": "import_gunbroker_order", "data": {"api_key": selected.apiKey , "gunbroker_order_id": Number(selected.orderId)}})
                                        })
                                        .then(response=>response.json())
                                        .then(data=>{ 
                                            document.getElementById("import_gunbroker_order_button").disabled = false; 
                                            document.getElementById('import_gunbroker_order_button').innerText = 'Import';     
                                            if (data.Error != null && data.Error != undefined){
                                                alert(data.Error);
                                            }else{
                                                alert("Gunbroker Order Imported, go to the WooCommerce order page to view Order.");
                                            }
                                        });
                                    }
                                });
                                    importButton.dataset.gffcGunbrokerClickBound = '1';
                                }

                                if (!generateCartButton.dataset.gffcGunbrokerClickBound) {
                                    generateCartButton.addEventListener("click", async function(){
                                    const selected = gffcGetSelectedGunbrokerContext();
                                    const orderId = selected.orderId;
                                    if (!orderId) {
                                        alert('Select a GunBroker order first.');
                                        return;
                                    }
                                    const originalText = generateCartButton.innerText;
                                    generateCartButton.disabled = true;
                                    generateCartButton.innerText = 'In Progress...';
                                    try {
                                        await gffcRunGunbrokerGenerateFlow(orderId, async (checkoutType) => {
                                            return await gffcGenerateGunbrokerCart(orderId, checkoutType, selected.apiKey);
                                        });
                                    } catch (error) {
                                        console.error(error);
                                    } finally {
                                        updateGunbrokerActionButtonsState();
                                        generateCartButton.innerText = originalText;
                                    }
                                });
                                    generateCartButton.dataset.gffcGunbrokerClickBound = '1';
                                }
                            }
                        });
                        
                    </script>
                </div>
            </div>         
            <button class="accordion">Analytics</button>
            <div id="marketplace_dashboard" class="tabcontent">
                <style>
                    /* ── Dashboard Styles ── */
                    .gffc-dash { position: relative; }
                    .gffc-dash-loading { text-align: center; padding: 60px 20px; }
                    .gffc-dash-loading-logo { display: inline-block; user-select: none; position: relative; }
                    .gffc-dash-loading-logo img { width: 220px; height: auto; display: block; margin: 0 auto; }
                    .gffc-dash-loading-logo .gffc-logo-sub { display: block; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 12px; font-weight: 600; color: #94a3b8; letter-spacing: 2px; text-transform: uppercase; margin-top: 6px; text-align: center; }
                    .gffc-dash-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px; }
                    .gffc-dash-title { font-size: 22px; font-weight: 700; color: #3d3d3c; }
                    .gffc-dash-controls { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
                    .gffc-dash-toggle { display: inline-flex; border-radius: 6px; overflow: hidden; border: 1px solid #ccc; }
                    .gffc-dash-toggle-btn { background: #fff; border: none; padding: 6px 16px; cursor: pointer; font-size: 13px; font-weight: 600; color: #666; transition: all 0.2s; }
                    .gffc-dash-toggle-btn.active { background: #3d3d3c; color: #fff; }
                    .gffc-dash-toggle-btn:hover:not(.active) { background: #e9ecef; }
                    .gffc-dash-asof { font-size: 12px; color: #999; font-style: italic; }

                    /* Product Class Toggle Buttons */
                    .gffc-dash-class-toggles { display: inline-flex; flex-wrap: wrap; gap: 0; border-radius: 6px; overflow: hidden; border: 1px solid #ccc; }
                    .gffc-dash-class-toggle-btn { background: #fff; border: none; border-right: 1px solid #ccc; padding: 6px 16px; cursor: pointer; font-size: 13px; font-weight: 600; color: #666; transition: all 0.2s; white-space: nowrap; }
                    .gffc-dash-class-toggle-btn:last-child { border-right: none; }
                    .gffc-dash-class-toggle-btn.active { background: #3d3d3c; color: #fff; }
                    .gffc-dash-class-toggle-btn:hover:not(.active) { background: #e9ecef; }

                    /* Widget Cards */
                    .gffc-dash-widget { background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); margin-bottom: 20px; overflow: hidden; }
                    .gffc-dash-widget-header { background: #f0f0f0; color: #333; padding: 10px 16px; border-bottom: 1px solid #666; display: flex; align-items: flex-start; justify-content: space-between; }
                    .gffc-dash-widget-header h3 { margin: 0; font-size: 16px; font-weight: 600; color: #333 !important; }
                    .gffc-dash-widget-desc { font-size: 12px; color: #666; margin-top: 2px; font-weight: 400; }

                    /* Help Button in Widget Headers */
                    .gffc-dash-help-btn { background: rgba(0,254,72,0.25); border: 2px solid #333; color: #333; border-radius: 14px; cursor: pointer; font-size: 11px; font-weight: 700; line-height: 1; padding: 5px 10px; flex-shrink: 0; margin-left: 10px; margin-top: 1px; transition: all 0.2s; white-space: nowrap; }
                    .gffc-dash-help-btn:hover { background: rgba(0,254,72,0.5); box-shadow: 0 2px 6px rgba(0,254,72,0.3); }

                    /* Help Modal */
                    .gffc-dash-help-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 100000; align-items: center; justify-content: center; }
                    .gffc-dash-help-overlay.open { display: flex; }
                    .gffc-dash-help-modal { background: #fff; border-radius: 10px; box-shadow: 0 8px 30px rgba(0,0,0,0.25); max-width: 620px; width: 90%; max-height: 80vh; display: flex; flex-direction: column; }
                    .gffc-dash-help-modal-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid #e2e8f0; }
                    .gffc-dash-help-modal-header h3 { margin: 0; font-size: 17px; font-weight: 700; color: #3d3d3c; }
                    .gffc-dash-help-modal-close { background: none; border: none; font-size: 22px; color: #999; cursor: pointer; padding: 0 4px; line-height: 1; }
                    .gffc-dash-help-modal-close:hover { color: #333; }
                    .gffc-dash-help-modal-body { padding: 20px; overflow-y: auto; font-size: 13px; line-height: 1.65; color: #444; }
                    .gffc-dash-help-modal-body p { margin: 0 0 12px; }
                    .gffc-dash-help-modal-body p:last-child { margin-bottom: 0; }
                    .gffc-dash-help-modal-body .gffc-help-note { background: #f8f9fa; border-left: 3px solid #4a90d9; padding: 10px 14px; border-radius: 0 6px 6px 0; margin: 12px 0; font-size: 12px; color: #555; }
                    .gffc-dash-help-modal-body table { width: 100%; border-collapse: collapse; margin: 10px 0; font-size: 12px; }
                    .gffc-dash-help-modal-body table th { background: #f0f0f0; text-align: left; padding: 6px 10px; font-weight: 600; color: #555; border-bottom: 1px solid #ddd; }
                    .gffc-dash-help-modal-body table td { padding: 6px 10px; border-bottom: 1px solid #eee; }
                    .gffc-dash-help-modal-body table tr:last-child td { border-bottom: none; }
                    .gffc-dash-widget-body { padding: 0; overflow-x: auto; }

                    /* Layout */
                    .gffc-dash-row { display: flex; gap: 20px; margin-bottom: 0; }
                    .gffc-dash-col { flex: 1; min-width: 0; }

                    /* Tables */
                    .gffc-dash-table { width: 100%; border-collapse: collapse; font-size: 13px; }
                    .gffc-dash-table thead th { position: relative; background: #f8f9fa; padding: 8px 12px; text-align: left; font-weight: 600; color: #666; border-bottom: 2px solid #e9ecef; white-space: nowrap; font-size: 12px; }
                    .gffc-dash-table tbody td { padding: 7px 12px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
                    .gffc-dash-table tbody tr:hover { background: #edf2f7; }
                    .gffc-dash-table tbody tr[data-upc] { cursor: pointer; }
                    .gffc-dash-table tbody tr:last-child td { border-bottom: none; }
                    .gffc-dash-table thead th.gffc-dash-num { text-align: right; }
                    .gffc-dash-table td.gffc-dash-num { text-align: right; font-variant-numeric: tabular-nums; }
                    .gffc-dash-col-resizer { position: absolute; top: 0; right: -4px; width: 8px; height: 100%; cursor: col-resize; z-index: 3; user-select: none; }
                    .gffc-dash-col-resizer::after { content: ''; position: absolute; top: 20%; bottom: 20%; right: 3px; width: 1px; background: #cbd5e1; opacity: 0; transition: opacity 0.15s ease; }
                    .gffc-dash-table thead th:hover .gffc-dash-col-resizer::after,
                    .gffc-dash-table.gffc-dash-resizing .gffc-dash-col-resizer::after { opacity: 1; }
                    .gffc-dash-pagination { display: flex; justify-content: space-between; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid #e9ecef; background: #fafafa; }
                    .gffc-dash-pagination-info { font-size: 12px; color: #64748b; }
                    .gffc-dash-pagination-buttons { display: inline-flex; align-items: center; gap: 6px; }
                    .gffc-dash-page-btn { border: 1px solid #cbd5e1; background: #fff; color: #334155; border-radius: 4px; padding: 4px 10px; font-size: 12px; cursor: pointer; }
                    .gffc-dash-page-btn:hover:not(:disabled) { background: #f1f5f9; }
                    .gffc-dash-page-btn:disabled { opacity: 0.45; cursor: not-allowed; }

                    /* Badges */
                    .gffc-dash-badge { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; margin-left: 4px; vertical-align: middle; white-space: nowrap; }
                    .gffc-dash-badge-new { background: #7c3aed; color: #fff; }
                    .gffc-dash-badge-new30 { background: #ede9fe; color: #6d28d9; }
                    .gffc-dash-badge-restock { background: #0d9488; color: #fff; }
                    .gffc-dash-badge-lowest { background: #fef3c7; color: #92400e; }
                    .gffc-dash-badge-first-cat { background: #ef4444; color: #fff; }

                    /* Trend & Discount */
                    .gffc-dash-trend-up { color: #16a34a; font-weight: 700; }
                    .gffc-dash-trend-down { color: #dc2626; font-weight: 700; }
                    .gffc-dash-trend-nowrap { white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; }
                    .gffc-dash-discount { color: #dc2626; font-weight: 700; }
                    .gffc-dash-discount-good { color: #16a34a; font-weight: 700; white-space: nowrap; display: inline-flex; align-items: center; gap: 4px; }
                    .gffc-dash-profit { color: #16a34a; font-weight: 700; }
                    .gffc-dash-price-stack { display: inline-flex; flex-direction: column; align-items: flex-end; line-height: 1.2; gap: 2px; }
                    .gffc-dash-price-was { color: #999; text-decoration: line-through; font-size: 12px; }
                    .gffc-dash-price-now { color: #111827; font-weight: 700; }

                    /* Confidence bar */
                    .gffc-dash-conf-bar { display: inline-block; width: 50px; height: 8px; background: #e9ecef; border-radius: 4px; overflow: hidden; vertical-align: middle; margin-right: 4px; }
                    .gffc-dash-conf-fill { height: 100%; border-radius: 4px; }

                    /* Product name */
                    .gffc-dash-pname { font-weight: 500; color: #333; white-space: normal; overflow: visible; text-overflow: clip; display: inline; vertical-align: middle; }

                    /* Empty/Error states */
                    .gffc-dash-empty { text-align: center; padding: 30px; color: #999; font-size: 13px; }
                    .gffc-dash-error { text-align: center; padding: 20px; color: #dc3545; font-size: 13px; }
                    .gffc-dash-load-progress { width: 360px; margin: 2px auto 0; }
                    .gffc-dash-load-progress-bar { width: 100%; height: 6px; border-radius: 999px; background: #e2e8f0; overflow: hidden; }
                    .gffc-dash-load-progress-fill { width: 0%; height: 100%; border-radius: 999px; background: #00FE48; transition: width 0.3s ease; }
                    .gffc-dash-load-progress-text { margin-top: 12px; font-size: 12px; color: #94a3b8; font-weight: 500; letter-spacing: 0.3px; }


                    /* Global Filters */
                    .gffc-dash-filters { display: flex; flex-direction: column; gap: 0; margin-bottom: 16px; background: #fff; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.08); overflow: visible; border: 1px solid #e2e8f0; }
                    .gffc-dash-filter-group { display: flex; flex-direction: column; gap: 8px; padding: 12px 16px; border-bottom: 1px solid #e2e8f0; }
                    .gffc-dash-filter-group:last-child { border-bottom: none; }
                    .gffc-dash-filter-group label { font-size: 11px; font-weight: 700; color: #888; white-space: nowrap; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
                    .gffc-dash-filter-group label i { color: #4a90d9; margin-right: 3px; }

                    /* Category Toggle Buttons */
                    .gffc-dash-cat-toggles { display: inline-flex; flex-wrap: wrap; gap: 0; border-radius: 6px; overflow: hidden; border: 1px solid #ccc; }
                    .gffc-dash-cat-toggle-btn { background: #fff; border: none; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; padding: 5px 14px; cursor: pointer; font-size: 12px; font-weight: 600; color: #666; transition: all 0.2s; white-space: nowrap; }
                    .gffc-dash-cat-toggle-btn:last-child { border-right: none; }
                    .gffc-dash-cat-toggle-btn.active { background: #3d3d3c; color: #fff; }
                    .gffc-dash-cat-toggle-btn:hover:not(.active) { background: #e9ecef; }

                    /* Active filter summary */
                    .gffc-dash-active-filters { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; align-items: center; }
                    .gffc-dash-active-filters:empty { display: none; }
                    .gffc-dash-filter-pill { display: inline-flex; align-items: center; gap: 5px; background: #f0f4ff; color: #2563eb; border: 1px solid #bfdbfe; border-radius: 20px; padding: 5px 8px 5px 12px; font-size: 12px; font-weight: 500; }
                    .gffc-dash-filter-pill-label { color: #64748b; font-weight: 700; font-size: 10px; text-transform: uppercase; letter-spacing: 0.3px; }
                    .gffc-dash-filter-pill-remove { display: inline-flex; align-items: center; justify-content: center; background: #dbeafe; border: none; cursor: pointer; color: #2563eb; width: 18px; height: 18px; border-radius: 50%; font-size: 13px; line-height: 1; padding: 0; transition: all 0.15s; }
                    .gffc-dash-filter-pill-remove:hover { background: #2563eb; color: #fff; }
                    .gffc-dash-filter-clear-all { font-size: 12px; color: #dc3545; cursor: pointer; background: none; border: none; font-weight: 600; padding: 4px 8px; transition: opacity 0.15s; }
                    .gffc-dash-filter-clear-all:hover { text-decoration: underline; }

                    /* Responsive — tablets */
                    @media (max-width: 900px) {
                        .gffc-dash-row { flex-direction: column; }
                        .gffc-dash-header { flex-direction: column; align-items: flex-start; }
                        .gffc-dash-pname { font-size: 12px; }
                    }

                    /* Responsive — mobile */
                    @media (max-width: 600px) {
                        /* Header & controls */
                        .gffc-dash-title { font-size: 18px; }
                        .gffc-dash-controls { width: 100%; }
                        .gffc-dash-toggle { width: 100%; }
                        .gffc-dash-toggle-btn { flex: 1; padding: 8px 8px; font-size: 12px; text-align: center; }
                        .gffc-dash-asof { font-size: 11px; }

                        /* Filter toggles — full width, wrap naturally */
                        .gffc-dash-filters { border-radius: 6px; }
                        .gffc-dash-filter-group { padding: 10px 12px; }
                        .gffc-dash-class-toggles { display: flex; flex-wrap: wrap; border: none; border-radius: 0; gap: 6px; }
                        .gffc-dash-class-toggle-btn { border: 1px solid #ccc; border-radius: 6px; padding: 6px 12px; font-size: 12px; border-right: 1px solid #ccc; }
                        .gffc-dash-cat-toggles { display: flex; flex-wrap: wrap; border: none; border-radius: 0; gap: 6px; }
                        .gffc-dash-cat-toggle-btn { border: 1px solid #ccc; border-radius: 6px; padding: 5px 10px; font-size: 11px; border-right: 1px solid #ccc; }

                        /* Widget headers — stack title and help button */
                        .gffc-dash-widget-header { padding: 10px 12px; flex-wrap: wrap; gap: 6px; }
                        .gffc-dash-widget-header h3 { font-size: 14px; }
                        .gffc-dash-widget-desc { font-size: 11px; }
                        .gffc-dash-help-btn { margin-left: 0; font-size: 10px; padding: 4px 8px; }

                        /* Tables — smaller text, tighter padding */
                        .gffc-dash-table { font-size: 11px; }
                        .gffc-dash-table thead th { padding: 6px 6px; font-size: 10px; }
                        .gffc-dash-table tbody td { padding: 6px 6px; }
                        .gffc-dash-pname { font-size: 11px; }

                        /* Badges */
                        .gffc-dash-badge { font-size: 8px; padding: 1px 5px; }

                        /* Help modal — full-width on mobile */
                        .gffc-dash-help-modal { width: 95%; max-height: 85vh; border-radius: 8px; }
                        .gffc-dash-help-modal-header { padding: 12px 14px; }
                        .gffc-dash-help-modal-header h3 { font-size: 15px; }
                        .gffc-dash-help-modal-body { padding: 14px; font-size: 12px; }
                        .gffc-dash-help-modal-body table { font-size: 11px; }
                        .gffc-dash-help-modal-body table th, .gffc-dash-help-modal-body table td { padding: 5px 6px; }

                        /* Filter pills */
                        .gffc-dash-filter-pill { font-size: 11px; padding: 4px 6px 4px 10px; }

                    }
                </style>
                <div style="background: #f8f9fa; padding: 20px;">
                    <div class="gffc-dash" id="gffc-dash-main">

                        <!-- Loading -->
                        <div id="gffc-dash-loading" class="gffc-dash-loading">
                            <div class="gffc-dash-loading-logo"><img src="<?php echo plugin_dir_url(dirname(__FILE__)); ?>admin/images/ffl-cockpit-logo-nolines.svg" alt="FFL Cockpit"><span class="gffc-logo-sub">Analytics</span></div>
                            <div class="gffc-dash-load-progress">
                                <div class="gffc-dash-load-progress-bar">
                                    <div id="gffc-dash-load-progress-fill" class="gffc-dash-load-progress-fill"></div>
                                </div>
                                <div id="gffc-dash-load-progress-text" class="gffc-dash-load-progress-text">Loading dashboard data...</div>
                            </div>
                        </div>

                        <!-- Content (hidden until loaded) -->
                        <div id="gffc-dash-content" style="display:none;">

                            <!-- Beta Notice -->
                            <div style="background: rgba(0,254,72,0.12); border: 1px solid rgba(0,254,72,0.4); border-radius: 8px; padding: 12px 16px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 10px;">
                                <i class="fas fa-flask" style="color: #333; margin-top: 2px;"></i>
                                <div style="font-size: 13px; color: #333; line-height: 1.5;">
                                    <strong>Analytics is currently in beta.</strong> We're actively improving this section &mdash; you may encounter occasional quirks or incomplete data as we refine the experience. Your feedback helps us make it better!
                                </div>
                            </div>

                            <!-- Header -->
                            <div class="gffc-dash-header">
                                <div class="gffc-dash-title">
                                    <i class="fas fa-chart-line" style="color:#4a90d9;"></i> Analytics
                                </div>
                                <div class="gffc-dash-controls">
                                    <div class="gffc-dash-toggle" id="gffc-dash-window-toggle">
                                        <button type="button" class="gffc-dash-toggle-btn active" data-window="7d">7 Day</button>
                                        <button type="button" class="gffc-dash-toggle-btn" data-window="30d">30 Day</button>
                                        <button type="button" class="gffc-dash-toggle-btn" data-window="60d">60 Day</button>
                                        <button type="button" class="gffc-dash-toggle-btn" data-window="90d">90 Day</button>
                                    </div>
                                    <span class="gffc-dash-asof" id="gffc-dash-asof"></span>
                                </div>
                            </div>

                            <!-- Global Filters -->
                            <div class="gffc-dash-filters" id="gffc-dash-filters">
                                <div class="gffc-dash-filter-group">
                                    <label><i class="fas fa-crosshairs"></i> Product Class</label>
                                    <div id="gffc-dash-class-toggles" class="gffc-dash-class-toggles"></div>
                                </div>
                                <div class="gffc-dash-filter-group">
                                    <label><i class="fas fa-layer-group"></i> Category</label>
                                    <div id="gffc-dash-cat-toggles" class="gffc-dash-cat-toggles"></div>
                                </div>
                            </div>
                            <div class="gffc-dash-active-filters" id="gffc-dash-active-filters"></div>

                            <!-- Top Products by Movement -->
                            <div class="gffc-dash-widget">
                                <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-trophy"></i> Top Products by Movement</h3><div class="gffc-dash-widget-desc">Products ranked by movement score in the selected time window</div></div><button type="button" class="gffc-dash-help-btn" data-help="top-products" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                <div class="gffc-dash-widget-body" id="gffc-dash-top-products"><div class="gffc-dash-empty">No data</div></div>
                            </div>

                            <!-- Trending | On Sale -->
                            <div class="gffc-dash-row">
                                <div class="gffc-dash-col">
                                    <div class="gffc-dash-widget">
                                        <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-fire"></i> Trending Products</h3><div class="gffc-dash-widget-desc">Products accelerating in movement vs. their 30-day average &mdash; higher ratio = faster recent sales</div></div><button type="button" class="gffc-dash-help-btn" data-help="trending" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                        <div class="gffc-dash-widget-body" id="gffc-dash-trending"><div class="gffc-dash-empty">No data</div></div>
                                    </div>
                                </div>
                                <div class="gffc-dash-col">
                                    <div class="gffc-dash-widget">
                                        <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-tags"></i> On Sale</h3><div class="gffc-dash-widget-desc">Products with meaningful price drops from their reference price</div></div><button type="button" class="gffc-dash-help-btn" data-help="on-sale" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                        <div class="gffc-dash-widget-body" id="gffc-dash-on-sale"><div class="gffc-dash-empty">No data</div></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Price Gaps -->
                            <div class="gffc-dash-widget">
                                <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-balance-scale"></i> Largest Price Gaps</h3><div class="gffc-dash-widget-desc">Products priced significantly lower than the average across other distributors &mdash; potential buying opportunities</div></div><button type="button" class="gffc-dash-help-btn" data-help="price-gaps" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                <div class="gffc-dash-widget-body" id="gffc-dash-price-gaps"><div class="gffc-dash-empty">No data</div></div>
                            </div>

                            <!-- New Arrivals | Back in Stock -->
                            <div class="gffc-dash-row">
                                <div class="gffc-dash-col">
                                    <div class="gffc-dash-widget">
                                        <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-star"></i> New Arrivals</h3><div class="gffc-dash-widget-desc">Products first seen by distributors in the selected window</div></div><button type="button" class="gffc-dash-help-btn" data-help="new-arrivals" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                        <div class="gffc-dash-widget-body" id="gffc-dash-new-arrivals"><div class="gffc-dash-empty">No data</div></div>
                                    </div>
                                </div>
                                <div class="gffc-dash-col">
                                    <div class="gffc-dash-widget">
                                        <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-undo"></i> Back in Stock</h3><div class="gffc-dash-widget-desc">Previously out-of-stock products that are now available again</div></div><button type="button" class="gffc-dash-help-btn" data-help="back-in-stock" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                        <div class="gffc-dash-widget-body" id="gffc-dash-back-in-stock"><div class="gffc-dash-empty">No data</div></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Margin Opportunities -->
                            <div class="gffc-dash-widget">
                                <div class="gffc-dash-widget-header"><div><h3><i class="fas fa-dollar-sign"></i> Margin Opportunities</h3><div class="gffc-dash-widget-desc">Best profit opportunities sorted by gross profit &mdash; confidence score reflects data quality</div></div><button type="button" class="gffc-dash-help-btn" data-help="margin" title="How this works"><i class="fas fa-info-circle"></i> How is this calculated?</button></div>
                                <div class="gffc-dash-widget-body" id="gffc-dash-margin"><div class="gffc-dash-empty">No data</div></div>
                            </div>

                        </div><!-- /gffc-dash-content -->

                        <!-- Help Modal -->
                        <div class="gffc-dash-help-overlay" id="gffc-dash-help-overlay">
                            <div class="gffc-dash-help-modal">
                                <div class="gffc-dash-help-modal-header">
                                    <h3 id="gffc-dash-help-title"></h3>
                                    <button type="button" class="gffc-dash-help-modal-close" id="gffc-dash-help-close">&times;</button>
                                </div>
                                <div class="gffc-dash-help-modal-body" id="gffc-dash-help-body"></div>
                            </div>
                        </div>

                    </div><!-- /gffc-dash -->
                </div>

                <script>
                (function() {
                    /* ── Dashboard State ── */
                    var _loaded = false;
                    var _window = '7d';
                    var _data = {};
                    var _selectedClasses = [];
                    var _selectedCategories = [];
                    var _filtersInitialized = false;
                    var _suppressFilterRefresh = false;
                    var _productClassMap = {}; // code → description, e.g. { "FI": "Firearms" }
                    var _knownCategories = {}; // id → name, accumulates across all refreshes
                    var _lastClassForCats = null; // tracks which class the category list was built for
                    var _blockPages = {
                        topProducts: 1,
                        trending: 1,
                        onSale: 1,
                        margin: 1,
                        priceGaps: 1,
                        newArrivals: 1,
                        backInStock: 1
                    };

                    /* ── Help Content ── */
                    var _helpContent = {
                        'top-products': {
                            title: 'Top Products by Movement',
                            body: '<p>This section ranks products by their <strong>Movement Score</strong> &mdash; a composite metric that measures overall market activity by analyzing distributor inventory data feeds.</p>'
                                + '<div class="gffc-help-note">All metrics are derived from distributor data feeds only. We track inventory changes across distributors to infer product demand &mdash; no point-of-sale data is used.</div>'
                                + '<p><strong>How Movement Score works:</strong></p>'
                                + '<table><tr><th>Factor</th><th>Weight</th><th>What It Measures</th></tr>'
                                + '<tr><td>Sales Volume</td><td>60%</td><td>Total estimated units sold in the last 30 days (log-scaled to prevent a single runaway product from dominating)</td></tr>'
                                + '<tr><td>Frequency</td><td>25%</td><td>How many of the last 30 days had activity &mdash; rewards consistent daily demand over one-time spikes</td></tr>'
                                + '<tr><td>Recency</td><td>15%</td><td>How recently the product moved &mdash; products active today score highest, fading to zero after 30 days of inactivity</td></tr></table>'
                                + '<p><strong>Column definitions:</strong></p>'
                                + '<table><tr><th>Column</th><th>Meaning</th></tr>'
                                + '<tr><td>Movement</td><td>Average daily Movement Score across the selected time window</td></tr>'
                                + '<tr><td>Avg Cost</td><td>Average dealer acquisition cost from distributors</td></tr>'
                                + '<tr><td>Qty</td><td>Last known quantity in stock across distributors</td></tr></table>'
                                + '<p>Use the time window toggles (7 / 30 / 60 / 90 Day) to change the analysis period. A higher Movement Score means stronger, more consistent market demand.</p>'
                        },
                        'trending': {
                            title: 'Trending Products',
                            body: '<p>Trending identifies products that are <strong>accelerating</strong> &mdash; selling faster recently compared to their longer-term average.</p>'
                                + '<div class="gffc-help-note">All metrics are derived from distributor data feeds only. We track inventory changes across distributors to infer product demand.</div>'
                                + '<p><strong>Trend Ratio</strong> = Recent daily average &divide; 30-day daily average</p>'
                                + '<table><tr><th>Ratio</th><th>Meaning</th></tr>'
                                + '<tr><td>2.0</td><td>Selling at <strong>double</strong> the normal rate</td></tr>'
                                + '<tr><td>1.5</td><td>50% faster than normal</td></tr>'
                                + '<tr><td>1.0</td><td>Stable &mdash; same pace as usual</td></tr>'
                                + '<tr><td>0.5</td><td>Slowing down &mdash; half the normal rate</td></tr></table>'
                                + '<p>Products are ranked by trend ratio (highest first). This helps you spot emerging demand before it becomes obvious in the top sellers list.</p>'
                                + '<p><strong>Tip:</strong> A product with a moderate movement score but a high trend ratio may be worth stocking &mdash; it\'s picking up steam.</p>'
                        },
                        'on-sale': {
                            title: 'On Sale &mdash; Price Drop Detection',
                            body: '<p>This section detects <strong>meaningful price drops</strong> by comparing each product\'s current price to its recent baseline.</p>'
                                + '<div class="gffc-help-note">Prices are sourced from distributor data feeds. The reference price is the median dealer cost over the trailing 30 days &mdash; this filters out one-day pricing errors.</div>'
                                + '<p><strong>How a "sale" is identified:</strong></p>'
                                + '<table><tr><th>Metric</th><th>What It Means</th></tr>'
                                + '<tr><td>Reference Price</td><td>The 30-day median (typical) dealer cost &mdash; represents the "normal" price</td></tr>'
                                + '<tr><td>Current Price</td><td>The most recent dealer cost observed (within the last 7 days)</td></tr>'
                                + '<tr><td>Drop %</td><td>How far the current price has fallen below the reference price (e.g., 12.5% off)</td></tr>'
                                + '<tr><td>Drop $</td><td>The dollar amount of the price reduction</td></tr></table>'
                                + '<p>A product is flagged as <strong>on sale</strong> only when the price drop is at least <strong>5%</strong> and at least <strong>$10</strong> &mdash; this filters out insignificant fluctuations.</p>'
                                + '<p>Products are ranked by the largest percentage drop first. A "30-day low" badge means the current price is the lowest seen in the past month.</p>'
                        },
                        'margin': {
                            title: 'Margin Opportunities',
                            body: '<p>This section estimates <strong>profit potential</strong> for each product by comparing your dealer cost to estimated retail selling prices.</p>'
                                + '<div class="gffc-help-note">Cost data comes from distributor data feeds. Selling prices are estimated from MAP (Minimum Advertised Price) or MSRP when MAP is unavailable. Actual margins will vary based on your selling price.</div>'
                                + '<p><strong>How margins are calculated:</strong></p>'
                                + '<table><tr><th>Metric</th><th>How It\'s Determined</th></tr>'
                                + '<tr><td>Cost</td><td>Latest average dealer cost from distributor feeds</td></tr>'
                                + '<tr><td>Sell Price</td><td>MAP price if available; otherwise MSRP &times; 0.95 as an estimate</td></tr>'
                                + '<tr><td>Fees</td><td>Estimated marketplace/transaction fees ($15 per unit)</td></tr>'
                                + '<tr><td>Shipping</td><td>Estimated shipping cost ($12 per unit)</td></tr>'
                                + '<tr><td>Gross Profit</td><td>Sell Price &minus; Cost &minus; Fees &minus; Shipping</td></tr>'
                                + '<tr><td>Margin %</td><td>Gross Profit &divide; Sell Price (e.g., 30% means $0.30 profit per $1 of sales)</td></tr></table>'
                                + '<p><strong>Confidence Score</strong> (0&ndash;100) indicates how reliable the estimate is:</p>'
                                + '<table><tr><th>Factor</th><th>Points</th></tr>'
                                + '<tr><td>Product exists (valid UPC)</td><td>+20</td></tr>'
                                + '<tr><td>Has category data</td><td>+15</td></tr>'
                                + '<tr><td>Has MAP or MSRP pricing</td><td>+25</td></tr>'
                                + '<tr><td>Has cost data</td><td>+25</td></tr>'
                                + '<tr><td>Currently in stock</td><td>+15</td></tr></table>'
                                + '<p>Higher confidence = more trustworthy margin estimate. Products are ranked by gross profit (highest first).</p>'
                        },
                        'new-arrivals': {
                            title: 'New Arrivals',
                            body: '<p>Products that have <strong>appeared for the first time</strong> in distributor data feeds within the selected time window.</p>'
                                + '<div class="gffc-help-note">A "new arrival" means the product\'s UPC was never seen in any distributor feed before that date. This helps you discover products as soon as they enter the distribution channel.</div>'
                                + '<p><strong>What the badges mean:</strong></p>'
                                + '<table><tr><th>Badge</th><th>Meaning</th></tr>'
                                + '<tr><td>New (7d)</td><td>First appeared in the last 7 days &mdash; brand new to the market</td></tr>'
                                + '<tr><td>New (30d)</td><td>First appeared in the last 30 days</td></tr>'
                                + '<tr><td>First in Category</td><td>The first new product to appear in its category in the last 30 days &mdash; could signal a new product line</td></tr></table>'
                                + '<p>Products are sorted by newest first. Use this to stay ahead of your competition by identifying new products as soon as distributors begin carrying them.</p>'
                        },
                        'price-gaps': {
                            title: 'Largest Price Gaps',
                            body: '<p>This section finds products where one distributor\'s price is <strong>significantly lower</strong> than the average price across other distributors carrying the same product.</p>'
                                + '<div class="gffc-help-note">Prices are sourced from distributor data feeds. The peer average is calculated across all other distributors currently stocking the same UPC.</div>'
                                + '<p><strong>How a "price gap" is identified:</strong></p>'
                                + '<table><tr><th>Metric</th><th>What It Means</th></tr>'
                                + '<tr><td>Price</td><td>The current dealer cost from the lowest-priced distributor</td></tr>'
                                + '<tr><td>Peer Avg</td><td>The average dealer cost across all <em>other</em> distributors carrying this product</td></tr>'
                                + '<tr><td>Gap %</td><td>How far below the peer average this price falls (e.g., 18.6% below)</td></tr>'
                                + '<tr><td>Gap $</td><td>The dollar amount of the price difference</td></tr>'
                                + '<tr><td>Peers</td><td>Number of other distributors used in the comparison</td></tr></table>'
                                + '<p>A product is shown only when it is at least <strong>10% below</strong> the peer average and the gap is at least <strong>$20</strong>, with at least <strong>2 peer distributors</strong> for a reliable comparison.</p>'
                                + '<p>Large price gaps may indicate distributor promotions, closeouts, or pricing errors &mdash; all potential buying opportunities worth investigating.</p>'
                        },
                        'back-in-stock': {
                            title: 'Back in Stock',
                            body: '<p>Products that were <strong>previously out of stock</strong> but are now available again from distributors.</p>'
                                + '<div class="gffc-help-note">This is detected from distributor inventory feeds. A product qualifies if it had zero quantity for a period and has since been restocked.</div>'
                                + '<p><strong>How it works:</strong></p>'
                                + '<table><tr><th>Label</th><th>Meaning</th></tr>'
                                + '<tr><td>Back in Stock (7d)</td><td>Was out of stock 7&ndash;14 days ago, now has inventory &mdash; a recent restock</td></tr>'
                                + '<tr><td>Back in Stock (30d)</td><td>Was out of stock 30&ndash;60 days ago, now has inventory &mdash; longer gap before restocking</td></tr></table>'
                                + '<p>This is useful for identifying products that have been hard to get. If a popular item comes back in stock, it may be worth ordering before it sells out again.</p>'
                                + '<p>Products are sorted by most recently restocked first.</p>'
                        }
                    };

                    /* ── Help Modal Handlers ── */
                    (function() {
                        var overlay = document.getElementById('gffc-dash-help-overlay');
                        var titleEl = document.getElementById('gffc-dash-help-title');
                        var bodyEl = document.getElementById('gffc-dash-help-body');
                        var closeBtn = document.getElementById('gffc-dash-help-close');

                        // Open on help button click (delegated)
                        document.getElementById('gffc-dash-main').addEventListener('click', function(e) {
                            var btn = e.target.closest('.gffc-dash-help-btn');
                            if (!btn) return;
                            var key = btn.getAttribute('data-help');
                            var content = _helpContent[key];
                            if (!content) return;
                            titleEl.textContent = content.title;
                            bodyEl.innerHTML = content.body;
                            overlay.classList.add('open');
                        });

                        // Close on X button
                        closeBtn.addEventListener('click', function() {
                            overlay.classList.remove('open');
                        });

                        // Close on overlay background click
                        overlay.addEventListener('click', function(e) {
                            if (e.target === overlay) overlay.classList.remove('open');
                        });

                        // Close on Escape key
                        document.addEventListener('keydown', function(e) {
                            if (e.key === 'Escape' && overlay.classList.contains('open')) {
                                overlay.classList.remove('open');
                            }
                        });
                    })();

                    /* ── Helpers ── */
                    function esc(s) {
                        if (s == null) return '';
                        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
                    }
                    function trunc(s, n) {
                        if (!s) return '';
                        return s.length > n ? s.substring(0, n) + '...' : s;
                    }
                    function numOrNull(v) {
                        if (v == null || v === '') return null;
                        var n = Number(v);
                        return isNaN(n) ? null : n;
                    }
                    function getRowQty(row) {
                        var candidates = [
                            row.last_seen_qty,
                            row.qty_available,
                            row.qty_on_hand,
                            row.current_qty,
                            row.quantity_available,
                            row.qty
                        ];
                        for (var i = 0; i < candidates.length; i++) {
                            var n = numOrNull(candidates[i]);
                            if (n != null) return n;
                        }
                        return null;
                    }
                    function filterRowsInStock(rows) {
                        return rows;
                    }
                    function fmt$(v) {
                        if (v == null) return '&mdash;';
                        return '$' + Number(v).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                    }
                    function fmtPct(v, mult) {
                        if (v == null) return '&mdash;';
                        var n = mult ? v * 100 : v;
                        return n.toFixed(1) + '%';
                    }
                    function fmtNum(v) {
                        if (v == null) return '&mdash;';
                        return Number(v).toLocaleString();
                    }
                    function fmtScore(v) {
                        if (v == null) return '&mdash;';
                        return Number(v).toFixed(1);
                    }
                    function fmtDate(ts) {
                        if (!ts) return '';
                        var d = new Date(ts);
                        if (isNaN(d)) return ts;
                        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' });
                    }
                    function fmtDateShort(ts) {
                        if (!ts) return '&mdash;';
                        var d = new Date(ts);
                        if (isNaN(d)) return esc(ts);
                        return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                    }
                    function isTruthy(v) {
                        return v === 1 || v === true || v === '1' || v === 'true';
                    }
                    function badges(row, opts) {
                        opts = opts || {};
                        var h = '';
                        var isRestocked = isTruthy(row.newly_available_7d) || isTruthy(row.back_in_stock_7d) || isTruthy(row.newly_available_30d) || isTruthy(row.back_in_stock_30d);
                        if (opts.restockOnly || opts.context === 'backInStock') {
                            if (isRestocked) h += '<span class="gffc-dash-badge gffc-dash-badge-restock">RESTOCKED</span>';
                            return h;
                        }
                        if (isTruthy(row.is_new_7d)) h += '<span class="gffc-dash-badge gffc-dash-badge-new">NEW</span>';
                        else if (isTruthy(row.is_new_30d)) h += '<span class="gffc-dash-badge gffc-dash-badge-new30">NEW 30D</span>';
                        if (isTruthy(row.newly_available_7d)) h += '<span class="gffc-dash-badge gffc-dash-badge-restock">RESTOCKED</span>';
                        if (isTruthy(row.lowest_price_30d)) h += '<span class="gffc-dash-badge gffc-dash-badge-lowest">LOWEST PRICE</span>';
                        if (isTruthy(row.first_in_category_30d)) h += '<span class="gffc-dash-badge gffc-dash-badge-first-cat">1ST IN CATEGORY</span>';
                        return h;
                    }
                    function productCell(name, row, maxLen, badgeOpts) {
                        var upcAttr = row.upc ? ' data-upc="' + esc(row.upc) + '"' : '';
                        var label = maxLen ? trunc(name, maxLen) : name;
                        return '<span class="gffc-dash-pname"' + upcAttr + ' title="' + esc(name) + '">' + esc(label || '') + '</span> ' + badges(row, badgeOpts);
                    }
                    function updateDashboardLoadProgress(completed, total, message) {
                        var fill = document.getElementById('gffc-dash-load-progress-fill');
                        var text = document.getElementById('gffc-dash-load-progress-text');
                        if (!fill || !text) return;
                        var safeTotal = total > 0 ? total : 1;
                        var pct = Math.max(0, Math.min(100, Math.round((completed / safeTotal) * 100)));
                        fill.style.width = pct + '%';
                        text.textContent = (message || 'Loading dashboard data') + ' (' + completed + '/' + total + ', ' + pct + '%)';
                    }
                    function backInStockLabel(row) {
                        if (row.back_in_stock_label) return row.back_in_stock_label;
                        if (isTruthy(row.newly_available_7d) || isTruthy(row.back_in_stock_7d)) return 'Back in Stock (7d)';
                        if (isTruthy(row.newly_available_30d) || isTruthy(row.back_in_stock_30d)) return 'Back in Stock (30d)';
                        return 'Back in Stock';
                    }
                    function sortByNumericDesc(rows, field) {
                        return rows.slice().sort(function(a, b) {
                            var av = numOrNull(a[field]) || 0;
                            var bv = numOrNull(b[field]) || 0;
                            return bv - av;
                        });
                    }
                    function paginationControls(blockKey, page, totalPages, totalRows, pageSize) {
                        if (totalPages <= 1) return '';
                        var start = ((page - 1) * pageSize) + 1;
                        var end = Math.min(page * pageSize, totalRows);
                        return ''
                            + '<div class="gffc-dash-pagination">'
                            + '<div class="gffc-dash-pagination-info">Showing ' + start + '-' + end + ' of ' + totalRows + '</div>'
                            + '<div class="gffc-dash-pagination-buttons">'
                            + '<button type="button" class="gffc-dash-page-btn" data-block="' + esc(blockKey) + '" data-page-dir="prev"' + (page <= 1 ? ' disabled' : '') + '>Previous</button>'
                            + '<span class="gffc-dash-pagination-info">Page ' + page + ' of ' + totalPages + '</span>'
                            + '<button type="button" class="gffc-dash-page-btn" data-block="' + esc(blockKey) + '" data-page-dir="next"' + (page >= totalPages ? ' disabled' : '') + '>Next</button>'
                            + '</div>'
                            + '</div>';
                    }
                    function renderPaginatedBlock(el, blockKey, rows, pageSize, renderTableFn) {
                        var size = pageSize || 10;
                        var totalRows = rows.length;
                        var totalPages = Math.max(1, Math.ceil(totalRows / size));
                        if (!_blockPages[blockKey]) _blockPages[blockKey] = 1;
                        if (_blockPages[blockKey] > totalPages) _blockPages[blockKey] = totalPages;
                        var page = _blockPages[blockKey];
                        var start = (page - 1) * size;
                        var pageRows = rows.slice(start, start + size);
                        el.innerHTML = renderTableFn(pageRows, start, page) + paginationControls(blockKey, page, totalPages, totalRows, size);
                        attachColumnResizers(el.querySelector('table'));
                    }
                    function setColumnWidth(table, colIndex, px) {
                        var rows = table.querySelectorAll('tr');
                        rows.forEach(function(row) {
                            var cell = row.children[colIndex];
                            if (cell) {
                                cell.style.minWidth = px + 'px';
                                cell.style.width = px + 'px';
                            }
                        });
                    }
                    function attachColumnResizers(table) {
                        if (!table || table.dataset.resizable === '1') return;
                        table.dataset.resizable = '1';
                        var ths = table.querySelectorAll('thead th');
                        ths.forEach(function(th, idx) {
                            if (idx === ths.length - 1) return;
                            var handle = document.createElement('span');
                            handle.className = 'gffc-dash-col-resizer';
                            handle.addEventListener('mousedown', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                var startX = e.clientX;
                                var startW = th.getBoundingClientRect().width;
                                table.classList.add('gffc-dash-resizing');
                                function onMove(ev) {
                                    var nextW = Math.max(80, startW + (ev.clientX - startX));
                                    setColumnWidth(table, idx, nextW);
                                }
                                function onUp() {
                                    table.classList.remove('gffc-dash-resizing');
                                    document.removeEventListener('mousemove', onMove);
                                    document.removeEventListener('mouseup', onUp);
                                }
                                document.addEventListener('mousemove', onMove);
                                document.addEventListener('mouseup', onUp);
                            });
                            th.appendChild(handle);
                        });
                    }

                    /* ── API Fetch ── */
                    async function apiFetch(action, params) {
                        var resp = await fetch('https://ffl-api.garidium.com', {
                            method: 'POST',
                            headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'x-api-key': '<?php echo esc_attr($gFFLCockpitKey); ?>'
                            },
                            body: JSON.stringify({ action: action, data: params })
                        });
                        if (!resp.ok) throw new Error('API ' + resp.status);
                        return resp.json();
                    }

                    /* ── Fetch product class names (code → description map) ── */
                    async function fetchProductClassMap() {
                        try {
                            var data = await apiFetch('get_product_classes', { api_key: '<?php echo esc_attr($gFFLCockpitKey); ?>' });
                            var list = data.product_classes || data || [];
                            if (Array.isArray(list)) {
                                list.forEach(function(pc) {
                                    if (pc.product_class && pc.description) {
                                        _productClassMap[pc.product_class] = pc.description;
                                    }
                                });
                            }
                        } catch (e) {
                            console.warn('Could not load product class names:', e);
                        }
                    }

                    function productClassName(code) {
                        return _productClassMap[code] || code;
                    }

                    /* ── Load (called once on tab click) ── */
                    window.loadDashboard = async function() {
                        if (_loaded) return;
                        _loaded = true;
                        await fetchProductClassMap();
                        gffcDashRefresh();
                    };

                    /* ── Build params with active filters ── */
                    function buildParams(extra) {
                        var p = extra || {};
                        p.api_key = '<?php echo esc_attr($gFFLCockpitKey); ?>';
                        if (!p.window) p.window = _window;
                        if (_selectedClasses.length) p.product_class = _selectedClasses.join(',');
                        if (_selectedCategories.length) p.category_id = _selectedCategories.join(',');
                        return p;
                    }

                    /* ── Refresh ── */
                    window.gffcDashRefresh = async function() {
                        try {
                            Object.keys(_blockPages).forEach(function(k) { _blockPages[k] = 1; });
                            var loadingEl = document.getElementById('gffc-dash-loading');
                            var contentEl = document.getElementById('gffc-dash-content');
                            if (loadingEl) loadingEl.style.display = 'block';
                            if (contentEl) contentEl.style.display = 'none';

                            var requests = [
                                { key: 'topProducts', label: 'Top Products', promise: apiFetch('dashboard_top_products', buildParams({ limit: '50' })) },
                                { key: 'onSale', label: 'On Sale', promise: apiFetch('dashboard_on_sale', buildParams({ limit: '50' })) },
                                { key: 'margin', label: 'Margin Opportunities', promise: apiFetch('dashboard_margin_opportunities', buildParams({ limit: '50', min_confidence: '50', sort_by: 'gross_profit' })) },
                                { key: 'trending', label: 'Trending', promise: apiFetch('dashboard_trending', buildParams({ limit: '50' })) },
                                { key: 'priceGaps', label: 'Price Gaps', promise: apiFetch('dashboard_price_gaps', buildParams({ limit: '50' })) },
                                { key: 'newArrivals', label: 'New Arrivals', promise: apiFetch('dashboard_new_arrivals', buildParams({ limit: '50' })) },
                                { key: 'backInStock', label: 'Back in Stock', promise: apiFetch('dashboard_newly_available', buildParams({ limit: '50' })) }
                            ];
                            var totalRequests = requests.length;
                            var completedRequests = 0;
                            updateDashboardLoadProgress(0, totalRequests, 'Fetching analytics');

                            var wrappedPromises = requests.map(function(req) {
                                return req.promise
                                    .then(function(value) {
                                        completedRequests += 1;
                                        updateDashboardLoadProgress(completedRequests, totalRequests, 'Loaded ' + req.label);
                                        return { key: req.key, status: 'fulfilled', value: value };
                                    })
                                    .catch(function(reason) {
                                        completedRequests += 1;
                                        updateDashboardLoadProgress(completedRequests, totalRequests, 'Loaded ' + req.label);
                                        return { key: req.key, status: 'rejected', reason: reason };
                                    });
                            });
                            var results = await Promise.all(wrappedPromises);

                            results.forEach(function(r) {
                                _data[r.key] = r.status === 'fulfilled' ? r.value : null;
                            });

                            // Show content first so GridJS/Select2 can measure container dimensions
                            updateDashboardLoadProgress(totalRequests, totalRequests, 'Rendering dashboard');
                            if (loadingEl) loadingEl.style.display = 'none';
                            if (contentEl) contentEl.style.display = 'block';

                            // as_of timestamp
                            var asOf = (_data.topProducts && _data.topProducts.as_of) || (_data.trending && _data.trending.as_of) || '';
                            if (asOf) {
                                document.getElementById('gffc-dash-asof').textContent = 'Data as of ' + fmtDate(asOf);
                            }

                            // Populate filter dropdowns (only on first load or if uninitialized)
                            populateFilterDropdowns();

                            // Render active filter pills
                            renderActiveFilters();

                            // Render each widget with isolated error handling
                            var renders = [
                                ['Top Products', renderTopProducts],
                                ['Trending', renderTrending],
                                ['On Sale', renderOnSale],
                                ['Margin', renderMargin],
                                ['Price Gaps', renderPriceGaps],
                                ['New Arrivals', renderNewArrivals],
                                ['Back in Stock', renderBackInStock]
                            ];
                            renders.forEach(function(r) {
                                try { r[1](); } catch(err) { console.error('Dashboard render error [' + r[0] + ']:', err); }
                            });

                        } catch(e) {
                            console.error('Dashboard fetch error:', e);
                            document.getElementById('gffc-dash-loading').innerHTML = '<div class="gffc-dash-error"><i class="fas fa-exclamation-triangle"></i> Failed to load dashboard data. Check the browser console for details.</div>';
                        }
                    };

                    /* ── Window Toggle (event delegation) ── */
                    jQuery(document).on('click', '#gffc-dash-window-toggle .gffc-dash-toggle-btn', function() {
                        var w = jQuery(this).attr('data-window');
                        if (w === _window) return;
                        _window = w;
                        jQuery('#gffc-dash-window-toggle .gffc-dash-toggle-btn').removeClass('active');
                        jQuery(this).addClass('active');
                        gffcDashRefresh();
                    });

                    /* ── Global Filter Dropdowns ── */
                    function populateFilterDropdowns() {
                        // Collect distinct product_class values and accumulate categories
                        var classes = {};
                        var classCats = {}; // categories visible for the current class filter
                        var classFilter = _selectedClasses.length ? {} : null;
                        if (classFilter) _selectedClasses.forEach(function(c) { classFilter[c] = true; });

                        ['topProducts','onSale','margin','priceGaps','trending','newArrivals','backInStock'].forEach(function(key) {
                            var d = _data[key];
                            if (d && d.results) {
                                d.results.forEach(function(r) {
                                    var pc = r.product_class || r.productClass || r.product_type || '';
                                    if (pc) classes[pc] = pc;
                                    // Always accumulate into master category list
                                    if (r.category_id && r.category_name) {
                                        _knownCategories[r.category_id] = r.category_name;
                                        // Track which categories match the current class filter
                                        if (!classFilter || (pc && classFilter[pc])) {
                                            classCats[r.category_id] = r.category_name;
                                        }
                                    }
                                });
                            }
                        });
                        // Use class-filtered categories if a class is selected, otherwise show all known
                        var cats = classFilter ? classCats : _knownCategories;

                        // Also include any classes from the product class map that aren't in the data
                        Object.keys(_productClassMap).forEach(function(code) {
                            if (!classes[code]) classes[code] = code;
                        });

                        // Product Class toggles — hide the filter group if no classes found
                        var clsContainer = jQuery('#gffc-dash-class-toggles');
                        var clsGroup = clsContainer.closest('.gffc-dash-filter-group');
                        var classKeys = Object.keys(classes).sort(function(a, b) {
                            return productClassName(a).localeCompare(productClassName(b));
                        });
                        if (!classKeys.length) {
                            clsGroup.hide();
                        } else {
                            clsGroup.show();
                            clsContainer.empty();
                            classKeys.forEach(function(c) {
                                var label = _productClassMap[c] ? _productClassMap[c] : c;
                                var isActive = _selectedClasses.indexOf(c) !== -1;
                                clsContainer.append('<button type="button" class="gffc-dash-class-toggle-btn' + (isActive ? ' active' : '') + '" data-class="' + esc(c) + '">' + esc(label) + '</button>');
                            });
                        }

                        // Category toggles — only rebuild when the product class selection changes
                        var classKey = _selectedClasses.join(',');
                        var catContainer = jQuery('#gffc-dash-cat-toggles');
                        var catGroup = catContainer.closest('.gffc-dash-filter-group');
                        if (classKey !== _lastClassForCats) {
                            _lastClassForCats = classKey;
                            var catKeys = Object.keys(cats).sort(function(a, b) { return cats[a].localeCompare(cats[b]); });
                            if (!catKeys.length) {
                                catGroup.hide();
                            } else {
                                catGroup.show();
                                catContainer.empty();
                                catKeys.forEach(function(id) {
                                    var isActive = _selectedCategories.indexOf(id) !== -1;
                                    catContainer.append('<button type="button" class="gffc-dash-cat-toggle-btn' + (isActive ? ' active' : '') + '" data-cat="' + esc(id) + '">' + esc(cats[id]) + '</button>');
                                });
                                // Prune selected categories that no longer exist in the new class
                                var validPrev = _selectedCategories.filter(function(id) { return cats.hasOwnProperty(id); });
                                if (validPrev.length !== _selectedCategories.length) {
                                    _selectedCategories = validPrev;
                                }
                            }
                        }

                        // Init filters once
                        if (!_filtersInitialized) {
                            _filtersInitialized = true;

                            // Toggle click handler for product class buttons (single-select)
                            jQuery('#gffc-dash-class-toggles').on('click', '.gffc-dash-class-toggle-btn', function() {
                                var wasActive = jQuery(this).hasClass('active');
                                jQuery('#gffc-dash-class-toggles .gffc-dash-class-toggle-btn').removeClass('active');
                                if (!wasActive) {
                                    jQuery(this).addClass('active');
                                    _selectedClasses = [jQuery(this).attr('data-class')];
                                    // Class selection changes the category universe; clear category filters.
                                    _selectedCategories = [];
                                    jQuery('#gffc-dash-cat-toggles .gffc-dash-cat-toggle-btn').removeClass('active');
                                } else {
                                    _selectedClasses = [];
                                }
                                if (!_suppressFilterRefresh) gffcDashRefresh();
                            });

                            // Toggle click handler for category buttons (multi-select)
                            jQuery('#gffc-dash-cat-toggles').on('click', '.gffc-dash-cat-toggle-btn', function() {
                                jQuery(this).toggleClass('active');
                                _selectedCategories = [];
                                jQuery('#gffc-dash-cat-toggles .gffc-dash-cat-toggle-btn.active').each(function() {
                                    _selectedCategories.push(jQuery(this).attr('data-cat'));
                                });
                                if (!_suppressFilterRefresh) gffcDashRefresh();
                            });

                        }
                    }

                    /* ── Active Filter Pills ── */
                    function renderActiveFilters() {
                        var container = document.getElementById('gffc-dash-active-filters');
                        var html = '';

                        if (_selectedClasses.length) {
                            html += '<span class="gffc-dash-filter-pill"><span class="gffc-dash-filter-pill-label">Class:</span> ';
                            _selectedClasses.forEach(function(c, i) {
                                if (i > 0) html += ', ';
                                html += esc(productClassName(c));
                            });
                            html += ' <button class="gffc-dash-filter-pill-remove" data-filter="class" title="Clear product class filter">&times;</button></span>';
                        }

                        if (_selectedCategories.length) {
                            // Resolve category names from the toggle buttons
                            var names = [];
                            _selectedCategories.forEach(function(id) {
                                var btn = document.querySelector('#gffc-dash-cat-toggles .gffc-dash-cat-toggle-btn[data-cat="' + id + '"]');
                                names.push(btn ? btn.textContent : id);
                            });
                            html += '<span class="gffc-dash-filter-pill"><span class="gffc-dash-filter-pill-label">Category:</span> ';
                            html += esc(names.join(', '));
                            html += ' <button class="gffc-dash-filter-pill-remove" data-filter="category" title="Clear category filter">&times;</button></span>';
                        }
                        container.innerHTML = html;
                    }

                    // Pill remove click handler
                    document.getElementById('gffc-dash-active-filters').addEventListener('click', function(e) {
                        var btn = e.target.closest('.gffc-dash-filter-pill-remove');
                        if (!btn) return;
                        var which = btn.getAttribute('data-filter');
                        if (which === 'class') {
                            _selectedClasses = [];
                            jQuery('#gffc-dash-class-toggles .gffc-dash-class-toggle-btn').removeClass('active');
                        } else if (which === 'category') {
                            _selectedCategories = [];
                            jQuery('#gffc-dash-cat-toggles .gffc-dash-cat-toggle-btn').removeClass('active');
                        }
                        gffcDashRefresh();
                    });

                    /* ── Top Products ── */
                    function renderTopProducts() {
                        var el = document.getElementById('gffc-dash-top-products');
                        var d = _data.topProducts;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No product data available</div>'; return; }
                        var rows = sortByNumericDesc(filterRowsInStock(d.results), 'avg_movement_score');
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No product data available</div>'; return; }
                        renderPaginatedBlock(el, 'topProducts', rows, 10, function(pageRows, startIndex) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>#</th><th>Product</th><th>Manufacturer</th><th>Category</th><th class="gffc-dash-num">Movement</th><th class="gffc-dash-num">Avg Cost</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r, i) {
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + (startIndex + i + 1) + '</td><td>' + productCell(r.name, r) + '</td><td>' + esc(r.mfg_name || '') + '</td><td>' + esc(r.category_name || '') + '</td><td class="gffc-dash-num"><strong>' + fmtScore(r.avg_movement_score) + '</strong></td><td class="gffc-dash-num">' + fmt$(r.avg_cost) + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── Trending ── */
                    function renderTrending() {
                        var el = document.getElementById('gffc-dash-trending');
                        var d = _data.trending;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No trending data</div>'; return; }
                        var rows = sortByNumericDesc(filterRowsInStock(d.results), 'trend_ratio');
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No trending data</div>'; return; }
                        renderPaginatedBlock(el, 'trending', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th>Trend</th><th class="gffc-dash-num">7d</th><th class="gffc-dash-num">30d</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                var ratio = Number(r.trend_ratio) || 0;
                                var cls = ratio >= 1 ? 'gffc-dash-trend-up' : 'gffc-dash-trend-down';
                                var arrow = ratio >= 1 ? '<i class="fas fa-arrow-up"></i>' : '<i class="fas fa-arrow-down"></i>';
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r) + '</td><td><span class="' + cls + ' gffc-dash-trend-nowrap">' + arrow + ratio.toFixed(1) + 'x</span></td><td class="gffc-dash-num">' + fmtNum(r.movement_7d) + '</td><td class="gffc-dash-num">' + fmtNum(r.movement_30d) + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── On Sale ── */
                    function renderOnSale() {
                        var el = document.getElementById('gffc-dash-on-sale');
                        var d = _data.onSale;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No sale data</div>'; return; }
                        var rows = sortByNumericDesc(filterRowsInStock(d.results), 'drop_pct');
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No sale data</div>'; return; }
                        renderPaginatedBlock(el, 'onSale', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th class="gffc-dash-num">Price</th><th class="gffc-dash-num">Off %</th><th class="gffc-dash-num">Off $</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                var ref = numOrNull(r.ref_price) || 0;
                                var cur = numOrNull(r.current_price) || 0;
                                var offDollar = (ref > 0 && cur > 0) ? Math.max(0, ref - cur) : null;
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r) + '</td><td class="gffc-dash-num"><span class="gffc-dash-price-stack"><span class="gffc-dash-price-was">' + fmt$(r.ref_price) + '</span><span class="gffc-dash-price-now">' + fmt$(r.current_price) + '</span></span></td><td class="gffc-dash-num"><span class="gffc-dash-discount-good"><i class="fas fa-arrow-down" style="font-size:10px;"></i>' + fmtPct(r.drop_pct, true) + '</span></td><td class="gffc-dash-num"><span class="gffc-dash-discount-good">' + fmt$(offDollar) + '</span></td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── Margin Opportunities ── */
                    function renderMargin() {
                        var el = document.getElementById('gffc-dash-margin');
                        var d = _data.margin;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No margin data</div>'; return; }
                        var rows = sortByNumericDesc(filterRowsInStock(d.results), 'gross_profit');
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No margin data</div>'; return; }
                        renderPaginatedBlock(el, 'margin', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th class="gffc-dash-num">Cost</th><th class="gffc-dash-num">Sell</th><th class="gffc-dash-num">Profit</th><th class="gffc-dash-num">Margin</th><th>Confidence</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                var conf = r.confidence_score || 0;
                                var cc = conf >= 80 ? '#28a745' : conf >= 50 ? '#ffc107' : '#dc3545';
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r) + '</td><td class="gffc-dash-num">' + fmt$(r.cost_basis) + '</td><td class="gffc-dash-num">' + fmt$(r.sell_price) + '</td><td class="gffc-dash-num"><span class="gffc-dash-profit">' + fmt$(r.gross_profit) + '</span></td><td class="gffc-dash-num">' + fmtPct(r.gross_margin_pct, true) + '</td><td><span class="gffc-dash-conf-bar"><span class="gffc-dash-conf-fill" style="width:' + conf + '%;background:' + cc + ';"></span></span> ' + Math.round(conf) + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── Price Gaps ── */
                    function renderPriceGaps() {
                        var el = document.getElementById('gffc-dash-price-gaps');
                        var d = _data.priceGaps;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No price gap data</div>'; return; }
                        var rows = sortByNumericDesc(filterRowsInStock(d.results), 'peer_gap_pct');
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No price gap data</div>'; return; }
                        renderPaginatedBlock(el, 'priceGaps', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th class="gffc-dash-num">Price</th><th class="gffc-dash-num">Peer Avg</th><th class="gffc-dash-num">Gap %</th><th class="gffc-dash-num">Gap $</th><th class="gffc-dash-num">Peers</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                var gapPct = numOrNull(r.peer_gap_pct) || 0;
                                var gapAbs = numOrNull(r.peer_gap_abs) || 0;
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r) + '</td><td class="gffc-dash-num">' + fmt$(r.current_price) + '</td><td class="gffc-dash-num">' + fmt$(r.peer_avg_price) + '</td><td class="gffc-dash-num"><span class="gffc-dash-discount-good"><i class="fas fa-arrow-down" style="font-size:10px;"></i>' + fmtPct(gapPct, true) + '</span></td><td class="gffc-dash-num"><span class="gffc-dash-discount-good">' + fmt$(gapAbs) + '</span></td><td class="gffc-dash-num">' + fmtNum(r.peer_count) + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── New Arrivals ── */
                    function renderNewArrivals() {
                        var el = document.getElementById('gffc-dash-new-arrivals');
                        var d = _data.newArrivals;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No new arrivals</div>'; return; }
                        var rows = filterRowsInStock(d.results).slice().sort(function(a, b) {
                            return (new Date(b.first_seen_ts || 0)).getTime() - (new Date(a.first_seen_ts || 0)).getTime();
                        });
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No new arrivals</div>'; return; }
                        renderPaginatedBlock(el, 'newArrivals', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th>Category</th><th>First Seen</th><th class="gffc-dash-num">Days</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r) + '</td><td>' + esc(r.category_name || '') + '</td><td>' + fmtDateShort(r.first_seen_ts) + '</td><td class="gffc-dash-num">' + (r.days_since_first_seen != null ? r.days_since_first_seen : '&mdash;') + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── Back in Stock ── */
                    function renderBackInStock() {
                        var el = document.getElementById('gffc-dash-back-in-stock');
                        var d = _data.backInStock;
                        if (!d || !d.results || !d.results.length) { el.innerHTML = '<div class="gffc-dash-empty">No restocked products</div>'; return; }
                        var rows = filterRowsInStock(d.results).slice().sort(function(a, b) {
                            var aPriority = backInStockLabel(a) === 'Back in Stock (7d)' ? 2 : backInStockLabel(a) === 'Back in Stock (30d)' ? 1 : 0;
                            var bPriority = backInStockLabel(b) === 'Back in Stock (7d)' ? 2 : backInStockLabel(b) === 'Back in Stock (30d)' ? 1 : 0;
                            return bPriority - aPriority;
                        });
                        if (!rows.length) { el.innerHTML = '<div class="gffc-dash-empty">No restocked products</div>'; return; }
                        renderPaginatedBlock(el, 'backInStock', rows, 10, function(pageRows) {
                            var h = '<table class="gffc-dash-table"><thead><tr><th>Product</th><th>Status</th><th>Category</th><th class="gffc-dash-num">Avg Cost</th><th class="gffc-dash-num">Qty</th></tr></thead><tbody>';
                            pageRows.forEach(function(r) {
                                h += '<tr data-upc="' + esc(r.upc) + '"><td>' + productCell(r.name, r, null, { context: "backInStock", restockOnly: true }) + '</td><td>' + esc(backInStockLabel(r)) + '</td><td>' + esc(r.category_name || '') + '</td><td class="gffc-dash-num">' + fmt$(r.avg_cost) + '</td><td class="gffc-dash-num">' + fmtNum(getRowQty(r)) + '</td></tr>';
                            });
                            h += '</tbody></table>';
                            return h;
                        });
                    }

                    /* ── Click-to-Search: UPC lookup in Product Search tab ── */
                    function gffcDashSearchUPC(upc) {
                        if (!upc) return;
                        // Switch to Product Search tab
                        var tab = document.querySelector('#cockpit_main_tab_control button[onclick*="product_feed"]');
                        if (tab) {
                            if (typeof window.openTab === 'function') {
                                window.openTab({ currentTarget: tab, preventDefault: function(){} }, 'product_feed');
                            } else {
                                tab.click();
                            }
                        }
                        // Ensure Ignore Restrictions and In Stock toggles are OFF
                        var ignoreToggle = document.getElementById('ignore-product-restrictions-toggle');
                        var inStockToggle = document.getElementById('gffc-in-stock-toggle');
                        if (ignoreToggle) { ignoreToggle.checked = true; gffcSetCookie('gffc_ignore_restrictions', '1', 365); }
                        if (inStockToggle) { inStockToggle.checked = false; gffcSetCookie('gffc_in_stock', '0', 365); }

                        // Trigger the existing UPC search
                        if (typeof window.searchByUPC === 'function') {
                            searchByUPC(upc);
                        } else {
                            var input = document.getElementById('cockpit-product-search-input');
                            if (input) { input.value = upc; }
                            if (typeof window.loadGrid === 'function') loadGrid();
                        }
                    }

                    // Event delegation: click any row with data-upc to search
                    document.getElementById('gffc-dash-main').addEventListener('click', function(e) {
                        var pagerBtn = e.target.closest('.gffc-dash-page-btn');
                        if (pagerBtn) {
                            var block = pagerBtn.getAttribute('data-block');
                            var dir = pagerBtn.getAttribute('data-page-dir');
                            if (_blockPages[block] == null) _blockPages[block] = 1;
                            _blockPages[block] = Math.max(1, _blockPages[block] + (dir === 'next' ? 1 : -1));
                            if (block === 'topProducts') renderTopProducts();
                            else if (block === 'trending') renderTrending();
                            else if (block === 'onSale') renderOnSale();
                            else if (block === 'margin') renderMargin();
                            else if (block === 'priceGaps') renderPriceGaps();
                            else if (block === 'newArrivals') renderNewArrivals();
                            else if (block === 'backInStock') renderBackInStock();
                            return;
                        }
                        var target = e.target.closest('[data-upc]');
                        if (target) {
                            gffcDashSearchUPC(target.getAttribute('data-upc'));
                        }
                    });

                })();
                </script>
            </div>
            <?php if (!(function_exists('g_ffl_is_fflcockpit_multisite_domain') && g_ffl_is_fflcockpit_multisite_domain())) : ?>
            <button class="accordion">Logs</button>
            <div id="logs" class="tabcontent">
                <style>
                    #logs .gridjs-table td.gridjs-td,
                    #logs .gridjs-table th.gridjs-th {
                        padding: 2px 6px !important;
                        font-size: 13px;
                        line-height: 1.3;
                    }
                    #logs .gridjs-table tr.gridjs-tr {
                        height: auto !important;
                    }
                    .gffc-log-subtabs { display: flex; gap: 0; border-bottom: 2px solid #e2e8f0; margin-bottom: 10px; }
                    .gffc-log-subtab { padding: 8px 16px; font-size: 13px; font-weight: 600; color: #64748b; background: none; border: none; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -2px; transition: color 0.15s, border-color 0.15s; }
                    .gffc-log-subtab:hover { color: #1e293b; }
                    .gffc-log-subtab:focus { outline: none; box-shadow: none; }
                    .gffc-log-subtab.active { color: #1e293b; border-bottom-color: #00FE48; }
                    .gffc-log-pane { display: none; }
                    .gffc-log-pane.active { display: block; }
                </style>
                <div style="background: #fff; padding: 10px; overflow-x: scroll;">
                    <div class="gffc-log-subtabs" id="gffc-log-subtabs">
                        <button class="gffc-log-subtab active" data-log-target="woo" onclick="gffcSwitchLogTab('woo')"><i class="fas fa-store" style="margin-right:4px;"></i>WooCommerce</button>
                        <button class="gffc-log-subtab" data-log-target="gunbroker" onclick="gffcSwitchLogTab('gunbroker')" id="gffc-log-tab-gunbroker" style="display:none;"><i class="fas fa-gavel" style="margin-right:4px;"></i>Gunbroker</button>
                    </div>

                    <div class="gffc-log-pane active" id="gffc-log-pane-woo">
                        <div id="log_table_woo"></div>
                        <a class="button alt" onclick="gffcRefreshLogGrid('woo');">Refresh</a>
                    </div>

                    <div class="gffc-log-pane" id="gffc-log-pane-gunbroker">
                        <div id="log_table_gunbroker"></div>
                        <a class="button alt" onclick="gffcRefreshLogGrid('gunbroker');">Refresh</a>
                    </div>

                    <script>
                        var gffc_log_grids = {};
                        var gffc_log_grid_rendered = {};
                        var gffc_api_key = "<?php echo esc_attr($gFFLCockpitKey);?>";

                        function gffcCreateLogGrid(target) {
                            var logTarget = target === 'gunbroker' ? 'gunbroker' : 'woo';
                            return new gridjs.Grid({
                                columns: [
                                    {
                                        name: 'Timestamp',
                                        width: '190px',
                                        formatter: (cell) => gridjs.html(`<span style="color: #e6ffe6;">${new Date(cell).toLocaleString()}</span>`)
                                    },
                                    {name: "Message"}
                                ],
                                resizable: true,
                                fixedHeader: true,
                                style: {
                                    td: { 'padding': '3px', 'background': 'black', 'color': '#a1e89f', 'border': 'solid #353333 1px' },
                                    th: { 'padding': '3px', 'background': 'black', 'color': '#a1e89f', 'border': 'solid #353333 1px' }
                                },
                                server: {
                                    url: 'https://ffl-api.garidium.com',
                                    method: 'POST',
                                    headers: {
                                        "Accept": "application/json",
                                        "Content-Type": "application/json",
                                        "x-api-key": gffc_api_key,
                                    },
                                    body: JSON.stringify({"action": "get_logs", "data": {"api_key": gffc_api_key, "target": logTarget, "log_count": 2}}),
                                    then: data => {
                                        var logs = JSON.parse(data).logs || [];
                                        logs.sort(function(a, b) {
                                            return new Date(a.timestamp) - new Date(b.timestamp);
                                        });
                                        return logs.map(log => [log.timestamp, log.message]);
                                    }
                                }
                            });
                        }

                        // Initialize WooCommerce grid (always available)
                        gffc_log_grids['woo'] = gffcCreateLogGrid('woo');
                        // Keep backward-compatible reference
                        var log_grid = gffc_log_grids['woo'];

                        function gffcSwitchLogTab(target) {
                            // Update tab buttons
                            document.querySelectorAll('.gffc-log-subtab').forEach(function(btn) {
                                btn.classList.toggle('active', btn.getAttribute('data-log-target') === target);
                            });
                            // Update panes
                            document.querySelectorAll('.gffc-log-pane').forEach(function(p) { p.classList.remove('active'); });
                            var pane = document.getElementById('gffc-log-pane-' + target);
                            if (pane) pane.classList.add('active');
                            // Create and render grid if not yet done
                            if (!gffc_log_grids[target]) {
                                gffc_log_grids[target] = gffcCreateLogGrid(target);
                            }
                            if (!gffc_log_grid_rendered[target]) {
                                gffc_log_grids[target].render(document.getElementById('log_table_' + target));
                                gffc_log_grid_rendered[target] = true;
                            }
                        }

                        function gffcRefreshLogGrid(target) {
                            if (gffc_log_grids[target]) {
                                gffc_log_grids[target].forceRender();
                            }
                        }

                        // Show Gunbroker tab if active
                        document.addEventListener('DOMContentLoaded', function() {
                            setTimeout(function() {
                                if (window.gffcHasGunbrokerTargetInConfig) {
                                    var gbTab = document.getElementById('gffc-log-tab-gunbroker');
                                    if (gbTab) gbTab.style.display = '';
                                }
                            }, 2000);
                        });
                    </script>
                </div>
            </div>
            <?php endif; ?>
            <button class="accordion" id="gffc-ai-review-accordion" style="display:none;">Category Review</button>
            <div id="ai_category_review" class="tabcontent">
                <style>
                    .gffc-ai-review { max-width: 100%; margin: 0 auto; padding: 8px; }
                    .gffc-ai-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden; box-shadow: 0 1px 4px rgba(0,0,0,0.06); }
                    .gffc-ai-card-header { display: flex; gap: 12px; padding: 12px; align-items: stretch; flex-wrap: wrap; }
                    .gffc-ai-card-img { width: 240px; height: 240px; object-fit: contain; border-radius: 6px; background: #f8fafc; border: 1px solid #e2e8f0; flex-shrink: 0; align-self: center; }
                    .gffc-ai-card-proposal { flex: 1; min-width: 280px; display: flex; flex-direction: column; justify-content: center; }
                    .gffc-ai-card-details { flex: 1; min-width: 250px; border-left: 1px solid #e2e8f0; padding-left: 16px; display: flex; flex-direction: column; justify-content: center; }
                    .gffc-ai-card-title { font-size: 18px; font-weight: 700; color: #1e293b; margin-bottom: 8px; line-height: 1.3; }
                    .gffc-ai-meta { font-size: 13px; color: #64748b; margin-bottom: 3px; }
                    .gffc-ai-meta b { color: #334155; }
                    .gffc-ai-desc { font-size: 13px; color: #475569; margin-top: 6px; max-height: 60px; overflow-y: auto; line-height: 1.4; }
                    .gffc-ai-confidence { font-size: 14px; font-weight: 700; padding: 4px 12px; border-radius: 12px; display: inline-block; margin-top: 6px; }
                    .gffc-ai-proposal-label { font-size: 12px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 2px; }
                    .gffc-ai-proposal-cat { font-size: 22px; font-weight: 800; color: #1d4ed8; line-height: 1.2; }
                    .gffc-ai-btn { padding: 10px 26px; border: none; border-radius: 8px; font-size: 15px; font-weight: 700; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: transform 0.1s, box-shadow 0.1s; }
                    .gffc-ai-btn:active { transform: scale(0.97); }
                    .gffc-ai-btn-approve { background: #10b981; color: #fff; box-shadow: 0 2px 8px rgba(16,185,129,0.3); }
                    .gffc-ai-btn-approve:hover { background: #059669; }
                    .gffc-ai-btn-reject { background: #ef4444; color: #fff; box-shadow: 0 2px 8px rgba(239,68,68,0.3); }
                    .gffc-ai-btn-reject:hover { background: #dc2626; }
                    .gffc-ai-btn-skip { background: #f1f5f9; color: #64748b; border: 1px solid #e2e8f0; }
                    .gffc-ai-btn-skip:hover { background: #e2e8f0; }
                    .gffc-ai-progress { text-align: center; padding: 4px; font-size: 12px; color: #64748b; }
                    .gffc-ai-progress b { color: #1e293b; }
                    .gffc-ai-reject-picker { padding: 0 12px 12px; display: none; }
                    .gffc-ai-reject-picker select { width: 100%; padding: 4px 12px; font-size: 14px; border: 1px solid #e2e8f0; border-radius: 0 0 8px 8px; border-top: none; box-sizing: border-box; }
                    .gffc-ai-reject-picker select option { padding: 6px 4px; }
                    .gffc-ai-reject-picker select option:checked { background: #eff6ff; }
                    .gffc-ai-reject-picker-actions { display: flex; gap: 8px; margin-top: 8px; justify-content: center; }
                    .gffc-ai-recent { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 8px; }
                    .gffc-ai-recent-chip { padding: 5px 12px; font-size: 12px; font-weight: 600; background: #eff6ff; color: #1d4ed8; border: 1px solid #bfdbfe; border-radius: 6px; cursor: pointer; transition: background 0.1s; }
                    .gffc-ai-recent-chip:hover { background: #dbeafe; }
                    .gffc-ai-images { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 4px; }
                    .gffc-ai-thumb { width: 44px; height: 44px; object-fit: contain; border-radius: 4px; border: 1px solid #e2e8f0; cursor: pointer; background: #fff; }
                    .gffc-ai-empty { text-align: center; padding: 40px 20px; color: #94a3b8; }
                    .gffc-ai-empty i { font-size: 36px; margin-bottom: 8px; display: block; }
                    @media (max-width: 768px) {
                        .gffc-ai-card-header { flex-direction: column; align-items: center; text-align: center; }
                        .gffc-ai-card-img { width: 200px; height: 200px; }
                        .gffc-ai-card-proposal { align-items: center; }
                        .gffc-ai-card-details { width: 100%; border-left: none; padding-left: 0; border-top: 1px solid #e2e8f0; padding-top: 10px; margin-top: 6px; }
                        .gffc-ai-btn { padding: 12px 20px; font-size: 16px; flex: 1; justify-content: center; }
                        .gffc-ai-proposal-cat { font-size: 16px; }
                    }
                    .gffc-ai-token-bar { display: flex; align-items: center; justify-content: space-between; padding: 4px 0; gap: 12px; flex-wrap: wrap; }
                    .gffc-ai-pc-filter { display: flex; align-items: center; background: #fff; border: 1px solid #e2e8f0; border-left: 3px solid #6366f1; border-radius: 6px; padding: 6px 12px; gap: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.04); }
                    .gffc-ai-pc-filter label { font-size: 13px; font-weight: 700; color: #334155; margin-right: 0; }
                    .gffc-ai-pc-filter select { padding: 6px 10px; font-size: 14px; font-weight: 600; border: 1px solid #e2e8f0; border-radius: 6px; background: #f8fafc; color: #1e293b; min-width: 160px; }
                    .gffc-ai-token-balance { display: inline-flex; align-items: center; gap: 6px; background: #fff; border: 1px solid #e2e8f0; border-left: 3px solid #3b82f6; border-radius: 4px; padding: 4px 10px; box-shadow: 0 1px 2px rgba(0,0,0,0.04); }
                    .gffc-ai-token-balance .gffc-ai-token-icon { width: 24px; height: 24px; background: #3b82f6; border-radius: 4px; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 12px; }
                    .gffc-ai-token-balance .gffc-ai-token-info { display: flex; flex-direction: column; }
                    .gffc-ai-token-balance .gffc-ai-token-count { font-size: 15px; font-weight: 700; color: #1e293b; line-height: 1.1; }
                    .gffc-ai-token-balance .gffc-ai-token-label { font-size: 8px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
                    .gffc-ai-stats { font-size: 11px; color: #64748b; display: flex; gap: 12px; flex-wrap: wrap; }
                    .gffc-ai-lightbox { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 100000; display: flex; align-items: center; justify-content: center; cursor: pointer; }
                    .gffc-ai-lightbox img { max-width: 90%; max-height: 90%; object-fit: contain; border-radius: 8px; box-shadow: 0 4px 24px rgba(0,0,0,0.4); }
                    .gffc-ai-toast { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 48px; font-weight: 900; pointer-events: none; z-index: 99999; opacity: 0; transition: opacity 0.15s, transform 0.6s; }
                    .gffc-ai-toast.show { opacity: 1; transform: translate(-50%, -50%) scale(1.2); }
                    .gffc-ai-toast.fade { opacity: 0; transform: translate(-50%, -80%) scale(0.8); }
                    .gffc-ai-leaderboard { margin-top: 12px; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden; }
                    .gffc-ai-leaderboard table { width: 100%; border-collapse: collapse; font-size: 12px; }
                    .gffc-ai-leaderboard th { background: #f8fafc; padding: 6px 10px; text-align: left; font-weight: 600; color: #64748b; border-bottom: 1px solid #e2e8f0; }
                    .gffc-ai-leaderboard td { padding: 6px 10px; border-bottom: 1px solid #f1f5f9; }
                    .gffc-ai-leaderboard tr:first-child td { font-weight: 700; color: #f59e0b; }
                    .gffc-ai-leaderboard .gffc-ai-lb-me { background: #eff6ff; }
                </style>
                <div class="gffc-ai-review">
                    <div class="gffc-ai-token-bar">
                        <div class="gffc-ai-token-balance"><div class="gffc-ai-token-icon"><i class="fas fa-database"></i></div><div class="gffc-ai-token-info"><span class="gffc-ai-token-count" id="gffc-ai-token-count">0</span><span class="gffc-ai-token-label">FFL Cockpit AI Tokens</span></div></div>
                        <div class="gffc-ai-pc-filter">
                            <label><i class="fas fa-filter" style="margin-right:4px;color:#6366f1;"></i>Product Class:</label>
                            <select id="gffc-ai-pc-select" onchange="gffcAiApplyPcFilter()">
                                <option value="">All</option>
                            </select>
                        </div>
                    </div>
                    <div class="gffc-ai-progress" id="gffc-ai-progress"></div>
                    <div id="gffc-ai-card-container">
                        <div class="gffc-ai-empty"><i class="fas fa-spinner fa-spin"></i>Loading...</div>
                    </div>
                    <details style="margin-top:16px;">
                        <summary style="cursor:pointer;font-size:13px;font-weight:600;color:#6366f1;"><i class="fas fa-trophy" style="margin-right:4px;color:#f59e0b;"></i>Leaderboard</summary>
                        <div class="gffc-ai-leaderboard" id="gffc-ai-leaderboard"><div style="padding:20px;text-align:center;color:#94a3b8;">Loading...</div></div>
                    </details>
                </div>
                <script>
                    var gffcAiItems = [];
                    var gffcAiIndex = 0;
                    var gffcAiTotal = 0;
                    var gffcAiLastAction = 0;
                    var gffcAiReviewed = 0;
                    var gffcAiSessionTokens = 0;
                    var gffcAiTotalTokens = 0;
                    var gffcAiCategories = null;
                    var gffcAiRecentCategories = [];
                    var gffcAiProductClassFilter = '';
                    var gffcAiLoaded = false;
                    var gffcAiApiKey = "<?php echo esc_attr($gFFLCockpitKey); ?>";

                    function gffcAiParseResponse(text) {
                        var obj = text;
                        for (var i = 0; i < 5; i++) {
                            if (typeof obj !== 'string') break;
                            try { obj = JSON.parse(obj); } catch(e) { break; }
                        }
                        if (obj && typeof obj === 'object') return Promise.resolve(obj);
                        return Promise.resolve(null);
                    }

                    function gffcLoadAiReview() {
                        if (gffcAiLoaded && gffcAiItems.length > 0) return;
                        gffcAiLoaded = true;
                        // Load categories, product classes, pending items, token balance, and leaderboard
                        Promise.all([
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                                body: JSON.stringify({ "action": "get_category_list", "data": {} })
                            }).then(function(r) { return r.text(); }).then(function(text) { return gffcAiParseResponse(text); }),
                            fetch("https://ffl-api.garidium.com", {
                                method: "POST",
                                headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                                body: JSON.stringify({ "action": "get_product_classes", "data": {} })
                            }).then(function(r) { return r.text(); }).then(function(text) { return gffcAiParseResponse(text); })
                        ])
                        .then(function(results) {
                            var catData = results[0];
                            var pcData = results[1];
                            gffcAiCategories = (catData && catData.categories) ? catData.categories : [];
                            // Populate product class filter
                            var pcSelect = document.getElementById('gffc-ai-pc-select');
                            console.log("Product classes data:", pcData);
                            if (pcSelect && pcData && pcData.product_classes) {
                                var pcs = pcData.product_classes;
                                for (var pi = 0; pi < pcs.length; pi++) {
                                    var pc = pcs[pi];
                                    var opt = document.createElement('option');
                                    opt.value = pc.product_class || pc;
                                    opt.textContent = (pc.product_class || pc) + (pc.description ? ' - ' + pc.description : '');
                                    pcSelect.appendChild(opt);
                                }
                            }
                            gffcLoadTokenBalance();
                            gffcLoadLeaderboard();
                            return gffcFetchPendingItems();
                        })
                        .catch(function(e) {
                            console.error("Error loading AI review:", e);
                            document.getElementById('gffc-ai-card-container').innerHTML = '<div class="gffc-ai-empty"><i class="fas fa-exclamation-triangle"></i>Failed to load. Try refreshing.</div>';
                        });
                    }

                    function gffcLoadTokenBalance() {
                        fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                            body: JSON.stringify({ "action": "get_ai_token_balance", "data": { "api_key": gffcAiApiKey } })
                        })
                        .then(function(r) { return r.text(); })
                        .then(function(text) { return gffcAiParseResponse(text); })
                        .then(function(data) {
                            if (!data) return;
                            gffcAiTotalTokens = Number(data.available_tokens) || 0;
                            document.getElementById('gffc-ai-token-count').textContent = gffcAiTotalTokens.toLocaleString();
                        }).catch(function(e) { console.error("Token balance error:", e); });
                    }

                    function gffcLoadLeaderboard() {
                        fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                            body: JSON.stringify({ "action": "get_ai_token_leaderboard", "data": {} })
                        })
                        .then(function(r) { return r.text(); })
                        .then(function(text) { return gffcAiParseResponse(text); })
                        .then(function(data) {
                            var el = document.getElementById('gffc-ai-leaderboard');
                            if (!el || !data || !data.leaderboard) return;
                            var leaders = data.leaderboard;
                            if (leaders.length === 0) { el.innerHTML = '<div style="padding:20px;text-align:center;color:#94a3b8;">No reviews yet. Be the first!</div>'; return; }
                            var html = '<table><tr><th>#</th><th>Reviewer</th><th><i class="fas fa-coins" style="color:#f59e0b;"></i> Tokens</th><th>Reviews</th><th>Corrections</th></tr>';
                            for (var i = 0; i < leaders.length; i++) {
                                var l = leaders[i];
                                var isMe = l.api_key === gffcAiApiKey;
                                var medal = i === 0 ? '<span style="color:#f59e0b;">&#x1F947;</span> ' : i === 1 ? '<span style="color:#94a3b8;">&#x1F948;</span> ' : i === 2 ? '<span style="color:#cd7f32;">&#x1F949;</span> ' : '';
                                var displayName = 'Anonymous';
                                if (l.reviewer_name) {
                                    var parts = l.reviewer_name.trim().split(/\s+/);
                                    displayName = parts[0].charAt(0).toUpperCase() + '.' + (parts.length > 1 ? ' ' + parts[parts.length - 1].charAt(0).toUpperCase() + '.' : '');
                                }
                                html += '<tr class="' + (isMe ? 'gffc-ai-lb-me' : '') + '">';
                                html += '<td>' + medal + (i + 1) + '</td>';
                                html += '<td>' + displayName + (isMe ? ' <b>(you)</b>' : '') + '</td>';
                                html += '<td style="font-weight:700;color:#f59e0b;">' + Number(l.total_tokens).toLocaleString() + '</td>';
                                html += '<td>' + l.reviews + '</td>';
                                html += '<td>' + l.corrections + '</td></tr>';
                            }
                            html += '</table>';
                            el.innerHTML = html;
                        }).catch(function() {});
                    }

                    function gffcAiShowLightbox(src) {
                        var overlay = document.createElement('div');
                        overlay.className = 'gffc-ai-lightbox';
                        overlay.innerHTML = '<img src="' + src + '">';
                        overlay.onclick = function() { overlay.remove(); };
                        document.body.appendChild(overlay);
                    }

                    function gffcShowTokenToast(tokens) {
                        if (tokens <= 0) return;
                        var toast = document.createElement('div');
                        toast.className = 'gffc-ai-toast';
                        toast.style.color = tokens >= 150 ? '#6366f1' : '#10b981';
                        toast.textContent = '+' + tokens;
                        document.body.appendChild(toast);
                        requestAnimationFrame(function() {
                            toast.classList.add('show');
                            setTimeout(function() {
                                toast.classList.remove('show');
                                toast.classList.add('fade');
                                setTimeout(function() { toast.remove(); }, 600);
                            }, 500);
                        });
                    }

                    function gffcAiApplyPcFilter() {
                        var sel = document.getElementById('gffc-ai-pc-select');
                        gffcAiProductClassFilter = sel ? sel.value : '';
                        gffcAiLoaded = false;
                        gffcAiItems = [];
                        gffcAiIndex = 0;
                        gffcAiReviewed = 0;
                        document.getElementById('gffc-ai-card-container').innerHTML = '<div class="gffc-ai-empty"><i class="fas fa-spinner fa-spin"></i>Loading...</div>';
                        gffcFetchPendingItems();
                    }

                    function gffcFetchPendingItems() {
                        var reqData = { "limit": 100, "api_key": gffcAiApiKey };
                        if (gffcAiProductClassFilter) reqData.product_class = gffcAiProductClassFilter;
                        return fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                            body: JSON.stringify({ "action": "get_pending_ai_categories", "data": reqData })
                        })
                        .then(function(r) { return r.text(); })
                        .then(function(text) {
                            console.log("Pending items raw:", text && text.substring ? text.substring(0, 200) : text);
                            return gffcAiParseResponse(text);
                        })
                        .then(function(data) {
                            console.log("Pending items parsed:", data);
                            if (!data) { data = { total: 0, items: [] }; }
                            gffcAiTotal = data.total || 0;
                            gffcAiItems = data.items || [];
                            gffcAiIndex = 0;
                            gffcRenderAiCard();
                        });
                    }

                    var gffcAiFetching = false;

                    function gffcRenderAiCard() {
                        var container = document.getElementById('gffc-ai-card-container');
                        var progress = document.getElementById('gffc-ai-progress');

                        // Auto-fetch more when we've exhausted the current batch
                        if (gffcAiIndex >= gffcAiItems.length && gffcAiTotal > 0 && !gffcAiFetching) {
                            gffcAiFetching = true;
                            container.innerHTML = '<div class="gffc-ai-empty"><i class="fas fa-spinner fa-spin"></i>Loading more...</div>';
                            gffcFetchPendingItems().then(function() { gffcAiFetching = false; });
                            return;
                        }

                        if (gffcAiItems.length === 0 || gffcAiIndex >= gffcAiItems.length) {
                            container.innerHTML = '<div class="gffc-ai-empty"><i class="fas fa-check-circle" style="color:#10b981;"></i><div style="font-size:18px;font-weight:700;color:#1e293b;margin-bottom:4px;">All caught up!</div><div>No more products to review.</div></div>';
                            progress.innerHTML = '<b>' + gffcAiReviewed + '</b> reviewed';
                            return;
                        }

                        var item = gffcAiItems[gffcAiIndex];
                        progress.innerHTML = '<b>' + gffcAiReviewed + '</b> reviewed';

                        var conf = Math.round((Number(item.confidence) || 0) * 100);
                        var confColor = conf >= 80 ? '#10b981' : conf >= 50 ? '#f59e0b' : '#ef4444';
                        var confBg = conf >= 80 ? '#ecfdf5' : conf >= 50 ? '#fffbeb' : '#fef2f2';

                        // Images
                        var imgs = item.images || [];
                        var mainImg = item.image_url || (imgs.length > 0 && imgs[0] && imgs[0].src ? imgs[0].src : '');
                        var imgHtml = mainImg ? '<img class="gffc-ai-card-img" src="' + mainImg + '" onclick="gffcAiShowLightbox(this.src)" style="cursor:pointer;" onerror="this.style.display=\'none\'">' : '<div class="gffc-ai-card-img" style="display:flex;align-items:center;justify-content:center;color:#cbd5e1;"><i class="fas fa-image" style="font-size:36px;"></i></div>';

                        // Thumbnails
                        var thumbsHtml = '';
                        if (imgs.length > 1) {
                            thumbsHtml = '<div class="gffc-ai-images">';
                            for (var t = 0; t < Math.min(imgs.length, 6); t++) {
                                var tsrc = imgs[t] && imgs[t].src ? imgs[t].src : '';
                                if (tsrc) thumbsHtml += '<img class="gffc-ai-thumb" src="' + tsrc + '" onclick="gffcAiShowLightbox(this.src)" style="cursor:pointer;" onerror="this.style.display=\'none\'">';
                            }
                            thumbsHtml += '</div>';
                        }

                        // Description
                        var desc = item.description || item.short_description || '';
                        desc = desc.replace(/<[^>]*>/g, '').substring(0, 300);
                        var descHtml = desc ? '<div class="gffc-ai-desc">' + desc + '</div>' : '';

                        // GB category (shown inline in product meta)
                        var gbMetaHtml = '';
                        if (item.gb_category_name) {
                            gbMetaHtml = '<div class="gffc-ai-meta"><b>GunBroker Category:</b> ' + item.gb_category_name + '</div>';
                        }

                        var html = '<div class="gffc-ai-card">';
                        html += '<div class="gffc-ai-card-header">' + imgHtml;
                        // Center: proposal + buttons
                        html += '<div class="gffc-ai-card-proposal">';
                        html += '<div class="gffc-ai-card-title">' + (item.product_name || 'Unknown Product') + '</div>';
                        html += '<div class="gffc-ai-proposal-label">AI Proposed Category</div>';
                        html += '<div class="gffc-ai-proposal-cat"><i class="fas fa-robot" style="margin-right:4px;opacity:0.5;font-size:14px;"></i>' + (item.category_name || 'Unknown') + '</div>';
                        html += '<span class="gffc-ai-confidence" style="background:' + confBg + ';color:' + confColor + ';">' + conf + '%</span>';
                        html += '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:10px;">';
                        html += '<button class="gffc-ai-btn gffc-ai-btn-approve" onclick="gffcAiDecision(\'approve\')"><i class="fas fa-check"></i> Approve <span style="opacity:0.7;font-size:11px;font-weight:400;">+250</span></button>';
                        html += '<button class="gffc-ai-btn gffc-ai-btn-skip" onclick="gffcAiDecision(\'skip\')"><i class="fas fa-forward"></i> Skip</button>';
                        html += '<button class="gffc-ai-btn gffc-ai-btn-reject" onclick="gffcShowRejectPicker()"><i class="fas fa-times"></i> Wrong <span style="opacity:0.7;font-size:11px;font-weight:400;">+500</span></button>';
                        html += '</div>';
                        html += '</div>';
                        // Right: product details (visible on desktop, collapsible on mobile)
                        html += '<div class="gffc-ai-card-details">';
                        html += '<div class="gffc-ai-meta"><b>UPC:</b> ' + item.upc + '</div>';
                        if (item.mfg_name) html += '<div class="gffc-ai-meta"><b>Manufacturer:</b> ' + item.mfg_name + '</div>';
                        if (item.mpn) html += '<div class="gffc-ai-meta"><b>MPN:</b> ' + item.mpn + '</div>';
                        if (item.product_class) html += '<div class="gffc-ai-meta"><b>Product Class:</b> ' + item.product_class + '</div>';
                        if (item.distributor_category) html += '<div class="gffc-ai-meta"><b>Distributor Category:</b> ' + item.distributor_category + '</div>';
                        if (item.distid) html += '<div class="gffc-ai-meta"><b>Distributor:</b> ' + item.distid + '</div>';
                        if (item.unit_price) html += '<div class="gffc-ai-meta"><b>Cost:</b> $' + Number(item.unit_price).toFixed(2) + (item.msrp ? ' &nbsp;|&nbsp; <b>MSRP:</b> $' + Number(item.msrp).toFixed(2) : '') + '</div>';
                        html += gbMetaHtml;
                        html += descHtml + thumbsHtml;
                        html += '</div>';
                        html += '</div>';

                        // Reject category picker (hidden by default)
                        html += '<div class="gffc-ai-reject-picker" id="gffc-ai-reject-picker">';
                        html += '<label style="font-size:13px;font-weight:600;color:#991b1b;display:block;margin-bottom:4px;">Select the correct category:</label>';
                        // Recent categories — one-click to set
                        html += '<div class="gffc-ai-recent" id="gffc-ai-recent">';
                        for (var ri = 0; ri < gffcAiRecentCategories.length; ri++) {
                            var rc = gffcAiRecentCategories[ri];
                            html += '<button class="gffc-ai-recent-chip" onclick="gffcAiQuickReject(\'' + rc.id + '\')">' + rc.label + '</button>';
                        }
                        html += '</div>';
                        html += '<input type="text" id="gffc-ai-reject-filter" placeholder="Type to filter categories..." oninput="gffcAiFilterCategories(this.value)" style="width:100%;padding:8px 12px;font-size:14px;border:1px solid #e2e8f0;border-radius:8px 8px 0 0;box-sizing:border-box;outline:none;" onfocus="this.style.borderColor=\'#6366f1\'" onblur="this.style.borderColor=\'#e2e8f0\'">';
                        html += '<select id="gffc-ai-reject-select" size="8" style="border-radius:0 0 8px 8px;border-top:none;"><option value="">-- Choose a category --</option>';
                        if (gffcAiCategories) {
                            for (var ci = 0; ci < gffcAiCategories.length; ci++) {
                                var cat = gffcAiCategories[ci];
                                var catLabel = cat.parent ? cat.parent + ' > ' + cat.name : cat.name;
                                html += '<option value="' + cat.id + '">' + catLabel + '</option>';
                            }
                        }
                        html += '</select>';
                        html += '<div class="gffc-ai-reject-picker-actions">';
                        html += '<button class="gffc-ai-btn gffc-ai-btn-reject" style="padding:8px 20px;font-size:13px;" onclick="gffcAiRejectConfirm()"><i class="fas fa-check"></i> Confirm</button>';
                        html += '<button class="gffc-ai-btn gffc-ai-btn-skip" style="padding:8px 20px;font-size:13px;" onclick="document.getElementById(\'gffc-ai-reject-picker\').style.display=\'none\'">Cancel</button>';
                        html += '</div></div>';

                        html += '</div>';
                        container.innerHTML = html;
                    }

                    function gffcShowRejectPicker() {
                        document.getElementById('gffc-ai-reject-picker').style.display = 'block';
                        var filterInput = document.getElementById('gffc-ai-reject-filter');
                        if (filterInput) { filterInput.value = ''; gffcAiFilterCategories(''); filterInput.focus(); }
                    }

                    function gffcAiFilterCategories(query) {
                        var sel = document.getElementById('gffc-ai-reject-select');
                        if (!sel || !gffcAiCategories) return;
                        var q = query.toLowerCase();
                        var html = '';
                        if (!q) html += '<option value="">-- Choose a category --</option>';
                        for (var ci = 0; ci < gffcAiCategories.length; ci++) {
                            var cat = gffcAiCategories[ci];
                            var catLabel = cat.parent ? cat.parent + ' > ' + cat.name : cat.name;
                            if (!q || catLabel.toLowerCase().indexOf(q) !== -1) {
                                html += '<option value="' + cat.id + '">' + catLabel + '</option>';
                            }
                        }
                        if (!html) html = '<option value="" disabled>No matching categories</option>';
                        sel.innerHTML = html;
                    }

                    function gffcAiAddRecentCategory(catId) {
                        if (!catId || !gffcAiCategories) return;
                        // Remove if already in recents
                        gffcAiRecentCategories = gffcAiRecentCategories.filter(function(r) { return r.id !== catId; });
                        // Find the label
                        var label = catId;
                        for (var ci = 0; ci < gffcAiCategories.length; ci++) {
                            if (String(gffcAiCategories[ci].id) === String(catId)) {
                                var cat = gffcAiCategories[ci];
                                label = cat.parent ? cat.parent + ' > ' + cat.name : cat.name;
                                break;
                            }
                        }
                        // Add to front, keep max 8
                        gffcAiRecentCategories.unshift({ id: String(catId), label: label });
                        if (gffcAiRecentCategories.length > 8) gffcAiRecentCategories.pop();
                    }

                    function gffcAiQuickReject(catId) {
                        gffcAiAddRecentCategory(catId);
                        gffcAiDecision('reject', catId);
                    }

                    function gffcAiRejectConfirm() {
                        var sel = document.getElementById('gffc-ai-reject-select');
                        var catId = sel ? sel.value : '';
                        if (catId) gffcAiAddRecentCategory(catId);
                        gffcAiDecision('reject', catId || null);
                    }

                    function gffcAiDecision(decision, selectedCategory) {
                        var now = Date.now();
                        if (now - gffcAiLastAction < 1000) return;
                        gffcAiLastAction = now;
                        if (gffcAiIndex >= gffcAiItems.length) return;
                        var item = gffcAiItems[gffcAiIndex];

                        // Calculate expected tokens for toast
                        var expectedTokens = 0;
                        if (decision === 'approve') expectedTokens = 250;
                        else if (decision === 'reject' && selectedCategory) expectedTokens = 500;

                        var payload = {
                            "action": "review_ai_category",
                            "data": {
                                "api_key": gffcAiApiKey,
                                "upc": item.upc,
                                "decision": decision
                            }
                        };
                        if (selectedCategory) payload.data.selected_category = selectedCategory;

                        // Optimistically advance and show feedback
                        gffcAiReviewed++;
                        gffcAiTotal = Math.max(0, gffcAiTotal - 1);
                        gffcAiIndex++;
                        gffcAiSessionTokens += expectedTokens;
                        if (expectedTokens > 0) {
                            gffcAiTotalTokens += expectedTokens;
                            var availEl = document.getElementById('gffc-ai-token-count');
                            if (availEl) availEl.textContent = gffcAiTotalTokens.toLocaleString();
                        }
                        gffcShowTokenToast(expectedTokens);
                        gffcRenderAiCard();

                        // Fire API call in background
                        fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: { "Accept": "application/json", "Content-Type": "application/json", "x-api-key": gffcAiApiKey },
                            body: JSON.stringify(payload)
                        }).then(function(r) { return r.json(); }).then(function(data) {
                            gffcLoadTokenBalance();
                            if (gffcAiReviewed % 10 === 0) gffcLoadLeaderboard();
                        }).catch(function(e) { console.error("Review submit error:", e); });
                    }

                    // Show accordion when tab is activated via earn tokens modal
                    document.addEventListener('DOMContentLoaded', function() {
                        var tab = document.getElementById('gffc-ai-review-tab');
                        if (tab) {
                            tab.addEventListener('click', function() {
                                var acc = document.getElementById('gffc-ai-review-accordion');
                                if (acc) acc.style.display = '';
                            });
                        }
                    });
                </script>
            </div>

            <button class="accordion">Help Center</button>
            <div id="help_center" class="tabcontent">
                <script>
                    function load_help_videos(){
                        fetch("https://ffl-api.garidium.com", {
                            method: "POST",
                            headers: {
                            "Accept": "application/json",
                            "Content-Type": "application/json",
                            "x-api-key": "<?php echo esc_attr($gFFLCockpitKey); ?>",
                            },
                            body: JSON.stringify({"action": "get_training_videos"})
                        })
                        .then(response=>response.json())
                        .then(data=>{ 
                            var video_div = document.getElementById("training_videos");
                            video_div.innerHTML = '';
                            for (var i = 0, l = data.length; i < l; i++) {
                                var innerDiv = document.createElement("div");
                                innerDiv.innerHTML = '<div style="width:390px;"><iframe width="370" height="208" src="' + data[i].url + '" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe><br><span style="width:99%;">' + data[i].title + '</span><br><span style="color:#a29f9f !important;width:99%;height:50px;">' + data[i].description + '</span></div>';
                                video_div.appendChild(innerDiv);
                            }
                        });
                    }
                </script>
                <style>
                    .gffc-helpdesk-container { position: relative; }
                    .gffc-helpdesk-launcher { display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 16px 0 22px; }
                    .gffc-helpdesk-launcher .gffc-helpdesk-button { display: inline-flex; align-items: center; gap: 10px; padding: 12px 22px; border-radius: 8px; border: 1px solid #111827; background: #000; color: #fff; font-weight: 700; font-size: 15px; box-shadow: 0 10px 20px rgba(15, 23, 42, 0.2); cursor: pointer; transition: transform 120ms ease, box-shadow 120ms ease; }
                    .gffc-helpdesk-launcher .gffc-helpdesk-button:hover { transform: translateY(-1px); box-shadow: 0 12px 24px rgba(15, 23, 42, 0.25); }
                    .gffc-helpdesk-launcher .gffc-helpdesk-button:active { transform: translateY(0); box-shadow: 0 6px 16px rgba(15, 23, 42, 0.18); }
                    .gffc-helpdesk-launcher .gffc-helpdesk-button:focus { outline: 2px solid rgba(0, 254, 72, 0.35); outline-offset: 2px; }
                    #ai-kb-submit { display: inline-flex !important; align-items: center !important; gap: 8px !important; padding: 10px 18px !important; border-radius: 999px !important; border: 1px solid #111827 !important; background: #000 !important; color: #fff !important; font-weight: 700 !important; font-size: 14px !important; box-shadow: 0 8px 20px rgba(15, 23, 42, 0.2) !important; text-shadow: none !important; transition: transform 120ms ease, box-shadow 120ms ease; }
                    #ai-kb-submit:hover { background: #000 !important; transform: translateY(-1px); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.25) !important; }
                    #ai-kb-submit:active { background: #000 !important; transform: translateY(0); box-shadow: 0 6px 16px rgba(15, 23, 42, 0.18) !important; }
                    #ai-kb-submit:focus { outline: 2px solid rgba(0, 254, 72, 0.35) !important; outline-offset: 2px; }
                    #ai-kb-submit .gffc-helpdesk-fab-icon { color: #00FE48 !important; font-size: 18px; width: 18px; height: 18px; }
                    .gffc-helpdesk-overlay { position: fixed; inset: 0; background: rgba(15, 23, 42, 0.25); opacity: 0; pointer-events: none; transition: opacity 200ms ease; z-index: 2147483646; }
                    .gffc-helpdesk-panel { position: fixed; top: 0; right: 0; height: 100vh; width: 480px; max-width: 96vw; background: rgba(255, 255, 255, 0.92); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: -8px 0 24px rgba(15, 23, 42, 0.25); transform: translateX(110%); transition: transform 220ms ease; display: flex; flex-direction: column; border-left: 1px solid rgba(226, 232, 240, 0.7); z-index: 2147483647; }
                    body.admin-bar .gffc-helpdesk-panel { top: 32px; height: calc(100vh - 32px); }
                    @media screen and (max-width: 782px) {
                        body.admin-bar .gffc-helpdesk-panel { top: 46px; height: calc(100vh - 46px); }
                    }
                    .gffc-helpdesk-overlay.is-open { opacity: 1; pointer-events: auto; }
                    .gffc-helpdesk-overlay.is-open .gffc-helpdesk-panel { transform: translateX(0); }
                    .gffc-helpdesk-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: #000; border-bottom: 1px solid #111827; }
                    .gffc-helpdesk-title { font-weight: 700; color: #fff; display: flex; align-items: center; gap: 8px; }
                    .gffc-helpdesk-title .gffc-helpdesk-icon { font-size: 22px; line-height: 1; color: #00FE48; }
                    .gffc-helpdesk-launcher .gffc-helpdesk-icon { font-size: 20px; line-height: 1; margin-right: 6px; display: inline-flex; align-items: center; color: #00FE48; }
                    .gffc-helpdesk-close { background: transparent; border: none; font-size: 20px; cursor: pointer; color: #e2e8f0; }
                    .gffc-helpdesk-body { padding: 10px 14px; overflow: auto; }
                    .ai-md-h1, .ai-md-h2, .ai-md-h3 { margin: 12px 0 6px; font-weight: 700; color: #1f2937; }
                    .ai-md-h1 { font-size: 18px; }
                    .ai-md-h2 { font-size: 16px; }
                    .ai-md-h3 { font-size: 15px; }
                    .gffc-helpdesk-fab { position: fixed; right: 20px; bottom: 24px; padding: 8px 12px; min-height: 40px; border-radius: 8px; border: 1px solid #111827; background: #000; color: #fff; display: inline-flex; align-items: center; gap: 8px; box-shadow: 0 10px 20px rgba(15, 23, 42, 0.2); cursor: pointer; z-index: 2147483647; font-weight: 600; }
                    .gffc-helpdesk-fab .gffc-helpdesk-fab-icon { color: #00FE48; font-size: 18px; width: 18px; height: 18px; }
                    .gffc-helpdesk-fab .gffc-helpdesk-fab-text { font-size: 12px; letter-spacing: 0.2px; }
                    .gffc-helpdesk-fab .gffc-helpdesk-brand { display: inline-flex; align-items: center; gap: 0; letter-spacing: 0; word-spacing: 0; }
                    .gffc-helpdesk-fab .gffc-helpdesk-brand-accent { color: #00FE48; font-weight: 700; }
                    .gffc-helpdesk-brand-accent { color: #00FE48; font-weight: 700; }
                    .gffc-helpdesk-brand { display: inline-flex; align-items: center; gap: 0; letter-spacing: 0; word-spacing: 0; }
                    .gffc-helpdesk-fab:hover { box-shadow: 0 12px 24px rgba(15, 23, 42, 0.25); }
                    .gffc-helpdesk-fab:focus { outline: 2px solid rgba(0, 254, 72, 0.35); outline-offset: 2px; }
                    @media screen and (max-width: 768px) {
                        .gffc-helpdesk-panel { width: 100%; max-width: 100%; height: 100vh; }
                        .gffc-helpdesk-fab { right: 14px; bottom: 16px; padding: 6px 10px; }
                    }
                </style>
                <div class="gffc-helpdesk-container" style="background: #fff; padding: 10px; overflow-x: auto;">
                    <div style="padding:10px;">If you have any questions about FFL Cockpit configuration, send an email to support@garidium.com detailing your questions. We'll get back as soon as we can. Include your name and your website URL so we can look up your configuration. Also, make to review our <a target=_blank href="https://fflcockpit.com/help-center/">Help Center</a> for tips on using FFL Cockpit.</div>

                    <div class="gffc-helpdesk-launcher">
                        <button class="gffc-helpdesk-button" onclick="gffcOpenHelpdesk()">
                            <span class="gffc-helpdesk-icon dashicons dashicons-format-chat" aria-hidden="true"></span>Chat with <span class="gffc-helpdesk-brand"><span>G</span><span class="gffc-helpdesk-brand-accent">A</span><span>R</span><span class="gffc-helpdesk-brand-accent">I</span></span> the FFL Cockpit AI Agent
                        </button>
                        <div style="text-align: center; margin-top: 6px; font-size: 11px; color: #94a3b8; letter-spacing: 0.5px; font-weight: 500;"><span style="color: #64748b; font-weight: 700;">G</span>aridium <span style="color: #00FE48; font-weight: 700;">A</span>utomated <span style="color: #64748b; font-weight: 700;">R</span>esource <span style="color: #00FE48; font-weight: 700;">I</span>ntelligence</div>
                    </div>

                    
                    <div class="video_grid" id="training_videos"></div>
                    
                    <?php
                    $gffc_current_user = wp_get_current_user();
                    $gffc_site_url = home_url();
                    $gffc_can_manage_kb = current_user_can('manage_options')
                        && strtolower(trim((string) $gffc_current_user->user_email)) === 'sales@garidium.com'
                        && stripos((string) $gffc_site_url, 'garidium.com') !== false;
                    ?>
                    <?php if ($gffc_can_manage_kb): ?>
                    <!-- Admin-only: Add to Knowledge Base -->
                    <details class="ai-knowledge-collapsible" style="margin: 20px 0;">
                        <summary style="cursor: pointer; font-weight: bold; color: #e65100; padding: 10px 12px; background: #fff8e1; border: 1px solid #ffcc80; border-radius: 8px;">
                            <span style="margin-right: 8px;">📚</span>Add to Knowledge Base (Admin Only)
                        </summary>
                        <div class="ai-knowledge-section" style="margin: 10px 0 0 0; padding: 20px; background: #fff8e1; border: 1px solid #ffcc80; border-radius: 8px;">
                            <p style="color: #666; margin-bottom: 15px;">Add question and answer pairs to train the AI assistant.</p>
                            
                            <div class="ai-knowledge-form">
                                <div style="margin-bottom: 15px;">
                                    <label for="ai-kb-question" style="display: block; font-weight: bold; margin-bottom: 5px;">Question:</label>
                                    <textarea id="ai-kb-question" class="large-text" rows="2" placeholder="Enter a common question users might ask..."></textarea>
                                </div>
                                <div style="margin-bottom: 15px;">
                                    <label for="ai-kb-answer" style="display: block; font-weight: bold; margin-bottom: 5px;">Answer:</label>
                                    <textarea id="ai-kb-answer" class="large-text" rows="4" placeholder="Enter the answer to provide..."></textarea>
                                </div>
                                <button id="ai-kb-submit" class="gffc-helpdesk-kb-button" onclick="addAIKnowledge()">
                                    <span class="gffc-helpdesk-fab-icon dashicons dashicons-format-chat" aria-hidden="true"></span>
                                    <span id="ai-kb-button-text">Add to Knowledge Base</span>
                                    <span id="ai-kb-spinner" class="spinner" style="display: none; float: none; margin: 0 0 0 5px;"></span>
                                </button>
                                <span id="ai-kb-status" style="margin-left: 15px; font-weight: bold;"></span>
                            </div>
                        </div>
                    </details>
                    <?php endif; ?>
                </div>
            </div>    

            <button id="gffc-helpdesk-fab" class="gffc-helpdesk-fab" onclick="gffcOpenHelpdesk()" aria-label="Open GARI help" title="Chat with GARI">
                <span class="gffc-helpdesk-fab-icon dashicons dashicons-format-chat" aria-hidden="true"></span>
                <span class="gffc-helpdesk-fab-text">Ask <span class="gffc-helpdesk-brand"><span>G</span><span class="gffc-helpdesk-brand-accent">A</span><span>R</span><span class="gffc-helpdesk-brand-accent">I</span></span></span>
            </button>

            <div id="gffc-helpdesk-overlay" class="gffc-helpdesk-overlay" aria-hidden="true" onclick="gffcCloseHelpdesk(event)">
                <div id="gffc-helpdesk-panel" class="gffc-helpdesk-panel" role="dialog" aria-modal="true" aria-labelledby="gffc-helpdesk-title" onclick="event.stopPropagation()">
                    <div class="gffc-helpdesk-header">
                        <div id="gffc-helpdesk-title" class="gffc-helpdesk-title">
                            <span class="gffc-helpdesk-icon dashicons dashicons-format-chat" aria-hidden="true"></span><span class="gffc-helpdesk-brand"><span>G</span><span class="gffc-helpdesk-brand-accent">A</span><span>R</span><span class="gffc-helpdesk-brand-accent">I</span></span> Help Agent
                        </div>
                        <button class="gffc-helpdesk-close" onclick="gffcCloseHelpdesk()" aria-label="Close help dialog">×</button>
                    </div>
                    <div class="gffc-helpdesk-body">
                        <!-- AI Helpdesk Chat Section -->
                        <div class="ai-helpdesk-section" style="margin: 0; padding: 0; background: transparent; border: none; border-radius: 0;">
                            <p style="color: #64748b; margin: 0 0 8px 0; font-size: 14px; background: rgba(241,245,249,0.8); border: 1px solid #e2e8f0; padding: 8px 12px; border-radius: 6px; line-height: 1.4; text-align: center;">AI-generated responses may not always be accurate. For critical questions, contact <a href="mailto:support@garidium.com" style="color: #3b82f6; font-weight: 600;">support@garidium.com</a></p>
                            
                            <div id="ai-chat-container" class="ai-chat-container">
                                <div id="ai-chat-messages" class="ai-chat-messages">
                                    <div class="ai-message ai-assistant-message">
                                        <div class="ai-message-content">
                                            How can I help you with FFL Cockpit today?
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="ai-chat-input-container">
                                    <textarea id="ai-question-input" class="ai-question-input" placeholder="Type your question here..." rows="2"></textarea>
                                    <button id="ai-ask-button" class="button button-primary ai-ask-button" onclick="askAIHelpdesk()">
                                        <span id="ai-ask-button-text">Ask</span>
                                        <span id="ai-ask-spinner" class="spinner" style="display: none; float: none; margin: 0 0 0 5px;"></span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <button class="accordion" style="display:none;" id="gffc_cart_accordion_btn">Cart <span id="gffc_cart_badge_mobile" style="display:inline-block; margin-left:6px; background:#dc3545; color:white; padding:1px 7px; border-radius:999px; font-size:11px; font-weight:700;">0</span></button>
            <div id="cart" class="tabcontent" style="display:none;">
                <div style="background: #fff; padding: 10px;">
                    <div class="helperDialog" style="margin: 0 0 12px 0; width: auto; padding: 8px; display: flex; justify-content: space-between; align-items: center;">
                        <span>Add items from <strong>Product Search</strong> to this FFL Cockpit Cart, then submit as a <strong>Drop Ship</strong> or <strong>Ship to Store</strong> order. Please note: <strong>This will not generate a WooCommerce order</strong>, it will just submit your order to the distributor(s).</span>
                        <button class="button" id="gffc_cart_clear_top_btn" onclick="gffcCartClear()" style="display:none;">Clear Cart</button>
                    </div>
                    <div id="gffc_gunbroker_cart_notice" style="display:none; margin: 0 0 12px 0; border: 1px solid #f59e0b; background: #fffbeb; color: #7c2d12; border-radius: 10px; padding: 10px 12px;"></div>
                    <div id="gffc_cart_root"></div>
                </div>
            </div>
            <style>
                @media screen and (max-width: 768px) {
                    /* Cockpit Key + Admin Functions: stack cleanly on mobile */
                    .gffc-key-admin-table {
                        margin-top: 100px;
                    }

                    .gffc-key-admin-table,
                    .gffc-key-admin-table tbody,
                    .gffc-key-admin-table tr,
                    .gffc-key-admin-table td {
                        display: block;
                        width: 100% !important;
                        box-sizing: border-box;
                    }

                    #gffc-cockpit-key-label {
                        width: auto !important;
                        margin: 0 0 8px 0;
                        font-size: 18px;
                        line-height: 1.2;
                    }

                    #g_ffl_cockpit_key_form {
                        display: block !important;
                        align-items: stretch !important;
                        width: 100% !important;
                    }

                    #g_ffl_cockpit_key {
                        width: 100% !important;
                        max-width: 100% !important;
                        box-sizing: border-box;
                    }

                    #set_key_form {
                        margin-left: 0 !important;
                        margin-top: 10px;
                        display: block;
                    }

                    #set_key_form input[type="submit"],
                    #set_key_form .button,
                    #set_key_form button {
                        width: 100% !important;
                        box-sizing: border-box;
                    }

                    /* Admin functions: full-width stacked buttons */
                    #g-ffl-admin-buttons {
                        margin: 12px 0 0 0 !important;
                        text-align: left !important;
                        width: 100% !important;
                    }

                    #g-ffl-admin-buttons a.button {
                        display: block;
                        width: 100% !important;
                        box-sizing: border-box;
                        margin: 10px 0 0 0;
                        text-align: center;
                    }

                    #g-ffl-admin-buttons b {
                        display: block;
                        margin-bottom: 6px;
                    }
                }
            </style>

            <table class="gffc-key-admin-table" style="width:100%;">
                <tr>
                    <td id="gffc-cockpit-key-label" style="width:150px;font-weight:bold;" scope="row">FFL Cockpit Key:</td>
                    <td>
                    <form method="post" action="options.php" style="display: flex; align-items: center;" id="g_ffl_cockpit_key_form">
                        <?php settings_fields('g-ffl-cockpit-settings'); ?>
                        <input oninput="document.getElementById('set_key_form').style.display='inline';" type="password" style="width: 350px;" name="g_ffl_cockpit_key" id="g_ffl_cockpit_key"  autocomplete="off" 
                            aria-describedby="login_error" class="input password-input" size="20"
                            value="<?php echo esc_attr($gFFLCockpitKey); ?>"/>
                        <span id="set_key_form" style="display: none; margin-left: 10px;">
                            <?php submit_button('Set Key', 'primary', 'confirm_set_key_button', false, array('id' => 'confirm_set_key_button_actual')); ?>
                        </span>
                    </form>
                    </td>
                    <td align="right">
                        <div id="g-ffl-admin-buttons" align="right" style="margin:20px;display:none;">
                            <div style="margin-bottom: 8px;">
                                <b>Admin Functions:&nbsp;</b>
                                <a class="button alt" onclick="handleLoadConfigClick();">Load Config</a>
                                <a class="button alt" id="admin_save_config_btn" onclick="handleAdminSaveClick();">Save</a>
                            </div>
                            <div id="admin_current_editing_key" style="color:red;display:none;"></div>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div id="categoryChangeModal" class="category_change_modal" style="display:none;">
            <div class="category_change_modal_content">
                <span class="category_change_modal_close" onclick="closeCategoryChangeModal()">&times;</span>
                <div>
                    <b>Product Category Change:</b>
                    <p><span style="color:red;font-weight:bold;">PLEASE READ BEFORE DOING ANYTHING</span> This will update the product category on your site AND the product category this product is associated with for <u><span style="color:red;">All Cockpit Fed Sites</span></u>. So <span style="color:red;">please make sure you are making changes that help everyone</span>. We track all changes made and who made the changes. <b>Changes are not immediate, and may take up to an hour to apply</b>.<u>Thank you</u> for your contribution, Gary.</p>
                    <input type="text" id="categoryChangeModalSearch" placeholder="Search categories..." style="width:450px; margin-bottom: 10px;"><br>
                    <div id="categoryList" style="width:450px; max-height: 200px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;"></div>
                    <button id="updateCategoryButton" style="width: 450px; margin-top: 10px;">Apply Category Update</button>
                </div>
            </div>
        </div>
        
        <!-- Checkout Confirmation Modal -->
        <div id="gffcCheckoutConfirmationModal" class="category_change_modal" style="display:none; z-index: 10000;">
            <div class="category_change_modal_content" style="width: 800px; max-width: 90%; max-height: 85vh; display: flex; flex-direction: column; padding: 0; overflow: hidden; border-radius: 8px;">
                <div style="padding: 16px 24px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center;">
                    <h3 style="margin: 0; font-size: 18px; color: #0f172a;">Confirm Order</h3>
                    <span class="category_change_modal_close" style="position: static; float: none; line-height: 1; margin: 0; color: #64748b;" onclick="document.getElementById('gffcCheckoutConfirmationModal').style.display='none'">&times;</span>
                </div>
                <div style="flex: 1; overflow: hidden; display: flex; flex-direction: column; padding: 16px 24px;">
                    <div id="gffcConfirmationContent" style="flex: 1; overflow-y: auto; margin-bottom: 0; padding-right: 5px;"></div>
                    <div style="display: flex; gap: 12px; justify-content: flex-end; padding-top: 20px; margin-top: 20px; border-top: 1px solid #e2e8f0;">
                        <button class="button" onclick="document.getElementById('gffcCheckoutConfirmationModal').style.display='none'">Cancel</button>
                        <button class="button button-primary" id="gffcConfirmOrderBtn">Submit Order</button>
                    </div>
                </div>
            </div>
        </div>
        <script>
            // Add event listener for search input
            document.getElementById("categoryChangeModalSearch").addEventListener("input", function() {
                    const filter = this.value.toLowerCase();
                    const labels = document.getElementById('categoryList').getElementsByTagName("label");
                    for (let i = 0; i < labels.length; i++) {
                        const text = labels[i].textContent.toLowerCase();
                        labels[i].style.display = text.includes(filter) ? "block" : "none";
                    }
                });

                async function handleLoadConfigClick() {
                try {
                    document.getElementById('configuration').style.border='solid red 3px';
                    initialCockpitConfiguration = null;
                    await reset_validated_distributors();
                    var _adminLoadKey = document.getElementById('g_ffl_cockpit_key').value;
                    get_and_set_cockpit_configuration(_adminLoadKey, true);
                    document.getElementById('admin_current_editing_key').innerHTML = 'Editing: ' + _adminLoadKey;document.getElementById('admin_current_editing_key').style.display='';
                    if (typeof window.gFFLCockpit !== 'undefined' && typeof window.gFFLCockpit.loadSiteHealth === 'function') {
                        window.gFFLCockpit.loadSiteHealth(null, _adminLoadKey);
                    }
                    document.getElementById('save_cockpit_configuration_button').style.display='none';
                    
                    // If on notifications tab, re-check email verification after config loads
                    setTimeout(function() {
                        const notificationsTab = document.getElementById('notifications-config-tab');
                        const notificationsPane = document.getElementById('notifications-config');
                        if ((notificationsTab && notificationsTab.classList.contains('active')) || 
                            (notificationsPane && notificationsPane.classList.contains('active'))) {
                            if (typeof window.gffcCheckEmailVerification === 'function') {
                                window.gffcEmailVerificationChecked = false;
                                window.gffcCheckEmailVerification();
                            }
                        }
                    }, 1500); // Delay to allow config to fully load
                } catch (error) {
                    console.error('Error during Load Config process:', error);
                }
            }
            
            async function handleAdminSaveClick() {
                const btn = document.getElementById('admin_save_config_btn');
                const originalText = btn.innerText;
                btn.innerText = 'Saving...';
                btn.style.pointerEvents = 'none';
                
                // Get modal elements
                const modal = document.getElementById('gffc_save_modal');
                const modalTitle = document.getElementById('gffc_save_modal_title');
                const modalIcon = document.getElementById('gffc_save_modal_icon');
                const modalProgress = document.getElementById('gffc_save_modal_progress');
                const modalMessage = document.getElementById('gffc_save_modal_message');
                const modalFooter = document.getElementById('gffc_save_modal_footer');
                
                // Helper to show the modal with result
                function showAdminSaveResult(result) {
                    modalProgress.style.display = 'none';
                    modalMessage.style.display = 'block';
                    modalFooter.style.display = 'block';
                    
                    let messageHtml = '';
                    
                    if (result.error_message) {
                        modalTitle.textContent = 'Save Failed';
                        modalIcon.innerHTML = '<span style="color: #dc3545; font-size: 24px;">✕</span>';
                        messageHtml += '<div class="gffc-save-error"><strong>Error:</strong> ' + result.error_message + '</div>';
                    } else if (result.no_changes) {
                        modalTitle.textContent = 'No Changes Detected';
                        modalIcon.innerHTML = '<span style="color: #2271b1; font-size: 24px;">ℹ</span>';
                        messageHtml += '<div class="gffc-save-info">No changes were detected in your configuration.</div>';
                    } else {
                        modalTitle.textContent = 'Changes Saved Successfully';
                        modalIcon.innerHTML = '<span style="color: #28a745; font-size: 24px;">✓</span>';
                        messageHtml += '<div class="gffc-save-success">Your FFL Cockpit configuration has been updated successfully.</div>';
                    }
                    
                    if (result.warning_message) {
                        messageHtml += '<div class="gffc-save-warning"><strong>Warning:</strong> ' + result.warning_message + '</div>';
                    }
                    
                    modalMessage.innerHTML = messageHtml;
                    modal.style.display = 'flex';
                }
                
                try {
                    const result = await setConfig(document.getElementById('g_ffl_cockpit_key').value);
                    
                    // Reset button state
                    btn.innerText = originalText;
                    btn.style.background = '';
                    btn.style.color = '';
                    btn.style.borderColor = '';
                    btn.style.pointerEvents = '';
                    
                    // Show result in modal
                    showAdminSaveResult(result);
                    
                    // Refresh editor on success
                    if (result.success) {
                        refreshEditor();
                    }
                } catch (error) {
                    console.error('Admin save error:', error);
                    
                    // Reset button state
                    btn.innerText = originalText;
                    btn.style.background = '';
                    btn.style.color = '';
                    btn.style.borderColor = '';
                    btn.style.pointerEvents = '';
                    
                    // Show error in modal
                    showAdminSaveResult({
                        success: false,
                        error_message: error.message || 'An unexpected error occurred. Please try again.'
                    });
                }
            }

        </script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const setKeyButton = document.getElementById('confirm_set_key_button_actual');
                if (setKeyButton) {
                    setKeyButton.addEventListener('click', function(event) {
                        event.preventDefault(); // Prevent default button action
                        if (confirm("Please confirm, Do you want to apply a new key?")) {
                            document.getElementById('g_ffl_cockpit_key_form').submit();
                        }
                    });
                }
            });
            
            // Ensure compatibility with other plugins that might need Select2
            jQuery(document).ready(function($) {
                // If Select2 is loaded but not available on window, make it global
                if (typeof $.fn.select2 !== 'undefined' && typeof window.Select2 === 'undefined') {
                    window.Select2 = $.fn.select2;
                }
            });
            
            // Function to show description tabs in test results
            function showDescriptionTab(productIndex, tabType) {
                // Remove active class from all tabs for this product
                const tabButtons = document.querySelectorAll(`#tab-${productIndex} .description-tab-btn`);
                const tabPanes = document.querySelectorAll(`#tab-${productIndex} .description-tab-pane`);
                
                tabButtons.forEach(btn => btn.classList.remove('active'));
                tabPanes.forEach(pane => pane.classList.remove('active'));
                
                // Add active class to selected tab and pane
                const activeButton = document.querySelector(`#tab-${productIndex} [onclick*="${tabType}"]`);
                const activePane = document.getElementById(`desc-${tabType}-${productIndex}`);
                
                if (activeButton) activeButton.classList.add('active');
                if (activePane) activePane.classList.add('active');
            }
        </script>


    <?php }
}
