<?php

/**
 * 后台管理类
 * 统一管理后台配置面板相关功能
 * 
 * @package XHTheme\AIToolbox
 */

namespace XHTheme\AIToolbox;

defined('ABSPATH') || exit;

class XHAdmin
{

    /**
     * 单例实例
     */
    private static $instance = null;

    /**
     * 获取单例实例
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 获取默认设置
     */
    public static function get_default_settings()
    {
        return [
            // 基础配置
            'appId' => '',
            'modelType' => 'auto',
            'imageRecognition' => true,
            'languageType' => 'auto',
            'aiUserLimit' => 500,         // AI用户生成上限（全局）
            'aiWorkbenchAutoOpen' => false,

            // 内容优化
            'paragraphEnabled' => true,
            'paragraphCapacity' => ['optimize', 'follow', 'expand', 'shorten'],

            // 摘要配置
            'summaryEnabled' => true,
            'summaryModel' => 'summary',
            'summaryMaxLength' => 150,
            'summaryStyle' => 'aurora',
            'summaryTitle' => __('Generate Summary', 'xhtheme-ai-toolbox'),
            'summarySubtitle' => __('Summary Generated', 'xhtheme-ai-toolbox'),
            'summaryDesc' => __('AI-generated, for reference only', 'xhtheme-ai-toolbox'),
            'summaryCssCode' => '',
            'summaryExportFields' => [],

            // 标签配置
            'tagEnabled' => true,
            'tagMinCount' => 2,
            'tagMaxCount' => 4,
            'tagExpandDefault' => false,
            'tagSeoTitle' => true,

            // 评论配置
            'commentEnabled' => true,
            'commentMinCount' => 10,
            'commentMaxCount' => 50,
            'commentMaxday' => 30,
            'commentGroup' => 3,
            'commentNotice' => true,
            'commentuser' => (xh_themeName() === 'Zibll') ? 'user' : 'guest',
            'commentMixedRatio' => 20,

            // 元数据配置
            'primarySlug' => false,
            'primaryCategory' => false,

            // 话题配置
            'primaryThread' => true,
            'primaryThreadTypes' => ['question', 'definition'],
            'primaryThreadPerspectives' => ['blogger', 'expert'],
            'primaryThreadTitle' => __('Related Topics', 'xhtheme-ai-toolbox'),
            'primaryThreadNumber' => 3,
            'primaryThreadtype' => 'default',
            'primaryThreadDesc' => '',
            'primaryThreadComment' => true,
            'primaryThreadimage' => false,
            'primaryThreadimageRatio' => 50,
            'primaryThreadTemplate' => (function_exists('wp_is_block_theme') && wp_is_block_theme()) ? 'default' : 's2',
            'primaryThreadPage' => false,

            // 图片配置
            'imageThumb' => false,
            'imagePlatform' => 'default',
            'imageSize' => '1280x768',
            'imageStyle' => 'auto',
            'imageApikey' => '',
            'imageAliyunRegion' => 'beijing',
            'imageModel' => 'flash',
            'imageModelCode' => '',
            'imagePromptLevel' => 'safe',
            'imagePattern' => 'fill',
            'imageMapnum' => '1',
            'imageMark' => false,
            'imageCompress' => true
        ];
    }

    /**
     * 构造函数
     */
    private function __construct()
    {
        $this->init_hooks();
    }

    /**
     * 初始化钩子
     */
    private function init_hooks()
    {
        // 注册后台菜单
        add_action('admin_menu', [$this, 'add_admin_pages']);

        // 注册后台脚本
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('admin_head', [$this, 'print_admin_menu_icon_styles']);

        // 注册顶部工具栏链接
        add_action('admin_bar_menu', [$this, 'add_toolbar_queue_link'], 100);

        // 注册插件设置链接
        add_filter('plugin_action_links', [$this, 'add_settings_link'], 10, 2);

        // 注册AJAX处理
        add_action('wp_ajax_save_xhtheme_ai_settings', [$this, 'ajax_save_settings']);
        add_action('wp_ajax_xhaitool_thread_page', [$this, 'toggle_thread_page']);
        add_action('wp_ajax_hide_theme_notice', [$this, 'ajax_hide_theme_notice']);
        add_action('wp_ajax_xhaitool_wizard_save', [$this, 'ajax_wizard_save']);
        add_action('wp_ajax_xhaitool_upload_ticket_image', [$this, 'ajax_upload_ticket_image']);
        add_action('wp_ajax_xhaitool_submit_support_ticket', [$this, 'ajax_submit_support_ticket']);

        // 注册后台通知
        add_action('admin_notices', [$this, 'show_adminnotice']);

        // 在插件页面屏蔽所有 WP 后台通知
        add_action('in_admin_header', [$this, 'suppress_admin_notices']);

        // 注册停用反馈弹窗脚本
        add_action('admin_enqueue_scripts', [$this, 'enqueue_deactivate_feedback']);
        add_action('xhaitoolbox_log_error', [$this, 'pass_error'],10 ,2);
        add_action('wp_ajax_xhtheme_log_react_error', [$this, 'ajax_log_react_error']);
    }

    /**
     * 固定 AI 助理后台菜单图标尺寸与位置
     */
    public function print_admin_menu_icon_styles()
    {
        ?>
        <style id="xhtheme-ai-toolbox-admin-menu-icon">
            #adminmenu #toplevel_page_xhtheme-ai-toolbox .wp-menu-image {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            #adminmenu #toplevel_page_xhtheme-ai-toolbox .wp-menu-image:before {
                display: none;
            }

