{% extends "base.html" %}
{% from "components/help_macros.html" import tooltip, help_panel, help_step, help_tip %}

{% block title %}Download Manager{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="/static/css/download_manager.css">
<link rel="stylesheet" href="/static/css/components/pagination.css">
{% endblock %}

{% block content %}
<div class="ldr-download-manager-container">
    <div class="ldr-manager-header">
        <h1>Download Manager</h1>
        <div class="ldr-header-actions">
            <div class="ldr-btn-group" style="margin-right: 15px;">
                <button class="btn btn-success" onclick="downloadAllNew()"
                        {% if not enable_pdf_storage %}
                        disabled
                        title="PDF storage is disabled. Click the storage mode button to enable."
                        {% else %}
                        title="Download PDF files from all your research sources and save to library"
                        {% endif %}>
                    <i aria-hidden="true" class="fas fa-file-pdf"></i> Get All Research PDFs
                </button>
                <button class="btn btn-info" onclick="downloadAllAsText()"
                        title="Extract text from all research sources without saving PDF files">
                    <i aria-hidden="true" class="fas fa-file-alt"></i> Text Only (from PDFs)
                </button>
            </div>
            <div class="ldr-collection-selector" style="margin: 0 15px;">
                <label for="target-collection" style="font-size: 0.9em; color: var(--text-secondary); margin-right: 8px;">
                    <i aria-hidden="true" class="fas fa-folder"></i> Target Collection:
                </label>
                <select id="target-collection" class="form-control" style="width: 200px; display: inline-block;">
                    <option value="">Loading collections...</option>
                </select>
            </div>
            <div class="ldr-btn-group ldr-download-buttons">
                <button class="btn btn-success" id="download-pdfs" disabled
                        {% if not enable_pdf_storage %}
                        title="PDF storage is disabled. Click the storage mode button to enable."
                        {% else %}
                        title="Download PDF files and save to library"
                        {% endif %}>
                    <i aria-hidden="true" class="fas fa-file-pdf"></i> Get PDFs (<span class="ldr-selected-count-pdf">0</span>)
                </button>
                <button class="btn btn-info" id="download-text-db" disabled
                        title="Extract text without saving PDF files">
                    <i aria-hidden="true" class="fas fa-file-alt"></i> Text Only (<span class="ldr-selected-count-text-db">0</span>)
                </button>
            </div>
        </div>
    </div>

    <!-- Download Manager Help Panel -->
    {% call help_panel('download-how', 'Using the Download Manager', icon='download', collapsed=true, dismissible=true) %}
    <div class="ldr-help-steps">
        {{ help_step(1, "Source Tracking", "Research sessions automatically track all cited sources (PDFs, papers, articles).") }}
        {{ help_step(2, "Bulk Download", "Select multiple research sessions and download all their PDFs at once.") }}
        {{ help_step(3, "Text Only Option", "Extract just the text without saving PDFs. Saves storage while keeping content searchable.") }}
        {{ help_step(4, "Target Collection", "Choose which collection to add downloaded documents to for organized searching.") }}
    </div>
    {{ help_tip("<strong>Tip:</strong> Use 'Text Only' for initial exploration, then download PDFs for papers you want to keep permanently.") }}
    {% endcall %}

    <!-- Library Storage Settings Info -->
    <div class="ldr-library-settings-info">
        <div class="ldr-info-banner">
            <div class="ldr-info-icon">
                <i aria-hidden="true" class="fas fa-info-circle"></i>
            </div>
            <div class="ldr-info-content">
                <h4>Library Storage Settings</h4>
                {% if pdf_storage_mode == 'database' %}
                <button class="ldr-storage-mode-btn ldr-info-message" onclick="showStorageModeModal()" title="Click to change storage mode">
                    <i aria-hidden="true" class="fas fa-database"></i>
                    <strong>PDF Storage: Encrypted Database</strong> - PDFs encrypted in your personal database. Portable, isolated per-user.
                    <i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>
                </button>
                {% elif pdf_storage_mode == 'filesystem' %}
                <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">
                    <i aria-hidden="true" class="fas fa-hdd"></i>
                    <strong>PDF Storage: Filesystem</strong> - PDFs saved unencrypted to disk. Faster for large files.
                    <i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>
                </button>
                {% else %}
                <button class="ldr-storage-mode-btn ldr-warning-message" onclick="showStorageModeModal()" title="Click to change storage mode">
                    <i aria-hidden="true" class="fas fa-file-alt"></i>
                    <strong>PDF Storage: Text Only</strong> - Only extracted text stored. Re-download PDFs when needed.
                    <i aria-hidden="true" class="fas fa-pen" style="margin-left: 8px; opacity: 0.6; font-size: 0.85em;"></i>
                </button>
                {% endif %}

                <p class="ldr-info-message">
                    <i aria-hidden="true" class="fas fa-lock"></i>
                    Text content is always stored in the encrypted database.
                </p>

                {% if shared_library %}
                <p class="ldr-warning-message">
                    <i aria-hidden="true" class="fas fa-users"></i>
                    <strong>Shared Library Mode:</strong> All users share the same library directory.
                </p>
                {% endif %}

                <a href="/settings#research-library" class="btn btn-sm btn-outline-primary ldr-settings-link">
                    <i aria-hidden="true" class="fas fa-cog"></i> Configure Library Settings
                </a>
            </div>
        </div>
    </div>

    <!-- Summary Stats -->
    <div class="ldr-summary-stats">
        <div class="ldr-stat-card">
            <h3>{{ total_researches }}</h3>
            <p>Total Research Sessions</p>
        </div>
        <div class="ldr-stat-card">
            <h3>{{ total_resources }}</h3>
            <p>Total Resources</p>
        </div>
        <div class="ldr-stat-card">
            <h3>{{ already_downloaded }}</h3>
            <p>Already Downloaded</p>
        </div>
        <div class="ldr-stat-card">
            <h3>{{ available_to_download }}</h3>
            <p>Available to Download</p>
        </div>
    </div>

    <!-- Filters -->
    <div class="ldr-filters-section">
        <div class="ldr-filter-row">
            <div class="ldr-filter-group">
                <label>Research Mode</label>
                <select id="filter-mode" class="form-control">
                    <option value="">All Modes</option>
                    <option value="quick">Quick</option>
                    <option value="detailed">Detailed</option>
                </select>
            </div>

            <div class="ldr-filter-group ldr-date-range">
                <label>Date Range</label>
                <div class="ldr-date-inputs">
                    <input type="date" id="filter-from" class="form-control" placeholder="From">
                    <span class="ldr-date-separator">to</span>
                    <input type="date" id="filter-to" class="form-control" placeholder="To">
                </div>
            </div>

            <div class="ldr-filter-group">
                <label>Rating</label>
                <select id="filter-rating" class="form-control">
                    <option value="">All Ratings</option>
                    <option value="5">⭐⭐⭐⭐⭐ 5 Stars</option>
                    <option value="4">⭐⭐⭐⭐ 4+ Stars</option>
                    <option value="3">⭐⭐⭐ 3+ Stars</option>
                </select>
            </div>

            <div class="ldr-filter-group">
                <label>PDF Status</label>
                <select id="filter-pdfs" class="form-control">
                    <option value="">All Research</option>
                    <option value="yes">Has PDFs</option>
                    <option value="no">No PDFs</option>
                </select>
            </div>

            <div class="ldr-filter-group ldr-search-group">
                <label>Search</label>
                <div class="ldr-search-wrapper">
                    <i aria-hidden="true" class="fas fa-search"></i>
                    <input type="text" id="search-research" class="form-control"
                           placeholder="Search titles or queries...">
                </div>
            </div>
        </div>

        <div class="ldr-bulk-actions">
            <button class="ldr-btn-bulk" onclick="selectAll()">Select All</button>
            <button class="ldr-btn-bulk" onclick="selectNone()">Select None</button>
            <button class="ldr-btn-bulk" onclick="selectFiltered()">Select Filtered</button>
        </div>
    </div>

    <!-- Research List -->
    <div class="ldr-research-list">
        {% for research in research_list %}
        <div class="ldr-research-item" data-id="{{ research.id }}"
             data-mode="{{ research.mode }}"
             data-rating="{{ research.rating or 0 }}"
             data-date="{{ research.created_at }}"
             data-downloadable="{{ research.downloadable_count }}"
             data-downloaded="{{ research.downloaded_count }}">

            <!-- Checkbox and Basic Info -->
            <div class="ldr-research-header">
                <input type="checkbox" class="ldr-research-select" value="{{ research.id }}"
                       data-resources="{{ research.total_resources }}"
                       data-downloadable="{{ research.downloadable_count }}">

                <div class="ldr-research-info">
                    <h3>{{ research.title or research.query[:80] }}</h3>
                    <div class="ldr-research-meta">
                        <span class="ldr-meta-item">
                            <i aria-hidden="true" class="fas fa-calendar"></i> <span class="ldr-research-date" data-date="{{ research.created_at }}">{{ research.created_at }}</span>
                        </span>
                        <span class="ldr-meta-item">
                            <i aria-hidden="true" class="fas fa-clock"></i> <span class="ldr-research-duration" data-seconds="{{ research.duration_seconds }}">{{ research.duration_seconds }}s</span>
                        </span>
                        <span class="ldr-meta-item ldr-mode-badge {{ research.mode }}">
                            {{ research.mode|replace('_', ' ')|title }}
                        </span>
                        {% if research.rating %}
                        <span class="ldr-meta-item">
                            <i aria-hidden="true" class="fas fa-star"></i> {{ research.rating }}/5
                        </span>
                        {% endif %}
                        {% if research.total_cost %}
                        <span class="ldr-meta-item">
                            <i aria-hidden="true" class="fas fa-dollar-sign"></i> {{ research.total_cost|round(3) }}
                        </span>
                        {% endif %}
                    </div>
                </div>

                <div class="ldr-research-stats">
                    <div class="ldr-stat">
                        <strong>{{ research.total_resources }}</strong>
                        <small>Total Sources</small>
                    </div>
                    <div class="ldr-stat">
                        <strong>{{ research.downloadable_count }}</strong>
                        <small>PDFs Available</small>
                    </div>
                    <div class="ldr-stat {{ 'ldr-success' if research.downloaded_count > 0 else '' }}">
                        <strong>{{ research.downloaded_count }}</strong>
                        <small>Downloaded</small>
                    </div>
                </div>
            </div>

            <!-- Expandable Details -->
            <details class="ldr-research-details">
                <summary>
                    View Sources ({{ research.total_resources }})
                    <div class="ldr-domain-preview">
                        {% for domain, count in research.top_domains[:5] %}
                        <span class="ldr-domain-chip">{{ domain }} ({{ count }})</span>
                        {% endfor %}
                    </div>
                </summary>

                <div class="ldr-sources-breakdown">
                    <!-- Domain breakdown -->
                    <div class="ldr-breakdown-section">
                        <h4>Sources by Domain</h4>
                        <div class="ldr-domain-list">
                            {% for domain, info in research.domains.items() %}
                            <div class="ldr-domain-item">
                                <span class="ldr-domain-name">{{ domain }}</span>
                                <span class="ldr-domain-stats">
                                    {{ info.total }} total |
                                    {{ info.pdfs }} PDFs |
                                    {{ info.downloaded }} downloaded
                                </span>
                            </div>
                            {% endfor %}
                        </div>
                    </div>

                    <!-- Individual sources preview -->
                    <div class="ldr-breakdown-section">
                        <h4>Downloadable PDFs</h4>
                        <div class="ldr-source-list">
                            {% for source in research.pdf_sources[:10] %}
                            <div class="ldr-source-item">
                                <i aria-hidden="true" class="fas fa-file-pdf"></i>
                                <span class="ldr-source-title">{{ source.document_title|truncate(60) }}</span>
                                <span class="ldr-source-domain">{{ source.domain }}</span>
                                {% if source.download_status == 'completed' %}
                                <span class="ldr-badge ldr-badge-success">Downloaded</span>
                                {% endif %}
                            </div>
                            {% endfor %}
                            {% if research.pdf_sources|length > 10 %}
                            <div class="ldr-source-item ldr-more">
                                ... and {{ research.pdf_sources|length - 10 }} more PDFs
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </details>

            <!-- Action Buttons -->
            <div class="ldr-research-actions">
                <button class="btn btn-sm" onclick="viewResearch('{{ research.id }}')">
                    <i aria-hidden="true" class="fas fa-eye"></i> View Research
                </button>
                <button class="btn btn-sm btn-success"
                        onclick="downloadResearch('{{ research.id }}', 'pdf')"
                        {% if not enable_pdf_storage %}
                        disabled
                        title="PDF downloads are disabled. Enable PDF storage in Settings"
                        {% else %}
                        title="Download PDFs from this research"
                        {% endif %}>
                    <i aria-hidden="true" class="fas fa-file-pdf"></i> PDFs
                </button>
                <button class="btn btn-sm btn-info"
                        onclick="downloadResearch('{{ research.id }}', 'text_only')"
                        title="Extract text from this research without saving PDF files">
                    <i aria-hidden="true" class="fas fa-file-alt"></i> Text Only
                </button>
                {% if research.downloaded_count > 0 %}
                <button class="btn btn-sm" onclick="viewDownloaded('{{ research.id }}')">
                    <i aria-hidden="true" class="fas fa-folder-open"></i> View Downloaded
                </button>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Pagination -->
    {% if total_pages > 1 %}
    <nav class="ldr-pagination" aria-label="Research list pagination">
        <a class="ldr-page-link {% if page <= 1 %}disabled{% endif %}"
           href="?page={{ page - 1 }}"
           {% if page <= 1 %}tabindex="-1" aria-disabled="true"{% endif %}>
            <i aria-hidden="true" class="fas fa-chevron-left"></i> Previous
        </a>

        {% set start_page = [1, page - 2] | max %}
        {% set end_page = [total_pages, page + 2] | min %}

        {% if start_page > 1 %}
        <a class="ldr-page-link" href="?page=1">1</a>
        {% if start_page > 2 %}<span class="ldr-page-ellipsis">&hellip;</span>{% endif %}
        {% endif %}

        {% for p in range(start_page, end_page + 1) %}
        <a class="ldr-page-link {% if p == page %}active{% endif %}" href="?page={{ p }}">{{ p }}</a>
        {% endfor %}

        {% if end_page < total_pages %}
        {% if end_page < total_pages - 1 %}<span class="ldr-page-ellipsis">&hellip;</span>{% endif %}
        <a class="ldr-page-link" href="?page={{ total_pages }}">{{ total_pages }}</a>
        {% endif %}

        <a class="ldr-page-link {% if page >= total_pages %}disabled{% endif %}"
           href="?page={{ page + 1 }}"
           {% if page >= total_pages %}tabindex="-1" aria-disabled="true"{% endif %}>
            Next <i aria-hidden="true" class="fas fa-chevron-right"></i>
        </a>
    </nav>
    {% endif %}

    <!-- Download Progress Modal -->
    <div id="download-progress-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Download Progress</h2>
            </div>
            <div class="modal-body">
                <div class="ldr-overall-progress">
                    <div class="ldr-progress-bar">
                        <div class="ldr-progress-fill" id="overall-progress" style="width: 0%"></div>
                    </div>
                    <p>
                        <span id="current-count">0</span> / <span id="total-count">0</span> files
                        <span class="ldr-status-breakdown" style="display:none;">
                            (<span id="succeeded-count">0</span> succeeded,
                            <span id="skipped-count">0</span> skipped,
                            <span id="failed-count">0</span> failed)
                        </span>
                    </p>
                </div>

                <div class="ldr-download-log" id="download-log">
                    <!-- Download entries will be added here -->
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeProgressModal()">Close</button>
                <button class="btn btn-danger" onclick="cancelDownloads()">Cancel</button>
            </div>
        </div>
    </div>

    {% include 'components/storage_mode_modal.html' %}
</div>

<script>
let selectedResearches = new Set();

// Per-status counters for the download progress breakdown.
// Reset in resetStatusCounts() at the start of each bulk download.
let statusCounts = {succeeded: 0, skipped: 0, failed: 0};

function resetStatusCounts() {
    statusCounts = {succeeded: 0, skipped: 0, failed: 0};
    const breakdown = document.querySelector('.ldr-status-breakdown');
    if (breakdown) breakdown.style.display = 'none';
    document.getElementById('succeeded-count').textContent = '0';
    document.getElementById('skipped-count').textContent = '0';
    document.getElementById('failed-count').textContent = '0';
}

// Aggregate a single item's SSE status into the succeeded/skipped/failed
// breakdown and reveal the breakdown span once anything has been processed.
// Shared by both progress loops (file download -> updateProgress, text
// extraction -> updateTextExtractionProgress). The text-extraction backend
// only emits "success"/"failed", so the "skipped" bucket stays 0 there.
function recordStatus(status) {
    if (status === 'success') {
        statusCounts.succeeded++;
    } else if (status === 'skipped') {
        statusCounts.skipped++;
    } else if (status === 'failed' || status === 'error') {
        statusCounts.failed++;
    } else {
        return;
    }
    document.getElementById('succeeded-count').textContent = statusCounts.succeeded;
    document.getElementById('skipped-count').textContent = statusCounts.skipped;
    document.getElementById('failed-count').textContent = statusCounts.failed;

    const total = statusCounts.succeeded + statusCounts.skipped + statusCounts.failed;
    const breakdown = document.querySelector('.ldr-status-breakdown');
    if (breakdown && total > 0) {
        breakdown.style.display = '';
    }
}

// Load collections for dropdown
async function loadCollections() {
    try {
        const response = await fetch('/library/api/collections/list');
        const data = await response.json();

        const select = document.getElementById('target-collection');
        select.innerHTML = ''; // Clear loading message

        if (data.success && data.collections && data.collections.length > 0) {
            data.collections.forEach(collection => {
                const option = document.createElement('option');
                option.value = collection.id;
                option.textContent = collection.name;

                // Select "Library" as default if it exists
                if (collection.name === 'Library') {
                    option.selected = true;
                }

                select.appendChild(option);
            });
        } else {
            // Fallback if no collections
            const option = document.createElement('option');
            option.value = '';
            option.textContent = 'No collections available';
            select.appendChild(option);
        }
    } catch (error) {
        console.error('Error loading collections:', error);
        const select = document.getElementById('target-collection');
        select.innerHTML = '<option value="">Error loading collections</option>';
    }
}

// Load collections on page load
loadCollections();

// Handle checkbox selection
document.querySelectorAll('.ldr-research-select').forEach(checkbox => {
    checkbox.addEventListener('change', (e) => {
        const researchId = e.target.value;
        const item = e.target.closest('.ldr-research-item');

        if (e.target.checked) {
            selectedResearches.add(researchId);
            item.classList.add('ldr-selected');
        } else {
            selectedResearches.delete(researchId);
            item.classList.remove('ldr-selected');
        }

        updateSelectedCount();
    });
});

function updateSelectedCount() {
    const count = selectedResearches.size;

    // Update all count displays
    document.querySelectorAll('.ldr-selected-count-pdf, .ldr-selected-count-text-db').forEach(el => {
        el.textContent = count;
    });

    // Enable/disable buttons based on count and settings
    const pdfBtn = document.getElementById('download-pdfs');
    const textDbBtn = document.getElementById('download-text-db');

    if (pdfBtn) {
        pdfBtn.disabled = count === 0 {% if not enable_pdf_storage %}|| true{% endif %};
    }
    if (textDbBtn) {
        textDbBtn.disabled = count === 0;
    }
}

// Bulk selection
function selectAll() {
    document.querySelectorAll('.ldr-research-select').forEach(cb => {
        cb.checked = true;
        cb.dispatchEvent(new Event('change'));
    });
}

function selectNone() {
    document.querySelectorAll('.ldr-research-select').forEach(cb => {
        cb.checked = false;
        cb.dispatchEvent(new Event('change'));
    });
}

function selectFiltered() {
    document.querySelectorAll('.ldr-research-item:not([style*="display: none"]) .ldr-research-select').forEach(cb => {
        cb.checked = true;
        cb.dispatchEvent(new Event('change'));
    });
}

// Download functions
document.getElementById('download-pdfs')?.addEventListener('click', () => {
    if (selectedResearches.size === 0) return;
    document.getElementById('download-progress-modal').style.display = 'block';
    startBulkDownload(Array.from(selectedResearches), 'pdf');
});

document.getElementById('download-text-db')?.addEventListener('click', () => {
    if (selectedResearches.size === 0) return;
    document.getElementById('download-progress-modal').style.display = 'block';
    startBulkDownload(Array.from(selectedResearches), 'text_only');
});

let currentDownloadController = null;

async function startBulkDownload(researchIds, mode = 'pdf') {
    // Reset per-status counters + breakdown for this run.
    resetStatusCounts();

    // Get CSRF token from meta tag
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    // Get selected collection_id
    const collectionSelect = document.getElementById('target-collection');
    const collectionId = collectionSelect ? collectionSelect.value : null;

    // Create abort controller for cancellation
    currentDownloadController = new AbortController();

    // Set modal title based on mode
    const modalTitles = {
        'pdf': 'Downloading PDFs',
        'text_only': 'Extracting Text to Database'
    };
    document.querySelector('#download-progress-modal h2').textContent = modalTitles[mode] || 'Processing';

    try {
        const requestBody = {
            research_ids: researchIds,
            mode: mode
        };

        // Add collection_id if selected
        if (collectionId) {
            requestBody.collection_id = collectionId;
        }

        const response = await fetch('/library/api/download-bulk', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify(requestBody),
            signal: currentDownloadController.signal
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = JSON.parse(line.slice(6));
                    updateProgress(data);

                    // Check if download is complete
                    if (handleSSECompletion(data, () => location.reload())) {
                        currentDownloadController = null;
                    }
                }
            }
        }
    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('Download cancelled by user');
            const log = document.getElementById('download-log');
            const entry = document.createElement('div');
            entry.className = 'ldr-download-entry ldr-cancelled';
            entry.innerHTML = '<strong>Download cancelled by user</strong>';
            log.appendChild(entry);
        } else {
            console.error('Download error:', error);
        }
    } finally {
        currentDownloadController = null;
    }
}

