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.

38.7 KB
Raw Blame
// Subscriptions Management Page
// Security: Uses escapeHtml from /static/js/security/xss-protection.js (loaded globally)
// Note: URLValidator is available globally via /static/js/security/url-validator.js

let subscriptions = [];
let folders = [];
const currentFilter = {
    folder: 'all',
    status: 'all',
    frequency: 'all',
    search: ''
};

// Default fetch options to include credentials
const fetchOptions = {
    credentials: 'same-origin'
};
const runningSubscriptionIds = new Set();
const subscriptionToggleIntents = new Map();
let subscriptionsMutationGeneration = 0;
let subscriptionsLoadRequestId = 0;
let foldersLoadRequestId = 0;

// Format next update time correctly
function formatNextUpdate(dateString) {
    // The date string from the database is in UTC
    // If it contains 'Z' or '+00:00', it's UTC
    // Otherwise, assume it's already in local time

    const date = new Date(dateString);

    // Check if the date is valid
    if (isNaN(date.getTime())) {
        return 'Invalid date';
    }

    // If the date string doesn't contain timezone info, it might be interpreted incorrectly
    // Let's check if it's in the past (more than 5 minutes ago)
    const now = new Date();
    const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);

    if (date < fiveMinutesAgo) {
        // The date is in the past, which likely means it was interpreted in the wrong timezone
        // Add the local timezone offset to correct it
        const offset = now.getTimezoneOffset() * 60 * 1000;
        const correctedDate = new Date(date.getTime() - offset);
        return correctedDate.toLocaleString();
    }

    return date.toLocaleString();
}

// Initialize page
document.addEventListener('DOMContentLoaded', function() {
    loadSubscriptions();
    loadFolders();
    setupEventListeners();
    checkSchedulerStatus();
    // Jitter info now handled by dedicated form pages
});

// Setup event listeners
function setupEventListeners() {
    // Card actions. Each card carries its subscription ID as inert data, and
    // the card and its buttons name their action in data-subscription-action.
    // This one delegated listener joins the two, so an ID is never compiled
    // as JavaScript, as it would be inside an inline on* handler.
    document.getElementById('subscriptions-grid')
        ?.addEventListener('click', handleSubscriptionCardAction);

    // Search box
    document.getElementById('subscription-search').addEventListener('input', (e) => {
        currentFilter.search = e.target.value;
        renderSubscriptions();
    });

    // Filter dropdowns
    document.getElementById('status-filter').addEventListener('change', (e) => {
        currentFilter.status = e.target.value;
        renderSubscriptions();
    });

    document.getElementById('frequency-filter').addEventListener('change', (e) => {
        currentFilter.frequency = e.target.value;
        renderSubscriptions();
    });

    // Folder navigation
    document.addEventListener('click', (e) => {
        if (e.target.closest('.ldr-folder-item')) {
            const folderItem = e.target.closest('.ldr-folder-item');
            const folderId = folderItem.dataset.folder;
            selectFolder(folderId);
        }
    });

    // Form handlers removed - now handled by dedicated form pages

    // Add folder button
    document.getElementById('add-folder-btn').addEventListener('click', createNewFolder);

    // Create subscription button - redirect to form page
    document.getElementById('create-subscription-btn').addEventListener('click', () => {
        window.location.href = '/news/subscriptions/new';
    });
}

// Dispatch a click on a subscription card or on one of its action buttons
function handleSubscriptionCardAction(event) {
    const grid = event.currentTarget;
    // A click inside a link on a card (Edit, View original research) is left
    // to the link: it navigates and does not also open the card's history.
    // So the Edit link needs no inline handler to keep the click off the card.
    const link = event.target.closest('a');
    if (link && grid.contains(link)) return;

    const actionElement = event.target.closest('[data-subscription-action]');
    if (!actionElement || !grid.contains(actionElement)) return;
    const card = actionElement.closest('.ldr-subscription-card');
    const subscriptionId = card?.dataset.subscriptionId;
    if (!subscriptionId) return;

    // A button click stays inside the card, as it did when each button
    // stopped propagation itself.
    if (actionElement !== card) event.stopPropagation();

    switch (actionElement.dataset.subscriptionAction) {
        case 'run':
            runSubscriptionNow(subscriptionId);
            break;
        case 'toggle':
            toggleSubscription(subscriptionId);
            break;
        case 'history':
            viewSubscriptionHistory(subscriptionId);
            break;
        case 'delete':
            deleteSubscriptionDirect(subscriptionId);
            break;
        default:
            break;
    }
}

