<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?><?= esc($document['title']) ?><?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Document Viewer<?= $this->endSection() ?>

<?= $this->section('content') ?>

<style>
.rendered-doc { color: #1e293b; line-height: 1.7; font-size: 14.5px; font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif; }
.rendered-doc h1 { font-size: 28px; font-weight: 800; color: #0f172a; margin: 0 0 18px; letter-spacing: -0.01em; line-height: 1.2; padding-bottom: 10px; border-bottom: 1px solid #e2e8f0; }
.rendered-doc h2 { font-size: 22px; font-weight: 700; color: #0f172a; margin: 28px 0 14px; line-height: 1.25; }
.rendered-doc h3 { font-size: 18px; font-weight: 700; color: #1e293b; margin: 22px 0 10px; line-height: 1.3; }
.rendered-doc h4 { font-size: 15.5px; font-weight: 700; color: #334155; margin: 18px 0 8px; }
.rendered-doc p  { margin: 0 0 14px; }
.rendered-doc strong, .rendered-doc b { font-weight: 700; color: #0f172a; }
.rendered-doc em, .rendered-doc i { font-style: italic; }
.rendered-doc u { text-decoration: underline; text-underline-offset: 2px; }
.rendered-doc a { color: #4f46e5; text-decoration: none; border-bottom: 1px solid #c7d2fe; }
.rendered-doc a:hover { color: #4338ca; border-bottom-color: #6366f1; }
.rendered-doc ul, .rendered-doc ol { margin: 0 0 16px 24px; padding: 0; }
.rendered-doc ul { list-style: disc; }
.rendered-doc ol { list-style: decimal; }
.rendered-doc li { margin: 0 0 6px; padding-left: 2px; }
.rendered-doc li::marker { color: #64748b; }
.rendered-doc blockquote { margin: 18px 0; padding: 10px 16px; border-left: 4px solid #818cf8; background: #eef2ff; border-radius: 0 10px 10px 0; color: #3730a3; }
.rendered-doc blockquote p:last-child { margin-bottom: 0; }
.rendered-doc code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; background: #f1f5f9; padding: 2px 6px; border-radius: 5px; font-size: 12.5px; color: #be185d; }
.rendered-doc pre { background: #0f172a; color: #e2e8f0; padding: 16px 18px; border-radius: 12px; overflow-x: auto; margin: 18px 0; font-size: 12.5px; line-height: 1.6; }
.rendered-doc pre code { background: transparent; color: inherit; padding: 0; border-radius: 0; }
.rendered-doc table { width: 100%; border-collapse: collapse; margin: 18px 0; font-size: 13.5px; border: 1px solid #e2e8f0; border-radius: 10px; overflow: hidden; }
.rendered-doc thead { background: #f8fafc; }
.rendered-doc th { font-weight: 700; color: #0f172a; text-align: left; padding: 10px 14px; border-bottom: 2px solid #e2e8f0; }
.rendered-doc td { padding: 9px 14px; border-bottom: 1px solid #f1f5f9; color: #334155; vertical-align: top; }
.rendered-doc tbody tr:last-child td { border-bottom: none; }
.rendered-doc tbody tr:hover { background: #f8fafc; }
.rendered-doc img { max-width: 100%; height: auto; border-radius: 10px; margin: 14px 0; box-shadow: 0 1px 2px rgba(15,23,42,0.06), 0 1px 3px rgba(15,23,42,0.05); border: 1px solid #e2e8f0; }
.rendered-doc hr { border: none; border-top: 2px solid #e2e8f0; margin: 28px 0; }
.rendered-doc .mammoth-warning { background: #fff7ed; border: 1px solid #fed7aa; color: #9a3412; padding: 10px 14px; border-radius: 10px; font-size: 12.5px; margin: 0 0 16px; }
.view-seg { display: inline-flex; padding: 3px; background: #f1f5f9; border: 1px solid #e2e8f0; border-radius: 10px; gap: 2px; }
.view-seg button { padding: 6px 12px; border: none; background: transparent; border-radius: 7px; font-size: 11.5px; font-weight: 600; color: #64748b; cursor: pointer; transition: all .15s; white-space: nowrap; display: inline-flex; align-items: center; gap: 5px; }
.view-seg button:hover:not(.vs-active) { color: #334155; background: rgba(255,255,255,0.7); }
.view-seg button.vs-active { background: #0f172a; color: #fff; box-shadow: 0 1px 2px rgba(15,23,42,0.2); }
</style>

<?php
    $docId = (int) $document['id'];
    $docType = strtolower(trim((string) ($document['type'] ?? 'txt')));
    $downloadUrl = site_url('/documents/download/' . $docId);
    $inlineUrl = site_url('/documents/download/' . $docId) . '?inline=1';
    $summarizeUrl = site_url('/chat/summarize');
    $askUrl = site_url('/chat/ask');
    $suggestUrl = site_url('/chat/suggest');
    $hasFile = !empty($document['file_path']);
    $hasUrl = !empty($document['url']);
    $canDownload = $hasFile || ($hasUrl && in_array($docType, ['pdf','txt','docx','image','video','md'], true));
    $hasContentText = !empty($document['content_text']);
?>

<div class="mb-5 flex items-center gap-3 flex-wrap">
    <a href="<?= esc(site_url('/agent/documents')) ?>" class="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white border border-slate-200 text-sm text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all shadow-sm">
        <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="M15 19l-7-7 7-7" />
        </svg>
        Back to Documents
    </a>
    <?php if (!empty($document['category_name'])): ?>
        <span class="inline-flex items-center px-3 py-1.5 rounded-xl bg-blue-50 text-blue-700 text-xs font-medium border border-blue-100">
            <?= esc($document['category_name']) ?>
        </span>
    <?php endif; ?>
    <span class="inline-flex items-center px-3 py-1.5 rounded-xl bg-slate-100 text-slate-700 text-xs font-semibold uppercase border border-slate-200">
        <?= esc($docType) ?>
    </span>
</div>

<div class="flex gap-6 flex-col xl:flex-row">

    <div class="xl:w-3/5 2xl:w-2/3 min-w-0">
        <div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden mb-6">
            <div class="px-6 py-4 border-b border-slate-200/60 flex items-center justify-between gap-4 flex-wrap">
                <div class="min-w-0 flex-1">
                    <h2 class="text-xl font-bold text-slate-800 truncate"><?= esc($document['title']) ?></h2>
                    <?php if (!empty($document['description'])): ?>
                        <p class="text-sm text-slate-500 mt-1"><?= esc($document['description']) ?></p>
                    <?php endif; ?>
                </div>
                <div class="flex items-center gap-2 flex-wrap">
                    <?php if ($docType === 'link' && $hasUrl): ?>
                        <a href="<?= esc($document['url']) ?>" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-blue-600 text-white text-sm font-medium hover:bg-blue-700 transition-colors shadow-sm">
                            <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="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                            </svg>
                            Open in New Tab
                        </a>
                    <?php endif; ?>
                    <?php if ($canDownload): ?>
                        <a href="<?= esc($downloadUrl) ?>" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-900 text-white text-sm font-medium hover:bg-slate-800 transition-colors shadow-sm">
                            <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-4l-4 4m0 0l-4-4m4 4V4" />
                            </svg>
                            Download
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <div class="bg-slate-50/60">
                <?php if ($docType === 'link'): ?>
                    <?php if ($hasUrl): ?>
                        <div class="aspect-video w-full bg-white">
                            <iframe src="<?= esc($document['url']) ?>" class="w-full h-full border-0" title="<?= esc($document['title']) ?>" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                        </div>
                    <?php else: ?>
                        <div class="p-12 text-center">
                            <p class="text-slate-500">No URL provided for this link.</p>
                        </div>
                    <?php endif; ?>
                <?php elseif ($docType === 'video'): ?>
                    <?php if ($hasUrl): ?>
                        <div class="aspect-video w-full bg-black">
                            <iframe src="<?= esc($document['url']) ?>" class="w-full h-full border-0" title="<?= esc($document['title']) ?>" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
                        </div>
                    <?php elseif ($hasFile): ?>
                        <div class="aspect-video w-full bg-black flex items-center justify-center">
                            <video src="<?= esc($inlineUrl) ?>" controls class="max-w-full max-h-full"></video>
                        </div>
                    <?php else: ?>
                        <div class="p-12 text-center">
                            <p class="text-slate-500">No video source available.</p>
                        </div>
                    <?php endif; ?>
                <?php elseif ($docType === 'image'): ?>
                    <div class="p-6 flex items-center justify-center">
                        <?php if ($hasFile): ?>
                            <img src="<?= esc($inlineUrl) ?>" alt="<?= esc($document['title']) ?>" class="max-w-full max-h-[70vh] rounded-xl shadow-lg border border-slate-200">
                        <?php elseif ($hasUrl): ?>
                            <img src="<?= esc($document['url']) ?>" alt="<?= esc($document['title']) ?>" class="max-w-full max-h-[70vh] rounded-xl shadow-lg border border-slate-200">
                        <?php else: ?>
                            <p class="text-slate-500">No image source available.</p>
                        <?php endif; ?>
                    </div>
                <?php elseif ($docType === 'pdf'): ?>
                    <div>
                        <div class="px-5 py-3 border-b border-slate-100 flex items-center gap-3 flex-wrap bg-white/70">
                            <div class="flex items-center gap-2 text-xs text-slate-500 font-medium uppercase tracking-wide">
                                <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="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                                </svg>
                                <span>Document Preview</span>
                            </div>
                            <?php if ($hasContentText): ?>
                                <div class="view-seg" data-view-group="pdf">
                                    <button type="button" class="vs-active" data-view="rendered">
                                        <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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                        Native PDF
                                    </button>
                                    <button type="button" data-view="text">
                                        <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="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>
                                        Extracted Text
                                    </button>
                                </div>
                            <?php endif; ?>
                            <?php if ($canDownload): ?>
                                <span class="ml-auto inline-flex items-center gap-1">
                                    <a href="<?= esc($downloadUrl) ?>" class="inline-flex items-center gap-1 px-3 py-1 rounded-lg bg-slate-900 text-white hover:bg-slate-800 transition-colors text-xs font-semibold normal-case">
                                        <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                        </svg>
                                        Download Original
                                    </a>
                                </span>
                            <?php endif; ?>
                        </div>
                        <div data-view-pane="pdf" data-view-pane-type="rendered" class="h-[75vh] w-full bg-slate-100">
                            <?php if ($hasFile): ?>
                                <iframe src="<?= esc($inlineUrl) ?>" class="w-full h-full border-0" title="<?= esc($document['title']) ?>"></iframe>
                            <?php else: ?>
                                <div class="p-12 text-center">
                                    <p class="text-slate-500">No PDF file available.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php if ($hasContentText): ?>
                            <div data-view-pane="pdf" data-view-pane-type="text" class="hidden max-h-[75vh] overflow-y-auto scrollbar-thin p-6 bg-white">
                                <pre class="whitespace-pre-wrap break-words font-sans text-slate-700 leading-relaxed text-sm"><?= esc($document['content_text']) ?></pre>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php elseif ($docType === 'docx' || $docType === 'txt' || $docType === 'md'): ?>
                    <?php if ($hasContentText || $hasFile): ?>
                        <div class="p-6">
                            <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                                <div class="px-5 py-3 border-b border-slate-100 flex items-center gap-3 flex-wrap">
                                    <div class="flex items-center gap-2 text-xs text-slate-500 font-medium uppercase tracking-wide">
                                        <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="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>
                                        <span>Document Content</span>
                                    </div>
                                    <div class="view-seg" data-view-group="doc">
                                        <button type="button" class="vs-active" data-view="rendered">
                                            <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="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z"/><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
                                            <?php if ($docType === 'docx'): ?>Original Preview
                                            <?php elseif ($docType === 'md'): ?>Rendered Markdown
                                            <?php else: ?>Styled View<?php endif; ?>
                                        </button>
                                        <?php if ($hasContentText): ?>
                                            <button type="button" data-view="text">
                                                <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="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>
                                                Extracted Text
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($canDownload): ?>
                                        <span class="ml-auto inline-flex items-center gap-1">
                                            <a href="<?= esc($downloadUrl) ?>" class="inline-flex items-center gap-1 px-3 py-1 rounded-lg bg-slate-900 text-white hover:bg-slate-800 transition-colors text-xs font-semibold normal-case">
                                                <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                                </svg>
                                                Download Original
                                            </a>
                                        </span>
                                    <?php endif; ?>
                                </div>

                                <div data-view-pane="doc" data-view-pane-type="rendered" class="max-h-[75vh] overflow-y-auto scrollbar-thin bg-white">
                                    <?php if ($docType === 'docx'): ?>
                                        <?php if ($hasFile): ?>
                                            <div id="docxLoader" class="p-12 flex flex-col items-center justify-center gap-3 text-center min-h-[300px]">
                                                <svg class="w-10 h-10 text-indigo-500 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                </svg>
                                                <div>
                                                    <p class="font-semibold text-slate-700 text-sm">Rendering Word document…</p>
                                                    <p class="text-xs text-slate-400 mt-1">Converting styles, headings, images and tables to HTML preview.</p>
                                                </div>
                                            </div>
                                            <div id="docxMammothOutput" class="rendered-doc p-8 hidden"></div>
                                            <div id="docxError" class="hidden p-10 text-center">
                                                <p class="text-sm text-red-600 font-medium mb-1">Couldn't render DOCX preview.</p>
                                                <p class="text-xs text-slate-500">Showing extracted training text instead.</p>
                                            </div>
                                        <?php else: ?>
                                            <div class="p-10 text-center">
                                                <p class="text-sm text-slate-500 italic">No DOCX file available for rendering.</p>
                                            </div>
                                        <?php endif; ?>
                                    <?php elseif ($docType === 'md'): ?>
                                        <?php if ($hasContentText || $hasFile): ?>
                                            <div id="mdLoader" class="p-12 flex flex-col items-center justify-center gap-3 text-center min-h-[200px]">
                                                <svg class="w-9 h-9 text-violet-500 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                                </svg>
                                                <p class="font-semibold text-slate-700 text-sm">Rendering Markdown…</p>
                                            </div>
                                            <div id="mdMarkedOutput" class="rendered-doc p-8 hidden"></div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <?php if ($hasContentText): ?>
                                            <div class="p-8">
                                                <pre class="whitespace-pre-wrap break-words font-mono text-[13.5px] leading-[1.8] text-slate-800 bg-slate-50 rounded-xl p-6 border border-slate-200"><?= esc($document['content_text']) ?></pre>
                                            </div>
                                        <?php else: ?>
                                            <div class="p-10 text-center">
                                                <p class="text-sm text-slate-500 italic">No text content available.</p>
                                            </div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>

                                <?php if ($hasContentText): ?>
                                    <div data-view-pane="doc" data-view-pane-type="text" class="hidden max-h-[75vh] overflow-y-auto scrollbar-thin p-6 bg-slate-50/80 border-t border-slate-100">
                                        <div class="mb-3 flex items-center gap-2 px-2">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 text-amber-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z"/></svg>
                                            <span class="text-[10.5px] font-semibold uppercase tracking-wider text-slate-500">Training Data · Text used by the RAG chatbot for Q&A</span>
                                        </div>
                                        <pre class="whitespace-pre-wrap break-words font-sans text-slate-700 leading-relaxed text-sm bg-white rounded-xl p-6 border border-slate-200"><?= esc($document['content_text']) ?></pre>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="p-12 text-center">
                            <p class="text-slate-500">No text content extracted yet.</p>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="p-12 text-center">
                        <p class="text-slate-500">Preview not available for this type.</p>
                        <?php if ($canDownload): ?>
                            <p class="text-sm text-slate-400 mt-3">
                                <a href="<?= esc($downloadUrl) ?>" class="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-slate-900 text-white font-medium hover:bg-slate-800 transition-colors">
                                    <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-4l-4 4m0 0l-4-4m4 4V4" />
                                    </svg>
                                    Download File
                                </a>
                            </p>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-200/60 flex items-center gap-3">
                <div class="w-8 h-8 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 flex items-center justify-center shadow-md">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                </div>
                <div>
                    <h3 class="font-semibold text-slate-800">Document Summary</h3>
                    <p class="text-xs text-slate-500 mt-0.5">Key points generated by AI</p>
                </div>
                <span id="summaryStatus" class="ml-auto inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium bg-amber-50 text-amber-700 border border-amber-100">
                    <svg class="w-3 h-3 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Loading summary...
                </span>
            </div>
            <div class="px-6 py-5">
                <div id="summaryContent" class="text-sm text-slate-700 leading-relaxed bg-slate-50/80 rounded-xl p-5 border border-slate-100 min-h-[100px]">
                    <?php if (!empty($document['summary'])): ?>
                        <p class="text-slate-400 italic">Initializing AI summary...</p>
                    <?php else: ?>
                        <p class="text-slate-400 italic">Summarizing document for the first time. This may take a moment...</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="xl:w-2/5 2xl:w-1/3 flex-shrink-0">
        <div class="sticky top-24">
            <div id="chatContainer" class="glass rounded-2xl border border-white/60 shadow-xl overflow-hidden"
                data-document-id="<?= $docId ?>"
                data-summarize-url="<?= esc($summarizeUrl) ?>"
                data-ask-url="<?= esc($askUrl) ?>"
                data-suggest-url="<?= esc($suggestUrl) ?>">

                <div class="px-5 py-4 border-b border-slate-200/60 flex items-center gap-3 bg-gradient-to-r from-slate-50/80 to-blue-50/60">
                    <div class="w-9 h-9 rounded-2xl bg-gradient-to-br from-violet-500 via-blue-500 to-indigo-600 flex items-center justify-center shadow-md shadow-blue-500/30">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M9.75 3.104v5.714a2.25 2.25 0 01-.659 1.591L5 14.5M9.75 3.104c-.251.023-.501.05-.75.082m.75-.082a24.301 24.301 0 014.5 0m0 0v5.714a2.25 2.25 0 00.659 1.591L19 14.5M14.25 3.104c.251.023.501.05.75.082M14.25 3.104a24.3 24.301 0 014.5 0M5 14.5c.758.126 1.53.198 2.307.214a17.403 17.403 0 005.386 0c.777-.016 1.549-.088 2.307-.214m-10 0v1.143c0 .351.061.696.178 1.024m-.178-2.167v.05c0 .329.041.651.12.959M19 14.5v.05c0 .308.079.63.12.959M19 14.5c-.758.126-1.53.198-2.307.214a17.403 17.403 0 01-5.386 0M5 15.643v1.117c0 .313.036.622.107.923m13.893-2.037v1.117c0 .313-.036.622-.107.923m-13.679 2.037c.207.269.452.518.728.744a20.936 20.936 0 0013.696 0M8 20.5h8" />
                        </svg>
                    </div>
                    <div class="flex-1 min-w-0">
                        <h3 class="font-bold text-slate-800">AI Assistant</h3>
                        <p class="text-xs text-slate-500 mt-0.5">Ask anything about this document</p>
                    </div>
                    <div class="w-2.5 h-2.5 rounded-full bg-emerald-500 shadow-[0_0_10px_rgba(16,185,129,0.6)]"></div>
                </div>

                <div id="suggestedQuestions" class="px-4 pt-3 pb-2 border-b border-slate-100">
                    <div class="flex items-center justify-between gap-3 mb-2">
                        <p class="text-[11px] font-semibold text-slate-500 uppercase tracking-wide px-1 flex-1 min-w-0 truncate">Suggested Questions</p>
                        <div class="flex items-center gap-1.5">
                            <button
                                type="button"
                                id="viewerToggleSuggestBtn"
                                title="Show / hide suggested questions"
                                data-collapse-state="collapsed"
                                class="inline-flex items-center gap-1 px-2 py-1 rounded-md border border-slate-200 bg-white hover:bg-slate-50 hover:border-slate-300 text-slate-600 shadow-sm transition-all text-[10px] font-medium">
                                <svg id="viewerToggleSuggestIcon" xmlns="http://www.w3.org/2000/svg" class="w-3 h-3 transition-transform -rotate-90" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
                                </svg>
                                <span id="viewerToggleSuggestLabel">Show</span>
                            </button>
                            <button
                                type="button"
                                id="viewerRegenerateSuggestBtn"
                                title="Generate a fresh set of questions for this document"
                                class="inline-flex items-center gap-1 px-2 py-1 rounded-md border border-slate-200 bg-white hover:bg-indigo-50 hover:border-indigo-200 hover:text-indigo-700 text-slate-600 shadow-sm transition-all text-[10px] font-medium disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-white disabled:hover:text-slate-600 disabled:hover:border-slate-200">
                                <svg id="viewerRegenerateSuggestIcon" xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.2">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
                                </svg>
                                <span id="viewerRegenerateSuggestLabel">Regenerate</span>
                            </button>
                        </div>
                    </div>
                    <div id="suggestedQuestionsBody" class="hidden">
                        <div id="questionsContainer" class="flex flex-wrap gap-1.5">
                        </div>
                        <div id="viewerSuggestStatusCaption" class="mt-1.5 text-[10px] leading-snug text-slate-400 min-h-[12px] px-1">
                            Loading AI-generated questions for this document…
                        </div>
                    </div>
                </div>

                <div id="chatMessages" class="h-[380px] overflow-y-auto scrollbar-thin p-4 space-y-4 bg-gradient-to-b from-transparent to-slate-50/40">
                    <div class="flex gap-3 max-w-[90%]">
                        <div class="w-8 h-8 rounded-2xl bg-gradient-to-br from-violet-500 via-blue-500 to-indigo-600 flex items-center justify-center flex-shrink-0 shadow-md shadow-blue-500/20">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                            </svg>
                        </div>
                        <div class="bg-white rounded-2xl rounded-tl-sm border border-slate-200 shadow-sm p-3.5">
                            <p class="text-sm text-slate-700 leading-relaxed">
                                Hi! 👋 I'm your AI assistant. I'm analyzing this document now. Once the summary is ready, I'll suggest questions — or ask me anything right away!
                            </p>
                        </div>
                    </div>
                </div>

                <div class="p-4 border-t border-slate-200/60 bg-white/40">
                    <div class="flex gap-2 items-end">
                        <div class="flex-1 relative">
                            <textarea id="chatInput" rows="2" placeholder="Ask about this document..." class="w-full pl-4 pr-11 py-3 rounded-2xl bg-white border border-slate-200 focus:border-blue-400 focus:ring-4 focus:ring-blue-100/60 outline-none text-sm resize-none transition-all shadow-sm placeholder:text-slate-500" style="min-height:50px;max-height:150px;"></textarea>
                        </div>
                        <button id="chatSendBtn" class="w-12 h-12 rounded-2xl bg-gradient-to-br from-blue-600 to-indigo-600 text-white flex items-center justify-center hover:from-blue-700 hover:to-indigo-700 transition-all shadow-lg shadow-blue-500/30 hover:shadow-xl hover:shadow-blue-500/40 active:scale-95 flex-shrink-0 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-lg disabled:hover:shadow-blue-500/30 disabled:active:scale-100">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                            </svg>
                        </button>
                    </div>
                    <p class="text-[11px] text-slate-400 mt-2 px-1">Press <kbd class="px-1.5 py-0.5 rounded-md bg-slate-100 border border-slate-200 font-mono text-[10px]">Enter</kbd> to send · <kbd class="px-1.5 py-0.5 rounded-md bg-slate-100 border border-slate-200 font-mono text-[10px]">Shift+Enter</kbd> for new line</p>
                </div>

            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/mammoth@1.6.0/mammoth.browser.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js"></script>
<script>
(function () {
    var DOC_TYPE = <?= json_encode($docType) ?>;
    var INLINE_URL = <?= json_encode($inlineUrl) ?>;
    var DOWNLOAD_URL = <?= json_encode($downloadUrl) ?>;
    var CONTENT_TEXT = <?= json_encode($document['content_text'] ?? '') ?>;
    var HAS_FILE = <?= json_encode($hasFile) ?>;

    function setViewGroupActive(group, view) {
        var seg = document.querySelector('[data-view-group="' + group + '"]');
        if (!seg) return;
        var btns = seg.querySelectorAll('button[data-view]');
        btns.forEach(function (b) {
            if (b.getAttribute('data-view') === view) b.classList.add('vs-active');
            else b.classList.remove('vs-active');
        });
        var panes = document.querySelectorAll('[data-view-pane="' + group + '"]');
        panes.forEach(function (p) {
            if (p.getAttribute('data-view-pane-type') === view) p.classList.remove('hidden');
            else p.classList.add('hidden');
        });
    }
    function bindViewGroup(group) {
        var seg = document.querySelector('[data-view-group="' + group + '"]');
        if (!seg) return;
        seg.addEventListener('click', function (e) {
            var btn = e.target.closest && e.target.closest('button[data-view]');
            if (!btn || !seg.contains(btn)) return;
            e.preventDefault();
            setViewGroupActive(group, btn.getAttribute('data-view'));
        });
    }
    bindViewGroup('pdf');
    bindViewGroup('doc');

    function switchDocToTextOnFail() {
        var seg = document.querySelector('[data-view-group="doc"]');
        if (!seg) return;
        var hasText = seg.querySelector('button[data-view="text"]');
        if (hasText) setViewGroupActive('doc', 'text');
    }

    function renderDocx() {
        if (DOC_TYPE !== 'docx' || !HAS_FILE || typeof mammoth === 'undefined') return;
        var loader = document.getElementById('docxLoader');
        var output = document.getElementById('docxMammothOutput');
        var errBox = document.getElementById('docxError');
        if (!output) return;
        fetch(DOWNLOAD_URL, {
            method: 'GET',
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        }).then(function (r) {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.arrayBuffer();
        }).then(function (buf) {
            return mammoth.convertToHtml({ arrayBuffer: buf }, {
                includeDefaultStyleMap: true,
                convertImage: mammoth.images.imgElement(function (image) {
                    return image.read('base64').then(function (b64) {
                        return { src: 'data:' + image.contentType + ';base64,' + b64 };
                    });
                })
            }).then(function (res) {
                var html = res.value || '';
                var warns = res.messages || [];
                if (warns.length) {
                    var uniq = [];
                    var seen = {};
                    warns.forEach(function (w) { var k = String(w.message || w); if (!seen[k]) { seen[k] = 1; uniq.push(k); } });
                    if (uniq.length) {
                        html = '<div class="mammoth-warning">Rendered with ' + uniq.length + ' note' + (uniq.length !== 1 ? 's' : '') + ': ' + uniq.slice(0, 3).map(function (t) { var s = String(t); return s.length > 120 ? s.slice(0, 117) + '…' : s; }).join(' · ') + '</div>' + html;
                    }
                }
                if (!html.trim()) throw new Error('empty output');
                output.innerHTML = html;
                if (loader) loader.classList.add('hidden');
                output.classList.remove('hidden');
            });
        }).catch(function (e) {
            console.error('[DOCX render failed]', e);
            if (loader) loader.classList.add('hidden');
            if (errBox) errBox.classList.remove('hidden');
            setTimeout(switchDocToTextOnFail, 150);
        });
    }

    function renderMd() {
        if (DOC_TYPE !== 'md' || typeof marked === 'undefined') return;
        var loader = document.getElementById('mdLoader');
        var output = document.getElementById('mdMarkedOutput');
        if (!output) return;
        if (CONTENT_TEXT && CONTENT_TEXT.trim()) {
            try {
                output.innerHTML = marked.parse(CONTENT_TEXT);
                if (loader) loader.classList.add('hidden');
                output.classList.remove('hidden');
                return;
            } catch (e) { /* fallthrough to fetch */ }
        }
        if (HAS_FILE) {
            fetch(DOWNLOAD_URL, { method: 'GET', credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } })
                .then(function (r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); })
                .then(function (t) {
                    output.innerHTML = marked.parse(t);
                    if (loader) loader.classList.add('hidden');
                    output.classList.remove('hidden');
                }).catch(function (e) {
                    console.error('[MD render failed]', e);
                    setTimeout(switchDocToTextOnFail, 150);
                });
        }
    }

    document.addEventListener('DOMContentLoaded', function () {
        renderDocx();
        renderMd();
    });
})();
</script>
<script>
(function () {
    var toggleBtn = document.getElementById('viewerToggleSuggestBtn');
    var toggleIcon = document.getElementById('viewerToggleSuggestIcon');
    var toggleLabel = document.getElementById('viewerToggleSuggestLabel');
    var bodyEl = document.getElementById('suggestedQuestionsBody');
    if (toggleBtn && bodyEl) {
        var key = 'viewer_suggest_open_' + (document.getElementById('chatContainer')?.getAttribute('data-document-id') || '0');
        var open = false;
        try {
            open = localStorage.getItem(key) === '1';
        } catch (e) {}
        function applyState(doOpen) {
            if (doOpen) {
                bodyEl.classList.remove('hidden');
                toggleIcon?.classList.remove('-rotate-90');
                if (toggleLabel) toggleLabel.textContent = 'Hide';
                toggleBtn.setAttribute('data-collapse-state', 'open');
            } else {
                bodyEl.classList.add('hidden');
                toggleIcon?.classList.add('-rotate-90');
                if (toggleLabel) toggleLabel.textContent = 'Show';
                toggleBtn.setAttribute('data-collapse-state', 'collapsed');
            }
            try { localStorage.setItem(key, doOpen ? '1' : '0'); } catch (e) {}
        }
        applyState(open);
        toggleBtn.addEventListener('click', function () {
            var nowOpen = toggleBtn.getAttribute('data-collapse-state') !== 'open';
            applyState(nowOpen);
        });
    }
})();
</script>
<script src="<?= base_url('assets/js/chatbot.js') ?>"></script>

<?= $this->endSection() ?>