function updateProgress(data) {
    const progressBar = document.getElementById('overall-progress');
    const currentCount = document.getElementById('current-count');
    const totalCount = document.getElementById('total-count');
    const log = document.getElementById('download-log');

    progressBar.style.width = `${data.progress}%`;
    progressBar.setAttribute('data-percent', `${data.progress}%`);
    currentCount.textContent = data.current;
    totalCount.textContent = data.total;

    // Aggregate per-item status into the succeeded/skipped/failed breakdown.
    recordStatus(data.status);

    if (data.file) {
        const entry = document.createElement('div');
        entry.className = `ldr-download-entry ldr-${data.status}`;
        entry.innerHTML = `
            <strong>${window.escapeHtml(data.file)}</strong>
            <span>${window.escapeHtml(data.status)}</span>
            ${data.error ? `<span class="ldr-error">${window.escapeHtml(data.error)}</span>` : ''}
        `;
        log.appendChild(entry);
        log.scrollTop = log.scrollHeight;
    }
}

// Individual research download
function downloadResearch(researchId, mode = 'pdf') {
    document.getElementById('download-progress-modal').style.display = 'block';
    startBulkDownload([researchId], mode);
}

// Navigation
function viewResearch(researchId) {
    window.open(`/results/${researchId}`, '_blank');
}

