<?php

/**
 * Plugin Name: Peligent AI Assistant
 * Description: AI Assistant for Wordpress Site Owner
 * Version: 1.7.11
 * Author: Peligent
 * Plugin Icon: https://app.peligent.com/peligent-icon-only-transparent.png
 * Requires at least: 5.8
 * Tested up to: 6.9
 * Requires PHP: 7.4
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: peligent-ai-assistant
 * Requires Plugins: woocommerce
 */

if (! defined('ABSPATH')) {
    exit;
}

class Peligent_For_WooCommerce_Plugin
{
    const OPTION_KEY         = 'peligent_wc_last_key';
    const OPTION_APP_USER    = 'peligent_wc_app_user';
    const OPTION_CONNECT_KEY = 'peligent_wc_connect_token';
    const OPTION_SITE_TOKEN  = 'peligent_site_token';
    const OPTION_ALLOWED_USERS = 'peligent_allowed_users';
    const OPTION_ONBOARDING_COMPLETED = 'peligent_wc_onboarding_completed';
    const OPTION_LAST_CONNECT_ERROR = 'peligent_wc_last_connect_error';
    const OPTION_ONBOARDING_PROFILE = 'peligent_wc_onboarding_profile';
    const OPTION_ASSISTANT_DEFAULTS = 'peligent_wc_assistant_defaults';
    const OPTION_PARTNER_ID   = 'peligent_wc_partner_id';

    const PELIGENT_ENDPOINT  = 'https://app.peligent.com/api/integrations/woocommerce/connect';
    const PELIGENT_ONBOARDING_ENDPOINT = 'https://app.peligent.com/api/integrations/woocommerce/onboarding';
    const PELIGENT_INSTALL_NOTIFICATION_ENDPOINT = 'https://app.peligent.com/api/integrations/woocommerce/install-notification';
    const PELIGENT_PROFILE_STATUS_ENDPOINT = 'https://app.peligent.com/api/integrations/woocommerce/profile-status';
    const PELIGENT_PROFILE_SETTINGS_ENDPOINT = 'https://app.peligent.com/api/client/profile-settings';

    private function log_debug($message)
    {
        if (! defined('WP_DEBUG') || ! WP_DEBUG) {
            return;
        }

        if (function_exists('wc_get_logger')) {
            wc_get_logger()->debug($message, array('source' => 'peligent-ai-assistant'));
        }
    }