// Load subscriptions from API
async function loadSubscriptions() {
    const loadRequestId = ++subscriptionsLoadRequestId;
    const loadGeneration = subscriptionsMutationGeneration;
    const ownsLoad = () => (
        loadRequestId === subscriptionsLoadRequestId &&
        loadGeneration === subscriptionsMutationGeneration
    );
    SafeLogger.log('Loading subscriptions...');
    try {
        const response = await fetch('/news/api/subscriptions/current', {
            credentials: 'same-origin'
        });
        if (!ownsLoad()) return;

        if (response.ok) {
            const data = await response.json();
            if (!ownsLoad()) return;
            subscriptions = data.subscriptions || [];
            SafeLogger.log('Loaded subscriptions:', subscriptions);

            // Log the 3090 subscription specifically
            const sub3090 = subscriptions.find(s => s.query && s.query.includes('3090'));
            if (sub3090) {
                SafeLogger.log('3090 subscription data:', {
                    id: sub3090.id,
                    refresh_minutes: sub3090.refresh_minutes,
                    next_refresh: sub3090.next_refresh,
                    last_refreshed: sub3090.last_refreshed
                });
            }

            renderSubscriptions();
            updateStats();
        } else {
            SafeLogger.error('Failed to load subscriptions:', response.status, response.statusText);
            showAlert('Failed to load subscriptions', 'error');
        }
    } catch (error) {
        if (!ownsLoad()) return;
        SafeLogger.error('Error loading subscriptions:', error);
        showAlert('Failed to load subscriptions', 'error');
    }
}

// Load folders
async function loadFolders() {
    const loadRequestId = ++foldersLoadRequestId;
    const ownsLoad = () => loadRequestId === foldersLoadRequestId;
    try {
        const response = await fetch('/news/api/subscription/folders', {
            credentials: 'same-origin'
        });
        if (!ownsLoad()) return;

        if (response.ok) {
            const data = await response.json();
            if (!ownsLoad()) return;
            folders = Array.isArray(data) ? data : (data.folders || []);
            renderFolders();
        } else {
            SafeLogger.error('Failed to load folders:', response.status, response.statusText);
        }
    } catch (error) {
        if (!ownsLoad()) return;
        SafeLogger.error('Error loading folders:', error);
    }
}

// Render subscriptions grid
function renderSubscriptions() {
    const grid = document.getElementById('subscriptions-grid');
    const filtered = filterSubscriptions();

    if (filtered.length === 0) {
        grid.innerHTML = `
            <div class="ldr-empty-state">
                <i class="bi bi-bell-slash"></i>
                <h3>No subscriptions found</h3>
                <p>Create your first subscription to start tracking news topics</p>
            </div>
        `;
        return;
    }

    // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
    grid.innerHTML = filtered.map(sub => createSubscriptionCard(sub)).join('');
}

