<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
            <p class="text-sm text-slate-500"><?= count($quizSettings ?? []) ?> quizzes configured</p>
        </div>
        <div class="flex flex-wrap gap-2">
            <a href="<?= site_url('/admin/quiz-attempts') ?>" class="inline-flex items-center gap-2 px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-semibold rounded-xl shadow-sm border border-slate-200 transition">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" /></svg>
                View Attempt History
            </a>
            <button id="btnNewQuiz" class="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-sm font-semibold rounded-xl shadow-md shadow-violet-500/20 hover:shadow-lg hover:-translate-y-0.5 active:translate-y-0 transition-all">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" /></svg>
                New Quiz
            </button>
        </div>
    </div>

    <div id="quizFormPanel" class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6 hidden">
        <h3 class="text-base font-semibold text-slate-800 mb-4" id="quizFormTitle">Create New Quiz</h3>
        <form method="post" action="<?= site_url('/admin/quiz-settings/save') ?>" class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <input type="hidden" name="id" id="qf_id" value="">
            <div class="md:col-span-2">
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Quiz Title</label>
                <input type="text" name="title" id="qf_title" required class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition" placeholder="e.g. Product Knowledge Assessment #1">
            </div>
            <div class="md:col-span-2">
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Description (optional)</label>
                <textarea name="description" id="qf_description" rows="2" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition" placeholder="What topic this quiz covers..."></textarea>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Question Type</label>
                <select name="question_type" id="qf_type" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
                    <option value="multiple_choice">Multiple Choice</option>
                    <option value="fill_up">Fill in the Blank</option>
                </select>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Number of Questions (1-30)</label>
                <input type="number" name="question_count" id="qf_count" min="1" max="30" value="10" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Per-Question Timer (seconds, 10-600)</label>
                <input type="number" name="question_timer_seconds" id="qf_timer" min="10" max="600" value="60" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">Passing Score % (0-100)</label>
                <input type="number" name="passing_score_pct" id="qf_passing" min="0" max="100" value="70" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
            </div>
            <div class="md:col-span-2">
                <label class="block text-xs font-semibold text-slate-600 mb-2">
                    Select Trained Documents (multi-select; AI will pull questions ONLY from these docs)
                </label>
                <div class="rounded-xl border border-slate-300 bg-white max-h-72 overflow-y-auto scrollbar-thin">
                    <?php if (empty($documents)): ?>
                        <div class="p-6 text-center text-sm text-slate-500">No documents uploaded yet — upload some at Documents first.</div>
                    <?php else: ?>
                        <?php foreach ($documents as $d):
                            $chunkCount = (int)($d['chunk_count'] ?? 0);
                            $trained = $chunkCount > 0;
                            $status = $trained ? 'Trained' : 'Untrained';
                            $statusClass = $trained ? 'text-emerald-700 bg-emerald-50' : 'text-slate-600 bg-slate-100';
                        ?>
                            <label class="flex items-start gap-3 px-4 py-3 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer">
                                <input type="checkbox" class="doc-check mt-1 w-4 h-4 text-violet-600 rounded" name="document_ids[]" value="<?= (int)$d['id'] ?>" data-id="<?= (int)$d['id'] ?>">
                                <div class="flex-1 min-w-0">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <span class="text-sm font-medium text-slate-800 truncate"><?= esc($d['title']) ?></span>
                                        <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold <?= $statusClass ?>"><?= $status ?></span>
                                        <?php if (!empty($d['category_name'])): ?>
                                            <span class="text-[11px] text-slate-500"><?= esc($d['category_name']) ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (!empty($d['description'])): ?>
                                        <p class="text-[11px] text-slate-500 mt-0.5 line-clamp-2"><?= esc($d['description']) ?></p>
                                    <?php endif; ?>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="mt-2 flex flex-wrap gap-2">
                    <button type="button" id="selectAllDocs" class="text-[11px] font-semibold text-violet-600 hover:text-violet-700">Select all trained</button>
                    <span class="text-slate-300">|</span>
                    <button type="button" id="clearAllDocs" class="text-[11px] font-semibold text-slate-500 hover:text-slate-700">Clear all</button>
                    <span class="ml-auto text-[11px] text-slate-500"><span id="docsSelectedCount">0</span> selected</span>
                </div>
            </div>
            <div class="md:col-span-2 flex flex-wrap items-center gap-3">
                <label class="inline-flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" name="is_active" id="qf_active" value="1" checked class="w-4 h-4 text-violet-600 rounded">
                    <span class="text-sm font-medium text-slate-700">Active (agents can take this quiz)</span>
                </label>
                <div class="ml-auto flex items-center gap-2">
                    <button type="button" id="cancelQuizForm" class="px-4 py-2.5 rounded-xl text-sm font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 transition">Cancel</button>
                    <button type="submit" class="px-5 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-violet-600 to-fuchsia-600 shadow-md hover:shadow-lg transition">Save Quiz</button>
                </div>
            </div>
        </form>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50/70 border-b border-slate-200/60">
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Title</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Type</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Questions</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Timer</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Pass</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Docs</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Attempts</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (empty($quizSettings)): ?>
                        <tr><td colspan="9" class="px-6 py-16 text-center">
                            <div class="flex flex-col items-center gap-3">
                                <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5m9.75-11.396v5.714a2.25 2.25 0 00.659 1.591L19 14.5" /></svg>
                                </div>
                                <p class="text-sm font-medium text-slate-600">No quizzes yet — click "New Quiz" above to create one.</p>
                            </div>
                        </td></tr>
                    <?php else: ?>
                        <?php foreach ($quizSettings as $q):
                            $docIds = $q['docIds'] ?? [];
                            $docNames = $q['docNames'] ?? [];
                            $type = ($q['question_type'] ?? '') === 'fill_up' ? 'Fill-Up' : 'Multiple Choice';
                            $typeBadge = ($q['question_type'] ?? '') === 'fill_up' ? 'bg-sky-100 text-sky-700' : 'bg-indigo-100 text-indigo-700';
                            $active = !empty($q['is_active']);
                            $activeLabel = $active ? 'Active' : 'Paused';
                            $activeClass = $active ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600';
                            $nextToggle = $active ? 'off' : 'on';
                        ?>
                            <tr class="hover:bg-slate-50/50 transition" data-row-id="<?= (int)$q['id'] ?>">
                                <td class="px-6 py-4">
                                    <div class="flex flex-col">
                                        <span class="text-sm font-semibold text-slate-800"><?= esc($q['title']) ?></span>
                                        <?php if (!empty($q['description'])): ?>
                                            <span class="text-[11px] text-slate-500 line-clamp-1 mt-0.5"><?= esc($q['description']) ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4"><span class="inline-flex px-2.5 py-1 rounded-lg text-[11px] font-semibold <?= $typeBadge ?>"><?= $type ?></span></td>
                                <td class="px-6 py-4 text-sm text-slate-700 font-semibold"><?= (int)($q['question_count'] ?? 0) ?></td>
                                <td class="px-6 py-4 text-sm text-slate-600"><?= (int)($q['question_timer_seconds'] ?? 0) ?>s</td>
                                <td class="px-6 py-4 text-sm text-slate-600 font-semibold"><?= (int)($q['passing_score_pct'] ?? 0) ?>%</td>
                                <td class="px-6 py-4">
                                    <div class="flex flex-col gap-1">
                                        <span class="text-xs font-semibold text-slate-600"><?= count($docIds) ?> doc(s)</span>
                                        <?php if ($docNames !== []): ?>
                                            <span class="text-[10px] text-slate-500 max-w-[220px] truncate" title="<?= esc(implode(', ', $docNames)) ?>"><?= esc(implode(', ', array_slice($docNames, 0, 2))) ?><?= count($docNames) > 2 ? ' +' . (count($docNames) - 2) : '' ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <a href="<?= site_url('/admin/quiz-attempts/quiz/' . (int)$q['id']) ?>" class="text-sm font-semibold text-slate-700 hover:text-violet-600 transition"><?= (int)($q['attempt_count'] ?? 0) ?></a>
                                </td>
                                <td class="px-6 py-4">
                                    <a href="<?= site_url('/admin/quiz-settings/toggle/' . (int)$q['id'] . '/' . $nextToggle) ?>" class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold <?= $activeClass ?>">
                                        <span class="w-1.5 h-1.5 rounded-full <?= $active ? 'bg-emerald-500' : 'bg-slate-400' ?>"></span>
                                        <?= $activeLabel ?>
                                    </a>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="inline-flex items-center gap-1.5 justify-end flex-wrap">
                                        <button type="button" class="edit-quiz px-2.5 py-1.5 rounded-lg text-[12px] font-semibold bg-slate-100 text-slate-700 hover:bg-slate-200 transition"
                                                data-id="<?= (int)$q['id'] ?>"
                                                data-title="<?= esc($q['title']) ?>"
                                                data-description="<?= esc($q['description'] ?? '') ?>"
                                                data-type="<?= esc($q['question_type']) ?>"
                                                data-count="<?= (int)($q['question_count'] ?? 10) ?>"
                                                data-timer="<?= (int)($q['question_timer_seconds'] ?? 60) ?>"
                                                data-passing="<?= (int)($q['passing_score_pct'] ?? 70) ?>"
                                                data-active="<?= !empty($q['is_active']) ? '1' : '0' ?>"
                                                data-docids="<?= esc(implode(',', $docIds)) ?>">
                                            Edit
                                        </button>
                                        <a href="<?= site_url('/admin/quiz-attempts/quiz/' . (int)$q['id']) ?>" class="px-2.5 py-1.5 rounded-lg text-[12px] font-semibold bg-violet-50 text-violet-700 hover:bg-violet-100 transition">Attempts</a>
                                        <form method="get" action="<?= site_url('/admin/quiz-settings/delete/' . (int)$q['id']) ?>" onsubmit="return confirm('Delete this quiz and all its attempt history?');" class="inline">
                                            <button type="submit" class="p-1.5 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
