<?php
/**
 * PufferGo 主题样式桥接层
 *
 * 职责：
 *   1. 读取 Node.js 预编译的 CSS 变量并注入前台/编辑器
 *   2. 让 WP 主题 header/footer 也跟随 PufferGo 设计系统（主题变量覆盖）
 *   3. 注入 Google Fonts
 *   4. 提供 Tailwind theme config 给编译 API
 *
 * PHP 不做任何颜色计算，所有色板由 Node.js 后端生成。
 *
 * @package PufferGo_Core
 * @since 3.0.0
 */

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

class PufferGo_Theme_Bridge {

    const STYLE_HANDLE = 'puffergo';

    // 主题常量
    const THEME_KADENCE = 'kadence';
    const THEME_FSE     = 'fse';
    const THEME_GENERIC = 'generic';

    /**
     * Google Fonts 白名单：key = CSS font-family 名称，value = Google Fonts URL family 参数
     * 与 JS 端 useDesignSystem.js 中的 GOOGLE_FONTS_MAP 以及 Node.js 端保持同步。
     */
    const GOOGLE_FONTS_MAP = array(
        'Inter'              => 'Inter:wght@300;400;500;600;700',
        'Roboto'             => 'Roboto:wght@300;400;500;700',
        'Poppins'            => 'Poppins:wght@300;400;500;600;700',
        'Lato'               => 'Lato:wght@300;400;700',
        'Montserrat'         => 'Montserrat:wght@300;400;500;600;700',
        'Open Sans'          => 'Open+Sans:wght@300;400;600;700',
        'Nunito'             => 'Nunito:wght@300;400;600;700',
        'Source Sans 3'      => 'Source+Sans+3:wght@300;400;600;700',
        'Playfair Display'   => 'Playfair+Display:wght@400;500;600;700',
        'Merriweather'       => 'Merriweather:wght@300;400;700',
        'Lora'               => 'Lora:wght@400;500;600;700',
        'Cormorant Garamond' => 'Cormorant+Garamond:wght@300;400;500;600',
        'DM Sans'            => 'DM+Sans:wght@300;400;500;600;700',
        'Outfit'             => 'Outfit:wght@300;400;500;600;700',
        'Plus Jakarta Sans'  => 'Plus+Jakarta+Sans:wght@300;400;500;600;700',
        'Noto Sans SC'       => 'Noto+Sans+SC:wght@300;400;500;700',
        'Noto Serif SC'      => 'Noto+Serif+SC:wght@300;400;500;700',
    );

    public function __construct() {
        // 1. 前台加载 (仅针对访客)
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_styles' ), 20 );
        
        // 2. 编辑器加载 (仅针对古腾堡后台)
        add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_editor_styles' ), 20 );

    }

    /**
     * 前台加载
     */
    public function enqueue_frontend_styles() {
        $this->load_core_styles();
    }

    /**
     * 编辑器加载
     */
    public function enqueue_editor_styles() {
        $this->load_core_styles();
        
        // 编辑器修正样式
        $editor_fix_css = "
            .editor-styles-wrapper {
                --pg-max-width: var(--global-content-width, 1200px);
            }
        ";
        wp_add_inline_style( self::STYLE_HANDLE, $editor_fix_css );
    }

    /**
     * 核心加载器
     */
    private function load_core_styles() {
        wp_enqueue_style(
            self::STYLE_HANDLE,
            plugins_url( 'assets/css/puffergo.css', PUFFERGO_PLUGIN_FILE ),
            array(),
            PUFFERGO_CORE_VERSION
        );

        $css_variables = $this->get_css_variables();
        $inline_css = ":root { {$css_variables} }";
        wp_add_inline_style( self::STYLE_HANDLE, $inline_css );

        // 如果 AI 设计系统中包含自定义字体，注入 Google Fonts
        if ( class_exists( 'PufferGo_Design_System' ) ) {
            $ai_tokens = PufferGo_Design_System::get_active_tokens();
            if ( $ai_tokens ) {
                $this->enqueue_google_fonts( $ai_tokens );
            }
        }
    }

    // ═══════════════════════════════════════════════════════════
    //  CSS Variable Output (reads compiledCss from Node.js)
    // ═══════════════════════════════════════════════════════════

    /**
     * 根据 tokens 中的字体名注入 Google Fonts link
     */
    private function enqueue_google_fonts( $tokens ) {
        $families_to_load = array();

        foreach ( array( 'fontHeading', 'fontBody' ) as $field ) {
            $font_name = isset( $tokens[ $field ] ) ? trim( $tokens[ $field ] ) : '';
            if ( ! empty( $font_name ) && isset( self::GOOGLE_FONTS_MAP[ $font_name ] ) ) {
                $families_to_load[] = self::GOOGLE_FONTS_MAP[ $font_name ];
            }
        }

        $families_to_load = array_unique( $families_to_load );
        if ( empty( $families_to_load ) ) return;

        $query = implode( '&family=', $families_to_load );
        $url   = 'https://fonts.googleapis.com/css2?family=' . $query . '&display=swap';

        wp_enqueue_style( 'puffergo-google-fonts', esc_url( $url ), array(), PUFFERGO_CORE_VERSION );
    }