    public function __construct()
    {
        register_activation_hook(__FILE__, array($this, 'on_activation'));
        register_deactivation_hook(__FILE__, array($this, 'on_deactivation'));
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'add_settings_link'));
        add_action('admin_init', array($this, 'maybe_redirect_to_settings'));
        add_action('admin_notices', array($this, 'maybe_show_woocommerce_notice'));
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_post_peligent_wc_regen', array($this, 'handle_regenerate'));
        add_action('admin_post_peligent_wc_revoke', array($this, 'handle_revoke'));
        add_action('admin_post_peligent_wc_regen_appuser', array($this, 'handle_regenerate_app_user'));
        add_action('admin_post_peligent_wc_revoke_appuser', array($this, 'handle_revoke_app_user'));
        add_action('admin_post_peligent_wc_save_token', array($this, 'handle_save_connect_token'));
        add_action('admin_post_peligent_wc_send_peligent', array($this, 'handle_send_to_peligent'));
        add_action('admin_post_peligent_save_allowed_users', array($this, 'handle_save_allowed_users'));
        add_action('admin_post_peligent_wc_save_assistant_defaults', array($this, 'handle_save_assistant_defaults'));
        add_action('admin_enqueue_scripts', array($this, 'admin_assets'));
        add_action('admin_footer', array($this, 'render_sidebar_on_all_pages'));
        add_action('admin_head', array($this, 'inject_console_filter'));
        // Content generation modal is now handled in React sidebar, no need for HTML modal
        add_action('admin_bar_menu', array($this, 'add_admin_bar_chat_icon'), 100);
        add_action('wp_dashboard_setup', array($this, 'add_pulse_dashboard_widget'));
        // Ensure Application Passwords UI is available even on non-HTTPS setups
        add_filter('wp_is_application_passwords_available', array($this, 'force_enable_application_passwords'));
        add_filter('wp_is_application_passwords_available_for_user', array($this, 'force_enable_application_passwords_for_user'), 10, 2);
        // Add a fallback section on the user profile page to display the generated app password
        add_action('show_user_profile', array($this, 'render_app_passwords_profile_section'));
        add_action('edit_user_profile', array($this, 'render_app_passwords_profile_section'));
        // Ensure previously created app user has Administrator role and needed caps
        add_action('init', array($this, 'ensure_app_user_admin_role'));
        // Register REST API endpoint for overview data
        add_action('rest_api_init', array($this, 'register_overview_endpoint'));
        // Add Peligent buttons to product description fields
        add_action('woocommerce_product_options_general_product_data', array($this, 'add_peligent_content_buttons'));
        add_action('woocommerce_product_after_variable_attributes', array($this, 'add_peligent_content_buttons'));
        // Add buttons next to Add Media button in editor
        add_action('media_buttons', array($this, 'add_peligent_media_buttons'), 11);
        // Webhook handlers for indexing
        add_action('wp_ajax_peligent_poll_profile', array($this, 'ajax_poll_profile'));
        add_action('wp_ajax_peligent_trigger_profile', array($this, 'ajax_trigger_profile'));
        add_action('wp_ajax_peligent_save_app_password', array($this, 'ajax_save_app_password'));
        add_action('wp_ajax_peligent_connect', array($this, 'ajax_connect'));
        add_action('wp_ajax_peligent_save_assistant_defaults', array($this, 'ajax_save_assistant_defaults'));
        add_action('wp_ajax_peligent_save_allowed_users', array($this, 'ajax_save_allowed_users'));
        add_action('wp_ajax_peligent_reset_onboarding', array($this, 'ajax_reset_onboarding'));
        add_action('wp_ajax_peligent_enable_advanced_features', array($this, 'ajax_enable_advanced_features'));
        add_action('wp_ajax_peligent_toggle_floating_widget', array($this, 'ajax_toggle_floating_widget'));
        add_action('woocommerce_new_product', array($this, 'send_product_webhook'), 10, 1);
        add_action('woocommerce_update_product', array($this, 'send_product_webhook'), 10, 1);
        add_action('woocommerce_delete_product', array($this, 'send_product_delete_webhook'), 10, 1);
        add_action('woocommerce_new_order', array($this, 'send_order_webhook'), 10, 1);
        add_action('woocommerce_update_order', array($this, 'send_order_webhook'), 10, 1);
    }

    /**
     * Generate a 24-character password grouped as six blocks of four separated by spaces,
     * using only [a-zA-Z0-9], ensuring at least one lowercase, one uppercase, and one digit overall.
     */
    private function generate_grouped_password()
    {
        $lower = 'abcdefghijklmnopqrstuvwxyz';
        $upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $digits = '0123456789';
        $all = $lower . $upper . $digits;

        $chars = array();
        // Ensure diversity across the whole password
        $chars[] = $lower[wp_rand(0, strlen($lower) - 1)];
        $chars[] = $upper[wp_rand(0, strlen($upper) - 1)];
        $chars[] = $digits[wp_rand(0, strlen($digits) - 1)];

        for ($i = 3; $i < 24; $i++) {
            $chars[] = $all[wp_rand(0, strlen($all) - 1)];
        }

        // Shuffle to distribute the ensured characters
        shuffle($chars);

        // Insert spaces every 4 chars: 4-4-4-4-4-4
        $password = '';
        for ($i = 0; $i < 24; $i++) {
            $password .= $chars[$i];
            if ($i % 4 === 3 && $i < 23) {
                $password .= ' ';
            }
        }

        return $password;
    }

    /**
     * Force-enable WordPress Application Passwords feature only when the
     * Peligent app user needs it AND the site is served over HTTPS.
     */
    public function force_enable_application_passwords($available)
    {
        $app = get_option(self::OPTION_APP_USER);
        if (!empty($app['user_id']) && is_ssl()) {
            return true;
        }
        return $available;
    }

    /**
     * Force-enable Application Passwords only for the Peligent-managed app user.
     */
    public function force_enable_application_passwords_for_user($available, $user)
    {
        $app = get_option(self::OPTION_APP_USER);
        if (!empty($app['user_id']) && $user && (int) $user->ID === (int) $app['user_id']) {
            return true;
        }
        return $available;
    }

    /**
     * Render a small read-only section on the user edit/profile page to show
     * the generated application password for the special app user, in case the
     * core UI is hidden by another plugin/policy.
     */
    public function render_app_passwords_profile_section($user)
    {
        if (! $user || ! isset($user->ID)) {
            return;
        }

        $app = get_option(self::OPTION_APP_USER);
        if (empty($app) || empty($app['user_id']) || (int) $app['user_id'] !== (int) $user->ID) {
            return; // Only show for our generated app user
        }

        echo '<h2>Peligent Application Password</h2>';
        echo '<table class="form-table" role="presentation"><tbody>';
        if (! empty($app['app_password'])) {
            echo '<tr><th><label>Application Password</label></th><td><code>' . esc_html($app['app_password']) . '</code><p class="description">Saved when the user was created. Regenerate from WooCommerce → Auto API Keys.</p></td></tr>';
        } else if (! empty($app['raw_user_password'])) {
            echo '<tr><th><label>Initial Password</label></th><td><code>' . esc_html($app['raw_user_password']) . '</code><p class="description">Used as a fallback when Application Passwords are unavailable.</p></td></tr>';
        } else {
            echo '<tr><th><label>Status</label></th><td><p>No stored password available. Regenerate from WooCommerce → Auto API Keys.</p></td></tr>';
        }
        if (! empty($app['app_password_label'])) {
            echo '<tr><th><label>Label</label></th><td>' . esc_html($app['app_password_label']) . '</td></tr>';
        }
        echo '</tbody></table>';
    }

    /**
     * Ensure the stored app user has only the specific capabilities needed
     * for the plugin to operate (media, products, user listing).
     * Does NOT force-elevate to administrator role.
     */
    public function ensure_app_user_admin_role()
    {
        $app = get_option(self::OPTION_APP_USER);
        if (empty($app) || empty($app['user_id'])) {
            return;
        }
        $user_id = (int) $app['user_id'];
        $user = get_user_by('id', $user_id);
        if (! $user) {
            return;
        }

        $wp_user = new WP_User($user_id);

        // If the user was previously created as administrator, downgrade to limited role
        if (in_array('administrator', $wp_user->roles, true)) {
            $wp_user->set_role('');
        }

        // Only grant the minimum capabilities the plugin actually requires.
        // Does NOT elevate to administrator role.
        $required_caps = array(
            'read',
            'upload_files',
            'edit_posts',
            'edit_others_posts',
            'publish_posts',
            'edit_published_posts',
            'edit_others_published_posts',
            'list_users',
            'manage_woocommerce',
            'edit_products',
            'publish_products',
            'edit_published_products',
        );

        foreach ($required_caps as $cap) {
            if (! $wp_user->has_cap($cap)) {
                $wp_user->add_cap($cap);
            }
        }
    }

    private function add_admin_notice($message, $type = 'updated')
    {
        set_transient('peligent_wc_message', array('type' => $type, 'text' => $message), 30);
    }

    public function on_activation()
    {
        // Require WooCommerce to be active
        if (! class_exists('WooCommerce') && ! class_exists('WC_Auth')) {
            set_transient('peligent_wc_missing_notice', true, 30);
            if (! function_exists('deactivate_plugins')) {
                require_once ABSPATH . 'wp-admin/includes/plugin.php';
            }
            deactivate_plugins(plugin_basename(__FILE__));
            return;
        }

        // Only create keys if not already connected — re-creating keys breaks the connection
        $existing_token = get_option(self::OPTION_SITE_TOKEN, '');
        $existing_key = get_option(self::OPTION_KEY, array());
        $has_valid_key = is_array($existing_key) && !empty($existing_key['consumer_key']) && empty($existing_key['error']);

        if (!empty($existing_token) && $has_valid_key) {
            $this->log_debug('Activation: already connected — skipping key regeneration');
        } elseif (! class_exists('WC_Auth')) {
            update_option(self::OPTION_KEY, array('error' => 'WooCommerce is not active or WC_Auth class missing.'));
        } else {
            $created = $this->create_key_programmatically(array(
                'app_name' => 'Auto-generated by WC Auto Keygen',
                'user_id'  => get_current_user_id() ?: 1,
                'scope'    => 'read_write',
            ));

            if (is_wp_error($created)) {
                update_option(self::OPTION_KEY, array('error' => $created->get_error_message()));
            } else {
                update_option(self::OPTION_KEY, $created);
            }
        }

        $existing_app = get_option(self::OPTION_APP_USER, array());
        $has_valid_app = is_array($existing_app) && !empty($existing_app['user_id']) && empty($existing_app['error']);

        if (!empty($existing_token) && $has_valid_app) {
            $this->log_debug('Activation: already connected — skipping app user regeneration');
        } else {
            $app = $this->create_app_user_and_password();
            if (is_wp_error($app)) {
                update_option(self::OPTION_APP_USER, array('error' => $app->get_error_message()));
            } else {
                update_option(self::OPTION_APP_USER, $app);
            
                // Auto-send credentials to Peligent if connect token exists (from activation or later)
                // This will be called later when connect token is set, but we prepare the credentials now
            }
        }

        // Add current user to allowed users list on first activation
        $current_user_id = get_current_user_id();
        if ($current_user_id) {
            $allowed_users = get_option(self::OPTION_ALLOWED_USERS, array());
            if (!is_array($allowed_users)) {
                $allowed_users = array();
            }
            if (!in_array($current_user_id, array_map('intval', $allowed_users), true)) {
                $allowed_users[] = $current_user_id;
                update_option(self::OPTION_ALLOWED_USERS, $allowed_users);
            }
        }

        // Flag for one-time redirect to settings page after activation
        update_option('peligent_wc_activation_redirect', true);
    }

    /**
     * Notify Peligent dashboard when plugin is deactivated.
     * Uses a short timeout since this runs during deactivation.
     */
    public function on_deactivation()
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }

        $disconnect_url = str_replace('/connect', '/disconnect', self::PELIGENT_ENDPOINT);

        $payload = array(
            'site_token' => $site_token,
            'reason'     => 'plugin_deactivated',
            'site_url'   => home_url('/'),
            'site_name'  => get_bloginfo('name'),
            'timestamp'  => current_time('mysql'),
        );

        $this->log_debug('Sending deactivation notification: ' . wp_json_encode($payload));

        wp_remote_post($disconnect_url, array(
            'headers'   => array(
                'Content-Type'          => 'application/json',
                'X-Peligent-Site-Token' => $site_token,
            ),
            'body'      => wp_json_encode($payload),
            'timeout'   => 5,
            'blocking'  => true,
            'sslverify' => true,
        ));
    }

    public function maybe_show_woocommerce_notice()
    {
        if (! current_user_can('activate_plugins')) {
            return;
        }
        if (get_transient('peligent_wc_missing_notice')) {
            delete_transient('peligent_wc_missing_notice');
            echo '<div class="notice notice-error"><p>' . esc_html__('Peligent AI Assistant requires the WooCommerce plugin to be installed and active.', 'peligent-ai-assistant') . '</p></div>';
        }
    }

    public function maybe_redirect_to_settings()
    {
        if (! is_admin()) {
            return;
        }
        if (! current_user_can('manage_options')) {
            return;
        }
        if (defined('WP_CLI') && WP_CLI) {
            return; // skip in CLI
        }
        if (wp_doing_ajax()) {
            return;
        }
        $should_redirect = get_option('peligent_wc_activation_redirect', false);
        if (! $should_redirect) {
            return;
        }
        // Avoid redirect during network or bulk activation
        $activate_multi = filter_input(INPUT_GET, 'activate-multi', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        if (null !== $activate_multi) {
            delete_option('peligent_wc_activation_redirect');
            return;
        }
        delete_option('peligent_wc_activation_redirect');
        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    protected function create_key_programmatically($data)
    {
        if (! class_exists('WC_Auth')) {
            return new WP_Error('no_wc_auth', 'WC_Auth class not found. Is WooCommerce active?');
        }

        try {
            if (! is_user_logged_in()) {
                return new WP_Error('not_logged_in', 'Must be logged in as an admin to generate the key.');
            }

            $wc_auth = new WC_Auth();
            $method = new ReflectionMethod($wc_auth, 'create_keys');
            $method->setAccessible(true);

            $app_name = isset($data['app_name']) ? $data['app_name'] : 'Auto app';
            $user_id  = isset($data['user_id']) ? (int) $data['user_id'] : get_current_user_id();
            $scope    = isset($data['scope']) ? $data['scope'] : 'read';

            $result = $method->invoke($wc_auth, $app_name, $user_id, $scope);

            if (is_array($result)) {
                $result['generated_at'] = current_time('mysql');
                return $result;
            }

            return new WP_Error('create_failed', 'Key generation returned unexpected result.');
        } catch (Exception $e) {
            return new WP_Error('exception', $e->getMessage());
        }
    }

    protected function create_app_user_and_password($auto_create_app_password = false)
    {
        $stored = get_option(self::OPTION_APP_USER);
        if ($stored && ! empty($stored['user_id']) && get_user_by('id', $stored['user_id'])) {
            return $stored;
        }

        $time  = time();
        $login = 'wc_api_app_' . $time;
        $pass  = wp_generate_password(24, true, true);
        $email = 'wc-api-app+' . $time . '@example.local';

        $user_id = wp_create_user($login, $pass, $email);
        if (is_wp_error($user_id)) {
            return $user_id;
        }

        $user = new WP_User($user_id);
        $user->set_role('');
        $required_caps = array(
            'read',
            'upload_files',
            'edit_posts',
            'edit_others_posts',
            'publish_posts',
            'edit_published_posts',
            'edit_others_published_posts',
            'list_users',
            'manage_woocommerce',
            'edit_products',
            'publish_products',
            'edit_published_products',
        );
        foreach ($required_caps as $cap) {
            $user->add_cap($cap);
        }

        $out = array(
            'user_id'           => $user_id,
            'user_login'        => $login,
            'user_email'        => $email,
            'app_password'      => '',
            'created_at'        => current_time('mysql'),
        );

        // Auto-create application password if requested
        if ($auto_create_app_password && class_exists('WP_Application_Passwords')) {
            $app_pass_result = WP_Application_Passwords::create_new_application_password(
                $user_id,
                array('name' => 'Peligent AI Assistant')
            );
            if (!is_wp_error($app_pass_result) && !empty($app_pass_result[0])) {
                $out['app_password'] = $app_pass_result[0]; // plaintext, available only at creation
                $out['app_password_label'] = 'Peligent AI Assistant';
            }
        }

        update_option(self::OPTION_APP_USER, $out);
        return $out;
    }

    public function add_settings_link($links)
    {
        $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=peligent-connect')) . '">' . esc_html__('Settings', 'peligent-ai-assistant') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    public function add_admin_menu()
    {
        // SVG sparkle icon for WP admin menu (20x20 viewBox, black fill – WP handles colorizing)
        $icon_svg = 'data:image/svg+xml;base64,' . base64_encode(
            '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M10 0Q10 10 0 10Q10 10 10 20Q10 10 20 10Q10 10 10 0Z" fill="black"/></svg>'
        );

        add_menu_page(
            'Peligent',
            'Peligent',
            'manage_options',
            'peligent-connect',
            array($this, 'render_admin_page'),
            $icon_svg,
            58
        );

        // "Settings" submenu (same slug as parent replaces auto-generated first item)
        add_submenu_page('peligent-connect', 'Settings - Peligent', 'Settings', 'manage_options', 'peligent-connect', array($this, 'render_admin_page'));

        // Iframe submenus
        add_submenu_page('peligent-connect', 'Bulk Update - Peligent', 'Bulk Update', 'manage_options', 'peligent-bulk-update', array($this, 'render_bulk_update_page'));
        add_submenu_page('peligent-connect', 'Blog Update - Peligent', 'Blog Update', 'manage_options', 'peligent-blog-update', array($this, 'render_blog_update_page'));
        add_submenu_page('peligent-connect', 'Action History - Peligent', 'Action History', 'manage_options', 'peligent-action-history', array($this, 'render_action_history_page'));
        add_submenu_page('peligent-connect', 'Bots - Peligent', 'Bots', 'manage_options', 'peligent-bots', array($this, 'render_bots_page'));
        add_submenu_page('peligent-connect', 'Reports - Peligent', 'Reports', 'manage_options', 'peligent-reports', array($this, 'render_reports_page'));
        add_submenu_page('peligent-connect', 'Integrations - Peligent', 'Integrations', 'manage_options', 'peligent-integrations', array($this, 'render_integrations_page'));
    }

    /**
     * Render a full-width iframe page for a Peligent dashboard route.
     */
    private function render_iframe_page($route, $title)
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            echo '<div class="wrap" style="max-width:600px;margin:40px auto;">';
            echo '<div style="background:#fff;border:1px solid #e5e7eb;border-radius:12px;padding:40px;text-align:center;box-shadow:0 1px 3px rgba(0,0,0,0.1);">';
            echo '<div style="margin-bottom:16px;">';
            echo '<img src="' . esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__)) . '" alt="Peligent" width="48" height="48" style="opacity:0.6;">';
            echo '</div>';
            echo '<h2 style="margin:0 0 8px;color:#111827;font-size:20px;">' . esc_html__('Connection Required', 'peligent-ai-assistant') . '</h2>';
            echo '<p style="color:#6b7280;margin:0 0 24px;font-size:15px;">' . esc_html__('Please connect your store to Peligent before using this feature.', 'peligent-ai-assistant') . '</p>';
            echo '<a href="' . esc_url(admin_url('admin.php?page=peligent-connect')) . '" class="button button-primary" style="padding:8px 24px;font-size:14px;">';
            echo '<span class="dashicons dashicons-admin-links" style="margin-top:3px;"></span> ';
            echo esc_html__('Go to Settings', 'peligent-ai-assistant');
            echo '</a>';
            echo '</div>';
            echo '</div>';
            return;
        }

        $origin = 'https://app.peligent.com';
        $embed_url = trailingslashit($origin) . 'frontend/dashboard/' . $route . '?embed=true';
        $icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
        $settings_url = admin_url('admin.php?page=peligent-connect');

        echo '<div class="peligent-iframe-wrap">';
        // Loading overlay shown until iframe loads or timeout
        echo '<div id="peligent-iframe-loading" style="position:absolute;inset:0;z-index:10;background:#f9fafb;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;">';
        echo '<div class="peligent-analyzing-spinner" style="width:32px;height:32px;border:3px solid #e5e7eb;border-top-color:#2563eb;border-radius:50%;animation:peligent-spin 0.8s linear infinite;"></div>';
        echo '<p style="color:#6b7280;font-size:14px;margin:0;">' . esc_html__('Loading...', 'peligent-ai-assistant') . '</p>';
        echo '</div>';
        // Error overlay (hidden by default)
        echo '<div id="peligent-iframe-error" style="display:none;position:absolute;inset:0;z-index:10;background:#f9fafb;flex-direction:column;align-items:center;justify-content:center;gap:12px;text-align:center;padding:40px;">';
        echo '<img src="' . esc_url($icon_url) . '" alt="Peligent" width="48" height="48" style="opacity:0.5;">';
        echo '<h3 style="margin:0;color:#111827;font-size:18px;font-weight:600;">' . esc_html__('Unable to load this page', 'peligent-ai-assistant') . '</h3>';
        echo '<p style="margin:0;color:#6b7280;font-size:14px;max-width:400px;line-height:1.5;">' . esc_html__('The page could not be loaded. This may be a temporary issue or your session may have expired.', 'peligent-ai-assistant') . '</p>';
        echo '<div style="display:flex;gap:10px;margin-top:8px;">';
        echo '<button onclick="location.reload();" class="button button-primary" style="padding:8px 20px;font-size:13px;">' . esc_html__('Retry', 'peligent-ai-assistant') . '</button>';
        echo '<a href="' . esc_url($settings_url) . '" class="button" style="padding:8px 20px;font-size:13px;">' . esc_html__('Go to Settings', 'peligent-ai-assistant') . '</a>';
        echo '</div>';
        echo '</div>';
        echo '<iframe id="peligent-iframe-content" src="' . esc_url($embed_url) . '" referrerpolicy="strict-origin-when-cross-origin" allow="microphone" style="opacity:0;transition:opacity 0.3s;"></iframe>';
        echo '</div>';
        echo '<style>@keyframes peligent-spin{to{transform:rotate(360deg)}}</style>';
        echo '<script>';
        echo '(function(){';
        echo '  var iframe=document.getElementById("peligent-iframe-content");';
        echo '  var loading=document.getElementById("peligent-iframe-loading");';
        echo '  var error=document.getElementById("peligent-iframe-error");';
        echo '  var loaded=false;';
        // On successful load, hide loading overlay and show iframe
        echo '  var siteToken=' . wp_json_encode($site_token) . ';';
        echo '  var origin="https://app.peligent.com";';
        echo '  function sendTokenToIframe(){try{iframe.contentWindow.postMessage({type:"PELIGENT_AI_TOKEN",token:siteToken},origin);}catch(e){}}';
        echo '  iframe.addEventListener("load",function(){';
        echo '    loaded=true;';
        echo '    if(loading)loading.style.display="none";';
        echo '    if(error)error.style.display="none";';
        echo '    iframe.style.opacity="1";';
        echo '    sendTokenToIframe();';
        echo '    var retries=0;var tid=setInterval(function(){if(++retries>15){clearInterval(tid);return;}sendTokenToIframe();},400);';
        echo '    window.addEventListener("message",function(ev){if(ev.origin===origin&&ev.data&&ev.data.type==="PELIGENT_AI_ACK"){clearInterval(tid);}});';
        echo '  });';
        // Timeout: if not loaded after 15s, show error
        echo '  setTimeout(function(){';
        echo '    if(!loaded){';
        echo '      if(loading)loading.style.display="none";';
        echo '      if(error)error.style.display="flex";';
        echo '    }';
        echo '  },15000);';
        echo '})();';
        echo '</script>';
    }

    public function render_bulk_update_page()
    {
        $this->render_iframe_page('bulk-update', 'Bulk Update');
    }

    public function render_blog_update_page()
    {
        $this->render_iframe_page('blog-update', 'Blog Update');
    }

    public function render_action_history_page()
    {
        $this->render_iframe_page('action-history', 'Action History');
    }

    public function render_bots_page()
    {
        $this->render_iframe_page('bots', 'Bots');
    }

    public function render_reports_page()
    {
        $this->render_iframe_page('report', 'Reports');
    }

    public function render_integrations_page()
    {
        $this->render_iframe_page('integrations', 'Integrations');
    }

    /**
     * Register Peligent Insights dashboard widget.
     */
    public function add_pulse_dashboard_widget()
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) return;
        if (!$this->is_user_allowed()) return;

        wp_add_dashboard_widget(
            'peligent_pulse_widget',
            '✦ Peligent AI Insights',
            array($this, 'render_pulse_widget')
        );
    }

    /**
     * Render Peligent Insights dashboard widget content.
     */
    public function render_pulse_widget()
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            echo '<p style="color:#6b7280;">Connect your site to Peligent to see insights.</p>';
            return;
        }

        // Check transient cache first (5 min)
        $cache_key = 'peligent_pulse_' . substr(md5($site_token), 0, 12);
        $cached = get_transient($cache_key);

        if ($cached === false) {
            // Fetch from API
            $response = wp_remote_get('https://app.peligent.com/api/wpai/sites/pulse', array(
                'headers' => array(
                    'x-site-token' => $site_token,
                    'Accept' => 'application/json',
                ),
                'timeout' => 10,
            ));

            if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
                echo '<p style="color:#6b7280;font-size:13px;">Unable to load insights. <a href="' . esc_url(admin_url('admin.php?page=peligent-connect')) . '">Check connection</a></p>';
                return;
            }

            $cached = wp_remote_retrieve_body($response);
            set_transient($cache_key, $cached, 300); // 5 min cache
        }

        $data = json_decode($cached, true);
        $insights = isset($data['insights']) ? $data['insights'] : (is_array($data) ? $data : array());

        if (empty($insights)) {
            echo '<div style="text-align:center;padding:16px 0;">';
            echo '<p style="color:#6b7280;font-size:13px;margin:0;">No new insights</p>';
            echo '<p style="color:#9ca3af;font-size:12px;margin:4px 0 0;">Set up <a href="' . esc_url(admin_url('admin.php?page=peligent-bots')) . '">automated bots</a> to get proactive insights.</p>';
            echo '</div>';
            return;
        }

        echo '<style>';
        echo '.peligent-pulse-card{display:flex;gap:10px;padding:10px 12px;border:1px solid #e5e7eb;border-radius:8px;margin-bottom:8px;background:#fff;transition:border-color .2s;}';
        echo '.peligent-pulse-card:hover{border-color:#93c5fd;}';
        echo '.peligent-pulse-icon{flex-shrink:0;width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;}';
        echo '.peligent-pulse-icon.bot{background:#eff6ff;color:#3b82f6;}';
        echo '.peligent-pulse-icon.sync{background:#fef3c7;color:#d97706;}';
        echo '.peligent-pulse-icon.metric{background:#ecfdf5;color:#059669;}';
        echo '.peligent-pulse-body{flex:1;min-width:0;}';
        echo '.peligent-pulse-title{font-size:13px;font-weight:600;color:#1f2937;margin:0 0 2px;}';
        echo '.peligent-pulse-summary{font-size:12px;color:#6b7280;margin:0;line-height:1.4;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}';
        echo '.peligent-pulse-ask{display:inline-flex;align-items:center;gap:4px;font-size:11px;color:#3b82f6;cursor:pointer;border:none;background:none;padding:2px 0;margin-top:4px;}';
        echo '.peligent-pulse-ask:hover{color:#2563eb;text-decoration:underline;}';
        echo '</style>';

        $icon_map = array(
            'bot_report' => array('icon' => '🤖', 'class' => 'bot'),
            'sync_warning' => array('icon' => '🔄', 'class' => 'sync'),
            'metric_change' => array('icon' => '📊', 'class' => 'metric'),
        );

        foreach (array_slice($insights, 0, 5) as $insight) {
            $type = isset($insight['type']) ? $insight['type'] : 'bot_report';
            $icon_info = isset($icon_map[$type]) ? $icon_map[$type] : $icon_map['bot_report'];
            $title = esc_html(isset($insight['title']) ? $insight['title'] : 'Insight');
            $summary = esc_html(isset($insight['summary']) ? substr($insight['summary'], 0, 200) : '');
            $prompt = esc_attr(isset($insight['suggestedPrompt']) ? $insight['suggestedPrompt'] : '');

            echo '<div class="peligent-pulse-card">';
            echo '<div class="peligent-pulse-icon ' . esc_attr($icon_info['class']) . '">' . $icon_info['icon'] . '</div>';
            echo '<div class="peligent-pulse-body">';
            echo '<p class="peligent-pulse-title">' . $title . '</p>';
            echo '<p class="peligent-pulse-summary">' . $summary . '</p>';
            if ($prompt) {
                echo '<button class="peligent-pulse-ask" onclick="peligentAskAI(&quot;' . esc_js($prompt) . '&quot;)">💬 Ask AI about this</button>';
            }
            echo '</div>';
            echo '</div>';
        }

        // JS to open sidebar and send prompt
        echo '<script>';
        echo 'function peligentAskAI(prompt){';
        echo '  var sidebar=document.querySelector(".peligent-ai-fixed-sidebar");';
        echo '  if(sidebar&&sidebar.classList.contains("peligent-ai-hidden")){';
        echo '    sidebar.classList.remove("peligent-ai-hidden");';
        echo '    document.body.classList.add("peligent-sidebar-open");';
        echo '  }';
        echo '  if(typeof window._peligentPendingPrompt!=="undefined"){';
        echo '    window._peligentPendingPrompt=prompt;';
        echo '  }else{';
        echo '    window._peligentPendingPrompt=prompt;';
        echo '  }';
        echo '  var iframe=sidebar?sidebar.querySelector("iframe.peligent-ai-iframe"):null;';
        echo '  if(iframe&&iframe.contentWindow){';
        echo '    try{iframe.contentWindow.postMessage({type:"PELIGENT_AI_PROMPT",prompt:prompt},"https://app.peligent.com");}catch(e){}';
        echo '  }';
        echo '}';
        echo '</script>';
    }

    private function maybe_render_notice()
    {
        $notice = get_transient('peligent_wc_message');
        if (! $notice) {
            return;
        }
            delete_transient('peligent_wc_message');
        $class = $notice['type'] === 'error' ? 'notice notice-error' : 'notice notice-success';
        echo '<div class="' . esc_attr($class) . '"><p>' . esc_html($notice['text']) . '</p></div>';
    }


    public function render_admin_page()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }

        $stored   = get_option(self::OPTION_KEY);
        $app      = get_option(self::OPTION_APP_USER);
        $connect  = get_option(self::OPTION_CONNECT_KEY, '');
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        $site_url = home_url('/');
        $site_name = get_bloginfo('name');
        $last_connect_error = get_option(self::OPTION_LAST_CONNECT_ERROR, '');
        $assistant_defaults = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        if (!is_array($assistant_defaults)) {
            $assistant_defaults = array();
        }

        // Check connection status
        $has_consumer_key = !empty($stored['consumer_key']) && !empty($stored['consumer_secret']) && empty($stored['error']);
        $has_app_user = !empty($app['user_login']) && empty($app['error']);
        $has_connect_secret = !empty($connect);
        $credentials_sent = !empty($app['credentials_sent']);
        $is_connected = !empty($site_token) && ($credentials_sent || ($has_consumer_key && $has_connect_secret));
        $onboarding_completed = get_option(self::OPTION_ONBOARDING_COMPLETED, false);

        // Auto-complete onboarding for existing installs that already have defaults set
        if ($is_connected && !empty($assistant_defaults) && !$onboarding_completed) {
            update_option(self::OPTION_ONBOARDING_COMPLETED, true);
            $onboarding_completed = true;
        }

        // Route: settings page vs wizard
        if ($is_connected && $onboarding_completed) {
            $this->render_settings_page();
        } else {
            $this->render_wizard();
        }
    }

    /**
     * Render the settings page (post-onboarding).
     */
    private function render_settings_page()
    {
        $stored   = get_option(self::OPTION_KEY);
        $app      = get_option(self::OPTION_APP_USER);
        $connect  = get_option(self::OPTION_CONNECT_KEY, '');
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        $site_url = home_url('/');
        $site_name = get_bloginfo('name');
        $assistant_defaults = $this->fetch_profile_settings();
        $partner_id = get_option(self::OPTION_PARTNER_ID, '');
        $has_app_password = !empty($app['app_password']);
        $credentials_sent = !empty($app['credentials_sent']);
        $app_user_login = !empty($app['user_login']) ? $app['user_login'] : '';
        $app_user_id = !empty($app['user_id']) ? (int) $app['user_id'] : 0;
        $app_user_edit_url = $app_user_id ? admin_url('user-edit.php?user_id=' . $app_user_id . '#application-passwords-section') : '';

        // Validate that the app user still exists in WordPress
        $advanced_features_error = '';
        if (($has_app_password || $credentials_sent) && $app_user_id) {
            $app_user_exists = get_user_by('id', $app_user_id);
            if (!$app_user_exists) {
                // User was deleted — clear stored credentials
                $app['app_password'] = '';
                $app['user_id'] = 0;
                $app['user_login'] = '';
                unset($app['credentials_sent']);
                update_option(self::OPTION_APP_USER, $app);
                $has_app_password = false;
                $credentials_sent = false;
                $app_user_id = 0;
                $app_user_login = '';
                $app_user_edit_url = '';
                $advanced_features_error = 'The WordPress user for Advanced Features was deleted. Please re-enable to create a new one.';
            }
        }

        $default_language = !empty($assistant_defaults['language']) ? $assistant_defaults['language'] : get_locale();
        $default_tone = !empty($assistant_defaults['tone']) ? $assistant_defaults['tone'] : 'Expert';
        $default_industry = isset($assistant_defaults['industry']) ? $assistant_defaults['industry'] : '';
        $default_products = isset($assistant_defaults['products']) ? $assistant_defaults['products'] : '';
        $default_expectations = isset($assistant_defaults['expectations']) ? $assistant_defaults['expectations'] : '';
        $default_currency = isset($assistant_defaults['currency']) ? $assistant_defaults['currency'] : '';

        $language_options = array(
            'en' => 'English', 'es' => 'Spanish', 'fr' => 'French', 'de' => 'German',
            'it' => 'Italian', 'fa' => 'Persian', 'ar' => 'Arabic', 'hi' => 'Hindi', 'pt' => 'Portuguese',
        );

        $allowed_users = get_option(self::OPTION_ALLOWED_USERS, array());
        if (!is_array($allowed_users)) {
            $allowed_users = array();
        }

        $users = get_users(array(
            'role__not_in' => array('customer', 'subscriber'),
            'orderby' => 'display_name',
            'order' => 'ASC'
        ));
        $users = array_filter($users, function($user) {
            return strpos($user->user_login, 'wc_api_app') !== 0;
        });

        $dashboard_url = 'https://app.peligent.com/dashboard?site_url=' . rawurlencode($site_url);

        echo '<div class="wrap peligent-settings-wrap">';

        // Header
        echo '<div class="peligent-header">';
        echo '<div class="peligent-header-content">';
        echo '<h1 class="peligent-title">';
        echo '<span class="peligent-icon" style="position: relative; display: inline-flex; align-items: center;">';
        echo '<img src="' . esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__)) . '" alt="Peligent" width="28" height="28">';
        echo '</span>';
        echo esc_html__('Peligent AI Assistant', 'peligent-ai-assistant');
        echo '</h1>';
        echo '</div>';
        echo '<div style="display:flex; align-items:center; gap: 12px;">';
        if (! empty($site_token) && $this->is_user_allowed()) {
            $toggle_icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
            echo '<button type="button" class="button" onclick="(function(e){e.preventDefault();var s=document.querySelector(\'.peligent-ai-fixed-sidebar\');if(s){var h=s.classList.contains(\'peligent-ai-hidden\');if(h){s.classList.remove(\'peligent-ai-hidden\');document.body.classList.remove(\'peligent-ai-sidebar-hidden\');try{localStorage.setItem(\'peligent_ai_sidebar_visible\',\'1\')}catch{}}else{s.classList.add(\'peligent-ai-hidden\');document.body.classList.add(\'peligent-ai-sidebar-hidden\');try{localStorage.setItem(\'peligent_ai_sidebar_visible\',\'0\')}catch{}}}return false;})(event);return false;" style="background: transparent; border: 1px solid #2563eb; color: #2563eb; display: inline-flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 6px; font-weight: 500;">';
            echo '<img src="' . esc_url($toggle_icon_url) . '" alt="Peligent" width="16" height="16" style="display:block;" />';
            echo 'Toggle Assistant';
            echo '</button>';
        }
        echo '<div class="peligent-status-badge peligent-status-connected">';
        echo '<span class="dashicons dashicons-yes-alt"></span>';
        echo esc_html__('Connected', 'peligent-ai-assistant');
        echo '</div>';
        echo '</div>';
        echo '</div>';

        $this->maybe_render_notice();

        // ──── Indexing Progress Banner ────
        echo '<div id="peligent-indexing-banner" style="display:none;margin-bottom:16px;padding:16px 20px;background:linear-gradient(135deg,#eff6ff,#f5f3ff);border:1px solid #bfdbfe;border-radius:12px;">';
        echo '<div style="display:flex;align-items:center;gap:12px;margin-bottom:10px;">';
        echo '<div style="width:32px;height:32px;border-radius:50%;background:#dbeafe;display:flex;align-items:center;justify-content:center;flex-shrink:0;">';
        echo '<span class="dashicons dashicons-update" style="font-size:16px;width:16px;height:16px;color:#2563eb;animation:peligent-spin 2s linear infinite;"></span>';
        echo '</div>';
        echo '<div>';
        echo '<div style="font-size:14px;font-weight:600;color:#1e3a5f;" id="peligent-index-title">Indexing your store data...</div>';
        echo '<div style="font-size:12px;color:#6b7280;margin-top:2px;" id="peligent-index-detail">Hang tight! Your products, orders, and customers are being indexed. All features will be fully available once this is done.</div>';
        echo '</div>';
        echo '</div>';
        echo '<div style="background:#e5e7eb;border-radius:8px;height:6px;overflow:hidden;">';
        echo '<div id="peligent-index-bar" style="background:linear-gradient(90deg,#2563eb,#7c3aed);height:100%;width:0%;border-radius:8px;transition:width 0.5s ease;"></div>';
        echo '</div>';
        echo '<div style="display:flex;justify-content:space-between;margin-top:6px;">';
        echo '<span style="font-size:11px;color:#9ca3af;" id="peligent-index-items"></span>';
        echo '<span style="font-size:11px;color:#9ca3af;" id="peligent-index-pct"></span>';
        echo '</div>';
        echo '</div>';

        // ──── Section 1: Connection Status ────
        echo '<div class="peligent-settings-card" id="peligent-section-connection">';
        echo '<div class="peligent-settings-card-header" onclick="toggleSettingsCard(\'connection\')">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex:1;">';
        echo '<span class="dashicons dashicons-admin-links" style="color:#2563eb;font-size:20px;width:20px;height:20px;"></span>';
        echo '<h3 style="margin:0;font-size:16px;font-weight:600;color:#111827;">' . esc_html__('Connection Status', 'peligent-ai-assistant') . '</h3>';
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:12px;">';
        echo '<span style="background:#d1fae5;color:#065f46;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:500;">' . esc_html__('Connected', 'peligent-ai-assistant') . '</span>';
        echo '<span class="dashicons dashicons-arrow-down-alt2 peligent-chevron" style="color:#9ca3af;font-size:16px;width:16px;height:16px;transition:transform 0.2s;"></span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="peligent-settings-card-body">';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Site URL', 'peligent-ai-assistant') . '</span><span>' . esc_html($site_url) . '</span></div>';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Connect Secret', 'peligent-ai-assistant') . '</span><span>' . esc_html(substr($connect, 0, 4) . '...' . substr($connect, -4)) . '</span></div>';
        if (!empty($partner_id)) {
            echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Partner ID', 'peligent-ai-assistant') . '</span><span>' . esc_html($partner_id) . '</span></div>';
        }
        echo '<div style="display:flex;gap:12px;margin-top:16px;">';
        echo '<a href="' . esc_url($dashboard_url) . '" target="_blank" rel="noopener noreferrer" class="peligent-button peligent-button-primary" style="font-size:13px;padding:8px 16px;">';
        echo '<span class="dashicons dashicons-external"></span>';
        echo esc_html__('Open Dashboard', 'peligent-ai-assistant');
        echo '</a>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // ──── Section 2: Store Profile ────
        echo '<div class="peligent-settings-card" id="peligent-section-profile">';
        echo '<div class="peligent-settings-card-header" onclick="toggleSettingsCard(\'profile\')">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex:1;">';
        echo '<span class="dashicons dashicons-admin-settings" style="color:#2563eb;font-size:20px;width:20px;height:20px;"></span>';
        echo '<h3 style="margin:0;font-size:16px;font-weight:600;color:#111827;">' . esc_html__('Store Profile', 'peligent-ai-assistant') . '</h3>';
        if (isset($this->_profile_synced)) {
            if ($this->_profile_synced) {
                $last_sync = get_option('peligent_last_profile_sync', '');
                echo '<span style="font-size:11px;color:#059669;font-weight:400;display:inline-flex;align-items:center;gap:3px;margin-left:8px;">';
                echo '<span class="dashicons dashicons-yes" style="font-size:14px;width:14px;height:14px;color:#059669;"></span>';
                echo 'Synced with Dashboard';
                echo '</span>';
            } else {
                echo '<span style="font-size:11px;color:#d97706;font-weight:400;display:inline-flex;align-items:center;gap:3px;margin-left:8px;">';
                echo '<span class="dashicons dashicons-warning" style="font-size:14px;width:14px;height:14px;color:#d97706;"></span>';
                echo esc_html($this->_profile_sync_message);
                echo '</span>';
            }
        }
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:12px;">';
        echo '<button type="button" class="button peligent-edit-toggle" data-section="profile" onclick="event.stopPropagation();toggleEditMode(\'profile\')" style="font-size:12px;padding:2px 12px;">' . esc_html__('Edit', 'peligent-ai-assistant') . '</button>';
        echo '<span class="dashicons dashicons-arrow-down-alt2 peligent-chevron" style="color:#9ca3af;font-size:16px;width:16px;height:16px;transition:transform 0.2s;"></span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="peligent-settings-card-body">';
        // View mode
        echo '<div id="peligent-profile-view">';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Language', 'peligent-ai-assistant') . '</span><span>' . esc_html(isset($language_options[$default_language]) ? $language_options[$default_language] : $default_language) . '</span></div>';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Tone', 'peligent-ai-assistant') . '</span><span>' . esc_html($default_tone) . '</span></div>';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Industry', 'peligent-ai-assistant') . '</span><span>' . esc_html($default_industry ?: '—') . '</span></div>';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Currency', 'peligent-ai-assistant') . '</span><span>' . esc_html($default_currency ?: '—') . ' <span style="color:#9ca3af;font-size:11px;">' . esc_html__('(AI-detected)', 'peligent-ai-assistant') . '</span></span></div>';
        echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Products', 'peligent-ai-assistant') . '</span><span>' . esc_html($default_products ? wp_trim_words($default_products, 20) : '—') . '</span></div>';
        if (!empty($default_expectations)) {
            echo '<div class="peligent-settings-field"><span class="peligent-settings-label">' . esc_html__('Expectations', 'peligent-ai-assistant') . '</span><span>' . esc_html(wp_trim_words($default_expectations, 20)) . '</span></div>';
        }
        echo '</div>';
        // Edit mode (hidden)
        echo '<div id="peligent-profile-edit" style="display:none;">';
        echo '<div class="peligent-form-group">';
        echo '<label class="peligent-form-label" for="peligent_settings_language">' . esc_html__('Language', 'peligent-ai-assistant') . '</label>';
        echo '<select class="peligent-form-input" id="peligent_settings_language" name="language">';
        foreach ($language_options as $code => $label) {
            $selected = ($default_language === $code) ? 'selected="selected"' : '';
            echo '<option value="' . esc_attr($code) . '" ' . $selected . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '</div>';
        $tone_options = array('Expert','Daring','Playful','Sophisticated','Persuasive','Supportive','Custom');
        echo '<div class="peligent-form-group">';
        echo '<label class="peligent-form-label" for="peligent_settings_tone">' . esc_html__('Tone', 'peligent-ai-assistant') . '</label>';
        echo '<select class="peligent-form-input" id="peligent_settings_tone" name="tone">';
        foreach ($tone_options as $tone) {
            $selected = ($default_tone === $tone) ? 'selected="selected"' : '';
            echo '<option value="' . esc_attr($tone) . '" ' . $selected . '>' . esc_html($tone) . '</option>';
        }
        echo '</select>';
        echo '</div>';
        echo '<div class="peligent-form-group"><label class="peligent-form-label" for="peligent_settings_industry">' . esc_html__('Industry', 'peligent-ai-assistant') . '</label><input type="text" class="peligent-form-input" id="peligent_settings_industry" value="' . esc_attr($default_industry) . '" /></div>';
        echo '<div class="peligent-form-group"><label class="peligent-form-label" for="peligent_settings_currency">' . esc_html__('Currency', 'peligent-ai-assistant') . '</label><input type="text" class="peligent-form-input" id="peligent_settings_currency" value="' . esc_attr($default_currency ?: '') . '" placeholder="e.g. USD, EUR, GBP" /></div>';
        echo '<div class="peligent-form-group"><label class="peligent-form-label" for="peligent_settings_products">' . esc_html__('Products', 'peligent-ai-assistant') . '</label><textarea class="peligent-form-input" id="peligent_settings_products" rows="3" style="resize:vertical;">' . esc_textarea($default_products) . '</textarea></div>';
        echo '<div class="peligent-form-group"><label class="peligent-form-label" for="peligent_settings_expectations">' . esc_html__('Expectations (optional)', 'peligent-ai-assistant') . '</label><textarea class="peligent-form-input" id="peligent_settings_expectations" rows="2" style="resize:vertical;">' . esc_textarea($default_expectations) . '</textarea></div>';
        echo '<div style="display:flex;gap:8px;">';
        echo '<button type="button" class="peligent-button peligent-button-primary" onclick="saveSettingsProfile()" id="peligent-save-profile-btn" style="font-size:13px;padding:8px 20px;">' . esc_html__('Save', 'peligent-ai-assistant') . '</button>';
        echo '<button type="button" class="button" onclick="toggleEditMode(\'profile\')" style="font-size:13px;padding:8px 16px;">' . esc_html__('Cancel', 'peligent-ai-assistant') . '</button>';
        echo '</div>';
        echo '<div id="peligent-profile-edit-result" style="margin-top:8px;"></div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // Toggle CSS for settings page
        echo '<style>.peligent-toggle input:checked+.peligent-toggle-slider{background:#10b981;}.peligent-toggle-slider:before{content:"";position:absolute;height:20px;width:20px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:0.3s;box-shadow:0 1px 3px rgba(0,0,0,0.2);}.peligent-toggle input:checked+.peligent-toggle-slider:before{transform:translateX(22px);}.peligent-toggle input:disabled+.peligent-toggle-slider{opacity:0.6;cursor:not-allowed;}</style>';

        // ──── Section 3: Advanced Features ────
        $app_pass_configured = $credentials_sent || $has_app_password;
        echo '<div class="peligent-settings-card" id="peligent-section-apppass">';
        echo '<div class="peligent-settings-card-header" onclick="toggleSettingsCard(\'apppass\')">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex:1;">';
        echo '<span class="dashicons dashicons-superhero-alt" style="color:#2563eb;font-size:20px;width:20px;height:20px;"></span>';
        echo '<h3 style="margin:0;font-size:16px;font-weight:600;color:#111827;">' . esc_html__('Advanced Features', 'peligent-ai-assistant') . '</h3>';
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:12px;">';
        if ($app_pass_configured) {
            echo '<span style="background:#d1fae5;color:#065f46;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:500;">' . esc_html__('Enabled', 'peligent-ai-assistant') . '</span>';
        } else {
            echo '<span style="background:#f3f4f6;color:#6b7280;padding:3px 10px;border-radius:12px;font-size:12px;font-weight:500;">' . esc_html__('Disabled', 'peligent-ai-assistant') . '</span>';
        }
        echo '<span class="dashicons dashicons-arrow-down-alt2 peligent-chevron" style="color:#9ca3af;font-size:16px;width:16px;height:16px;transition:transform 0.2s;"></span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="peligent-settings-card-body">';
        echo '<p style="color:#6b7280;font-size:13px;margin:0 0 16px;line-height:1.5;">' . esc_html__('Unlock site health monitoring, blog management, page speed insights, and image uploads.', 'peligent-ai-assistant') . '</p>';

        // Toggle switch
        echo '<div id="peligent-settings-advanced-toggle-wrap" style="display:flex;align-items:center;justify-content:space-between;padding:16px;background:' . ($app_pass_configured ? '#f0fdf4' : '#f9fafb') . ';border:1px solid ' . ($app_pass_configured ? '#bbf7d0' : '#e5e7eb') . ';border-radius:10px;transition:all 0.3s ease;">';
        echo '<div>';
        echo '<div style="font-size:14px;font-weight:600;color:#111827;">' . esc_html__('Enable Advanced Features', 'peligent-ai-assistant') . '</div>';
        echo '<div style="font-size:12px;color:#6b7280;margin-top:2px;">' . esc_html__('Creates a secure application password automatically', 'peligent-ai-assistant') . '</div>';
        echo '</div>';
        echo '<label class="peligent-toggle" style="position:relative;display:inline-block;width:48px;height:26px;flex-shrink:0;">';
        echo '<input type="checkbox" id="peligent-settings-advanced-toggle" ' . ($app_pass_configured ? 'checked' : '') . ' onchange="toggleAdvancedFeatures(this.checked, \'settings\')" style="opacity:0;width:0;height:0;">';
        echo '<span class="peligent-toggle-slider" style="position:absolute;cursor:pointer;inset:0;background:' . ($app_pass_configured ? '#10b981' : '#d1d5db') . ';border-radius:26px;transition:0.3s;"></span>';
        echo '</label>';
        echo '</div>';

        // Features list (shown when enabled)
        echo '<div id="peligent-settings-advanced-features" style="margin-top:12px;' . ($app_pass_configured ? '' : 'display:none;') . '">';
        $features = array(
            array('dashicons-warning', '#f59e0b', 'Site health monitoring & error alerts'),
            array('dashicons-performance', '#3b82f6', 'Page speed & performance insights'),
            array('dashicons-media-text', '#8b5cf6', 'Blog post & page management'),
            array('dashicons-format-image', '#10b981', 'AI image uploads to WordPress'),
        );
        foreach ($features as $feat) {
            echo '<div style="display:flex;align-items:center;gap:8px;padding:4px 0;">';
            echo '<span class="dashicons ' . esc_attr($feat[0]) . '" style="color:' . esc_attr($feat[1]) . ';font-size:16px;width:16px;height:16px;"></span>';
            echo '<span style="font-size:13px;color:#374151;">' . esc_html__($feat[2], 'peligent-ai-assistant') . '</span>';
            echo '</div>';
        }
        echo '</div>';

        echo '<div id="peligent-settings-advanced-result" style="margin-top:8px;">';
        if (!empty($advanced_features_error)) {
            echo '<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:10px 14px;display:flex;align-items:center;gap:8px;font-size:13px;color:#991b1b;">';
            echo '<span class="dashicons dashicons-warning" style="color:#dc2626;font-size:16px;width:16px;height:16px;"></span>';
            echo esc_html($advanced_features_error);
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // ──── Section: Chat Widget ────
        echo '<div class="peligent-settings-card" id="peligent-section-widget">';
        echo '<div class="peligent-settings-card-header" onclick="toggleSettingsCard(\'widget\')">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex:1;">';
        echo '<span class="dashicons dashicons-format-chat" style="color:#2563eb;font-size:20px;width:20px;height:20px;"></span>';
        echo '<h3 style="margin:0;font-size:16px;font-weight:600;color:#111827;">' . esc_html__('Chat Widget', 'peligent-ai-assistant') . '</h3>';
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:12px;">';
        $widget_on = get_option('peligent_show_floating_widget', '1') === '1';
        echo '<span style="font-size:12px;color:' . ($widget_on ? '#059669' : '#9ca3af') . ';font-weight:500;">' . ($widget_on ? esc_html__('Enabled', 'peligent-ai-assistant') : esc_html__('Disabled', 'peligent-ai-assistant')) . '</span>';
        echo '<span class="dashicons dashicons-arrow-down-alt2 peligent-chevron" style="color:#9ca3af;font-size:16px;width:16px;height:16px;transition:transform 0.2s;"></span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="peligent-settings-card-body">';
        echo '<p style="color:#6b7280;font-size:13px;margin:0 0 16px;line-height:1.5;">' . esc_html__('Show a floating chat button on all WordPress admin pages for quick access to the AI assistant.', 'peligent-ai-assistant') . '</p>';

        echo '<div style="display:flex;align-items:center;justify-content:space-between;padding:16px;background:' . ($widget_on ? '#eff6ff' : '#f9fafb') . ';border:1px solid ' . ($widget_on ? '#bfdbfe' : '#e5e7eb') . ';border-radius:10px;transition:all 0.3s ease;">';
        echo '<div>';
        echo '<div style="font-size:14px;font-weight:600;color:#111827;">' . esc_html__('Show Chat Widget', 'peligent-ai-assistant') . '</div>';
        echo '<div style="font-size:12px;color:#6b7280;margin-top:2px;">' . esc_html__('Floating button in the bottom-right corner of every admin page', 'peligent-ai-assistant') . '</div>';
        echo '</div>';
        echo '<label class="peligent-toggle" style="position:relative;display:inline-block;width:48px;height:26px;flex-shrink:0;">';
        echo '<input type="checkbox" id="peligent-show-floating-widget" ' . ($widget_on ? 'checked' : '') . ' onchange="toggleFloatingWidget(this.checked)" style="opacity:0;width:0;height:0;">';
        echo '<span class="peligent-toggle-slider" style="position:absolute;cursor:pointer;inset:0;background:' . ($widget_on ? '#2563eb' : '#d1d5db') . ';border-radius:26px;transition:0.3s;"></span>';
        echo '<style>.peligent-toggle-slider::before{content:"";position:absolute;height:20px;width:20px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:0.3s;box-shadow:0 1px 3px rgba(0,0,0,0.2);}#peligent-show-floating-widget:checked+.peligent-toggle-slider{background:#2563eb !important;}#peligent-show-floating-widget:checked+.peligent-toggle-slider::before{transform:translateX(22px);}#peligent-show-floating-widget:not(:checked)+.peligent-toggle-slider{background:#d1d5db !important;}</style>';
        echo '</label>';
        echo '</div>';

        echo '<div id="peligent-widget-save-result" style="margin-top:8px;"></div>';
        echo '</div>';
        echo '</div>';

        // ──── Section 4: User Access ────
        echo '<div class="peligent-settings-card" id="peligent-section-users">';
        echo '<div class="peligent-settings-card-header" onclick="toggleSettingsCard(\'users\')">';
        echo '<div style="display:flex;align-items:center;gap:10px;flex:1;">';
        echo '<span class="dashicons dashicons-groups" style="color:#2563eb;font-size:20px;width:20px;height:20px;"></span>';
        echo '<h3 style="margin:0;font-size:16px;font-weight:600;color:#111827;">' . esc_html__('User Access', 'peligent-ai-assistant') . '</h3>';
        echo '</div>';
        echo '<div style="display:flex;align-items:center;gap:12px;">';
        echo '<button type="button" class="button peligent-edit-toggle" data-section="users" onclick="event.stopPropagation();toggleEditMode(\'users\')" style="font-size:12px;padding:2px 12px;">' . esc_html__('Edit', 'peligent-ai-assistant') . '</button>';
        echo '<span class="dashicons dashicons-arrow-down-alt2 peligent-chevron" style="color:#9ca3af;font-size:16px;width:16px;height:16px;transition:transform 0.2s;"></span>';
        echo '</div>';
        echo '</div>';
        echo '<div class="peligent-settings-card-body">';
        // View mode
        $allowed_count = count($allowed_users);
        $allowed_names = array();
        foreach ($users as $user) {
            if (in_array((int) $user->ID, array_map('intval', $allowed_users), true)) {
                $allowed_names[] = $user->display_name;
            }
        }
        echo '<div id="peligent-users-view">';
        echo '<p style="color:#374151;font-size:14px;margin:0;">';
        if ($allowed_count > 0) {
            /* translators: %d: number of users */
            echo esc_html(sprintf(_n('%d user has access', '%d users have access', $allowed_count, 'peligent-ai-assistant'), $allowed_count));
            if (!empty($allowed_names)) {
                echo '<br><span style="color:#6b7280;font-size:13px;">' . esc_html(implode(', ', array_slice($allowed_names, 0, 5)));
                if (count($allowed_names) > 5) {
                    echo ', ...';
                }
                echo '</span>';
            }
        } else {
            echo esc_html__('No users have access', 'peligent-ai-assistant');
        }
        echo '</p>';
        echo '</div>';
        // Edit mode (hidden)
        echo '<div id="peligent-users-edit" style="display:none;">';
        echo '<p class="peligent-card-description">' . esc_html__('Select which users can access Peligent features.', 'peligent-ai-assistant') . '</p>';
        echo '<div class="peligent-users-list">';
        if (empty($users)) {
            echo '<p class="peligent-empty-state">' . esc_html__('No users found.', 'peligent-ai-assistant') . '</p>';
        } else {
            foreach ($users as $user) {
                $user_id = (int) $user->ID;
                $checked = in_array($user_id, array_map('intval', $allowed_users), true) ? 'checked="checked"' : '';
                $user_roles = implode(', ', array_map('esc_html', $user->roles));
                echo '<label class="peligent-user-item">';
                echo '<input type="checkbox" class="peligent-settings-user-cb" name="allowed_users[]" value="' . esc_attr($user_id) . '" ' . $checked . ' />';
                echo '<div class="peligent-user-info">';
                echo '<span class="peligent-user-name">' . esc_html($user->display_name) . '</span>';
                echo '<span class="peligent-user-email">' . esc_html($user->user_email) . '</span>';
                if (!empty($user_roles)) {
                    echo '<span class="peligent-user-role">' . esc_html($user_roles) . '</span>';
                }
                echo '</div>';
                echo '</label>';
            }
        }
        echo '</div>';
        echo '<div style="display:flex;gap:8px;margin-top:12px;">';
        echo '<button type="button" class="peligent-button peligent-button-primary" onclick="saveSettingsUsers()" id="peligent-save-users-btn" style="font-size:13px;padding:8px 20px;">' . esc_html__('Save', 'peligent-ai-assistant') . '</button>';
        echo '<button type="button" class="button" onclick="toggleEditMode(\'users\')" style="font-size:13px;padding:8px 16px;">' . esc_html__('Cancel', 'peligent-ai-assistant') . '</button>';
        echo '</div>';
        echo '<div id="peligent-users-edit-result" style="margin-top:8px;"></div>';
        echo '</div>';
        echo '</div>';
        echo '</div>';

        // Re-run Setup Wizard link
        echo '<div style="text-align:center;margin-top:24px;">';
        echo '<a href="javascript:void(0);" onclick="resetOnboarding()" style="color:#6b7280;font-size:13px;text-decoration:none;">' . esc_html__('Re-run Setup Wizard', 'peligent-ai-assistant') . '</a>';
        echo '</div>';

        // Settings page JavaScript
        echo '<script>';
        echo 'var ajaxUrl=' . wp_json_encode(admin_url('admin-ajax.php')) . ';';
        echo 'var saveDefaultsNonce=' . wp_json_encode(wp_create_nonce('peligent_save_defaults_nonce')) . ';';
        echo 'var saveUsersNonce=' . wp_json_encode(wp_create_nonce('peligent_save_users_nonce')) . ';';
        echo 'var appPassNonce=' . wp_json_encode(wp_create_nonce('peligent_save_app_password_nonce')) . ';';
        echo 'var advancedFeaturesNonce=' . wp_json_encode(wp_create_nonce('peligent_enable_advanced_features_nonce')) . ';';
        echo 'var resetOnboardingNonce=' . wp_json_encode(wp_create_nonce('peligent_reset_onboarding_nonce')) . ';';
        echo 'var floatingWidgetNonce=' . wp_json_encode(wp_create_nonce('peligent_toggle_widget_nonce')) . ';';

        echo 'function toggleSettingsCard(id){';
        echo '  var card=document.getElementById("peligent-section-"+id);if(!card)return;';
        echo '  var body=card.querySelector(".peligent-settings-card-body");';
        echo '  var chevron=card.querySelector(".peligent-chevron");';
        echo '  if(body.style.display==="none"){body.style.display="";if(chevron)chevron.style.transform="";}';
        echo '  else{body.style.display="none";if(chevron)chevron.style.transform="rotate(-90deg)";}';
        echo '}';

        echo 'function toggleEditMode(section){';
        echo '  var view=document.getElementById("peligent-"+section+"-view");';
        echo '  var edit=document.getElementById("peligent-"+section+"-edit");';
        echo '  var btn=document.querySelector(".peligent-edit-toggle[data-section=\'"+section+"\']");';
        echo '  if(!view||!edit)return;';
        echo '  if(edit.style.display==="none"){edit.style.display="";view.style.display="none";if(btn)btn.textContent="Cancel";}';
        echo '  else{edit.style.display="none";view.style.display="";if(btn)btn.textContent="Edit";}';
        echo '}';

        echo 'function saveSettingsProfile(){';
        echo '  var btn=document.getElementById("peligent-save-profile-btn");';
        echo '  var res=document.getElementById("peligent-profile-edit-result");';
        echo '  if(btn){btn.textContent="Saving...";btn.disabled=true;}';
        echo '  var data="action=peligent_save_assistant_defaults&nonce="+encodeURIComponent(saveDefaultsNonce);';
        echo '  data+="&language="+encodeURIComponent(document.getElementById("peligent_settings_language").value);';
        echo '  data+="&tone="+encodeURIComponent(document.getElementById("peligent_settings_tone").value);';
        echo '  data+="&industry="+encodeURIComponent(document.getElementById("peligent_settings_industry").value);';
        echo '  data+="&products="+encodeURIComponent(document.getElementById("peligent_settings_products").value);';
        echo '  data+="&expectations="+encodeURIComponent(document.getElementById("peligent_settings_expectations").value);
  var curSettings=document.getElementById("peligent_settings_currency");if(curSettings)data+="&currency="+encodeURIComponent(curSettings.value);';
        echo '  var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    if(btn){btn.textContent="Save";btn.disabled=false;}';
        echo '    try{var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){var sw=r.data&&r.data.sync_warning;if(res)res.innerHTML="<span style=\'color:"+(sw?"#d97706":"#065f46")+";font-size:12px;\'>"+(sw?"Saved locally. Dashboard sync pending.":"Saved!")+"</span>";setTimeout(function(){location.reload();},1000);}';
        echo '      else{if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>"+(r.data&&r.data.message?r.data.message:"Failed.")+"</span>";}';
        echo '    }catch(e){if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>Error.</span>";}';
        echo '  };xhr.onerror=function(){if(btn){btn.textContent="Save";btn.disabled=false;}if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>Network error.</span>";};';
        echo '  xhr.send(data);';
        echo '}';

        echo 'function toggleAdvancedFeatures(enable, context){';
        echo '  var wrap=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-toggle-wrap");';
        echo '  var toggle=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-toggle");';
        echo '  var features=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-features");';
        echo '  var resultEl=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-result");';
        echo '  if(!toggle)return;';
        echo '  toggle.disabled=true;';
        echo '  resultEl.innerHTML="<span style=\'color:#6b7280;font-size:12px;\'>"+(enable?"Enabling...":"Disabling...")+"</span>";';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    toggle.disabled=false;';
        echo '    try{var r=JSON.parse(xhr.responseText);}catch(e){resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>Error: Invalid response</span>";toggle.checked=!enable;return;}';
        echo '    if(r.success){';
        echo '      resultEl.innerHTML="<span style=\'color:#059669;font-size:12px;\'>"+r.data.message+"</span>";';
        echo '      if(wrap){wrap.style.background=enable?"#f0fdf4":"#f9fafb";wrap.style.borderColor=enable?"#bbf7d0":"#e5e7eb";}';
        echo '      var slider=toggle.nextElementSibling;if(slider)slider.style.background=enable?"#10b981":"#d1d5db";';
        echo '      if(features){features.style.opacity=enable?"1":"0.5";if(context==="settings"){features.style.display=enable?"block":"none";}}';
        echo '      setTimeout(function(){resultEl.innerHTML="";},3000);';
        echo '    }else{';
        echo '      toggle.checked=!enable;';
        echo '      resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>"+(r.data&&r.data.message?r.data.message:"Failed")+"</span>";';
        echo '    }';
        echo '  };';
        echo '  xhr.onerror=function(){toggle.disabled=false;toggle.checked=!enable;resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>Network error</span>";};';
        echo '  xhr.send("action=peligent_enable_advanced_features&nonce="+encodeURIComponent(advancedFeaturesNonce)+"&enable="+(enable?"1":"0"));';
        echo '}';
        

        echo 'function toggleFloatingWidget(checked){';
        echo '  var sl=document.querySelector("#peligent-show-floating-widget+.peligent-toggle-slider");';
        echo '  if(sl){sl.style.background=checked?"#2563eb":"#d1d5db";sl.style.setProperty("--knob","translateX("+(checked?"22px":"0")+")");';
        echo '    var k=sl.querySelector("::before")||sl;if(sl.style.cssText)sl.style.background=checked?"#2563eb":"#d1d5db";}';
        echo '  var wrap=document.getElementById("peligent-show-floating-widget");';
        echo '  if(wrap){var box=wrap.closest("div[style*=background]");if(box){box.style.background=checked?"#eff6ff":"#f9fafb";box.style.borderColor=checked?"#bfdbfe":"#e5e7eb";}}';
        echo '  var hdr=document.querySelector("#peligent-section-widget .peligent-settings-card-header span[style*=color]");';
        echo '  if(hdr){hdr.style.color=checked?"#059669":"#9ca3af";hdr.textContent=checked?"Enabled":"Disabled";}';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxurl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    if(xhr.status===200){';
        echo '      var r=document.getElementById("peligent-widget-save-result");';
        echo '      if(r){r.innerHTML=\'<div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:8px 14px;font-size:13px;color:#166534;">Saved. Refresh to see changes.</div>\';setTimeout(function(){r.innerHTML=\'\';},3000);}';
        echo '    }';
        echo '  };';
        echo '  xhr.send("action=peligent_toggle_floating_widget&nonce="+encodeURIComponent(floatingWidgetNonce)+"&enabled="+(checked?"1":"0"));';
        echo '}';

        echo 'function saveSettingsAppPassword(){';
        echo '  var inp=document.getElementById("peligent_settings_app_password");';
        echo '  var btn=document.getElementById("peligent-settings-save-apppass-btn");';
        echo '  var res=document.getElementById("peligent-settings-app-pass-result");';
        echo '  if(!inp||!inp.value.trim()){if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>Please enter the password.</span>";return;}';
        echo '  if(btn){btn.textContent="Saving...";btn.disabled=true;}';
        echo '  var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    if(btn){btn.textContent="Save";btn.disabled=false;}';
        echo '    try{var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){';
        echo '        var sec=document.getElementById("peligent-settings-app-pass-section");';
        echo '        if(sec){var msg=r.data&&r.data.message?r.data.message:"Saved.";';
        echo '          sec.innerHTML="<div style=\'background:#ecfdf5;border:1px solid #a7f3d0;border-radius:8px;padding:10px 14px;display:flex;align-items:center;gap:8px;font-size:13px;color:#065f46;\'><span class=\'dashicons dashicons-yes-alt\' style=\'color:#10b981;\'></span>"+msg+"</div>";}';
        echo '      }else{if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>"+(r.data&&r.data.message?r.data.message:"Failed.")+"</span>";}';
        echo '    }catch(e){if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>Error.</span>";}';
        echo '  };xhr.onerror=function(){if(btn){btn.textContent="Save";btn.disabled=false;}};';
        echo '  xhr.send("action=peligent_save_app_password&nonce="+encodeURIComponent(appPassNonce)+"&app_password="+encodeURIComponent(inp.value.trim()));';
        echo '}';

        echo 'function saveSettingsUsers(){';
        echo '  var btn=document.getElementById("peligent-save-users-btn");';
        echo '  var res=document.getElementById("peligent-users-edit-result");';
        echo '  if(btn){btn.textContent="Saving...";btn.disabled=true;}';
        echo '  var cbs=document.querySelectorAll(".peligent-settings-user-cb:checked");';
        echo '  var data="action=peligent_save_allowed_users&nonce="+encodeURIComponent(saveUsersNonce);';
        echo '  cbs.forEach(function(cb){data+="&allowed_users[]="+encodeURIComponent(cb.value);});';
        echo '  var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    if(btn){btn.textContent="Save";btn.disabled=false;}';
        echo '    try{var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){if(res)res.innerHTML="<span style=\'color:#065f46;font-size:12px;\'>Saved!</span>";setTimeout(function(){location.reload();},800);}';
        echo '      else{if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>"+(r.data&&r.data.message?r.data.message:"Failed.")+"</span>";}';
        echo '    }catch(e){if(res)res.innerHTML="<span style=\'color:#ef4444;font-size:12px;\'>Error.</span>";}';
        echo '  };xhr.onerror=function(){if(btn){btn.textContent="Save";btn.disabled=false;}};';
        echo '  xhr.send(data);';
        echo '}';

        echo 'function resetOnboarding(){';
        echo '  if(!confirm("This will take you back to the setup wizard. Continue?"))return;';
        echo '  var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){location.reload();};';
        echo '  xhr.onerror=function(){location.reload();};';
        echo '  xhr.send("action=peligent_reset_onboarding&nonce="+encodeURIComponent(resetOnboardingNonce));';
        echo '}';

        // Indexing progress polling
        echo 'var indexPollTimer=null;';
        echo 'function pollIndexingStatus(){';
        echo '  var siteToken=typeof PELIGENT_AI_CLIENT!=="undefined"?PELIGENT_AI_CLIENT.token:"";';
        echo '  if(!siteToken)return;';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("GET","https://app.peligent.com/api/sites/sync-status",true);';
        echo '  xhr.setRequestHeader("X-Site-Token",siteToken);';
        echo '  xhr.onreadystatechange=function(){';
        echo '    if(xhr.readyState!==4)return;';
        echo '    if(xhr.status===200){';
        echo '      try{';
        echo '        var d=JSON.parse(xhr.responseText);';
        echo '        var banner=document.getElementById("peligent-indexing-banner");';
        echo '        if(!banner)return;';
        echo '        if(d.syncStatus==="in_progress"||d.syncStatus==="idle"){';
        echo '          banner.style.display="block";';
        echo '          var bar=document.getElementById("peligent-index-bar");';
        echo '          var title=document.getElementById("peligent-index-title");';
        echo '          var detail=document.getElementById("peligent-index-detail");';
        echo '          var items=document.getElementById("peligent-index-items");';
        echo '          var pctEl=document.getElementById("peligent-index-pct");';
        echo '          var total=(d.productsIndexed||0)+(d.ordersIndexed||0)+(d.customersIndexed||0)+(d.postsIndexed||0);';
        echo '          var logs=d.progressLogs||[];';
        echo '          var lastLog=logs.length?logs[logs.length-1]:{};';
        echo '          var pct=lastLog.progressPercent||0;';
        echo '          if(bar)bar.style.width=Math.max(5,pct)+"%";';
        echo '          if(pctEl)pctEl.textContent=Math.round(pct)+"%";';
        echo '          if(items)items.textContent=total+" items indexed so far";';
        echo '          if(d.syncStatus==="idle"&&total>0){';
        echo '            if(title)title.textContent="Almost ready!";';
        echo '            if(detail)detail.textContent="Your store data is being prepared. Features will unlock shortly.";';
        echo '          }';
        echo '        }else if(d.syncStatus==="completed"){';
        echo '          banner.style.display="block";';
        echo '          banner.style.background="linear-gradient(135deg,#ecfdf5,#f0fdf4)";';
        echo '          banner.style.borderColor="#86efac";';
        echo '          var title2=document.getElementById("peligent-index-title");';
        echo '          var detail2=document.getElementById("peligent-index-detail");';
        echo '          var bar2=document.getElementById("peligent-index-bar");';
        echo '          var pctEl2=document.getElementById("peligent-index-pct");';
        echo '          var items2=document.getElementById("peligent-index-items");';
        echo '          if(title2){title2.textContent="Indexing complete!";title2.style.color="#065f46";}';
        echo '          if(detail2)detail2.textContent="All features are now fully available. Your AI assistant has full access to your store data.";';
        echo '          if(bar2){bar2.style.width="100%";bar2.style.background="#10b981";}';
        echo '          if(pctEl2)pctEl2.textContent="100%";';
        echo '          var total2=(d.productsIndexed||0)+(d.ordersIndexed||0)+(d.customersIndexed||0)+(d.postsIndexed||0);';
        echo '          if(items2)items2.textContent=total2+" items indexed";';
        echo '          clearInterval(indexPollTimer);';
        echo '          setTimeout(function(){banner.style.opacity="0";banner.style.transition="opacity 1s";setTimeout(function(){banner.style.display="none"},1000);},8000);';
        echo '        }else{';
        echo '          banner.style.display="none";';
        echo '          clearInterval(indexPollTimer);';
        echo '        }';
        echo '      }catch(e){}';
        echo '    }';
        echo '  };';
        echo '  xhr.send();';
        echo '}';
        echo 'pollIndexingStatus();';
        echo 'indexPollTimer=setInterval(pollIndexingStatus,10000);';

        echo '</script>';
        echo '</div>'; // .peligent-settings-wrap
    }

    /**
     * Render the 3-step onboarding wizard.
     */
    private function render_wizard()
    {
        $stored   = get_option(self::OPTION_KEY);
        $app      = get_option(self::OPTION_APP_USER);
        $connect  = get_option(self::OPTION_CONNECT_KEY, '');
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        $site_url = home_url('/');
        $site_name = get_bloginfo('name');
        $last_connect_error = get_option(self::OPTION_LAST_CONNECT_ERROR, '');
        $assistant_defaults = $this->fetch_profile_settings();
        $default_language = !empty($assistant_defaults['language']) ? $assistant_defaults['language'] : get_locale();
        $default_tone = !empty($assistant_defaults['tone']) ? $assistant_defaults['tone'] : 'Expert';
        $default_industry = isset($assistant_defaults['industry']) ? $assistant_defaults['industry'] : get_bloginfo('name');
        $default_products = isset($assistant_defaults['products']) ? $assistant_defaults['products'] : get_bloginfo('description');
        $default_expectations = isset($assistant_defaults['expectations']) ? $assistant_defaults['expectations'] : '';
        $default_currency = isset($assistant_defaults['currency']) ? $assistant_defaults['currency'] : '';

        $has_consumer_key = !empty($stored['consumer_key']) && !empty($stored['consumer_secret']) && empty($stored['error']);
        $has_app_user = !empty($app['user_login']) && empty($app['error']);
        $has_app_password = $has_app_user && !empty($app['app_password']);
        $has_connect_secret = !empty($connect);
        $credentials_sent = !empty($app['credentials_sent']);
        $is_connected = !empty($site_token) && ($credentials_sent || ($has_consumer_key && $has_connect_secret));
        $has_connection_error = $has_connect_secret && ! $is_connected && ! empty($last_connect_error);

        $app_user_login = !empty($app['user_login']) ? $app['user_login'] : '';
        $app_user_id = !empty($app['user_id']) ? (int) $app['user_id'] : 0;
        $app_user_edit_url = $app_user_id ? admin_url('user-edit.php?user_id=' . $app_user_id . '#application-passwords-section') : '';

        // Validate that the app user still exists in WordPress
        if (($has_app_password || $credentials_sent) && $app_user_id && !get_user_by('id', $app_user_id)) {
            $app['app_password'] = '';
            $app['user_id'] = 0;
            $app['user_login'] = '';
            unset($app['credentials_sent']);
            update_option(self::OPTION_APP_USER, $app);
            $has_app_password = false;
            $credentials_sent = false;
            $has_app_user = false;
            $app_user_id = 0;
            $app_user_login = '';
            $app_user_edit_url = '';
        }

        $partner_id = get_option(self::OPTION_PARTNER_ID, '');
        $onboarding_completed = get_option(self::OPTION_ONBOARDING_COMPLETED, false);

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $just_connected = isset($_GET['peligent_connected']) && $_GET['peligent_connected'] === '1';

        // Check if sync is still in progress (for page refresh resilience)
        $sync_in_progress = false;
        if ($is_connected && !$onboarding_completed && !$just_connected) {
            $profile_data = $this->fetch_profile_status();
            if (!is_wp_error($profile_data) && isset($profile_data['indexing']['sync_status'])) {
                $ss = $profile_data['indexing']['sync_status'];
                $sync_in_progress = ($ss === 'in_progress' || $ss === 'idle');
            }
        }

        $dashboard_url = 'https://app.peligent.com/dashboard?site_url=' . rawurlencode($site_url);

        $allowed_users = get_option(self::OPTION_ALLOWED_USERS, array());
        if (!is_array($allowed_users)) {
            $allowed_users = array();
        }
        $users = get_users(array(
            'role__not_in' => array('customer', 'subscriber'),
            'orderby' => 'display_name',
            'order' => 'ASC'
        ));
        $users = array_filter($users, function($user) {
            return strpos($user->user_login, 'wc_api_app') !== 0;
        });

        echo '<div class="wrap peligent-settings-wrap">';

        // Header
        echo '<div class="peligent-header">';
        echo '<div class="peligent-header-content">';
        echo '<h1 class="peligent-title">';
        echo '<span class="peligent-icon" style="position: relative; display: inline-flex; align-items: center;">';
        echo '<img src="' . esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__)) . '" alt="Peligent" width="28" height="28">';
        echo '</span>';
        echo esc_html__('Peligent AI Assistant', 'peligent-ai-assistant');
        echo '</h1>';
        echo '</div>';
        echo '<div style="display:flex; align-items:center; gap: 12px;">';
        if ($is_connected) {
            echo '<div class="peligent-status-badge peligent-status-connected">';
            echo '<span class="dashicons dashicons-yes-alt"></span>';
            echo esc_html__('Connected', 'peligent-ai-assistant');
            echo '</div>';
        } elseif ($has_connection_error) {
            echo '<div class="peligent-status-badge peligent-status-disconnected">';
            echo '<span class="dashicons dashicons-warning"></span>';
            echo esc_html__('Connection Error', 'peligent-ai-assistant');
            echo '</div>';
        } else {
            echo '<div class="peligent-status-badge peligent-status-disconnected">';
            echo '<span class="dashicons dashicons-warning"></span>';
            echo esc_html__('Not Connected', 'peligent-ai-assistant');
            echo '</div>';
        }
        echo '</div>';
        echo '</div>';

        if (! $is_connected) {
            echo '<div style="margin: -18px 0 18px 0; display: flex; justify-content: flex-end;">';
            echo '<div style="color: #6b7280; font-size: 14px;">' . esc_html__('Need help connecting?', 'peligent-ai-assistant') . ' <a href="mailto:support@peligent.com">support@peligent.com</a></div>';
            echo '</div>';
        }

        $this->maybe_render_notice();

        // ──── WIZARD CONTAINER ────
        echo '<div id="peligent-wizard">';

        // Wizard step indicator (5 dots)
        echo '<div class="peligent-wizard-steps" id="peligent-wizard-indicator">';
        $wizard_labels = array(1 => 'Connect', 2 => 'Setting Up', 3 => 'Done');
        foreach ($wizard_labels as $s => $label) {
            echo '<div class="peligent-wizard-step" data-step="' . esc_attr($s) . '">';
            echo '<div class="peligent-wizard-dot"></div>';
            echo '<span class="peligent-wizard-label">' . esc_html($label) . '</span>';
            echo '</div>';
            if ($s < 3) echo '<div class="peligent-wizard-connector"></div>';
        }
        echo '</div>';

        // ──── STEP 1: Connect ────
        echo '<div class="peligent-wizard-panel" id="peligent-step-1">';
        echo '<div class="peligent-card">';
        echo '<div class="peligent-card-header"><h3 class="peligent-card-title"><span class="dashicons dashicons-admin-links"></span>' . esc_html__('Connect Your Store', 'peligent-ai-assistant') . '</h3></div>';
        echo '<div class="peligent-card-body">';

        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="peligent-connection-form" id="peligent-connect-form">';
        wp_nonce_field('peligent_wc_send_peligent');
        echo '<input type="hidden" name="action" value="peligent_wc_send_peligent" />';
        echo '<input type="hidden" name="site_name" value="' . esc_attr($site_name) . '" />';
        echo '<input type="hidden" name="site_url" value="' . esc_attr($site_url) . '" />';

        // Connection error banner
        if ($has_connection_error) {
            echo '<div class="peligent-alert peligent-alert-error" style="margin-bottom:16px;">';
            echo '<span class="dashicons dashicons-warning"></span>';
            echo '<div><strong>' . esc_html__('Connection failed', 'peligent-ai-assistant') . '</strong>';
            echo '<p style="margin:4px 0 0;">' . esc_html($last_connect_error) . '</p></div>';
            echo '</div>';
        }

        // Connect Secret
        echo '<div class="peligent-form-group">';
        echo '<label class="peligent-form-label" for="peligent_connect_token">' . esc_html__('Peligent Connect Secret', 'peligent-ai-assistant') . ' <span class="peligent-required">*</span></label>';
        echo '<div style="background:#f0f9ff;border:1px solid #bae6fd;border-radius:8px;padding:12px;margin:0 0 8px 0;font-size:13px;color:#0c4a6e;">';
        echo esc_html__('Get your secret from', 'peligent-ai-assistant') . ' <a href="https://app.peligent.com/dashboard/websites" target="_blank" rel="noopener noreferrer" style="font-weight:600;">' . esc_html__('Peligent Dashboard', 'peligent-ai-assistant') . ' <span class="dashicons dashicons-external" style="font-size:14px;width:14px;height:14px;"></span></a>';
        echo '</div>';
        echo '<div class="peligent-input-wrapper">';
        echo '<input type="text" class="peligent-form-input" id="peligent_connect_token" name="connect_token" value="' . esc_attr($connect) . '" placeholder="' . esc_attr__('Paste your Connect Secret here', 'peligent-ai-assistant') . '" required />';
        if ($has_connect_secret) echo '<span class="peligent-input-status peligent-input-valid"><span class="dashicons dashicons-yes-alt"></span></span>';
        echo '</div>';
        echo '</div>';

        // Application Password
        // Partner ID (collapsible)
        echo '<details style="margin-bottom:16px;" ' . (!empty($partner_id) ? 'open' : '') . '>';
        echo '<summary style="cursor:pointer;color:#6b7280;font-size:13px;">' . esc_html__('Partner ID (optional)', 'peligent-ai-assistant') . '</summary>';
        echo '<div class="peligent-form-group" style="margin-top:8px;margin-bottom:0;">';
        echo '<input type="text" class="peligent-form-input" name="partner_id" value="' . esc_attr($partner_id) . '" placeholder="' . esc_attr__('Enter Partner ID if referred', 'peligent-ai-assistant') . '" />';
        echo '</div>';
        echo '</details>';

        // Connect error/success container (for AJAX responses)
        echo '<div id="peligent-connect-result" style="margin-bottom:12px;"></div>';

        // Connect button
        echo '<div class="peligent-form-actions">';
        echo '<button type="submit" class="peligent-button peligent-button-primary" id="peligent-connect-btn" style="font-size:15px;padding:12px 28px;width:100%;">';
        echo '<span class="dashicons dashicons-admin-links"></span>';
        echo ($is_connected ? esc_html__('Reconnect to Peligent', 'peligent-ai-assistant') : esc_html__('Connect to Peligent', 'peligent-ai-assistant'));
        echo '</button>';
        echo '</div>';

        echo '</form>';
        echo '</div>';
        echo '</div>';
        echo '</div>'; // step-1

        // ──── STEP 2: Setting Up (Live Progress) ────
        echo '<div class="peligent-wizard-panel" id="peligent-step-2" style="display:none;">';
        echo '<div class="peligent-card" style="padding:40px 32px;">';

        // Title section
        echo '<div style="text-align:center;margin-bottom:32px;">';
        echo '<h3 style="margin:0 0 8px;font-size:20px;font-weight:700;color:#111827;">' . esc_html__('Setting up your AI assistant', 'peligent-ai-assistant') . '</h3>';
        echo '<p style="color:#6b7280;font-size:14px;margin:0;">' . esc_html__('We\'re connecting to your store and learning about your business', 'peligent-ai-assistant') . '</p>';
        echo '</div>';

        // Credential validation checks
        echo '<div id="peligent-validation-checks" style="margin-bottom:24px;">';
        echo '<div class="peligent-check-item" id="peligent-check-wc" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-radius:10px;background:#f9fafb;margin-bottom:8px;">';
        echo '<div class="peligent-check-icon" style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;flex-shrink:0;"><span class="dashicons dashicons-update" style="color:#6b7280;animation:peligent-spin 1s linear infinite;font-size:18px;width:18px;height:18px;"></span></div>';
        echo '<div><div style="font-weight:600;font-size:13px;color:#374151;">WooCommerce API</div><div style="font-size:12px;color:#9ca3af;" id="peligent-check-wc-detail">Verifying credentials...</div></div>';
        echo '</div>';
        echo '<div class="peligent-check-item" id="peligent-check-wp" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border-radius:10px;background:#f9fafb;margin-bottom:8px;">';
        echo '<div class="peligent-check-icon" style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;flex-shrink:0;"><span class="dashicons dashicons-update" style="color:#6b7280;animation:peligent-spin 1s linear infinite;font-size:18px;width:18px;height:18px;"></span></div>';
        echo '<div><div style="font-weight:600;font-size:13px;color:#374151;">WordPress Access</div><div style="font-size:12px;color:#9ca3af;" id="peligent-check-wp-detail">Setting up permissions...</div></div>';
        echo '</div>';
        echo '</div>';

        // Divider
        echo '<div style="height:1px;background:#e5e7eb;margin:0 0 24px;"></div>';

        // Live indexing stats
        echo '<div id="peligent-indexing-stats" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:12px;margin-bottom:24px;">';

        echo '<div style="text-align:center;padding:16px 12px;background:linear-gradient(135deg,#eff6ff,#f0f9ff);border-radius:12px;border:1px solid #bfdbfe;">';
        echo '<div id="peligent-stat-products" style="font-size:28px;font-weight:800;color:#2563eb;font-variant-numeric:tabular-nums;">&#8212;</div>';
        echo '<div style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-top:4px;">Products</div>';
        echo '</div>';

        echo '<div style="text-align:center;padding:16px 12px;background:linear-gradient(135deg,#f0fdf4,#ecfdf5);border-radius:12px;border:1px solid #bbf7d0;">';
        echo '<div id="peligent-stat-orders" style="font-size:28px;font-weight:800;color:#059669;font-variant-numeric:tabular-nums;">&#8212;</div>';
        echo '<div style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-top:4px;">Orders</div>';
        echo '</div>';

        echo '<div style="text-align:center;padding:16px 12px;background:linear-gradient(135deg,#faf5ff,#fdf4ff);border-radius:12px;border:1px solid #e9d5ff;">';
        echo '<div id="peligent-stat-customers" style="font-size:28px;font-weight:800;color:#7c3aed;font-variant-numeric:tabular-nums;">&#8212;</div>';
        echo '<div style="font-size:11px;font-weight:600;color:#6b7280;text-transform:uppercase;letter-spacing:0.5px;margin-top:4px;">Customers</div>';
        echo '</div>';

        echo '</div>';

        // AI insights (appears when profile analysis completes)
        echo '<div id="peligent-ai-insights" style="display:none;background:linear-gradient(135deg,#f8fafc,#f0f9ff);border:1px solid #e0e7ff;border-radius:12px;padding:20px;margin-bottom:24px;">';
        echo '<div style="display:flex;align-items:center;gap:8px;margin-bottom:12px;">';
        echo '<span style="font-size:16px;">&#10024;</span>';
        echo '<span style="font-weight:700;font-size:14px;color:#1e40af;">AI Store Insights</span>';
        echo '</div>';
        echo '<div id="peligent-ai-insights-content" style="display:flex;flex-direction:column;gap:8px;font-size:13px;color:#374151;"></div>';
        echo '</div>';

        // Progress bar
        echo '<div style="margin-bottom:16px;">';
        echo '<div style="display:flex;justify-content:space-between;margin-bottom:6px;">';
        echo '<span id="peligent-setup-phase" style="font-size:12px;font-weight:500;color:#6b7280;">Initializing...</span>';
        echo '<span id="peligent-setup-pct" style="font-size:12px;font-weight:600;color:#2563eb;">0%</span>';
        echo '</div>';
        echo '<div style="background:#f3f4f6;border-radius:8px;height:6px;overflow:hidden;">';
        echo '<div id="peligent-setup-bar" style="background:linear-gradient(90deg,#2563eb,#7c3aed);height:100%;width:0%;border-radius:8px;transition:width 0.6s ease;"></div>';
        echo '</div>';
        echo '</div>';

        // Patient message
        echo '<p style="text-align:center;color:#9ca3af;font-size:12px;margin:0;">' . esc_html__('This usually takes 30–60 seconds. Your store data is being indexed for AI access.', 'peligent-ai-assistant') . '</p>';

        // Skip button
        echo '<div style="text-align:center;margin-top:12px;">';
        echo '<button type="button" onclick="skipSetup();" class="button" style="color:#6b7280;border-color:#d1d5db;font-size:12px;">' . esc_html__('Skip & complete later', 'peligent-ai-assistant') . '</button>';
        echo '</div>';

        echo '</div>';
        echo '</div>'; // step-2

        // ──── STEP 3: Done ────
        echo '<div class="peligent-wizard-panel" id="peligent-step-3" style="display:none;">';
        echo '<div class="peligent-card" style="padding:48px 40px;text-align:center;position:relative;">';

        echo '<div style="width:72px;height:72px;border-radius:50%;background:#ecfdf5;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;">';
        echo '<span class="dashicons dashicons-yes-alt" style="font-size:40px;width:40px;height:40px;color:#10b981;"></span>';
        echo '</div>';
        echo '<h3 style="margin:0 0 8px;font-size:22px;font-weight:700;color:#111827;">' . esc_html__('You\'re all set!', 'peligent-ai-assistant') . '</h3>';
        echo '<p style="color:#6b7280;font-size:14px;margin:0 0 24px;line-height:1.6;">' . esc_html__('Your AI assistant is ready. Open the chat sidebar to start asking questions about your store.', 'peligent-ai-assistant') . '</p>';

        // Summary stats (populated by JS)
        echo '<div id="peligent-final-stats" style="display:none;background:#f8fafc;border-radius:12px;padding:16px;margin-bottom:24px;text-align:left;">';
        echo '<div id="peligent-final-stats-content"></div>';
        echo '</div>';

        // Advanced Features Toggle
        $app_pass_saved = $credentials_sent || ($has_app_password);
        echo '<div style="border-top:1px solid #e5e7eb;padding-top:24px;margin-bottom:24px;text-align:left;">';
        echo '<h4 style="margin:0 0 8px;font-size:16px;font-weight:700;color:#111827;">' . esc_html__('Advanced Features', 'peligent-ai-assistant') . '</h4>';
        echo '<p style="margin:0 0 16px;font-size:13px;color:#6b7280;line-height:1.6;">' . esc_html__('Advanced features are enabled automatically. A dedicated WordPress user is created on your site with permissions to manage products, blog posts, and images on your behalf.', 'peligent-ai-assistant') . '</p>';

        // Toggle switch
        echo '<div id="peligent-wizard-advanced-toggle-wrap" style="display:flex;align-items:center;justify-content:space-between;padding:16px;background:' . ($app_pass_saved ? '#f0fdf4' : '#f9fafb') . ';border:1px solid ' . ($app_pass_saved ? '#bbf7d0' : '#e5e7eb') . ';border-radius:10px;transition:all 0.3s ease;">';
        echo '<div>';
        echo '<div style="font-size:14px;font-weight:600;color:#111827;">' . esc_html__('Enable Advanced Features', 'peligent-ai-assistant') . '</div>';
        echo '<div style="font-size:12px;color:#6b7280;margin-top:2px;">' . esc_html__('Creates a dedicated WordPress user with permissions to manage your store', 'peligent-ai-assistant') . '</div>';
        echo '</div>';
        echo '<label class="peligent-toggle" style="position:relative;display:inline-block;width:48px;height:26px;flex-shrink:0;">';
        echo '<input type="checkbox" id="peligent-wizard-advanced-toggle" ' . ($app_pass_saved ? 'checked' : '') . ' onchange="toggleAdvancedFeatures(this.checked, \'wizard\')" style="opacity:0;width:0;height:0;">';
        echo '<span class="peligent-toggle-slider" style="position:absolute;cursor:pointer;inset:0;background:' . ($app_pass_saved ? '#10b981' : '#d1d5db') . ';border-radius:26px;transition:0.3s;"></span>';
        echo '</label>';
        echo '</div>';

        // Features list
        echo '<div id="peligent-wizard-advanced-features" style="margin-top:12px;display:flex;flex-direction:column;gap:8px;' . ($app_pass_saved ? '' : 'opacity:0.5;') . '">';
        $benefits = array(
            array('dashicons-warning', '#f59e0b', 'Monitor site errors and get maintenance alerts'),
            array('dashicons-performance', '#3b82f6', 'Track page speed and performance insights'),
            array('dashicons-media-text', '#8b5cf6', 'Index blog posts and pages for smarter AI'),
            array('dashicons-format-image', '#10b981', 'AI-powered image uploads to WordPress'),
        );
        foreach ($benefits as $benefit) {
            echo '<div style="display:flex;align-items:center;gap:10px;">';
            echo '<span class="dashicons ' . esc_attr($benefit[0]) . '" style="color:' . esc_attr($benefit[1]) . ';font-size:16px;width:16px;height:16px;flex-shrink:0;"></span>';
            echo '<span style="font-size:13px;color:#374151;">' . esc_html__($benefit[2], 'peligent-ai-assistant') . '</span>';
            echo '</div>';
        }
        echo '</div>';

        echo '<div id="peligent-wizard-advanced-result" style="margin-top:8px;"></div>';
        echo '</div>';

        // Complete Setup button
        echo '<div style="border-top:1px solid #e5e7eb;padding-top:24px;">';
        echo '<button type="button" onclick="finishOnboarding()" class="peligent-button peligent-button-primary" id="peligent-finish-btn" style="font-size:15px;padding:14px 28px;width:100%;">';
        echo '<span class="dashicons dashicons-yes-alt"></span>';
        echo esc_html__('Complete Setup', 'peligent-ai-assistant');
        echo '</button>';
        echo '</div>';

        // Success overlay (hidden by default)
        echo '<div id="peligent-success-overlay" style="display:none;position:absolute;inset:0;background:rgba(255,255,255,0.97);z-index:10;flex-direction:column;align-items:center;justify-content:center;border-radius:12px;text-align:center;padding:40px;">';
        echo '<div style="width:72px;height:72px;border-radius:50%;background:#ecfdf5;display:flex;align-items:center;justify-content:center;margin:0 auto 20px;animation:peligent-fadein 0.4s ease;">';
        echo '<span class="dashicons dashicons-yes-alt" style="font-size:40px;width:40px;height:40px;color:#10b981;"></span>';
        echo '</div>';
        echo '<h3 style="margin:0 0 8px;font-size:22px;font-weight:700;color:#111827;">' . esc_html__('Successfully connected to your store!', 'peligent-ai-assistant') . '</h3>';
        echo '<p style="color:#6b7280;font-size:14px;margin:0 0 24px;line-height:1.6;">' . esc_html__('Hang tight — your store data is being indexed in the background. You can start using your AI assistant right away, and we\'ll email you once everything is fully ready.', 'peligent-ai-assistant') . '</p>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=peligent-connect')) . '" style="color:#2563eb;font-size:13px;text-decoration:none;">' . esc_html__('Go to Settings', 'peligent-ai-assistant') . '</a>';
        echo '</div>';

        echo '</div>';
        echo '</div>'; // step-3

        echo '</div>'; // #peligent-wizard

        // ──── WIZARD JAVASCRIPT ────
        echo '<style>';
        echo '.peligent-wizard-steps{display:flex;align-items:center;justify-content:center;gap:0;margin:0 0 24px;padding:0 20px;}';
        echo '.peligent-wizard-step{display:flex;flex-direction:column;align-items:center;gap:6px;position:relative;}';
        echo '.peligent-wizard-dot{width:12px;height:12px;border-radius:50%;background:#d1d5db;transition:all 0.3s;}';
        echo '.peligent-wizard-step.active .peligent-wizard-dot{background:#2563eb;box-shadow:0 0 0 4px rgba(37,99,235,0.2);}';
        echo '.peligent-wizard-step.completed .peligent-wizard-dot{background:#10b981;}';
        echo '.peligent-wizard-label{font-size:11px;color:#9ca3af;font-weight:500;}';
        echo '.peligent-wizard-step.active .peligent-wizard-label{color:#2563eb;font-weight:600;}';
        echo '.peligent-wizard-step.completed .peligent-wizard-label{color:#10b981;}';
        echo '.peligent-wizard-connector{width:40px;height:2px;background:#e5e7eb;margin-bottom:18px;}';
        echo '.peligent-analyzing-spinner{width:48px;height:48px;border:4px solid #e5e7eb;border-top-color:#2563eb;border-radius:50%;animation:peligent-spin 0.8s linear infinite;margin:0 auto;}';
        echo '@keyframes peligent-spin{to{transform:rotate(360deg)}}';
        echo '.peligent-ai-badge{display:inline-block;padding:1px 8px;border-radius:10px;font-size:10px;font-weight:600;background:#eff6ff;color:#2563eb;border:1px solid #bfdbfe;margin-left:6px;vertical-align:middle;}';
        echo '.peligent-wizard-panel{animation:peligent-fadein 0.3s ease forwards;}';
        echo '.peligent-toggle input:checked+.peligent-toggle-slider{background:#10b981;}.peligent-toggle-slider:before{content:"";position:absolute;height:20px;width:20px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:0.3s;box-shadow:0 1px 3px rgba(0,0,0,0.2);}.peligent-toggle input:checked+.peligent-toggle-slider:before{transform:translateX(22px);}.peligent-toggle input:disabled+.peligent-toggle-slider{opacity:0.6;cursor:not-allowed;}
