@php
    $choiceQuestions = $questions['choice'] ?? [];
    $fillQuestions = $questions['fill'] ?? [];
    $answerQuestions = $questions['answer'] ?? [];
    $gradingMode = $grading ?? false;

    // 是否在题干后显示题目ID (Q000123)
    $showQuestionId = config('exam.show_question_id_in_pdf', false);
    // 是否在题号后显示题目难度（用于校验排序）
    $showQuestionDifficulty = config('exam.show_question_difficulty_in_pdf', false);
    // 判卷模式是否显示题目题干与选项，默认显示；可通过 EXAM_PDF_GRADING_SHOW_STEM 关闭
    $showGradingStem = config('exam.pdf_grading_show_stem', true);

    // 格式化题目ID为6位补0格式
    $formatQuestionId = function($id) {
        if (empty($id)) return '';
        return '(Q' . str_pad($id, 6, '0', STR_PAD_LEFT) . ')';
    };

    $formatDifficulty = function($difficulty) {
        if ($difficulty === null || $difficulty === '') return '';
        $value = (float) $difficulty;
        return sprintf('[%.2f]', $value);
    };

    // 【新增】动态计算大题号 - 根据有题目的题型分配序号
    $sectionNumbers = [
        'choice' => null,
        'fill' => null,
        'answer' => null
    ];
    $currentSectionNumber = 1;

    // 只给有题目的题型分配序号
    if (!empty($choiceQuestions)) {
        $sectionNumbers['choice'] = $currentSectionNumber++;
    }
    if (!empty($fillQuestions)) {
        $sectionNumbers['fill'] = $currentSectionNumber++;
    }
    if (!empty($answerQuestions)) {
        $sectionNumbers['answer'] = $currentSectionNumber++;
    }

    // 获取题型名称的辅助函数
    $getSectionTitle = function($type, $sectionNumber) {
        $typeNames = [
            'choice' => '选择题',
            'fill' => '填空题',
            'answer' => '解答题'
        ];
        // 将数字转换为中文数字
        $chineseNumbers = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
        $chineseNumber = $chineseNumbers[$sectionNumber] ?? (string)$sectionNumber;
        return $chineseNumber . '、' . $typeNames[$type];
    };

    // 检查是否有数学公式处理标记，避免重复处理
    $mathProcessed = false;
    // 检查所有题型中是否有任何题目包含 math_processed 标记
    foreach ([$choiceQuestions, $fillQuestions, $answerQuestions] as $questionType) {
        foreach ($questionType as $q) {
            if (isset($q->math_processed) && $q->math_processed) {
                $mathProcessed = true;
                break 2; // 找到标记就退出两层循环
            }
        }
    }

    $boxCounter = app(\App\Support\GradingMarkBoxCounter::class);
    $layoutDeciderService = app(\App\Support\OptionLayoutDecider::class);
    // 与判题卡共用同一计数规则，避免方框数量不一致
    $countBlanks = fn($text) => $boxCounter->countFillBlanks($text);

    $renderBoxes = function($num) {
        // 判卷方框放大 1.2 倍，保持单行布局
        if ($num == 2) {
            // 两个方框时，使用右对齐布局
            return '<div style="display:flex;justify-content:flex-end;gap:4px;">' .
                   str_repeat('<span style="display:inline-block;width:17px;height:17px;line-height:17px;border:1px solid #333;"></span>', $num) .
                   '</div>';
        }
        return str_repeat('<span style="display:inline-block;width:17px;height:17px;line-height:17px;border:1px solid #333;margin-right:4px;vertical-align:middle;"></span>', $num);
    };
@endphp

{{-- 【新增】步骤方框CSS样式 --}}
<style>
.solution-step {
    display: block;
    margin: 8px 0;
    padding: 4px 0;
}

.step-box {
    display: inline-block;
    margin-right: 8px;
    vertical-align: middle;
}

.step-label {
    white-space: normal;
    vertical-align: middle;
}

.solution-section {
    margin: 10px 0;
    padding: 8px;
    background-color: #f9f9f9;
}
</style>