function viewDownloaded(researchId) {
    window.location.href = `/library?research=${researchId}`;
}

// Filters
document.getElementById('filter-mode').addEventListener('change', filterResearch);
document.getElementById('filter-rating').addEventListener('change', filterResearch);
document.getElementById('filter-pdfs').addEventListener('change', filterResearch);
document.getElementById('search-research').addEventListener('input', filterResearch);

function filterResearch() {
    const mode = document.getElementById('filter-mode').value;
    const rating = document.getElementById('filter-rating').value;
    const pdfFilter = document.getElementById('filter-pdfs').value;
    const search = document.getElementById('search-research').value.toLowerCase();

    document.querySelectorAll('.ldr-research-item').forEach(item => {
        let show = true;

        if (mode && item.dataset.mode !== mode) show = false;
        if (rating && parseInt(item.dataset.rating) < parseInt(rating)) show = false;

        // Handle PDF filter
        if (pdfFilter) {
            const downloadable = parseInt(item.dataset.downloadable || 0);
            const downloaded = parseInt(item.dataset.downloaded || 0);
            const availablePdfs = downloadable - downloaded;

            if (pdfFilter === 'yes' && availablePdfs <= 0) show = false;
            if (pdfFilter === 'no' && availablePdfs > 0) show = false;
        }

        if (search && !item.textContent.toLowerCase().includes(search)) show = false;

        item.style.display = show ? '' : 'none';
    });
}

