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

    // 计算填空空格数量
    $countBlanks = function($text) {
        $count = 0;
        $count += preg_match_all('/_{2,}/u', $text, $m);
        $count += preg_match_all('/（\s*）/u', $text, $m);
        $count += preg_match_all('/\(\s*\)/', $text, $m);
        return max(1, $count);
    };

    // 计算步骤数量
    $countSteps = function($text) {
        $matches = [];
        $cnt = preg_match_all('/第\s*\d+\s*步/u', $text ?? '', $matches);
        return max(1, $cnt);
    };

    $renderBoxes = function($num) {
        // 判卷方框放大 1.2 倍，保持单行布局
        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

<!-- 一、选择题 -->
<div class="section-title">一、选择题
    @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
            $questionNumber = $index + 1;
            $cleanContent = preg_replace('/^\d+[\.、]\s*/', '', $q->content);
            $cleanContent = trim($cleanContent);
            $options = $q->options ?? [];
            if (empty($options)) {
                $pattern = '/([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)) {
                if (preg_match('/^(.+?)(?=[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>';
            $renderedStem = preg_replace(['/(（\s*）)/u', '/\(\s*\)/', '/_{2,}/'], $blankSpan, $stemLine);
            if ($renderedStem === $stemLine) {
                $renderedStem .= ' ' . $blankSpan;
            }
            $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>
                <div class="question-main">
                    <span class="question-stem">{!! $renderedStem !!}</span>
                </div>
                @if(!empty($options))
                    @php
                        $optCount = count($options);
                        $optionsClass = $optCount <= 4 ? 'options-grid-2' : 'options';
                    @endphp
                    <div class="question-lead spacer"></div>
                    <div class="{{ $optionsClass }}">
                        @foreach($options as $optIndex => $opt)
                            @php $label = chr(65 + $optIndex); @endphp
                            <div class="option option-compact">
                                <strong>{{ $label }}.</strong>&nbsp;{!! \App\Services\MathFormulaProcessor::processFormulas($opt) !!}
                            </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>'
                            : \App\Services\MathFormulaProcessor::processFormulas($solutionText);
                    @endphp
                    <div class="question-lead spacer"></div>
                    <div class="answer-meta">
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! \App\Services\MathFormulaProcessor::processFormulas($q->answer ?? '') !!}</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

<!-- 二、填空题 -->
<div class="section-title">二、填空题
    @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
            $questionNumber = count($choiceQuestions) + $index + 1;
            $blankSpan = '<span style="display:inline-block; min-width:80px; border-bottom:1.2px dashed #444; vertical-align:bottom;">&nbsp;</span>';
            $renderedContent = preg_replace(['/(（\s*）)/u', '/\(\s*\)/', '/_{2,}/'], $blankSpan, $q->content);
            if ($renderedContent === $q->content) {
                $renderedContent .= ' ' . $blankSpan;
            }
            $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>
                <div class="question-main">
                    <span class="question-stem">{!! $renderedContent !!}</span>
                </div>
                @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>'
                            : \App\Services\MathFormulaProcessor::processFormulas($solutionText);
                    @endphp
                    <div class="question-lead spacer"></div>
                    <div class="answer-meta">
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! \App\Services\MathFormulaProcessor::processFormulas($q->answer ?? '') !!}</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

<!-- 三、解答题 -->
<div class="section-title">三、解答题
    @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
            $questionNumber = count($choiceQuestions) + count($fillQuestions) + $index + 1;
        @endphp
        <div class="question">
            <div class="question-grid">
                <div class="question-lead">
                    <span class="question-number">{{ $gradingMode ? '题目 ' : '' }}{{ $questionNumber }}.</span>
                </div>
                <div class="question-main">
                    @unless($gradingMode)
                        <span class="question-score-inline">（本小题满分 {{ $q->score ?? 10 }} 分）</span>
                    @endunless
                    <span class="question-stem">{!! \App\Services\MathFormulaProcessor::processFormulas($q->content) !!}</span>
                </div>
                @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 = \App\Services\MathFormulaProcessor::processFormulas($solutionRaw);
                        // 去掉分步得分等分值标记
                        $solutionProcessed = preg_replace('/（\s*\d+\s*分\s*）/u', '', $solutionProcessed);
                        // 断行处理：在【解题思路】【详细解答】【最终答案】前后加换行
                        $solutionProcessed = preg_replace('/【(解题思路|详细解答|最终答案)】/u', '<br><strong class="solution-heading">【$1】</strong><br>', $solutionProcessed);
                        // 为每个“第 N 步”前添加方框；若没有，则在【详细解答】段落开头添加一个方框
                        if (preg_match('/第\s*\d+\s*步/u', $solutionProcessed)) {
                            $solutionProcessed = preg_replace_callback('/第\s*\d+\s*步/u', function($m) use ($renderBoxes) {
                                return '<br><span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">' . $m[0] . '</span></span>';
                            }, $solutionProcessed);
                        } else {
                            // 在【详细解答】标题后追加方框；若无标题则在正文最前补一个
                            $injected = false;
                            $count = 0;
                            $solutionProcessed = preg_replace(
                                '/(<strong class="solution-heading">【详细解答】<\/strong><br>)/u',
                                '$1' . '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">&nbsp;</span></span> ',
                                $solutionProcessed,
                                1,
                                $count
                            );
                            if (!empty($count)) {
                                $injected = true;
                            }
                            if (!$injected) {
                                $solutionProcessed = '<span class="solution-step"><span class="step-box">' . $renderBoxes(1) . '</span><span class="step-label">&nbsp;</span></span> ' . ltrim($solutionProcessed);
                            }
                        }
                        // 最终统一换行渲染
                        $solutionProcessed = nl2br($solutionProcessed);
                    @endphp
                    <div class="question-lead spacer"></div>
                    <div class="answer-meta">
                        <div class="answer-line"><strong>正确答案：</strong><span class="solution-content">{!! \App\Services\MathFormulaProcessor::processFormulas($q->answer ?? '') !!}</span></div>
                        <div class="answer-line"><span class="solution-content">{!! $solutionProcessed !!}</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