// Create subscription card HTML
function createSubscriptionCard(subscription) {
    const statusClass = subscription.is_active ? 'active' : 'paused';
    const statusIcon = subscription.is_active ? 'bi-play-circle' : 'bi-pause-circle';
    const lastUpdated = subscription.last_refreshed ?
        new Date(subscription.last_refreshed).toLocaleString() : 'Never';

    // Coerce the raw API value to an integer before any of it can reach
    // markup: non-numeric refresh_minutes values fall back to a safe label.
    const parsedRefreshMinutes = Number.parseInt(subscription.refresh_minutes, 10);
    const refreshMinutes = Number.isFinite(parsedRefreshMinutes) ? parsedRefreshMinutes : null;
    let refreshInterval;
    if (refreshMinutes === null) {
        refreshInterval = 'Custom schedule';
    } else if (refreshMinutes === 1) {
        refreshInterval = 'Every minute';
    } else if (refreshMinutes < 60) {
        refreshInterval = `Every ${refreshMinutes} minutes`;
    } else if (refreshMinutes === 60) {
        refreshInterval = 'Hourly';
    } else if (refreshMinutes === 1440) {
        refreshInterval = 'Daily';
    } else if (refreshMinutes === 10080) {
        refreshInterval = 'Weekly';
    } else if (refreshMinutes % 1440 === 0) {
        refreshInterval = `Every ${refreshMinutes / 1440} days`;
    } else if (refreshMinutes % 60 === 0) {
        refreshInterval = `Every ${refreshMinutes / 60} hours`;
    } else {
        refreshInterval = `Every ${refreshMinutes} minutes`;
    }

    // Truncate long text and escape for XSS prevention
    const displayName = subscription.name || subscription.query;
    const truncatedName = displayName.length > 50 ? displayName.substring(0, 50) + '...' : displayName;
    const truncatedQuery = subscription.query.length > 80 ? subscription.query.substring(0, 80) + '...' : subscription.query;

    // Escape user-controlled values for safe HTML insertion
    const safeDisplayName = escapeHtml(displayName);
    const safeTruncatedName = escapeHtml(truncatedName);
    const safeTruncatedQuery = escapeHtml(truncatedQuery);
    const safeQuery = escapeHtml(subscription.query);

    // Coerce to an integer so a hostile total_runs value can never become
    // markup when interpolated into the card stats below.
    const parsedTotalRuns = Number.parseInt(subscription.total_runs, 10);
    const totalRuns = Number.isFinite(parsedTotalRuns) ? parsedTotalRuns : 0;

    return `
        <div class="ldr-subscription-card" data-subscription-id="${escapeHtml(subscription.id)}" data-subscription-action="history" style="cursor: pointer;">
            <div class="ldr-card-header">
                <h4 title="${safeDisplayName}">${safeTruncatedName}</h4>
                <div class="ldr-card-actions">
                    <button class="btn btn-sm ldr-btn-icon" data-subscription-action="run" title="Run now">
                        <i class="bi bi-arrow-clockwise"></i>
                    </button>
                    <button class="btn btn-sm ldr-btn-icon" data-subscription-action="toggle" title="${statusClass === 'active' ? 'Pause' : 'Resume'}">
                        <i class="bi ${statusIcon}"></i>
                    </button>
                    <button class="btn btn-sm ldr-btn-icon" data-subscription-action="history" title="View history">
                        <i class="bi bi-clock-history"></i>
                    </button>
                    <a href="/news/subscriptions/${encodeURIComponent(subscription.id)}/edit" class="btn btn-sm ldr-btn-icon" title="Edit">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <button class="btn btn-sm ldr-btn-icon btn-danger" data-subscription-action="delete" title="Delete">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
            <div class="ldr-card-body">
                <div class="ldr-query-text" title="${safeQuery}">${safeTruncatedQuery}</div>
                <div class="ldr-subscription-meta">
                    <span class="ldr-status-badge ldr-status-${statusClass}">${statusClass}</span>
                    <span class="ldr-frequency-badge">${refreshInterval}</span>
                    ${subscription.folder_id ? `<span class="ldr-folder-badge">${escapeHtml(getFolderName(subscription.folder_id))}</span>` : ''}
                </div>
                <div class="ldr-subscription-stats">
                    <div class="ldr-stat-item">
                        <i class="bi bi-file-text"></i>
                        <span>${totalRuns} research runs</span>
                    </div>
                    ${subscription.source_id ? `
                        <div class="ldr-stat-item">
                            <i class="bi bi-link-45deg"></i>
                            <a href="/progress/${encodeURIComponent(subscription.source_id)}" class="ldr-source-link">View original research</a>
                        </div>
                    ` : ''}
                </div>
                <div class="ldr-last-updated">
                    <i class="bi bi-clock"></i> Last updated: ${lastUpdated}
                </div>
                ${subscription.next_refresh ? `
                    <div class="ldr-next-update">
                        <i class="bi bi-arrow-clockwise"></i> Next update: ${formatNextUpdate(subscription.next_refresh)}
                    </div>
                ` : ''}
            </div>
        </div>
    `;
}