            #adminmenu #toplevel_page_xhtheme-ai-toolbox .wp-menu-image img {
                width: 18px;
                height: 18px;
                max-width: 18px;
                max-height: 18px;
                padding: 0;
                object-fit: contain;
                opacity: 1;
            }
        </style>
        <?php
    }

    /**
     * 在插件自有页面屏蔽所有 WordPress 后台通知
     */
    public function suppress_admin_notices()
    {
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }

        $plugin_pages = [
            'page_xhtheme-ai-toolbox'
        ];

        foreach ($plugin_pages as $page) {
            if (strpos($screen->id, $page) !== false) {
                remove_all_actions('admin_notices');
                remove_all_actions('all_admin_notices');
                break;
            }
        }
    }

    /**
     * 错误上报到服务器
     */
    public function pass_error($errorMsg, $data = [])
    {
        if (defined('XHAITOOLBOX_ERROR_NOAPI') && XHAITOOLBOX_ERROR_NOAPI) {
            return;
        }

        $rate_data = get_transient('xhaitool_errorrate_limit');
        $current_time = time();

        if (!$rate_data || ($current_time - $rate_data['time'] > HOUR_IN_SECONDS)) {
            $rate_data = ['time' => $current_time, 'count' => 0];
        }

        if ($rate_data['count'] >= 5) {
            return;
        }
        $apiCode = isset($data['code']) ? $data['code'] : 0;
        if( $apiCode == 5 ){
            return;
        }

        $rate_data['count']++;
        set_transient('xhaitool_errorrate_limit', $rate_data, HOUR_IN_SECONDS);

        xh_api_request('error-report', [
            'args' => [
                'site_hash' => md5(home_url()),
                'error' => sanitize_text_field($errorMsg),
                'php' => PHP_VERSION,
                'wp' => get_bloginfo('version'),
                'otherdata' => $data
            ]
        ], null, 'aidata', 10);
    }

    /**
     * AJAX 处理 React 加载失败日志
     */
    public function ajax_log_react_error()
    {
        check_ajax_referer('xhtheme_react_log_nonce');
        if (get_transient('xhtheme_react_error_rate_limit')) {
            wp_send_json_success();
            return;
        }
        set_transient('xhtheme_react_error_rate_limit', true, 10 * MINUTE_IN_SECONDS);
        $error = isset($_POST['error']) ? sanitize_text_field(wp_unslash($_POST['error'])) : 'React load failed';
        xhaitoolbox_log_error($error);
        wp_send_json_success();
    }

    /**
     * 工单图片上传 AJAX 处理
     * 接受 $_FILES['image']，压缩转 base64 后上传到远程临时附件服务器
     */
    public function ajax_upload_ticket_image()
    {
        check_ajax_referer('xhtheme_ai_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions', 'xhtheme-ai-toolbox')]);
        }

        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Uploaded file array is validated field-by-field below.
        $file = isset($_FILES['image']) && is_array($_FILES['image']) ? $_FILES['image'] : [];

        if (
            empty($file) ||
            !isset($file['error'], $file['name'], $file['type'], $file['tmp_name'], $file['size']) ||
            UPLOAD_ERR_OK !== (int) $file['error']
        ) {
            wp_send_json_error(['message' => __('No valid image file was received.', 'xhtheme-ai-toolbox')]);
        }

        $file_name = sanitize_file_name(wp_unslash($file['name']));
        $file_type = sanitize_mime_type(wp_unslash($file['type']));
        $file_tmp_name = sanitize_text_field(wp_unslash($file['tmp_name']));
        $file_size = absint($file['size']);
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $checked_file_type = wp_check_filetype($file_name);
        $mime = !empty($checked_file_type['type']) ? $checked_file_type['type'] : $file_type;

        if (!in_array($mime, $allowed_types, true)) {
            wp_send_json_error(['message' => __('Unsupported image format. Only JPG, PNG, GIF, and WebP are supported.', 'xhtheme-ai-toolbox')]);
        }

        $max_size = 10 * 1024 * 1024; // 10MB
        if ($file_size > $max_size) {
            wp_send_json_error(['message' => __('Image file exceeds the 10MB size limit.', 'xhtheme-ai-toolbox')]);
        }

        // 使用图像编辑器压缩并统一为 JPEG
        $editor = wp_get_image_editor($file_tmp_name);
        $output_mime = 'image/jpeg';

        if (!is_wp_error($editor)) {
            $size = $editor->get_size();
            $editor->set_quality(85);

            $max_side = 1200;
            if ($size['width'] > $max_side || $size['height'] > $max_side) {
                $editor->resize($max_side, $max_side, false);
            }

            if (!function_exists('wp_tempnam')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }
            $tmp_file = wp_tempnam('ticket_img_');
            $saved = $editor->save($tmp_file, 'image/jpeg');

            if (!is_wp_error($saved) && file_exists($saved['path'])) {
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading local temp file
                $file_content = file_get_contents($saved['path']);
                wp_delete_file($saved['path']);
                if ($saved['path'] !== $tmp_file && file_exists($tmp_file)) {
                    wp_delete_file($tmp_file);
                }
            } else {
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading uploaded temp file
                $file_content = file_get_contents($file_tmp_name);
                if (file_exists($tmp_file)) {
                    wp_delete_file($tmp_file);
                }
            }
        } else {
            // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Reading uploaded temp file
            $file_content = file_get_contents($file_tmp_name);
        }

        if (empty($file_content)) {
            wp_send_json_error(['message' => __('Image content is empty.', 'xhtheme-ai-toolbox')]);
        }

        $base64_image = 'data:' . $output_mime . ';base64,' . base64_encode($file_content);

        // 上传到远程临时附件服务器
        $appid = xh_option('appId', '');
        if (empty($appid)) {
            wp_send_json_error(['message' => __('AppID is not configured. Upload is unavailable.', 'xhtheme-ai-toolbox')]);
        }

        $response = wp_remote_post(XHTHEME_AI_TOOLBOX_IMAGE_TMPURL, [
            'headers' => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $appid,
            ],
            'body'    => wp_json_encode(['image' => $base64_image]),
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => $response->get_error_message()]);
        }

        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code !== 200) {
            /* translators: %d: HTTP status code returned by the remote upload service. */
            wp_send_json_error(['message' => sprintf(__('Upload failed, HTTP status code: %d', 'xhtheme-ai-toolbox'), $status_code)]);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!isset($body['code']) || $body['code'] !== 0) {
            $message = isset($body['message']) ? $body['message'] : __('Upload failed', 'xhtheme-ai-toolbox');
            wp_send_json_error(['message' => $message]);
        }

        $filename = isset($body['data']['filename']) ? sanitize_file_name($body['data']['filename']) : '';

        wp_send_json_success([
            'filename' => $filename,
            'expires'  => isset($body['data']['expires']) ? intval($body['data']['expires']) : 86400,
        ]);
    }

    /**
     * 工单提交 AJAX 处理
     */
    public function ajax_submit_support_ticket()
    {
        check_ajax_referer('xhtheme_ai_toolbox_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions to submit a ticket.', 'xhtheme-ai-toolbox')]);
        }

        $appid = xh_option('appId', '');
        if (empty($appid)) {
            wp_send_json_error(['message' => __('Please enter the AppID in Global Environment Settings before submitting a ticket.', 'xhtheme-ai-toolbox')]);
        }

        $ticket_type = isset($_POST['ticketType']) ? sanitize_key(wp_unslash($_POST['ticketType'])) : '';
        $allowed_types = ['api', 'ui', 'logic', 'feature', 'other'];
        if (!in_array($ticket_type, $allowed_types, true)) {
            wp_send_json_error(['message' => __('Please select a valid ticket type.', 'xhtheme-ai-toolbox')]);
        }

        $ticket_content = isset($_POST['content']) ? sanitize_textarea_field(wp_unslash($_POST['content'])) : '';
        if (empty(trim($ticket_content))) {
            wp_send_json_error(['message' => __('Please enter your issue description before submitting a ticket.', 'xhtheme-ai-toolbox')]);
        }

        $include_diagnostics = isset($_POST['includeDiagnostics']) && wp_validate_boolean(wp_unslash($_POST['includeDiagnostics']));
        if (!$include_diagnostics) {
            wp_send_json_error(['message' => __('Please enable environment diagnostics before submitting a ticket.', 'xhtheme-ai-toolbox')]);
        }

        $images = [];
        if (!empty($_POST['images'])) {
            $decoded_images = json_decode(wp_unslash($_POST['images']), true);
            if (is_array($decoded_images)) {
                foreach ($decoded_images as $image) {
                    if (!is_array($image)) {
                        continue;
                    }
                    $filename = isset($image['filename']) ? sanitize_file_name($image['filename']) : '';
                    if (empty($filename)) {
                        continue;
                    }
                    $images[] = [
                        'filename' => $filename,
                        'expires' => isset($image['expires']) ? absint($image['expires']) : 0,
                    ];
                }
            }
        }

        $request_args = [
            'content' => $ticket_content,
            'args' => [
                'ticketType' => $ticket_type,
                'includeDiagnostics' => $include_diagnostics,
                'images' => $images,
                'siteInfo' => $this->get_support_ticket_site_info(),
            ],
        ];

        $result = xh_api_request('support-ticket', $request_args, null, 'data', 15);
        if (is_wp_error($result)) {
            wp_send_json_error([
                'message' => $result->get_error_message() ?: __('Ticket submission failed. Please try again later.', 'xhtheme-ai-toolbox'),
            ]);
        }

        $masked_email = isset($result['email']) ? sanitize_text_field($result['email']) : '';
        $success_message = $masked_email
            ? sprintf(
                /* translators: %s: masked support email address. */
                __('Your ticket has been submitted. We will share progress with your email address [%s].', 'xhtheme-ai-toolbox'),
                $masked_email
            )
            : __('Your ticket has been submitted. The development team will update you by email as soon as possible.', 'xhtheme-ai-toolbox');

        wp_send_json_success([
            'message' => $success_message,
            'email' => $masked_email,
        ]);
    }

    /**
     * 获取工单诊断信息
     */
    private function get_support_ticket_site_info()
    {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $theme = wp_get_theme();
        $plugins = get_plugins();
        $active_plugins = (array) get_option('active_plugins', []);

        if (is_multisite()) {
            $network_plugins = array_keys((array) get_site_option('active_sitewide_plugins', []));
            $active_plugins = array_unique(array_merge($active_plugins, $network_plugins));
        }

        $active_plugin_snapshots = [];
        foreach ($active_plugins as $plugin_file) {
            $plugin_meta = isset($plugins[$plugin_file]) ? $plugins[$plugin_file] : [];
            $active_plugin_snapshots[] = [
                'name' => isset($plugin_meta['Name']) ? $plugin_meta['Name'] : $plugin_file,
                'version' => isset($plugin_meta['Version']) ? $plugin_meta['Version'] : '',
                'path' => $plugin_file,
            ];
        }

        return [
            'siteUrl' => site_url(),
            'homeUrl' => home_url(),
            'phpVersion' => PHP_VERSION,
            'wpVersion' => get_bloginfo('version'),
            'themeName' => $theme->get('Name'),
            'themeVersion' => $theme->get('Version'),
            'pluginVersion' => XHTHEME_AI_TOOLBOX_VERSION,
            'locale' => get_locale(),
            'isMultisite' => is_multisite(),
            'activePlugins' => $active_plugin_snapshots,
        ];
    }


    /**
     * 添加后台菜单页面
     */
    public function add_admin_pages()
    {
        $menu_icon = plugin_dir_url(dirname(__FILE__)) . 'assets/images/botton-xxxxx-icon.png';

        // 主菜单
        add_menu_page(
            __('XHTheme AI Assistant', 'xhtheme-ai-toolbox'),
            __('XHTheme AI Assistant', 'xhtheme-ai-toolbox'),
            'manage_options',
            'xhtheme-ai-toolbox',
            [$this, 'render_settings_page'],
            $menu_icon
        );

        // 仪表盘首页子菜单
        add_submenu_page(
            'xhtheme-ai-toolbox',
            __('Basic Settings', 'xhtheme-ai-toolbox'),
            __('Basic Settings', 'xhtheme-ai-toolbox'),
            'manage_options',
            'xhtheme-ai-toolbox',
            [$this, 'render_settings_page']
        );

        // 任务队列子菜单
        $pending_count = XHCronQueue::getInstance()->getCachedPendingCount();
        $queue_menu_title = __('Task Queue', 'xhtheme-ai-toolbox');
        if ($pending_count > 0) {
            $queue_menu_title .= sprintf(
                ' <span class="awaiting-mod count-%d"><span class="pending-count">%s</span></span>',
                $pending_count,
                number_format_i18n($pending_count)
            );
        }
        add_submenu_page(
            'xhtheme-ai-toolbox',
            __('Task Queue', 'xhtheme-ai-toolbox'),
            $queue_menu_title,
            'manage_options',
            'xhtheme-ai-queue',
            [$this, 'render_queue_page']
        );

        // 自动化设置子菜单
        add_submenu_page(
            'xhtheme-ai-toolbox',
            __('Automation', 'xhtheme-ai-toolbox'),
            __('Automation', 'xhtheme-ai-toolbox'),
            'manage_options',
            'xhtheme-ai-automate',
            [$this, 'render_automate_page']
        );


        // AI 互动助手子菜单
        $comment_menu_title  = __('Smart Interaction Assistant', 'xhtheme-ai-toolbox');
        $comment_menu_title .= sprintf(
            ' <span class="awaiting-mod count-1 xh-newicon-menu" style="transform: scale(.8);transform-origin: left;"><span class="pending-count">%s</span></span>',
            __('New', 'xhtheme-ai-toolbox')
        );
        add_submenu_page(
            'xhtheme-ai-toolbox',
            __('Smart Interaction Assistant', 'xhtheme-ai-toolbox'),
            $comment_menu_title,
            'manage_options',
            'xhtheme-ai-interact',
            [$this, 'render_interact_page']
        );

        // 配置引导子菜单
        $option_json = get_option('xhtheme_ai_toolbox_automate_rules');
        $rules_json = get_option('xhtheme_ai_toolbox_automate_rules');
        if ($option_json && $rules_json) {
            return;
        }
        add_submenu_page(
            'xhtheme-ai-toolbox',
            __('Setup Wizard', 'xhtheme-ai-toolbox'),
            __('Setup Wizard', 'xhtheme-ai-toolbox'),
            'manage_options',
            'xhtheme-ai-wizard',
            [$this, 'render_wizard_page']
        );
    }

    /**
     * 渲染设置页面
     */
    public function render_settings_page()
    {
        echo '<div id="xhtheme-ai-toolbox-wrapper"></div>';
    }

    /**
     * 渲染队列页面
     */
    public function render_queue_page()
    {
        echo '<div id="xhtheme-ai-toolbox-queues-wrapper"></div>';
    }

    /**
     * 渲染自动化页面
     */
    public function render_automate_page()
    {
        echo '<div id="xhtheme-ai-toolbox-automate-wrapper"></div>';
    }

    /**
     * 渲染配置引导页面
     */
    public function render_wizard_page()
    {
        echo '<div id="xhtheme-ai-toolbox-wizard-wrapper" class="xhtheme-wizard-fullpage" style="position:fixed;top:0;left:0;right:0;bottom:0;z-index:99999;background-color:#f3f4f6;display:flex;align-items:center;justify-content:center;">
            <div style="text-align:center;color:#94a3b8;">
                <svg style="width:48px;height:48px;animation:spin 1s linear infinite;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle style="opacity:0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path style="opacity:0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <style>@keyframes spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}</style>
            </div>
        </div>';
    }

    /**
     * 渲染 AI 互动助手页面
     */
    public function render_interact_page()
    {
        echo '<div id="xhtheme-ai-interact-wrapper"></div>';
    }

    /**
     * 加载后台脚本和样式
     */
    public function enqueue_admin_scripts()
    {
        $screen = get_current_screen();
        $enqueue = false;
        $pages = [
            'page_xhtheme-ai-toolbox',
            'page_xhtheme-ai-queue',
            'page_xhtheme-ai-automate',
            'page_xhtheme-ai-wizard',
            'page_xhtheme-ai-interact'
        ];

        foreach ($pages as $page) {
            if (strpos($screen->id, $page) !== false) {
                $enqueue = true;
                break;
            }
        }

        if (!$enqueue) {
            return;
        }

        $dir = untrailingslashit(plugin_dir_path(dirname(__FILE__)));
        $url = untrailingslashit(plugin_dir_url(dirname(__FILE__)));

        // 判断页面类型
        $is_dashboard_page = strpos($screen->id, 'page_xhtheme-ai-toolbox') !== false;
        $is_queue_page = strpos($screen->id, 'page_xhtheme-ai-queue') !== false;
        $is_automate_page = strpos($screen->id, 'page_xhtheme-ai-automate') !== false;
        $is_wizard_page = strpos($screen->id, 'page_xhtheme-ai-wizard') !== false;
        $is_interact_page = strpos($screen->id, 'page_xhtheme-ai-interact') !== false;

        wp_enqueue_script(
            'xhtheme-check-react',
            $url . '/assets/js/check-react.js',
            ['react', 'react-dom'],
            XHTHEME_AI_TOOLBOX_VERSION,
            true
        );
        wp_localize_script('xhtheme-check-react', 'xhtheme_react_check_vars', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('xhtheme_react_log_nonce')
        ]);

        if ($is_wizard_page) {
            // 加载向导脚本
            if (!file_exists("{$dir}/build/wizard.asset.php")) {
                return;
            }
            $asset = include "{$dir}/build/wizard.asset.php";
            wp_enqueue_script(
                'xhtheme-ai-toolbox-wizard',
                "{$url}/build/wizard.js",
                $asset['dependencies'],
                $asset['version'],
                true
            );
            wp_enqueue_style(
                'xhtheme-ai-toolbox-wizard',
                "{$url}/build/wizard.css",
                [],
                $asset['version']
            );
            wp_set_script_translations(
                'xhtheme-ai-toolbox-wizard',
                'xhtheme-ai-toolbox',
                plugin_dir_path(dirname(__FILE__)) . 'languages'
            );
            $script_handle = 'xhtheme-ai-toolbox-wizard';
        } elseif ($is_interact_page) {
            // 加载 AI 互动助手脚本
            if (!file_exists("{$dir}/build/interact.asset.php")) {
                // 如果 interact 脚本不存在，暂时使用 settings 脚本
                if (!file_exists("{$dir}/build/settings.asset.php")) {
                    return;
                }
                $asset = include "{$dir}/build/settings.asset.php";
                wp_enqueue_script(
                    'xhtheme-ai-toolbox-settings',
                    "{$url}/build/settings.js",
                    $asset['dependencies'],
                    $asset['version'],
                    true
                );
                $script_handle = 'xhtheme-ai-toolbox-settings';
            } else {
                $asset = include "{$dir}/build/interact.asset.php";
                wp_enqueue_script(
                    'xhtheme-ai-interact',
                    "{$url}/build/interact.js",
                    $asset['dependencies'],
                    $asset['version'],
                    true
                );
                wp_enqueue_style(
                    'xhtheme-ai-interact',
                    "{$url}/build/interact.css",
                    [],
                    $asset['version']
                );
                wp_set_script_translations(
                    'xhtheme-ai-interact',
                    'xhtheme-ai-toolbox',
                    plugin_dir_path(dirname(__FILE__)) . 'languages'
                );
                $script_handle = 'xhtheme-ai-interact';

                // 为 interact 页面添加专属本地化数据
                $XHInteract = XHInteract::getInstance();
                $settings = $XHInteract->get_settings();
                $settings = $XHInteract->enrich_settings_for_admin($settings);

                wp_localize_script($script_handle, 'xhInteractData', [
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('xhinteract_nonce'),
                    'settings' => $settings,
                    'stats' => $XHInteract->get_stats(),
                    'pluginUrl' => plugin_dir_url(dirname(__FILE__)),
                    'hasAppId' => !empty(xh_option('appId', '')),
                    'settingsUrl' => admin_url('admin.php?page=xhtheme-ai-toolbox'),
                    'commentablePostTypes' => $this->get_commentable_post_types(),
                ]);
                return;
            }
        } elseif ($is_dashboard_page) {
            // 加载控制台脚本
            if (!file_exists("{$dir}/build/settings.asset.php")) {
                return;
            }
            $asset = include "{$dir}/build/settings.asset.php";
            wp_enqueue_script(
                'xhtheme-ai-toolbox-settings',
                "{$url}/build/settings.js",
                $asset['dependencies'],
                $asset['version'],
                true
            );
            wp_enqueue_style(
                'xhtheme-ai-toolbox-settings',
                "{$url}/build/settings.css",
                [],
                $asset['version']
            );
            wp_set_script_translations(
                'xhtheme-ai-toolbox-settings',
                'xhtheme-ai-toolbox',
                plugin_dir_path(dirname(__FILE__)) . 'languages'
            );
            $script_handle = 'xhtheme-ai-toolbox-settings';
        } elseif ($is_queue_page) {
            // 加载队列脚本
            if (!file_exists("{$dir}/build/queues.asset.php")) {
                return;
            }
            $asset = include "{$dir}/build/queues.asset.php";
            wp_enqueue_script(
                'xhtheme-ai-toolbox-queues',
                "{$url}/build/queues.js",
                $asset['dependencies'],
                $asset['version'],
                true
            );
            wp_enqueue_style(
                'xhtheme-ai-toolbox-queues',
                "{$url}/build/queues.css",
                [],
                $asset['version']
            );
            wp_set_script_translations(
                'xhtheme-ai-toolbox-queues',
                'xhtheme-ai-toolbox',
                plugin_dir_path(dirname(__FILE__)) . 'languages'
            );
            $script_handle = 'xhtheme-ai-toolbox-queues';
        } elseif ($is_automate_page) {
            // 加载自动化脚本
            if (!file_exists("{$dir}/build/automate.asset.php")) {
                return;
            }
            $asset = include "{$dir}/build/automate.asset.php";
            wp_enqueue_script(
                'xhtheme-ai-toolbox-automate',
                "{$url}/build/automate.js",
                $asset['dependencies'],
                $asset['version'],
                true
            );
            wp_enqueue_style(
                'xhtheme-ai-toolbox-automate',
                "{$url}/build/automate.css",
                [],
                $asset['version']
            );
            wp_set_script_translations(
                'xhtheme-ai-toolbox-automate',
                'xhtheme-ai-toolbox',
                plugin_dir_path(dirname(__FILE__)) . 'languages'
            );
            $script_handle = 'xhtheme-ai-toolbox-automate';
        } else {
            return;
        }

        // 获取保存的设置，与默认值合并
        $saved_settings = get_option('xhtheme_ai_toolbox_settings', []);
        $settings = wp_parse_args($saved_settings, self::get_default_settings());

        if (!function_exists('is_plugin_active')) {
            include_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }

        $ai_instance = XHThemeAi::getInstance();
        $thread_instance = XHThread::getInstance();
        $remote_state = XHDashboardRemoteState::getInstance()->get_bootstrap_payload();
        $userQuota = $remote_state['userQuota'];

        $links = $this->get_dashboard_links();
        $queue_tasks = xh_active_post_types();
        $queue_pending_count = XHCronQueue::getInstance()->getCachedPendingCount();
        $dashboard_payload = [
            'queuePendingCount' => $queue_pending_count,
            'queueActive' => XHCronQueue::getInstance()->isQueueActive(),
            'queueUrl' => admin_url('admin.php?page=xhtheme-ai-queue'),
            'automateUrl' => admin_url('admin.php?page=xhtheme-ai-automate'),
            'interactUrl' => admin_url('admin.php?page=xhtheme-ai-interact'),
            'links' => $links,
            'automateRules' => [],
            'interactStats' => [],
            'interactSummary' => [],
            'aiUserCount' => 0,
        ];

        if ($is_dashboard_page) {
            $dashboard_payload['automateRules'] = $this->get_dashboard_automate_rules();
            $dashboard_payload['interactStats'] = XHInteract::getInstance()->get_stats();
            $dashboard_payload['interactSummary'] = $this->get_dashboard_interact_summary();
            $dashboard_payload['aiUserCount'] = (new XHTool())->get_ai_user_count();
        }

        wp_localize_script(
            $script_handle,
            'xhthemeAiToolbox',
            array_merge(
                [
                    'nonce' => wp_create_nonce('xhtheme_ai_toolbox_nonce'),
                    'settings' => $settings,
                    'modelList' => $remote_state['modelList'],
                    'modelVersion' => $remote_state['modelVersion'],
                    'updateTime' => $remote_state['updateTime'],
                    'dashboardMessages' => $remote_state['dashboardMessages'],
                    'classicEditorActive' => is_plugin_active('classic-editor/classic-editor.php'),
                    'gutenbergActive' => function_exists('register_block_type'),
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'uploadNonce' => wp_create_nonce('xhtheme_ai_nonce'),
                    'pluginVersion' => XHTHEME_AI_TOOLBOX_VERSION,
                    'version' => $ai_instance->getVersion(),
                    'apiurl' => xh_apiurl(),
                    'apitoken' => xh_option('appId', ''),
                    'userAppiderror' => $ai_instance->userData('error'),
                    'userType' => $ai_instance->userData('type'),
                    'userName' => $ai_instance->userData('name'),
                    'userQuota' => $userQuota,
                    'userTypename' => $ai_instance->userTypeName($ai_instance->userData('type')),
                    //'userType' => 'free',
                    //'userTypename' => '免费用户',
                    'queueTasks' => $queue_tasks,
                    'automationCapabilities' => xh_automation_task_capabilities(),
                    'themeFitter' => xh_themefitter_notice(),
                    'themeName' => xh_themeName(),
                    'blockTheme' => function_exists('wp_is_block_theme') && wp_is_block_theme(),
                    'threadPageEditUrl' => $thread_instance->get_pageedit_url(),
                    'settingsUrl' => admin_url('admin.php?page=xhtheme-ai-toolbox'),
                    'pluginUrl' => plugin_dir_url(dirname(__FILE__)),
                ],
                $dashboard_payload
            )
        );
    }

    /**
     * 获取仪表盘外部链接
     */
    private function get_dashboard_links()
    {
        $links = [
            'docs' => 'https://www.xhtheme.com/docs/aitoolbox',
            'automateDocs' => 'https://www.xhtheme.com/docs/aitoolbox/ai-automate-docs',
            'faq' => 'https://www.xhtheme.com/docs/aitoolbox/problem',
            'pricing' => 'https://www.xhtheme.com/xhtheme-ai-toolbox#pricing',
            'site' => 'https://www.xhtheme.com/xhtheme-ai-toolbox',
            'support' => 'https://www.xhtheme.com/users#chat',
            'queue' => admin_url('admin.php?page=xhtheme-ai-queue'),
            'automate' => admin_url('admin.php?page=xhtheme-ai-automate'),
            'interact' => admin_url('admin.php?page=xhtheme-ai-interact'),
            'changelog' => 'https://www.xhtheme.com/xhtheme-ai-toolbox',
        ];

        return apply_filters('xhtheme_ai_toolbox_dashboard_links', $links);
    }

    /**
     * 获取仪表盘自动化规则摘要数据
     */
    private function get_dashboard_automate_rules()
    {
        $rules_json = get_option('xhtheme_ai_toolbox_automate_rules', '[]');
        $rules = json_decode($rules_json, true);

        if (empty($rules)) {
            $rules = xh_migrate_automate_config();
        }

        return is_array($rules) ? array_values($rules) : [];
    }

    /**
     * 获取仪表盘互动模块摘要状态
     */
    private function get_dashboard_interact_summary()
    {
        $settings = XHInteract::getInstance()->get_settings();

        return [
            'auditEnabled' => !empty($settings['audit']['enabled']),
            'autoReplyEnabled' => !empty($settings['auto_reply']['enabled']),
            'moderatorEnabled' => !empty($settings['moderator']['enabled']),
            'randCommentEnabled' => !empty($settings['rand_comment']['enabled']),
            'emailNotifyEnabled' => !empty($settings['email_notify']['enabled']),
        ];
    }

    /**
     * 添加顶部工具栏链接
     */
    public function add_toolbar_queue_link($wp_admin_bar)
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $icon_svg = '<svg style="width:20px;height:20px;margin-top:2px;vertical-align:middle;fill:currentColor;opacity:.75;margin-right:3px" viewBox="0 0 1024 1024"><path d="M240.832 250.24v549.76a38.4 38.4 0 0 0 76.8 0v-155.968q48.512-15.104 92.544-15.104 53.568 0 101.44 22.528 63.36 29.824 134.208 29.824 69.248 0 144.576-28.672a38.4 38.4 0 0 0 24.704-35.84V250.112a38.4 38.4 0 0 0-52.096-35.84q-62.08 23.68-117.184 23.68-53.632 0-101.504-22.592Q480.96 185.6 410.24 185.6q-69.248 0-144.64 28.672a38.4 38.4 0 0 0-24.704 35.904zM410.24 552.064q-44.992 0-92.544 12.16V277.44Q366.144 262.4 410.24 262.4q53.568 0 101.44 22.528 63.36 29.824 134.208 29.824 44.928 0 92.48-12.096v286.72q-48.512 15.104-92.48 15.104-53.632 0-101.504-22.528-63.36-29.824-134.144-29.824z"></path></svg>';

        // 获取队列数量
        $pending_count = XHCronQueue::getInstance()->getCachedPendingCount();
        $count_badge = '';
        if ($pending_count > 0) {
            $count_badge = '｜<span style="opacity:0.8">' . number_format_i18n($pending_count) . '</span>';
        }

        $wp_admin_bar->add_node([
            'id' => 'xhtheme-ai-queue',
            'title' => $icon_svg . ' <span style="vertical-align:middle">' . __('AI Queue', 'xhtheme-ai-toolbox') . '</span>' . $count_badge,
            'href' => admin_url('admin.php?page=xhtheme-ai-queue'),
            'meta' => [
                'title' => __('Manage AI Task Queue', 'xhtheme-ai-toolbox'),
                'html' => '<style>#wp-admin-bar-xhtheme-ai-queue .ab-item{display:flex !important;align-items:center !important;}</style>'
            ]
        ]);
    }


    /**
     * 添加插件设置链接
     */
    public function add_settings_link($links, $file)
    {
        $plugin_basename = plugin_basename(dirname(dirname(__FILE__)) . '/aitoolbox.php');

        if ($file === $plugin_basename && current_user_can('manage_options')) {
            $url = admin_url('admin.php?page=xhtheme-ai-toolbox');
            $links = (array) $links;
            $links[] = sprintf('<a href="%s">%s</a>', $url, __('Console', 'xhtheme-ai-toolbox'));
            $links[] = sprintf(
                '<a href="%s" target="_blank" style="color:#04b3a2">%s</a>',
                'https://www.xhtheme.com/docs/aitoolbox',
                __('Documentation', 'xhtheme-ai-toolbox')
            );
        }

        return $links;
    }

    /**
     * AJAX: 保存设置
     */
    public function ajax_save_settings()
    {
        // 验证nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'xhtheme_ai_toolbox_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'xhtheme-ai-toolbox')]);
            return;
        }

        // 检查权限
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions', 'xhtheme-ai-toolbox')]);
            return;
        }

        // 获取设置数据 - JSON 原文仅做 wp_unslash，字段清理在 validate_settings() 中完成
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON payload sanitized after decode in validate_settings()
        $settingsRaw = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : '';
        if (!is_string($settingsRaw) || trim($settingsRaw) === '') {
            wp_send_json_error(['message' => __('No settings data received', 'xhtheme-ai-toolbox')]);
            return;
        }

        $settings = json_decode($settingsRaw, true);
        if (!is_array($settings)) {
            wp_send_json_error(['message' => __('Settings data format error', 'xhtheme-ai-toolbox')]);
            return;
        }

        $refresh = false;
        $validated_settings = $this->validate_settings($settings);

        // 如果未启用评论功能，强制关闭话题自动评论
        if (empty($validated_settings['commentEnabled'])) {
            $validated_settings['primaryThreadComment'] = false;
        }

        $userappId = isset($validated_settings['appId']) ? $validated_settings['appId'] : '';
        $oldappId = xh_option('appId', '');

        // 保存设置到数据库
        update_option('xhtheme_ai_toolbox_settings', $validated_settings);

        if ($oldappId !== $userappId) {
            $refresh = true;
            delete_transient('xhtheme_aitoolbox_users_error');
            delete_transient('xhtheme_aitoolbox_users');
            delete_option('xhtheme_aitoolbox_users');
            if ($userappId) {
                delete_transient('xhtheme_aitoolbox_apicheck');
                XHThemeAi::getInstance()->fetchRemoteModelList(false);
            }
        }

        if (isset($validated_settings['primaryThread'])) {
            if (!empty($validated_settings['primaryThread'])) {
                if (get_option('xhtheme_ai_toolbox_thread_rewrite') !== 'pass') {
                    update_option('xhtheme_ai_toolbox_thread_rewrite', 'load');
                }
            } else {
                delete_option('xhtheme_ai_toolbox_thread_rewrite');
            }
        }

        wp_send_json_success([
            'message' => __('Settings saved', 'xhtheme-ai-toolbox'),
            'refresh' => $refresh
        ]);
    }

    /**
     * 验证设置数据
     */
    private function validate_settings($settings)
    {
        $validated_settings = [];

        foreach ($settings as $key => $value) {
            switch ($key) {
                case 'tagEnabled':
                case 'tagSeoTitle':
                case 'summaryEnabled':
                case 'commentEnabled':
                case 'commentPlanned':
                case 'primarySlug':
                case 'primaryCategory':
                case 'tagExpandDefault':
                case 'commentNotice':
                case 'primaryThread':
                case 'primaryThreadComment':
                case 'primaryThreadimage':
                case 'imageThumb':
                case 'imageMark':
                case 'imageCompress':
                case 'imageRecognition':
                case 'primaryThreadPage':
                case 'aiWorkbenchAutoOpen':
                    $validated_settings[$key] = (bool) $value;
                    break;

                case 'imagePromptLevel':
                    $promptLevel = sanitize_key((string) $value);
                    $validated_settings[$key] = in_array($promptLevel, ['safe', 'aggressive'], true)
                        ? $promptLevel
                        : 'safe';
                    break;

                case 'tagMinCount':
                case 'tagMaxCount':
                case 'summaryMaxLength':
                case 'commentMinCount':
                case 'commentMaxCount':
                case 'commentMaxday':
                case 'commentGroup':
                case 'commentMixedRatio':
                case 'primaryThreadNumber':
                case 'primaryThreadimageRatio':
                case 'aiUserLimit':
                    $validated_settings[$key] = absint($value);
                    break;

                case 'primaryThreadTypes':
                case 'primaryThreadPerspectives':
                case 'paragraphCapacity':
                    if (is_array($value)) {
                        $validated_settings[$key] = array_map(function ($item) {
                            return sanitize_text_field(trim($item));
                        }, $value);

                        if ($key === 'paragraphCapacity') {
                            if (
                                in_array('fyauto', $validated_settings[$key]) &&
                                isset($validated_settings['languageType']) &&
                                $validated_settings['languageType'] === 'webauto'
                            ) {
                                $validated_settings[$key] = array_filter($validated_settings[$key], function ($item) {
                                    return $item !== 'fyauto';
                                });
                            }
                        }
                    } else {
                        $validated_settings[$key] = [];
                    }
                    break;

                case 'summaryExportFields':
                    if (is_array($value)) {
                        $validated_settings[$key] = array_map(function ($item) {
                            return sanitize_text_field(trim($item));
                        }, $value);
                    } else {
                        $validated_settings[$key] = [];
                    }
                    break;

                case 'summaryCssCode':
                    if (function_exists('wp_strip_all_tags')) {
                        $css = wp_strip_all_tags($value);
                        $disallowed = ['javascript', 'expression', 'behavior', 'vbscript', 'mocha', 'livescript', 'data:', 'javascript:', 'vbscript:'];
                        foreach ($disallowed as $d) {
                            $css = preg_replace('/' . preg_quote($d, '/') . '/i', '', $css);
                        }
                        $css = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $css);
                        $css = preg_replace('/on\w+\s*=/i', '', $css);
                        $css = preg_replace('/[^a-zA-Z0-9\{\}\(\)\[\]\-\+\*\/\,\.\;\:\s\#\@\%\!\=\>\<\~\|\&\"\'\_\\\r\n\t]/', '', $css);

                        if (substr_count($css, '{') !== substr_count($css, '}')) {
                            $open_count = substr_count($css, '{');
                            $close_count = substr_count($css, '}');
                            if ($open_count > $close_count) {
                                $css .= str_repeat('}', $open_count - $close_count);
                            } elseif ($close_count > $open_count) {
                                $css = preg_replace('/\}/', '', $css, $close_count - $open_count);
                            }
                        }
                        $validated_settings[$key] = trim($css);
                    } else {
                        $validated_settings[$key] = '';
                    }
                    break;

                default:
                    $validated_settings[$key] = sanitize_text_field($value);
                    break;
            }
        }

        return $validated_settings;
    }

    /**
     * AJAX: 切换话题聚合页
     */
    public function toggle_thread_page()
    {
        // 验证nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'xhtheme_ai_toolbox_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'xhtheme-ai-toolbox')]);
        }

        // 检查权限
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions', 'xhtheme-ai-toolbox')]);
        }

        // 获取启用状态
        $is_enable = isset($_POST['enable']) && !empty(wp_unslash($_POST['enable']));

        $thread_instance = XHThread::getInstance();
        $threadPage = (array) $thread_instance->toggle_thread_page($is_enable);
        if (!$threadPage) {
            wp_send_json_error(['message' => __('Processing failed, please try again later!', 'xhtheme-ai-toolbox')]);
        }
        if ($threadPage['success']) {

            $response = ['message' => $threadPage['message']];
            // 返回编辑链接
            $edit_url = $thread_instance->get_pageedit_url();
            if ($edit_url) {
                $response['edit_url'] = $edit_url;
            }
            wp_send_json_success($response);
        }
        // 处理失败
        wp_send_json_error(['message' => $threadPage['message']]);
    }

    /**
     * AJAX: 隐藏主题通知
     */
    public function ajax_hide_theme_notice()
    {
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'xhtheme_ai_toolbox_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'xhtheme-ai-toolbox')]);
        }

        $theme_key = isset($_POST['theme']) ? sanitize_text_field(wp_unslash($_POST['theme'])) : '';
        if (empty($theme_key)) {
            wp_send_json_error(['message' => __('Theme key is required', 'xhtheme-ai-toolbox')]);
        }

        $hidden_notices = get_option('xhaitool_theme_notices', []);
        if (!is_array($hidden_notices)) {
            $hidden_notices = [];
        }
        $hidden_notices[] = $theme_key;
        $hidden_notices = array_unique($hidden_notices);
        update_option('xhaitool_theme_notices', $hidden_notices);

        wp_send_json_success(['message' => __('Notice hidden successfully', 'xhtheme-ai-toolbox')]);
    }

    /**
     * 显示配置提醒
     */
    public function show_adminnotice()
    {
        // 仅管理员可见
        if (!current_user_can('manage_options')) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only for admin notice display, no data modification
        $current_page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

        $appId = xh_option('appId', '');
        if (empty($appId)) {
            // 排除插件设置页面（避免重复提醒）            
            if ($current_page === 'xhtheme-ai-toolbox') {
                return;
            }
?>
            <div class="notice notice-warning" style="padding: 4px 10px; font-size: 12px;margin-top:20px;">
                <p style="margin: 0.3em 0;">
                    <strong><?php esc_html_e('XHTheme AI Toolbox', 'xhtheme-ai-toolbox'); ?>:</strong>
                    <?php esc_html_e('Please complete the AppID configuration to start using the plugin features.', 'xhtheme-ai-toolbox'); ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=xhtheme-ai-toolbox')); ?>"
                        style="margin-left: 6px; color: #2271b1; text-decoration: underline;">
                        <?php esc_html_e('Go to Settings', 'xhtheme-ai-toolbox'); ?> →
                    </a>
                </p>
            </div>
        <?php
            return;
        }

        // AppID 已配置，检查自动化规则
        $rules_json = get_option('xhtheme_ai_toolbox_automate_rules', '[]');
        $rules = json_decode($rules_json, true);

        if (empty($rules) || !is_array($rules) || count($rules) === 0) {
            if ($current_page === 'xhtheme-ai-automate') {
                return;
            }
        ?>
            <div class="notice notice-info" style="padding: 4px 10px; font-size: 12px;margin-top:20px;">
                <p style="margin: 0.3em 0;">
                    <strong><?php esc_html_e('XHTheme AI Toolbox', 'xhtheme-ai-toolbox'); ?>:</strong>
                    <?php esc_html_e('Configure automation rules to automatically apply AI capabilities to your posts and save time.', 'xhtheme-ai-toolbox'); ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=xhtheme-ai-automate')); ?>"
                        style="margin-left: 6px; color: #2271b1; text-decoration: underline;">
                        <?php esc_html_e('Configure Automation', 'xhtheme-ai-toolbox'); ?> →
                    </a>
                </p>
            </div>
<?php
            return;
        }
    }

    /**
     * AJAX: Wizard 保存配置
     */
    public function ajax_wizard_save()
    {
        // 验证nonce
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (empty($nonce) || !wp_verify_nonce($nonce, 'xhtheme_ai_toolbox_nonce')) {
            wp_send_json_error(['message' => __('Security check failed', 'xhtheme-ai-toolbox')]);
            return;
        }

        // 检查权限
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions', 'xhtheme-ai-toolbox')]);
            return;
        }

        // 获取数据
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- JSON data sanitized after decode
        $features_raw = isset($_POST['features']) ? wp_unslash($_POST['features']) : '[]';
        $config_raw = isset($_POST['config']) ? wp_unslash($_POST['config']) : '{}';

        $features = json_decode($features_raw, true);
        $config = json_decode($config_raw, true);

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

        // 创建模拟请求对象来复用 wizardSave 逻辑
        $params = [
            'features' => $features,
            'config' => $config
        ];

        // 调用保存逻辑
        $result = $this->wizardSaveInternal($params);

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }

    /**
     * Wizard 保存配置内部逻辑
     * 供 REST API 和 AJAX 共用
     */
    private function wizardSaveInternal($params)
    {
        $oldAppId = xh_option('appId', '');
        $oldPrimaryThread = xh_option('primaryThread', false);
        $oldPrimaryThreadPage = xh_option('primaryThreadPage', false);
        $features = isset($params['features']) && is_array($params['features']) ? $params['features'] : [];
        $config = isset($params['config']) && is_array($params['config']) ? $params['config'] : [];
        $appId = isset($config['appId']) ? sanitize_text_field($config['appId']) : '';
        if (empty($appId) || strlen($appId) < 15 || strlen($appId) > 30) {
            return [
                'success' => false,
                'message' => __('Invalid AppID, please check your input', 'xhtheme-ai-toolbox')
            ];
        }
        $postTypeAutomation = [];
        if (isset($config['postTypeAutomation']) && is_array($config['postTypeAutomation'])) {
            $postTypeAutomation = $config['postTypeAutomation'];
            unset($config['postTypeAutomation']);
        }
        $featureConfigMap = [
            'summary' => 'summaryEnabled',
            'tags' => 'tagEnabled',
            'comments' => 'commentEnabled',
            'slug' => 'primarySlug',
            'category' => 'primaryCategory',
            'thread' => 'primaryThread',
            'image' => 'imageThumb',
        ];
        foreach ($featureConfigMap as $feature => $configKey) {
            $config[$configKey] = in_array($feature, $features);
        }
        $validated_settings = $this->validate_settings($config);

        // 如果未启用评论功能，强制关闭话题自动评论
        if (!in_array('comments', $features)) {
            $validated_settings['primaryThreadComment'] = false;
        }

        $existing_settings = get_option('xhtheme_ai_toolbox_settings', []);
        $settings = wp_parse_args($validated_settings, is_array($existing_settings) ? $existing_settings : []);
        update_option('xhtheme_ai_toolbox_settings', $settings);

        if (!empty($postTypeAutomation)) {
            $rules = [];
            $queueTasks = xh_active_post_types();
            $taskIdMapping = [
                'image' => 'aiimage'
            ];

            foreach ($postTypeAutomation as $postType => $postTypeConfig) {
                if (!isset($queueTasks[$postType])) {
                    continue;
                }
                $tasks = [];
                $publishOnStatuses = [];

                if (is_array($postTypeConfig)) {
                    if (isset($postTypeConfig['tasks']) && is_array($postTypeConfig['tasks'])) {
                        $tasks = $postTypeConfig['tasks'];
                        $publishOnStatuses = isset($postTypeConfig['publishOnStatuses']) && is_array($postTypeConfig['publishOnStatuses'])
                            ? $postTypeConfig['publishOnStatuses']
                            : [];
                    } else {
                        $tasks = $postTypeConfig;
                    }
                }

                if (empty($tasks)) {
                    continue;
                }

                $typeData = $queueTasks[$postType];
                $validTasks = array_filter($tasks, function ($task) use ($typeData, $features, $taskIdMapping) {
                    $backendTaskId = isset($taskIdMapping[$task]) ? $taskIdMapping[$task] : $task;
                    return isset($typeData['tasks'])
                        && in_array($backendTaskId, $typeData['tasks'])
                        && in_array($task, $features);
                });

                if (!empty($validTasks)) {
                    $tasksObject = [];
                    foreach ($validTasks as $task) {
                        $backendTaskId = isset($taskIdMapping[$task]) ? $taskIdMapping[$task] : $task;
                        $tasksObject[sanitize_text_field($backendTaskId)] = [
                            'enabled' => true,
                            'categories' => ['type' => 'all', 'list' => []]
                        ];
                    }

                    $validStatuses = ['pending', 'private'];
                    $sanitizedStatuses = array_filter(
                        array_map('sanitize_text_field', $publishOnStatuses),
                        function ($status) use ($validStatuses) {
                            return in_array($status, $validStatuses);
                        }
                    );

                    $rules[] = [
                        'id' => $postType . '_' . time(),
                        'name' => $typeData['name'] ?? $postType,
                        'postType' => sanitize_text_field($postType),
                        'enabled' => true,
                        'defaultTrigger' => 'auto',
                        'publishOnStatuses' => array_values($sanitizedStatuses),
                        'tasks' => $tasksObject,
                        'createdAt' => current_time('Y-m-d H:i:s')
                    ];
                }
            }

            if (!empty($rules)) {
                update_option('xhtheme_ai_toolbox_automate_rules', wp_json_encode($rules));
            }
        }

        $newAppId = isset($settings['appId']) ? $settings['appId'] : '';
        $refresh = false;
        if ($oldAppId !== $newAppId) {
            $refresh = true;
            delete_transient('xhtheme_aitoolbox_users_error');
            delete_transient('xhtheme_aitoolbox_users');
            delete_option('xhtheme_aitoolbox_users');
            if ($newAppId) {
                delete_transient('xhtheme_aitoolbox_apicheck');
                XHThemeAi::getInstance()->fetchRemoteModelList(false);
            }
        }

        $newPrimaryThread = isset($settings['primaryThread']) ? $settings['primaryThread'] : false;
        if ($newPrimaryThread !== $oldPrimaryThread) {
            if (!empty($newPrimaryThread)) {
                if (get_option('xhtheme_ai_toolbox_thread_rewrite') !== 'pass') {
                    update_option('xhtheme_ai_toolbox_thread_rewrite', 'load');
                }
            } else {
                delete_option('xhtheme_ai_toolbox_thread_rewrite');
            }
        }

        $newPrimaryThreadPage = isset($settings['primaryThreadPage']) ? $settings['primaryThreadPage'] : false;
        if ($newPrimaryThreadPage !== $oldPrimaryThreadPage) {
            XHThread::getInstance()->toggle_thread_page($newPrimaryThreadPage);
        }

        return [
            'success' => true,
            'message' => __('Configuration saved successfully', 'xhtheme-ai-toolbox'),
            'refresh' => $refresh
        ];
    }

    /**
     * 插件停用反馈弹窗脚本
     * 仅在 plugins.php 页面加载
     */
    public function enqueue_deactivate_feedback($hook)
    {
        if ($hook !== 'plugins.php') {
            return;
        }

        $url = untrailingslashit(plugin_dir_url(dirname(__FILE__)));

        wp_enqueue_script(
            'xhtheme-deactivate-feedback',
            "{$url}/assets/js/deactivate-feedback.min.js",
            [],
            XHTHEME_AI_TOOLBOX_VERSION,
            true
        );

        wp_localize_script('xhtheme-deactivate-feedback', 'xhDeactivateFeedback', [
            'pluginSlug' => XHTHEME_AI_TOOLBOX_SLUG,
            'apiUrl' => xh_apiurl(),
            'apiToken' => xh_option('appId', ''),
            'pluginsVer' => XHTHEME_AI_TOOLBOX_VERSION,
            'wpVersion' => get_bloginfo('version'),
            'phpVersion' => PHP_VERSION,
            'reasons' => [
                'missing_feature' => __('Missing features I need', 'xhtheme-ai-toolbox'),
                'bug_or_error' => __('Found a bug or error', 'xhtheme-ai-toolbox'),
                'switch_plugin' => __('Switching to another plugin', 'xhtheme-ai-toolbox'),
                'temporary' => __('Temporary, will re-enable later', 'xhtheme-ai-toolbox'),
                'other' => __('Other', 'xhtheme-ai-toolbox')
            ],
            'feedbackPrompts' => [
                'missing_feature' => __('What feature do you need? 💡', 'xhtheme-ai-toolbox'),
                'missing_feature_placeholder' => __('Your ideas matter, share your suggestions...', 'xhtheme-ai-toolbox'),
                'bug_or_error' => __('What issue did you encounter? 🔧', 'xhtheme-ai-toolbox'),
                'bug_or_error_placeholder' => __('Describe the problem briefly...', 'xhtheme-ai-toolbox'),
                'switch_plugin' => __('What attracted you to switch?', 'xhtheme-ai-toolbox'),
                'switch_plugin_placeholder' => __('Your feedback helps us improve...', 'xhtheme-ai-toolbox'),
                'other' => __('Mind sharing more?', 'xhtheme-ai-toolbox'),
                'other_placeholder' => __('We are happy to listen...', 'xhtheme-ai-toolbox')
            ],
            'i18n' => [
                'title' => __('Leaving?', 'xhtheme-ai-toolbox'),
                'subtitle' => __('Your feedback helps us improve', 'xhtheme-ai-toolbox'),
                'feedbackLabel' => __('Feedback or suggestions (optional)', 'xhtheme-ai-toolbox'),
                'feedbackPlaceholder' => __('How can we improve...', 'xhtheme-ai-toolbox'),
                'submit' => __('Submit & Deactivate', 'xhtheme-ai-toolbox'),
                'skip' => __('Skip & Deactivate', 'xhtheme-ai-toolbox'),
                'footerHint' => __('We read every feedback carefully ❤️', 'xhtheme-ai-toolbox')
            ]
        ]);
    }

    /**
     * 获取支持评论的文章类型列表
     */
    private function get_commentable_post_types()
    {
        $post_types = get_post_types(['public' => true], 'objects');
        $commentable = [];

        foreach ($post_types as $post_type) {
            // 跳过附件类型
            if ($post_type->name === 'attachment') {
                continue;
            }

            // 检查是否支持评论
            if (post_type_supports($post_type->name, 'comments')) {
                $commentable[] = [
                    'value' => $post_type->name,
                    'label' => $post_type->labels->singular_name ?: $post_type->label
                ];
            }
        }

        // 确保 post 类型始终在列表中且排在第一位
        $has_post = false;
        foreach ($commentable as $type) {
            if ($type['value'] === 'post') {
                $has_post = true;
                break;
            }
        }

        if (!$has_post) {
            array_unshift($commentable, [
                'value' => 'post',
                'label' => __('Post', 'xhtheme-ai-toolbox')
            ]);
        } else {
            // 将 post 移到第一位
            usort($commentable, function ($a, $b) {
                if ($a['value'] === 'post') return -1;
                if ($b['value'] === 'post') return 1;
                return 0;
            });
        }

        return $commentable;
    }
}
