<?php

namespace XZD\AI\V5\UI;

use XZD\AI\V5\Core\Config;
use XZD\AI\V5\Theme\AdapterRegistry;
use XZD\AI\V5\Theme\Adapters\ZibllAdapter;

/**
 * 摘要前端渲染器 — 在文章页内容上方展示AI摘要卡片
 *
 * 16种展示风格 x 6种皮肤 x 2个标签上下位置 x 4个标签左右排列，支持自定义渐变。
 */
class SummaryRenderer
{
    private static ?self $instance = null;

    public static function instance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 注册展示钩子
     */
    public function init(): void
    {
        $adapter = AdapterRegistry::getCurrent();
        $isZibll = $adapter instanceof \XZD\AI\V5\Theme\Adapters\ZibllAdapter;

        if ($isZibll) {
            add_action('zib_posts_content_before', [$this, 'render']);
        } else {
            add_filter('the_content', [$this, 'renderBeforeContent'], 5);
        }
    }

    /**
     * 16种展示风格
     */
    public static function styles(): array
    {
        return [
            ''            => '默认风格',
            'glass'       => '毛玻璃',
            'neon'        => '霓虹边框',
            'minimal'     => '极简纸片',
            'terminal'    => '终端科技',
            'warm'        => '温暖亲和',
            'neumorph'    => '新拟态',
            'editorial'   => '杂志排版',
            'chat'        => '聊天气泡',
            'pixel'       => '像素复古',
            'sticky'      => '便签纸',
            'aurora'      => '渐变流光',
            'menghuan'    => '梦幻流光',
            'simple'      => '简约清新',
            'floating'    => '卡片悬浮',
            'simple-card' => '清爽卡片',
        ];
    }

    /**
     * 皮肤选项
     */
    public static function skins(): array
    {
        return [
            'default'      => '默认皮肤',
            'blue-yellow'  => '蓝黄渐变',
            'blue-pink'    => '蓝粉渐变',
            'green-blue'   => '绿蓝渐变',
            'orange-blue'  => '橙蓝渐变',
            'custom'       => '自定义渐变',
        ];
    }

    /**
     * 渲染摘要卡片（Zibll钩子直接输出）
     */
    public function render(): void
    {
        if (!$this->shouldDisplay()) {
            return;
        }

        $postId = get_the_ID();
        $summary = get_post_meta($postId, '_xzd_ai_summary', true);
        if (empty($summary)) {
            return;
        }

        $this->enqueueAssets();
        echo $this->buildCard($summary);
    }

    /**
     * 渲染到内容前（the_content filter，通用主题用）
     */
    public function renderBeforeContent(string $content): string
    {
        if (!$this->shouldDisplay()) {
            return $content;
        }

        $postId = get_the_ID();
        $summary = get_post_meta($postId, '_xzd_ai_summary', true);
        if (empty($summary)) {
            return $content;
        }

        $this->enqueueAssets();
        return $this->buildCard($summary) . $content;
    }

    private function shouldDisplay(): bool
    {
        if (!is_singular('post')) {
            return false;
        }

        $enabled = $this->cfg('enabled', 'summary_enabled', true);
        if (!$enabled) {
            return false;
        }

        $postId = get_the_ID();
        if (!$postId) {
            return false;
        }

        if (get_post_meta($postId, '_xzd_ai_summary_disabled', true)) {
            return false;
        }

        return true;
    }

    private function enqueueAssets(): void
    {
        $cssUrl = XZD_AI_URL . 'assets/standalone/summary.css';
        $jsUrl  = XZD_AI_URL . 'assets/standalone/summary.js';

        wp_enqueue_style('xzd-ai-summary', $cssUrl, [], XZD_AI_VERSION);

        $animation = $this->cfg('animation', 'summary_animation', false);
        if ($animation) {
            wp_enqueue_script('xzd-ai-summary', $jsUrl, [], XZD_AI_VERSION, true);
        }
    }