// Close modal
function closeProgressModal() {
    document.getElementById('download-progress-modal').style.display = 'none';
}

// Cancel downloads
function cancelDownloads() {
    if (currentDownloadController) {
        currentDownloadController.abort();
        currentDownloadController = null;

        // Update UI to show cancellation
        const progressBar = document.getElementById('overall-progress');
        progressBar.classList.add('ldr-cancelled');

        // Add cancellation message
        const log = document.getElementById('download-log');
        const entry = document.createElement('div');
        entry.className = 'ldr-download-entry ldr-cancelled';
        entry.innerHTML = '<strong class="ldr-error-text">Download process cancelled</strong>';
        log.appendChild(entry);

        // Close modal after a delay
        setTimeout(() => {
            closeProgressModal();
            location.reload();
        }, 1500);
    } else {
        // If no active download, just close modal
        closeProgressModal();
    }
}

// Download ALL PDFs function
async function downloadAllNew() {
    const btn = event.target.closest('button');
    const originalContent = btn.innerHTML;
    btn.innerHTML = '<i aria-hidden="true" class="fas fa-spinner fa-spin"></i> Preparing...';
    btn.disabled = true;

    try {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

        // First, queue all undownloaded articles
        const queueResponse = await fetch('/library/api/queue-all-undownloaded', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            }
        });

        if (!queueResponse.ok) {
            throw new Error(`HTTP error! status: ${queueResponse.status}`);
        }

        const queueResult = await queueResponse.json();

        if (queueResult.queued === 0) {
            alert('No new articles to download. All available articles have already been downloaded.');
            btn.innerHTML = originalContent;
            btn.disabled = false;
            return;
        }

        // Show progress modal
        document.getElementById('download-progress-modal').style.display = 'block';
        document.querySelector('#download-progress-modal h2').textContent = 'Downloading ALL PDFs';

        // Reset progress
        document.getElementById('overall-progress').style.width = '0%';
        document.getElementById('current-count').textContent = '0';
        document.getElementById('total-count').textContent = queueResult.queued;
        document.getElementById('download-log').innerHTML = '';
        resetStatusCounts();

        btn.innerHTML = originalContent;
        btn.disabled = false;

        // Create abort controller
        currentDownloadController = new AbortController();

        // Start streaming download
        const downloadResponse = await fetch('/library/api/download-bulk', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({research_ids: queueResult.research_ids || []}),
            signal: currentDownloadController.signal
        });

        const reader = downloadResponse.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = JSON.parse(line.slice(6));
                    updateProgress(data);

                    if (handleSSECompletion(data, () => location.reload())) {
                        currentDownloadController = null;
                    }
                }
            }
        }

    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('Download cancelled by user');
        } else {
            console.error('Failed to start downloads:', error);
            alert('Failed to start downloads. Please try again.');
        }
        btn.innerHTML = originalContent;
        btn.disabled = false;
    } finally {
        currentDownloadController = null;
    }
}

