<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Perspicacité AI - True Agentic RAG</title>
    <link rel="stylesheet" href="/static/css/theme.css">
    <link rel="stylesheet" href="/static/css/base.css">
    <link rel="stylesheet" href="/static/css/layout.css">
    <link rel="stylesheet" href="/static/css/chat.css">
    <link rel="stylesheet" href="/static/css/kb.css">
    <link rel="stylesheet" href="/static/css/survey.css">
    <!-- Sub-project C (2026-05-15): Prism.js for code-excerpt syntax highlighting -->
    <!-- TODO(plan-c-task-7): compute SRI hashes for prismjs@1.29.0 assets. -->
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/themes/prism-tomorrow.min.css"
          integrity=""
          crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/components/prism-core.min.js"
            integrity=""
            crossorigin="anonymous" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js"
            integrity=""
            crossorigin="anonymous" defer></script>
</head>
<body>
    <div class="container">
        <div class="side-panel">
            <div class="panel" style="flex: 1; display: flex; flex-direction: column; gap: 16px;">
                <!-- New Chat Button -->
                <button class="new-chat-btn" onclick="startNewChat()">
                    <span>+</span> New Chat
                </button>
                
                <!-- Chat History -->
                <div class="chat-history-section">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
                        <h3 style="margin: 0;">💬 Chat History</h3>
                        <div class="history-actions">
                            <button class="history-action-btn" id="select-mode-btn" onclick="toggleSelectMode()" title="Select multiple">☑️</button>
                            <button class="clear-history-btn" onclick="isSelectMode ? showClearHistoryDialog('selected') : showClearHistoryDialog('all')" title="Clear history">🗑️</button>
                        </div>
                    </div>
                    <!-- Conversation search -->
                    <div class="conv-search-wrapper">
                        <input id="conv-search-input" class="conv-search-input" type="search" placeholder="Search conversations…" autocomplete="off">
                        <div id="conv-search-results" class="conv-search-results" style="display:none;"></div>
                    </div>
                    <div id="chat-history-list" class="chat-history-list">
                        <div class="chat-history-item active" data-session="" data-kb="" data-created-at="" data-conv-id="">
                            <span class="chat-title">Current Chat</span>
                            <span class="chat-kb">Web Search</span>
                            <span class="chat-date">Now</span>
                            <button class="delete-chat-btn" onclick="deleteChatItem(this, event)" title="Delete this chat">×</button>
                        </div>
                    </div>
                </div>
                
                <!-- Database Selector -->
                <div class="db-section">
                    <h3>🌐 Search Databases</h3>
                    <div id="db-selector" class="db-selector">
                        <label class="db-option" data-db="semantic_scholar">
                            <input type="checkbox" value="semantic_scholar">
                            <span>Semantic Scholar</span>
                        </label>
                        <label class="db-option" data-db="openalex">
                            <input type="checkbox" value="openalex">
                            <span>OpenAlex</span>
                        </label>
                        <label class="db-option selected" data-db="pubmed">
                            <input type="checkbox" value="pubmed" checked>
                            <span>PubMed</span>
                        </label>
                        <label class="db-option" data-db="arxiv">
                            <input type="checkbox" value="arxiv">
                            <span>arXiv</span>
                        </label>
                        <label class="db-option" data-db="europepmc">
                            <input type="checkbox" value="europepmc">
                            <span>Europe PMC</span>
                        </label>
                        <label class="db-option" data-db="core">
                            <input type="checkbox" value="core">
                            <span>CORE</span>
                        </label>
                        <label class="db-option" data-db="inspire">
                            <input type="checkbox" value="inspire">
                            <span>INSPIRE-HEP</span>
                        </label>
                        <label class="db-option" data-db="pubchem">
                            <input type="checkbox" value="pubchem">
                            <span>PubChem</span>
                        </label>
                        <label class="db-option" data-db="dblp_sparql">
                            <input type="checkbox" value="dblp_sparql">
                            <span>DBLP-SPARQL</span>
                        </label>
                        <label class="db-option selected" data-db="google_scholar" title="Broad coverage via Playwright scraping">
                            <input type="checkbox" value="google_scholar" checked>
                            <span>Google Scholar</span>
                        </label>
                        <label class="db-option" data-db="ieee">
                            <input type="checkbox" value="ieee">
                            <span>IEEE</span>
                        </label>
                        <label class="db-option" data-db="springer">
                            <input type="checkbox" value="springer">
                            <span>Springer</span>
                        </label>
                    </div>
                    <span class="db-select-all" onclick="toggleAllDatabases()">Select All / Deselect All</span>
                </div>
                
                <!-- Knowledge Base -->
                <div class="kb-section">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h3 style="margin-bottom: 0;">📚 Knowledge Base</h3>
                        <button class="kb-create-toggle" onclick="toggleCreateKB()" title="Create new KB" style="font-size: 16px; padding: 2px 6px;">+</button>
                    </div>
                    <select id="kb-select" class="kb-select" onchange="selectKB(this.value)" style="margin-top: 8px;">
                        <option value="">No KB (web search only)</option>
                    </select>
                    <!-- KB detail tabs (Info / Stats) — visible when a KB is selected -->
                    <div id="kb-detail-tab-strip" class="kb-detail-tab-strip" style="display:none;">
                        <button id="kb-detail-tab-info" class="kb-detail-tab-btn active" type="button" onclick="switchKbDetailTab('info')">Info</button>
                        <button id="kb-detail-tab-stats" class="kb-detail-tab-btn" type="button" onclick="switchKbDetailTab('stats')">Stats</button>
                    </div>
                    <div id="kb-info" class="kb-info" style="display:none;"></div>
                    <div id="kb-stats-container" style="display:none;"></div>
                    <div style="display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap;">
                        <button id="kb-add-bibtex-btn" class="kb-create-toggle" style="display:none;" onclick="document.getElementById('kb-add-bibtex-file').click()">Add from BibTeX</button>
                        <input type="file" id="kb-add-bibtex-file" accept=".bib" style="display:none" onchange="addToKBFromBibtex(this.files[0])">
                        <button id="kb-add-dois-btn" class="kb-create-toggle" style="display:none;" onclick="toggleAddDoisPanel()">Add DOIs</button>
                        <button id="kb-delete-btn" class="kb-delete-btn" style="display:none;" onclick="showDeleteKBDialog(selectedKb)">Delete KB</button>
                    </div>
                    <div style="margin-top: 8px;">
                        <button id="build-kbs-from-zotero-btn"
                                data-testid="build-kbs-from-zotero"
                                class="kb-create-toggle"
                                title="Build KBs from your Zotero library">
                            Build KBs from Zotero
                        </button>
                    </div>
                    <div style="margin-top: 8px;">
                        <button id="kb-build-capsules-btn"
                                data-testid="kb-build-capsules"
                                class="kb-create-toggle"
                                title="Build per-paper capsules (figures + structured text + provenance)">
                            Build capsules
                        </button>
                        <div id="kb-build-capsules-progress" class="hidden"></div>
                    </div>
                    <!-- Local-file drop zone (drag-and-drop or click to upload) -->
                    <div id="kb-local-dropzone" data-testid="kb-local-dropzone" class="kb-dropzone">
                        <p>Drop files here, or <label for="kb-local-file-picker" class="link">click to choose</label></p>
                        <input type="file" id="kb-local-file-picker" multiple class="hidden" />
                        <div id="kb-local-progress" class="hidden"></div>
                    </div>
                    <!-- DOI add panel (shown when "Add DOIs" is clicked) -->
                    <div id="kb-dois-panel" class="kb-dois-panel">
                        <textarea id="kb-dois-input" placeholder="One DOI per line&#10;e.g. 10.1038/s41586-020-2649-2" rows="4" style="width:100%;font-size:12px;font-family:monospace;border:1px solid #cbd5e1;border-radius:4px;padding:6px;resize:vertical;margin-bottom:6px;"></textarea>
                        <div id="kb-dois-progress"></div>
                        <button id="kb-dois-submit-btn" onclick="addDoisToKB()" style="width:100%;padding:7px;background:var(--secondary);color:white;border:none;border-radius:var(--radius);font-size:13px;font-weight:500;cursor:pointer;font-family:'Chivo',sans-serif;">Add DOIs</button>
                    </div>
                    <div id="kb-create-form" class="kb-create-form">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <span style="font-size: 13px; font-weight: 500; color: var(--text-main);">Create new Knowledge Base</span>
                            <button onclick="toggleCreateKB()" style="background: none; border: none; font-size: 18px; cursor: pointer; color: var(--text-muted); padding: 0 2px; line-height: 1;" title="Close">&times;</button>
                        </div>
                        <div class="kb-tab-strip">
                            <button id="kb-tab-btn-empty" type="button" class="kb-tab-button active" onclick="switchKbCreateTab('empty')">Empty KB</button>
                            <button id="kb-tab-btn-bibtex" type="button" class="kb-tab-button" onclick="switchKbCreateTab('bibtex')">From BibTeX</button>
                        </div>
                        <div id="kb-tab-panel-empty" class="kb-tab-panel active">
                            <input id="kb-empty-name-input" type="text" placeholder="KB Name (e.g. My research)">
                            <input id="kb-empty-desc-input" type="text" placeholder="Description (optional)">
                            <button id="kb-empty-create-btn" onclick="createEmptyKB()">Create empty KB</button>
                        </div>
                        <div id="kb-tab-panel-bibtex" class="kb-tab-panel">
                            <input id="kb-bibtex-name-input" type="text" placeholder="KB Name (e.g. FBMN papers)">
                            <div id="bibtex-drop-zone" class="bibtex-drop-zone" style="border: 2px dashed var(--border-color); border-radius: 8px; padding: 20px; text-align: center; margin-bottom: 8px; cursor: pointer; transition: all 0.2s;">
                                <div style="font-size: 24px; margin-bottom: 4px;">📄</div>
                                <div style="font-size: 13px; color: var(--text-secondary);">Drop a <b>.bib</b> file here or click to browse</div>
                                <input id="bibtex-file-input" type="file" accept=".bib,.txt" style="display:none;">
                            </div>
                            <input type="hidden" id="kb-bibtex-content" value="">
                            <div id="bibtex-progress" style="display:none; margin-bottom: 8px;">
                                <div style="background: var(--border); border-radius: 4px; height: 6px; overflow: hidden;">
                                    <div id="bibtex-progress-bar" style="background: var(--secondary); height: 100%; width: 0%; transition: width 0.3s;"></div>
                                </div>
                                <div id="bibtex-progress-text" style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">Creating KB...</div>
                            </div>
                            <button id="bibtex-create-btn" onclick="createKBFromBibtex()">Create from BibTeX</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="main-panel">
            <div class="header">
                <div class="header-content">
                    <div class="header-title">
                        <h1>📖 Perspicacité AI</h1>
                        <p>Literature AI assistant — KB-first retrieval with web fallback</p>
                    </div>
                    <a id="ro-crate-link" class="ro-crate-link" href="#" download style="display:none;" title="Download RO-Crate bundle">RO-Crate bundle</a>
                    <a class="header-icon-link" href="https://github.com/holobiomicslab/Perspicacite-AI/issues/new" target="_blank" rel="noopener noreferrer" title="Report a bug or ask a question on GitHub">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
                            <path d="M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.75 2.68 1.24 3.34.95.1-.74.4-1.24.72-1.53-2.55-.29-5.24-1.28-5.24-5.7 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.47.11-3.07 0 0 .97-.31 3.18 1.18.92-.26 1.91-.39 2.89-.39.98 0 1.97.13 2.89.39 2.21-1.49 3.18-1.18 3.18-1.18.63 1.6.23 2.78.11 3.07.74.81 1.19 1.84 1.19 3.1 0 4.43-2.7 5.4-5.27 5.69.41.36.78 1.06.78 2.13v3.16c0 .31.21.66.8.55C20.22 21.39 23.5 17.08 23.5 12 23.5 5.65 18.35.5 12 .5z"/>
                        </svg>
                    </a>
                    <button class="header-icon-link" type="button" onclick="showAboutModal()" title="About Perspicacité-AI">
                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="16" x2="12" y2="12"></line>
                            <line x1="12" y1="8" x2="12.01" y2="8"></line>
                        </svg>
                    </button>
                    <button class="theme-toggle" onclick="toggleTheme()" title="Toggle dark mode">
                        <span id="theme-icon">🌙</span>
                    </button>
                </div>
            </div>
            
            <div class="chat-container" id="chat-container">
                <div class="message assistant">
                    Hello! I'm Perspicacité — an AI literature assistant. I will:
                    <br><br>
                    • Search your selected Knowledge Base first (curated by you)<br>
                    • Fall back to web literature search (OpenAlex) when your KB is insufficient<br>
                    • Ground answers in retrieved papers and maintain conversation context<br>
                    • Let you curate: add selected retrieved papers back into your KB<br><br>
                    Try: "What are key metabolites in jasmine?" or "Summarize feature-based molecular networking (FBMN)"
                </div>
            </div>
            
            <!-- Sub-project C (2026-05-15): code-excerpt display channel -->
            <div id="code-excerpts-panel" class="attachments-panel" style="display: none;">
                <h3 class="attachments-heading">📜 Code excerpts</h3>
                <div id="code-excerpts-list" class="attachments-list"></div>
            </div>

            <!-- Sub-project C (2026-05-15): figure-reference display channel -->
            <div id="figures-panel" class="attachments-panel" style="display: none;">
                <h3 class="attachments-heading">🖼️ Figures</h3>
                <div id="figures-list" class="attachments-list"></div>
            </div>

            <div id="chat-status-bar" class="chat-status-bar" aria-live="polite">
                <span id="chat-heartbeat" class="chat-heartbeat" title="Working…" aria-hidden="true"></span>
                <span id="chat-status-label" class="chat-status-label">Idle</span>
                <span class="chat-status-sep" aria-hidden="true">·</span>
                <span class="chat-status-metric"><span id="chat-elapsed">0.0s</span></span>
                <span class="chat-status-sep" aria-hidden="true">·</span>
                <span class="chat-status-metric" title="Input tokens ↑ / Output tokens ↓">
                    <span id="chat-tokens-in">0</span> ↑ <span id="chat-tokens-out">0</span> ↓
                </span>
                <span class="chat-status-sep" aria-hidden="true">·</span>
                <span class="chat-status-metric" id="chat-llm-model" title="LLM model in use">—</span>
            </div>

            <div class="input-area">
                <div class="chat-input-wrapper">
                    <textarea
                        id="query-input"
                        class="chat-input"
                        placeholder="Ask your research question..."
                        rows="3"
                        onkeydown="handleInputKeydown(event)"
                        oninput="handleInputChange()"
                    ></textarea>
                    <!-- Advanced query options -->
                    <details id="advanced-options-details" class="advanced-options-disclosure">
                        <summary class="advanced-options-summary">Advanced options</summary>
                        <div class="advanced-options-body">
                            <div class="adv-opt-row">
                                <label class="adv-opt-label">Vector vs BM25 weight <span id="adv-vector-value">vector 0.50 / BM25 0.50</span></label>
                                <input type="range" id="adv-vector-slider" min="0" max="1" step="0.05" value="0.5">
                            </div>
                            <div class="adv-opt-row">
                                <label class="adv-opt-label">Recency weight <span id="adv-recency-value">0.00</span></label>
                                <input type="range" id="adv-recency-slider" min="0" max="1" step="0.05" value="0">
                            </div>
                            <div class="adv-opt-row">
                                <label class="adv-opt-label">Knowledge Bases (select 2+ for multi-KB)</label>
                                <div id="adv-kb-list" class="adv-kb-list"></div>
                            </div>
                        </div>
                    </details>
                    <div class="input-actions">
                        <select id="mode-dropdown" class="mode-dropdown" onchange="setMode(this.value)"
                                title="Search mode — hover an option for what it does.">
                            <option value="basic" selected title="Fast single-pass retrieval over your KB and the web. Best for one-shot factual lookups.">📚 Quick Search</option>
                            <option value="advanced" title="Query expansion + hybrid BM25/vector retrieval with rerank. Use when keyword and semantic both matter.">⚡ Advanced (Hybrid)</option>
                            <option value="deep_research" title="Iterates plan → retrieve → reflect up to 3 cycles. For ambiguous or under-specified questions.">🔬 Deep Research</option>
                            <option value="agentic" title="Classifies the intent, plans tool use, and executes multi-step research (search → curate → synthesize) with full audit trail.">🤖 Perspicacité Agentic</option>
                            <option value="literature_survey" title="Broad search across databases, then clusters retrieved papers into themes and recommends additions to your KB.">📖 Literature Survey</option>
                            <option value="contradiction" title="Highlights agreement / disagreement / open questions across cited papers. Needs ≥3 sources to engage.">⚖️ Contradiction</option>
                        </select>
                        <div id="download-cap-control" class="download-cap-control" title="Number of papers retrieved and passed to the answer (also caps full-text download in Agentic mode)">
                            <label>📄 Papers for answer:</label>
                            <input type="range" id="download-cap-slider" min="1" max="10" value="5" oninput="updateDownloadCapDisplay(this.value)">
                            <span class="value-display" id="download-cap-value">5</span>
                        </div>
                        <button id="send-btn" class="send-btn" onclick="sendQuery()" disabled>
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <line x1="22" y1="2" x2="11" y2="13"></line>
                                <polygon points="22,2 15,22 11,13 2,9"></polygon>
                            </svg>
                        </button>
                        <button id="stop-btn" class="stop-btn" onclick="stopQuery()" style="display:none;" title="Stop the current request">
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor">
                                <rect x="6" y="6" width="12" height="12" rx="2"></rect>
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/js/utils.js"></script>
    <script src="/static/js/databases.js"></script>
    <script src="/static/js/mode.js"></script>
    <script src="/static/js/conversations.js"></script>
    <script src="/static/js/chat.js"></script>
    <script src="/static/js/kb.js"></script>
    <script src="/static/js/kb_stats.js"></script>
    <script src="/static/js/paper_detail.js"></script>
    <script src="/static/js/survey.js"></script>
    <script src="/static/js/provenance.js"></script>
    <script src="/static/js/main.js"></script>

    <!-- Paper detail slide-over panel -->
    <div id="paper-detail-panel" class="paper-detail-panel" hidden></div>

    <!-- About / GitHub Modal -->
    <div id="about-modal" class="modal-overlay">
        <div class="modal">
            <h3>📖 Perspicacité-AI</h3>
            <p>A local-first, AI-powered scientific literature research assistant. Six RAG modes over your knowledge base with web-search fallback when the KB is insufficient.</p>
            <p><strong>Useful links:</strong></p>
            <ul style="margin: 0 0 12px 18px; padding: 0;">
                <li><a href="https://github.com/holobiomicslab/Perspicacite-AI" target="_blank" rel="noopener noreferrer">GitHub repository</a></li>
                <li><a href="https://github.com/holobiomicslab/Perspicacite-AI/issues/new" target="_blank" rel="noopener noreferrer">Report a bug / open an issue</a></li>
                <li><a href="https://github.com/holobiomicslab/Perspicacite-AI/blob/main/README.md" target="_blank" rel="noopener noreferrer">Documentation (README)</a></li>
            </ul>
            <div class="modal-buttons">
                <button class="modal-cancel" onclick="hideAboutModal()">Close</button>
            </div>
        </div>
    </div>

    <!-- Delete KB Confirmation Modal -->
    <div id="delete-modal" class="modal-overlay">
        <div class="modal">
            <h3>Delete Knowledge Base</h3>
            <p>This will permanently delete <strong id="delete-kb-name"></strong> and all its papers. This cannot be undone.</p>
            <p>Type <strong id="delete-kb-name2"></strong> to confirm:</p>
            <input type="text" id="delete-kb-input" placeholder="Type KB name to confirm" oninput="checkDeleteKBInput()">
            <div class="modal-buttons">
                <button class="modal-cancel" onclick="hideDeleteKBDialog()">Cancel</button>
                <button class="modal-confirm" id="delete-kb-confirm" onclick="confirmDeleteKB()" disabled>Delete</button>
            </div>
        </div>
    </div>

    <!-- Build KBs from Zotero Modal -->
    <div id="zotero-build-modal" class="modal-overlay zotero-build-overlay" data-testid="zotero-build-modal">
        <div class="modal zotero-build-modal-content">
            <h3>Build KBs from Zotero</h3>
            <div id="zotero-plan-loading">Loading plan…</div>
            <table id="zotero-plan-table" class="zotero-plan-table hidden">
                <thead>
                    <tr>
                        <th></th>
                        <th>KB name</th>
                        <th>Source</th>
                        <th>Items</th>
                        <th>w/ DOI</th>
                        <th>w/ PDF</th>
                        <th>w/ Notes</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <div id="zotero-progress" class="zotero-progress hidden"></div>
            <div class="modal-buttons">
                <button id="zotero-build-cancel" class="modal-cancel">Cancel</button>
                <button id="zotero-build-execute" class="modal-confirm zotero-execute-btn">Execute</button>
            </div>
        </div>
    </div>

    <!-- Clear History Confirmation Modal -->
    <div id="clear-history-dialog" class="modal-overlay" style="display: none;">
        <div class="modal">
            <h3 id="clear-history-title">Clear Chat History</h3>
            <p id="clear-history-message">This will permanently delete <strong>all</strong> your chat conversations. This cannot be undone.</p>
            <div class="modal-buttons">
                <button class="modal-cancel" onclick="hideClearHistoryDialog()">Cancel</button>
                <button class="modal-confirm" id="clear-history-confirm-btn" onclick="confirmClearHistory()">Clear All</button>
            </div>
        </div>
    </div>
</body>
</html>
