<x-filament::page>
    <div class="space-y-6">
        {{-- 试卷 JSON 输出案例 --}}
        <x-filament::section>
            <div class="text-base font-semibold text-slate-800">试卷 JSON 输出案例</div>
            <div class="mt-2 text-xs text-slate-500">输入卷子 ID，返回与智能出卷 API 中 `exam_content` 完全一致的 JSON，可预览或导出。</div>
            <div class="mt-4 space-y-3">
                <div class="flex flex-wrap items-center gap-3">
                    <input
                        id="paper-json-id"
                        type="text"
                        class="w-80 rounded-lg border border-slate-200 px-3 py-2 text-sm"
                        value="paper_1765788931_ce02f6a3"
                        placeholder="请输入 paper_id"
                    />
                    <button
                        type="button"
                        class="rounded-lg bg-primary-600 px-3 py-2 text-sm font-semibold text-white"
                        onclick="loadPaperJson()"
                    >
                        获取 JSON
                    </button>
                    <button
                        type="button"
                        class="rounded-lg border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700"
                        onclick="downloadPaperJson()"
                    >
                        导出 JSON
                    </button>
                </div>
                <pre id="paper-json-output" class="max-h-96 overflow-auto rounded-lg border border-slate-200 bg-slate-50 p-3 text-xs text-slate-700">等待输入 paper_id ...</pre>
            </div>
        </x-filament::section>

        {{-- API 文档列表 --}}
        @foreach ($apiGroups as $group)
            <x-filament::section>
                <div class="flex items-center justify-between">
                    <div class="text-base font-semibold text-slate-800">{{ $group['name'] }}</div>
                    <div class="text-xs text-slate-400">{{ count($group['items']) }} 个接口</div>
                </div>
                <div class="mt-2 text-xs text-slate-500">基于 Laravel 路由自动生成，配合详细文档说明</div>
                <div class="mt-4 space-y-4">
                    @foreach ($group['items'] as $item)
                        <details class="rounded-lg border border-slate-200 bg-white">
                            <summary class="flex cursor-pointer list-none flex-wrap items-center gap-3 p-4 hover:bg-slate-50">
                                <span class="rounded-md px-2 py-1 text-xs font-bold uppercase {{ $this->getMethodColor($item['method']) }}">
                                    {{ $item['method'] }}
                                </span>
                                <span class="font-mono text-sm text-slate-800">{{ $item['path'] }}</span>
                                @if (!empty($item['tag']))
                                    <span class="rounded-full border border-amber-200 bg-amber-50 px-2 py-0.5 text-xs font-semibold text-amber-700">
                                        {{ $item['tag'] }}
                                    </span>
                                @endif
                                <span class="ml-auto text-xs text-slate-400">点击展开详情</span>
                            </summary>

                            <div class="border-t border-slate-200 p-4 space-y-4">
                                {{-- 摘要和描述 --}}
                                @if (!empty($item['details']['summary']))
                                    <div>
                                        <div class="text-sm font-semibold text-slate-700">{{ $item['details']['summary'] }}</div>
                                        @if (!empty($item['details']['description']))
                                            <div class="mt-1 text-sm text-slate-600">{{ $item['details']['description'] }}</div>
                                        @endif
                                    </div>
                                @endif

                                {{-- 路由信息 --}}
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                                    @if (!empty($item['details']['route_name']))
                                        <div>
                                            <span class="font-semibold text-slate-700">路由名：</span>
                                            <span class="font-mono text-xs text-slate-600">{{ $item['details']['route_name'] }}</span>
                                        </div>
                                    @endif
                                    @if (!empty($item['details']['action']))
                                        <div>
                                            <span class="font-semibold text-slate-700">Action：</span>
                                            <span class="font-mono text-xs text-slate-600">{{ $item['details']['action'] }}</span>
                                        </div>
                                    @endif
                                </div>

                                {{-- 参数说明 --}}
                                @if (!empty($item['details']['param_details']))
                                    <div>
                                        <div class="mb-2 text-sm font-semibold text-slate-700">参数说明</div>
                                        <div class="space-y-3">
                                            @foreach ($item['details']['param_details'] as $paramGroup)
                                                <div>
                                                    @if (!empty($paramGroup[0]) && is_string($paramGroup[0]))
                                                        <div class="mb-1 text-xs font-semibold text-slate-600 uppercase">{{ $paramGroup[0] }}</div>
                                                        @php $params = array_slice($paramGroup, 1) @endphp
                                                    @else
                                                        @php $params = $paramGroup @endphp
                                                    @endif

                                                    <div class="overflow-x-auto">
                                                        <table class="min-w-full text-xs">
                                                            <thead>
                                                                <tr class="bg-slate-50">
                                                                    <th class="px-3 py-2 text-left font-semibold text-slate-600">名称</th>
                                                                    <th class="px-3 py-2 text-left font-semibold text-slate-600">类型</th>
                                                                    <th class="px-3 py-2 text-left font-semibold text-slate-600">必填</th>
                                                                    <th class="px-3 py-2 text-left font-semibold text-slate-600">默认值</th>
                                                                    <th class="px-3 py-2 text-left font-semibold text-slate-600">说明</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody class="divide-y divide-slate-200">
                                                                @foreach ($params as $param)
                                                                    <tr class="hover:bg-slate-50">
                                                                        <td class="px-3 py-2 font-mono text-slate-700">{{ $param['name'] }}</td>
                                                                        <td class="px-3 py-2 text-slate-600">{{ $param['type'] }}</td>
                                                                        <td class="px-3 py-2">
                                                                            @if ($param['required'])
                                                                                <span class="rounded bg-red-100 px-2 py-0.5 text-red-700">是</span>
                                                                            @else
                                                                                <span class="rounded bg-gray-100 px-2 py-0.5 text-gray-600">否</span>
                                                                            @endif
                                                                        </td>
                                                                        <td class="px-3 py-2 text-slate-600">{{ $param['default'] ?? '-' }}</td>
                                                                        <td class="px-3 py-2 text-slate-600">{{ $param['description'] }}</td>
                                                                    </tr>
                                                                @endforeach
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </div>
                                            @endforeach
                                        </div>
                                    </div>
                                @endif

                                {{-- 响应示例 --}}
                                @if (!empty($item['details']['response_examples']))
                                    <div>
                                        <div class="mb-2 text-sm font-semibold text-slate-700">响应示例</div>
                                        <div class="space-y-3">
                                            @foreach ($item['details']['response_examples'] as $responseType => $responseExample)
                                                <div>
                                                    <div class="mb-1 text-xs font-semibold text-slate-600 uppercase">{{ $responseType }}</div>
                                                    <pre class="rounded-lg bg-slate-900 p-3 text-xs text-slate-100 overflow-x-auto">{{ json_encode($responseExample, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</pre>
                                                </div>
                                            @endforeach
                                        </div>
                                    </div>
                                @endif

                                {{-- 使用示例 --}}
                                @if (!empty($item['details']['examples']))
                                    <div>
                                        <div class="mb-2 text-sm font-semibold text-slate-700">使用示例</div>
                                        <div class="space-y-1">
                                            @foreach ($item['details']['examples'] as $example)
                                                <div class="rounded bg-slate-50 px-3 py-2 font-mono text-xs text-slate-700">{{ $example }}</div>
                                            @endforeach
                                        </div>
                                    </div>
                                @endif

                                {{-- 在线测试按钮 --}}
                                @if ($item['doc'])
                                    <div class="pt-3 border-t border-slate-200">
                                        <button
                                            type="button"
                                            class="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700"
                                            onclick="toggleApiTest('{{ $item['uri'] }}', '{{ $item['method'] }}')"
                                        >
                                            在线测试
                                        </button>
                                    </div>

                                    {{-- 测试表单 --}}
                                    <div id="test-form-{{ $item['uri'] }}-{{ $item['method'] }}" class="mt-4 hidden rounded-lg border border-slate-200 bg-slate-50 p-4">
                                        <div class="mb-3 text-sm font-semibold text-slate-700">API 测试</div>
                                        <form onsubmit="testApi(event, '{{ $item['uri'] }}', '{{ $item['method'] }}')">
                                            @if (!empty($item['details']['param_details']))
                                                @foreach ($item['details']['param_details'] as $paramGroup)
                                                    @if (!empty($paramGroup[0]) && is_string($paramGroup[0]))
                                                        @php $params = array_slice($paramGroup, 1) @endphp
                                                    @else
                                                        @php $params = $paramGroup @endphp
                                                    @endif

                                                    @foreach ($params as $param)
                                                        @if ($paramGroup === $params && $paramGroup[0] === 'query' || (is_array($paramGroup[0]) && $paramGroup[0] === $params))
                                                            <div class="mb-3">
                                                                <label class="mb-1 block text-xs font-semibold text-slate-600">{{ $param['name'] }} ({{ $param['type'] }})</label>
                                                                @if ($param['required'])
                                                                    <input
                                                                        type="text"
                                                                        name="query_{{ $param['name'] }}"
                                                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                                                                        placeholder="{{ $param['description'] }}"
                                                                    />
                                                                @else
                                                                    <input
                                                                        type="text"
                                                                        name="query_{{ $param['name'] }}"
                                                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm"
                                                                        placeholder="{{ $param['description'] }} (可选)"
                                                                    />
                                                                @endif
                                                            </div>
                                                        @endif
                                                    @endforeach
                                                @endforeach
                                            @endif

                                            @if (in_array($item['method'], ['POST', 'PUT', 'PATCH']))
                                                <div class="mb-3">
                                                    <label class="mb-1 block text-xs font-semibold text-slate-600">请求体 (JSON)</label>
                                                    <textarea
                                                        name="request_body"
                                                        rows="5"
                                                        class="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm font-mono"
                                                        placeholder='{"example": "value"}'
                                                    ></textarea>
                                                </div>
                                            @endif

                                            <div class="flex gap-2">
                                                <button
                                                    type="submit"
                                                    class="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700"
                                                >
                                                    发送请求
                                                </button>
                                                <button
                                                    type="button"
                                                    class="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-100"
                                                    onclick="toggleApiTest('{{ $item['uri'] }}', '{{ $item['method'] }}')"
                                                >
                                                    取消
                                                </button>
                                            </div>
                                        </form>

                                        <div id="test-response-{{ $item['uri'] }}-{{ $item['method'] }}" class="mt-4 hidden">
                                            <div class="mb-2 text-xs font-semibold text-slate-600">响应结果</div>
                                            <pre class="rounded-lg bg-slate-900 p-3 text-xs text-slate-100 overflow-x-auto"></pre>
                                        </div>
                                    </div>
                                @endif
                            </div>
                        </details>
                    @endforeach
                </div>
            </x-filament::section>
        @endforeach
    </div>

    <script>
        async function loadPaperJson() {
            const input = document.getElementById('paper-json-id');
            const output = document.getElementById('paper-json-output');
            const paperId = (input?.value || '').trim();
            if (!paperId) {
                output.textContent = '请输入 paper_id';
                return;
            }
            output.textContent = '加载中...';
            try {
                const response = await fetch(`/api/papers/${encodeURIComponent(paperId)}/json`);
                const data = await response.json();
                output.textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                output.textContent = `请求失败: ${error}`;
            }
        }

        function downloadPaperJson() {
            const input = document.getElementById('paper-json-id');
            const paperId = (input?.value || '').trim();
            if (!paperId) {
                return;
            }
            window.location.href = `/api/papers/${encodeURIComponent(paperId)}/json?download=1`;
        }

        function toggleApiTest(uri, method) {
            const formId = `test-form-${uri}-${method}`;
            const form = document.getElementById(formId);
            if (form) {
                form.classList.toggle('hidden');
            }
        }

        async function testApi(event, uri, method) {
            event.preventDefault();

            const formId = `test-form-${uri}-${method}`;
            const responseId = `test-response-${uri}-${method}`;
            const form = document.getElementById(formId);
            const responseDiv = document.getElementById(responseId);
            const pre = responseDiv.querySelector('pre');

            // 构建 URL
            let url = uri;
            const queryParams = new URLSearchParams();

            // 收集查询参数
            const formData = new FormData(event.target);
            for (let [key, value] of formData.entries()) {
                if (key.startsWith('query_')) {
                    const paramName = key.replace('query_', '');
                    if (value) {
                        queryParams.append(paramName, value);
                    }
                }
            }

            // 替换路径参数
            const pathParams = uri.match(/\{([^}]+)\}/g);
            if (pathParams) {
                pathParams.forEach(param => {
                    const paramName = param.slice(1, -1);
                    const value = formData.get(`query_${paramName}`);
                    if (value) {
                        url = url.replace(param, encodeURIComponent(value));
                    }
                });
            }

            if (queryParams.toString()) {
                url += '?' + queryParams.toString();
            }

            // 准备请求选项
            const options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                }
            };

            // 添加请求体
            const body = formData.get('request_body');
            if (body) {
                try {
                    options.body = JSON.stringify(JSON.parse(body));
                } catch (e) {
                    pre.textContent = 'JSON 格式错误: ' + e.message;
                    responseDiv.classList.remove('hidden');
                    return;
                }
            }

            try {
                pre.textContent = '发送中...';
                responseDiv.classList.remove('hidden');

                const response = await fetch(url, options);
                const data = await response.json();

                pre.textContent = `状态: ${response.status}\n\n` + JSON.stringify(data, null, 2);
            } catch (error) {
                pre.textContent = '请求失败: ' + error.message;
            }
        }
    </script>
</x-filament::page>