// Extract ALL Text function
async function downloadAllAsText() {
    const btn = event.target.closest('button');
    const originalContent = btn.innerHTML;
    btn.innerHTML = '<i aria-hidden="true" class="fas fa-spinner fa-spin"></i> Extracting...';
    btn.disabled = true;

    try {
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

        // Show progress modal
        document.getElementById('download-progress-modal').style.display = 'block';
        document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction to Database';

        // Reset progress
        document.getElementById('overall-progress').style.width = '0%';
        document.getElementById('current-count').textContent = '0';
        document.getElementById('total-count').textContent = '0';
        document.getElementById('download-log').innerHTML = '';
        resetStatusCounts();

        currentDownloadController = new AbortController();

        const response = await fetch('/library/api/download-all-text', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({}),
            signal: currentDownloadController.signal
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const {done, value} = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n');

            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = JSON.parse(line.slice(6));
                    updateTextExtractionProgress(data);

                    if (handleSSECompletion(data, (d) => alert(`Text extraction complete! Extracted ${d.total} documents to encrypted database.`))) {
                        currentDownloadController = null;
                    }
                }
            }
        }

    } catch (error) {
        if (error.name === 'AbortError') {
            console.log('Text extraction cancelled by user');
        } else {
            console.error('Failed to start text extraction:', error);
            alert('Failed to start text extraction. Please try again.');
        }
    } finally {
        btn.innerHTML = originalContent;
        btn.disabled = false;
        currentDownloadController = null;
    }
}