<!-- 动态大题号 - 选择题 -->
@if($sectionNumbers['choice'] !== null)
<div class="section-title">{{ $getSectionTitle('choice', $sectionNumbers['choice']) }}
    @if(count($choiceQuestions) > 0)
        @php
            $choiceTotal = array_sum(array_map(fn($q) => $q->score ?? 5, $choiceQuestions));
        @endphp
        （本大题共 {{ count($choiceQuestions) }} 小题，共 {{ $choiceTotal }} 分）
    @else
        （本大题共 0 小题，共 0 分）
    @endif
</div>
@if(count($choiceQuestions) > 0)
    @foreach($choiceQuestions as $index => $q)
        @php
            // 【修复】使用question_number字段作为显示序号，确保全局序号一致性
            $questionNumber = $q->question_number ?? ($index + 1);
            $cleanContent = preg_replace('/^\d+[\.、]\s*/', '', $q->content);
            $cleanContent = trim($cleanContent);
            $options = $q->options ?? [];
            if (empty($options)) {
                // 【修复】选项标记必须在行首或空白后，避免误匹配 SVG 注释中的 BD:DC 等内容
                $pattern = '/(?:^|\s)([A-D])[\.、：．:]\s*(.+?)(?=(?:^|\s)[A-D][\.、：．:]|$)/su';
                if (preg_match_all($pattern, $cleanContent, $matches, PREG_SET_ORDER)) {
                    foreach ($matches as $match) {
                        $optionText = trim($match[2]);
                        if (!empty($optionText)) {
                            $options[] = $optionText;
                        }
                    }
                }
            }
            $stemLine = $cleanContent;
            if (!empty($options)) {
                // 【修复】只匹配行首或空白后的选项标记，避免误匹配 SVG 注释中的 BD:DC 等内容
                if (preg_match('/^(.+?)(?=(?:^|\s)[A-D][\.、：．:])/su', $cleanContent, $stemMatch)) {
                    $stemLine = trim($stemMatch[1]);
                }
            }
            // 将题干中的空括号/下划线替换为短波浪线；如无占位符，则在末尾追加短波浪线
            $blankSpan = '<span style="display:inline-block; min-width:80px; border-bottom:1.2px dashed #444; vertical-align:bottom;">&nbsp;</span>';
            // 【修复】扩展下划线转换规则，支持LaTeX格式和多种占位符
            $renderedStem = $stemLine;
            // 先处理LaTeX格式的underline命令
            $renderedStem = preg_replace('/\\\underline\{[^}]*\}/', $blankSpan, $renderedStem);
            $renderedStem = preg_replace('/\\\qquad+/', $blankSpan, $renderedStem);
            // 【修复】在处理填空占位符时，保护LaTeX公式不被破坏
            // 先标记LaTeX公式区域
            $latexPlaceholders = [];
            $counter = 0;
            $renderedStem = preg_replace_callback('/\$[^$]+\$/u', function($matches) use (&$latexPlaceholders, &$counter, $blankSpan) {
                $placeholder = '<<<LATEX_' . $counter . '>>>';
                $latexPlaceholders[$placeholder] = $matches[0];
                $counter++;
                return $placeholder;
            }, $renderedStem);

            // 现在处理普通占位符（不会破坏LaTeX公式）
            $renderedStem = preg_replace(['/（\s*）/u', '/\(\s*\)/', '/_{2,}/'], $blankSpan, $renderedStem);

            // 恢复LaTeX公式（并进行HTML实体编码防止被浏览器解析）
            foreach ($latexPlaceholders as $placeholder => $latexContent) {
                $encodedLatex = htmlspecialchars($latexContent, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $renderedStem = str_replace($placeholder, $encodedLatex, $renderedStem);
            }

            // 如果没有占位符，在末尾添加
            if ($renderedStem === $stemLine) {
                $renderedStem .= ' ' . $blankSpan;
            }
            $renderedStem = $mathProcessed ? $renderedStem : \App\Services\MathFormulaProcessor::processFormulas($renderedStem);
        @endphp
        <div class="question">
            <div class="question-grid">
                <div class="question-lead">
                    @if($gradingMode)
                        <span class="grading-boxes">{!! $renderBoxes(1) !!}</span>
                    @endif
                    <span class="question-number">{{ $gradingMode ? '题目 ' : '' }}{{ $questionNumber }}.</span>
                </div>
                @if(!$gradingMode || $showGradingStem)
                    <div class="question-main">
                        <span class="question-stem">{!! $renderedStem !!}</span>
                        @if($showQuestionId && !empty($q->id))
                            <span class="question-id" style="font-size:10px;color:#999;margin-left:4px;">{!! $formatQuestionId($q->id) !!}</span>
                            @if($showQuestionDifficulty)
                                <span style="font-size:10px;color:#999;margin-left:4px;white-space:nowrap;">{{ $formatDifficulty($q->difficulty ?? null) }}</span>
                            @endif
                        @endif
                    </div>
                @endif
                @if((!$gradingMode || $showGradingStem) && !empty($options))
                    @php
                        $layoutMeta = $layoutDeciderService->decide(
                            $options,
                            $gradingMode ? 'grading' : 'exam'
                        );
                        $optionsClass = $layoutMeta['class'];
                        $layoutDesc = $layoutMeta['layout'];

                        \Illuminate\Support\Facades\Log::debug('选择题布局决策', [
                            'question_number' => $questionNumber,
                            'context' => $gradingMode ? 'grading' : 'exam',
                            'opt_count' => $layoutMeta['opt_count'],
                            'max_length' => $layoutMeta['max_length'],
                            'has_complex_formula' => $layoutMeta['has_complex_formula'],
                            'selected_class' => $optionsClass,
                            'layout' => $layoutDesc
                        ]);
                    @endphp
                    <div class="question-lead spacer"></div>
                    <div class="{{ $optionsClass }}">
                        @foreach($options as $optIndex => $opt)
                            @php
                                // 兼容两种格式：数字索引 (0,1,2,3) 或字母键 (A,B,C,D)
                                if (is_numeric($optIndex)) {
                                    $label = chr(65 + (int)$optIndex);
                                } else {
                                    $label = strtoupper($optIndex);
                                }
                                // 【修复】根据是否已预处理决定处理方式
                                $normalizedOpt = (string) $opt;
                                // 选项内优先使用行内分式，避免 \dfrac 导致单个选项视觉突兀
                                $normalizedOpt = str_replace('\\dfrac', '\\frac', $normalizedOpt);
                                $normalizedOpt = str_replace('\\displaystyle', '', $normalizedOpt);
                                $normalizedOpt = $layoutDeciderService->normalizeCompactMathForDisplay($normalizedOpt);
                                // 清理来源HTML里可能携带的超大字号，避免单题选项异常放大
                                $normalizedOpt = preg_replace('/font-size\s*:[^;"]+;?/iu', '', $normalizedOpt);
                                $normalizedOpt = preg_replace('/line-height\s*:[^;"]+;?/iu', '', $normalizedOpt);
                                $normalizedOpt = preg_replace('/style\s*=\s*([\'"])\s*\1/iu', '', $normalizedOpt);

                                if ($mathProcessed) {
                                    // 已预处理：数据已包含处理好的 <img> 和公式，直接使用
                                    $renderedOpt = $normalizedOpt;
                                } else {
                                    // 未预处理：先转义保护，processFormulas() 内部会解码并处理
                                    $encodedOpt = htmlspecialchars($normalizedOpt, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                                    $renderedOpt = \App\Services\MathFormulaProcessor::processFormulas($encodedOpt);
                                }

                                // 细粒度控制：短选项（如 1/2、-1/3、x、-x）尽量单行展示，长选项允许换行
                                $rawOptText = html_entity_decode(strip_tags((string) $opt), ENT_QUOTES | ENT_HTML5, 'UTF-8');
                                $rawOptText = preg_replace('/\s+/u', '', $rawOptText ?? '');
                                $rawOptLen = mb_strlen((string) $rawOptText, 'UTF-8');
                                $isShortOption = $rawOptLen <= 8;
                            @endphp
                            <div class="option option-compact">
                                <strong>{{ $label }}.</strong>
                                <span class="option-value {{ $isShortOption ? 'option-short' : 'option-long' }}">{!! $renderedOpt !!}</span>
                            </div>
                        @endforeach
                    </div>
                @endif
                @if($gradingMode)
                    @php
                        $solutionText = trim($q->solution ?? '');
                        // 去掉前置的"解题思路"标签，避免出现"解题思路：【解题思路】"重复
                        $solutionText = preg_replace('/^【?\s*解题思路\s*】?\s*[:：]?\s*/u', '', $solutionText);
                        $solutionHtml = $solutionText === ''
                            ? '<span style="color:#999;font-style:italic;">（暂无解题思路）</span>'
                            : ($mathProcessed ? $solutionText : \App\Services\MathFormulaProcessor::processFormulas($solutionText));
                    @endphp
                    @if($showGradingStem)
                        <div class="question-lead spacer"></div>
                    @endif
                    <div class="answer-meta">
                        @php
                            $choiceAnswerRaw = $layoutDeciderService->normalizeCompactMathForDisplay((string) ($q->answer ?? ''));
                        @endphp
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! $mathProcessed ? $choiceAnswerRaw : \App\Services\MathFormulaProcessor::processFormulas($choiceAnswerRaw) !!}</span></div>
                        <div class="answer-line"><strong>解题思路：</strong><span class="solution-content">{!! $solutionHtml !!}</span></div>
                    </div>
                @endif
            </div>
        </div>
    @endforeach
@else
    <div class="question">
        <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
            该题型正在生成中或暂无题目，请稍后刷新页面查看
        </div>
    </div>
@endif
@endif

<!-- 动态大题号 - 填空题 -->
@if($sectionNumbers['fill'] !== null)
<div class="section-title">{{ $getSectionTitle('fill', $sectionNumbers['fill']) }}
    @if(count($fillQuestions) > 0)
        @php
            $fillTotal = array_sum(array_map(fn($q) => $q->score ?? 5, $fillQuestions));
        @endphp
        （本大题共 {{ count($fillQuestions) }} 小题，共 {{ $fillTotal }} 分）
    @else
        （本大题共 0 小题，共 0 分）
    @endif
</div>
@if(count($fillQuestions) > 0)
    @foreach($fillQuestions as $index => $q)
        @php
            // 【修复】使用question_number字段作为显示序号，确保全局序号一致性
            $questionNumber = $q->question_number ?? (count($choiceQuestions) + $index + 1);
            $blankSpan = '<span style="display:inline-block; min-width:80px; border-bottom:1.2px dashed #444; vertical-align:bottom;">&nbsp;</span>';
            // 【修复】扩展下划线转换规则，支持LaTeX格式和多种占位符
            $renderedContent = $q->content;
            // 【修复】在处理填空占位符时，保护LaTeX公式不被破坏
            // 先标记LaTeX公式区域（支持包含反斜杠和花括号的LaTeX命令）
            $latexPlaceholders = [];
            $counter = 0;
            $renderedContent = preg_replace_callback('/\$(?:[^\$]|\\.)*\$/u', function($matches) use (&$latexPlaceholders, &$counter, $blankSpan) {
                $placeholder = '<<<LATEX_FILL_' . $counter . '>>>';
                $latexPlaceholders[$placeholder] = $matches[0];
                $counter++;
                return $placeholder;
            }, $renderedContent);

            // 现在处理普通占位符（不会破坏LaTeX公式）
            $renderedContent = preg_replace(['/（\s*）/u', '/\(\s*\)/', '/_{2,}/'], $blankSpan, $renderedContent);

            // 恢复LaTeX公式（并进行HTML实体编码防止被浏览器解析）
            foreach ($latexPlaceholders as $placeholder => $latexContent) {
                $encodedLatex = htmlspecialchars($latexContent, ENT_QUOTES | ENT_HTML5, 'UTF-8');
                $renderedContent = str_replace($placeholder, $encodedLatex, $renderedContent);
            }

            // 如果没有占位符且内容没有变化，在末尾添加
            // 但要检查是否已经有填空占位符（如\underline{\qquad}）
            if ($renderedContent === $q->content && !preg_match('/\\\\underline|\\\\qquad|（\s*）|\(\s*\)/', $renderedContent)) {
                $renderedContent .= ' ' . $blankSpan;
            }
            $renderedContent = $mathProcessed ? $renderedContent : \App\Services\MathFormulaProcessor::processFormulas($renderedContent);
        @endphp
        <div class="question">
            <div class="question-grid">
                <div class="question-lead">
                    @if($gradingMode)
                        <span class="grading-boxes">{!! $renderBoxes($countBlanks($q->content ?? '')) !!}</span>
                    @endif
                    <span class="question-number">{{ $gradingMode ? '题目 ' : '' }}{{ $questionNumber }}.</span>
                </div>
                @if(!$gradingMode || $showGradingStem)
                    <div class="question-main">
                        <span class="question-stem">{!! $renderedContent !!}</span>
                        @if($showQuestionId && !empty($q->id))
                            <span class="question-id" style="font-size:10px;color:#999;margin-left:4px;">{!! $formatQuestionId($q->id) !!}</span>
                            @if($showQuestionDifficulty)
                                <span style="font-size:10px;color:#999;margin-left:4px;white-space:nowrap;">{{ $formatDifficulty($q->difficulty ?? null) }}</span>
                            @endif
                        @endif
                    </div>
                @endif
                @if($gradingMode)
                    @php
                        $solutionText = trim($q->solution ?? '');
                        // 去掉前置的"解题思路"标签，避免出现"解题思路：【解题思路】"重复
                        $solutionText = preg_replace('/^【?\s*解题思路\s*】?\s*[:：]?\s*/u', '', $solutionText);
                        $solutionHtml = $solutionText === ''
                            ? '<span style="color:#999;font-style:italic;">（暂无解题思路）</span>'
                            : ($mathProcessed ? $solutionText : \App\Services\MathFormulaProcessor::processFormulas($solutionText));
                    @endphp
                    @if($showGradingStem)
                        <div class="question-lead spacer"></div>
                    @endif
                    <div class="answer-meta">
                        @php
                            $fillAnswerRaw = $layoutDeciderService->normalizeCompactMathForDisplay((string) ($q->answer ?? ''));
                        @endphp
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! $mathProcessed ? $fillAnswerRaw : \App\Services\MathFormulaProcessor::processFormulas($fillAnswerRaw) !!}</span></div>
                        <div class="answer-line"><strong>解题思路：</strong><span class="solution-content">{!! $solutionHtml !!}</span></div>
                    </div>
                @endif
            </div>
        </div>
    @endforeach
