{% extends "base.html" %}
{% block title %}File Details{% endblock %}

{% block head_extra %}
  <!-- PDF.js library (Apache 2.0 License - compatible) -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
  <script>
    // Configure PDF.js worker
    pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
  </script>
  <style>
    .detail-container {
      max-width: 1200px;
      margin: 0 auto;
    }
    .back-button {
      display: inline-flex;
      align-items: center;
      color: #3182ce;
      text-decoration: none;
      margin-bottom: 1.5rem;
      font-weight: 600;
    }
    .back-button:hover {
      color: #2c5aa0;
    }
    .back-button i {
      margin-right: 0.5rem;
    }

    .detail-card {
      background-color: white;
      border-radius: 0.5rem;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      padding: 2rem;
      margin-bottom: 1.5rem;
    }
    .detail-card h3 {
      font-size: 1.5rem;
      font-weight: bold;
      margin-bottom: 1rem;
      color: #2d3748;
    }

    .detail-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 1.5rem;
    }
    .detail-item {
      display: flex;
      flex-direction: column;
    }
    .detail-label {
      font-weight: 600;
      color: #4a5568;
      margin-bottom: 0.25rem;
      font-size: 0.875rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }
    .detail-value {
      color: #2d3748;
      font-size: 1rem;
      word-break: break-word;
    }

    /* Status badges */
    .status-badge {
      display: inline-block;
      padding: 0.5rem 1rem;
      border-radius: 9999px;
      font-size: 1rem;
      font-weight: 600;
      text-align: center;
    }
    .status-pending {
      background-color: #FEF3C7;
      color: #92400E;
    }
    .status-processing {
      background-color: #DBEAFE;
      color: #1E3A8A;
    }
    .status-completed {
      background-color: #D1FAE5;
      color: #065F46;
    }
    .status-failed {
      background-color: #FEE2E2;
      color: #991B1B;
    }
    .status-duplicate {
      background-color: #E5E7EB;
      color: #374151;
    }

    /* Step summary section */
    .step-summary {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      gap: 1rem;
      margin-bottom: 1.5rem;
    }
    .summary-card {
      background-color: #f7fafc;
      border-radius: 0.5rem;
      padding: 1rem;
      border-left: 4px solid #e2e8f0;
    }
    .summary-card.main-steps {
      border-left-color: #4299e1;
    }
    .summary-card.upload-steps {
      border-left-color: #48bb78;
    }
    .summary-title {
      font-weight: 600;
      color: #2d3748;
      margin-bottom: 0.5rem;
      font-size: 0.875rem;
      text-transform: uppercase;
    }
    .summary-counts {
      display: flex;
      gap: 1rem;
      flex-wrap: wrap;
    }
    .summary-count {
      display: flex;
      align-items: center;
      gap: 0.25rem;
      font-size: 0.875rem;
    }
    .count-badge {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 50%;
      font-weight: 600;
      font-size: 0.75rem;
    }
    .count-badge.success {
      background-color: #48bb78;
      color: white;
    }
    .count-badge.failure {
      background-color: #f56565;
      color: white;
    }
    .count-badge.in-progress {
      background-color: #4299e1;
      color: white;
    }
    .count-badge.queued {
      background-color: #ecc94b;
      color: white;
    }

    /* Processing logs - collapsible */
    .timeline {
      position: relative;
      padding-left: 2rem;
    }
    .timeline::before {
      content: '';
      position: absolute;
      left: 0.5rem;
      top: 0;
      bottom: 0;
      width: 2px;
      background-color: #e2e8f0;
    }
    .timeline-item {
      position: relative;
      padding-bottom: 2rem;
    }
    .timeline-item:last-child {
      padding-bottom: 0;
    }
    .timeline-marker {
      position: absolute;
      left: -1.5rem;
      width: 1rem;
      height: 1rem;
      border-radius: 50%;
      background-color: #e2e8f0;
      border: 2px solid white;
    }
    .timeline-marker.success {
      background-color: #48bb78;
    }
    .timeline-marker.failure {
      background-color: #f56565;
    }
    .timeline-marker.in_progress {
      background-color: #4299e1;
    }
    .timeline-marker.pending {
      background-color: #ecc94b;
    }
    .timeline-content {
      background-color: #f7fafc;
      border-radius: 0.5rem;
      padding: 1rem;
      border-left: 3px solid #e2e8f0;
    }
    .timeline-content.success {
      border-left-color: #48bb78;
      background-color: #f0fff4;
    }
    .timeline-content.failure {
      border-left-color: #f56565;
      background-color: #fff5f5;
    }
    .timeline-content.in_progress {
      border-left-color: #4299e1;
      background-color: #ebf8ff;
    }
    .timeline-content.pending {
      border-left-color: #ecc94b;
      background-color: #fffff0;
    }
    .timeline-title {
      font-weight: 600;
      color: #2d3748;
      margin-bottom: 0.5rem;
    }
    .timeline-message {
      color: #4a5568;
      margin-bottom: 0.5rem;
    }
    .timeline-meta {
      display: flex;
      justify-content: space-between;
      font-size: 0.875rem;
      color: #718096;
    }
    .timeline-task-id {
      font-family: monospace;
      font-size: 0.75rem;
      color: #a0aec0;
    }

    .logs-toggle {
      cursor: pointer;
      user-select: none;
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      color: #3182ce;
      font-weight: 600;
      margin-bottom: 1rem;
    }
    .logs-toggle:hover {
      color: #2c5aa0;
    }
    .logs-content {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease-out;
    }
    .logs-content.expanded {
      max-height: 5000px;
      transition: max-height 0.5s ease-in;
    }

    /* Verbose detail block */
    .timeline-detail-toggle {
      cursor: pointer;
      color: #3182ce;
      font-size: 0.75rem;
      font-weight: 600;
      margin-top: 0.25rem;
      display: inline-flex;
      align-items: center;
      gap: 0.25rem;
    }
    .timeline-detail-toggle:hover {
      color: #2c5aa0;
    }
    .timeline-detail {
      display: none;
      margin-top: 0.5rem;
      background-color: #1a202c;
      color: #e2e8f0;
      padding: 0.75rem;
      border-radius: 0.375rem;
      font-family: monospace;
      font-size: 0.75rem;
      white-space: pre-wrap;
      word-break: break-word;
      max-height: 400px;
      overflow-y: auto;
    }
    .timeline-detail.visible {
      display: block;
    }

    .no-logs {
      text-align: center;
      padding: 3rem;
      color: #718096;
    }
    .no-logs i {
      font-size: 3rem;
      margin-bottom: 1rem;
      opacity: 0.5;
    }

    .error-message {
      background-color: #FEE2E2;
      border: 1px solid #F87171;
      color: #B91C1C;
      padding: 1rem;
      border-radius: 0.25rem;
      margin-bottom: 1rem;
    }

    .file-status-indicator {
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;
      border-radius: 0.25rem;
      font-size: 0.875rem;
    }
    .file-status-indicator.exists {
      background-color: #D1FAE5;
      color: #065F46;
    }
    .file-status-indicator.missing {
      background-color: #FEE2E2;
      color: #991B1B;
    }

    /* Flow visualization with branches */
    .flow-stage {
      display: flex;
      align-items: flex-start;
      margin-bottom: 1.5rem;
    }
    .flow-indicator {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 1rem;
      flex-shrink: 0;
    }
    .flow-indicator.success {
      background-color: #48bb78;
      color: white;
    }
    .flow-indicator.failure {
      background-color: #f56565;
      color: white;
    }
    .flow-indicator.in_progress {
      background-color: #4299e1;
      color: white;
    }
    .flow-indicator.pending, .flow-indicator.queued {
      background-color: #ecc94b;
      color: white;
    }
    .flow-indicator.not_run {
      background-color: #e2e8f0;
      color: #718096;
    }
    .flow-content {
      flex: 1;
      background-color: #f7fafc;
      padding: 1rem;
      border-radius: 0.5rem;
      border-left: 3px solid #e2e8f0;
    }
    .flow-content.success {
      border-left-color: #48bb78;
      background-color: #f0fff4;
    }
    .flow-content.failure {
      border-left-color: #f56565;
      background-color: #fff5f5;
    }
    .flow-content.in_progress {
      border-left-color: #4299e1;
      background-color: #ebf8ff;
    }
    .flow-content.pending, .flow-content.queued {
      border-left-color: #ecc94b;
      background-color: #fffff0;
    }
    .flow-title {
      font-weight: 600;
      color: #2d3748;
      margin-bottom: 0.25rem;
    }
    .flow-message {
      color: #4a5568;
      font-size: 0.875rem;
    }
    .flow-timestamp {
      color: #718096;
      font-size: 0.75rem;
      margin-top: 0.25rem;
    }
    .flow-connector {
      width: 2px;
      height: 20px;
      background-color: #e2e8f0;
      margin-left: 19px;
      margin-bottom: 0.5rem;
    }

    /* Branch visualization */
    .flow-branches {
      margin-left: 56px;
      margin-top: 1rem;
      padding-left: 1rem;
      border-left: 2px dashed #cbd5e0;
    }
    .branch-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 1rem;
      position: relative;
    }
    .branch-item::before {
      content: '';
      position: absolute;
      left: -1rem;
      top: 20px;
      width: 1rem;
      height: 2px;
      background-color: #cbd5e0;
    }
    .branch-indicator {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 0.75rem;
      flex-shrink: 0;
      font-size: 0.875rem;
    }
    .branch-indicator.success {
      background-color: #48bb78;
      color: white;
    }
    .branch-indicator.failure {
      background-color: #f56565;
      color: white;
    }
    .branch-indicator.in_progress {
      background-color: #4299e1;
      color: white;
    }
    .branch-indicator.pending, .branch-indicator.queued {
      background-color: #ecc94b;
      color: white;
    }
    .branch-content {
      flex: 1;
      background-color: white;
      padding: 0.75rem;
      border-radius: 0.5rem;
      border: 1px solid #e2e8f0;
    }
    .branch-content.failure {
      border-color: #f56565;
      background-color: #fffafa;
    }
    .branch-title {
      font-weight: 600;
      color: #2d3748;
      font-size: 0.875rem;
      margin-bottom: 0.25rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .branch-message {
      color: #4a5568;
      font-size: 0.75rem;
    }
    .retry-btn {
      background-color: #f56565;
      color: white;
      border: none;
      padding: 0.25rem 0.75rem;
      border-radius: 0.25rem;
      font-size: 0.75rem;
      cursor: pointer;
      font-weight: 600;
    }
    .retry-btn:hover {
      background-color: #e53e3e;
    }
    .retry-btn:disabled {
      background-color: #cbd5e0;
      cursor: not-allowed;
    }

    /* Text Modal Styles */
    .text-modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.7);
      z-index: 1000;
      overflow-y: auto;
      padding: 2rem;
    }
    .text-modal-content {
      background-color: white;
      max-width: 1200px;
      margin: 0 auto;
      padding: 2rem;
      border-radius: 0.5rem;
      box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    }

    /* PDF Canvas Viewer Styles */
    .pdf-viewer-container {
      border: 2px solid #e2e8f0;
      border-radius: 0.5rem;
      overflow: hidden;
      background-color: #f7fafc;
      position: relative;
    }
    .pdf-canvas-wrapper {
      overflow-y: auto;
      max-height: 600px;
      background-color: #525252;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 1rem;
    }
    .pdf-canvas {
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      margin-bottom: 0.5rem;
      background-color: white;
    }
    .pdf-controls {
      background-color: #2d3748;
      color: white;
      padding: 0.5rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 0.875rem;
    }
    .pdf-nav-btn {
      background-color: #4299e1;
      color: white;
      border: none;
      padding: 0.25rem 0.75rem;
      border-radius: 0.25rem;
      cursor: pointer;
      font-size: 0.875rem;
    }
    .pdf-nav-btn:hover {
      background-color: #3182ce;
    }
    .pdf-nav-btn:disabled {
      background-color: #718096;
      cursor: not-allowed;
    }
    .pdf-loading {
      text-align: center;
      padding: 3rem;
      color: #718096;
    }
  </style>
  {% if file %}
  <script>
    // JavaScript for handling retry functionality
    async function reprocessFile() {
      const fileId = {{ file.id | tojson }};
      const button = document.getElementById('reprocess-btn');
      const statusDiv = document.getElementById('reprocess-status');

      // Disable button and show loading
      button.disabled = true;
      button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
      statusDiv.innerHTML = '';

      try {
        const response = await fetch(`/api/files/${fileId}/reprocess`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': getCsrfToken()
          }
        });

        const data = await response.json();

        if (response.ok) {
          statusDiv.innerHTML = `
            <div style="background-color: #D1FAE5; color: #065F46; padding: 1rem; border-radius: 0.25rem; margin-top: 1rem;">
              <i class="fas fa-check-circle"></i> File queued for reprocessing. Task ID: ${data.task_id}
              <br><small>Refresh the page in a few moments to see updated status.</small>
            </div>
          `;
          // Reload page after 3 seconds
          setTimeout(() => window.location.reload(), 3000);
        } else {
          statusDiv.innerHTML = `
            <div class="error-message" style="margin-top: 1rem;">
              <i class="fas fa-exclamation-triangle"></i> Error: ${data.detail || 'Failed to reprocess file'}
            </div>
          `;
          button.disabled = false;
          button.innerHTML = '<i class="fas fa-redo"></i> Retry Processing';
        }
      } catch (error) {
        statusDiv.innerHTML = `
          <div class="error-message" style="margin-top: 1rem;">
            <i class="fas fa-exclamation-triangle"></i> Network error: ${error.message}
          </div>
        `;
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-redo"></i> Retry Processing';
      }
    }

    // JavaScript for handling per-subtask retry
    async function retrySubtask(subtaskName, buttonId) {
      const fileId = {{ file.id | tojson }};
      const button = document.getElementById(buttonId);
      const statusDiv = document.getElementById('subtask-status-' + subtaskName);

      // Disable button and show loading
      button.disabled = true;
      button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Retrying...';
      if (statusDiv) {
        statusDiv.innerHTML = '';
      }

      try {
        const response = await fetch(`/api/files/${fileId}/retry-subtask?subtask_name=${subtaskName}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': getCsrfToken()
          }
        });

        const data = await response.json();

        if (response.ok) {
          if (statusDiv) {
            statusDiv.innerHTML = `
              <div style="background-color: #D1FAE5; color: #065F46; padding: 0.5rem; border-radius: 0.25rem; margin-top: 0.5rem; font-size: 0.75rem;">
                <i class="fas fa-check-circle"></i> Queued for retry. Task ID: ${data.task_id}
              </div>
            `;
          }
          // Reload page after 2 seconds
          setTimeout(() => window.location.reload(), 2000);
        } else {
          if (statusDiv) {
            statusDiv.innerHTML = `
              <div style="background-color: #FEE2E2; color: #991B1B; padding: 0.5rem; border-radius: 0.25rem; margin-top: 0.5rem; font-size: 0.75rem;">
                <i class="fas fa-exclamation-triangle"></i> Error: ${data.detail || 'Failed to retry'}
              </div>
            `;
          }
          button.disabled = false;
          button.innerHTML = '<i class="fas fa-redo"></i> Retry';
        }
      } catch (error) {
        if (statusDiv) {
          statusDiv.innerHTML = `
            <div style="background-color: #FEE2E2; color: #991B1B; padding: 0.5rem; border-radius: 0.25rem; margin-top: 0.5rem; font-size: 0.75rem;">
              <i class="fas fa-exclamation-triangle"></i> Network error: ${error.message}
            </div>
          `;
        }
        button.disabled = false;
        button.innerHTML = '<i class="fas fa-redo"></i> Retry';
      }
    }

    // Toggle logs visibility
    function toggleLogs() {
      const logsContent = document.getElementById('logs-content');
      const toggleIcon = document.getElementById('logs-toggle-icon');

      if (logsContent.classList.contains('expanded')) {
        logsContent.classList.remove('expanded');
        toggleIcon.classList.remove('fa-chevron-up');
        toggleIcon.classList.add('fa-chevron-down');
      } else {
        logsContent.classList.add('expanded');
        toggleIcon.classList.remove('fa-chevron-down');
        toggleIcon.classList.add('fa-chevron-up');
      }
    }

    // Toggle verbose detail for a log entry
    function toggleDetail(logId) {
      const detail = document.getElementById('detail-' + logId);
      const icon = document.getElementById('detail-icon-' + logId);
      if (detail.classList.contains('visible')) {
        detail.classList.remove('visible');
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-right');
      } else {
        detail.classList.add('visible');
        icon.classList.remove('fa-chevron-right');
        icon.classList.add('fa-chevron-up');
      }
    }

    // JavaScript for metadata JSON toggle
    function toggleMetadata() {
      const jsonView = document.getElementById('metadata-json-view');
      const icon = document.getElementById('metadata-toggle-icon');
      const btn = document.getElementById('metadata-toggle-btn');

      if (jsonView.style.display === 'none') {
        jsonView.style.display = 'block';
        icon.classList.remove('fa-chevron-down');
        icon.classList.add('fa-chevron-up');
        btn.innerHTML = '<i id="metadata-toggle-icon" class="fas fa-chevron-up"></i> Hide JSON';
      } else {
        jsonView.style.display = 'none';
        icon.classList.remove('fa-chevron-up');
        icon.classList.add('fa-chevron-down');
        btn.innerHTML = '<i id="metadata-toggle-icon" class="fas fa-chevron-down"></i> Show JSON';
      }
    }

    // JavaScript for text modal toggle with on-demand loading
    let textCache = { original: null, processed: null };

    async function loadAndShowText(type, fileId) {
      const modalId = type + '-text-modal';
      const loadingId = type + '-text-loading';
      const contentId = type + '-text-content';

      // Show modal immediately
      toggleTextModal(modalId);

      // If already loaded, just show it
      if (textCache[type]) {
        document.getElementById(loadingId).style.display = 'none';
        document.getElementById(contentId).style.display = 'block';
        document.getElementById(contentId).textContent = textCache[type];
        return;
      }

      // Show loading state
      document.getElementById(loadingId).style.display = 'block';
      document.getElementById(contentId).style.display = 'none';

      try {
        const response = await fetch(`/files/${fileId}/text/${type}`);
        if (!response.ok) {
          throw new Error('Failed to extract text');
        }

        const data = await response.json();
        textCache[type] = data.text;

        // Show the text
        document.getElementById(loadingId).style.display = 'none';
        document.getElementById(contentId).style.display = 'block';
        document.getElementById(contentId).textContent = data.text;
      } catch (error) {
        console.error('Error loading text:', error);
        document.getElementById(loadingId).innerHTML = `
          <div style="color: #f56565;">
            <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 1rem;"></i>
            <p>Failed to extract text from PDF</p>
            <p style="font-size: 0.875rem;">${error.message}</p>
          </div>
        `;
      }
    }

    function toggleTextModal(modalId) {
      const modal = document.getElementById(modalId);
      if (modal.style.display === 'none' || modal.style.display === '') {
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden'; // Prevent background scrolling
      } else {
        modal.style.display = 'none';
        document.body.style.overflow = 'auto'; // Re-enable scrolling
      }
    }

    function showCopyFeedback(type, success) {
      const btn = document.getElementById(type + '-copy-btn');
      if (!btn) return;
      const original = btn.innerHTML;
      if (success) {
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        btn.style.backgroundColor = '#48bb78';
      } else {
        btn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';
        btn.style.backgroundColor = '#f56565';
      }
      setTimeout(() => {
        btn.innerHTML = original;
        btn.style.backgroundColor = '#4299e1';
      }, 2000);
    }

    function copyTextToClipboard(type) {
      const contentId = type + '-text-content';
      const content = document.getElementById(contentId);
      const text = content ? content.textContent : '';

      if (!text) return;

      navigator.clipboard.writeText(text).then(() => {
        showCopyFeedback(type, true);
      }).catch(() => {
        // Fallback for older browsers
        try {
          const textarea = document.createElement('textarea');
          textarea.value = text;
          textarea.style.position = 'fixed';
          textarea.style.opacity = '0';
          document.body.appendChild(textarea);
          textarea.select();
          const ok = document.execCommand('copy');
          document.body.removeChild(textarea);
          showCopyFeedback(type, ok);
        } catch (e) {
          showCopyFeedback(type, false);
        }
      });
    }

    // Close modal when clicking outside the content
    window.onclick = function(event) {
      const modals = document.querySelectorAll('.text-modal');
      modals.forEach(modal => {
        if (event.target === modal) {
          modal.style.display = 'none';
          document.body.style.overflow = 'auto';
        }
      });
    }

    // PDF.js viewer functionality
    const pdfViewers = {
      original: { currentPage: 1, totalPages: 0, pdfDoc: null },
      processed: { currentPage: 1, totalPages: 0, pdfDoc: null }
    };

    async function loadPDF(type, fileId) {
      const url = `/files/${fileId}/preview/${type}`;
      const canvasWrapper = document.getElementById(`${type}-canvas-wrapper`);

      try {
        // Load PDF document
        const loadingTask = pdfjsLib.getDocument(url);
        const pdf = await loadingTask.promise;

        pdfViewers[type].pdfDoc = pdf;
        pdfViewers[type].totalPages = pdf.numPages;
        pdfViewers[type].currentPage = 1;

        // Clear loading message and render first page
        canvasWrapper.innerHTML = '';
        await renderPage(type);
        updatePageInfo(type);
      } catch (error) {
        console.error(`Error loading ${type} PDF:`, error);
        canvasWrapper.innerHTML = `
          <div class="pdf-loading">
            <i class="fas fa-exclamation-triangle" style="font-size: 2rem; color: #f56565; margin-bottom: 1rem;"></i>
            <p style="color: #f56565;">Failed to load PDF</p>
          </div>
        `;
      }
    }

    async function renderPage(type) {
      const viewer = pdfViewers[type];
      if (!viewer.pdfDoc) return;

      const canvasWrapper = document.getElementById(`${type}-canvas-wrapper`);
      const page = await viewer.pdfDoc.getPage(viewer.currentPage);

      // Calculate scale to fit container width (max 600px width)
      const viewport = page.getViewport({ scale: 1.0 });
      const scale = Math.min(600 / viewport.width, 2.0);
      const scaledViewport = page.getViewport({ scale });

      // Create canvas for this page
      const canvas = document.createElement('canvas');
      canvas.className = 'pdf-canvas';
      canvas.height = scaledViewport.height;
      canvas.width = scaledViewport.width;

      const context = canvas.getContext('2d');
      const renderContext = {
        canvasContext: context,
        viewport: scaledViewport
      };

      // Clear previous canvas and render new one
      canvasWrapper.innerHTML = '';
      canvasWrapper.appendChild(canvas);

      await page.render(renderContext).promise;
    }

    function changePage(type, delta) {
      const viewer = pdfViewers[type];
      const newPage = viewer.currentPage + delta;

      if (newPage >= 1 && newPage <= viewer.totalPages) {
        viewer.currentPage = newPage;
        renderPage(type);
        updatePageInfo(type);
      }
    }

    function updatePageInfo(type) {
      const viewer = pdfViewers[type];
      document.getElementById(`${type}-page-info`).textContent =
        `Page ${viewer.currentPage} of ${viewer.totalPages}`;

      document.getElementById(`${type}-prev-btn`).disabled = viewer.currentPage === 1;
      document.getElementById(`${type}-next-btn`).disabled = viewer.currentPage === viewer.totalPages;
    }

    // Load PDFs when page loads
    document.addEventListener('DOMContentLoaded', function() {
      const fileId = {{ file.id | tojson }};
      {% if original_file_exists %}
      loadPDF('original', fileId);
      {% endif %}
      {% if processed_file_exists %}
      loadPDF('processed', fileId);
      {% endif %}

      // Load similar documents and embedding status
      loadSimilarDocuments(fileId);
      loadEmbeddingStatus(fileId);
    });

    // Fetch and display embedding debug info
    async function loadEmbeddingStatus(fileId) {
      const statusDiv = document.getElementById('embedding-status');
      const actionsDiv = document.getElementById('embedding-actions');
      try {
        const response = await fetch(`/api/files/${fileId}/embedding-status`);
        if (!response.ok) return;
        const data = await response.json();

        let html = '';
        if (data.has_embedding) {
          html = `<i class="fas fa-check-circle" aria-hidden="true"></i> Embedding: <strong>${data.embedding_dimensions} dimensions</strong> (model: ${data.embedding_model})`;
          statusDiv.style.backgroundColor = '#f0fff4';
          statusDiv.style.color = '#276749';
          statusDiv.style.border = '1px solid #c6f6d5';
        } else if (data.has_ocr_text) {
          html = `<i class="fas fa-exclamation-circle" aria-hidden="true"></i> Embedding: <strong>not yet computed</strong> — OCR text available (${data.ocr_text_length} chars). Click "Recompute Embedding" to generate.`;
          statusDiv.style.backgroundColor = '#fffff0';
          statusDiv.style.color = '#975a16';
          statusDiv.style.border = '1px solid #fefcbf';
        } else {
          html = `<i class="fas fa-times-circle" aria-hidden="true"></i> Embedding: <strong>unavailable</strong> — no OCR text extracted for this file.`;
          statusDiv.style.backgroundColor = '#fff5f5';
          statusDiv.style.color = '#9b2c2c';
          statusDiv.style.border = '1px solid #fed7d7';
        }
        statusDiv.innerHTML = html;
        statusDiv.style.display = 'block';
        actionsDiv.style.display = data.has_ocr_text ? 'block' : 'none';
      } catch (error) {
        console.error('Error loading embedding status:', error);
      }
    }

    // Trigger embedding recomputation
    async function recomputeEmbedding(fileId) {
      const btn = document.getElementById('recompute-embedding-btn');
      btn.disabled = true;
      btn.innerHTML = '<i class="fas fa-spinner fa-spin" aria-hidden="true"></i> Computing…';

      try {
        const response = await fetch(`/api/files/${fileId}/compute-embedding`, { method: 'POST' });
        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.detail || 'Request failed');
        }
        btn.innerHTML = '<i class="fas fa-check" aria-hidden="true"></i> Done';
        btn.style.backgroundColor = '#48bb78';
        // Refresh both embedding status and similar documents
        loadEmbeddingStatus(fileId);
        loadSimilarDocuments(fileId);
      } catch (error) {
        btn.innerHTML = '<i class="fas fa-times" aria-hidden="true"></i> Failed';
        btn.style.backgroundColor = '#e53e3e';
        console.error('Recompute embedding failed:', error);
      } finally {
        setTimeout(() => {
          btn.disabled = false;
          btn.innerHTML = '<i class="fas fa-redo" aria-hidden="true"></i> Recompute Embedding';
          btn.style.backgroundColor = '#4299e1';
        }, 3000);
      }
    }

    // Similar documents loading
    async function loadSimilarDocuments(fileId) {
      const loadingDiv = document.getElementById('similar-documents-loading');
      const contentDiv = document.getElementById('similar-documents-content');
      const emptyDiv = document.getElementById('similar-documents-empty');
      const errorDiv = document.getElementById('similar-documents-error');

      try {
        const response = await fetch(`/api/files/${fileId}/similar?limit=5&threshold=0.3`);
        if (!response.ok) {
          throw new Error(response.statusText || 'Request failed');
        }

        const data = await response.json();
        loadingDiv.style.display = 'none';

        if (!data.similar_documents || data.similar_documents.length === 0) {
          emptyDiv.style.display = 'block';
          if (data.message) {
            emptyDiv.querySelector('p').textContent = data.message;
          }
          return;
        }

        // Build the results HTML
        let html = '<div style="display: grid; gap: 0.75rem;" role="list" aria-label="Similar documents">';
        for (const doc of data.similar_documents) {
          const scorePercent = Math.round(doc.similarity_score * 100);
          const title = doc.document_title || doc.original_filename || 'Untitled';
          const filename = doc.original_filename || 'Unknown';
          const createdAt = doc.created_at ? new Date(doc.created_at).toLocaleDateString() : '';
          const scoreLabel = scorePercent >= 80 ? 'High' : scorePercent >= 50 ? 'Medium' : 'Low';

          html += `
            <div role="listitem">
            <a href="/files/${doc.file_id}/detail" aria-label="${title} — ${scorePercent}% similarity (${scoreLabel})" style="text-decoration: none; color: inherit; display: block;">
              <div style="display: flex; align-items: center; gap: 1rem; padding: 0.75rem 1rem; background-color: #f7fafc; border-radius: 0.5rem; border: 1px solid #e2e8f0; transition: border-color 0.2s; cursor: pointer;" onmouseover="this.style.borderColor='#4299e1'" onmouseout="this.style.borderColor='#e2e8f0'">
                <div style="flex-shrink: 0; width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.875rem; color: white; background-color: ${scorePercent >= 80 ? '#48bb78' : scorePercent >= 50 ? '#ecc94b' : '#718096'};" aria-hidden="true">
                  ${scorePercent}%
                </div>
                <div style="flex: 1; min-width: 0;">
                  <div style="font-weight: 600; color: #2d3748; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${title}">
                    ${title}
                  </div>
                  <div style="font-size: 0.75rem; color: #4a5568; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                    ${scorePercent}% match (${scoreLabel}) · ${filename}${createdAt ? ' · ' + createdAt : ''}
                  </div>
                </div>
                <div style="flex-shrink: 0; color: #4a5568;">
                  <i class="fas fa-chevron-right" aria-hidden="true"></i>
                </div>
              </div>
            </a>
            </div>
          `;
        }
        html += '</div>';

        contentDiv.innerHTML = html;
        contentDiv.style.display = 'block';
      } catch (error) {
        console.error('Error loading similar documents:', error);
        loadingDiv.style.display = 'none';
        errorDiv.style.display = 'block';
        document.getElementById('similar-documents-error-msg').textContent =
          'Failed to load similar documents: ' + error.message;
      }
    }
  </script>
  {% endif %}
{% endblock %}

{% block content %}
<div class="detail-container">
  <div style="display:flex;align-items:center;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap;">
    <a href="/files" class="back-button" style="margin-bottom:0;" aria-label="Back to File List">
      <i class="fas fa-arrow-left" aria-hidden="true"></i>
      Back to File List
    </a>
    {% if file %}
    <a href="/files/{{ file.id }}" class="back-button" style="margin-bottom:0;" aria-label="View document for {{ file.original_filename }}">
      <i class="fas fa-eye" aria-hidden="true"></i>
      View Document
    </a>
    {% endif %}
  </div>

  {% if error %}
  <div class="error-message">
    <p><strong>Error:</strong> {{ error }}</p>
  </div>
  {% else %}

  <!-- Overall Processing Status Banner -->
  {% if step_summary %}
  <div style="margin-bottom: 1.5rem; padding: 1.5rem; background-color: #f0f9ff; border-left: 4px solid #3b82f6; border-radius: 0.5rem;">
    <div style="display: flex; align-items: center; justify-content: space-between;">
      <div>
        <div style="font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 0.5rem;">Status</div>
        <div style="font-size: 1.5rem; font-weight: 600; color: #1f2937;">
          {% set main_completed = step_summary.main.success + step_summary.main.skipped %}
          {% set uploads_completed = step_summary.uploads.success + step_summary.uploads.skipped %}
          {% if file.is_duplicate %}
            <i class="fas fa-copy" aria-hidden="true" style="color: #6b7280; margin-right: 0.5rem;"></i>Duplicate
          {% elif step_summary.main.failure > 0 or step_summary.uploads.failure > 0 %}
            <i class="fas fa-times-circle" aria-hidden="true" style="color: #dc2626; margin-right: 0.5rem;"></i>Failed
          {% elif step_summary.main["in_progress"] > 0 or step_summary.uploads["in_progress"] > 0 %}
            <i class="fas fa-circle-notch" aria-hidden="true" style="color: #f59e0b; margin-right: 0.5rem; animation: spin 1s linear infinite;"></i>Processing
          {% elif step_summary.total_main_steps > 0 and main_completed == step_summary.total_main_steps and step_summary.main.failure == 0 %}
            <i class="fas fa-check-circle" aria-hidden="true" style="color: #059669; margin-right: 0.5rem;"></i>Completed
          {% else %}
            <i class="fas fa-pause-circle" aria-hidden="true" style="color: #f59e0b; margin-right: 0.5rem;"></i>Pending
          {% endif %}
        </div>
      </div>
      <div style="text-align: right;">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem;">
          <div>
            <div style="font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 0.5rem;">Main Steps</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1f2937;">
              {% set main_completed = step_summary.main.success + step_summary.main.skipped %}
              {% if main_completed == step_summary.total_main_steps and step_summary.main.failure == 0 %}
                <span style="color: #059669;">✓</span> {{ main_completed }}/{{ step_summary.total_main_steps }}
              {% else %}
                {{ main_completed }}/{{ step_summary.total_main_steps }}
              {% endif %}
            </div>
          </div>
          <div>
            <div style="font-size: 0.75rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 0.5rem;">Uploads</div>
            <div style="font-size: 1.5rem; font-weight: 600; color: #1f2937;">
              {% set uploads_completed = step_summary.uploads.success + step_summary.uploads.skipped %}
              {% if uploads_completed == step_summary.total_upload_tasks and step_summary.uploads.failure == 0 and step_summary.total_upload_tasks > 0 %}
                <span style="color: #059669;">✓</span> {{ uploads_completed }}/{{ step_summary.total_upload_tasks }}
              {% else %}
                {{ uploads_completed }}/{{ step_summary.total_upload_tasks }}
              {% endif %}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <style>
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  </style>
  {% endif %}

  <!-- File Information Card -->
  <div class="detail-card">
    <h3>File Information</h3>
    <div class="detail-grid">
      <div class="detail-item">
        <span class="detail-label">File ID</span>
        <span class="detail-value">{{ file.id }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Original Filename</span>
        <span class="detail-value">{{ file.original_filename }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">File Hash</span>
        <span class="detail-value" style="font-family: monospace; font-size: 0.875rem;">{{ file.filehash }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">File Size</span>
        <span class="detail-value">{{ (file.file_size / 1024) | round(2) }} KB ({{ file.file_size }} bytes)</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">MIME Type</span>
        <span class="detail-value">{{ file.mime_type or 'N/A' }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Created At</span>
        <span class="detail-value">{{ file.created_at.strftime('%Y-%m-%d %H:%M:%S') if file.created_at else 'N/A' }}</span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Processing Pipeline</span>
        <span class="detail-value">
          {% if pipeline_info %}
          <a href="/pipelines" style="text-decoration: none; color: inherit; font-weight: 500;" aria-label="View pipeline management for {{ pipeline_info.name }}">{{ pipeline_info.name }}</a>
          {% if not pipeline_info.is_explicit and pipeline_info.is_system %}
          <span style="display: inline-block; margin-left: 0.4rem; padding: 0.1rem 0.45rem; font-size: 0.7rem; font-weight: 600; border-radius: 0.25rem; background: #ede9fe; color: #5b21b6;" title="No pipeline was explicitly assigned; the system default is applied">System Default</span>
          {% elif pipeline_info.is_system %}
          <span style="display: inline-block; margin-left: 0.4rem; padding: 0.1rem 0.45rem; font-size: 0.7rem; font-weight: 600; border-radius: 0.25rem; background: #dbeafe; color: #1e40af;" title="This file uses a system-managed pipeline">System</span>
          {% else %}
          <span style="display: inline-block; margin-left: 0.4rem; padding: 0.1rem 0.45rem; font-size: 0.7rem; font-weight: 600; border-radius: 0.25rem; background: #d1fae5; color: #065f46;" title="This file uses a custom user-defined pipeline">Custom</span>
          {% endif %}
          {% else %}
          <span style="color: #9ca3af; font-style: italic;">Standard (legacy)</span>
          {% endif %}
        </span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Original File Path</span>
        <span class="detail-value" style="font-family: monospace; font-size: 0.875rem;">
          {{ file.original_file_path if file.original_file_path else 'N/A' }}
        </span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Original File Status</span>
        <span class="detail-value">
          {% if original_file_exists %}
          <span class="file-status-indicator exists">
            <i class="fas fa-check-circle" aria-hidden="true"></i> File exists
          </span>
          {% else %}
          <span class="file-status-indicator missing">
            <i class="fas fa-times-circle" aria-hidden="true"></i> File not found
          </span>
          {% endif %}
        </span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Processed File Path</span>
        <span class="detail-value" style="font-family: monospace; font-size: 0.875rem;">
          {{ file.processed_file_path if file.processed_file_path else 'N/A' }}
        </span>
      </div>
      <div class="detail-item">
        <span class="detail-label">Processed File Status</span>
        <span class="detail-value">
          {% if processed_file_exists %}
          <span class="file-status-indicator exists">
            <i class="fas fa-check-circle" aria-hidden="true"></i> File exists
          </span>
          {% else %}
          <span class="file-status-indicator missing">
            <i class="fas fa-times-circle" aria-hidden="true"></i> File not found
          </span>
          {% endif %}
        </span>
      </div>
    </div>
  </div>

  <!-- GPT Metadata Card -->
  {% if gpt_metadata %}
  <div class="detail-card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
      <h3 style="margin: 0;">Extracted Metadata (GPT)</h3>
      <button id="metadata-toggle-btn" onclick="toggleMetadata()" style="background-color: #4299e1; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;">
        <i id="metadata-toggle-icon" class="fas fa-chevron-down"></i> Show JSON
      </button>
    </div>

    <div class="detail-grid">
      {% if gpt_metadata.document_type %}
      <div class="detail-item">
        <span class="detail-label">Document Type</span>
        <span class="detail-value">{{ gpt_metadata.document_type }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.filename %}
      <div class="detail-item">
        <span class="detail-label">Suggested Filename</span>
        <span class="detail-value" style="font-family: monospace; font-size: 0.875rem;">{{ gpt_metadata.filename }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.date %}
      <div class="detail-item">
        <span class="detail-label">Document Date</span>
        <span class="detail-value">{{ gpt_metadata.date }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.absender %}
      <div class="detail-item">
        <span class="detail-label">Sender (Absender)</span>
        <span class="detail-value">{{ gpt_metadata.absender }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.empfaenger %}
      <div class="detail-item">
        <span class="detail-label">Recipient (Empfänger)</span>
        <span class="detail-value">{{ gpt_metadata.empfaenger }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.betrag %}
      <div class="detail-item">
        <span class="detail-label">Amount (Betrag)</span>
        <span class="detail-value">{{ gpt_metadata.betrag }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.kontonummer %}
      <div class="detail-item">
        <span class="detail-label">Account Number</span>
        <span class="detail-value" style="font-family: monospace;">{{ gpt_metadata.kontonummer }}</span>
      </div>
      {% endif %}

      {% if gpt_metadata.tags %}
      <div class="detail-item">
        <span class="detail-label">Tags</span>
        <span class="detail-value">
          {% if gpt_metadata.tags is string %}
            {{ gpt_metadata.tags }}
          {% else %}
            {{ ', '.join(gpt_metadata.tags) }}
          {% endif %}
        </span>
      </div>
      {% endif %}
    </div>

    <!-- Collapsible JSON view -->
    <div id="metadata-json-view" style="display: none; margin-top: 1rem;">
      <pre style="background-color: #1a202c; color: #e2e8f0; padding: 1rem; border-radius: 0.5rem; overflow-x: auto; font-size: 0.875rem; line-height: 1.5;">{{ gpt_metadata | tojson(indent=2) }}</pre>
    </div>
  </div>
  {% endif %}

  <!-- PDF Preview Card -->
  <div class="detail-card">
    <h3>Document Previews</h3>

    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-top: 1rem;">
      <!-- Original PDF Preview -->
      <div>
        <h4 style="font-weight: 600; color: #2d3748; margin-bottom: 0.5rem;">Original Document</h4>
        {% if original_file_exists %}
        <div class="pdf-viewer-container" id="original-pdf-container">
          <div class="pdf-controls">
            <button class="pdf-nav-btn" onclick="changePage('original', -1)" id="original-prev-btn">← Previous</button>
            <span id="original-page-info">Loading...</span>
            <button class="pdf-nav-btn" onclick="changePage('original', 1)" id="original-next-btn">Next →</button>
          </div>
          <div class="pdf-canvas-wrapper" id="original-canvas-wrapper">
            <div class="pdf-loading">
              <i class="fas fa-spinner fa-spin" aria-hidden="true" style="font-size: 2rem; margin-bottom: 1rem;"></i>
              <p>Loading PDF...</p>
            </div>
          </div>
        </div>
        <button
          onclick="loadAndShowText('original', {{ file.id }})"
          style="margin-top: 0.5rem; background-color: #4299e1; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600; width: 100%;"
        >
          <i class="fas fa-file-alt" aria-hidden="true"></i> View Extracted Text
        </button>
        {% else %}
        <div style="text-align: center; padding: 3rem; background-color: #f7fafc; border-radius: 0.5rem; color: #718096;">
          <i class="fas fa-file-pdf" aria-hidden="true" style="font-size: 3rem; opacity: 0.5; margin-bottom: 1rem;"></i>
          <p>Original file not available</p>
        </div>
        {% endif %}
      </div>

      <!-- Processed PDF Preview -->
      <div>
        <h4 style="font-weight: 600; color: #2d3748; margin-bottom: 0.5rem;">Processed Document</h4>
        {% if processed_file_exists %}
        <div class="pdf-viewer-container" id="processed-pdf-container">
          <div class="pdf-controls">
            <button class="pdf-nav-btn" onclick="changePage('processed', -1)" id="processed-prev-btn">← Previous</button>
            <span id="processed-page-info">Loading...</span>
            <button class="pdf-nav-btn" onclick="changePage('processed', 1)" id="processed-next-btn">Next →</button>
          </div>
          <div class="pdf-canvas-wrapper" id="processed-canvas-wrapper">
            <div class="pdf-loading">
              <i class="fas fa-spinner fa-spin" aria-hidden="true" style="font-size: 2rem; margin-bottom: 1rem;"></i>
              <p>Loading PDF...</p>
            </div>
          </div>
        </div>
        <button
          onclick="loadAndShowText('processed', {{ file.id }})"
          style="margin-top: 0.5rem; background-color: #48bb78; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600; width: 100%;"
        >
          <i class="fas fa-file-alt" aria-hidden="true"></i> View Extracted Text
        </button>
        {% else %}
        <div style="text-align: center; padding: 3rem; background-color: #f7fafc; border-radius: 0.5rem; color: #718096;">
          <i class="fas fa-file-pdf" aria-hidden="true" style="font-size: 3rem; opacity: 0.5; margin-bottom: 1rem;"></i>
          <p>Processed file not available yet</p>
        </div>
        {% endif %}
      </div>
    </div>
  </div>

  <!-- Text Modals (Hidden by default, loaded on-demand) -->
  <!-- Original Text Modal -->
  <div id="original-text-modal" class="text-modal" style="display: none;">
    <div class="text-modal-content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 2px solid #e2e8f0;">
        <h3 style="margin: 0; color: #2d3748;">Extracted Text (Original)</h3>
        <div style="display: flex; gap: 0.5rem;">
          <button
            id="original-copy-btn"
            onclick="copyTextToClipboard('original')"
            style="background-color: #4299e1; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;"
            aria-label="Copy extracted text"
          >
            <i class="fas fa-copy" aria-hidden="true"></i> Copy
          </button>
          <button
            onclick="toggleTextModal('original-text-modal')"
            style="background-color: #f56565; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;"
            aria-label="Close modal"
          >
            <i class="fas fa-times" aria-hidden="true"></i> Close
          </button>
        </div>
      </div>
      <div id="original-text-loading" style="text-align: center; padding: 3rem; color: #4299e1;">
        <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 1rem;"></i>
        <p>Extracting text from PDF...</p>
      </div>
      <pre id="original-text-content" style="display: none; background-color: #1a202c; color: #e2e8f0; padding: 1.5rem; border-radius: 0.5rem; max-height: 600px; overflow-y: auto; white-space: pre-wrap; word-wrap: break-word; font-size: 0.875rem; line-height: 1.6;"></pre>
    </div>
  </div>

  <!-- Processed Text Modal -->
  <div id="processed-text-modal" class="text-modal" style="display: none;">
    <div class="text-modal-content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; padding-bottom: 1rem; border-bottom: 2px solid #e2e8f0;">
        <h3 style="margin: 0; color: #2d3748;">Extracted Text (Processed)</h3>
        <div style="display: flex; gap: 0.5rem;">
          <button
            id="processed-copy-btn"
            onclick="copyTextToClipboard('processed')"
            style="background-color: #4299e1; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;"
            aria-label="Copy extracted text"
          >
            <i class="fas fa-copy" aria-hidden="true"></i> Copy
          </button>
          <button
            onclick="toggleTextModal('processed-text-modal')"
            style="background-color: #f56565; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;"
            aria-label="Close modal"
          >
            <i class="fas fa-times" aria-hidden="true"></i> Close
          </button>
        </div>
      </div>
      <div id="processed-text-loading" style="text-align: center; padding: 3rem; color: #48bb78;">
        <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 1rem;"></i>
        <p>Extracting text from PDF...</p>
      </div>
      <pre id="processed-text-content" style="display: none; background-color: #1a202c; color: #e2e8f0; padding: 1.5rem; border-radius: 0.5rem; max-height: 600px; overflow-y: auto; white-space: pre-wrap; word-wrap: break-word; font-size: 0.875rem; line-height: 1.6;"></pre>
    </div>
  </div>

  <!-- Step Summary Card -->
  {% if step_summary %}
  <div class="detail-card">
    <h3>Processing Status Summary</h3>
    <div class="step-summary">
      <div class="summary-card main-steps">
        <div class="summary-title">Main Processing Steps</div>
        <div class="summary-counts">
          {% set main_completed = step_summary.main.success + step_summary.main.skipped %}
          {% if main_completed > 0 %}
          <div class="summary-count">
            <span class="count-badge success">{{ main_completed }}</span>
            <span>Success</span>
          </div>
          {% endif %}
          {% if step_summary.main.failure > 0 %}
          <div class="summary-count">
            <span class="count-badge failure">{{ step_summary.main.failure }}</span>
            <span>Failed</span>
          </div>
          {% endif %}
          {% if step_summary.main.in_progress > 0 %}
          <div class="summary-count">
            <span class="count-badge in-progress">{{ step_summary.main.in_progress }}</span>
            <span>In Progress</span>
          </div>
          {% endif %}
          {% if step_summary.main.queued > 0 %}
          <div class="summary-count">
            <span class="count-badge queued">{{ step_summary.main.queued }}</span>
            <span>Queued</span>
          </div>
          {% endif %}
        </div>
      </div>

      {% if step_summary.total_upload_tasks > 0 %}
      <div class="summary-card upload-steps">
        <div class="summary-title">Upload Destinations</div>
        <div class="summary-counts">
          {% set uploads_completed = step_summary.uploads.success + step_summary.uploads.skipped %}
          {% if uploads_completed > 0 %}
          <div class="summary-count">
            <span class="count-badge success">{{ uploads_completed }}</span>
            <span>Success</span>
          </div>
          {% endif %}
          {% if step_summary.uploads.failure > 0 %}
          <div class="summary-count">
            <span class="count-badge failure">{{ step_summary.uploads.failure }}</span>
            <span>Failed</span>
          </div>
          {% endif %}
          {% if step_summary.uploads.in_progress > 0 %}
          <div class="summary-count">
            <span class="count-badge in-progress">{{ step_summary.uploads.in_progress }}</span>
            <span>In Progress</span>
          </div>
          {% endif %}
          {% if step_summary.uploads.queued > 0 %}
          <div class="summary-count">
            <span class="count-badge queued">{{ step_summary.uploads.queued }}</span>
            <span>Queued</span>
          </div>
          {% endif %}
        </div>
      </div>
      {% endif %}
    </div>
  </div>
  {% endif %}

  <!-- Processing History Card (Collapsible) -->
  <div class="detail-card">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
      <h3 style="margin: 0;">Processing History</h3>
      {% if file_exists %}
      <button id="reprocess-btn" onclick="reprocessFile()" style="background-color: #3182ce; color: white; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; cursor: pointer; font-weight: 600;">
        <i class="fas fa-redo"></i> Retry Processing
      </button>
      {% endif %}
    </div>
    <div id="reprocess-status"></div>
    {% if logs %}
    <div class="logs-toggle" onclick="toggleLogs()">
      <i id="logs-toggle-icon" class="fas fa-chevron-down"></i>
      <span>View Full Processing Logs ({{ logs|length }} entries)</span>
    </div>
    <div id="logs-content" class="logs-content">
      <div class="timeline">
        {% for log in logs %}
        <div class="timeline-item">
          <div class="timeline-marker {{ log.status.lower().replace(' ', '_') }}"></div>
          <div class="timeline-content {{ log.status.lower().replace(' ', '_') }}">
            <div class="timeline-title">
              {{ log.step_name }} - <span style="text-transform: capitalize;">{{ log.status }}</span>
            </div>
            {% if log.message %}
            <div class="timeline-message">{{ log.message }}</div>
            {% endif %}
            <div class="timeline-meta">
              <span>{{ log.timestamp.strftime('%Y-%m-%d %H:%M:%S') if log.timestamp else 'N/A' }}</span>
              {% if log.task_id %}
              <span class="timeline-task-id">Task: {{ log.task_id[:16] }}...</span>
              {% endif %}
            </div>
            {% if log.detail %}
            <div class="timeline-detail-toggle" onclick="toggleDetail({{ loop.index }})">
              <i id="detail-icon-{{ loop.index }}" class="fas fa-chevron-right"></i>
              <span>Show worker log detail</span>
            </div>
            <div id="detail-{{ loop.index }}" class="timeline-detail">{{ log.detail }}</div>
            {% endif %}
          </div>
        </div>
        {% endfor %}
      </div>
    </div>
    {% else %}
    <div class="no-logs">
      <i class="fas fa-clipboard-list"></i>
      <p>No processing logs found for this file.</p>
      <p style="margin-top: 0.5rem; font-size: 0.875rem;">The file may not have been processed yet.</p>
    </div>
    {% endif %}
  </div>

  <!-- Process Flow Visualization Card -->
  {% if flow_data %}
  <div class="detail-card">
    <h3>Process Flow Visualization</h3>
    <div style="padding: 1rem 0;">
      {% for stage in flow_data %}
      <div class="flow-stage">
        <!-- Status indicator -->
        <div class="flow-indicator {{ stage.status.lower().replace(' ', '_') }}">
          {% if stage.status == 'success' %}<i class="fas fa-check"></i>
          {% elif stage.status == 'failure' %}<i class="fas fa-times"></i>
          {% elif stage.status == 'in_progress' %}<i class="fas fa-spinner fa-spin"></i>
          {% elif stage.status in ['pending', 'queued'] %}<i class="fas fa-clock"></i>
          {% else %}<i class="fas fa-circle"></i>{% endif %}
        </div>

        <!-- Stage content -->
        <div class="flow-content {{ stage.status.lower().replace(' ', '_') }}">
          <div class="flow-title">{{ stage.label }}</div>
          {% if stage.message %}
          <div class="flow-message">{{ stage.message }}</div>
          {% endif %}
          {% if stage.status == 'not_run' %}
          <div style="color: #718096; font-size: 0.875rem; font-style: italic;">Not executed</div>
          {% endif %}
          {% if stage.can_retry and stage.status == 'failure' %}
          <button
            id="retry-btn-{{ stage.key }}"
            class="retry-btn"
            onclick="retrySubtask('{{ stage.key }}', 'retry-btn-{{ stage.key }}')"
            style="margin-top: 0.5rem;">
            <i class="fas fa-redo"></i> Retry from this step
          </button>
          {% endif %}
          {% if stage.timestamp %}
          <div class="flow-timestamp">
            {{ stage.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}
          </div>
          {% endif %}
        </div>
      </div>

      <!-- Upload branches (if this stage has them) -->
      {% if stage.is_branch_parent and stage.branches %}
      <div class="flow-branches">
        {% for branch in stage.branches %}
        <div class="branch-item">
          <div class="branch-indicator {{ branch.status.lower().replace(' ', '_') }}">
            {% if branch.status == 'success' %}<i class="fas fa-check"></i>
            {% elif branch.status == 'failure' %}<i class="fas fa-times"></i>
            {% elif branch.status == 'in_progress' %}<i class="fas fa-spinner fa-spin"></i>
            {% else %}<i class="fas fa-clock"></i>{% endif %}
          </div>
          <div class="branch-content {% if branch.status == 'failure' %}failure{% endif %}">
            <div class="branch-title">
              <span>{{ branch.label }}</span>
              {% if branch.can_retry and branch.status == 'failure' %}
              <button
                id="retry-btn-{{ branch.key }}"
                class="retry-btn"
                onclick="retrySubtask('{{ branch.key }}', 'retry-btn-{{ branch.key }}')">
                <i class="fas fa-redo"></i> Retry
              </button>
              {% endif %}
            </div>
            {% if branch.message %}
            <div class="branch-message">{{ branch.message }}</div>
            {% endif %}
            {% if branch.timestamp %}
            <div style="color: #718096; font-size: 0.65rem; margin-top: 0.25rem;">
              {{ branch.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}
            </div>
            {% endif %}
            <div id="subtask-status-{{ branch.key }}"></div>
          </div>
        </div>
        {% endfor %}
      </div>
      {% endif %}

      <!-- Connector line (except for last item) -->
      {% if not loop.last %}
      <div class="flow-connector"></div>
      {% endif %}
      {% endfor %}
    </div>
  </div>
  {% endif %}

  <!-- Similar Documents Card -->
  <div class="detail-card" id="similar-documents-card">
    <h3><i class="fas fa-copy" aria-hidden="true"></i> Similar Documents</h3>
    <!-- Embedding debug info -->
    <div id="embedding-status" style="display: none; padding: 0.5rem 1rem; margin-bottom: 0.75rem; border-radius: 0.375rem; font-size: 0.8rem;"></div>
    <div id="similar-documents-loading" style="text-align: center; padding: 2rem; color: #718096;">
      <i class="fas fa-spinner fa-spin" aria-hidden="true" style="font-size: 1.5rem; margin-bottom: 0.5rem;"></i>
      <p>Searching for similar documents…</p>
    </div>
    <div id="similar-documents-content" style="display: none;"></div>
    <div id="similar-documents-empty" style="display: none; text-align: center; padding: 2rem; color: #718096;">
      <i class="fas fa-search" aria-hidden="true" style="font-size: 2rem; margin-bottom: 0.5rem; opacity: 0.5;"></i>
      <p>No similar documents found.</p>
    </div>
    <div id="similar-documents-error" style="display: none; text-align: center; padding: 2rem; color: #991B1B;">
      <i class="fas fa-exclamation-triangle" aria-hidden="true" style="font-size: 2rem; margin-bottom: 0.5rem;"></i>
      <p id="similar-documents-error-msg">Failed to load similar documents.</p>
    </div>
    <!-- Recompute embedding button -->
    <div id="embedding-actions" style="display: none; text-align: right; margin-top: 0.75rem;">
      <button id="recompute-embedding-btn" onclick="recomputeEmbedding({{ file.id | tojson }})" style="background-color: #4299e1; color: white; border: none; padding: 0.4rem 0.75rem; border-radius: 0.375rem; font-size: 0.8rem; cursor: pointer;" aria-label="Recompute document embedding for similarity analysis">
        <i class="fas fa-redo" aria-hidden="true"></i> Recompute Embedding
      </button>
    </div>
  </div>

  <!-- File Preview Card -->
  {% if original_file_exists or processed_file_exists %}
  <div class="detail-card">
    <h3>File Previews</h3>
    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 2rem;">
      {% if original_file_exists %}
      <div>
        <h4 style="font-weight: 600; color: #2d3748; margin-bottom: 1rem;">Original File</h4>
        <div style="border: 2px solid #e2e8f0; border-radius: 0.5rem; overflow: hidden; background-color: #f7fafc;">
          {% if file.mime_type and file.mime_type.startswith('image/') %}
          <!-- Image preview -->
          <img src="/api/files/{{ file.id }}/preview?version=original" alt="{{ file.original_filename }}" style="width: 100%; height: auto; display: block;">
          {% elif file.mime_type and file.mime_type.startswith('text/') %}
          <!-- Text file preview -->
          <iframe src="/api/files/{{ file.id }}/preview?version=original" title="Original text file preview" style="width: 100%; height: 600px; border: none;"></iframe>
          {% else %}
          <!-- PDF via pdf.js (rendered by loadPDF above) — fallback canvas container -->
          <div id="detail-original-canvas" class="pdf-canvas-wrapper" style="min-height: 400px; display: flex; justify-content: center; align-items: center; padding: 0.5rem;">
            <div class="pdf-loading">
              <i class="fas fa-file-pdf" aria-hidden="true" style="font-size: 2rem; margin-bottom: 1rem; color: #94a3b8;"></i>
              <p>This PDF is displayed in the Document Previews section at the top of the page.</p>
            </div>
          </div>
          {% endif %}
        </div>
        <div style="margin-top: 0.5rem; text-align: center; display: flex; gap: 1rem; justify-content: center;">
          <a href="/api/files/{{ file.id }}/preview?version=original" target="_blank" style="color: #3182ce; text-decoration: none; font-size: 0.875rem;">
            <i class="fas fa-external-link-alt" aria-hidden="true"></i> Open in new tab
          </a>
          <a href="/api/files/{{ file.id }}/download?version=original" style="color: #3182ce; text-decoration: none; font-size: 0.875rem;">
            <i class="fas fa-download" aria-hidden="true"></i> Download
          </a>
        </div>
      </div>
      {% endif %}

      {% if processed_file_exists %}
      <div>
        <h4 style="font-weight: 600; color: #2d3748; margin-bottom: 1rem;">Processed File</h4>
        <div style="border: 2px solid #e2e8f0; border-radius: 0.5rem; overflow: hidden; background-color: #f7fafc;">
          <!-- Processed files are typically PDFs — rendered by pdf.js above -->
          <div style="min-height: 400px; display: flex; justify-content: center; align-items: center; padding: 0.5rem;">
            <div class="pdf-loading">
              <i class="fas fa-file-pdf" aria-hidden="true" style="font-size: 2rem; margin-bottom: 1rem; color: #94a3b8;"></i>
              <p>This PDF is displayed in the Document Previews section at the top of the page.</p>
            </div>
          </div>
        </div>
        <div style="margin-top: 0.5rem; text-align: center; display: flex; gap: 1rem; justify-content: center;">
          <a href="/api/files/{{ file.id }}/preview?version=processed" target="_blank" style="color: #3182ce; text-decoration: none; font-size: 0.875rem;">
            <i class="fas fa-external-link-alt" aria-hidden="true"></i> Open in new tab
          </a>
          <a href="/api/files/{{ file.id }}/download?version=processed" style="color: #3182ce; text-decoration: none; font-size: 0.875rem;">
            <i class="fas fa-download" aria-hidden="true"></i> Download
          </a>
        </div>
      </div>
      {% endif %}
    </div>
  </div>
  {% endif %}

  {% endif %}
</div>
{% endblock %}