    private function buildCard(string $summary): string
    {
        $title   = $this->cfg('title', 'summary_title', 'AI智能摘要');
        $badge   = $this->cfg('badge', 'summary_badge', 'AI');
        $style   = $this->cfg('style', 'summary_style', '');
        $skin    = $this->cfg('skin', null, 'default');
        $anim    = $this->cfg('animation', 'summary_animation', false);
        $labelV  = $this->cfg('label_v_position', null, 'top');
        $labelH  = $this->cfg('label_h_position', null, 'space-between');

        // 构建CSS class
        $styleClass = empty($style) ? 'xzd-style-default' : 'xzd-style-' . esc_attr($style);
        $skinClass  = 'xzd-skin-' . esc_attr($skin);
        $vClass     = 'xzd-labels-v-' . esc_attr($labelV);
        $hClass     = 'xzd-labels-h-' . esc_attr($labelH);

        $classes = "post-XZDAI {$styleClass} {$skinClass} {$vClass} {$hClass}";

        $adapter = AdapterRegistry::getCurrent();
        $isZibll = $adapter instanceof ZibllAdapter;
        $fallbackAttr = $isZibll ? '' : ' data-xzd-fallback="1"';

        // 自定义皮肤 — 内联CSS变量
        $inlineStyle = '';
        if ($skin === 'custom') {
            $bgS  = $this->cfg('skin_custom_bg_start', null, '#e3f2fd');
            $bgE  = $this->cfg('skin_custom_bg_end', null, '#fff8e1');
            $bgSD = $this->cfg('skin_custom_bg_start_dark', null, '#1e3a5f');
            $bgED = $this->cfg('skin_custom_bg_end_dark', null, '#3d2914');

            $inlineStyle = ' style="'
                . '--xzd-skin-bg-start:' . esc_attr($bgS) . ';'
                . '--xzd-skin-bg-end:' . esc_attr($bgE) . ';'
                . '--xzd-skin-bg-start-dark:' . esc_attr($bgSD) . ';'
                . '--xzd-skin-bg-end-dark:' . esc_attr($bgED) . ';'
                . '"';
        }

        $summaryEsc = esc_attr($summary);

        $html = '<div class="' . $classes . '"' . $fallbackAttr . $inlineStyle . '>';

        // 风格特有装饰元素
        if ($style === 'terminal') {
            $html .= '<div class="xzd-st-bar"><span class="xzd-st-dot r"></span><span class="xzd-st-dot y"></span><span class="xzd-st-dot g"></span><span class="xzd-st-title">AI Summary</span></div>';
        }
        if ($style === 'sticky') {
            $html .= '<div class="xzd-ss-pin"></div>';
        }
        if ($style === 'editorial') {
            $html .= '<div class="xzd-se-header"><span class="xzd-se-label">AI</span><span class="xzd-se-line"></span></div>';
        }

        // 统一标签栏
        $html .= '<div class="XZDAI-labels">';
        $html .= '<span class="XZDAI-label-text">' . esc_html($title) . '</span>';
        $html .= '<span class="XZDAI-label-divider">·</span>';
        $html .= '<span class="XZDAI-label-badge">' . esc_html($badge) . '</span>';
        $html .= '</div>';

        // 摘要内容
        $html .= '<div class="XZDAI-explanation"';
        if ($anim) {
            $html .= ' data-summary="' . $summaryEsc . '"';
        }
        $html .= '>';
        if (!$anim) {
            $html .= esc_html($summary);
        }
        if ($anim) {
            $html .= '<span class="blinking-cursor"></span>';
        }
        $html .= '</div>';

        // 渐变流光shimmer
        if ($style === 'aurora') {
            $html .= '<div class="xzd-sa-shimmer"></div>';
        }

        $html .= '</div>';

        return $html;
    }

    /**
     * 获取摘要配置 — 新键优先，回退旧键
     */
    private function cfg(string $newKey, ?string $oldKey = null, mixed $default = null): mixed
    {
        $cfg = Config::instance();
        $val = $cfg->get("summary.{$newKey}");
        if ($val !== null) return $val;
        if ($oldKey !== null) {
            return $cfg->get($oldKey, $default);
        }
        return $default;
    }
}