@keyframes peligent-fadein{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}';
        echo '.peligent-button.loading{opacity:0.75;pointer-events:none;}';
        echo '.peligent-button.loading .dashicons{animation:peligent-spin 0.7s linear infinite;}';
        echo '.peligent-form-input.input-valid{border-color:#10b981 !important;background-color:#f0fdf4 !important;}';
        echo '.peligent-form-input:focus{border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,0.1);outline:none;}';
        echo '@keyframes peligent-pulse-soft{0%,100%{opacity:1}50%{opacity:0.5}}';
        echo '.peligent-status-pulse{animation:peligent-pulse-soft 2s ease-in-out infinite;}';
        echo '.peligent-ai-success-banner{background:#ecfdf5;border:1px solid #a7f3d0;border-radius:8px;padding:12px 16px;margin:0 0 16px;display:flex;align-items:center;gap:10px;font-size:13px;color:#065f46;animation:peligent-fadein 0.4s ease;}';
        echo '@keyframes peligent-btn-glow{0%,100%{box-shadow:0 0 0 0 rgba(37,99,235,0.4)}50%{box-shadow:0 0 0 8px rgba(37,99,235,0)}}';
        echo '.peligent-btn-ready{animation:peligent-btn-glow 1.5s ease-in-out 3;}';
        echo '</style>';

        echo '<script>';
        // Wizard JS
        echo 'var isConnected=' . ($is_connected ? 'true' : 'false') . ';';
        echo 'var justConnected=' . ($just_connected ? 'true' : 'false') . ';';
        echo 'var onboardingCompleted=' . ($onboarding_completed ? 'true' : 'false') . ';';
        echo 'var syncInProgress=' . ($sync_in_progress ? 'true' : 'false') . ';';
        echo 'var ajaxUrl=' . wp_json_encode(admin_url('admin-ajax.php')) . ';';
        echo 'var pollNonce=' . wp_json_encode(wp_create_nonce('peligent_poll_profile_nonce')) . ';';
        echo 'var connectNonce=' . wp_json_encode(wp_create_nonce('peligent_connect_nonce')) . ';';
        echo 'var saveDefaultsNonce=' . wp_json_encode(wp_create_nonce('peligent_save_defaults_nonce')) . ';';
        echo 'var saveUsersNonce=' . wp_json_encode(wp_create_nonce('peligent_save_users_nonce')) . ';';
        echo 'var appPassNonce=' . wp_json_encode(wp_create_nonce('peligent_save_app_password_nonce')) . ';';
        echo 'var advancedFeaturesNonce=' . wp_json_encode(wp_create_nonce('peligent_enable_advanced_features_nonce')) . ';';

        // Helper: open sidebar and load iframe
        echo 'function openSidebar(){var sb=document.querySelector(".peligent-ai-fixed-sidebar");if(sb){sb.classList.remove("peligent-ai-hidden");sb.classList.remove("peligent-ai-initially-hidden");document.body.classList.remove("peligent-ai-sidebar-hidden");try{localStorage.setItem("peligent_ai_sidebar_visible","1")}catch(e){}var ifr=sb.querySelector("iframe.peligent-ai-iframe");if(ifr&&ifr.dataset.src&&ifr.src!==ifr.dataset.src){ifr.src=ifr.dataset.src;}}}';

        // Wizard navigation (3 steps)
        echo 'var currentStep=1;';
        echo 'function showStep(n){';
        echo '  for(var i=1;i<=3;i++){';
        echo '    var p=document.getElementById("peligent-step-"+i);';
        echo '    if(p)p.style.display=(i===n)?"block":"none";';
        echo '  }';
        echo '  var steps=document.querySelectorAll(".peligent-wizard-step");';
        echo '  var conns=document.querySelectorAll(".peligent-wizard-connector");';
        echo '  steps.forEach(function(s){';
        echo '    var stepNum=parseInt(s.getAttribute("data-step"),10);';
        echo '    s.classList.remove("active","completed");';
        echo '    if(stepNum<n)s.classList.add("completed");';
        echo '    else if(stepNum===n)s.classList.add("active");';
        echo '  });';
        echo '  conns.forEach(function(c,idx){';
        echo '    c.classList.toggle("active",idx<n-1);';
        echo '  });';
        echo '  currentStep=n;';
        echo '  if(n===1){var fi=document.getElementById("peligent_connect_token");if(fi&&!fi.value)setTimeout(function(){fi.focus();},300);}';
        echo '';
        echo '}';

        // Profile polling
        echo 'var setupTimer=null,setupCount=0,maxSetupPolls=200;';
        echo 'function markCheck(id,success,detail){';
        echo '  var el=document.getElementById("peligent-check-"+id);';
        echo '  var detailEl=document.getElementById("peligent-check-"+id+"-detail");';
        echo '  if(!el)return;';
        echo '  var icon=el.querySelector(".peligent-check-icon");';
        echo '  if(icon){icon.innerHTML=success?"<span class=\\"dashicons dashicons-yes-alt\\" style=\\"color:#10b981;font-size:18px;width:18px;height:18px;\\"></span>":"<span class=\\"dashicons dashicons-warning\\" style=\\"color:#ef4444;font-size:18px;width:18px;height:18px;\\"></span>";}';
        echo '  el.style.background=success?"#f0fdf4":"#fef2f2";';
        echo '  if(detailEl)detailEl.textContent=detail;';
        echo '}';

        echo 'function animateNumber(el,target){';
        echo '  if(!el)return;';
        echo '  var current=parseInt(String(el.textContent).replace(/[^0-9]/g,""))||0;';
        echo '  if(current===target)return;';
        echo '  if(target<current){el.textContent=target.toLocaleString();return;}';
        echo '  var step=Math.max(1,Math.floor((target-current)/10));';
        echo '  var timer=setInterval(function(){';
        echo '    current+=step;';
        echo '    if(current>=target){current=target;clearInterval(timer);}';
        echo '    el.textContent=current.toLocaleString();';
        echo '  },50);';
        echo '}';

        echo 'function startSetupPolling(){';
        echo '  setupCount=0;';
        echo '  var bar=document.getElementById("peligent-setup-bar");';
        echo '  var pct=document.getElementById("peligent-setup-pct");';
        echo '  var phase=document.getElementById("peligent-setup-phase");';
        echo '  var hasRealProgress=false;';
        echo '  setupTimer=setInterval(function(){';
        echo '    setupCount++;';
        // Fake progress only as fallback before real data arrives
        echo '    if(!hasRealProgress){';
        echo '      var progress=Math.min(90,5+setupCount*0.5);';
        echo '      if(bar)bar.style.width=progress+"%";';
        echo '      if(pct)pct.textContent=Math.round(progress)+"%";';
        echo '      if(setupCount<5){if(phase)phase.textContent="Indexing store data...";}';
        echo '      else if(setupCount<15){if(phase)phase.textContent="Analyzing products & orders...";}';
        echo '      else if(setupCount<25){if(phase)phase.textContent="AI is learning your store...";}';
        echo '      else{if(phase)phase.textContent="Syncing data...";}';
        echo '    }';
        echo '    if(setupCount>=maxSetupPolls){clearInterval(setupTimer);skipSetup();return;}';
        echo '    var xhr=new XMLHttpRequest();';
        echo '    xhr.open("POST",ajaxUrl,true);';
        echo '    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '    xhr.onload=function(){';
        echo '      try{';
        echo '        var r=JSON.parse(xhr.responseText);';
        echo '        if(!r.success||!r.data)return;';
        echo '        var d=r.data;';
        // Always update indexing stats as they arrive
        echo '        if(d.indexing){';
        echo '          if(d.indexing.products>0)animateNumber(document.getElementById("peligent-stat-products"),d.indexing.products);';
        echo '          if(d.indexing.orders>0)animateNumber(document.getElementById("peligent-stat-orders"),d.indexing.orders);';
        echo '          if(d.indexing.customers>0)animateNumber(document.getElementById("peligent-stat-customers"),d.indexing.customers);';
        // Use real sync progress when available
        echo '          if(d.indexing.progress_percent>0){';
        echo '            hasRealProgress=true;';
        echo '            var rp=Math.min(95,d.indexing.progress_percent);';
        echo '            if(bar)bar.style.width=rp+"%";';
        echo '            if(pct)pct.textContent=Math.round(rp)+"%";';
        echo '          }';
        echo '          if(d.indexing.progress_message&&phase){phase.textContent=d.indexing.progress_message;}';
        echo '        }';
        // Show profile insights as soon as available (cosmetic only, does not trigger completion)
        echo '        if(d.status==="success"&&d.profile){';
        echo '          var insights=document.getElementById("peligent-ai-insights");';
        echo '          var icontent=document.getElementById("peligent-ai-insights-content");';
        echo '          if(insights&&icontent&&insights.style.display==="none"){';
        echo '            var html="";';
        echo '            var langs={en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",fa:"Persian",ar:"Arabic",hi:"Hindi",pt:"Portuguese"};';
        echo '            if(d.profile.industry)html+="<div>&#127978; <strong>Industry:</strong> "+d.profile.industry+"</div>";';
        echo '            if(d.profile.currency)html+="<div>&#128176; <strong>Currency:</strong> "+d.profile.currency+"</div>";';
        echo '            if(d.profile.language)html+="<div>&#127760; <strong>Language:</strong> "+(langs[d.profile.language]||d.profile.language)+"</div>";';
        echo '            if(d.profile.tone)html+="<div>&#127919; <strong>Brand tone:</strong> "+d.profile.tone+"</div>";';
        echo '            if(d.profile.products)html+="<div>&#128230; <strong>Products:</strong> "+d.profile.products.substring(0,150)+(d.profile.products.length>150?"...":"")+"</div>";';
        echo '            icontent.innerHTML=html;';
        echo '            insights.style.display="block";';
        echo '            insights.style.animation="peligent-fadein 0.5s ease";';
        echo '          }';
        echo '          saveProfileSilently(d.profile);';
        echo '        }';
        // Completion: require BOTH sync done AND profile ready
        echo '        var syncDone=d.indexing&&(d.indexing.sync_status==="completed"||d.indexing.sync_status==="completed_with_errors");';
        echo '        var profileReady=d.status==="success"&&d.profile;';
        echo '        var syncFailed=d.indexing&&d.indexing.sync_status==="failed";';
        echo '        if(syncDone&&profileReady){';
        echo '          if(bar)bar.style.width="100%";';
        echo '          if(pct)pct.textContent="100%";';
        echo '          if(phase)phase.textContent="Setup complete!";';
        echo '          clearInterval(setupTimer);';
        echo '          window._finalStats={indexing:d.indexing,profile:d.profile};';
        echo '          setTimeout(function(){showStep(3);populateFinalStats();},2000);';
        echo '        }else if(syncDone&&!profileReady){';
        echo '          if(phase)phase.textContent="Analyzing your store...";';
        echo '          if(bar)bar.style.width="95%";';
        echo '          if(pct)pct.textContent="95%";';
        echo '        }else if(syncFailed){';
        echo '          if(phase)phase.textContent="Setup finished with some issues.";';
        echo '          clearInterval(setupTimer);';
        echo '          window._finalStats={indexing:d.indexing,profile:d.profile||null};';
        echo '          setTimeout(function(){showStep(3);populateFinalStats();},3000);';
        echo '        }';
        echo '      }catch(e){console.log("Poll parse error",e);}';
        echo '    };';
        echo '    xhr.send("action=peligent_poll_profile&nonce="+encodeURIComponent(pollNonce));';
        echo '  },3000);';
        echo '}';

        echo 'var profileSaved=false;';
        echo 'function saveProfileSilently(profile){';
        echo '  if(profileSaved)return;profileSaved=true;';
        echo '  var data="action=peligent_save_assistant_defaults&nonce="+encodeURIComponent(saveDefaultsNonce);';
        echo '  if(profile.language)data+="&language="+encodeURIComponent(profile.language);';
        echo '  if(profile.tone)data+="&tone="+encodeURIComponent(profile.tone);';
        echo '  if(profile.industry)data+="&industry="+encodeURIComponent(profile.industry);';
        echo '  if(profile.currency)data+="&currency="+encodeURIComponent(profile.currency);';
        echo '  if(profile.products)data+="&products="+encodeURIComponent(profile.products);';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.send(data);';
        echo '}';

        echo 'function populateFinalStats(){';
        echo '  var stats=window._finalStats;';
        echo '  if(!stats)return;';
        echo '  var el=document.getElementById("peligent-final-stats");';
        echo '  var content=document.getElementById("peligent-final-stats-content");';
        echo '  if(!el||!content)return;';
        echo '  var html="<div style=\\"display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:13px;\\">";';
        echo '  if(stats.indexing){';
        echo '    if(stats.indexing.products)html+="<div>&#128230; <strong>"+stats.indexing.products.toLocaleString()+"</strong> products indexed</div>";';
        echo '    if(stats.indexing.orders)html+="<div>&#128722; <strong>"+stats.indexing.orders.toLocaleString()+"</strong> orders indexed</div>";';
        echo '    if(stats.indexing.customers)html+="<div>&#128101; <strong>"+stats.indexing.customers.toLocaleString()+"</strong> customers indexed</div>";';
        echo '  }';
        echo '  if(stats.profile){';
        echo '    if(stats.profile.industry)html+="<div>&#127978; "+stats.profile.industry+"</div>";';
        echo '  }';
        echo '  html+="</div>";';
        echo '  content.innerHTML=html;';
        echo '  el.style.display="block";';
        echo '}';

        echo 'function skipSetup(){';
        echo '  clearInterval(setupTimer);';
        echo '  showStep(3);';
        echo '}';

        // Apply profile data to form
        

        // Init: determine which step to show
        echo 'if(justConnected||syncInProgress){showStep(2);markCheck("wc",true,"Connected successfully");markCheck("wp",true,"Permissions configured");startSetupPolling();openSidebar();}';
        echo 'else if(isConnected&&!onboardingCompleted){showStep(3);openSidebar();}';
        echo 'else{showStep(1);}';

        // Connect form: AJAX submit
        echo 'var connectForm=document.getElementById("peligent-connect-form");';
        echo 'if(connectForm){connectForm.addEventListener("submit",function(e){';
        echo '  e.preventDefault();';
        echo '  var btn=document.getElementById("peligent-connect-btn");';
        echo '  var res=document.getElementById("peligent-connect-result");';
        echo '  var tokenEl=document.getElementById("peligent_connect_token");';
        echo '  var token=tokenEl?tokenEl.value.trim():"";';
        echo '  if(!token){if(res)res.innerHTML="<div class=\"peligent-alert peligent-alert-error\"><span class=\"dashicons dashicons-warning\"></span><span>Please enter the Connect Secret.</span></div>";return;}';
        echo '  if(res)res.innerHTML="";';
        echo '  if(btn){btn.classList.add("loading");var ic=btn.querySelector(".dashicons");if(ic)ic.className="dashicons dashicons-update";var txt=btn.childNodes[btn.childNodes.length-1];if(txt)txt.textContent=" Connecting...";}';
        echo '  var partnerEl=connectForm.querySelector("[name=partner_id]");';
        echo '  var partnerId=partnerEl?partnerEl.value.trim():"";';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    try{';
        echo '      var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){';
        echo '        if(res)res.innerHTML="<div class=\"peligent-alert\" style=\"background:#ecfdf5;border:1px solid #a7f3d0;border-radius:8px;padding:10px 14px;display:flex;align-items:center;gap:8px;font-size:13px;color:#065f46;\"><span class=\"dashicons dashicons-yes-alt\" style=\"color:#10b981;\"></span><span>Connected!</span></div>";';
        echo '        var badge=document.querySelector(".peligent-status-disconnected");if(badge){badge.className="peligent-status-badge peligent-status-connected";badge.innerHTML="<span class=\\"dashicons dashicons-yes-alt\\"></span>Connected";}';
        echo '        var advToggle=document.getElementById("peligent-wizard-advanced-toggle");if(advToggle){advToggle.checked=true;var sl=advToggle.nextElementSibling;if(sl)sl.style.background="#10b981";var wrap=document.getElementById("peligent-wizard-advanced-toggle-wrap");if(wrap){wrap.style.background="#f0fdf4";wrap.style.borderColor="#bbf7d0";}var feat=document.getElementById("peligent-wizard-advanced-features");if(feat)feat.style.opacity="1";}';
        echo '        setTimeout(function(){showStep(2);markCheck("wc",true,"Connected successfully");markCheck("wp",true,"Permissions configured");startSetupPolling();},800);';
        echo '        openSidebar();';
        echo '      }else{';
        echo '        if(btn){btn.classList.remove("loading");var ic=btn.querySelector(".dashicons");if(ic)ic.className="dashicons dashicons-admin-links";var txt=btn.childNodes[btn.childNodes.length-1];if(txt)txt.textContent=" Connect to Peligent";}';
        echo '        var msg=r.data&&r.data.message?r.data.message:"Connection failed. Please check your Connect Secret.";';
        echo '        if(res)res.innerHTML="<div class=\"peligent-alert peligent-alert-error\"><span class=\"dashicons dashicons-warning\"></span><div><strong>Connection failed</strong><p style=\"margin:4px 0 0;\">"+msg+"</p></div></div>";';
        echo '      }';
        echo '    }catch(ex){';
        echo '      if(btn){btn.classList.remove("loading");var ic=btn.querySelector(".dashicons");if(ic)ic.className="dashicons dashicons-admin-links";var txt=btn.childNodes[btn.childNodes.length-1];if(txt)txt.textContent=" Connect to Peligent";}';
        echo '      if(res)res.innerHTML="<div class=\"peligent-alert peligent-alert-error\"><span class=\"dashicons dashicons-warning\"></span><span>Unexpected error. Please try again.</span></div>";';
        echo '    }';
        echo '  };';
        echo '  xhr.onerror=function(){';
        echo '    if(btn){btn.classList.remove("loading");var ic=btn.querySelector(".dashicons");if(ic)ic.className="dashicons dashicons-admin-links";var txt=btn.childNodes[btn.childNodes.length-1];if(txt)txt.textContent=" Connect to Peligent";}';
        echo '    if(res)res.innerHTML="<div class=\"peligent-alert peligent-alert-error\"><span class=\"dashicons dashicons-warning\"></span><span>Network error. Please check your connection.</span></div>";';
        echo '  };';
        echo '  xhr.send("action=peligent_connect&nonce="+encodeURIComponent(connectNonce)+"&connect_token="+encodeURIComponent(token)+"&partner_id="+encodeURIComponent(partnerId));';
        echo '});}';

        // Save profile via AJAX (Step 3)
        

        // Finish onboarding (Step 3 Complete)
        echo 'function finishOnboarding(){';
        echo '  var btn=document.getElementById("peligent-finish-btn");';
        echo '  if(btn){btn.textContent="Completing...";btn.disabled=true;}';
        echo '  var data="action=peligent_save_allowed_users&nonce="+encodeURIComponent(saveUsersNonce)+"&complete_onboarding=1";';
        echo '  var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    try{var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){';
        echo '        var overlay=document.getElementById("peligent-success-overlay");';
        echo '        if(overlay){overlay.style.display="flex";var card=overlay.parentNode;if(card)card.style.position="relative";}';
        echo '        try{localStorage.setItem("peligent_ai_sidebar_visible","1");}catch(e){}';
        echo '        setTimeout(function(){window.location.href=' . wp_json_encode(admin_url('admin.php?page=peligent-connect')) . ';},3000);';
        echo '      }';
        echo '    }catch(e){window.location.href=' . wp_json_encode(admin_url('admin.php?page=peligent-connect')) . ';}';
        echo '  };xhr.onerror=function(){window.location.href=' . wp_json_encode(admin_url('admin.php?page=peligent-connect')) . ';};';
        echo '  xhr.send(data);';
        echo '}';

        // Input validation
        echo 'function checkInputValid(el){setTimeout(function(){if(el.value.trim().length>8){el.classList.add("input-valid");}else{el.classList.remove("input-valid");}checkConnectReady();},50);}';
        echo '["peligent_connect_token"].forEach(function(id){';
        echo '  var el=document.getElementById(id);if(!el)return;';
        echo '  el.addEventListener("paste",function(){checkInputValid(el);});';
        echo '  el.addEventListener("input",function(){checkInputValid(el);});';
        echo '  if(el.value.trim().length>8)el.classList.add("input-valid");';
        echo '});';

        echo 'function checkConnectReady(){';
        echo '  var t=document.getElementById("peligent_connect_token");';
        echo '  var btn=document.querySelector("#peligent-connect-form button[type=submit]");';
        echo '  if(t&&btn){if(t.value.trim().length>8){btn.classList.add("peligent-btn-ready");}else{btn.classList.remove("peligent-btn-ready");}}';
        echo '}';
        echo 'checkConnectReady();';

        // Save Application Password (Step 4)
        echo 'function toggleAdvancedFeatures(enable, context){';
        echo '  var wrap=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-toggle-wrap");';
        echo '  var toggle=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-toggle");';
        echo '  var features=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-features");';
        echo '  var resultEl=document.getElementById("peligent-"+(context==="wizard"?"wizard":"settings")+"-advanced-result");';
        echo '  if(!toggle)return;';
        echo '  toggle.disabled=true;';
        echo '  resultEl.innerHTML="<span style=\'color:#6b7280;font-size:12px;\'>"+(enable?"Enabling...":"Disabling...")+"</span>";';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    toggle.disabled=false;';
        echo '    try{var r=JSON.parse(xhr.responseText);}catch(e){resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>Error: Invalid response</span>";toggle.checked=!enable;return;}';
        echo '    if(r.success){';
        echo '      resultEl.innerHTML="<span style=\'color:#059669;font-size:12px;\'>"+r.data.message+"</span>";';
        echo '      if(wrap){wrap.style.background=enable?"#f0fdf4":"#f9fafb";wrap.style.borderColor=enable?"#bbf7d0":"#e5e7eb";}';
        echo '      var slider=toggle.nextElementSibling;if(slider)slider.style.background=enable?"#10b981":"#d1d5db";';
        echo '      if(features){features.style.opacity=enable?"1":"0.5";if(context==="settings"){features.style.display=enable?"block":"none";}}';
        echo '      setTimeout(function(){resultEl.innerHTML="";},3000);';
        echo '    }else{';
        echo '      toggle.checked=!enable;';
        echo '      resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>"+(r.data&&r.data.message?r.data.message:"Failed")+"</span>";';
        echo '    }';
        echo '  };';
        echo '  xhr.onerror=function(){toggle.disabled=false;toggle.checked=!enable;resultEl.innerHTML="<span style=\'color:#dc2626;font-size:12px;\'>Network error</span>";};';
        echo '  xhr.send("action=peligent_enable_advanced_features&nonce="+encodeURIComponent(advancedFeaturesNonce)+"&enable="+(enable?"1":"0"));';
        echo '}';
        
        echo 'function saveAppPassword(){';
        echo '  var inp=document.getElementById("peligent_app_password_step4");';
        echo '  var btn=document.getElementById("peligent-save-app-pass-btn");';
        echo '  var res=document.getElementById("peligent-app-pass-result");';
        echo '  if(!inp||!inp.value.trim()){if(res)res.innerHTML="<span style=\"color:#ef4444;font-size:12px;\">Please enter the Application Password.</span>";return;}';
        echo '  if(btn){btn.classList.add("loading");btn.textContent="Saving...";}';
        echo '  var xhr=new XMLHttpRequest();';
        echo '  xhr.open("POST",ajaxUrl,true);';
        echo '  xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");';
        echo '  xhr.onload=function(){';
        echo '    if(btn){btn.classList.remove("loading");btn.textContent="Save";}';
        echo '    try{';
        echo '      var r=JSON.parse(xhr.responseText);';
        echo '      if(r.success){';
        echo '        var sec=document.getElementById("peligent-app-pass-section");';
        echo '        if(sec)sec.innerHTML="<div style=\"background:#ecfdf5;border:1px solid #a7f3d0;border-radius:8px;padding:10px 14px;display:flex;align-items:center;gap:8px;font-size:13px;color:#065f46;\"><span class=\'dashicons dashicons-yes-alt\' style=\'color:#10b981;\'></span>"+(r.data&&r.data.message?r.data.message:"Application Password saved.")+"</div>";';
        echo '      }else{';
        echo '        if(res)res.innerHTML="<span style=\"color:#ef4444;font-size:12px;\">"+(r.data&&r.data.message?r.data.message:"Failed to save.")+"</span>";';
        echo '      }';
        echo '    }catch(e){if(res)res.innerHTML="<span style=\"color:#ef4444;font-size:12px;\">Unexpected error.</span>";}';
        echo '  };';
        echo '  xhr.onerror=function(){if(btn){btn.classList.remove("loading");btn.textContent="Save";}if(res)res.innerHTML="<span style=\"color:#ef4444;font-size:12px;\">Network error.</span>";};';
        echo '  xhr.send("action=peligent_save_app_password&nonce="+encodeURIComponent(appPassNonce)+"&app_password="+encodeURIComponent(inp.value.trim()));';
        echo '}';

        echo '</script>';

        echo '</div>'; // .peligent-settings-wrap
    }

    public function handle_regenerate()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_regen');

        $created = $this->create_key_programmatically(array(
            'app_name' => 'Auto-generated by WC Auto Keygen',
            'user_id'  => get_current_user_id(),
            'scope'    => 'read_write',
        ));

        if (is_wp_error($created)) {
            $this->add_admin_notice($created->get_error_message(), 'error');
        } else {
            update_option(self::OPTION_KEY, $created);
            $this->add_admin_notice('New WooCommerce key generated.');
        }

        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    public function handle_revoke()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_revoke');

        $stored = get_option(self::OPTION_KEY);
        if (! empty($stored['key_id'])) {
            $key_id = (int) $stored['key_id'];

            if (! class_exists('WC_API_Keys') && defined('WC_ABSPATH')) {
                $keys_class = WC_ABSPATH . 'includes/class-wc-api-keys.php';
                if (file_exists($keys_class)) {
                    include_once $keys_class;
                }
            }

            if (! class_exists('WC_API_Keys') && function_exists('WC')) {
                $keys_class = trailingslashit(WC()->plugin_path()) . 'includes/class-wc-api-keys.php';
                if (file_exists($keys_class)) {
                    include_once $keys_class;
                }
            }

            if (class_exists('WC_API_Keys')) {
                WC_API_Keys::delete_key($key_id);
            } else {
                $this->log_debug(sprintf('Unable to delete API key %d because WC_API_Keys is not available.', $key_id));
            }
        }

        delete_option(self::OPTION_KEY);
        $this->add_admin_notice('Key revoked and removed.');
        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    public function handle_regenerate_app_user()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_regen_appuser');

        $this->revoke_app_user_internal();
        $app = $this->create_app_user_and_password();
        if (is_wp_error($app)) {
            $this->add_admin_notice($app->get_error_message(), 'error');
        } else {
            update_option(self::OPTION_APP_USER, $app);
            $this->add_admin_notice('New app user created.');
            
            // Auto-send credentials to Peligent if connect token exists
            $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
            if (! empty($connect_token)) {
                $this->auto_send_to_peligent();
            }
        }

        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    public function handle_revoke_app_user()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_revoke_appuser');

        $this->revoke_app_user_internal();
        delete_option(self::OPTION_APP_USER);
        $this->add_admin_notice('App user revoked and removed.');

        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    public function handle_save_connect_token()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_save_token');

        $previous_token = get_option(self::OPTION_CONNECT_KEY, '');
        $token = isset($_POST['connect_token']) ? sanitize_text_field(wp_unslash($_POST['connect_token'])) : '';
        update_option(self::OPTION_CONNECT_KEY, $token);
        $this->add_admin_notice('Connect secret saved.');

        // If connect secret changed, invalidate any previously stored site token and errors
        if ($token !== $previous_token) {
            delete_option(self::OPTION_SITE_TOKEN);
            delete_option(self::OPTION_LAST_CONNECT_ERROR);
        }
        
        // Auto-send credentials if they're already available
        if (! empty($token)) {
            $this->auto_send_to_peligent();
        }
        
        wp_safe_redirect(admin_url('admin.php?page=wc-auto-keys'));
        exit;
    }

    /**
     * Auto-send credentials to Peligent (called automatically when app user is created/regenerated)
     */
    protected function auto_send_to_peligent()
    {
        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($connect_token)) {
            return; // No connect token, skip auto-send
        }

        $key = get_option(self::OPTION_KEY);
        $app = get_option(self::OPTION_APP_USER);

        if (empty($key['consumer_key']) || empty($key['consumer_secret'])) {
            return; // WooCommerce keys not available yet
        }
        // Auto-create application password if user exists but password is missing
        if (!empty($app['user_login']) && empty($app['app_password']) && empty($app['credentials_sent'])) {
            $app_user_id = !empty($app['user_id']) ? (int) $app['user_id'] : 0;
            if ($app_user_id && get_user_by('id', $app_user_id) && class_exists('WP_Application_Passwords')) {
                $app_pass_result = WP_Application_Passwords::create_new_application_password(
                    $app_user_id,
                    array('name' => 'Peligent AI Assistant')
                );
                if (!is_wp_error($app_pass_result) && !empty($app_pass_result[0])) {
                    $app['app_password'] = $app_pass_result[0];
                    $app['app_password_label'] = 'Peligent AI Assistant';
                    update_option(self::OPTION_APP_USER, $app);
                    $this->log_debug('Auto-created application password during connection');
                }
            }
        }

        $payload = array(
            'site_name'         => get_bloginfo('name'),
            'site_url'          => home_url('/'),
            'consumer_key'      => $key['consumer_key'],
            'consumer_secret'   => $key['consumer_secret'],
            'app_user_login'    => !empty($app['user_login']) ? $app['user_login'] : '',
            'app_user_password' => !empty($app['app_password']) ? $app['app_password'] : '',
            'partner_id'        => get_option(self::OPTION_PARTNER_ID, ''),
        );

        $this->log_debug('Auto-sending credentials to Peligent: ' . wp_json_encode($payload));
        $response = wp_remote_post(self::PELIGENT_ENDPOINT, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'X-Peligent-Connect-Token' => $connect_token,
            ),
            'body'      => wp_json_encode($payload),
            'timeout'   => 20,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            $this->log_debug('Auto-send to Peligent failed: ' . $response->get_error_message());
            return;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $this->log_debug('Auto-send: Peligent responded with HTTP ' . $code . ' body: ' . $body);
        
        if ($code >= 200 && $code < 300) {
            $decoded = json_decode($body, true);
            if (is_array($decoded) && ! empty($decoded['site_token'])) {
                $tok = sanitize_text_field($decoded['site_token']);
                update_option(self::OPTION_SITE_TOKEN, $tok);
                $this->log_debug('Auto-send: Site token saved successfully');
            }
        }
    }

    public function handle_send_to_peligent()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_send_peligent');

        // If a token is provided, save/update it first so a single button can both save and send
        if (isset($_POST['connect_token'])) {
            $previous_token = get_option(self::OPTION_CONNECT_KEY, '');
            $posted_token = sanitize_text_field(wp_unslash($_POST['connect_token']));
            update_option(self::OPTION_CONNECT_KEY, $posted_token);

            // If connect secret changed, invalidate any previously stored site token and errors
            if ($posted_token !== $previous_token) {
                delete_option(self::OPTION_SITE_TOKEN);
                delete_option(self::OPTION_LAST_CONNECT_ERROR);
            }
        }

        // Save partner ID if provided
        if (isset($_POST['partner_id'])) {
            update_option(self::OPTION_PARTNER_ID, sanitize_text_field(wp_unslash($_POST['partner_id'])));
        }

        // Save user-provided Application Password if given
        if (isset($_POST['app_password']) && !empty($_POST['app_password'])) {
            $app_pass = sanitize_text_field(wp_unslash($_POST['app_password']));
            $app = get_option(self::OPTION_APP_USER, array());
            if (is_array($app)) {
                $app['app_password'] = $app_pass;
                update_option(self::OPTION_APP_USER, $app);
            }
        }

        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($connect_token)) {
            $this->add_admin_notice('Set the Peligent Connect Secret before sending.', 'error');
            wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
            exit;
        }

        // Use the extracted perform_connection method
        $connected = $this->perform_connection($connect_token);
        
        if ($connected) {
            $site_token = get_option(self::OPTION_SITE_TOKEN, '');
            $mask = strlen($site_token) > 8 ? substr($site_token, 0, 4) . '...' . substr($site_token, -4) : $site_token;
            $this->add_admin_notice('Connected to Peligent successfully. Site token saved: ' . $mask);
            wp_safe_redirect(admin_url('admin.php?page=peligent-connect&peligent_connected=1'));
            exit;
        } else {
            $this->add_admin_notice('Failed to connect to Peligent. Please check your Connect Secret and try again.', 'error');
        }

        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    /**
     * Handle saving allowed users setting
     */
    public function handle_save_allowed_users()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_save_allowed_users');

        $allowed_users = isset($_POST['allowed_users']) && is_array($_POST['allowed_users']) 
            ? array_map('intval', $_POST['allowed_users']) 
            : array();
        
        // Validate that all user IDs exist and are not customers/subscribers
        $validated_users = array();
        foreach ($allowed_users as $user_id) {
            $user = get_userdata($user_id);
            if ($user && !in_array('customer', $user->roles, true) && !in_array('subscriber', $user->roles, true)) {
                $validated_users[] = $user_id;
            }
        }
        
        update_option(self::OPTION_ALLOWED_USERS, $validated_users);
        $this->add_admin_notice('Allowed users saved successfully.');

        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    /**
     * Check if current user is allowed to use Peligent
     * Returns true only if user is in the allowed users list
     */
    private function is_user_allowed()
    {
        // Check if user is in allowed users list
        $allowed_users = get_option(self::OPTION_ALLOWED_USERS, array());
        if (empty($allowed_users) || !is_array($allowed_users)) {
            // If no users are selected, no one has access
            return false;
        }
        
        $current_user_id = get_current_user_id();
        return in_array($current_user_id, array_map('intval', $allowed_users), true);
    }

    /**
     * Render sidebar on all WordPress admin pages
     */
    public function render_sidebar_on_all_pages()
    {
        if (! $this->is_user_allowed()) {
            return;
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }

        // Check if we are on a Peligent iframe page — show sidebar hidden + floating toggle
        $screen = get_current_screen();
        $iframe_pages = array(
            'peligent_page_peligent-bulk-update',
            'peligent_page_peligent-blog-update',
            'peligent_page_peligent-action-history',
            'peligent_page_peligent-bots',
            'peligent_page_peligent-reports',
            'peligent_page_peligent-integrations',
        );
        $is_iframe_page = $screen && in_array($screen->id, $iframe_pages, true);
        $force_hidden = $is_iframe_page; // Always start hidden on iframe pages

        $origin = 'https://app.peligent.com';
        $embed = trailingslashit($origin) . 'frontend/dashboard/assistant?embed=true';

        // Use data-src for lazy loading — iframe src is set by JS only when sidebar is visible
        $sidebar_class = 'peligent-ai-fixed-sidebar peligent-ai-initially-hidden';
        if ($force_hidden) {
            $sidebar_class .= ' peligent-ai-hidden';
        }

        echo '<aside class="' . esc_attr($sidebar_class) . '">';
        echo '<div class="peligent-ai-resize-handle" title="Drag to resize"></div>';
        echo '<div class="peligent-ai-sidebar-header">';
        echo '<div style="display: flex; align-items: center; justify-content: space-between; width: 100%;">';
        echo '<div style="display: flex; align-items: center; gap: 8px; position: relative;">';
        echo '<img src="' . esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__)) . '" alt="Peligent" width="28" height="28" style="display: block;" />';
        echo '<span style="color: #ffffff; font-size: 16px; font-weight: 600; letter-spacing: 0.05em;">PELIGENT</span>';
        echo '</div>';
        echo '<div style="display: flex; align-items: center; gap: 8px;">';
        echo '<button class="peligent-ai-header-btn peligent-ai-support-btn" title="Support" onclick="(function(e){e.preventDefault();e.stopPropagation();var w=window.open(\'https://app.peligent.com/dashboard/websites?openCrisp=true&site_url=\'+encodeURIComponent(window.location.origin+\'/\'),\'_blank\');if(w){setTimeout(function(){try{w.postMessage({type:\'OPEN_CRISP\',action:\'open\'},\'https://app.peligent.com\');}catch(err){}},500);}return false;})(event);" style="background: #2563eb; border: none; color: #ffffff; cursor: pointer; padding: 4px 8px; display: flex; align-items: center; justify-content: center; gap: 4px; opacity: 1; transition: background 0.2s; border-radius: 6px; font-size: 12px; font-weight: 500;" onmouseover="this.style.background=\'#3b82f6\'" onmouseout="this.style.background=\'#2563eb\'">';
        echo '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 18v-6a9 9 0 0 1 18 0v6"></path><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"></path></svg>';
        echo 'Support';
        echo '</button>';
        echo '<button class="peligent-ai-header-btn peligent-ai-target-btn" title="Select element" style="background: transparent; border: none; color: #ffffff; cursor: pointer; padding: 4px; display: flex; align-items: center; justify-content: center; opacity: 0.8; transition: opacity 0.2s;">';
        echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/></svg>';
        echo '</button>';
        echo '<button class="peligent-ai-header-btn peligent-ai-maximize-btn" title="Maximize" style="background: transparent; border: none; color: #ffffff; cursor: pointer; padding: 4px; display: flex; align-items: center; justify-content: center; opacity: 0.8; transition: opacity 0.2s;">';
        echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"></path></svg>';
        echo '</button>';
        echo '<button class="peligent-ai-header-btn peligent-ai-close-btn" title="Close" style="background: transparent; border: none; color: #ffffff; cursor: pointer; padding: 4px; display: flex; align-items: center; justify-content: center; opacity: 0.8; transition: opacity 0.2s;">';
        echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>';
        echo '</button>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        // Floating exit bar — visible only in fullscreen, always rendered by PHP so it works even if iframe fails
        echo '<div class="peligent-ai-fullscreen-bar">';
        echo '<button class="peligent-ai-fullscreen-bar-btn peligent-ai-fullscreen-minimize" title="Exit fullscreen">';
        echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14h6v6m10-10h-6V4"></path></svg>';
        echo '<span>Exit fullscreen</span>';
        echo '</button>';
        echo '<button class="peligent-ai-fullscreen-bar-btn peligent-ai-fullscreen-close" title="Close chat">';
        echo '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>';
        echo '</button>';
        echo '</div>';
        echo '<div class="peligent-ai-iframe-container">';
        // Lazy-load: use data-src so the iframe doesn't load until sidebar is opened
        echo '<iframe class="peligent-ai-iframe" src="about:blank" data-src="' . esc_url($embed) . '" referrerpolicy="strict-origin-when-cross-origin" allow="microphone"></iframe>';
        echo '</div>';

        // Feature 7: Page context detection for quick actions
        $page_context = array('page' => 'unknown', 'entity_id' => null, 'entity_type' => null, 'entity_name' => null);
        if ($screen) {
            if ($screen->base === 'edit' && $screen->post_type === 'product') {
                $page_context['page'] = 'product_list';
            } elseif ($screen->base === 'post' && $screen->post_type === 'product') {
                $post_id = isset($_GET['post']) ? intval($_GET['post']) : null;
                $page_context = array('page' => 'edit_product', 'entity_id' => $post_id, 'entity_type' => 'product',
                    'entity_name' => $post_id ? get_the_title($post_id) : null);
            } elseif (($screen->base === 'edit' && $screen->post_type === 'shop_order') ||
                      ($screen->id === 'woocommerce_page_wc-orders' && !isset($_GET['action']))) {
                $page_context['page'] = 'order_list';
            } elseif (($screen->base === 'post' && $screen->post_type === 'shop_order') ||
                      ($screen->id === 'woocommerce_page_wc-orders' && isset($_GET['action']) && $_GET['action'] === 'edit')) {
                $order_id = isset($_GET['post']) ? intval($_GET['post']) : (isset($_GET['id']) ? intval($_GET['id']) : null);
                $page_context = array('page' => 'edit_order', 'entity_id' => $order_id, 'entity_type' => 'order', 'entity_name' => null);
            } elseif ($screen->base === 'edit' && $screen->post_type === 'post') {
                $page_context['page'] = 'post_list';
            } elseif (in_array($screen->base, array("post", "post-new"), true) && $screen->post_type === "post") {
                // Blog post editor detection
                $post_id = isset($_GET["post"]) ? intval($_GET["post"]) : null;
                $page_context["page"] = "blog_editor";
                $page_context["page_type"] = "blog_editor";
                $page_context["is_new_post"] = ($screen->base === "post-new");
                if ($post_id) {
                    $blog_post = get_post($post_id);
                    if ($blog_post) {
                        $page_context["entity_id"] = $blog_post->ID;
                        $page_context["entity_type"] = "post";
                        $page_context["entity_name"] = $blog_post->post_title;
                        $page_context["post_status"] = $blog_post->post_status;
                        $page_context["word_count"] = str_word_count(strip_tags($blog_post->post_content));
                    }
                }
            } elseif ($screen->base === 'dashboard') {
                $page_context['page'] = 'dashboard';
            } elseif ($screen->base === 'plugins') {
                $page_context['page'] = 'plugins';
            } elseif ($screen->id === 'woocommerce_page_wc-settings') {
                $page_context['page'] = 'wc_settings';
            }
        }
        echo '<script>window.PELIGENT_PAGE_CONTEXT = ' . wp_json_encode($page_context) . ';</script>';

        echo '</aside>';

        // Floating toggle button on all admin pages (controlled by setting)
        $show_floating_widget = get_option('peligent_show_floating_widget', '1');
        if ($show_floating_widget === '1') { // Show floating toggle if enabled in settings
            $toggle_icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
            echo '<button type="button" class="peligent-floating-toggle" id="peligent-floating-toggle" title="' . esc_attr__('Open Peligent Assistant', 'peligent-ai-assistant') . '">';
            echo '<img src="' . esc_url($toggle_icon_url) . '" alt="Peligent" width="26" height="26" />';
            echo '</button>';
            echo '<script>document.getElementById("peligent-floating-toggle").addEventListener("click",function(e){e.preventDefault();var s=document.querySelector(".peligent-ai-fixed-sidebar");if(s){var h=s.classList.contains("peligent-ai-hidden");if(h){s.classList.remove("peligent-ai-hidden");document.body.classList.remove("peligent-ai-sidebar-hidden");this.style.display="none";try{localStorage.setItem("peligent_ai_sidebar_visible","1")}catch(ex){}}else{s.classList.add("peligent-ai-hidden");document.body.classList.add("peligent-ai-sidebar-hidden");this.style.display="";try{localStorage.setItem("peligent_ai_sidebar_visible","0")}catch(ex){}}}});</script>';
        }
    }

    public function inject_console_filter()
    {
        // Console filtering removed to avoid interfering with other plugins
        return;
    }

    public function admin_assets($hook)
    {
        wp_enqueue_script('jquery');
        
        // Enqueue RTL stylesheet if the site is RTL - will be enqueued after sidebar.css
        // This is handled later to ensure proper loading order
        
        // Register and enqueue styles/scripts for Peligent admin pages
        $peligent_pages = array(
            'toplevel_page_peligent-connect',
            'peligent_page_peligent-connect',
            'peligent_page_peligent-bulk-update',
            'peligent_page_peligent-blog-update',
            'peligent_page_peligent-action-history',
            'peligent_page_peligent-bots',
            'peligent_page_peligent-reports',
            'peligent_page_peligent-integrations',
        );
        if (in_array($hook, $peligent_pages, true)) {
            // Enqueue admin settings CSS on all Peligent pages
            wp_enqueue_style(
                'peligent-admin-settings',
                plugins_url('assets/admin-settings.css', __FILE__),
                array(),
                '1.7.09'
            );

            // Enqueue admin settings JS only on the settings page
            if ($hook === 'toplevel_page_peligent-connect' || $hook === 'peligent_page_peligent-connect') {
                wp_enqueue_script(
                    'peligent-admin-settings',
                    plugins_url('assets/admin-settings.js', __FILE__),
                    array('jquery'),
                    '1.7.09',
                    true
                );
            }
        }
        
        // Load on all admin pages, not just Peligent settings page
        $origin = 'https://app.peligent.com';
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');

        // Only enqueue if we have a token
        if (empty($site_token)) {
            return;
        }

        // Only enqueue if user has access
        if (! $this->is_user_allowed()) {
            return;
        }

        // Defaults (language/tone) for embed + content generation
        $assistant_defaults = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        if (!is_array($assistant_defaults)) {
            $assistant_defaults = array();
        }
        $default_language = !empty($assistant_defaults['language']) ? $assistant_defaults['language'] : 'en';
        $default_tone = !empty($assistant_defaults['tone']) ? $assistant_defaults['tone'] : 'Expert';

        wp_register_script(
            'peligent-ai-embed',
            plugins_url('assets/peligent-ai-embed.js', __FILE__),
            array('jquery'), // Depend on jQuery which WordPress includes
            '1.7.09',
            false // Load in header to ensure it's available early
        );
        wp_localize_script('peligent-ai-embed', 'PELIGENT_AI_CLIENT', array(
            'server'   => $origin,
            'token'    => $site_token,
            'site_url' => home_url('/'),
        ));
        wp_enqueue_script('peligent-ai-embed');

        // Register and enqueue sidebar styles
        wp_enqueue_style(
            'peligent-sidebar',
            plugins_url('assets/sidebar.css', __FILE__),
            array(),
            '1.7.09'
        );
        
        // Enqueue RTL stylesheet after sidebar.css if the site is RTL
        if (is_rtl()) {
            wp_enqueue_style(
                'peligent-rtl',
                plugins_url('assets/peligent-rtl.css', __FILE__),
                array('peligent-sidebar'), // Load after sidebar.css
                '1.7.09' // Bump version
            );
        }
        
        // Define peligentGenerateContent function early so it's available when buttons are clicked
        // Define it OUTSIDE IIFE to ensure it's available immediately
        $generate_content_script = "console.log('[Peligent] Early script loading in admin_assets...');

        // Defaults (language/tone) from WP settings
        window.PELIGENT_DEFAULTS = window.PELIGENT_DEFAULTS || {};
        window.PELIGENT_DEFAULTS.language = " . wp_json_encode($default_language) . ";
        window.PELIGENT_DEFAULTS.tone = " . wp_json_encode($default_tone) . ";
        
        // Define peligentGenerateContent function immediately (before buttons are rendered)
        window.peligentGenerateContent = function(fieldType, prodId) {
                console.log('[Peligent] ===== peligentGenerateContent CALLED (early version) =====');
                console.log('[Peligent] fieldType:', fieldType);
                console.log('[Peligent] prodId:', prodId);
                
                // Get product ID from URL if not provided
                if (!prodId) {
                    var urlParams = new URLSearchParams(window.location.search);
                    prodId = parseInt(urlParams.get('post')) || 0;
                    console.log('[Peligent] Got productId from URL:', prodId);
                }
                
                // Show sidebar if hidden
                console.log('[Peligent] Looking for sidebar...');
                var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                console.log('[Peligent] Sidebar found:', !!sidebar);
                if (sidebar) {
                    console.log('[Peligent] Sidebar classes before:', sidebar.className);
                    sidebar.classList.remove('peligent-ai-hidden');
                    document.body.classList.remove('peligent-ai-sidebar-hidden');
                    console.log('[Peligent] Sidebar classes after:', sidebar.className);
                    try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch (e) {
                        console.warn('[Peligent] Could not set localStorage:', e);
                    }
                } else {
                    console.warn('[Peligent] Sidebar not found!');
                }
                
                // Get current field value for default prompt
                console.log('[Peligent] Getting current field value for:', fieldType);
                var currentValue = '';
                if (fieldType === 'short_description') {
                    if (typeof jQuery !== 'undefined') {
                        currentValue = jQuery('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]').val() || '';
                        console.log('[Peligent] Short description value (jQuery):', currentValue.substring(0, 50));
                    } else {
                        var excerptEl = document.getElementById('excerpt') || document.querySelector('textarea[name=\"excerpt\"]');
                        currentValue = excerptEl ? excerptEl.value : '';
                        console.log('[Peligent] Short description value (native):', currentValue.substring(0, 50));
                    }
                } else {
                    // Get description from editor
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        currentValue = tinyMCE.get('content').getContent({ format: 'text' }) || '';
                        console.log('[Peligent] Description value (tinyMCE):', currentValue.substring(0, 50));
                    } else {
                        if (typeof jQuery !== 'undefined') {
                            currentValue = jQuery('#content, textarea[name=\"content\"]').val() || '';
                            console.log('[Peligent] Description value (jQuery):', currentValue.substring(0, 50));
                        } else {
                            var contentEl = document.getElementById('content') || document.querySelector('textarea[name=\"content\"]');
                            currentValue = contentEl ? contentEl.value : '';
                            console.log('[Peligent] Description value (native):', currentValue.substring(0, 50));
                        }
                    }
                }
                
                // Send raw content only — prompt construction is handled by the frontend/server
                var defaultPrompt = currentValue || '';
                console.log('[Peligent] Default prompt length:', defaultPrompt.length);
                
                // Determine output type based on field
                var outputType = fieldType === 'short_description' ? 'short_description' : 'description';
                console.log('[Peligent] Output type:', outputType);
                
                // Send message to Peligent iframe
                console.log('[Peligent] Looking for iframe...');
                var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
                console.log('[Peligent] Iframe found:', !!iframe);
                console.log('[Peligent] Iframe contentWindow:', iframe ? !!iframe.contentWindow : false);
                
                if (iframe && iframe.contentWindow) {
                var message = {
                    type: 'WPAI_GENERATE_CONTENT',
                        prompt: defaultPrompt,
                        outputType: outputType,
                        outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                        tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                        productId: prodId,
                        fieldType: fieldType
                    };
                    console.log('[Peligent] Sending message to iframe:', message);
                    iframe.contentWindow.postMessage(message, 'https://app.peligent.com');
                    console.log('[Peligent] ✓ Message sent successfully to iframe');
                } else {
                    console.log('[Peligent] Iframe not ready, queuing message for when iframe loads...');
                    // Queue the message — it will be sent after iframe ACKs
                    if (typeof pendingGenerateContent !== 'undefined') {
                        pendingGenerateContent = message;
                    } else {
                        window.pendingGenerateContent = message;
                    }
                    // Also retry after a delay as fallback
                    setTimeout(function() {
                        var sidebar2 = document.querySelector('.peligent-ai-fixed-sidebar');
                        var iframe2 = sidebar2 ? sidebar2.querySelector('iframe.peligent-ai-iframe') : null;
                        if (iframe2 && iframe2.contentWindow) {
                            iframe2.contentWindow.postMessage(message, 'https://app.peligent.com');
                            console.log('[Peligent] ✓ Message sent on retry');
                        }
                    }, 1500);
                }
                console.log('[Peligent] ===== peligentGenerateContent END =====');
        };
        
        console.log('[Peligent] peligentGenerateContent function defined (early):', typeof window.peligentGenerateContent);
        console.log('[Peligent] Function available on window:', 'peligentGenerateContent' in window);

        // Blog content generation function for post edit pages
        window.peligentGenerateBlogContent = function(postId) {
            console.log('[Peligent] ===== peligentGenerateBlogContent CALLED =====');
            console.log('[Peligent] postId:', postId);

            // Get post ID from URL if not provided
            if (!postId) {
                var urlParams = new URLSearchParams(window.location.search);
                postId = parseInt(urlParams.get('post')) || 0;
            }

            // Show sidebar if hidden
            var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
            if (sidebar) {
                sidebar.classList.remove('peligent-ai-hidden');
                document.body.classList.remove('peligent-ai-sidebar-hidden');
                try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch (e) {}
            }

            // Get current content from editor
            var currentValue = '';
            if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                currentValue = tinyMCE.get('content').getContent({ format: 'text' }) || '';
            } else if (typeof jQuery !== 'undefined') {
                currentValue = jQuery('#content, textarea[name=\"content\"]').val() || '';
            } else {
                var contentEl = document.getElementById('content');
                currentValue = contentEl ? contentEl.value : '';
            }

            // Get post title for context
            var postTitle = '';
            var titleEl = document.getElementById('title');
            if (titleEl) {
                postTitle = titleEl.value || '';
            }

            // Send raw content only — prompt construction is handled by the frontend/server
            var defaultPrompt = currentValue || '';

            // Send message to Peligent iframe
            var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
            if (iframe && iframe.contentWindow) {
                var message = {
                    type: 'WPAI_GENERATE_CONTENT',
                    prompt: defaultPrompt,
                    outputType: 'blog_content',
                    outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                    tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                    productId: 0,
                    postId: postId,
                    fieldType: 'blog_content',
                    postTitle: postTitle
                };
                console.log('[Peligent] Sending blog content message to iframe:', message);
                iframe.contentWindow.postMessage(message, 'https://app.peligent.com');
            } else {
                setTimeout(function() {
                    var s = document.querySelector('.peligent-ai-fixed-sidebar');
                    var f = s ? s.querySelector('iframe.peligent-ai-iframe') : null;
                    if (f && f.contentWindow) {
                        f.contentWindow.postMessage({
                            type: 'WPAI_GENERATE_CONTENT',
                            prompt: defaultPrompt,
                            outputType: 'blog_content',
                            outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                            tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                            productId: 0,
                            postId: postId,
                            fieldType: 'blog_content',
                            postTitle: postTitle
                        }, 'https://app.peligent.com');
                    } else {
                        alert('Peligent sidebar is not available. Please make sure it is open.');
                    }
                }, 500);
            }
            console.log('[Peligent] ===== peligentGenerateBlogContent END =====');
        };

        console.log('[Peligent] peligentGenerateBlogContent function defined:', typeof window.peligentGenerateBlogContent);";
        wp_add_inline_script('peligent-ai-embed', $generate_content_script);
        
        // Register script handle for sidebar initialization
        wp_enqueue_script(
            'peligent-sidebar-init',
            plugins_url('assets/sidebar-init.js', __FILE__),
            array('peligent-ai-embed'),
            '1.7.09',
            true
        );
        
        // Inline script to handle admin bar click and media library integration
        // Register a separate script handle for media library integration
        wp_register_script(
            'peligent-media-library',
            false,
            array('jquery', 'peligent-ai-embed'),
            '1.7.09',
            true
        );
        wp_enqueue_script('peligent-media-library');
        
        // Build the media library integration script
        $rest_url = esc_url(rest_url('wp/v2/media'));
        $rest_nonce = esc_js(wp_create_nonce('wp_rest'));
        $icon_url = esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__));
        $base64_endpoint = esc_url(rest_url('peligent/v1/image-to-base64'));
        $media_library_script = "(function() {
            function initAdminBarToggle() {
                var chatIcon = document.querySelector('#wp-admin-bar-peligent-chat a');
                if (chatIcon && !chatIcon.dataset.peligentAiInitialized) {
                    chatIcon.dataset.peligentAiInitialized = '1';
                    chatIcon.addEventListener('click', function(e) {
                        e.preventDefault();
                        var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                        if (sidebar) {
                            var isHidden = sidebar.classList.contains('peligent-ai-hidden');
                            if (isHidden) {
                                sidebar.classList.remove('peligent-ai-hidden');
                                document.body.classList.remove('peligent-ai-sidebar-hidden');
                                try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                            } else {
                                sidebar.classList.add('peligent-ai-hidden');
                                document.body.classList.add('peligent-ai-sidebar-hidden');
                                try { localStorage.setItem('peligent_ai_sidebar_visible', '0'); } catch {}
                            }
                        }
                        return false;
                    });
                }
            }
            
            // Function to upload edited image to WordPress media library
            function uploadEditedImageToMedia(imageDataUrl, originalImageData) {
                // Show loading for upload
                showPeligentLoading('Uploading edited image...');
                
                // Convert data URL or regular URL to blob
                var blobPromise;
                if (imageDataUrl.startsWith('data:')) {
                    // Data URL - convert directly to blob
                    var arr = imageDataUrl.split(',');
                    var mime = arr[0].match(/:(.*?);/)[1];
                    var bstr = atob(arr[1]);
                    var n = bstr.length;
                    var u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    blobPromise = Promise.resolve(new Blob([u8arr], { type: mime }));
                } else {
                    // Regular URL - fetch as blob
                    blobPromise = fetch(imageDataUrl).then(function(response) {
                        return response.blob();
                    });
                }
                
                blobPromise.then(function(blob) {
                        // Create FormData for upload
                        var formData = new FormData();
                        var filename = originalImageData.filename || 'peligent-edited-image.png';
                        // Add timestamp to filename to avoid conflicts
                        var timestamp = new Date().getTime();
                        var nameParts = filename.split('.');
                        var extension = nameParts.length > 1 ? nameParts.pop() : 'png';
                        var baseName = nameParts.join('.');
                        var newFilename = baseName + '-peligent-' + timestamp + '.' + extension;
                        
                        formData.append('file', blob, newFilename);
                        formData.append('title', (originalImageData.title || 'Peligent Edited Image') + ' (Edited)');
                        if (originalImageData.alt) {
                            formData.append('alt_text', originalImageData.alt);
                        }
                        if (originalImageData.caption) {
                            formData.append('caption', originalImageData.caption);
                        }
                        if (originalImageData.description) {
                            formData.append('description', originalImageData.description);
                        }
                        
                        // Upload to WordPress media library
                        var restUrl = " . wp_json_encode($rest_url) . ";
                        return fetch(restUrl, {
                            method: 'POST',
                            body: formData,
                            credentials: 'same-origin',
                            headers: {
                                'X-WP-Nonce': " . wp_json_encode($rest_nonce) . "
                            }
                        });
                    })
                    .then(function(response) {
                        return response.json();
                    })
                    .then(function(attachment) {
                        console.log('[Peligent] Image uploaded successfully:', attachment);
                        
                        // Update loading text
                        var loadingText = document.querySelector('#peligent-loading-overlay .peligent-loading-text');
                        if (loadingText) {
                            loadingText.textContent = 'Refreshing media library...';
                        }
                        
                        // Store uploaded attachment ID for later refresh
                        if (!window._peligentUploadedAttachments) {
                            window._peligentUploadedAttachments = [];
                        }
                        window._peligentUploadedAttachments.push(attachment.id);
                        
                        // Show success notice
                        var notice = document.createElement('div');
                        notice.className = 'notice notice-success is-dismissible';
                        var viewLink = attachment.link ? '<a href=\"' + attachment.link + '\" target=\"_blank\">View attachment</a>' : '';
                        var editLink = attachment.id ? '<a href=\"' + (attachment.link || '#') + '\" target=\"_blank\">Edit attachment</a>' : '';
                        notice.innerHTML = '<p><strong>Success!</strong> Image edited and uploaded successfully. ' + viewLink + (viewLink && editLink ? ' | ' : '') + editLink + '</p>';
                        notice.style.margin = '10px 0';
                        notice.style.padding = '10px';
                        
                        // Try to add notice to various possible containers
                        var noticeContainer = document.querySelector('.wrap, #wpbody-content, .wp-header-end, .notice');
                        if (noticeContainer && noticeContainer.parentNode) {
                            noticeContainer.parentNode.insertBefore(notice, noticeContainer);
                        } else {
                            // Fallback: add to body
                            var body = document.querySelector('body');
                            if (body) {
                                body.insertBefore(notice, body.firstChild);
                            }
                        }
                        
                        // Auto-dismiss after 5 seconds
                        setTimeout(function() {
                            if (notice.parentNode) {
                                notice.parentNode.removeChild(notice);
                            }
                        }, 5000);
                        
                        // Refresh media library using WordPress _requery method
                        setTimeout(function() {
                            try {
                                if (typeof wp !== 'undefined' && wp.media && wp.media.frame) {
                                    var frame = wp.media.frame;
                                    
                                    // Method 1: Use _requery to force refresh (WordPress native method)
                                    if (frame.content && frame.content.get() !== null) {
                                        try {
                                            var content = frame.content.get();
                                            if (content.collection && content.collection._requery) {
                                                content.collection._requery(true);
                                                console.log('[Peligent] Refreshed media library using _requery');
                                                // Hide loading after refresh
                                                setTimeout(function() {
                                                    hidePeligentLoading();
                                                }, 300);
                                            }
                                        } catch (requeryError) {
                                            console.log('[Peligent] _requery failed:', requeryError);
                                            hidePeligentLoading();
                                        }
                                    } else {
                                        // Media frame not open, hide loading
                                        hidePeligentLoading();
                                    }
                                    
                                    // Method 2: Also try library refresh
                                    if (frame.library) {
                                        try {
                                            // Reset and reload library
                                            if (frame.library.reset) {
                                                frame.library.reset();
                                            }
                                            if (frame.library.more) {
                                                frame.library.more();
                                            }
                                            
                                            // Refresh props
                                            if (frame.library.props) {
                                                frame.library.props.set({ ignore: (+ new Date()) });
                                            }
                                            
                                            console.log('[Peligent] Refreshed media library using library methods');
                                        } catch (libraryError) {
                                            console.log('[Peligent] Library refresh failed:', libraryError);
                                        }
                                    }
                                }
                                
                                // Trigger jQuery event for other scripts
                                if (typeof jQuery !== 'undefined') {
                                    jQuery(document).trigger('peligent:imageUploaded', [attachment]);
                                    jQuery(document).trigger('media:uploaded', [attachment]);
                                }
                            } catch (e) {
                                console.log('[Peligent] Could not refresh media library:', e);
                            }
                        }, 500);
                        
                        // Also try after a longer delay using _requery
                        setTimeout(function() {
                            try {
                                if (typeof wp !== 'undefined' && wp.media && wp.media.frame) {
                                    var frame = wp.media.frame;
                                    
                                    // Use _requery method again
                                    if (frame.content && frame.content.get() !== null) {
                                        try {
                                            var content = frame.content.get();
                                            if (content.collection && content.collection._requery) {
                                                content.collection._requery(true);
                                                console.log('[Peligent] Secondary refresh using _requery');
                                            }
                                        } catch (e) {
                                            // Ignore
                                        }
                                    }
                                    
                                    // Also try library refresh
                                    if (frame.library && frame.library.more) {
                                        frame.library.more();
                                    }
                                }
                            } catch (e) {
                                // Ignore
                            }
                        }, 1000);
                        
                        // Also try to trigger a custom event for other scripts to listen
                        try {
                            var event = new CustomEvent('peligent:imageUploaded', { detail: attachment });
                            window.dispatchEvent(event);
                        } catch (e) {
                            // Ignore if CustomEvent not supported
                        }
                    })
                    .catch(function(error) {
                        console.error('[Peligent] Failed to upload edited image:', error);
                        hidePeligentLoading();
                        alert('Failed to upload edited image. Please try again.');
                    });
            }
            
            // Function to show loading overlay
            function showPeligentLoading(text) {
                hidePeligentLoading(); // Remove any existing loading
                var overlay = document.createElement('div');
                overlay.className = 'peligent-loading-overlay';
                overlay.id = 'peligent-loading-overlay';
                overlay.innerHTML = '<div class=\"peligent-loading-spinner\"></div><div class=\"peligent-loading-text\">' + (text || 'Loading...') + '</div>';
                document.body.appendChild(overlay);
            }
            
            // Function to hide loading overlay
            function hidePeligentLoading() {
                var overlay = document.getElementById('peligent-loading-overlay');
                if (overlay) {
                    overlay.remove();
                }
            }
            
            // Function to send image data to Peligent iframe and open edit modal
            function sendImageToPeligent(imageData) {
                var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                if (!sidebar) return;
                
                // Make sure sidebar is visible
                sidebar.classList.remove('peligent-ai-hidden');
                document.body.classList.remove('peligent-ai-sidebar-hidden');
                try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                
                console.log('[Peligent] Preparing to send image data:', {
                    hasBase64Data: !!(imageData.base64Data || imageData.base64DataOnly),
                    base64DataLength: imageData.base64Data ? imageData.base64Data.length : 0,
                    base64DataOnlyLength: imageData.base64DataOnly ? imageData.base64DataOnly.length : 0,
                    mimeType: imageData.mimeType,
                    id: imageData.id
                });
                
                // Find the iframe and send message
                var iframe = sidebar.querySelector('iframe.peligent-ai-iframe');
                if (iframe && iframe.contentWindow) {
                    try {
                        var message = {
                            type: 'WPAI_IMAGE_EDIT',
                            image: imageData,
                            openModal: true // Signal to open the edit modal
                        };
                        
                        // Ensure base64 data is included (postMessage can handle large strings)
                        if (imageData.base64Data || imageData.base64DataOnly) {
                            console.log('[Peligent] Sending with base64 data');
                        } else {
                            console.warn('[Peligent] WARNING: No base64 data in imageData!');
                        }
                        
                        iframe.contentWindow.postMessage(message, 'https://app.peligent.com');
                        console.log('[Peligent] Sent image edit data to iframe, image keys:', Object.keys(imageData));
                        
                        // Hide loading after a short delay to allow modal to open
                        setTimeout(function() {
                            hidePeligentLoading();
                        }, 500);
                    } catch (e) {
                        console.warn('[Peligent] Could not send image data to iframe:', e);
                        hidePeligentLoading();
                    }
                } else {
                    console.warn('[Peligent] Iframe not found, retrying...');
                    // Retry after a short delay if iframe is not ready
                    setTimeout(function() {
                        sendImageToPeligent(imageData);
                    }, 500);
                }
            }
            
            // Listen for edited image from Peligent
            // Use a separate listener to avoid conflicts
            if (!window._peligentImageEditListenerAdded) {
                window._peligentImageEditListenerAdded = true;
                window.addEventListener('message', function(event) {
                    // Accept messages from Peligent origin or same origin (for iframe)
                    var allowedOrigins = ['https://app.peligent.com'];
                    if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                        allowedOrigins.push('http://localhost:3000', 'http://127.0.0.1:3000');
                    }
                    
                    var isAllowedOrigin = allowedOrigins.indexOf(event.origin) !== -1
                        || event.origin === window.location.origin;
                    
                    if (!isAllowedOrigin) {
                        return;
                    }
                    
                    var data = event.data;
                    var type = data && data.type;
                    var isImageEditApply = type === 'WPAI_IMAGE_EDIT_APPLY' || type === 'PELIGENT_AI_IMAGE_EDIT_APPLY';
                    var isGenerateContentResult = type === 'WPAI_GENERATE_CONTENT_RESULT' || type === 'PELIGENT_AI_GENERATE_CONTENT_RESULT';
                    if (isImageEditApply) {
                        // Received edited image from Peligent
                        console.log('[Peligent] Received image edit apply message:', type, data);
                        var editedImageDataUrl = data.editedImageUrl || data.editedImage;
                        var originalImageData = data.originalImage || {};
                        
                        if (editedImageDataUrl) {
                            console.log('[Peligent] Received edited image, uploading to media library...');
                            uploadEditedImageToMedia(editedImageDataUrl, originalImageData);
                        } else {
                            console.warn('[Peligent] No edited image URL in message');
                        }
                    } else if (isGenerateContentResult) {
                        // Received generated content from Peligent for product descriptions
                        console.log('[Peligent] Received generate content result message:', type, data);
                        var generatedContent = data.content || '';
                        var fieldType = data.fieldType || data.outputType || 'description';
                        
                        if (!generatedContent) {
                            console.warn('[Peligent] No content in generated content result message');
                            return;
                        }
                        
                        try {
                            if (fieldType === 'short_description') {
                                // Apply to product short description (excerpt) field
                                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                                    console.log('[Peligent] Applying generated content via tinyMCE(excerpt)');
                                    tinyMCE.get('excerpt').setContent(generatedContent);
                                } else if (typeof jQuery !== 'undefined') {
                                    console.log('[Peligent] Applying generated content via textarea excerpt (jQuery)');
                                    jQuery('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]').val(generatedContent);
                                } else {
                                    console.log('[Peligent] Applying generated content via textarea excerpt (native)');
                                    var excerptEl = document.getElementById('excerpt') || document.querySelector('textarea[name=\"excerpt\"]');
                                    if (excerptEl) {
                                        excerptEl.value = generatedContent;
                                    }
                                }
                            } else {
                                // Apply to main product description field
                                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                                    console.log('[Peligent] Applying generated content via tinyMCE(content)');
                                    tinyMCE.get('content').setContent(generatedContent);
                                } else if (typeof jQuery !== 'undefined') {
                                    console.log('[Peligent] Applying generated content via textarea content (jQuery)');
                                    jQuery('#content, textarea[name=\"content\"]').val(generatedContent);
                                } else {
                                    console.log('[Peligent] Applying generated content via textarea content (native)');
                                    var contentEl = document.getElementById('content') || document.querySelector('textarea[name=\"content\"]');
                                    if (contentEl) {
                                        contentEl.value = generatedContent;
                                    }
                                }
                            }
                            
                            // Show success notice
                            var notice = document.createElement('div');
                            notice.className = 'notice notice-success is-dismissible';
                            notice.innerHTML = '<p><strong>Success!</strong> Content generated and applied successfully.</p>';
                            notice.style.margin = '10px 0';
                            notice.style.padding = '10px';
                            
                            var noticeContainer = document.querySelector('.wrap, #wpbody-content, .wp-header-end');
                            if (noticeContainer && noticeContainer.parentNode) {
                                noticeContainer.parentNode.insertBefore(notice, noticeContainer);
                            } else {
                                var body = document.querySelector('body');
                                if (body) {
                                    body.insertBefore(notice, body.firstChild);
                                }
                            }
                            
                            // Auto-dismiss after 5 seconds
                            setTimeout(function() {
                                if (notice.parentNode) {
                                    notice.parentNode.removeChild(notice);
                                }
                            }, 5000);
                        } catch (e) {
                            console.error('[Peligent] Failed to apply generated content:', e);
                        }
                    }
                });
            }
            
            // Function to extract image data from WordPress media library
            function extractImageData(attachment) {
                if (!attachment || !attachment.id) return null;
                
                var imageData = {
                    id: attachment.id,
                    url: attachment.url || '',
                    filename: attachment.filename || '',
                    title: attachment.title || '',
                    alt: attachment.alt || '',
                    caption: attachment.caption || '',
                    description: attachment.description || '',
                    mime: attachment.mime || '',
                    sizes: attachment.sizes || {}
                };
                
                // Get full size URL if available
                if (attachment.sizes && attachment.sizes.full) {
                    imageData.fullSizeUrl = attachment.sizes.full.url;
                } else if (attachment.url) {
                    imageData.fullSizeUrl = attachment.url;
                }
                
                return imageData;
            }
            
            // Function to refresh media library when modal opens using _requery
            function setupMediaLibraryRefresh() {
                if (typeof wp === 'undefined' || !wp.media) {
                    return;
                }
                
                // Hook into media modal opening to refresh library using _requery
                if (wp.media.view && wp.media.view.Modal) {
                    if (!wp.media.view.Modal.prototype._peligentRefreshHooked) {
                        wp.media.view.Modal.prototype._peligentRefreshHooked = true;
                        
                        wp.media.view.Modal.prototype.on('open', function() {
                            if (wp.media.frame && wp.media.frame.content && wp.media.frame.content.get() !== null) {
                                try {
                                    // Use _requery to force refresh (WordPress native method)
                                    var content = wp.media.frame.content.get();
                                    if (content.collection && content.collection._requery) {
                                        content.collection._requery(true);
                                        console.log('[Peligent] Refreshed media library on modal open using _requery');
                                    }
                                } catch (e) {
                                    console.log('[Peligent] Error refreshing on modal open:', e);
                                }
                            }
                        });
                    }
                }
            }
            
            // Add Peligent button to WordPress media library
            function initMediaLibraryIntegration() {
                if (typeof wp === 'undefined' || !wp.media || !wp.media.view || !wp.media.view.Attachment) {
                    console.warn('[Peligent] WordPress media library not available');
                    return;
                }
                
                // Check if Details view exists
                if (!wp.media.view.Attachment.Details) {
                    console.warn('[Peligent] Attachment.Details view not available');
                    return;
                }
                
                // Prevent multiple extensions
                if (wp.media.view.Attachment.Details.prototype._peligentExtended) {
                    return;
                }
                
                // Setup media library refresh hook
                setupMediaLibraryRefresh();
                
                var restUrl = " . wp_json_encode($rest_url) . ";
                if (restUrl.endsWith('/')) {
                    restUrl = restUrl.slice(0, -1);
                }
                
                // Add Peligent button to attachment details modal
                var OriginalAttachmentDetails = wp.media.view.Attachment.Details;
                wp.media.view.Attachment.Details = OriginalAttachmentDetails.extend({
                    render: function() {
                        OriginalAttachmentDetails.prototype.render.apply(this, arguments);
                        
                        var attachment = this.model.toJSON();
                        // Only show button for images
                        if (attachment.type === 'image' && attachment.id) {
                            var \$buttonContainer = this.\$el.find('.attachment-actions');
                            if (\$buttonContainer.length === 0) {
                                \$buttonContainer = this.\$el.find('.attachment-info');
                            }
                            
                            // Check if button already exists
                            if (\$buttonContainer.find('.peligent-edit-image-btn').length === 0) {
                                var \$span = jQuery('<span>').css({'display': 'inline-flex', 'align-items': 'center', 'gap': '6px'});
                                var \$icon = jQuery('<img>').attr({
                                    'src': " . wp_json_encode($icon_url) . ",
                                    'alt': 'Peligent',
                                    'width': '16',
                                    'height': '16'
                                }).css({'display': 'block'});
                                \$span.append(\$icon);
                                \$span.append(' Edit with Peligent');
                                var \$peligentBtn = jQuery('<button>')
                                    .addClass('button button-primary peligent-edit-image-btn')
                                    .attr('type', 'button')
                                    .css({
                                        'margin-top': '10px',
                                        'margin-left': '5px',
                                        'background': 'transparent',
                                        'border': '1px solid #2663EB',
                                        'border-color': '#2663EB',
                                        'color': '#2663EB'
                                    })
                                    .append(\$span)
                                    .on('click', function(e) {
                                        e.preventDefault();
                                        e.stopPropagation();
                                        
                                        var attachmentId = attachment.id;
                                        if (!attachmentId) return;
                                        
                                        // Show loading immediately
                                        showPeligentLoading('Preparing image for editing...');
                                        
                                        // Show sidebar immediately for better UX
                                        var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                                        if (sidebar) {
                                            sidebar.classList.remove('peligent-ai-hidden');
                                            document.body.classList.remove('peligent-ai-sidebar-hidden');
                                            try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                                        }
                                        
                                        // Fetch full attachment data
                                        fetch(restUrl + '/' + attachmentId)
                                            .then(function(response) {
                                                return response.json();
                                            })
                                            .then(function(attachmentData) {
                                                var imageData = {
                                                    id: attachmentData.id,
                                                    url: attachmentData.source_url || '',
                                                    filename: attachmentData.media_details.file || '',
                                                    title: attachmentData.title.rendered || '',
                                                    alt: attachmentData.alt_text || '',
                                                    caption: attachmentData.caption.rendered || '',
                                                    description: attachmentData.description.rendered || '',
                                                    mime: attachmentData.mime_type || '',
                                                    sizes: {}
                                                };
                                                
                                                // Extract sizes
                                                if (attachmentData.media_details && attachmentData.media_details.sizes) {
                                                    Object.keys(attachmentData.media_details.sizes).forEach(function(size) {
                                                        imageData.sizes[size] = {
                                                            url: attachmentData.media_details.sizes[size].source_url,
                                                            width: attachmentData.media_details.sizes[size].width,
                                                            height: attachmentData.media_details.sizes[size].height
                                                        };
                                                    });
                                                }
                                                
                                                if (attachmentData.media_details && attachmentData.media_details.sizes && attachmentData.media_details.sizes.full) {
                                                    imageData.fullSizeUrl = attachmentData.media_details.sizes.full.source_url;
                                                } else {
                                                    imageData.fullSizeUrl = attachmentData.source_url;
                                                }
                                                
                                                // Store original image data for later use when uploading edited image
                                                imageData.originalId = attachmentData.id;
                                                
                                                // Get product ID from URL if available (when editing product)
                                                var urlParams = new URLSearchParams(window.location.search);
                                                var productId = parseInt(urlParams.get('post')) || 0;
                                                if (productId > 0) {
                                                    imageData.productId = productId;
                                                    console.log('[Peligent] Extracted productId from URL:', productId);
                                                }
                                                
                                                // Convert image to base64 using WordPress REST API to avoid CORS issues
                                                var base64Endpoint = " . wp_json_encode($base64_endpoint) . ";
                                                fetch(base64Endpoint + '?id=' + attachmentId, {
                                                    credentials: 'include',
                                                    headers: {
                                                        'X-WP-Nonce': " . wp_json_encode($rest_nonce) . "
                                                    }
                                                })
                                                    .then(function(response) {
                                                        return response.json();
                                                    })
                                                    .then(function(result) {
                                                        if (result.success && result.dataUrl) {
                                                            imageData.base64Data = result.dataUrl;
                                                            imageData.base64DataOnly = result.base64;
                                                            imageData.mimeType = result.mimeType;
                                                            console.log('[Peligent] Image converted to base64 successfully');
                                                            // Update loading text
                                                            var loadingText = document.querySelector('#peligent-loading-overlay .peligent-loading-text');
                                                            if (loadingText) {
                                                                loadingText.textContent = 'Opening editor...';
                                                            }
                                                            sendImageToPeligent(imageData);
                                                        } else {
                                                            console.warn('[Peligent] Failed to convert image to base64:', result);
                                                            hidePeligentLoading();
                                                            sendImageToPeligent(imageData);
                                                        }
                                                    })
                                                    .catch(function(error) {
                                                        console.warn('[Peligent] Could not convert image to base64:', error);
                                                        hidePeligentLoading();
                                                        alert('Failed to load image. Please try again.');
                                                        // Fallback: send without base64, Peligent will try to fetch
                                                        sendImageToPeligent(imageData);
                                                    });
                                            })
                                            .catch(function(error) {
                                                console.warn('[Peligent] Could not fetch attachment data:', error);
                                            });
                                    });
                                
                                \$buttonContainer.append(\$peligentBtn);
                            }
                        }
                        
                        return this;
                    }
                });
                wp.media.view.Attachment.Details.prototype._peligentExtended = true;
                
                // Also add button to attachment edit modal (when editing existing attachment)
                if (wp.media.view.Attachment && wp.media.view.Attachment.Edit && !wp.media.view.Attachment.Edit.prototype._peligentExtended) {
                    var OriginalAttachmentEdit = wp.media.view.Attachment.Edit;
                    wp.media.view.Attachment.Edit = OriginalAttachmentEdit.extend({
                        render: function() {
                            OriginalAttachmentEdit.prototype.render.apply(this, arguments);
                            
                            var attachment = this.model.toJSON();
                            if (attachment.type === 'image' && attachment.id) {
                                var \$buttonContainer = this.\$el.find('.attachment-actions, .attachment-info, .media-sidebar');
                                
                                if (\$buttonContainer.find('.peligent-edit-image-btn').length === 0) {
                                var \$span2 = jQuery('<span>').css({'display': 'inline-flex', 'align-items': 'center', 'gap': '6px'});
                                var \$icon2 = jQuery('<img>').attr({
                                    'src': " . wp_json_encode($icon_url) . ",
                                        'alt': 'Peligent',
                                        'width': '16',
                                        'height': '16'
                                    }).css({'display': 'block'});
                                    \$span2.append(\$icon2);
                                    \$span2.append(' Edit with Peligent');
                                    var \$peligentBtn = jQuery('<button>')
                                        .addClass('button button-primary peligent-edit-image-btn')
                                        .attr('type', 'button')
                                        .css({
                                            'margin-top': '10px',
                                            'margin-left': '5px',
                                            'background': 'transparent',
                                            'border': '1px solid #2663EB',
                                            'border-color': '#2663EB',
                                            'color': '#2663EB',
                                            'width': '100%'
                                        })
                                        .append(\$span2)
                                        .on('click', function(e) {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            
                                            var attachmentId = attachment.id;
                                            if (!attachmentId) return;
                                            
                                            // Show loading immediately
                                            showPeligentLoading('Preparing image for editing...');
                                            
                                            // Show sidebar immediately for better UX
                                            var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                                            if (sidebar) {
                                                sidebar.classList.remove('peligent-ai-hidden');
                                                document.body.classList.remove('peligent-ai-sidebar-hidden');
                                                try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                                            }
                                            
                                            fetch(restUrl + '/' + attachmentId)
                                                .then(function(response) {
                                                    return response.json();
                                                })
                                                .then(function(attachmentData) {
                                                    var imageData = {
                                                        id: attachmentData.id,
                                                        url: attachmentData.source_url || '',
                                                        filename: attachmentData.media_details.file || '',
                                                        title: attachmentData.title.rendered || '',
                                                        alt: attachmentData.alt_text || '',
                                                        caption: attachmentData.caption.rendered || '',
                                                        description: attachmentData.description.rendered || '',
                                                        mime: attachmentData.mime_type || '',
                                                        sizes: {}
                                                    };
                                                    
                                                    if (attachmentData.media_details && attachmentData.media_details.sizes) {
                                                        Object.keys(attachmentData.media_details.sizes).forEach(function(size) {
                                                            imageData.sizes[size] = {
                                                                url: attachmentData.media_details.sizes[size].source_url,
                                                                width: attachmentData.media_details.sizes[size].width,
                                                                height: attachmentData.media_details.sizes[size].height
                                                            };
                                                        });
                                                    }
                                                    
                                                    if (attachmentData.media_details && attachmentData.media_details.sizes && attachmentData.media_details.sizes.full) {
                                                        imageData.fullSizeUrl = attachmentData.media_details.sizes.full.source_url;
                                                    } else {
                                                        imageData.fullSizeUrl = attachmentData.source_url;
                                                    }
                                                    
                                                    // Store original image data for later use when uploading edited image
                                                    imageData.originalId = attachmentData.id;
                                                    
                                                    // Get product ID from URL if available (when editing product)
                                                    var urlParams = new URLSearchParams(window.location.search);
                                                    var productId = parseInt(urlParams.get('post')) || 0;
                                                    if (productId > 0) {
                                                        imageData.productId = productId;
                                                        console.log('[Peligent] Extracted productId from URL:', productId);
                                                    }
                                                    
                                                // Convert image to base64 using WordPress REST API to avoid CORS issues
                                                var base64Endpoint = " . wp_json_encode($base64_endpoint) . ";
                                                fetch(base64Endpoint + '?id=' + attachmentId, {
                                                    credentials: 'include',
                                                    headers: {
                                                        'X-WP-Nonce': " . wp_json_encode($rest_nonce) . "
                                                    }
                                                })
                                                        .then(function(response) {
                                                            return response.json();
                                                        })
                                                        .then(function(result) {
                                                            if (result.success && result.dataUrl) {
                                                                imageData.base64Data = result.dataUrl;
                                                                imageData.base64DataOnly = result.base64;
                                                                imageData.mimeType = result.mimeType;
                                                                console.log('[Peligent] Image converted to base64 successfully');
                                                                // Update loading text
                                                                var loadingText = document.querySelector('#peligent-loading-overlay .peligent-loading-text');
                                                                if (loadingText) {
                                                                    loadingText.textContent = 'Opening editor...';
                                                                }
                                                                sendImageToPeligent(imageData);
                                                            } else {
                                                                console.warn('[Peligent] Failed to convert image to base64:', result);
                                                                hidePeligentLoading();
                                                                sendImageToPeligent(imageData);
                                                            }
                                                        })
                                                        .catch(function(error) {
                                                            console.warn('[Peligent] Could not convert image to base64:', error);
                                                            hidePeligentLoading();
                                                            alert('Failed to load image. Please try again.');
                                                            // Fallback: send without base64, Peligent will try to fetch
                                                            sendImageToPeligent(imageData);
                                                        });
                                                })
                                                .catch(function(error) {
                                                    console.warn('[Peligent] Could not fetch attachment data:', error);
                                                    hidePeligentLoading();
                                                });
                                        });
                                    
                                    \$buttonContainer.append(\$peligentBtn);
                                }
                            }
                            
                            return this;
                        }
                    });
                    wp.media.view.Attachment.Edit.prototype._peligentExtended = true;
                }
                
                // Add button after upload completes
                if (wp.media && wp.media.controller && wp.media.controller.Library) {
                    var originalLibrary = wp.media.controller.Library.prototype;
                    if (originalLibrary && !originalLibrary._peligentHooked) {
                        originalLibrary._peligentHooked = true;
                        
                        // Hook into selection change to add button after upload
                        var originalSelection = wp.media.controller.Library.prototype.select;
                        wp.media.controller.Library.prototype.select = function(options) {
                            var result = originalSelection.apply(this, arguments);
                            
                            setTimeout(function() {
                                var selection = wp.media.frame.state().get('selection');
                                if (selection && selection.length > 0) {
                                    var attachment = selection.first();
                                    if (attachment && attachment.get('type') === 'image') {
                                        var attachmentId = attachment.get('id');
                                        if (attachmentId) {
                                            // Trigger a refresh to show the button
                                            wp.media.frame.state().get('selection').trigger('reset');
                                        }
                                    }
                                }
                            }, 100);
                            
                            return result;
                        };
                    }
                }
            }
            
            // Try immediately
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', function() {
                    initAdminBarToggle();
                    // Wait for WordPress media library to load
                    setTimeout(initMediaLibraryIntegration, 1000);
                });
            } else {
                initAdminBarToggle();
                // Wait for WordPress media library to load
                setTimeout(initMediaLibraryIntegration, 1000);
            }
            // Also try after delays in case admin bar or media library loads later
            setTimeout(initAdminBarToggle, 100);
            setTimeout(initAdminBarToggle, 500);
            setTimeout(initMediaLibraryIntegration, 2000);
            setTimeout(initMediaLibraryIntegration, 3000);
        })();";
        wp_add_inline_script('peligent-media-library', $media_library_script);
    }


    /**
     * Fetch profile analysis status from the Peligent backend.
     *
     * @return array|WP_Error
     */
    private function fetch_profile_status()
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($site_token) || empty($connect_token)) {
            return new \WP_Error('no_token', 'Site token or connect secret not available');
        }

        $response = wp_remote_get(self::PELIGENT_PROFILE_STATUS_ENDPOINT, array(
            'headers' => array(
                'X-Peligent-Site-Token'    => $site_token,
                'X-Peligent-Connect-Token' => $connect_token,
            ),
            'timeout' => 15,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $decoded = json_decode($body, true);

        if ($code < 200 || $code >= 300 || !is_array($decoded)) {
            return new \WP_Error('api_error', 'Profile status request failed (HTTP ' . $code . ')');
        }

        return $decoded;
    }

    /**
     * AJAX handler for connecting to Peligent (replaces form POST + redirect).
     */
    public function ajax_connect()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_connect_nonce', 'nonce');

        // Save connect token
        if (isset($_POST['connect_token'])) {
            $previous_token = get_option(self::OPTION_CONNECT_KEY, '');
            $posted_token = sanitize_text_field(wp_unslash($_POST['connect_token']));
            update_option(self::OPTION_CONNECT_KEY, $posted_token);

            if ($posted_token !== $previous_token) {
                delete_option(self::OPTION_SITE_TOKEN);
                delete_option(self::OPTION_LAST_CONNECT_ERROR);
            }
        }

        // Save partner ID if provided
        if (isset($_POST['partner_id'])) {
            update_option(self::OPTION_PARTNER_ID, sanitize_text_field(wp_unslash($_POST['partner_id'])));
        }

        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($connect_token)) {
            wp_send_json_error(array('message' => 'Please enter the Connect Secret.'));
        }

        $connected = $this->perform_connection($connect_token);

        if ($connected) {
            wp_send_json_success(array('message' => 'Connected to Peligent successfully.'));
        } else {
            $last_error = get_option(self::OPTION_LAST_CONNECT_ERROR, '');
            wp_send_json_error(array('message' => $last_error ?: 'Failed to connect. Please check your Connect Secret and try again.'));
        }
    }

    /**
     * AJAX handler for saving Application Password from Step 4.
     */
    public function ajax_save_app_password()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_save_app_password_nonce', 'nonce');

        $app_pass = isset($_POST['app_password']) ? sanitize_text_field(wp_unslash($_POST['app_password'])) : '';
        if (empty($app_pass)) {
            wp_send_json_error(array('message' => 'Application Password is required.'));
        }

        $app = get_option(self::OPTION_APP_USER, array());
        if (!is_array($app)) {
            $app = array();
        }
        $app['app_password'] = $app_pass;
        update_option(self::OPTION_APP_USER, $app);

        // Re-send credentials to Peligent so the app password gets stored
        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (!empty($connect_token)) {
            $connected = $this->perform_connection($connect_token);
            if ($connected) {
                wp_send_json_success(array('message' => 'Application Password saved and sent to Peligent.'));
            } else {
                wp_send_json_success(array('message' => 'Application Password saved locally. Connection update pending.'));
            }
        } else {
            wp_send_json_success(array('message' => 'Application Password saved.'));
        }
    }

    /**
     * AJAX handler for enabling/disabling Advanced Features (auto app password).
     */
    public function ajax_toggle_floating_widget() {
        check_ajax_referer('peligent_toggle_widget_nonce', 'nonce');
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Unauthorized'));
        }
        $enabled = isset($_POST['enabled']) && $_POST['enabled'] === '1' ? '1' : '0';
        update_option('peligent_show_floating_widget', $enabled);
        wp_send_json_success(array('enabled' => $enabled));
    }

        public function ajax_enable_advanced_features()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_enable_advanced_features_nonce', 'nonce');

        $enable = isset($_POST['enable']) ? filter_var($_POST['enable'], FILTER_VALIDATE_BOOLEAN) : true;

        // Check we are connected
        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($connect_token)) {
            wp_send_json_error(array('message' => 'Please complete the setup wizard first.'));
        }

        $app = get_option(self::OPTION_APP_USER, array());
        if (!is_array($app)) {
            $app = array();
        }

        if ($enable) {
            // Ensure app user exists
            if (empty($app['user_id']) || !get_user_by('id', $app['user_id'])) {
                $app = $this->create_app_user_and_password(true);
                if (is_wp_error($app)) {
                    wp_send_json_error(array('message' => $app->get_error_message()));
                }
            } elseif (empty($app['app_password'])) {
                // User exists but no app password - create one
                if (!class_exists('WP_Application_Passwords')) {
                    wp_send_json_error(array('message' => 'Application Passwords not available on this WordPress version.'));
                }
                $app_pass_result = WP_Application_Passwords::create_new_application_password(
                    $app['user_id'],
                    array('name' => 'Peligent AI Assistant')
                );
                if (is_wp_error($app_pass_result)) {
                    wp_send_json_error(array('message' => $app_pass_result->get_error_message()));
                }
                $app['app_password'] = $app_pass_result[0];
                $app['app_password_label'] = 'Peligent AI Assistant';
                update_option(self::OPTION_APP_USER, $app);
            }

            // Send credentials to Peligent backend
            $connected = $this->perform_connection($connect_token);
            if ($connected) {
                wp_send_json_success(array(
                    'message' => 'Advanced Features enabled successfully.',
                    'enabled' => true,
                    'features' => array('Site health monitoring', 'Blog post management', 'Page speed insights', 'Image uploads'),
                ));
            } else {
                $last_error = get_option(self::OPTION_LAST_CONNECT_ERROR, '');
                wp_send_json_error(array('message' => $last_error ?: 'Failed to send credentials. Please try again.'));
            }
        } else {
            // Disable: revoke app passwords and clear credentials
            if (!empty($app['user_id']) && class_exists('WP_Application_Passwords')) {
                $passwords = WP_Application_Passwords::get_user_application_passwords($app['user_id']);
                foreach ($passwords as $pw) {
                    if (stripos($pw['name'], 'Peligent') !== false) {
                        WP_Application_Passwords::delete_application_password($app['user_id'], $pw['uuid']);
                    }
                }
            }

            // Clear stored password
            $app['app_password'] = '';
            unset($app['credentials_sent']);
            update_option(self::OPTION_APP_USER, $app);

            // Re-send with empty password (backend stores __unused__)
            $this->perform_connection($connect_token);

            wp_send_json_success(array(
                'message' => 'Advanced Features disabled.',
                'enabled' => false,
            ));
        }
    }

    /**
     * AJAX handler for profile polling from the wizard.
     */
    public function ajax_poll_profile()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error('Forbidden', 403);
        }

        check_ajax_referer('peligent_poll_profile_nonce', 'nonce');

        $result = $this->fetch_profile_status();

        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        }

        wp_send_json_success($result);
    }

    /**
     * AJAX handler for triggering a new profile analysis (called by Retry button).
     */
    public function ajax_trigger_profile()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error('Forbidden', 403);
        }

        check_ajax_referer('peligent_poll_profile_nonce', 'nonce');

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        if (empty($site_token) || empty($connect_token)) {
            wp_send_json_error('Not connected');
            return;
        }

        $response = wp_remote_post('https://app.peligent.com/api/integrations/woocommerce/profile-trigger', array(
            'headers' => array(
                'Content-Type'              => 'application/json',
                'X-Peligent-Site-Token'     => $site_token,
                'X-Peligent-Connect-Token'  => $connect_token,
            ),
            'timeout' => 10,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            wp_send_json_error($response->get_error_message());
            return;
        }

        wp_send_json_success(array('triggered' => true));
    }

    /**
     * Fetch profile settings from dashboard API.
     * Called ONLY when user visits the plugin settings/wizard page.
     * Uses 3s timeout so the plugin never slows down if dashboard is unreachable.
     * Sets $this->_profile_synced and $this->_profile_sync_message for UI indicator.
     * Returns array with keys: language, tone, industry, expectations, products, currency, timezone
     */
    public function fetch_profile_settings()
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            $this->_profile_synced = false;
            $this->_profile_sync_message = 'Not connected to Peligent Dashboard.';
            return $this->get_local_profile_settings();
        }

        $response = wp_remote_get(self::PELIGENT_PROFILE_SETTINGS_ENDPOINT, array(
            'headers' => array(
                'X-Site-Token' => $site_token,
                'Content-Type' => 'application/json',
            ),
            'timeout' => 3,
            'sslverify' => true,
        ));

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            $this->_profile_synced = false;
            $this->_profile_sync_message = 'Could not reach Peligent Dashboard. Showing locally saved settings.';
            return $this->get_local_profile_settings();
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $data = isset($body['data']) ? $body['data'] : (is_array($body) ? $body : array());

        $settings = array(
            'language'     => isset($data['language']) ? $data['language'] : '',
            'tone'         => isset($data['tone']) ? $data['tone'] : '',
            'industry'     => isset($data['industry']) ? $data['industry'] : '',
            'expectations' => isset($data['expectations']) ? $data['expectations'] : '',
            'products'     => isset($data['products']) ? $data['products'] : '',
            'currency'     => isset($data['currency']) ? $data['currency'] : '',
            'timezone'     => isset($data['timezone']) ? $data['timezone'] : 'UTC',
        );

        // Update local wp_options as cache (used by chatbot embed, offline fallback)
        $local = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        if (!is_array($local)) $local = array();
        $local['language'] = $settings['language'];
        $local['tone'] = $settings['tone'];
        $local['industry'] = $settings['industry'];
        $local['expectations'] = $settings['expectations'];
        $local['products'] = $settings['products'];
        $local['currency'] = $settings['currency'];
        update_option(self::OPTION_ASSISTANT_DEFAULTS, $local);
        update_option('peligent_last_profile_sync', current_time('mysql'));

        $this->_profile_synced = true;
        $this->_profile_sync_message = '';
        return $settings;
    }

    /**
     * Get profile settings from local wp_options (fallback when dashboard is unreachable).
     */
    private function get_local_profile_settings()
    {
        $defaults = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        if (!is_array($defaults)) $defaults = array();
        return array(
            'language'     => isset($defaults['language']) ? $defaults['language'] : '',
            'tone'         => isset($defaults['tone']) ? $defaults['tone'] : '',
            'industry'     => isset($defaults['industry']) ? $defaults['industry'] : '',
            'expectations' => isset($defaults['expectations']) ? $defaults['expectations'] : '',
            'products'     => isset($defaults['products']) ? $defaults['products'] : '',
            'currency'     => isset($defaults['currency']) ? $defaults['currency'] : '',
        );
    }

    /**
     * Push profile settings to dashboard API.
     * Returns true on success, WP_Error on failure.
     */
    private function push_profile_settings($settings)
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return new \WP_Error('no_token', 'Site not connected to dashboard');
        }

        $response = wp_remote_post(self::PELIGENT_PROFILE_SETTINGS_ENDPOINT, array(
            'headers' => array(
                'X-Site-Token' => $site_token,
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($settings),
            'timeout' => 3,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $code = wp_remote_retrieve_response_code($response);
        if ($code < 200 || $code >= 300) {
            return new \WP_Error('api_error', 'Dashboard returned HTTP ' . $code);
        }

        // Update local cache from API response
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $data = isset($body['data']) ? $body['data'] : array();
        $local = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        if (!is_array($local)) $local = array();
        if (isset($data['language'])) $local['language'] = $data['language'];
        if (isset($data['tone'])) $local['tone'] = $data['tone'];
        if (isset($data['industry'])) $local['industry'] = $data['industry'];
        if (isset($data['expectations'])) $local['expectations'] = $data['expectations'];
        if (isset($data['products'])) $local['products'] = $data['products'];
        if (isset($data['currency'])) $local['currency'] = $data['currency'];
        update_option(self::OPTION_ASSISTANT_DEFAULTS, $local);
        update_option('peligent_last_profile_sync', current_time('mysql'));

        return true;
    }

    /**
     * AJAX handler for saving assistant defaults (profile) from wizard Step 3 or settings page.
     */
    public function ajax_save_assistant_defaults()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_save_defaults_nonce', 'nonce');

        $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en';
        $tone = isset($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : 'Expert';
        $industry = isset($_POST['industry']) ? sanitize_text_field(wp_unslash($_POST['industry'])) : '';
        $products = isset($_POST['products']) ? sanitize_textarea_field(wp_unslash($_POST['products'])) : '';
        $expectations = isset($_POST['expectations']) ? sanitize_textarea_field(wp_unslash($_POST['expectations'])) : '';

        // Preserve existing currency if not provided (read-only AI-detected field)
        $existing = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        $currency = isset($_POST['currency']) ? sanitize_text_field(wp_unslash($_POST['currency'])) : (isset($existing['currency']) ? $existing['currency'] : '');

        $out = array(
            'language' => $language,
            'tone' => $tone,
            'industry' => $industry,
            'products' => $products,
            'expectations' => $expectations,
            'currency' => $currency,
            'updated_at' => current_time('mysql'),
        );

        // Push to dashboard API (source of truth)
        $push_result = $this->push_profile_settings(array(
            'language' => $language,
            'tone' => $tone,
            'industry' => $industry,
            'expectations' => $expectations,
            'currency' => $currency,
            'products' => $products,
        ));

        // Always save locally as fallback
        update_option(self::OPTION_ASSISTANT_DEFAULTS, $out);

        if (is_wp_error($push_result)) {
            // Dashboard unreachable — saved locally, will sync on next fetch
            wp_send_json_success(array(
                'message' => 'Saved locally. Dashboard sync will happen automatically.',
                'defaults' => $out,
                'sync_warning' => true,
            ));
        } else {
            wp_send_json_success(array('message' => 'Store profile saved successfully.', 'defaults' => $out));
        }
    }

    /**
     * AJAX handler for saving allowed users from wizard Step 4 or settings page.
     * Also sets onboarding completed flag when called from wizard.
     */
    public function ajax_save_allowed_users()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_save_users_nonce', 'nonce');

        // Mark onboarding as completed if requested (wizard flow)
        if (!empty($_POST['complete_onboarding'])) {
            update_option(self::OPTION_ONBOARDING_COMPLETED, true);
        }

        // Only update allowed_users if explicitly provided (avoid wiping on onboarding-only call)
        if (isset($_POST['allowed_users']) && is_array($_POST['allowed_users'])) {
            $allowed_users = array_map('intval', $_POST['allowed_users']);

            // Validate that all user IDs exist and are not customers/subscribers
            $validated_users = array();
            foreach ($allowed_users as $user_id) {
                $user = get_userdata($user_id);
                if ($user && !in_array('customer', $user->roles, true) && !in_array('subscriber', $user->roles, true)) {
                    $validated_users[] = $user_id;
                }
            }

            update_option(self::OPTION_ALLOWED_USERS, $validated_users);
        } else {
            $validated_users = get_option(self::OPTION_ALLOWED_USERS, array());
            if (!is_array($validated_users)) {
                $validated_users = array();
            }
        }

        wp_send_json_success(array(
            'message' => 'User access saved successfully.',
            'count' => count($validated_users),
        ));
    }

    /**
     * AJAX handler for resetting onboarding (re-run wizard).
     */
    public function ajax_reset_onboarding()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Forbidden'), 403);
        }
        check_ajax_referer('peligent_reset_onboarding_nonce', 'nonce');

        delete_option(self::OPTION_ONBOARDING_COMPLETED);

        wp_send_json_success(array('message' => 'Onboarding reset. Reloading...'));
    }

    public function handle_save_assistant_defaults()
    {
        if (! current_user_can('manage_options')) {
            wp_die('Forbidden');
        }
        check_admin_referer('peligent_wc_save_assistant_defaults');

        $language = isset($_POST['language']) ? sanitize_text_field(wp_unslash($_POST['language'])) : 'en';
        $tone = isset($_POST['tone']) ? sanitize_text_field(wp_unslash($_POST['tone'])) : 'Expert';
        $industry = isset($_POST['industry']) ? sanitize_text_field(wp_unslash($_POST['industry'])) : '';
        $products = isset($_POST['products']) ? sanitize_textarea_field(wp_unslash($_POST['products'])) : '';
        $expectations = isset($_POST['expectations']) ? sanitize_textarea_field(wp_unslash($_POST['expectations'])) : '';

        // Preserve existing currency if not provided (read-only AI-detected field)
        $existing = get_option(self::OPTION_ASSISTANT_DEFAULTS, array());
        $currency = isset($_POST['currency']) ? sanitize_text_field(wp_unslash($_POST['currency'])) : (isset($existing['currency']) ? $existing['currency'] : '');

        $out = array(
            'language' => $language,
            'tone' => $tone,
            'industry' => $industry,
            'products' => $products,
            'expectations' => $expectations,
            'currency' => $currency,
            'updated_at' => current_time('mysql'),
        );
        // Push to dashboard API (source of truth)
        $this->push_profile_settings(array(
            'language' => $language,
            'tone' => $tone,
            'industry' => $industry,
            'expectations' => $expectations,
        ));

        // Always save locally as fallback
        update_option(self::OPTION_ASSISTANT_DEFAULTS, $out);

        $this->add_admin_notice('Defaults saved successfully.');
        wp_safe_redirect(admin_url('admin.php?page=peligent-connect'));
        exit;
    }

    protected function revoke_app_user_internal()
    {
        $stored = get_option(self::OPTION_APP_USER);
        if (empty($stored['user_id'])) {
            return;
        }

        $user_id = (int) $stored['user_id'];
        $user = get_user_by('id', $user_id);
        if (! $user) {
            return;
        }

        if (class_exists('WP_Application_Passwords')) {
            delete_user_meta($user_id, 'application-passwords');
        }

        wp_delete_user($user_id);
    }

    /**
     * Register REST API endpoint for overview data
     */
    public function register_overview_endpoint()
    {
        register_rest_route('peligent/v1', '/overview', array(
            'methods' => 'GET',
            'callback' => array($this, 'handle_overview_endpoint'),
            'permission_callback' => array($this, 'check_overview_permission'),
        ));
        
        // Register action log endpoint
        register_rest_route('peligent/v1', '/log-action', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_log_action'),
            'permission_callback' => array($this, 'check_log_action_permission'),
        ));
        
        // Register image to base64 endpoint
        register_rest_route('peligent/v1', '/image-to-base64', array(
            'methods' => 'GET',
            'callback' => array($this, 'handle_image_to_base64'),
            'permission_callback' => array($this, 'check_overview_permission'),
        ));
        

        
        // Register product attributes endpoint
        register_rest_route('peligent/v1', '/product-attributes', array(
            'methods' => 'GET',
            'callback' => array($this, 'handle_product_attributes'),
            'permission_callback' => array($this, 'check_overview_permission'),
            'args' => array(
                'product_id' => array(
                    'required' => true,
                    'type' => 'integer',
                    'validate_callback' => function($param) {
                        return is_numeric($param) && $param > 0;
                    }
                ),
            ),
        ));
    }

    /**
     * Check permission for overview endpoint
     */
    public function check_overview_permission()
    {
        // Accept manage_woocommerce — the Peligent app user has this cap but not manage_options
        return current_user_can('manage_woocommerce');
    }

    /**
     * Check permission for log action endpoint
     */
    public function check_log_action_permission()
    {
        // Verify site token from header
        $site_token = isset($_SERVER['HTTP_X_PELIGENT_SITE_TOKEN']) 
            ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_PELIGENT_SITE_TOKEN'])) 
            : '';
        
        $stored_token = get_option(self::OPTION_SITE_TOKEN, '');
        
        if (empty($site_token) || empty($stored_token) || $site_token !== $stored_token) {
            return false;
        }
        
        return true;
    }

    /**
     * Handle overview endpoint request
     */
    public function handle_overview_endpoint()
    {
        global $wpdb;

        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        require_once ABSPATH . 'wp-admin/includes/update.php';
        wp_update_plugins();

        // Core information
        $core_version = get_bloginfo('version');
        wp_version_check();
        $core_updates = get_core_updates();
        $core_update_available = is_array($core_updates) && !empty($core_updates) && isset($core_updates[0]->response) && $core_updates[0]->response !== 'latest';

        // PHP information
        $php_info = array(
            'version' => PHP_VERSION,
            'memoryLimit' => ini_get('memory_limit'),
            'maxExecutionTime' => ini_get('max_execution_time'),
            'uploadMaxFilesize' => ini_get('upload_max_filesize'),
            'postMaxSize' => ini_get('post_max_size'),
        );

        // System health
        $constants = array(
            'WP_DEBUG' => defined('WP_DEBUG') ? (WP_DEBUG ? 'true' : 'false') : 'not set',
            'WP_ENVIRONMENT_TYPE' => defined('WP_ENVIRONMENT_TYPE') ? WP_ENVIRONMENT_TYPE : 'not set',
            'DISABLE_WP_CRON' => defined('DISABLE_WP_CRON') ? (DISABLE_WP_CRON ? 'true' : 'false') : 'false',
            'ALTERNATE_WP_CRON' => defined('ALTERNATE_WP_CRON') ? (ALTERNATE_WP_CRON ? 'true' : 'false') : 'false',
            'WP_CACHE' => defined('WP_CACHE') ? (WP_CACHE ? 'true' : 'false') : 'false',
        );

        $server_info = array(
            'software' => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : '',
            'mysqlVersion' => $wpdb->db_version(),
        );

        $health = array_merge(
            array(
                'homeUrl' => home_url('/'),
                'siteUrl' => site_url('/'),
                'timezone' => wp_timezone_string(),
                'locale' => get_locale(),
            ),
            $server_info,
            $constants,
            $php_info
        );

        // Plugins information
        $all_plugins = get_plugins();
        $active_plugins = get_option('active_plugins', array());
        $updates = get_site_transient('update_plugins');
        $needs_update = (isset($updates->response) && is_array($updates->response)) ? array_keys($updates->response) : array();

        $plugins_list = array();
        $i = 0;
        foreach ($all_plugins as $file => $data) {
            $i++;
            if ($i > 20) break; // Limit to top 20

            $is_active = in_array($file, $active_plugins, true);
            $need = in_array($file, $needs_update, true);

            $plugins_list[] = array(
                'name' => isset($data['Name']) ? $data['Name'] : $file,
                'version' => isset($data['Version']) ? $data['Version'] : '',
                'active' => $is_active,
                'needsUpdate' => $need,
                'author' => isset($data['Author']) ? $data['Author'] : '',
            );
        }

        // Content counts
        $post_counts = array();
        foreach (array('post', 'page', 'product') as $type) {
            $c = wp_count_posts($type);
            $post_counts[$type] = $c ? (array) $c : array();
        }

        // Draft pages
        $page_counts = wp_count_posts('page');
        $draft_total = (int) (isset($page_counts->draft) ? $page_counts->draft : 0);

        $draft_q = new WP_Query(array(
            'post_type' => 'page',
            'post_status' => 'draft',
            'posts_per_page' => 10,
            'fields' => 'ids'
        ));

        $draft_items = array_map(function ($id) {
            return array(
                'id' => $id,
                'title' => get_the_title($id) ? get_the_title($id) : '(no title)',
                'modified' => get_post_field('post_modified', $id),
                'editUrl' => get_edit_post_link($id, ''),
            );
        }, $draft_q->posts);

        // Try to get category and product URLs for PageSpeed
        $category_url = '';
        $product_url = '';

        if (taxonomy_exists('product_cat')) {
            $cats = get_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false, 'number' => 1));
            if (!is_wp_error($cats) && !empty($cats)) {
                $category_url = get_term_link($cats[0]);
            }
        }

        if (post_type_exists('product')) {
            $p = get_posts(array('post_type' => 'product', 'numberposts' => 1, 'post_status' => 'publish'));
            if ($p) {
                $product_url = get_permalink($p[0]);
            }
        }

        return array(
            'core' => array(
                'version' => $core_version,
                'updateAvailable' => $core_update_available,
            ),
            'php' => $php_info,
            'plugins' => array(
                'total' => count($all_plugins),
                'active' => count($active_plugins),
                'needsUpdate' => count($needs_update),
                'list' => $plugins_list,
            ),
            'health' => $health,
            'contentCounts' => $post_counts,
            'drafts' => array(
                'total' => $draft_total,
                'items' => $draft_items,
            ),
            'siteInfo' => array(
                'homeUrl' => home_url('/'),
                'categoryUrl' => $category_url,
                'productUrl' => $product_url,
            ),
        );
    }

    /**
     * Handle image to base64 conversion endpoint
     */
    public function handle_image_to_base64($request)
    {
        $attachment_id = $request->get_param('id');
        if (empty($attachment_id)) {
            return new WP_Error('missing_id', 'Attachment ID is required', array('status' => 400));
        }
        
        $attachment = get_post($attachment_id);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return new WP_Error('not_found', 'Attachment not found', array('status' => 404));
        }
        
        // Get full size image URL
        $image_url = wp_get_attachment_image_url($attachment_id, 'full');
        if (!$image_url) {
            $image_url = wp_get_attachment_url($attachment_id);
        }
        
        if (!$image_url) {
            return new WP_Error('no_image', 'Image URL not found', array('status' => 404));
        }
        
        // Get file path
        $file_path = get_attached_file($attachment_id);
        if (!$file_path || !file_exists($file_path)) {
            // Fallback: try to download from URL
            $response = wp_remote_get($image_url);
            if (is_wp_error($response)) {
                return new WP_Error('download_failed', 'Failed to download image', array('status' => 500));
            }
            $image_data = wp_remote_retrieve_body($response);
        } else {
            $image_data = file_get_contents($file_path);
        }
        
        if (!$image_data) {
            return new WP_Error('read_failed', 'Failed to read image data', array('status' => 500));
        }
        
        // Convert to base64
        $base64 = base64_encode($image_data);
        $mime_type = get_post_mime_type($attachment_id);
        if (!$mime_type) {
            $mime_type = 'image/jpeg';
        }
        
        return array(
            'success' => true,
            'base64' => $base64,
            'dataUrl' => 'data:' . $mime_type . ';base64,' . $base64,
            'mimeType' => $mime_type,
            'filename' => basename($file_path ?: $image_url),
        );
    }
    
    /**
     * Handle log action endpoint request
     */
    public function handle_log_action($request)
    {
        $params = $request->get_json_params();
        
        $action_type = isset($params['action_type']) ? sanitize_text_field($params['action_type']) : '';
        $route = isset($params['route']) ? sanitize_text_field($params['route']) : '';
        $resource_type = isset($params['resource_type']) ? sanitize_text_field($params['resource_type']) : '';
        $resource_id = isset($params['resource_id']) ? sanitize_text_field($params['resource_id']) : '';
        $changes_summary = isset($params['changes_summary']) ? sanitize_textarea_field($params['changes_summary']) : '';
        $timestamp = isset($params['timestamp']) ? sanitize_text_field($params['timestamp']) : current_time('mysql');
        
        // Log to WordPress debug log
        $log_message = sprintf(
            '[Peligent Action] %s %s - Resource: %s #%s - Changes: %s - Time: %s',
            strtoupper($action_type),
            $route,
            $resource_type ?: 'N/A',
            $resource_id ?: 'N/A',
            $changes_summary ?: 'N/A',
            $timestamp
        );
        
        $this->log_debug($log_message);
        
        // Also store in WordPress options as a simple log (keep last 100 entries)
        $log_key = 'peligent_action_log';
        $existing_logs = get_option($log_key, array());
        
        if (!is_array($existing_logs)) {
            $existing_logs = array();
        }
        
        // Add new entry
        $existing_logs[] = array(
            'action_type' => $action_type,
            'route' => $route,
            'resource_type' => $resource_type,
            'resource_id' => $resource_id,
            'changes_summary' => $changes_summary,
            'timestamp' => $timestamp,
            'created_at' => current_time('mysql')
        );
        
        // Keep only last 100 entries
        if (count($existing_logs) > 100) {
            $existing_logs = array_slice($existing_logs, -100);
        }
        
        update_option($log_key, $existing_logs);
        
        return new WP_REST_Response(array(
            'success' => true,
            'message' => 'Action logged successfully'
        ), 200);
    }

    /**
     * Handle product attributes endpoint
     */
    public function handle_product_attributes($request)
    {
        $product_id = $request->get_param('product_id');
        
        if (empty($product_id)) {
            return new WP_Error('missing_product_id', 'Product ID is required', array('status' => 400));
        }
        
        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            return new WP_Error('woocommerce_not_active', 'WooCommerce is not active', array('status' => 400));
        }
        
        // Get product
        $product = wc_get_product($product_id);
        if (!$product) {
            return new WP_Error('product_not_found', 'Product not found', array('status' => 404));
        }
        
        // Build attributes array
        $attributes_data = array();
        
        // Get product title
        $attributes_data['title'] = $product->get_name();
        
        // Get product SKU
        $sku = $product->get_sku();
        if ($sku) {
            $attributes_data['sku'] = $sku;
        }
        
        // Get product attributes
        $attributes = $product->get_attributes();
        if (!empty($attributes)) {
            $attributes_list = array();
            foreach ($attributes as $attribute_name => $attribute) {
                if ($attribute->get_variation()) {
                    continue; // Skip variation attributes
                }
                
                $attribute_label = wc_attribute_label($attribute_name, $product);
                $attribute_values = $attribute->get_options();
                
                if (!empty($attribute_values)) {
                    $values_string = is_array($attribute_values) 
                        ? implode(', ', array_map('trim', $attribute_values))
                        : trim($attribute_values);
                    $attributes_list[] = $attribute_label . ': ' . $values_string;
                }
            }
            if (!empty($attributes_list)) {
                $attributes_data['attributes'] = $attributes_list;
            }
        }
        
        // Get product meta (custom fields that might be useful)
        $meta_data = array();
        $meta_keys_to_include = array('_brand', '_model', '_mpn', '_gtin', '_weight', '_length', '_width', '_height');
        foreach ($meta_keys_to_include as $meta_key) {
            $meta_value = $product->get_meta($meta_key);
            if ($meta_value) {
                $meta_label = str_replace('_', ' ', ucfirst(ltrim($meta_key, '_')));
                $meta_data[$meta_label] = $meta_value;
            }
        }
        if (!empty($meta_data)) {
            $attributes_data['meta'] = $meta_data;
        }
        
        // Get product categories
        $categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'names'));
        if (!empty($categories) && !is_wp_error($categories)) {
            $attributes_data['categories'] = $categories;
        }
        
        // Get product tags
        $tags = wp_get_post_terms($product_id, 'product_tag', array('fields' => 'names'));
        if (!empty($tags) && !is_wp_error($tags)) {
            $attributes_data['tags'] = $tags;
        }
        
        return new WP_REST_Response($attributes_data, 200);
    }

    /**
     * Add Peligent content generation buttons to product description fields
     */
    public function add_peligent_content_buttons()
    {
        if (!current_user_can('edit_products')) {
            return;
        }
        
        if (! $this->is_user_allowed()) {
            return;
        }
        
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }
        
        // Register and enqueue script for product content buttons
        wp_register_script(
            'peligent-product-buttons',
            false,
            array('jquery', 'peligent-ai-embed'),
            '1.7.09',
            true
        );
        wp_enqueue_script('peligent-product-buttons');
        $icon_url_btn = esc_url(plugins_url('assets/peligent-icon-transparent.png', __FILE__));
        $product_buttons_script = "jQuery(document).ready(function($) {
            // Add button for short description field (textarea)
            var \$shortDescField = $('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]');
            if (\$shortDescField.length > 0) {
                var \$shortDescWrapper = \$shortDescField.closest('.form-field, .form-field-row');
                if (\$shortDescWrapper.length > 0) {
                    // Find the label or create a wrapper
                    var \$label = \$shortDescWrapper.find('label');
                    if (\$label.length > 0) {
                        // Add button after label, before field
                        var \$btnWrapper = $('<div>').css({
                            'margin-bottom': '10px',
                            'display': 'inline-block'
                        });
                        var \$btn = $('<button>')
                            .attr('type', 'button')
                            .addClass('button peligent-generate-content-btn')
                            .attr('data-field', 'short_description')
                            .css({
                                'background': 'transparent',
                                'border': '1px solid #2663EB',
                                'border-color': '#2663EB',
                                'color': '#2663EB',
                                'margin-left': '10px'
                            })
                            .html('<span style=\"display: inline-flex; align-items: center; gap: 6px;\"><img src=\"" . esc_js($icon_url_btn) . "\" alt=\"Peligent\" width=\"16\" height=\"16\" style=\"display: block;\" />Generate Short Description with Peligent</span>');
                        \$btnWrapper.append(\$btn);
                        \$label.after(\$btnWrapper);
                    }
                }
            }
        });";
        wp_add_inline_script('peligent-product-buttons', $product_buttons_script);
    }
    
    /**
     * Add Peligent buttons next to Add Media button in editor
     */
    public function add_peligent_media_buttons($editor_id = 'content')
    {
        global $post_type;

        if ($post_type === 'product') {
            $this->render_product_media_button($editor_id);
        } elseif ($post_type === 'post') {
            $this->render_blog_media_button($editor_id);
        }
    }

    /**
     * Render Peligent button for WooCommerce product editor
     */
    private function render_product_media_button($editor_id = 'content')
    {
        if (!current_user_can('edit_products')) {
            return;
        }

        if (! $this->is_user_allowed()) {
            return;
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }

        // Determine field type based on editor ID
        // 'content' is the main description editor, 'excerpt' is short description
        $field_type = ($editor_id === 'excerpt') ? 'short_description' : 'description';
        $button_text = ($field_type === 'short_description') ? 'Generate Short Description' : 'Generate Description';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for display, not processing form data
        $product_id = isset($_GET['post']) ? intval(wp_unslash($_GET['post'])) : 0;

        // Add inline onclick handler to ensure it works even if script loads after button
        $icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
        echo '<button type="button" class="button peligent-generate-content-btn" data-field="' . esc_attr($field_type) . '" onclick="console.log(\'[Peligent] Button clicked, fieldType:\', \'' . esc_js($field_type) . '\', \'productId:\', ' . esc_js($product_id) . '); console.log(\'[Peligent] peligentGenerateContent exists:\', typeof peligentGenerateContent); if(typeof peligentGenerateContent===\'function\'){console.log(\'[Peligent] Calling peligentGenerateContent...\'); peligentGenerateContent(\'' . esc_js($field_type) . '\',' . esc_js($product_id) . ');}else{console.error(\'[Peligent] peligentGenerateContent function not found, available functions:\', Object.keys(window).filter(k => k.includes(\'peligent\'))); alert(\'Peligent is loading, please try again in a moment. Function status: \' + typeof peligentGenerateContent);} return false;" style="background: transparent; border: 1px solid #2663EB; border-color: #2663EB; color: #2663EB; margin-left: 5px;">';
        echo '<span style="display: inline-flex; align-items: center; gap: 6px;">';
        echo '<img src="' . esc_url($icon_url) . '" alt="Peligent" width="16" height="16" style="display: block;" />';
        echo esc_html($button_text . ' with Peligent');
        echo '</span>';
        echo '</button>';
    }

    /**
     * Render Peligent button for blog post editor
     */
    private function render_blog_media_button($editor_id = 'content')
    {
        // Only show for the main content editor, not excerpt
        if ($editor_id !== 'content') {
            return;
        }

        if (!current_user_can('edit_posts')) {
            return;
        }

        if (! $this->is_user_allowed()) {
            return;
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for display, not processing form data
        $post_id = isset($_GET['post']) ? intval(wp_unslash($_GET['post'])) : 0;

        $icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
        echo '<button type="button" class="button peligent-generate-blog-btn" data-field="blog_content" onclick="if(typeof peligentGenerateBlogContent===\'function\'){peligentGenerateBlogContent(' . esc_js($post_id) . ');}else{alert(\'Peligent is loading, please try again in a moment.\');} return false;" style="background: transparent; border: 1px solid #2663EB; border-color: #2663EB; color: #2663EB; margin-left: 5px;">';
        echo '<span style="display: inline-flex; align-items: center; gap: 6px;">';
        echo '<img src="' . esc_url($icon_url) . '" alt="Peligent" width="16" height="16" style="display: block;" />';
        echo 'Generate Blog Content with Peligent';
        echo '</span>';
        echo '</button>';
    }
    
    /**
     * JavaScript handler for content generation buttons
     * Modal is now handled in React sidebar
     */
    public function render_content_generation_modal()
    {
        global $post_type;

        // Check capabilities based on post type
        if ($post_type === 'product' && !current_user_can('edit_products')) {
            return;
        }
        if ($post_type === 'post' && !current_user_can('edit_posts')) {
            return;
        }
        if (!in_array($post_type, array('product', 'post'), true)) {
            return;
        }

        if (! $this->is_user_allowed()) {
            return;
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }
        
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for display, not processing form data
        $product_id = isset($_GET['post']) ? intval(wp_unslash($_GET['post'])) : 0;
        
        // JavaScript to handle button clicks and send message to Peligent iframe
        // Note: peligentGenerateContent function is already defined in admin_assets
        // This script only handles the message listener and button initialization
        // Register and enqueue script for content generation modal
        wp_register_script(
            'peligent-content-generation',
            false,
            array('jquery', 'peligent-ai-embed'),
            '1.7.09',
            true
        );
        wp_enqueue_script('peligent-content-generation');
        $content_gen_script = "console.log('[Peligent] Content generation script loading (footer)...');
        (function() {
            var currentField = null;
            var productId = " . wp_json_encode($product_id) . ";
            console.log('[Peligent] Initializing with productId:', productId);
            
            // Check if function already exists (from admin_assets)
            if (typeof window.peligentGenerateContent === 'function') {
                console.log('[Peligent] peligentGenerateContent already defined, using existing function');
            } else {
                console.warn('[Peligent] peligentGenerateContent not found, defining fallback...');
                // Fallback definition (should not be needed if admin_assets loaded correctly)
                window.peligentGenerateContent = function(fieldType, prodId) {
                console.log('[Peligent] ===== peligentGenerateContent CALLED =====');
                console.log('[Peligent] fieldType:', fieldType);
                console.log('[Peligent] prodId:', prodId);
                console.log('[Peligent] currentField before:', currentField);
                console.log('[Peligent] productId before:', productId);
                currentField = fieldType;
                productId = prodId || productId;
                
                // Show sidebar if hidden
                var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                if (sidebar) {
                    sidebar.classList.remove('peligent-ai-hidden');
                    document.body.classList.remove('peligent-ai-sidebar-hidden');
                    try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                }
                
                // Get current field value for default prompt
                console.log('[Peligent] Getting current field value for:', currentField);
                var currentValue = '';
                if (currentField === 'short_description') {
                    if (typeof jQuery !== 'undefined') {
                        currentValue = jQuery('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]').val() || '';
                        console.log('[Peligent] Short description value (jQuery):', currentValue.substring(0, 50));
                    } else {
                        var excerptEl = document.getElementById('excerpt') || document.querySelector('textarea[name=\"excerpt\"]');
                        currentValue = excerptEl ? excerptEl.value : '';
                        console.log('[Peligent] Short description value (native):', currentValue.substring(0, 50));
                    }
                } else {
                    // Get description from editor
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        currentValue = tinyMCE.get('content').getContent({ format: 'text' }) || '';
                        console.log('[Peligent] Description value (tinyMCE):', currentValue.substring(0, 50));
                    } else {
                        if (typeof jQuery !== 'undefined') {
                            currentValue = jQuery('#content, textarea[name=\"content\"]').val() || '';
                            console.log('[Peligent] Description value (jQuery):', currentValue.substring(0, 50));
                        } else {
                            var contentEl = document.getElementById('content') || document.querySelector('textarea[name=\"content\"]');
                            currentValue = contentEl ? contentEl.value : '';
                            console.log('[Peligent] Description value (native):', currentValue.substring(0, 50));
                        }
                    }
                }
                
                // Send raw content only — prompt construction is handled by the frontend/server
                var defaultPrompt = currentValue || '';
                console.log('[Peligent] Default prompt length:', defaultPrompt.length);
                
                // Determine output type based on field
                var outputType = currentField === 'short_description' ? 'short_description' : 'description';
                console.log('[Peligent] Output type:', outputType);
                
                // Send message to Peligent iframe
                console.log('[Peligent] Looking for iframe...');
                var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
                console.log('[Peligent] Iframe found:', !!iframe);
                console.log('[Peligent] Iframe contentWindow:', iframe ? !!iframe.contentWindow : false);
                
                if (iframe && iframe.contentWindow) {
                    var message = {
                        type: 'WPAI_GENERATE_CONTENT',
                        prompt: defaultPrompt,
                        outputType: outputType,
                        outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                        tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                        productId: productId,
                        fieldType: currentField
                    };
                    console.log('[Peligent] Sending message to iframe:', message);
                    iframe.contentWindow.postMessage(message, 'https://app.peligent.com');
                    console.log('[Peligent] ✓ Message sent successfully to iframe');
                } else {
                    console.warn('[Peligent] ✗ Iframe not found, retrying in 500ms...');
                    setTimeout(function() {
                        console.log('[Peligent] Retry: Looking for sidebar and iframe...');
                        var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                        console.log('[Peligent] Retry: Sidebar found:', !!sidebar);
                        var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
                        console.log('[Peligent] Retry: Iframe found:', !!iframe);
                        if (iframe && iframe.contentWindow) {
                        var message = {
                            type: 'WPAI_GENERATE_CONTENT',
                                prompt: defaultPrompt,
                                outputType: outputType,
                                outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                                tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                                productId: productId,
                                fieldType: currentField
                            };
                            console.log('[Peligent] Retry: Sending message:', message);
                            iframe.contentWindow.postMessage(message, 'https://app.peligent.com');
                            console.log('[Peligent] ✓ Message sent successfully (retry)');
                        } else {
                            console.error('[Peligent] ✗ Iframe still not found after retry');
                            console.error('[Peligent] Sidebar:', sidebar);
                            console.error('[Peligent] Iframe:', iframe);
                            alert('Peligent sidebar is not available. Please make sure it is open.');
                        }
                    }, 500);
                }
                console.log('[Peligent] ===== peligentGenerateContent END =====');
            };
            
            console.log('[Peligent] peligentGenerateContent function defined:', typeof window.peligentGenerateContent);
            
            // Wait for jQuery and DOM to be ready
            function initContentGenerationButtons() {
                console.log('[Peligent] Initializing content generation buttons...');
                
                // Check if buttons exist
                var buttons = jQuery('.peligent-generate-content-btn');
                console.log('[Peligent] Found buttons:', buttons.length);
                
                // Handle button clicks - send message to Peligent iframe
                jQuery(document).off('click', '.peligent-generate-content-btn').on('click', '.peligent-generate-content-btn', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    console.log('[Peligent] Button clicked:', jQuery(this).data('field'));
                currentField = jQuery(this).data('field');
                
                // Show sidebar if hidden
                var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                if (sidebar) {
                    sidebar.classList.remove('peligent-ai-hidden');
                    document.body.classList.remove('peligent-ai-sidebar-hidden');
                    try { localStorage.setItem('peligent_ai_sidebar_visible', '1'); } catch {}
                }
                
                // Get current field value for default prompt
                var currentValue = '';
                if (currentField === 'short_description') {
                    currentValue = jQuery('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]').val() || '';
                } else {
                    // Get description from editor
                    if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                        currentValue = tinyMCE.get('content').getContent({ format: 'text' }) || '';
                    } else {
                        currentValue = jQuery('#content, textarea[name=\"content\"]').val() || '';
                    }
                }
                
                // Send raw content only — prompt construction is handled by the frontend/server
                var defaultPrompt = currentValue || '';

                // Determine output type based on field
                var outputType = currentField === 'short_description' ? 'short_description' : 'description';
                
                // Send message to Peligent iframe
                var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
                if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({
                        type: 'WPAI_GENERATE_CONTENT',
                        prompt: defaultPrompt,
                        outputType: outputType,
                        outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                        tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                        productId: productId,
                        fieldType: currentField
                    }, 'https://app.peligent.com');
                    console.log('[Peligent] Sent content generation request to iframe');
                } else {
                    console.warn('[Peligent] Iframe not found, retrying...');
                    setTimeout(function() {
                        var sidebar = document.querySelector('.peligent-ai-fixed-sidebar');
                        var iframe = sidebar ? sidebar.querySelector('iframe.peligent-ai-iframe') : null;
                        if (iframe && iframe.contentWindow) {
                            iframe.contentWindow.postMessage({
                                type: 'WPAI_GENERATE_CONTENT',
                                prompt: defaultPrompt,
                                outputType: outputType,
                                outputLanguage: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.language) ? window.PELIGENT_DEFAULTS.language : 'en',
                                tone: (window.PELIGENT_DEFAULTS && window.PELIGENT_DEFAULTS.tone) ? window.PELIGENT_DEFAULTS.tone : 'Expert',
                                productId: productId,
                                fieldType: currentField
                            }, 'https://app.peligent.com');
                        }
                    }, 500);
                }
            });
            }
            
            // Initialize when jQuery is ready
            console.log('[Peligent] Checking jQuery availability...');
            if (typeof jQuery !== 'undefined') {
                console.log('[Peligent] jQuery is available, waiting for DOM ready...');
                jQuery(document).ready(function() {
                    console.log('[Peligent] DOM ready, initializing buttons...');
                    initContentGenerationButtons();
                    // Also try after a delay in case buttons are added dynamically
                    setTimeout(function() {
                        console.log('[Peligent] Delayed init (1s)...');
                        initContentGenerationButtons();
                    }, 1000);
                    setTimeout(function() {
                        console.log('[Peligent] Delayed init (2s)...');
                        initContentGenerationButtons();
                    }, 2000);
                });
            } else {
                console.warn('[Peligent] jQuery not available, waiting for it...');
                // Wait for jQuery to load
                var checkJQuery = setInterval(function() {
                    if (typeof jQuery !== 'undefined') {
                        console.log('[Peligent] jQuery loaded, initializing...');
                        clearInterval(checkJQuery);
                        jQuery(document).ready(function() {
                            initContentGenerationButtons();
                            // Also try after a delay in case buttons are added dynamically
                            setTimeout(initContentGenerationButtons, 1000);
                            setTimeout(initContentGenerationButtons, 2000);
                        });
                    }
                }, 100);
                // Stop checking after 5 seconds
                setTimeout(function() {
                    clearInterval(checkJQuery);
                    console.warn('[Peligent] jQuery check timeout, initializing without jQuery...');
                    if (document.readyState === 'loading') {
                        document.addEventListener('DOMContentLoaded', initContentGenerationButtons);
                    } else {
                        initContentGenerationButtons();
                    }
                }, 5000);
            }
            
            // Also check immediately
            console.log('[Peligent] Document readyState:', document.readyState);
            if (document.readyState === 'complete' || document.readyState === 'interactive') {
                console.log('[Peligent] Document already ready, initializing immediately...');
                setTimeout(initContentGenerationButtons, 100);
            }
            
            // Listen for generated content from Peligent
            window.addEventListener('message', function(event) {
                console.log('[Peligent] Message received in WP admin:', {
                    origin: event.origin,
                    data: event.data,
                    currentField: currentField
                });
                var allowedOrigins = ['https://app.peligent.com'];
                if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                    allowedOrigins.push('http://localhost:3000', 'http://127.0.0.1:3000');
                }
                
                var isAllowedOrigin = allowedOrigins.indexOf(event.origin) !== -1
                    || event.origin === window.location.origin;
                
                if (!isAllowedOrigin) {
                    console.warn('[Peligent] Ignoring message from disallowed origin:', event.origin);
                    return;
                }
                
                var data = event.data;
                var type = data && data.type;
                var isGenerateContentResult = type === 'WPAI_GENERATE_CONTENT_RESULT' || type === 'PELIGENT_AI_GENERATE_CONTENT_RESULT';
                if (isGenerateContentResult) {
                    var generatedContent = data.content || '';
                    var fieldTypeFromData = data.fieldType || data.outputType || '';
                    console.log('[Peligent] Generate content result received:', type, {
                        hasContent: !!generatedContent,
                        contentLength: generatedContent ? generatedContent.length : 0,
                        currentField: currentField,
                        fieldTypeFromData: fieldTypeFromData
                    });
                    
                    // Prefer fieldType from message; fall back to currentField
                    var targetField = fieldTypeFromData || currentField || 'description';
                    
                    if (generatedContent && targetField) {
                        // 1) Remove simple Markdown first (**bold**, [link](url))
                        try {
                            generatedContent = generatedContent
                                .replace(/\\*\\*(.*?)\\*\\*/g, '$1')
                                .replace(/\\[(.*?)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g, '$1');
                        } catch (e) {
                            console.warn('[Peligent] Failed to strip markdown:', e);
                        }
                        
                        // 2) Clean up title prefixes like 'Product Description:' or 'Short Description:'
                        try {
                            if (targetField === 'short_description') {
                                generatedContent = generatedContent.replace(/^[\\s]*Short Description[^:]*:\\s*/i, '');
                            } else if (targetField === 'blog_content') {
                                generatedContent = generatedContent
                                    .replace(/^[\\s]*Blog Post[^:]*:\\s*/i, '')
                                    .replace(/^[\\s]*Blog Content[^:]*:\\s*/i, '')
                                    .replace(/^[\\s]*Article[^:]*:\\s*/i, '');
                            } else {
                                generatedContent = generatedContent
                                    .replace(/^[\\s]*Product Description[^:]*:\\s*/i, '')
                                    .replace(/^[\\s]*Description[^:]*:\\s*/i, '');
                            }
                        } catch (e) {
                            console.warn('[Peligent] Failed to strip title prefix:', e);
                        }
                        
                        // 3) For full description, convert plain text into HTML paragraphs/lines
                        var htmlContent = generatedContent;
                        if (targetField !== 'short_description') {
                            try {
                                var trimmed = generatedContent.trim();
                                if (trimmed) {
                                    if (trimmed.indexOf('\\n') !== -1) {
                                        var paragraphs = trimmed.split(/\\n{2,}/);
                                        htmlContent = paragraphs.map(function (p) {
                                            return '<p>' + p.replace(/\\n/g, '<br />') + '</p>';
                                        }).join('');
                                    } else {
                                        var sentences = trimmed.split(/(?<=[\\.!?])\\s+/);
                                        var blocks = [];
                                        var current = '';
                                        sentences.forEach(function (s, idx) {
                                            if (!s) return;
                                            if (!current) {
                                                current = s;
                                            } else if (current.length + s.length < 220) {
                                                current += ' ' + s;
                                            } else {
                                                blocks.push(current);
                                                current = s;
                                            }
                                        });
                                        if (current) {
                                            blocks.push(current);
                                        }
                                        htmlContent = blocks.map(function (p) {
                                            return '<p>' + p + '</p>';
                                        }).join('');
                                    }
                                }
                            } catch (e) {
                                console.warn('[Peligent] Failed to convert description to HTML:', e);
                                htmlContent = generatedContent;
                            }
                        }
                        
                        console.log('[Peligent] Applying generated content to field:', targetField, {
                            textLength: generatedContent.length,
                            htmlLength: htmlContent.length
                        });
                        
                        try {
                            if (targetField === 'short_description') {
                                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('excerpt')) {
                                    console.log('[Peligent] Applying generated content via tinyMCE(excerpt)');
                                    tinyMCE.get('excerpt').setContent(generatedContent.replace(/\\n/g, '<br />'));
                                } else if (typeof jQuery !== 'undefined') {
                                    console.log('[Peligent] Applying generated content via textarea excerpt (jQuery)');
                                    jQuery('#excerpt, #product_excerpt, textarea[name=\"excerpt\"]').val(generatedContent);
                                } else {
                                    console.log('[Peligent] Applying generated content via textarea excerpt (native)');
                                    var excerptEl = document.getElementById('excerpt') || document.querySelector('textarea[name=\"excerpt\"]');
                                    if (excerptEl) {
                                        excerptEl.value = generatedContent;
                                    }
                                }
                            } else {
                                if (typeof tinyMCE !== 'undefined' && tinyMCE.get('content')) {
                                    console.log('[Peligent] Applying generated content via tinyMCE(content)');
                                    tinyMCE.get('content').setContent(htmlContent);
                                } else if (typeof jQuery !== 'undefined') {
                                    console.log('[Peligent] Applying generated content via textarea content (jQuery)');
                                    jQuery('#content, textarea[name=\"content\"]').val(generatedContent);
                                } else {
                                    console.log('[Peligent] Applying generated content via textarea content (native)');
                                    var contentEl = document.getElementById('content') || document.querySelector('textarea[name=\"content\"]');
                                    if (contentEl) {
                                        contentEl.value = generatedContent;
                                    }
                                }
                            }
                            
                            // Show success notice
                            var notice = document.createElement('div');
                            notice.className = 'notice notice-success is-dismissible';
                            notice.innerHTML = '<p><strong>Success!</strong> Content generated and applied successfully.</p>';
                            notice.style.margin = '10px 0';
                            notice.style.padding = '10px';
                            
                            var noticeContainer = document.querySelector('.wrap, #wpbody-content, .wp-header-end');
                            if (noticeContainer && noticeContainer.parentNode) {
                                noticeContainer.parentNode.insertBefore(notice, noticeContainer);
                            } else {
                                var body = document.querySelector('body');
                                if (body) {
                                    body.insertBefore(notice, body.firstChild);
                                }
                            }
                            
                            // Auto-dismiss after 5 seconds
                            setTimeout(function() {
                                if (notice.parentNode) {
                                    notice.parentNode.removeChild(notice);
                                }
                            }, 5000);
                        } catch (e) {
                            console.error('[Peligent] Failed to apply generated content:', e);
                        }
                    } else if (data.error) {
                        alert('Failed to generate content: ' + data.error);
                    }
                }
            });
        })();";
        wp_add_inline_script('peligent-content-generation', $content_gen_script);
    }
    
    /**
     * Add chat icon to WordPress admin bar
     */
    public function add_admin_bar_chat_icon($wp_admin_bar)
    {
        // Only show in admin, not on frontend
        if (! is_admin()) {
            return;
        }

        if (! current_user_can('manage_options')) {
            return;
        }

        // Only show if user has access
        if (! $this->is_user_allowed()) {
            return;
        }

        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return;
        }

        $icon_url = plugins_url('assets/peligent-icon-transparent.png', __FILE__);
        $wp_admin_bar->add_node(array(
            'id'    => 'peligent-chat',
            'title' => '<span class="ab-icon" style="margin-top: 3px;"><img src="' . esc_url($icon_url) . '" alt="Peligent" width="20" height="20" style="display: block;" /></span><span class="ab-label">Peligent Assistant</span>',
            'href'  => '#',
            'meta'  => array(
                'class' => 'peligent-ai-admin-bar-chat',
                'title' => 'Toggle AI Assistant',
                'onclick' => 'javascript:(function(e){e.preventDefault();var s=document.querySelector(\'.peligent-ai-fixed-sidebar\');if(s){var h=s.classList.contains(\'peligent-ai-hidden\');if(h){s.classList.remove(\'peligent-ai-hidden\');document.body.classList.remove(\'peligent-ai-sidebar-hidden\');try{localStorage.setItem(\'peligent_ai_sidebar_visible\',\'1\')}catch{}}else{s.classList.add(\'peligent-ai-hidden\');document.body.classList.add(\'peligent-ai-sidebar-hidden\');try{localStorage.setItem(\'peligent_ai_sidebar_visible\',\'0\')}catch{}}}return false;})(event);',
            ),
        ));
    }

    /**
     * Send product webhook to Peligent when product is created or updated
     */
    public function send_product_webhook($product_id)
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return; // Not connected
        }

        $product = wc_get_product($product_id);
        if (!$product) {
            return;
        }

        // Get product data
        $product_data = $product->get_data();
        
        $this->send_webhook('product.updated', 'product', array(
            'id' => $product_id,
            'data' => $product_data
        ), $site_token);
    }

    /**
     * Perform connection to Peligent (extracted from handle_send_to_peligent for reuse)
     */
    private function perform_connection($connect_token = null)
    {
        if (is_null($connect_token)) {
            $connect_token = get_option(self::OPTION_CONNECT_KEY, '');
        }

        if (empty($connect_token)) {
            update_option(self::OPTION_LAST_CONNECT_ERROR, 'Connect secret is missing.');
            delete_option(self::OPTION_SITE_TOKEN);
            return false;
        }

        $key = get_option(self::OPTION_KEY);
        $app = get_option(self::OPTION_APP_USER);

        // Auto-generate consumer key/secret if missing
        if (empty($key['consumer_key']) || empty($key['consumer_secret']) || !empty($key['error'])) {
            $created = $this->create_key_programmatically(array(
                'app_name' => 'Auto-generated by Peligent',
                'user_id'  => get_current_user_id() ?: 1,
                'scope'    => 'read_write',
            ));

            if (is_wp_error($created)) {
                $err = $created->get_error_message();
                $this->log_debug('Failed to generate consumer key/secret: ' . $err);
                update_option(self::OPTION_LAST_CONNECT_ERROR, $err);
                delete_option(self::OPTION_SITE_TOKEN);
                return false;
            } else {
                update_option(self::OPTION_KEY, $created);
                $key = $created;
                $this->log_debug('Auto-generated consumer key/secret');
            }
        }

        // Auto-create app user if missing (but NOT the password — user provides it manually)
        if (empty($app['user_login']) || !empty($app['error'])) {
            $created_app = $this->create_app_user_and_password(true);
            if (is_wp_error($created_app)) {
                $err = $created_app->get_error_message();
                $this->log_debug('Failed to generate app user/password: ' . $err);
                update_option(self::OPTION_LAST_CONNECT_ERROR, $err);
                delete_option(self::OPTION_SITE_TOKEN);
                return false;
            } else {
                update_option(self::OPTION_APP_USER, $created_app);
                $app = $created_app;
                $this->log_debug('Auto-generated app user');
            }
        }

        // Auto-create application password if user exists but password is missing
        if (!empty($app['user_login']) && empty($app['app_password']) && empty($app['credentials_sent'])) {
            $app_user_id = !empty($app['user_id']) ? (int) $app['user_id'] : 0;
            if ($app_user_id && get_user_by('id', $app_user_id) && class_exists('WP_Application_Passwords')) {
                $app_pass_result = WP_Application_Passwords::create_new_application_password(
                    $app_user_id,
                    array('name' => 'Peligent AI Assistant')
                );
                if (!is_wp_error($app_pass_result) && !empty($app_pass_result[0])) {
                    $app['app_password'] = $app_pass_result[0];
                    $app['app_password_label'] = 'Peligent AI Assistant';
                    update_option(self::OPTION_APP_USER, $app);
                    $this->log_debug('Auto-created application password during connection');
                }
            }
        }

        $payload = array(
            'site_name'         => get_bloginfo('name'),
            'site_url'          => home_url('/'),
            'consumer_key'      => $key['consumer_key'],
            'consumer_secret'   => $key['consumer_secret'],
            'app_user_login'    => !empty($app['user_login']) ? $app['user_login'] : '',
            'app_user_password' => !empty($app['app_password']) ? $app['app_password'] : '',
            'partner_id'        => get_option(self::OPTION_PARTNER_ID, ''),
        );

        $this->log_debug('Sending payload to Peligent: ' . wp_json_encode($payload));
        $response = wp_remote_post(self::PELIGENT_ENDPOINT, array(
            'headers' => array(
                'Content-Type' => 'application/json',
                'X-Peligent-Connect-Token' => $connect_token,
            ),
            'body'      => wp_json_encode($payload),
            'timeout'   => 45,
            'sslverify' => true,
        ));

        if (is_wp_error($response)) {
            $err = 'Could not reach Peligent servers. Please check your internet connection and try again.';
            $this->log_debug('Peligent request failed (network): ' . $response->get_error_message());
            update_option(self::OPTION_LAST_CONNECT_ERROR, $err);
            // Do NOT delete site_token on network errors — the token may still be valid.
            // Only delete on confirmed auth failures (401/403).
            return false;
        } else {
            $code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            $this->log_debug('Peligent responded with HTTP ' . $code . ' body: ' . $body);
            if ($code >= 200 && $code < 300) {
                $decoded = json_decode($body, true);
                if (is_array($decoded) && ! empty($decoded['site_token'])) {
                    $tok = sanitize_text_field($decoded['site_token']);
                    update_option(self::OPTION_SITE_TOKEN, $tok);
                    delete_option(self::OPTION_LAST_CONNECT_ERROR);
                    $this->log_debug('Connected to Peligent successfully. Site token saved.');

                    $this->send_installation_notification();

                    // Scrub plaintext passwords from stored options
                    $stored_app = get_option(self::OPTION_APP_USER, array());
                    if (is_array($stored_app)) {
                        unset($stored_app['app_password']);
                        $stored_app['credentials_sent'] = true;
                        update_option(self::OPTION_APP_USER, $stored_app);
                    }
                    $stored_key = get_option(self::OPTION_KEY, array());
                    if (is_array($stored_key)) {
                        unset($stored_key['consumer_secret']);
                        $stored_key['credentials_sent'] = true;
                        update_option(self::OPTION_KEY, $stored_key);
                    }

                    return true;
                } else {
                    $err = 'Connected, but no site token was returned.';
                    $this->log_debug('Connected, but no site_token in response. Body: ' . substr($body, 0, 180));
                    update_option(self::OPTION_LAST_CONNECT_ERROR, $err);
                    delete_option(self::OPTION_SITE_TOKEN);
                    return false;
                }
            } else {
                // Parse backend error for user-friendly message
                $decoded_err = json_decode($body, true);
                $detail = isset($decoded_err['detail']) ? $decoded_err['detail'] : '';

                if ($code === 401 || $code === 403) {
                    $err = 'The Connect Secret is invalid or expired. Please copy a new one from your Peligent Dashboard.';
                } elseif ($code === 404) {
                    $err = 'Account not found. Please check your Peligent Dashboard account.';
                } elseif ($code === 400) {
                    $backend_error = isset($decoded_err['error']) ? $decoded_err['error'] : $detail;
                    $err = $backend_error ? $backend_error : 'Connection failed. Please try again.';
                } else {
                    $err = 'Connection failed (HTTP ' . $code . '). Please try again or contact support.';
                }

                $this->log_debug('Peligent responded with HTTP ' . $code . ': ' . $body);
                update_option(self::OPTION_LAST_CONNECT_ERROR, $err);
                // Only delete token on confirmed auth failures — server errors may be transient
                if ($code === 401 || $code === 403) {
                    delete_option(self::OPTION_SITE_TOKEN);
                }
                return false;
            }
        }
    }

    /**
     * Send product delete webhook to Peligent
     */
    public function send_product_delete_webhook($product_id)
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return; // Not connected
        }

        $this->send_webhook('product.deleted', 'product', array(
            'id' => $product_id
        ), $site_token);
    }

    /**
     * Send order webhook to Peligent when order is created or updated
     */
    public function send_order_webhook($order_id)
    {
        $site_token = get_option(self::OPTION_SITE_TOKEN, '');
        if (empty($site_token)) {
            return; // Not connected
        }

        $order = wc_get_order($order_id);
        if (!$order) {
            return;
        }

        // Get order data
        $order_data = $order->get_data();
        
        $this->send_webhook('order.updated', 'order', array(
            'id' => $order_id,
            'data' => $order_data
        ), $site_token);
    }

    /**
     * Send installation notification to Peligent server
     */
    private function send_installation_notification()
    {
        // Get plugin version
        if (!function_exists('get_plugin_data')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        $plugin_data = get_plugin_data(__FILE__);
        $plugin_version = isset($plugin_data['Version']) ? $plugin_data['Version'] : 'unknown';

        $current_user = wp_get_current_user();
        $admin_name = trim(($current_user->first_name ?? '') . ' ' . ($current_user->last_name ?? ''));
        if (!$admin_name) {
            $admin_name = $current_user->display_name ?? '';
        }

        $payload = array(
            'site_name' => get_bloginfo('name'),
            'site_url' => home_url('/'),
            'admin_name' => $admin_name,
            'admin_email' => get_bloginfo('admin_email'),
            'wp_version' => get_bloginfo('version'),
            'plugin_version' => $plugin_version,
            'php_version' => PHP_VERSION,
            'wc_version' => class_exists('WooCommerce') ? WC()->version : 'not_installed',
            'timestamp' => current_time('mysql'),
        );

        $this->log_debug('Sending installation notification: ' . wp_json_encode($payload));
        
        // Non-blocking — don't slow down the connection flow
        wp_remote_post(self::PELIGENT_INSTALL_NOTIFICATION_ENDPOINT, array(
            'headers' => array(
                'Content-Type' => 'application/json',
            ),
            'body' => wp_json_encode($payload),
            'timeout' => 5,
            'blocking' => false,
            'sslverify' => true,
        ));
    }

    /**
     * Send webhook to Peligent server
     */
    private function send_webhook($event, $resource, $data, $site_token)
    {
        try {
            $webhook_url = 'https://app.peligent.com/api/webhooks/woocommerce/' . $site_token;

            $payload = array(
                'event' => $event,
                'resource' => $resource,
                'data' => $data,
                'timestamp' => current_time('mysql')
            );

            // Non-blocking fire-and-forget — never slow down the user's site
            wp_remote_post($webhook_url, array(
                'headers' => array(
                    'Content-Type' => 'application/json',
                ),
                'body' => wp_json_encode($payload),
                'timeout' => 5,
                'blocking' => false,
                'sslverify' => true,
            ));
        } catch (\Exception $e) {
            $this->log_debug('Webhook exception: ' . $e->getMessage());
        } catch (\Throwable $e) {
            $this->log_debug('Webhook error: ' . $e->getMessage());
        }
    }
}

