<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div class="flex items-center gap-3 flex-wrap">
            <p class="text-sm text-slate-500"><?= count($documents ?? []) ?> documents</p>
            <?php if (!empty($pendingCount)): ?>
                <a href="<?= site_url('/admin/documents/train-all') ?>" class="inline-flex items-center gap-2 px-4 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:shadow-violet-500/25 hover:-translate-y-0.5 active:translate-y-0 transition-all" title="Train all pending / errored documents">
                    <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 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                    Train All Pending (<?= (int) $pendingCount ?>)
                </a>
            <?php endif; ?>
        </div>
        <a href="<?= site_url('/admin/documents/upload') ?>" class="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold rounded-xl shadow-md hover:shadow-lg 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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>
            Upload Document
        </a>
    </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">Category</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">Visibility</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-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Chunks</th>
                    <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Created</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($documents)): ?>
                        <tr><td colspan="8" 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 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
                                </div>
                                <p class="text-sm font-medium text-slate-600">No documents yet</p>
                            </div>
                        </td></tr>
                    <?php else: ?>
                        <?php foreach ($documents as $d): ?>
                            <?php
                                $rawStatus = (string) ($d['embedding_status'] ?? 'pending');
                                $numericMap = [
                                    '0' => 'pending',
                                    '1' => 'processing',
                                    '2' => 'trained',
                                    '3' => 'error',
                                ];
                                if (isset($numericMap[$rawStatus])) {
                                    $status = $numericMap[$rawStatus];
                                } else {
                                    $status = strtolower(trim($rawStatus));
                                    if ($status === '') $status = 'pending';
                                    if ($status === 'processed' || $status === 'completed') $status = 'trained';
                                }
                                $chunkCount = (int) ($d['chunk_count'] ?? 0);
                                $statusMap = [
                                    'pending'    => ['bg-slate-100 text-slate-700',    'bg-slate-400',   'Pending'],
                                    'processing' => ['bg-amber-100 text-amber-700',    'bg-amber-500',   'Processing'],
                                    'trained'    => ['bg-emerald-100 text-emerald-700','bg-emerald-500', 'Trained'],
                                    'error'      => ['bg-rose-100 text-rose-700',      'bg-rose-500',    'Error'],
                                ];
                                if (!isset($statusMap[$status])) {
                                    $status = 'pending';
                                }
                                [$statusClass, $dotClass, $label] = $statusMap[$status];
                                $needsTrain = in_array($status, ['pending', 'error', 'processing'], true);
                            ?>
                            <tr class="hover:bg-slate-50/50 transition">
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-3">
                                        <div class="w-9 h-9 rounded-xl bg-blue-100 flex items-center justify-center">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px] text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
                                        </div>
                                        <div class="flex flex-col">
                                            <span class="text-sm font-medium text-slate-800 leading-snug"><?= esc($d['title']) ?></span>
                                            <?php if (!empty($d['url'])): ?>
                                                <a href="<?= esc($d['url']) ?>" target="_blank" rel="noopener" class="text-[11px] text-indigo-500 hover:text-indigo-600 truncate max-w-xs"><?= esc($d['url']) ?></a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-slate-600"><?= esc($d['category_name'] ?? '—') ?></td>
                                <td class="px-6 py-4"><span class="inline-flex px-2.5 py-1 rounded-lg bg-slate-100 text-[11px] font-semibold text-slate-600 uppercase tracking-wide"><?= esc($d['type'] ?? '—') ?></span></td>
                                <td class="px-6 py-4">
                                    <?php
                                        $docVis = strtolower(trim((string) ($d['visibility'] ?? 'agents')));
                                        if (!in_array($docVis, ['agents', 'private'], true)) $docVis = 'agents';
                                        $nextVis = $docVis === 'agents' ? 'private' : 'agents';
                                        if ($docVis === 'agents') {
                                            $visClass = 'bg-emerald-100 text-emerald-700 border border-emerald-100 hover:bg-emerald-200 hover:border-emerald-200';
                                            $visLabel = 'Agents &amp; Admin';
                                            $visIcon = '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>';
                                        } else {
                                            $visClass = 'bg-rose-100 text-rose-700 border border-rose-100 hover:bg-rose-200 hover:border-rose-200';
                                            $visLabel = 'Admin Only';
                                            $visIcon = '<svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>';
                                        }
                                    ?>
                                    <a href="<?= site_url('/admin/documents/visibility/' . $d['id'] . '/' . $nextVis) ?>" class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold transition-colors <?= $visClass ?>" title="Click to toggle visibility to <?= esc(ucfirst($nextVis)) ?>">
                                        <?= $visIcon ?>
                                        <?= $visLabel ?>
                                    </a>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold <?= $statusClass ?>">
                                        <span class="w-1.5 h-1.5 rounded-full <?= $dotClass ?>"></span>
                                        <?= esc($label) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <?php if ($chunkCount > 0): ?>
                                        <div class="flex flex-col gap-1 items-start">
                                            <?php
                                                $contentLen = (int)($d['content_length'] ?? 0);
                                                $prefixLen = (int)($d['prefix_estimate_chars'] ?? 0);
                                                $bodyChars = (int)($d['body_extracted_chars'] ?? 0);
                                                $wordEst = (int)($d['word_count_est'] ?? 0);
                                                $bodyWordEst = (int)($d['body_word_estimate'] ?? 0);
                                                $warn = !empty($d['chunk_estimate_low']);
                                                $bodyWarn = $bodyChars < 50 && in_array(strtolower(trim((string)($d['type'] ?? ''))), ['pdf', 'docx', 'doc', 'txt', 'csv', 'link', 'url'], true);
                                                $chunkColor = $warn ? 'bg-amber-50 text-amber-700 ring-1 ring-amber-200' : 'bg-indigo-50 text-indigo-700';
                                                $chunkIconColor = $warn ? 'text-amber-500' : 'text-indigo-500';
                                                $fileSize = (int)($d['file_size'] ?? 0);
                                                $tipExtra = [];
                                                if ($fileSize > 0) $tipExtra[] = 'uploaded file size=' . $fileSize . ' bytes';
                                                if ($prefixLen > 0) $tipExtra[] = 'doc-header prefix=' . $prefixLen . ' chars';
                                                if ($bodyChars >= 0) $tipExtra[] = 'extracted body=' . $bodyChars . ' chars (subtracted prefix)';
                                                $titleTip = $chunkCount . ' trained chunks · ' . implode(' · ', $tipExtra);
                                            ?>
                                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-semibold <?= $chunkColor ?>" title="<?= esc($titleTip) ?>">
                                                <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 <?= $chunkIconColor ?>" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
                                                <?= $chunkCount ?> chunks
                                            </span>
                                            <?php if ($contentLen > 0): ?>
                                                <span class="text-[10.5px] text-slate-500 leading-tight" title="<?= esc($titleTip) ?>">
                                                    total:&nbsp;<span class="font-semibold text-slate-600"><?= number_format($contentLen) ?></span> chars
                                                    <?php if ($bodyChars > 0 || $bodyChars === 0): ?>
                                                        &nbsp;·&nbsp;body:&nbsp;<span class="font-semibold <?= $bodyWarn ? 'text-amber-700' : 'text-slate-700' ?>"><?= number_format($bodyChars) ?></span> chars
                                                    <?php endif; ?>
                                                    <?php if ($wordEst > 0): ?>
                                                        <br>words:&nbsp;<span class="font-semibold text-slate-600"><?= number_format($wordEst) ?></span> total
                                                        <?php if ($bodyWordEst > 0): ?>
                                                            &nbsp;·&nbsp;<span class="font-semibold text-slate-700"><?= number_format($bodyWordEst) ?></span> body words
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($warn || $bodyWarn): ?>
                                                <?php if ($bodyWarn && !$warn): ?>
                                                <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-orange-50 text-orange-700 text-[10px] font-semibold ring-1 ring-orange-200" title="Body-extracted chars = <?= $bodyChars ?> (< 50 chars) which is less than the 3-line document header prefix alone. This usually means the DOCX extractor failed to read any real page content. Try opening in Word → File → Save As → .docx and re-upload. Click Retrain to re-run 4-tier extraction fallback stack.">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
                                                    ⚠ Body extraction failed · Retrain now
                                                </span>
                                                <?php else: ?>
                                                <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-amber-50 text-amber-700 text-[10px] font-semibold ring-1 ring-amber-200" title="Low chunk count (<?= $chunkCount ?>) relative to extracted body size (<?= $bodyChars ?> chars / <?= $bodyWordEst ?> words). Click Retrain to re-split with 800-char / 100-char overlap windows.">
                                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /></svg>
                                                    Low chunks · click Retrain
                                                </span>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-xs text-slate-300">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-xs text-slate-400"><?= !empty($d['created_at']) ? date('M j, Y', strtotime($d['created_at'])) : '—' ?></td>
                                <td class="px-6 py-4 text-right">
                                    <div class="inline-flex items-center justify-end gap-1.5">
                                        <a href="<?= site_url('/admin/documents/train/' . $d['id']) ?>" class="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[12px] font-semibold shadow-sm <?= $needsTrain ? 'bg-violet-600 text-white hover:bg-violet-700 shadow-violet-500/20' : 'bg-slate-100 text-slate-700 hover:bg-slate-200' ?> transition" title="<?= $needsTrain ? 'Train this document' : 'Re-train this document' ?>">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z" /></svg>
                                            <?= $needsTrain ? 'Train' : 'Retrain' ?>
                                        </a>
                                        <form method="get" action="<?= site_url('/admin/documents/delete/' . $d['id']) ?>" onsubmit="return confirm('Delete this document?');" class="inline">
                                            <button type="submit" class="p-1.5 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete document">
                                                <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>