// Filter subscriptions based on current filters
function filterSubscriptions() {
    return subscriptions.filter(sub => {
        // Folder filter
        if (currentFilter.folder !== 'all') {
            if (currentFilter.folder === 'uncategorized' && sub.folder_id) return false;
            if (currentFilter.folder !== 'uncategorized' && sub.folder_id !== currentFilter.folder) return false;
        }

        // Status filter
        if (currentFilter.status !== 'all') {
            const isActive = sub.is_active;
            if (currentFilter.status === 'active' && !isActive) return false;
            if (currentFilter.status === 'paused' && isActive) return false;
        }

        // Frequency filter
        if (currentFilter.frequency !== 'all' && sub.refresh_interval !== currentFilter.frequency) {
            return false;
        }

        // Search filter
        if (currentFilter.search) {
            const searchLower = currentFilter.search.toLowerCase();
            const nameMatch = (sub.name || '').toLowerCase().includes(searchLower);
            const queryMatch = sub.query.toLowerCase().includes(searchLower);
            if (!nameMatch && !queryMatch) return false;
        }

        return true;
    });
}

// New subscription creation now handled by dedicated form page

// Run the saved subscription through its interval and configuration checks.
async function runSubscriptionNow(subscriptionId) {
    const subscription = subscriptions.find(s => s.id === subscriptionId);
    if (!subscription || runningSubscriptionIds.has(subscriptionId)) return;

    runningSubscriptionIds.add(subscriptionId);

    try {
        const query = subscription.query || subscription.query_or_topic || '';
        SafeLogger.log('Running subscription:', subscriptionId, 'with query:', query);
        // showAlert renders HTML, so the query is escaped to show as text.
        const safeQuery = escapeHtml(query);
        showAlert('Starting research for: ' + safeQuery, 'info');

        // The server validates the saved interval and uses the subscription's
        // stored provider and model before it starts research.
        const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}/run`, {
            ...fetchOptions,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            }
        });

        if (response.ok) {
            const data = await response.json();
            SafeLogger.log('Research API response:', data);

            if ((data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) && data.research_id) {
                // Validate research_id is a safe UUID format before using in URL
                const safeResearchId = String(data.research_id).replace(/[^a-z0-9-]/gi, '');
                showAlert(`Research started! <a href="/progress/${safeResearchId}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');

                // Store active research in localStorage so news page can show progress
                localStorage.setItem('active_news_research', JSON.stringify({
                    researchId: data.research_id,
                    query,
                    startTime: new Date().toISOString()
                }));

                // Update the subscription's last run time
                subscription.last_run = new Date().toISOString();
                renderSubscriptions();

                // Refresh subscription data after a delay
                setTimeout(() => loadSubscriptions(), 2000);

                // Optional: Open news page to show progress
                // window.open('/news', '_blank');
            } else {
                SafeLogger.error('Unexpected response:', data);
                // showAlert renders HTML, so the server's text is escaped.
                const safeMessage = escapeHtml(data.message || 'Unknown error');
                showAlert('Failed to start research: ' + safeMessage, 'error');
            }
        } else {
            SafeLogger.error('Research API error:', response.status, response.statusText);
            const errorData = await response.json().catch(() => ({}));
            SafeLogger.error('Error data:', errorData);
            // showAlert renders HTML, so the server's text is escaped.
            const safeError = escapeHtml(
                errorData.message || errorData.error || errorData.detail ||
                'Failed to start research'
            );
            showAlert(safeError, 'error');
        }
    } catch (error) {
        SafeLogger.error('Error running subscription:', error);
        showAlert('Failed to start research', 'error');
    } finally {
        runningSubscriptionIds.delete(subscriptionId);
    }
}

