<?php

namespace HaoZiTeam\AIPost\Service\Settings\Traits;

defined('ABSPATH') || exit;

trait TraitFontTools
{
    /**
     * 在设置页底部渲染“配图方式二字体工具”的按钮与事件逻辑。
     * 说明：保持与后端 AJAX 接口兼容（aipost_upload_font / aipost_check_font_status / aipost_download_default_font_now）。
     */
    public function render_font_tools_inline(): void
    {
        if (!isset($_GET['page']) || $_GET['page'] !== 'ai-post') { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }
        $nonce = \wp_create_nonce('aipost_upload_font');
        ?>
        <script>
        (function($){
            $(function(){
                function findFontSelect(){
                    var $sel = $(
                        "select[name*='[font-selection]'],"+
                        "select[name*='font-selection'],"+
                        "[data-depend-id='font-selection'] select"
                    );
                    $sel = $sel.filter(':visible').first();
                    return $sel.length ? $sel : $();
                }

                function ensureInjected($select){
                    if (!$('#aipost_upload_font_btn').length && $select && $select.length){
                        var $wrap = $select.closest('tr, .csf-field, .form-table');
                        if ($wrap.length === 0) { $wrap = $select.parent(); }
                        var html = '\n<div class="aipost-font-upload" style="margin-top:8px;display:flex;gap:8px;align-items:center;flex-wrap:wrap;">' +
                           '  <input type="file" id="aipost_font_file" accept=".ttf,.otf,.ttc" style="display:none" />' +
                           '  <button type="button" class="button" id="aipost_check_font_btn">检测/刷新字体</button>' +
                           '  <button type="button" class="button" id="aipost_upload_font_btn">上传字体文件</button>' +
                           '  <button type="button" class="button button-primary" id="aipost_download_font_btn">下载默认字体</button>' +
                           '  <span id="aipost_upload_font_tip" style="margin-left:8px;color:#666;"></span>' +
                           '</div>';
                        $wrap.append(html);

                        var pollTimer = null;
                        function setTip(msg, color){
                            $('#aipost_upload_font_tip').css('color', color || '#666').text(msg || '');
                        }
                        function stopPoll(){ if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }
                        function checkStatus(){
                            $.post(ajaxurl, {action:'aipost_check_font_status', _wpnonce:'<?php echo esc_js($nonce); ?>'}, function(resp){
                                if (!resp || !resp.success) return;
                                var d = resp.data || {};
                                if (d.exists) {
                                    setTip('已检测到字体：'+(d.file||'WeiRuanYaHei.ttf')+'，已自动选中', '#2271b1');
                                    if (d.file) {
                                        if ($select.find('option[value="'+d.file+'"]').length === 0) {
                                            $select.append('<option value="'+d.file+'">'+d.file+'</option>');
                                        }
                                        $select.val(d.file).trigger('change');
                                    }
                                    stopPoll();
                                } else if (d.downloading) {
                                    setTip('默认字体正在下载中，请稍候…', '#d9831f');
                                } else {
                                    setTip('未检测到字体文件，可上传或点击“立即下载默认字体”', '#aa0000');
                                }
                            });
                        }
                        checkStatus();

                        $(document).on('click', '#aipost_upload_font_btn', function(){
                            $('#aipost_font_file').trigger('click');
                        });
                        $(document).on('change', '#aipost_font_file', function(){
                            var file = this.files && this.files[0];
                            if (!file) return;
                            var formData = new FormData();
                            formData.append('action', 'aipost_upload_font');
                            formData.append('_wpnonce', '<?php echo esc_js($nonce); ?>');
                            formData.append('font_file', file);
                            $('#aipost_upload_font_btn').prop('disabled', true);
                            $('#aipost_upload_font_tip').text('上传中...');
                            $.ajax({
                                url: ajaxurl,
                                method: 'POST',
                                data: formData,
                                processData: false,
                                contentType: false
                            }).done(function(resp){
                                if (resp && resp.success) {
                                    $('#aipost_upload_font_tip').css('color','#2271b1').text('上传成功：' + (resp.data && resp.data.file || ''));
                                    var fname = resp.data && resp.data.file ? resp.data.file : '';
                                    if (fname) {
                                        if ($select.find('option[value="'+fname+'"]').length === 0) {
                                            $select.append('<option value="'+fname+'">'+fname+'</option>');
                                        }
                                        $select.val(fname).trigger('change');
                                    }
                                } else {
                                    var msg = (resp && resp.data && resp.data.message) ? resp.data.message : '上传失败';
                                    $('#aipost_upload_font_tip').css('color','#d63638').text(msg);
                                }
                            }).fail(function(){
                                $('#aipost_upload_font_tip').css('color','#d63638').text('网络错误，上传失败');
                            }).always(function(){
                                $('#aipost_upload_font_btn').prop('disabled', false);
                                checkStatus();
                            });
                        });

                        $(document).on('click', '#aipost_check_font_btn', function(){
                            setTip('正在检测字体…');
                            checkStatus();
                        });

                        $(document).on('click', '#aipost_download_font_btn', function(){
                            $('#aipost_download_font_btn').prop('disabled', true);
                            setTip('开始下载默认字体…', '#2271b1');
                            $.post(ajaxurl, {action:'aipost_download_default_font_now', _wpnonce:'<?php echo esc_js($nonce); ?>'}, function(resp){
                                if (resp && resp.success) {
                                    setTip(resp.data && resp.data.message ? resp.data.message : '已触发下载，正在检测…', '#2271b1');
                                    stopPoll();
                                    pollTimer = setInterval(checkStatus, 2000);
                                } else {
                                    setTip('下载触发失败：' + (resp && resp.data && resp.data.message ? resp.data.message : '未知错误'), '#d63638');
                                }
                            }).always(function(){
                                $('#aipost_download_font_btn').prop('disabled', false);
                            });
                        });
                        return true;
                    }
                    return false;
                }

                function bootstrapInject(){
                    var $sel = findFontSelect();
                    if ($sel.length){ return ensureInjected($sel); }
                    return false;
                }

                if (!bootstrapInject()){
                    var retries = 0;
                    var intv = setInterval(function(){
                        if (bootstrapInject() || ++retries > 120){ clearInterval(intv); }
                    }, 500);
                    try {
                        var mo = new MutationObserver(function(){ bootstrapInject(); });
                        mo.observe(document.body, {childList:true, subtree:true});
                        setTimeout(function(){ try{ mo.disconnect(); }catch(e){} }, 60000);
                    } catch(e){}
                    $(document).on('click focusin mouseenter', function(){ bootstrapInject(); });
                }
            });
        })(jQuery);
        </script>
        <?php
    }
}