new Peligent_For_WooCommerce_Plugin();

// ---- Uninstall cleanup ----
// Register an uninstall hook to clean up plugin data when uninstalled via WP admin.
register_uninstall_hook(__FILE__, 'peligent_ai_assistant_uninstall');

function peligent_ai_assistant_uninstall()
{
    // Notify dashboard BEFORE deleting options (we still have the site_token)
    $site_token = get_option('peligent_site_token', '');
    if (!empty($site_token)) {
        $disconnect_url = str_replace('/connect', '/disconnect', 'https://app.peligent.com/api/integrations/woocommerce/connect');
        wp_remote_post($disconnect_url, array(
            'headers'   => array(
                'Content-Type'          => 'application/json',
                'X-Peligent-Site-Token' => $site_token,
            ),
            'body'      => wp_json_encode(array(
                'site_token' => $site_token,
                'reason'     => 'plugin_uninstalled',
                'site_url'   => home_url('/'),
                'timestamp'  => current_time('mysql'),
            )),
            'timeout'   => 5,
            'sslverify' => true,
        ));
    }

    // Remove all Peligent options
    $options = array(
        'peligent_wc_last_key',
        'peligent_wc_app_user',
        'peligent_wc_connect_token',
        'peligent_site_token',
        'peligent_allowed_users',
        'peligent_wc_onboarding_completed',
        'peligent_wc_last_connect_error',
        'peligent_wc_onboarding_profile',
        'peligent_wc_assistant_defaults',
        'peligent_wc_partner_id',
        'peligent_wc_activation_redirect',
        'peligent_wc_missing_notice',
    );

    // Remove the created app user BEFORE deleting options (only if clearly ours)
    $app = get_option('peligent_wc_app_user');
    if (is_array($app) && !empty($app['user_id'])) {
        $user = get_user_by('id', (int) $app['user_id']);
        if ($user && strpos($user->user_login, 'wc_api_app_') === 0) {
            require_once ABSPATH . 'wp-admin/includes/user.php';
            wp_delete_user((int) $app['user_id']);
        }
    }

    foreach ($options as $option) {
        delete_option($option);
    }
}