// Toggle subscription active/paused
async function toggleSubscription(subscriptionId) {
    const subscription = subscriptions.find(s => s.id === subscriptionId);
    if (!subscription || subscriptionToggleIntents.has(subscriptionId)) return;

    const intendedActiveState = !subscription.is_active;
    subscriptionToggleIntents.set(subscriptionId, intendedActiveState);

    try {
        const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}`, {
            ...fetchOptions,
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({
                is_active: intendedActiveState
            })
        });

        if (!response.ok) {
            SafeLogger.error('Failed to toggle subscription:', response.status, response.statusText);
            showAlert('Failed to update subscription', 'error');
            return;
        }

        subscriptionsMutationGeneration += 1;
        const currentSubscription = subscriptions.find(s => s.id === subscriptionId);
        if (currentSubscription) currentSubscription.is_active = intendedActiveState;
        renderSubscriptions();
        updateStats();
    } catch (error) {
        SafeLogger.error('Error toggling subscription:', error);
        showAlert('Failed to update subscription', 'error');
    } finally {
        if (subscriptionToggleIntents.get(subscriptionId) === intendedActiveState) {
            subscriptionToggleIntents.delete(subscriptionId);
        }
    }
}

// View subscription history
async function viewSubscriptionHistory(subscriptionId) {
    const subscription = subscriptions.find(s => s.id === subscriptionId);
    if (!subscription) return;

    try {
        // Fetch subscription history
        const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}/history`, fetchOptions);
        if (response.ok) {
            const data = await response.json();
            showSubscriptionHistoryModal(subscription, data);
        } else {
            showAlert('Failed to load subscription history', 'error');
        }
    } catch (error) {
        SafeLogger.error('Error loading subscription history:', error);
        showAlert('Failed to load subscription history', 'error');
    }
}

