<?php

namespace XZD\AI\V5\Theme\Integrations;

/**
 * Zibll 前端投稿编辑器集成
 *
 * 在 Zibll 前端 pages/newposts.php 投稿表单中注入 AI 辅助按钮
 */
class ZibllFrontendEditorIntegration
{
    private static bool $assetsEnqueued = false;

    public static function register(): void
    {
        // 注入 AI 区域到前端投稿表单
        add_filter('zib_frontend_set_input_html', [self::class, 'injectAIButtons'], 10, 5);

        // 前端投稿提交后触发 AI 后处理
        add_action('new_add_posts', [self::class, 'onNewPost'], 10, 1);
        add_action('new_edit_posts', [self::class, 'onNewPost'], 10, 1);

        // 加载前端资源
        add_action('wp_enqueue_scripts', [self::class, 'enqueueAssets']);
    }

    public static function enqueueAssets(): void
    {
        if (self::$assetsEnqueued) return;

        // 仅在投稿页面加载
        if (!self::isEditorPage()) return;

        wp_enqueue_script(
            'xzd-frontend-editor-ai',
            XZD_AI_URL . 'assets/standalone/frontend-editor-ai.js',
            ['jquery'],
            XZD_AI_VERSION,
            true
        );

        wp_localize_script('xzd-frontend-editor-ai', 'xzdFrontendEditorConfig', [
            'restUrl'   => rest_url('xzdbk-ai/v1'),
            'restNonce' => wp_create_nonce('wp_rest'),
            'ajaxUrl'   => admin_url('admin-ajax.php'),
        ]);

        self::$assetsEnqueued = true;
    }

    /**
     * 注入 AI 按钮到前端投稿表单
     */
    public static function injectAIButtons($html, $postId, $type, $taxonomy, $postType): string
    {
        if (!self::isEditorPage()) return $html;

        $aiHtml = '<div class="xzd-frontend-ai-bar" style="margin:12px 0;padding:12px;background:var(--main-bg-color);border-radius:var(--main-radius);border:1px solid var(--main-border-color)">';
        $aiHtml .= '<div class="title-h-left mb10"><h5>🤖 AI写作助手</h5></div>';
        $aiHtml .= '<div class="flex ac" style="gap:8px;flex-wrap:wrap">';
        $aiHtml .= '<button type="button" class="but c-blue xzd-ai-btn" data-action="generate_title" style="font-size:12px"><i class="fa fa-pencil"></i> AI生成标题</button>';
        $aiHtml .= '<button type="button" class="but c-green xzd-ai-btn" data-action="generate_outline" style="font-size:12px"><i class="fa fa-list"></i> AI写大纲</button>';
        $aiHtml .= '<button type="button" class="but c-yellow xzd-ai-btn" data-action="polish" style="font-size:12px"><i class="fa fa-magic"></i> AI润色</button>';
        $aiHtml .= '<button type="button" class="but xzd-ai-btn" data-action="generate_tags" style="font-size:12px"><i class="fa fa-tags"></i> AI生成标签</button>';
        $aiHtml .= '</div>';
        $aiHtml .= '<div class="xzd-ai-result" style="display:none;margin-top:10px;padding:10px;background:var(--body-bg-color);border-radius:4px;font-size:13px;max-height:300px;overflow-y:auto"></div>';
        $aiHtml .= '</div>';

        return $html . $aiHtml;
    }

    /**
     * 新文章提交后触发 AI 后处理
     */
    public static function onNewPost($postObj): void
    {
        $postId = is_object($postObj) ? ($postObj->ID ?? 0) : (int) $postObj;
        if (!$postId) return;

        // 异步触发 AI 标签和摘要生成（通过后台计划任务）
        if (function_exists('wp_schedule_single_event')) {
            wp_schedule_single_event(time(), 'xzd_ai_process_frontend_post', [$postId]);
        }
    }

    private static function isEditorPage(): bool
    {
        global $wp_query;
        // Zibll 前端投稿页面通常包含 /newposts 或 /edit
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        return strpos($uri, 'newposts') !== false || strpos($uri, '/edit') !== false;
    }
}