    public function detect_theme_type() {
        $theme = wp_get_theme();
        if ( stripos( $theme->get('Name'), 'kadence' ) !== false || stripos( $theme->get_template(), 'kadence' ) !== false ) {
            return self::THEME_KADENCE;
        }
        if ( file_exists( get_template_directory() . '/theme.json' ) ) {
            return self::THEME_FSE;
        }
        return self::THEME_GENERIC;
    }

    /**
     * 主入口：输出 CSS 变量块
     * 直接读取 Node.js 预编译的 compiledCss，PHP 不做任何颜色计算
     */
    public function get_css_variables() {
        $type      = $this->detect_theme_type();
        $overrides = $this->get_theme_variable_overrides( $type );

        if ( class_exists( 'PufferGo_Design_System' ) ) {
            $compiled = PufferGo_Design_System::get_compiled_css();
            if ( $compiled ) {
                return "\n    /* === PufferGo Design System (compiled by Node.js) === */\n    " . $compiled . "\n" . $overrides;
            }
        }

        // 无 AI 设计系统时仅输出主题变量覆盖（不输出残缺的色阶变量）
        return $overrides;
    }

    /**
     * 主题变量覆盖 (让 WP 主题 header/footer 也跟随 PufferGo 设计系统)
     */
    private function get_theme_variable_overrides( $theme_type ) {
        switch ( $theme_type ) {
            case self::THEME_KADENCE:
                return '
    --global-palette1: var(--pg-brand-600);
    --global-palette2: var(--pg-accent-600);
    --global-palette3: var(--pg-neutral-900);
    --global-palette4: var(--pg-neutral-600);
    --global-palette6: var(--pg-neutral-200);
    --global-palette8: var(--pg-neutral-100);
    --global-palette9: var(--pg-neutral-50);
    --global-button-border-radius: var(--pg-radius);
    ';
            case self::THEME_FSE:
                return '
    --wp--preset--color--primary: var(--pg-brand-600);
    --wp--preset--color--secondary: var(--pg-accent-600);
    --wp--preset--color--base: var(--pg-neutral-50);
    --wp--preset--color--background: var(--pg-neutral-50);
    --wp--preset--color--contrast: var(--pg-neutral-900);
    --wp--preset--color--foreground: var(--pg-neutral-900);
    ';
            default:
                return '';
        }
    }

    /**
     * Tailwind theme config — v3 palette system
     *
     * 每个色族 (brand / accent / neutral) 11 个色阶全部映射到 CSS 变量，
     * 支持 <alpha-value> 透明度修饰符。
     *
     * 用于: compile-tailwind API + tailwind.frontend.config.js
     */
    public function get_tailwind_theme_config() {
        $shades = array( '50','100','200','300','400','500','600','700','800','900','950' );
        $wrap   = function ( $prefix, $family ) use ( $shades ) {
            $result = array();
            foreach ( $shades as $s ) {
                $result[ $s ] = "color-mix(in srgb, var({$prefix}-{$family}-{$s}) calc(<alpha-value> * 100%), transparent)";
            }
            return $result;
        };

        return array(
            'colors' => array(
                'brand'   => $wrap( '--pg', 'brand' ),
                'accent'  => $wrap( '--pg', 'accent' ),
                'neutral' => $wrap( '--pg', 'neutral' ),
                // Semantic shortcuts (convenience)
                'primary' => 'color-mix(in srgb, var(--pg-brand-600) calc(<alpha-value> * 100%), transparent)',
                'secondary' => 'color-mix(in srgb, var(--pg-accent-600) calc(<alpha-value> * 100%), transparent)',
                'base'    => 'color-mix(in srgb, var(--pg-neutral-50) calc(<alpha-value> * 100%), transparent)',
                'surface' => 'color-mix(in srgb, var(--pg-neutral-100) calc(<alpha-value> * 100%), transparent)',
                'main'    => 'color-mix(in srgb, var(--pg-neutral-900) calc(<alpha-value> * 100%), transparent)',
                'muted'   => 'color-mix(in srgb, var(--pg-neutral-600) calc(<alpha-value> * 100%), transparent)',
                'line'    => 'color-mix(in srgb, var(--pg-neutral-200) calc(<alpha-value> * 100%), transparent)',
                'on-primary' => '#ffffff',
            ),
            'fontFamily' => array(
                'heading' => 'var(--pg-font-heading)',
                'body'    => 'var(--pg-font-body)',
            ),
            'borderRadius' => array(
                'theme' => 'var(--pg-radius)',
            ),
            'boxShadow' => array(
                'theme' => 'var(--pg-shadow)',
            ),
            'maxWidth' => array(
                'theme' => 'var(--pg-max-width)',
            ),
        );
    }

}

new PufferGo_Theme_Bridge();