<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ $pdfMeta['exam_pdf_title'] ?? ($paper->paper_name ?? '试卷预览') }}</title>
    <link rel="stylesheet" href="/css/katex/katex.min.css">
    @php
        $examCode = $pdfMeta['exam_code'] ?? ($paper->paper_id ?? 'unknown');
        $studentName = $pdfMeta['student_name'] ?? ($student['name'] ?? ($paper->student_id ?? '________'));
        $paperHeaderTitle = $pdfMeta['header_title'] ?? ($studentName . '｜' . $examCode . '｜未知类型');
        // 生成时间（格式：2026年01月30日 15:04:05）
        $generateDateTime = now()->format('Y年m月d日 H:i:s');
    @endphp
    <style>
        @page {
            size: A4;
            margin: 2.2cm 2cm 2.3cm 2cm;
            @top-left {
                content: "知了数学·{{ $generateDateTime }}";
                font-size: 13px;
                color: #666;
            }
            @top-center {
                content: "{{ $studentName }}";
                font-size: 13px;
                color: #666;
            }
            @top-right {
                content: "{{ $examCode }}";
                font-size: 19px;
                font-weight: 600;
                font-family: "Noto Sans", "Liberation Sans", "Nimbus Sans", sans-serif;
                letter-spacing: 0;
                padding-right: 3mm;
                padding-top: 1.8mm;
                color: #222;
            }
            @bottom-left {
                content: "{{ $paperHeaderTitle }}";
                font-size: 11px;
                color: #666;
            }
            @bottom-right {
                content: counter(page) "/" counter(pages);
                font-size: 13px;
                color: #666;
            }
        }
        :root {
            --question-gap: 6px;
        }
        body {
            font-family: "Noto Serif", "Noto Serif CJK SC", "Noto Sans CJK SC", "Noto Sans", "STSongti-SC", "PingFang SC", "Songti SC", serif;
            line-height: 1.65;
            color: #000;
            background: #fff;
            font-size: 14px;
        }
        .page {
            max-width: 720px;
            margin: 0 auto;
            padding: 0 12px;
        }
        .header {
            text-align: center;
            margin-bottom: 2rem;
            border-bottom: 2px solid #000;
            padding-bottom: 1rem;
        }
        .school-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .paper-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-bottom: 5px;
        }
        .seal-line {
            position: absolute;
            left: -1.5cm;
            top: 0;
            bottom: 0;
            width: 1cm;
            border-right: 1px dashed #999;
            writing-mode: vertical-rl;
            text-align: center;
            font-size: 12px;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        @include('pdf.partials.paper-body-core-styles')
        .grading-boxes { gap: 4px; flex-wrap: wrap; align-items: center; }
        .grading-boxes span { vertical-align: middle; }
        .question-main { font-size: 14px; line-height: 1.65; font-family: inherit; display: block; }
        .question-score { margin-right: 6px; font-weight: 600; }
        .question-score-inline {
            display: block;
            font-size: 13px;
            color: #555;
            margin: 0 0 2px 0;
            white-space: nowrap;
        }
        /* 题目内容：防止孤行 */
        .question-stem {
            display: block;
            font-size: 14px;
            font-family: inherit;
            orphans: 3;
            widows: 3;
        }
        .question-content {
            font-size: 14px;
            margin-bottom: 8px;
            line-height: 1.6;
            orphans: 3;
            widows: 3;
        }
        .question-main {
            orphans: 3;
            widows: 3;
        }
        .parallel {
            font-family: "NotoSansMonoCJKjp", monospace;
            letter-spacing: 1px;
        }
        /* 选项容器：不分页 */
        .options {
            display: grid;
            row-gap: 8px;
            margin-top: 8px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .options-grid-4 {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 8px 12px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .options-grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px 20px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .options-grid-1 {
            display: grid;
            grid-template-columns: 1fr;
            gap: 8px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        /* 单个选项：不分页 */
        .option {
            width: 100%;
            font-size: 13.2px;
            line-height: 1.6;
            word-wrap: break-word;
            display: flex;
            align-items: baseline;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .option strong { margin-right: 4px; flex: 0 0 auto; line-height: 1.6; }
        .option-value { display: inline; }
        .option-short { white-space: nowrap; }
        .option-long { white-space: normal; word-break: break-word; }
        .option-inline { display: inline-flex; align-items: baseline; margin-right: 20px; }
        .option-compact { line-height: inherit; }
        .option p, .option div { margin: 0; display: inline; }
        .option .katex {
            font-size: 1em !important;
            vertical-align: 0;
        }
        /* 仅提升分式可读性（不放大整行选项） */
        .option .katex .mfrac {
            font-size: 1em !important;
        }
        /* 选项里的分子分母保持可读且不挤压横线 */
        .option .katex .mfrac .mtight {
            font-size: 1em !important;
        }
        /* 分数线稍加粗 */
        .option .katex .frac-line {
            border-bottom-width: 0.055em !important;
        }
        /* 自动化实测后的分式微调：分母下移、分子上移，避免贴线 */
        .option .katex .mfrac .vlist > span:nth-child(1) {
            transform: translateY(0.24em) !important;
        }
        .option .katex .mfrac .vlist > span:nth-child(3) {
            transform: translateY(-0.16em) !important;
        }
        .option .katex-display {
            display: inline;
            margin: 0 !important;
            vertical-align: baseline;
        }
        /* 答案元信息：不分页 */
        .answer-meta {
            font-size: 12px;
            color: #2f2f2f;
            line-height: 1.75;
            margin-top: 4px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .answer-line + .answer-line { margin-top: 4px; }
        .solution-step {
            align-items: center;
            gap: 6px;
        }
        .step-box { display: inline-block; }
        .step-label { white-space: nowrap; }
        .solution-heading { font-weight: 700; }
        .solution-content { display: inline-block; line-height: 1.75; }
        /* 解析区域：不分页 */
        .solution-section {
            margin-top: 8px;
            padding: 6px 8px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .solution-section strong {
            font-size: 13px;
        }
        .solution-parsed {
            margin-top: 6px;
            line-height: 1.8;
        }
        .fill-line {
            display: inline-block;
            border-bottom: 1px solid #000;
            width: 100px;
            text-align: center;
        }
        .answer-space {
            height: 150px; /* 解答题留白 */
            border: 1px dashed #eee;
            margin-top: 10px;
        }
        /* 答案区域：不分页 */
        .answer-area {
            position: relative;
            margin-top: 12px;
            page-break-inside: avoid;
            break-inside: avoid;
        }
        .answer-area .answer-label {
            position: absolute;
            top: -10px;
            left: 10px;
            font-size: 10px;
            background: #fff;
            padding: 0 4px;
            color: #555;
            letter-spacing: 1px;
        }
        .answer-area.wavy {
            height: 28px;
            border-bottom: 1.5px dashed #555;
            background-image: repeating-linear-gradient(
                -45deg,
                rgba(0, 0, 0, 0.35),
                rgba(0, 0, 0, 0.35) 4px,
                transparent 4px,
                transparent 8px
            );
            background-size: 16px 16px;
            background-repeat: repeat-x;
            background-position: bottom;
        }
        .answer-area.boxy {
            min-height: 150px;
            border: 1.5px solid #444;
            border-radius: 6px;
            padding: 14px;
        }
        /* 让内嵌 SVG 按比例缩放展示 */
        svg, .math-render svg {
            max-width: 100%;
            height: auto;
            display: block;
            /* 确保SVG中的文字和图形元素正确对齐 */
            shape-rendering: geometricPrecision;
            text-rendering: geometricPrecision;
        }
        /* 优化SVG中文字标签的显示 */
        svg text {
            font-family: "Noto Serif", "Noto Serif CJK SC", "Noto Sans CJK SC", "Noto Sans", "STSongti-SC", "PingFang SC", "Songti SC", serif !important;
            font-size: 13px !important;
            font-weight: bold;
            font-style: normal;
            dominant-baseline: middle;
            text-anchor: middle;
            alignment-baseline: central;
            /* 确保文字在点的正中央 */
            paint-order: stroke fill;
            stroke: none;
            fill: #000;
        }
        /* SVG中点标签的精确对齐 */
        svg text.label-point {
            font-size: 14px;
            font-weight: bold;
            dx: 0;
            dy: 0;
        }
        /* 确保SVG中的圆形和线条正确渲染 */
        svg circle, svg line, svg polygon, svg polyline {
            shape-rendering: geometricPrecision;
        }
        .wavy-underline {
            display: inline-block;
            min-width: 80px;
            height: 22px;
            border-bottom: 1.2px dashed #444;
            vertical-align: middle;
        }
        .wavy-underline.short {
            min-width: 60px;
        }
        /* PDF图片容器：防止图片跨页分割 - 增强版 */
        .pdf-figure {
            break-inside: avoid;
            page-break-inside: avoid;
            -webkit-column-break-inside: avoid;
            break-before: avoid;
            break-after: avoid;
            page-break-before: avoid;
            page-break-after: avoid;
            margin: 8px 0;
            display: block;
            /* 确保图片不会在页面底部被截断 */
            min-height: 30px;
            /* 限制独立图块尺寸，避免图片压过题干 */
            max-height: 82mm;
        }
        .pdf-figure img {
            max-width: min(84%, 420px);
            max-height: 82mm;
            width: auto;
            height: auto;
            display: block;
            margin: 0 auto;
            object-fit: contain;
            box-sizing: border-box;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
            image-rendering: -webkit-optimize-contrast;
        }
        /* 题干中的图片样式（向后兼容） */
        .question-stem img,
        .question-main img,
        .question-content img,
        .answer-meta img,
        .answer-line img,
        .solution-content img,
        .solution-section img,
        .solution-parsed img {
            display: block;
            max-width: 220px;
            max-height: 60mm;
            width: auto;
            height: auto;
            margin: 6px auto;
            box-sizing: border-box;
            object-fit: contain;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
            image-rendering: -webkit-optimize-contrast;
        }
        /* 选项中的图片样式 - 防止超出容器 */
        .option img {
            max-width: 92%;
            max-height: 42mm;
            height: auto;
            object-fit: contain;
            vertical-align: middle;
        }
        @media print {
            .no-print {
                display: none;
            }
            body {
                -webkit-print-color-adjust: exact;
            }
        }
        .question-stem .katex,
        .question-main .katex,
        .question-content .katex {
            font-size: 1em !important;
            /* 避免题干/解析中的行内公式整体下沉 */
            vertical-align: 0;
        }
        .question-stem .katex-display,
        .question-main .katex-display,
        .question-content .katex-display {
            margin: 0.35em 0 !important;
        }
    </style>
</head>
<body>
    <div class="seal-line">
        装&nbsp;&nbsp;&nbsp;&nbsp;订&nbsp;&nbsp;&nbsp;&nbsp;线&nbsp;&nbsp;&nbsp;&nbsp;内&nbsp;&nbsp;&nbsp;&nbsp;不&nbsp;&nbsp;&nbsp;&nbsp;要&nbsp;&nbsp;&nbsp;&nbsp;答&nbsp;&nbsp;&nbsp;&nbsp;题
    </div>

    <div class="page">
    <div class="header">
        <div class="school-name">数学智能练习题</div>
        <div class="paper-title">{{ $examCode }}</div>
        <div class="info-row">
            <span>老师：{{ $teacher['name'] ?? '________' }}</span>
            <span>年级：@formatGrade($student['grade'] ?? '________')</span>
            @if(!empty($pdfMeta['assemble_type_label']) && $pdfMeta['assemble_type_label'] !== '未知类型')
                <span>类型：{{ $pdfMeta['assemble_type_label'] }}</span>
            @endif
            <span>姓名：{{ $student['name'] ?? '________' }}</span>
            <span>得分：________</span>
        </div>
    </div>

    @include('components.exam.paper-body', ['questions' => $questions])

    {{-- 参考答案（仅在开启时显示） --}}
    @if($includeAnswer)
        <div style="page-break-before: always; margin-top: 40px;">
            <div style="text-align: center; font-size: 22px; font-weight: bold; margin-bottom: 30px; border-bottom: 2px solid #000; padding-bottom: 10px;">
                参考答案
            </div>
            <div style="font-size: 14px; margin-bottom: 20px; text-align: center; color: #666;">
                {{ $paper->paper_name ?? '未命名试卷' }}
            </div>

            {{-- 选择题答案 --}}
            @if(count($questions['choice']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">一、选择题</div>
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; font-size: 14px;">
                        @foreach($questions['choice'] as $index => $q)
                            <div style="padding: 8px; background: #f5f5f5; border-radius: 4px;">
                                <span style="font-weight: bold;">{{ $index + 1 }}.</span>
                                @if(!empty($q->answer))
                                    <span style="margin-left: 8px; font-weight: bold; color: #d32f2f;">
                                        @php
                                            // 提取答案中的选项字母
                                            $answerText = $q->answer;
                                            $letter = '';
                                            if (preg_match('/([A-D])/i', $answerText, $match)) {
                                                $letter = strtoupper($match[1]);
                                            } elseif (preg_match('/答案[：:]\s*([A-D])/i', $answerText, $match)) {
                                                $letter = strtoupper($match[1]);
                                            }
                                            echo $letter ?: '（待补充）';
                                        @endphp
                                    </span>
                                @else
                                    <span style="margin-left: 8px; color: #999; font-style: italic;">（待补充）</span>
                                @endif
            </div>
        @endforeach
    </div>
    </div>
                </div>
            @endif

            {{-- 填空题答案 --}}
            @if(count($questions['fill']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">二、填空题</div>
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; font-size: 14px;">
                        @foreach($questions['fill'] as $index => $q)
                            <div style="padding: 8px; background: #f5f5f5; border-radius: 4px;">
                                <span style="font-weight: bold;">{{ count($questions['choice']) + $index + 1 }}.</span>
                                <span style="margin-left: 8px;">
                                    @if(!empty($q->answer))
                                        @math($q->answer)
                                    @else
                                        <span style="color: #999; font-style: italic;">（待补充）</span>
                                    @endif
                                </span>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif

            {{-- 解答题答案 --}}
            @if(count($questions['answer']) > 0)
                <div style="margin-bottom: 20px;">
                    <div style="font-weight: bold; font-size: 16px; margin-bottom: 15px;">三、解答题</div>
                    <div style="space-y: 15px;">
                        @foreach($questions['answer'] as $index => $q)
                            @php
                                $questionNumber = count($questions['choice']) + count($questions['fill']) + $index + 1;
                            @endphp
                            <div style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border-radius: 4px; border-left: 4px solid #4163ff;">
                                <div style="font-weight: bold; font-size: 15px; margin-bottom: 10px;">
                                    {{ $questionNumber }}. ({{ $q->score ?? 10 }}分)
                                </div>
                                @if(!empty($q->answer))
                                    <div style="font-size: 14px; line-height: 1.8;">
                                        @math($q->answer)
                                    </div>
                                @else
                                    <div style="font-size: 14px; color: #999; font-style: italic;">
                                        （答案待补充或请参考标准答案）
                                    </div>
                                @endif
                                @if(!empty($q->solution))
                                    <div style="margin-top: 10px; font-size: 13px; color: #666; padding-top: 10px; border-top: 1px dashed #ddd;">
                                        <strong>解析：</strong> @math($q->solution)
                                    </div>
                                @endif
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif
        </div>
    @endif



    <!-- KaTeX JavaScript 库 -->
    <script src="/js/katex.min.js"></script>
    <script src="/js/auto-render.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            console.log('试卷公式渲染器启动');

            // 配置 KaTeX 自动渲染
            function renderMath() {
                try {
                    renderMathInElement(document.body, {
                        delimiters: [
                            {left: '$$', right: '$$', display: true},
                            {left: '$', right: '$', display: false},
                            {left: '\\(', right: '\\)', display: false},
                            {left: '\\[', right: '\\]', display: true}
                        ],
                        throwOnError: false,
                        strict: false,
                        trust: true,
                        macros: {
                            "\\f": "#1f(#2)"
                        }
                    });
                    console.log('数学公式渲染完成');
                } catch (e) {
                    console.warn('公式渲染警告:', e);
                }
            }

            // 页面加载后渲染
            renderMath();

            // 如果页面是动态加载的，等待一段时间后再次渲染
            setTimeout(renderMath, 500);
            setTimeout(renderMath, 1000);

            // 添加到全局，必要时手动调用
            window.renderExamMath = renderMath;
        });
    </script>
</body>
</html>