// Show subscription history modal
function showSubscriptionHistoryModal(subscription, historyData) {
    // Escape user-controlled values for XSS prevention
    const safeTitle = escapeHtml(subscription.name || subscription.query);

    // Coerce to an integer: historyData.total_runs is an API value that
    // must never be interpolated into the modal as raw markup.
    const parsedHistoryRuns = Number.parseInt(historyData.total_runs, 10);
    const totalHistoryRuns = Number.isFinite(parsedHistoryRuns) ? parsedHistoryRuns : 0;

    // Create modal content
    const modalContent = `
        <div class="modal fade" id="historyModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">
                            <i class="bi bi-clock-history"></i> History: ${safeTitle}
                        </h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="ldr-history-summary">
                            <p><strong>Total research runs:</strong> ${totalHistoryRuns}</p>
                            <p><strong>Created:</strong> ${new Date(subscription.created_at).toLocaleString()}</p>
                            ${subscription.source_id ? `
                                <p><strong>Created from:</strong>
                                    <a href="/progress/${encodeURIComponent(subscription.source_id)}" target="_blank" rel="noopener noreferrer">
                                        Original research <i class="bi bi-box-arrow-up-right"></i>
                                    </a>
                                </p>
                            ` : ''}
                        </div>

                        <h6 class="mt-4">Recent Research Runs</h6>
                        <div class="ldr-history-list" style="max-height: 400px; overflow-y: auto;">
                            ${historyData.history && historyData.history.length > 0 ?
                                historyData.history.map(item => {
                                    // Escape user-controlled values
                                    const safeHeadline = escapeHtml(item.headline || '[No headline]');
                                    // Sanitize status to alphanumeric for safe CSS class usage
                                    const safeStatusClass = (item.status || 'unknown').replace(/[^\w-]/g, '');
                                    const safeStatus = escapeHtml(item.status || 'unknown');
                                    const rawDurationSeconds = item.duration_seconds;
                                    const hasDurationValue =
                                        (typeof rawDurationSeconds === 'number' || typeof rawDurationSeconds === 'string') &&
                                        !(typeof rawDurationSeconds === 'string' && rawDurationSeconds.trim() === '');
                                    const durationSeconds = hasDurationValue ? Number(rawDurationSeconds) : NaN;
                                    const safeDurationSeconds = Number.isFinite(durationSeconds) && durationSeconds >= 0
                                        ? durationSeconds
                                        : null;
                                    return `
                                    <div class="ldr-history-item">
                                        <div class="ldr-history-item-header">
                                            <a href="/progress/${encodeURIComponent(item.research_id)}" target="_blank" rel="noopener noreferrer">
                                                ${safeHeadline} <i class="bi bi-box-arrow-up-right"></i>
                                            </a>
                                            <span class="ldr-history-date">${new Date(item.created_at).toLocaleString()}</span>
                                        </div>
                                        <div class="ldr-history-item-meta">
                                            <span class="ldr-status-badge ldr-status-${safeStatusClass}">${safeStatus}</span>
                                            ${safeDurationSeconds !== null ? `<span class="ldr-duration">${safeDurationSeconds}s</span>` : ''}
                                            ${item.topics && item.topics.length > 0 ?
                                                `<div class="ldr-topics-list">${item.topics.slice(0, 3).map(topic =>
                                                    `<span class="ldr-topic-badge">${escapeHtml(topic)}</span>`
                                                ).join('')}</div>` : ''
                                            }
                                        </div>
                                    </div>
                                `}).join('') :
                                '<p class="text-muted">No research runs yet</p>'
                            }
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing history modal if any
    const existingModal = document.getElementById('historyModal');
    if (existingModal) {
        existingModal.remove();
    }

    // Add modal to page
    // bearer:disable javascript_lang_dangerous_insert_html
    // eslint-disable-next-line no-unsanitized/method -- audited 2026-03-28: variable built from escaped/numeric values above
    document.body.insertAdjacentHTML('beforeend', modalContent);

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('historyModal'));
    modal.show();

    // Clean up when modal is hidden
    document.getElementById('historyModal').addEventListener('hidden.bs.modal', function() {
        this.remove();
    });
}

// Edit subscription redirects to dedicated form page

// Delete subscription directly from card
async function deleteSubscriptionDirect(subscriptionId) {
    const subscription = subscriptions.find(s => s.id === subscriptionId);

    if (!subscription || !confirm(`Are you sure you want to delete the subscription "${subscription.name || subscription.query}"?`)) {
        return;
    }

    try {
        const response = await fetch(`/news/api/subscriptions/${encodeURIComponent(subscriptionId)}`, {
            ...fetchOptions,
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCSRFToken()
            }
        });

        if (response.ok) {
            showAlert('Subscription deleted successfully', 'success');
            subscriptionsMutationGeneration += 1;
            subscriptions = subscriptions.filter(s => s.id !== subscriptionId);
            renderSubscriptions();
            updateStats();
            // Reload subscriptions
            await loadSubscriptions();
        } else {
            const error = await response.json();
            // showAlert renders HTML, so the server's text is escaped. A
            // not-found error repeats the subscription ID back.
            const safeError = escapeHtml(error.error || 'Failed to delete subscription');
            showAlert(safeError, 'error');
        }
    } catch (error) {
        SafeLogger.error('Error deleting subscription:', error);
        showAlert('Failed to delete subscription', 'error');
    }
}

// Update statistics
function updateStats() {
    const total = subscriptions.length;
    const active = subscriptions.filter(s => s.is_active).length;
    const paused = total - active;
    const updatedToday = subscriptions.filter(s => {
        if (!s.last_refreshed) return false;
        const lastUpdate = new Date(s.last_refreshed);
        const today = new Date();
        return lastUpdate.toDateString() === today.toDateString();
    }).length;

    document.getElementById('total-subscriptions').textContent = total;
    document.getElementById('active-subscriptions').textContent = active;
    document.getElementById('paused-subscriptions').textContent = paused;
    document.getElementById('updates-today').textContent = updatedToday;
}

// Folder management
function renderFolders() {
    const folderList = document.querySelector('.ldr-folder-list');

    // Remove existing dynamic folders first
    document.querySelectorAll('.ldr-folder-item[data-folder]:not([data-folder="all"]):not([data-folder="uncategorized"])').forEach(el => el.remove());

    const dynamicFolders = folders.map(folder => `
        <div class="ldr-folder-item" data-folder="${escapeHtml(folder.id)}">
            <i class="bi bi-folder"></i> ${escapeHtml(folder.name)}
            <span class="ldr-folder-count">${countSubscriptionsInFolder(folder.id)}</span>
        </div>
    `).join('');

    // Update counts for default folders
    document.querySelector('[data-folder="all"] .ldr-folder-count').textContent = subscriptions.length;
    document.querySelector('[data-folder="uncategorized"] .ldr-folder-count').textContent =
        subscriptions.filter(s => !s.folder_id).length;

    // Insert dynamic folders after uncategorized
    const uncategorizedFolder = document.querySelector('[data-folder="uncategorized"]');
    if (dynamicFolders) {
        // bearer:disable javascript_lang_dangerous_insert_html
        // eslint-disable-next-line no-unsanitized/method -- audited 2026-03-28: variable built from escaped/numeric values above
        uncategorizedFolder.insertAdjacentHTML('afterend', dynamicFolders);
    }

    // Folder dropdowns now handled by dedicated form pages
}

function countSubscriptionsInFolder(folderId) {
    return subscriptions.filter(s => s.folder_id === folderId).length;
}

// Jitter info loading removed - now handled by dedicated form pages

function selectFolder(folderId) {
    // Update active state
    document.querySelectorAll('.ldr-folder-item').forEach(item => {
        item.classList.toggle('active', item.dataset.folder === folderId);
    });

    currentFilter.folder = folderId;
    renderSubscriptions();
}

async function createNewFolder() {
    const name = prompt('Enter folder name:');
    if (!name || !name.trim()) return;

    try {
        const response = await fetch('/news/api/subscription/folders', {
            ...fetchOptions,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': getCSRFToken()
            },
            body: JSON.stringify({
                name: name.trim()
            })
        });

        if (response.ok) {
            const folder = await response.json();
            // showAlert renders HTML, so the folder name is escaped to show
            // as text.
            const safeFolderName = escapeHtml(folder.name);
            showAlert(`Folder "${safeFolderName}" created successfully!`, 'success');

            // Reload folders
            await loadFolders();

            // Re-render subscriptions to update folder badges
            renderSubscriptions();
        } else {
            const error = await response.json();
            if (response.status === 409) {
                showAlert('A folder with that name already exists', 'warning');
            } else {
                // showAlert renders HTML, so the server's text is escaped.
                const safeError = escapeHtml(error.error || 'Failed to create folder');
                showAlert(safeError, 'error');
            }
        }
    } catch (error) {
        SafeLogger.error('Error creating folder:', error);
        showAlert('Failed to create folder', 'error');
    }
}

// Utility functions
function getCurrentUserId() {
    return localStorage.getItem('userId') || 'anonymous';
}

function getCSRFToken() {
    return window.api ? window.api.getCsrfToken() : '';
}

function getFolderName(folderId) {
    const folder = folders.find(f => f.id === folderId);
    return folder ? folder.name : 'Unknown';
}

function showAlert(message, type) {
    // Simple alert implementation
    const alertDiv = document.createElement('div');
    const alertType = window.LdrAlertHelpers.mapAlertType(type);
    alertDiv.className = `alert alert-${alertType} alert-dismissible fade show`;
    // The message is HTML. Sanitizing keeps safe tags (links, lists) and
    // strips dangerous ones. Unlike the showAlert in services/ui.js, this one
    // does not escape. Callers therefore escape every value that comes from
    // the API (subscription fields, folder names, server error text) or reduce
    // it to safe characters (the research ID in the progress link), so no API
    // value adds markup of its own. They escape into a variable first: the
    // check-double-escaping hook assumes every showAlert escapes and flags
    // escapeHtml() written inside the call.
    // SAFE_FOR_TEMPLATES: false overrides SANITIZE_CONFIG's default of true.
    // With it on, DOMPurify blanks a text node from any `{{`, `<%` or `${` to
    // its end, and from its start through any `}}` or `%>`. Escaped server
    // error text often contains these (nested JSON error bodies, shell-style
    // examples). The option only matters when a client-side template engine
    // reads the page, and none does. SANITIZE_CONFIG's ALLOW_DATA_ATTR: false
    // still strips data-* attributes from the message.
    // bearer:disable javascript_lang_dangerous_insert_html
    /* eslint-disable no-unsanitized/property -- window.sanitizeHtml is an allowlisted escape method in eslint.config.js; the plugin does not special-case a ConditionalExpression callee, so this stays suppressed the same way the LogicalExpression form it replaces was (audited 2026-03-28; github.com/mozilla/eslint-plugin-no-unsanitized/issues/263) */
    alertDiv.innerHTML = `
        ${window.sanitizeHtml ? window.sanitizeHtml(message, { SAFE_FOR_TEMPLATES: false }) : escapeHtml(message)}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    /* eslint-enable no-unsanitized/property */

    const container = document.querySelector('.ldr-page-header');
    container.insertAdjacentElement('afterend', alertDiv);

    // Auto-dismiss after 5 seconds
    setTimeout(() => alertDiv.remove(), 5000);
}

// Scheduler status functions
async function checkSchedulerStatus() {
    const statusIndicator = document.getElementById('status-indicator');
    const statusText = document.getElementById('status-text');
    const schedulerDetails = document.getElementById('scheduler-details');

    // Set checking state
    statusIndicator.className = 'ldr-status-indicator ldr-checking';
    statusText.textContent = 'Checking...';

    try {
        const response = await fetch('/news/api/scheduler/status', fetchOptions);
        if (response.ok) {
            const data = await response.json();

            if (data.scheduler_available) {
                if (data.is_running) {
                    // Check if user is tracked
                    if (data.active_users && data.active_users > 0) {
                        statusIndicator.className = 'ldr-status-indicator active';
                        statusText.textContent = 'Active';
                        schedulerDetails.textContent = `${data.active_users} active users, ${data.scheduled_jobs || 0} scheduled jobs`;
                    } else {
                        statusIndicator.className = 'ldr-status-indicator ldr-inactive';
                        statusText.textContent = 'Not Tracking Your Session';
                        schedulerDetails.innerHTML = `Log out and log back in to activate automatic scheduling. <a href="#" ${window.LDRTemplateEvents.attributes('ldr-8b7c364b086d')}>Learn more</a>`;
                    }
                } else {
                    statusIndicator.className = 'ldr-status-indicator ldr-inactive';
                    statusText.textContent = 'Stopped';
                    schedulerDetails.textContent = 'Auto-refresh is disabled. Set LDR_NEWS_SCHEDULER_ALLOW_API_CONTROL=true to enable manual control.';
                }
            } else {
                statusIndicator.className = 'ldr-status-indicator ldr-inactive';
                statusText.textContent = 'Not Available';
                schedulerDetails.textContent = 'Install APScheduler: pip install apscheduler';
            }
        } else {
            throw new Error('Failed to check scheduler status');
        }
    } catch (error) {
        SafeLogger.error('Error checking scheduler status:', error);
        statusIndicator.className = 'ldr-status-indicator ldr-inactive';
        statusText.textContent = 'Error';
        schedulerDetails.textContent = 'Unable to check scheduler status';
    }

}

// Show scheduler information
function showSchedulerInfo() {
    showAlert(`
        <h6>About the Subscription Scheduler</h6>
        <p>The scheduler runs your subscriptions automatically in the background:</p>
        <ul>
            <li>Your subscriptions are stored in an encrypted database</li>
            <li>When you log in, the scheduler securely stores access for 48 hours</li>
            <li>Subscriptions run automatically based on their schedule</li>
            <li>You don't need to stay logged in - the scheduler works in the background</li>
            <li>Any overdue subscriptions will run shortly after login</li>
        </ul>
        <p>The scheduler will continue running subscriptions for 48 hours after your last login. Simply log in periodically to keep it active.</p>
    `, 'info');
}

// handleSubscriptionCardAction calls the card actions directly, so nothing
// on the page reaches them through window. Only the scheduler notice's
// constant inline "Learn more" handler still resolves a function through
// window: showSchedulerInfo. Assigning it explicitly keeps that handler
// working if this file is later loaded as a module. The card actions stay on
// window so tests can drive the real page runtime.
window.runSubscriptionNow = runSubscriptionNow;
window.toggleSubscription = toggleSubscription;
window.viewSubscriptionHistory = viewSubscriptionHistory;
window.deleteSubscriptionDirect = deleteSubscriptionDirect;
window.showSchedulerInfo = showSchedulerInfo;

// Exposed on window so vitest can exercise the pure formatting helper
// without standing up the full subscriptions page DOM.
window.formatNextUpdate = formatNextUpdate;