Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

36.8 KB
Raw Blame
{% extends "base.html" %}

{% block title %}Zotero - Local Deep Research{% endblock %}

{% block extra_head %}
<style nonce="{{ csp_nonce }}">
.ldr-zotero-wrap { max-width: 960px; margin: 0 auto; padding: 20px; }
.ldr-zotero-card {
    background: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    color: var(--text-primary);
}
.ldr-zotero-card h2 { margin-top: 0; font-size: 1.1rem; }
.ldr-zotero-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 16px; }
.ldr-zotero-actions button {
    padding: 8px 16px; border-radius: 6px; cursor: pointer;
    border: 1px solid var(--border-color); background: var(--card-bg);
    color: var(--text-primary);
}
.ldr-zotero-actions button.ldr-zotero-primary {
    background: var(--primary-color, #6e4ff6); color: var(--text-on-accent); border-color: transparent;
}
.ldr-zotero-actions button:disabled { opacity: .5; cursor: not-allowed; }
.ldr-zotero-msg { margin-top: 12px; font-size: .9rem; min-height: 1.2em; }
.ldr-zotero-msg.ldr-zotero-ok { color: #1faa59; }
.ldr-zotero-msg.ldr-zotero-err { color: #e5484d; }

/* Editable config form */
.ldr-zotero-form { display: flex; flex-direction: column; gap: 16px; }
.ldr-zotero-fieldset { border: 1px solid var(--border-color); border-radius: 6px; padding: 14px 16px 16px; margin: 0; }
.ldr-zotero-fieldset legend { padding: 0 6px; font-size: .78rem; text-transform: uppercase; letter-spacing: .04em; color: var(--text-secondary, #999); }
.ldr-zotero-field { margin-bottom: 14px; }
.ldr-zotero-field:last-child { margin-bottom: 0; }
.ldr-zotero-field > label { display: block; font-size: .85rem; margin-bottom: 5px; }
.ldr-zotero-hint { font-size: .78rem; color: var(--text-secondary, #999); margin-top: 5px; }
.ldr-zotero-input, .ldr-zotero-select {
    width: 100%; box-sizing: border-box; padding: 8px 10px; border-radius: 6px;
    border: 1px solid var(--border-color); background: var(--input-bg, var(--card-bg));
    color: var(--text-primary); font-size: .9rem;
}
.ldr-zotero-input:disabled { opacity: .5; }
.ldr-zotero-check { display: flex; align-items: center; gap: 9px; font-size: .9rem; cursor: pointer; }
.ldr-zotero-check input { width: 16px; height: 16px; flex: 0 0 auto; }
.ldr-zotero-row { display: grid; grid-template-columns: 170px 1fr; gap: 12px; }
.ldr-zotero-collection-picker {
    display: grid; gap: 8px; margin: 8px 0;
    padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;
}
.ldr-zotero-collection-picker[hidden] { display: none; }
.ldr-zotero-collection-options { display: grid; gap: 8px; }
.ldr-zotero-collection-option {
    display: flex; align-items: flex-start; gap: 9px; font-size: .9rem;
}
.ldr-zotero-collection-option input { width: 16px; height: 16px; margin-top: 2px; flex: 0 0 auto; }
.ldr-zotero-collection-key {
    color: var(--text-secondary, #999); font-family: monospace; font-size: .78rem;
}
.ldr-zotero-collection-fallback { margin-top: 10px; }

table.ldr-zotero-table { width: 100%; border-collapse: collapse; font-size: .88rem; }
table.ldr-zotero-table th, table.ldr-zotero-table td {
    text-align: left; padding: 8px; border-bottom: 1px solid var(--border-color);
}
/* Click/Enter-to-add key chips in the picker tables — real buttons so they
   are keyboard- and screen-reader-operable, styled to look like inline code. */
.ldr-zotero-keybtn {
    font-family: monospace; font-size: inherit; cursor: pointer;
    color: var(--primary-color, #6e4ff6); background: none; border: none; padding: 0;
}
.ldr-zotero-keybtn:hover, .ldr-zotero-keybtn:focus-visible { text-decoration: underline; }
.ldr-zotero-empty { color: var(--text-secondary, #999); font-size: .9rem; }
@media (max-width: 520px) {
    .ldr-zotero-row { grid-template-columns: 1fr; }
    .ldr-zotero-actions button { flex: 1 1 auto; }
}
/* Sync-status badges + inline error */
.ldr-zotero-badge { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: .78rem; font-weight: 500; }
.ldr-zotero-badge-ok { background: rgba(31, 170, 89, .15); color: #1faa59; }
.ldr-zotero-badge-err { background: rgba(229, 72, 77, .15); color: #e5484d; }
.ldr-zotero-badge-run { background: rgba(110, 79, 246, .15); color: var(--primary-color, #6e4ff6); }
.ldr-zotero-badge-muted { background: var(--border-color); color: var(--text-secondary, #999); }
.ldr-zotero-rowerr { color: #e5484d; font-size: .78rem; margin-top: 3px; word-break: break-word; }
.ldr-zotero-counts { color: var(--text-secondary, #999); font-size: .78rem; margin-top: 3px; }
.ldr-zotero-hint-inline { align-self: center; margin-top: 0; }
.ldr-zotero-advanced { margin: 14px 0 4px; border: 1px solid var(--border-color); border-radius: 8px; padding: 4px 14px; }
.ldr-zotero-advanced summary { cursor: pointer; font-size: .9rem; color: var(--text-secondary, #999); padding: 8px 0; user-select: none; }
.ldr-zotero-advanced[open] summary { margin-bottom: 6px; }
.ldr-zotero-progress { margin: 0 0 10px; }
.ldr-zotero-progress-label { font-size: .8rem; color: var(--text-secondary, #999); margin-bottom: 4px; word-break: break-word; }
.ldr-zotero-progress-track { height: 8px; border-radius: 999px; background: var(--border-color); overflow: hidden; }
.ldr-zotero-progress-fill { height: 100%; border-radius: 999px; background: var(--primary-color, #6e4ff6); width: 0%; transition: width .4s ease; }
.ldr-zotero-linkbtn { font: inherit; font-size: .8rem; font-weight: 400; margin-left: 10px; background: none; border: none; color: var(--primary-color, #6e4ff6); cursor: pointer; }
.ldr-zotero-linkbtn:hover, .ldr-zotero-linkbtn:focus-visible { text-decoration: underline; }
</style>
{% endblock %}

{% block content %}
<div class="ldr-zotero-wrap">
    <h1><i class="fas fa-book"></i> Zotero</h1>
    <p class="ldr-zotero-empty">
        Import papers from a Zotero library or collection into your document
        library — they are stored, text-extracted and indexed so you can use
        them as a search source during research. Configure and sync it all from
        this page.
    </p>

    <div class="ldr-zotero-card">
        <h2>Configuration</h2>
        <form id="zotero-config-form" class="ldr-zotero-form" autocomplete="off">
            <fieldset class="ldr-zotero-fieldset">
                <legend>Connection</legend>
                <div class="ldr-zotero-field">
                    <label for="zt-api-key">API key</label>
                    <div class="ldr-zotero-row">
                        <input type="password" id="zt-api-key" class="ldr-zotero-input" autocomplete="new-password" placeholder="Zotero API key">
                        <button type="button" id="zotero-test">Test connection</button>
                    </div>
                    <div class="ldr-zotero-hint" id="zt-api-key-hint">Create one at zotero.org → Settings → Security → Applications. That’s all you need — your library is detected from the key. Saving runs the connection test automatically.</div>
                </div>
                <div class="ldr-zotero-field">
                    <label for="zt-pdf-storage">PDF storage</label>
                    <select id="zt-pdf-storage" class="ldr-zotero-select">
                        <option value="none">Text only — extract &amp; index the text, don’t keep the PDF (default)</option>
                        <option value="database">Also store the full PDF in the encrypted library</option>
                    </select>
                </div>
                <div class="ldr-zotero-field">
                    <label class="ldr-zotero-check">
                        <input type="checkbox" id="zt-auto-sync"> Automatically sync in the background
                    </label>
                </div>
                <div class="ldr-zotero-field">
                    <label for="zt-interval">Interval (minutes)</label>
                    <div class="ldr-zotero-row">
                        <input type="number" id="zt-interval" class="ldr-zotero-input" min="15" max="10080" step="15" value="360">
                        <div class="ldr-zotero-hint ldr-zotero-hint-inline">How often to check Zotero for changes (only when auto-sync is on).</div>
                    </div>
                </div>
            </fieldset>

            <details id="zt-advanced" class="ldr-zotero-advanced">
                <summary>Advanced options — the defaults suit most libraries</summary>
                <div class="ldr-zotero-field">
                    <label class="ldr-zotero-check">
                        <input type="checkbox" id="zt-enabled"> Enable Zotero integration
                    </label>
                    <div class="ldr-zotero-hint">On by default — untick to pause all Zotero syncing without removing your credentials.</div>
                </div>
                <div class="ldr-zotero-field">
                    <label class="ldr-zotero-check">
                        <input type="checkbox" id="zt-local"> Use the local desktop app API (localhost:23119)
                    </label>
                    <div class="ldr-zotero-hint">Reads from the running Zotero desktop app — no API key needed.</div>
                </div>
                <div class="ldr-zotero-field">
                    <label for="zt-library-type">Library</label>
                    <div class="ldr-zotero-row">
                        <select id="zt-library-type" class="ldr-zotero-select" aria-label="Library type">
                            <option value="user">User</option>
                            <option value="group">Group</option>
                        </select>
                        <input type="text" id="zt-library-id" class="ldr-zotero-input" aria-label="Library ID (auto-detected for personal libraries)" placeholder="Library ID (leave blank for personal libraries)">
                    </div>
                    <div class="ldr-zotero-hint">Personal libraries are detected from the API key. For a group library, use “List groups” below to find its ID.</div>
                </div>
                <div class="ldr-zotero-field">
                    <label for="zt-collections">Collections</label>
                    <div class="ldr-zotero-collection-fallback">
                        <div id="zotero-collection-picker" class="ldr-zotero-collection-picker" hidden>
                            <label class="ldr-zotero-collection-option">
                                <input type="checkbox" id="zt-entire-library">
                                <span>Entire library</span>
                            </label>
                            <div id="zotero-collection-options" class="ldr-zotero-collection-options"></div>
                        </div>
                        <input type="text" id="zt-collections" class="ldr-zotero-input" placeholder="Collection keys, comma-separated (blank = entire library)">
                        <div class="ldr-zotero-hint">Advanced fallback: enter collection keys manually when the collection list cannot be loaded.</div>
                    </div>
                </div>
                <div class="ldr-zotero-field">
                    <label for="zt-tags">Only import items tagged (optional)</label>
                    <input type="text" id="zt-tags" class="ldr-zotero-input" placeholder="Tags, comma-separated (blank = all items)">
                </div>
                <div class="ldr-zotero-field">
                    <label class="ldr-zotero-check">
                        <input type="checkbox" id="zt-annotations"> Import annotations &amp; notes into the searchable text
                    </label>
                </div>
                <div class="ldr-zotero-field">
                    <label class="ldr-zotero-check">
                        <input type="checkbox" id="zt-without-pdf"> Import items that have no PDF (not recommended)
                    </label>
                    <div class="ldr-zotero-hint">Creates title/abstract-only documents with no full text — research over them is shallow. Prefer attaching the PDF in Zotero.</div>
                </div>
            </details>

        </form>

        <div class="ldr-zotero-actions">
            <!-- Start gated; loadConfig() enables these once the saved config is valid. -->
            <button id="zotero-groups" disabled>List groups</button>
            <button id="zotero-list" disabled>List collections</button>
            <button id="zotero-sync" class="ldr-zotero-primary" disabled>Sync now</button>
        </div>
        <div id="zotero-msg" class="ldr-zotero-msg" role="status" aria-live="polite"></div>
    </div>

    <div class="ldr-zotero-card ldr-zotero-collections" id="zotero-groups-card" style="display:none;">
        <h2>Zotero groups</h2>
        <p class="ldr-zotero-empty">Click a group to set Library Type = Group and fill its ID above.</p>
        <table class="ldr-zotero-table">
            <thead><tr><th>Name</th><th>Group ID</th></tr></thead>
            <tbody id="zotero-groups-body"></tbody>
        </table>
    </div>

    <div class="ldr-zotero-card">
        <h2>Sync status
            <button type="button" id="zotero-refresh" class="ldr-zotero-linkbtn" title="Refresh sync status"><i class="fas fa-rotate-right"></i> Refresh</button>
        </h2>
        <div id="zotero-progress" class="ldr-zotero-progress" hidden></div>
        <div id="zotero-status">
            <div class="ldr-zotero-empty">No syncs yet.</div>
        </div>
    </div>
</div>

<script nonce="{{ csp_nonce }}">
(function () {
    const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
    const msg = document.getElementById('zotero-msg');
    const $ = (id) => document.getElementById(id);
    let nextStatusRequestId = 0;
    let latestRenderedStatusRequestId = 0;

    function setMsg(text, ok) {
        msg.textContent = text || '';
        msg.className = 'ldr-zotero-msg ' + (ok === true ? 'ldr-zotero-ok' : ok === false ? 'ldr-zotero-err' : '');
    }
    function setSaveMsg(text, ok) {
        // App-wide status banner (ui.js), matching the rest of the app;
        // falls back to the inline message area if the service is absent.
        if (window.ui && window.ui.showMessage) {
            const type = ok === false ? 'error' : ok === true ? 'success' : 'info';
            window.ui.showMessage(text, type, ok === false ? 6000 : 4000);
        } else {
            setMsg(text, ok);
        }
    }

    async function getJSON(url) {
        const r = await fetch(url, { headers: { 'Accept': 'application/json' } });
        return r.json();
    }
    async function postJSON(url) {
        const r = await fetch(url, {
            method: 'POST',
            headers: { 'Accept': 'application/json', 'X-CSRFToken': csrf },
        });
        return r.json();
    }

    // Escape any dynamic value before inserting into innerHTML. Zotero
    // collection names/keys and user-entered settings are untrusted input.
    const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (ch) => (
        { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ch]
    ));

    // ---- Config form ----------------------------------------------------

    function updateLocalModeUI() {
        // In local-API mode no key is needed; dim the field to make that clear.
        const local = $('zt-local').checked;
        $('zt-api-key').disabled = local;
        $('zt-api-key-hint').textContent = local
            ? 'Not needed in local-API mode.'
            : 'Create one at zotero.org → Settings → Security → Applications. That’s all you need — your library is detected from the key. Saving runs the connection test automatically.';
    }

    function updateAutoSyncUI() {
        // The interval only applies when background auto-sync is enabled.
        $('zt-interval').disabled = !$('zt-auto-sync').checked;
    }

    function gateActions(configured) {
        // The Test/List/Sync buttons act on SAVED settings, so gate them until
        // the stored config is usable; Test connection stays available.
        ['zotero-list', 'zotero-groups', 'zotero-sync'].forEach((id) => {
            const b = $(id);
            if (!b) return;
            b.disabled = !configured;
            b.title = configured ? '' : 'Save valid Zotero settings first';
        });
    }

    function collectionKeysFromField() {
        return $('zt-collections').value
            .split(',')
            .map((key) => key.trim())
            .filter(Boolean);
    }

    function syncCollectionPickerFromField() {
        const selected = new Set(collectionKeysFromField());
        $('zt-entire-library').checked = selected.size === 0;
        document.querySelectorAll('.ldr-zotero-collection-choice').forEach((input) => {
            input.checked = selected.has(input.dataset.key);
        });
    }

    function saveCollectionChoices() {
        const keys = Array.from(
            document.querySelectorAll('.ldr-zotero-collection-choice:checked')
        ).map((input) => input.dataset.key);
        $('zt-collections').value = keys.join(', ');
        $('zt-entire-library').checked = keys.length === 0;
        autosave();
    }

    function fillForm(c) {
        $('zt-enabled').checked = !!c.enabled;
        $('zt-local').checked = !!c.use_local_api;
        $('zt-library-type').value = c.library_type || 'user';
        $('zt-library-id').value = c.library_id || '';
        $('zt-collections').value = (c.collection_keys || []).join(', ');
        syncCollectionPickerFromField();
        $('zt-api-key').value = '';  // write-only: never populate the secret
        $('zt-api-key').placeholder = c.has_api_key
            ? '•••••••• saved — leave blank to keep' : 'Zotero API key';
        $('zt-without-pdf').checked = !!c.import_items_without_pdf;
        $('zt-annotations').checked = !!c.import_annotations;
        $('zt-tags').value = (c.import_tags || []).join(', ');
        $('zt-pdf-storage').value = c.pdf_storage_mode || 'none';
        $('zt-auto-sync').checked = !!c.auto_sync_enabled;
        $('zt-interval').value = c.sync_interval_minutes || 360;
        // If any advanced setting deviates from its default, open the
        // section — an invisible active filter (e.g. collections) or a
        // disabled integration would otherwise silently shape what Sync
        // does.
        const advancedActive = !c.enabled
            || !!c.use_local_api
            || (c.library_type || 'user') !== 'user'
            || (c.collection_keys || []).length > 0
            || (c.import_tags || []).length > 0
            || !!c.import_items_without_pdf
            || !!c.import_annotations;
        if (advancedActive) $('zt-advanced').open = true;
        updateLocalModeUI();
        updateAutoSyncUI();
        gateActions(!!c.configured);
    }

    function collectPayload() {
        const payload = {
            'zotero.enabled': $('zt-enabled').checked,
            'zotero.use_local_api': $('zt-local').checked,
            'zotero.library_type': $('zt-library-type').value,
            'zotero.library_id': $('zt-library-id').value.trim(),
            'zotero.collection_keys': $('zt-collections').value.trim(),
            'zotero.import_items_without_pdf': $('zt-without-pdf').checked,
            'zotero.import_annotations': $('zt-annotations').checked,
            'zotero.import_tags': $('zt-tags').value.trim(),
            'zotero.pdf_storage_mode': $('zt-pdf-storage').value,
            'zotero.auto_sync_enabled': $('zt-auto-sync').checked,
            'zotero.sync_interval_minutes': parseInt($('zt-interval').value, 10) || 360,
        };
        // Only send the API key when the user actually typed one — an empty
        // value would be a no-op server-side anyway, but skipping it avoids
        // ever transmitting a blank over the wire.
        const key = $('zt-api-key').value.trim();
        if (key) payload['zotero.api_key'] = key;
        return payload;
    }

    async function loadConfig() {
        const c = await getJSON('/library/api/zotero/config');
        if (!c.success) {
            configLoadState = 'failed';
            setSaveMsg(c.error || 'Could not load current settings.', false);
            return;
        }
        fillForm(c);
        configLoadState = 'ready';
        // Readiness marker for the UI tests (and a truthful "the form now
        // shows your saved settings" signal).
        $('zotero-config-form').dataset.configLoaded = '1';
        // Show what the key can reach without requiring button clicks.
        if (c.configured) autoLoadPickers();
    }

    $('zt-local').addEventListener('change', updateLocalModeUI);
    $('zt-auto-sync').addEventListener('change', updateAutoSyncUI);

    // ---- Autosave (app-wide pattern: change -> save -> green banner) ----

    let saving = false, resaveQueued = false;
    // 'pending' until fillForm() ran, 'ready' after, 'failed' on a terminal
    // load error — guards autosave so DOM defaults never overwrite the
    // user's real settings (and reschedule background jobs off them).
    let configLoadState = 'pending';
    async function autosave() {
        if (configLoadState !== 'ready') {
            setSaveMsg(configLoadState === 'failed'
                ? 'Your saved settings could not be loaded, so changes are not being saved — reload the page and try again.'
                : 'Still loading your saved settings — that change was not saved. Please redo it once the form shows your current values.', false);
            return;
        }
        if (saving) { resaveQueued = true; return; }
        saving = true;
        try {
            const payload = collectPayload();
            const sentKey = !!payload['zotero.api_key'];
            const r = await fetch('/settings/save_all_settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrf },
                body: JSON.stringify(payload),
            });
            const data = await r.json().catch(() => ({}));
            if (r.ok && data.status === 'success') {
                setSaveMsg('Zotero settings saved.', true);
                // Refresh only the derived state (action gating + key
                // placeholder); do NOT re-fill the inputs — that would
                // clobber anything typed during the save round-trip.
                try {
                    const c2 = await getJSON('/library/api/zotero/config');
                    if (c2.success) {
                        gateActions(!!c2.configured);
                        if (sentKey) $('zt-api-key').value = '';
                        $('zt-api-key').placeholder = c2.has_api_key
                            ? '•••••••• saved — leave blank to keep' : 'Zotero API key';
                        // A newly saved key proves itself right away.
                        if (sentKey && c2.configured) {
                            runConnectionTest();
                            autoLoadPickers();
                        }
                    }
                } catch (e) { /* non-fatal: settings were saved regardless */ }
            } else {
                // save_all_settings returns errors as objects: {key, name, error}.
                const errList = (data.errors || []).map(
                    (e) => (e && typeof e === 'object') ? `${e.name || e.key || ''}: ${e.error || ''}` : String(e)
                );
                setSaveMsg(errList.join('; ') || data.message || 'Could not save settings.', false);
            }
        } catch (e) {
            setSaveMsg('Could not save settings.', false);
        } finally {
            saving = false;
            if (resaveQueued) { resaveQueued = false; autosave(); }
        }
    }

    // Every field saves on change; Enter in a text field saves too.
    ['zt-enabled', 'zt-local', 'zt-library-type', 'zt-library-id', 'zt-api-key',
        'zt-without-pdf', 'zt-annotations', 'zt-tags',
        'zt-pdf-storage', 'zt-auto-sync', 'zt-interval'].forEach((id) => {
        $(id).addEventListener('change', () => { autosave(); });
    });
    $('zt-collections').addEventListener('change', () => {
        syncCollectionPickerFromField();
        autosave();
    });
    $('zt-entire-library').addEventListener('change', () => {
        if ($('zt-entire-library').checked) {
            document.querySelectorAll('.ldr-zotero-collection-choice').forEach((input) => {
                input.checked = false;
            });
            $('zt-collections').value = '';
            autosave();
        } else {
            syncCollectionPickerFromField();
        }
    });
    $('zotero-config-form').addEventListener('submit', (e) => { e.preventDefault(); autosave(); });

    // ---- Sync status ----------------------------------------------------

    function statusBadge(st) {
        const s = String(st ?? '').toLowerCase();
        const kind = s === 'completed' ? 'ok' : s === 'failed' ? 'err'
            : s === 'syncing' ? 'run' : 'muted';
        return `<span class="ldr-zotero-badge ldr-zotero-badge-${kind}">${esc(st || '—')}</span>`;
    }

    // Counts of the last COMPLETED sync (null until one completes). While a
    // later attempt is failed or still running, label them so they are not
    // read as that attempt's results.
    function runCounts(counts, status) {
        if (!counts) return '';
        const labels = [
            ['imported', 'imported'],
            ['updated', 'updated'],
            ['removed', 'removed'],
            ['skipped', 'skipped'],
        ];
        const parts = labels
            .filter(([key]) => Number(counts[key]) > 0)
            .map(([key, label]) => `${esc(counts[key])} ${label}`);
        const errors = Number(counts.errors);
        if (errors > 0) {
            parts.push(`${esc(counts.errors)} ${errors === 1 ? 'error' : 'errors'}`);
        }
        const summary = parts.length ? parts.join(', ') : 'no changes';
        const prefix = status === 'completed' ? '' : 'Last completed sync: ';
        return `<div class="ldr-zotero-counts">${prefix}${summary}</div>`;
    }

    function renderProgress(prog) {
        const pel = $('zotero-progress');
        if (!prog) { pel.hidden = true; pel.innerHTML = ''; return; }
        const phases = { starting: 'Starting', checking: 'Checking for changes', removing: 'Removing', importing: 'Importing' };
        const label = phases[prog.phase] || 'Syncing';
        if (prog.total) {
            const done = prog.done || 0;
            const pct = Math.min(100, Math.round(done / prog.total * 100));
            const cur = prog.current ? ` — ${esc(prog.current)}` : '';
            pel.innerHTML = `<div class="ldr-zotero-progress-label">${label} ${done}/${prog.total}${cur}</div>` +
                '<div class="ldr-zotero-progress-track"><div class="ldr-zotero-progress-fill"></div></div>';
            pel.querySelector('.ldr-zotero-progress-fill').style.width = pct + '%';
        } else {
            pel.innerHTML = `<div class="ldr-zotero-progress-label">${label}…</div>`;
        }
        pel.hidden = false;
    }

    async function loadStatus() {
        // Returns true/false for a current successful snapshot and null for a
        // transient failure or stale response. Polling must not mistake a
        // failed request for proof that a previously observed sync completed.
        const requestId = ++nextStatusRequestId;
        const el = $('zotero-status');
        try {
            const s = await getJSON('/library/api/zotero/status');
            if (!s || !s.success || !Array.isArray(s.collections)) return null;
            if (requestId < latestRenderedStatusRequestId) return null;

            latestRenderedStatusRequestId = requestId;
            renderProgress(s && s.progress);
            if (!s.collections.length) {
                el.innerHTML = '<div class="ldr-zotero-empty">No syncs yet.</div>';
                return false;
            }
            let anySyncing = false;
            const head = '<table class="ldr-zotero-table"><thead><tr><th>Collection</th><th>Status</th><th>Items</th><th>Last sync</th></tr></thead><tbody>';
            const body = s.collections.map(c => {
                const st = String(c.last_status ?? '').toLowerCase();
                if (st === 'syncing') anySyncing = true;
                const when = c.last_synced_at ? new Date(c.last_synced_at).toLocaleString() : '—';
                const name = c.collection_key || 'Entire library';
                // Show last_error whenever present: a "completed" run can
                // still carry contained per-item failures worth surfacing.
                const err = c.last_error
                    ? `<div class="ldr-zotero-rowerr">${esc(c.last_error)}</div>` : '';
                const counts = runCounts(c.last_run_counts, st);
                return `<tr><td>${esc(name)}</td><td>${statusBadge(c.last_status)}${counts}${err}</td><td>${esc(c.item_count)}</td><td>${esc(when)}</td></tr>`;
            }).join('');
            el.innerHTML = head + body + '</tbody></table>';
            return anySyncing;
        } catch (e) {
            // Transient error — keep the previous content and let polling continue.
            return null;
        }
    }

    // ---- Actions --------------------------------------------------------

    async function runConnectionTest() {
        const b = $('zotero-test');
        b.disabled = true;
        setSaveMsg('Testing…');
        try {
            const r = await postJSON('/library/api/zotero/test');
            if (r.success) setSaveMsg(`Connected. Library version ${r.library_version}, ${r.collection_count} collections.`, true);
            else setSaveMsg(r.error || 'Connection failed.', false);
        } catch (e) { setSaveMsg('Connection failed.', false); }
        finally { b.disabled = false; }
    }

    $('zotero-test').addEventListener('click', () => { runConnectionTest(); });

    async function loadCollectionsList(interactive) {
        // interactive=true: user clicked the button (messages + scroll).
        // interactive=false: silent auto-load — populate the inline picker
        // without nagging on failure.
        const listBtn = $('zotero-list');
        if (interactive) { listBtn.disabled = true; setSaveMsg('Loading collections…'); }
        try {
            const r = await getJSON('/library/api/zotero/collections');
            if (!r.success) {
                if (interactive) setSaveMsg(r.error || 'Failed to list collections.', false);
                return;
            }
            const items = r.collections || [];
            const options = $('zotero-collection-options');
            options.innerHTML = items.map((c) => `
                <label class="ldr-zotero-collection-option">
                    <input type="checkbox" class="ldr-zotero-collection-choice" data-key="${esc(c.key)}">
                    <span>
                        ${esc(c.name) || '(untitled)'}
                        <span class="ldr-zotero-collection-key">${esc(c.key)}</span>
                    </span>
                </label>
            `).join('') || '<div class="ldr-zotero-empty">No collections found.</div>';
            $('zotero-collection-picker').hidden = false;
            syncCollectionPickerFromField();
            options.querySelectorAll('.ldr-zotero-collection-choice').forEach((input) => {
                input.addEventListener('change', saveCollectionChoices);
            });
            if (interactive) {
                $('zt-advanced').open = true;
                $('zotero-collection-picker').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }
            if (interactive) setSaveMsg(`Found ${items.length} collections.`, true);
        } catch (e) {
            if (interactive) setSaveMsg('Failed to list collections.', false);
        } finally {
            if (interactive) listBtn.disabled = false;
        }
    }

    async function loadGroupsList(interactive) {
        const groupsBtn = $('zotero-groups');
        if (interactive) { groupsBtn.disabled = true; setSaveMsg('Loading groups…'); }
        try {
            const r = await getJSON('/library/api/zotero/groups');
            if (!r.success) {
                if (interactive) setSaveMsg(r.error || 'Failed to list groups.', false);
                return;
            }
            const items = r.groups || [];
            const body = $('zotero-groups-body');
            body.innerHTML = items.map(g =>
                `<tr><td>${esc(g.name) || '(untitled)'}</td><td><button type="button" class="ldr-zotero-keybtn" title="Use this group" data-key="${esc(g.id)}">${esc(g.id)}</button></td></tr>`
            ).join('') || '<tr><td colspan="2" class="ldr-zotero-empty">No groups found.</td></tr>';
            const card = $('zotero-groups-card');
            if (interactive || items.length) card.style.display = '';
            if (interactive) card.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            body.querySelectorAll('.ldr-zotero-keybtn').forEach(btn => {
                btn.addEventListener('click', () => {
                    // Point the library at this group.
                    $('zt-library-type').value = 'group';
                    $('zt-library-id').value = btn.dataset.key;
                    $('zt-advanced').open = true;  // the field lives in Advanced
                    autosave();
                });
            });
            if (interactive) setSaveMsg(`Found ${items.length} groups.`, true);
        } catch (e) {
            if (interactive) setSaveMsg('Failed to list groups.', false);
        } finally {
            if (interactive) groupsBtn.disabled = false;
        }
    }

    function autoLoadPickers() {
        // Fire-and-forget: show what's available (collections to filter by,
        // groups the key can reach) without requiring button clicks.
        loadCollectionsList(false);
        loadGroupsList(false);
    }

    $('zotero-list').addEventListener('click', () => {
        if (!$('zotero-list').disabled) loadCollectionsList(true);
    });

    $('zotero-groups').addEventListener('click', () => {
        if (!$('zotero-groups').disabled) loadGroupsList(true);
    });

    $('zotero-sync').addEventListener('click', async () => {
        const btn = $('zotero-sync');
        if (btn.disabled) return;
        const orig = btn.textContent;
        btn.disabled = true;
        btn.textContent = 'Syncing…';
        const restore = () => { btn.disabled = false; btn.textContent = orig; renderProgress(null); };
        setSaveMsg('Starting sync…');
        // Immediate feedback: show the progress element right away rather
        // than waiting for the first status poll to catch the sync (a small
        // sync can finish between polls).
        renderProgress({ phase: 'starting' });
        try {
            const r = await postJSON('/library/api/zotero/sync');
            if (r.success) {
                setSaveMsg('Sync started in the background. Status updates below.', true);
                // Poll until the sync actually finishes (not a fixed window):
                // stop once a seen "syncing" clears, if none appears within the
                // grace window, or after a hard cap — so a large-library sync
                // isn't cut off and the button doesn't restore prematurely.
                // Fast cadence: the poll also drives the progress bar.
                let elapsed = 0, sawSyncing = false, pollInFlight = false;
                let pollFinished = false;
                const STEP = 1500, GRACE = 20000, MAX = 15 * 60 * 1000;
                let t = null;
                const finishPolling = (completed) => {
                    if (pollFinished) return;
                    pollFinished = true;
                    clearInterval(t);
                    restore();
                    if (completed) setSaveMsg('Sync finished.', true);
                    // Collections may have changed Zotero-side.
                    loadCollectionsList(false);
                };
                t = setInterval(async () => {
                    elapsed += STEP;
                    if (elapsed >= MAX) {
                        finishPolling(false);
                        return;
                    }
                    if (pollFinished || pollInFlight) return;

                    pollInFlight = true;
                    try {
                        const syncing = await loadStatus();
                        if (pollFinished) return;
                        if (syncing === null) return;

                        if (syncing) sawSyncing = true;
                        if (
                            (sawSyncing && !syncing) ||
                            (!sawSyncing && elapsed >= GRACE)
                        ) {
                            finishPolling(sawSyncing && !syncing);
                        }
                    } finally {
                        pollInFlight = false;
                    }
                }, STEP);
            } else {
                setSaveMsg(r.error || 'Could not start sync.', false);
                restore();
            }
        } catch (e) { setSaveMsg('Could not start sync.', false); restore(); }
    });

    $('zotero-refresh').addEventListener('click', () => { loadStatus(); });

    loadConfig().catch(() => { configLoadState = 'failed'; setSaveMsg('Could not load current settings.', false); });
    loadStatus();
})();
</script>
{% endblock %}