(function () {
    const panel = document.getElementById('quizFormPanel');
    const btnNew = document.getElementById('btnNewQuiz');
    const btnCancel = document.getElementById('cancelQuizForm');
    const titleEl = document.getElementById('quizFormTitle');
    const $id = document.getElementById('qf_id');
    const $title = document.getElementById('qf_title');
    const $desc = document.getElementById('qf_description');
    const $type = document.getElementById('qf_type');
    const $count = document.getElementById('qf_count');
    const $timer = document.getElementById('qf_timer');
    const $passing = document.getElementById('qf_passing');
    const $active = document.getElementById('qf_active');
    const checkboxes = Array.from(document.querySelectorAll('.doc-check'));
    const selectedCount = document.getElementById('docsSelectedCount');
    const selectAllBtn = document.getElementById('selectAllDocs');
    const clearAllBtn = document.getElementById('clearAllDocs');

    function showPanel() { panel.classList.remove('hidden'); panel.scrollIntoView({ behavior: 'smooth', block: 'start' }); }
    function hidePanel() { panel.classList.add('hidden'); }
    function resetForm() {
        $id.value = '';
        $title.value = '';
        $desc.value = '';
        $type.value = 'multiple_choice';
        $count.value = 10;
        $timer.value = 60;
        $passing.value = 70;
        $active.checked = true;
        checkboxes.forEach(c => c.checked = false);
        updateCount();
    }
    function updateCount() {
        const n = checkboxes.filter(c => c.checked).length;
        selectedCount.textContent = String(n);
    }

    btnNew?.addEventListener('click', () => { resetForm(); titleEl.textContent = 'Create New Quiz'; showPanel(); });
    btnCancel?.addEventListener('click', hidePanel);
    checkboxes.forEach(c => c.addEventListener('change', updateCount));
    selectAllBtn?.addEventListener('click', (e) => { e.preventDefault(); checkboxes.forEach(c => { const row = c.closest('label'); if (!row || row.textContent.indexOf('Trained') !== -1 || row.querySelector('.text-emerald-700')) c.checked = true; }); updateCount(); });
    clearAllBtn?.addEventListener('click', (e) => { e.preventDefault(); checkboxes.forEach(c => c.checked = false); updateCount(); });

    document.querySelectorAll('.edit-quiz').forEach(btn => {
        btn.addEventListener('click', () => {
            resetForm();
            titleEl.textContent = 'Edit Quiz';
            $id.value = btn.dataset.id || '';
            $title.value = btn.dataset.title || '';
            $desc.value = btn.dataset.description || '';
            $type.value = btn.dataset.type || 'multiple_choice';
            $count.value = btn.dataset.count || 10;
            $timer.value = btn.dataset.timer || 60;
            $passing.value = btn.dataset.passing || 70;
            $active.checked = (btn.dataset.active === '1');
            const ids = (btn.dataset.docids || '').split(',').map(x => parseInt(x, 10)).filter(x => x > 0);
            checkboxes.forEach(c => {
                const cid = parseInt(c.dataset.id, 10);
                c.checked = ids.indexOf(cid) !== -1;
            });
            updateCount();
            showPanel();
        });
    });
    updateCount();
})();
</script>