// Update text extraction progress
function updateTextExtractionProgress(data) {
    const progressBar = document.getElementById('overall-progress');
    const currentCount = document.getElementById('current-count');
    const totalCount = document.getElementById('total-count');
    const log = document.getElementById('download-log');

    progressBar.style.width = `${data.progress}%`;
    currentCount.textContent = data.current;
    totalCount.textContent = data.total;

    // Same succeeded/skipped/failed breakdown as the file-download loop
    // (text extraction emits success/failed only).
    recordStatus(data.status);

    if (data.file) {
        const entry = document.createElement('div');
        entry.className = `ldr-download-entry ldr-${data.status}`;

        let statusIcon = data.status === 'success' ? '✓' : '✗';
        let statusText = data.status === 'success' ? 'Text extracted' : (data.error || 'Extraction failed');

        entry.innerHTML = `
            <span class="ldr-status-icon">${statusIcon}</span>
            <div class="ldr-entry-details">
                <strong>${window.escapeHtml(data.file)}</strong>
                <span class="ldr-status-text">${window.escapeHtml(statusText)}</span>
            </div>
        `;

        log.appendChild(entry);
        log.scrollTop = log.scrollHeight;
    }
}

// Format dates and durations on page load
document.addEventListener('DOMContentLoaded', function() {
    // Format dates
    document.querySelectorAll('.ldr-research-date').forEach(span => {
        const dateStr = span.dataset.date;
        if (dateStr) {
            const date = new Date(dateStr);
            if (!isNaN(date)) {
                span.textContent = date.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric'
                });
            }
        }
    });

    // Format durations
    document.querySelectorAll('.ldr-research-duration').forEach(span => {
        const seconds = parseInt(span.dataset.seconds);
        if (!isNaN(seconds)) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;

            let duration = '';
            if (hours > 0) duration += hours + 'h ';
            if (minutes > 0) duration += minutes + 'm ';
            duration += secs + 's';

            span.textContent = duration;
        }
    });
});
</script>
{% endblock %}