@else
    <div class="question">
        <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
            该题型正在生成中或暂无题目，请稍后刷新页面查看
        </div>
    </div>
@endif
@endif

<!-- 动态大题号 - 解答题 -->
@if($sectionNumbers['answer'] !== null)
<div class="section-title">{{ $getSectionTitle('answer', $sectionNumbers['answer']) }}
    @if(count($answerQuestions) > 0)
        （本大题共 {{ count($answerQuestions) }} 小题，共 {{ array_sum(array_column($answerQuestions, 'score')) }} 分。解答应写出文字说明、证明过程或演算步骤）
    @else
        （本大题共 0 小题，共 0 分）
    @endif
</div>
@if(count($answerQuestions) > 0)
    @foreach($answerQuestions as $index => $q)
        @php
            // 【修复】使用question_number字段作为显示序号，确保全局序号一致性
            $questionNumber = $q->question_number ?? (count($choiceQuestions) + count($fillQuestions) + $index + 1);
            // 解答题小题排版优化（仅在小题编号语境下换行，避免误伤 f(1) 这类函数表达）
            $answerStem = (string) ($q->content ?? '');
            preg_match_all('/[（(][1-9][0-9]*[）)]/u', $answerStem, $subQuestionMatches);
            $subQuestionCount = count($subQuestionMatches[0] ?? []);
            // 前提：只有出现“至少两个小题编号（形成系列）”才做自动换行
            if ($subQuestionCount >= 2) {
                // 开头的 (1)/(2) 不额外插入换行，只做标准化空格
                $answerStem = preg_replace('/^\s*([（(][1-9][0-9]*[）)])\s*/u', '$1 ', $answerStem) ?? $answerStem;
                // 句读后接小题编号：断行
                $answerStem = preg_replace('/([。；;！？!?:：.])\s*([（(][1-9][0-9]*[）)])\s*/u', '$1<br>$2 ', $answerStem) ?? $answerStem;
                // 换行簇（实际换行、字面量\\n、已有<br>）后接小题编号：统一压成单个 <br>
                $answerStem = preg_replace('/(?:(?:\\\\r\\\\n|\\\\n)|(?:\r?\n)|(?:<br\s*\/?>)|\s)+\s*([（(][1-9][0-9]*[）)])\s*/u', '<br>$1 ', $answerStem) ?? $answerStem;
                // 关键词引导的小题也换行，如 “求(1)…(2)… / 写出（1）…”
                $answerStem = preg_replace('/(求出|求解|求|写出|计算|证明|判断|化简)\s*([（(][1-9][0-9]*[）)])\s*/u', '$1<br>$2 ', $answerStem) ?? $answerStem;
            }
            $answerStemRendered = $mathProcessed
                ? $answerStem
                : \App\Services\MathFormulaProcessor::processFormulas($answerStem);
        @endphp
        <div class="question">
            <div class="question-grid">
                <div class="question-lead">
                    <span class="question-number">{{ $gradingMode ? '题目 ' : '' }}{{ $questionNumber }}.</span>
                </div>
                @if(!$gradingMode || $showGradingStem)
                    <div class="question-main">
                        @unless($gradingMode)
                            <span class="question-score-inline">（本小题满分 {{ $q->score ?? 10 }} 分）
                                @if($showQuestionId && !empty($q->id))
                                    <span class="question-id" style="font-size:10px;color:#999;margin-left:4px;">{!! $formatQuestionId($q->id) !!}</span>
                                    @if($showQuestionDifficulty)
                                        <span style="font-size:10px;color:#999;margin-left:4px;white-space:nowrap;">{{ $formatDifficulty($q->difficulty ?? null) }}</span>
                                    @endif
                                @endif
                            </span>
                        @endunless
                        <span class="question-stem">{!! $answerStemRendered !!}</span>
                    </div>
                @endif
                @unless($gradingMode)
                    <div class="question-lead spacer"></div>
                    <div class="answer-area boxy">
                        <span class="answer-label">作答</span>
                    </div>
                @endunless
                @if($gradingMode)
                    @php
                        $solutionRaw = $q->solution ?? '';
                        $solutionProcessed = $mathProcessed ? $solutionRaw : \App\Services\MathFormulaProcessor::processFormulas($solutionRaw);
                        // 去掉分步得分等分值标记
                        $solutionProcessed = preg_replace('/（\s*\d+\s*分\s*）/u', '', $solutionProcessed);

                        // 【修复】优化解析分段格式 - 支持两种格式：
                        // 1. 【解题思路】格式
                        // 2. 解题过程：格式

                        // 先处理【】格式
                        $solutionProcessed = preg_replace('/【(解题思路|详细解答|最终答案)】/u', "\n\n===SECTION_START===\n【$1】\n===SECTION_END===\n\n", $solutionProcessed);

                        // 【扩展】处理多种"解题过程"格式，包括带括号的内容
                        $solutionProcessed = preg_replace('/(解题过程\s*[^：\n]*：)/u', "\n\n===SECTION_START===\n【解题过程】\n===SECTION_END===\n\n", $solutionProcessed);

                        // 按section分割内容
                        $sections = explode('===SECTION_START===', $solutionProcessed);
                        $processedSections = [];
                        $stepPattern = '(步骤\s*[0-9一二三四五六七八九十百零两]+\s*[：:]?|第\s*[0-9一二三四五六七八九十百零两]+\s*步\s*[：:]?)';

                        foreach ($sections as $section) {
                            if (empty(trim($section))) continue;

                            // 去掉结尾标记
                            $section = str_replace('===SECTION_END===', '', $section);

                            // 检查是否是解题相关部分
                            if (preg_match('/【(解题思路|详细解答|最终答案|解题过程)】/u', $section, $matches)) {
                                $sectionTitle = $matches[0];
                                $sectionContent = preg_replace('/【(解题思路|详细解答|最终答案|解题过程)】/u', '', $section);

                                // 【修复】处理步骤 - 在每个"步骤N"或"第N步"前添加方框
                                // 【优化】使用split分割步骤，为所有步骤添加方框（包括第一个）
                                if (preg_match('/' . $stepPattern . '/u', $sectionContent)) {
                                    // 使用前瞻断言分割，保留分隔符
                                    $allSteps = preg_split('/(?=' . $stepPattern . ')/u', $sectionContent, -1, PREG_SPLIT_NO_EMPTY);

                                    if (count($allSteps) > 0) {
                                        $processed = '';
                                        // 与判题卡计数规则一致：仅显式步骤前加方框；前置引导语不加方框
                                        for ($i = 0; $i < count($allSteps); $i++) {
                                            $stepText = trim($allSteps[$i]);
                                            if (!empty($stepText)) {
                                                $prefix = ($i > 0) ? '<br>' : '';
                                                $isStep = preg_match('/^' . $stepPattern . '/u', $stepText);
                                                if ($isStep) {
                                                    $processed .= $prefix . '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">' . $stepText . '</span></span>';
                                                } else {
                                                    $processed .= $prefix . '<span class="step-label">' . $stepText . '</span>';
                                                }
                                            }
                                        }
                                        $sectionContent = $processed;
                                    }
                                } else {
                                    // 没有明确步骤：在标题后添加一个方框作为开始
                                    $sectionContent = '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">&nbsp;</span></span> ' . trim($sectionContent);
                                }

                                // 包装section
                                $processedSections[] = '<div class="solution-section"><strong>' . $sectionTitle . '</strong><br>' . $sectionContent . '</div>';
                            } else {
                                // 非解题部分直接保留
                                $processedSections[] = $section;
                            }
                        }

                        // 重新组合所有部分
                        $solutionProcessed = implode('', $processedSections);

                        // 【新增】如果没有匹配到任何section标记，整个solution都没有方框，则默认加一个方框
                        if (empty($processedSections) || (count($processedSections) === 1 && !str_contains($processedSections[0] ?? '', 'step-box'))) {
                            // 检查是否有步骤关键词
                            if (preg_match('/' . $stepPattern . '/u', $solutionProcessed)) {
                                // 有步骤关键词：为每个步骤添加方框
                                $allSteps = preg_split('/(?=' . $stepPattern . ')/u', $solutionProcessed, -1, PREG_SPLIT_NO_EMPTY);
                                if (count($allSteps) > 0) {
                                    $processed = '';
                                    for ($i = 0; $i < count($allSteps); $i++) {
                                        $stepText = trim($allSteps[$i]);
                                        if (!empty($stepText)) {
                                            // 只有真正以"步骤"或"第X步"开头的部分才加方框
                                            // 第一个部分如果不是步骤开头（如【分析】），则不加方框
                                            $isStep = preg_match('/^' . $stepPattern . '/u', $stepText);
                                            $prefix = ($i > 0) ? '<br>' : '';
                                            if ($isStep) {
                                                $processed .= $prefix . '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">' . $stepText . '</span></span>';
                                            } else {
                                                // 非步骤的前缀文本，直接输出不加方框
                                                $processed .= $prefix . '<span class="step-label">' . $stepText . '</span>';
                                            }
                                        }
                                    }
                                    $solutionProcessed = $processed;
                                }
                            } else {
                                // 没有步骤关键词：默认在开头添加一个方框
                                $solutionProcessed = '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">' . trim($solutionProcessed) . '</span></span>';
                            }
                        }

                        // 将多余的换行转换为<br>，但保留合理的段落间距
                        $solutionProcessed = preg_replace('/\n{3,}/u', "\n\n", $solutionProcessed);
                        $solutionProcessed = nl2br($solutionProcessed);
                    @endphp
                    @if($showGradingStem)
                        <div class="question-lead spacer"></div>
                    @endif
                    <div class="answer-meta">
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! $mathProcessed ? ($q->answer ?? '') : \App\Services\MathFormulaProcessor::processFormulas($q->answer ?? '') !!}</span></div>
                        <div class="answer-line solution-parsed">{!! $solutionProcessed !!}</div>
                    </div>
                @endif
            </div>
        </div>
    @endforeach
@else
    <div class="question">
        <div class="question-content" style="font-style: italic; color: #999; padding: 20px; border: 1px dashed #ccc; background: #f9f9f9;">
            该题型正在生成中或暂无题目，请稍后刷新页面查看
        </div>
    </div>
@endif
@endif
