
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { getWithAuth, postWithAuth, fetchWithAuth } from '../fetchWithAuth';
import { useNotification } from '../context/NotificationContext';
import hljs from 'highlight.js/lib/core';
import xml from 'highlight.js/lib/languages/xml';
import 'highlight.js/styles/github.css';
hljs.registerLanguage('xml', xml);
import { downloadFile } from '../utils/downloadUtils';

const API_URL = import.meta.env.VITE_EFC_API_URL;

const TIPO_LABELS = {
  pc: 'Pedimento Completo',
  rm: 'Remesas',
  pt: 'Partidas',
  ac: 'Acuse de EDocument',
  cove: 'COVE',
  ac_cove: 'Acuse de COVE',
  edoc: 'EDocument',
};

// Mapeo tipo auditoría → url_path del endpoint de procesamiento individual
const PROCESAMIENTO_URL_MAP = {
  rm: 'procesar-remesas',
  pt: 'procesar-partidas',
  cove: 'procesar-coves',
  ac_cove: 'procesar-acuse-coves',
  edoc: 'procesar-edocuments',
  ac: 'procesar-acuses',
};

function AuditResultModal({ modal, iniciandoProcesamiento, onClose, onIniciarProcesamiento }) {
  const { tipo, pedimento_app, data } = modal;
  // si el backend no retorna 'estado' (ej. pedimento completo), tratamos como no completado
  const esCompletado = data?.estado === 'completado' || data?.auditoria_completa == true;
  // remesa sin remesas: no tiene nada que procesar, ocultar botón
  const sinNadaQueHacer = tipo === 'rm' && data?.tiene_remesas === false;
  const mostrarBotonProcesar = !esCompletado && !sinNadaQueHacer;

  const tituloTipo = TIPO_LABELS[tipo] || tipo;

  const iconoEstado = esCompletado ? (
    <div className="flex items-center justify-center w-12 h-12 mx-auto mb-3 bg-green-100 rounded-full">
      <svg className="w-7 h-7 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
      </svg>
    </div>
  ) : (
    <div className="flex items-center justify-center w-12 h-12 mx-auto mb-3 bg-amber-100 rounded-full">
      <svg className="w-7 h-7 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    </div>
  );

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="w-full max-w-lg bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden">
        {/* Header */}
        <div className={`px-6 py-4 ${esCompletado ? 'bg-green-50 border-b border-green-100' : 'bg-amber-50 border-b border-amber-100'}`}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">{tituloTipo}</p>
              <h3 className="text-lg font-bold text-gray-900 mt-0.5">{pedimento_app}</h3>
            </div>
            <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold ${
              esCompletado
                ? 'bg-green-100 text-green-700'
                : 'bg-amber-100 text-amber-700'
            }`}>
              <span className={`w-2 h-2 rounded-full ${esCompletado ? 'bg-green-500' : 'bg-amber-500'}`}></span>
              {esCompletado ? 'Completado' : 'En proceso'}
            </span>
          </div>
        </div>

        {/* Cuerpo */}
        <div className="px-6 py-5 space-y-4">
          {iconoEstado}

          {/* Mensaje principal */}
          <p className="text-center text-gray-700 font-medium">{data?.mensaje}</p>

          {/* Resumen numérico */}
          {data?.resumen && (
            <div className="grid grid-cols-2 gap-3 mt-2">
              {Object.entries(data.resumen).map(([key, val]) => (
                <div key={key} className="flex flex-col items-center p-3 bg-gray-50 rounded-xl border border-gray-100">
                  <span className="text-2xl font-bold text-gray-900">{val}</span>
                  <span className="text-xs text-gray-500 mt-0.5 text-center capitalize">
                    {key.replace(/_/g, ' ')}
                  </span>
                </div>
              ))}
            </div>
          )}

          {/* Resumen de XMLs analizados — solo muestra lo relevante */}
          {data?.xmls_analizados && (() => {
            const total = data.xmls_analizados.length;
            const conError = data.xmls_analizados.filter(x => x.informacion_extraida?.tiene_error === true);
            const auditOk = data.auditoria_completa !== false;

            return (
              <div className="space-y-3">
                {/* Contadores compactos */}
                <div className="grid grid-cols-3 gap-2">
                  <div className="flex flex-col items-center p-3 bg-gray-50 rounded-xl border border-gray-100">
                    <span className="text-2xl font-bold text-gray-900">{data.archivos_xml_encontrados ?? total}</span>
                    <span className="text-xs text-gray-500 mt-0.5 text-center">Encontrados</span>
                  </div>
                  <div className="flex flex-col items-center p-3 bg-gray-50 rounded-xl border border-gray-100">
                    <span className="text-2xl font-bold text-gray-900">{total}</span>
                    <span className="text-xs text-gray-500 mt-0.5 text-center">Analizados</span>
                  </div>
                  <div className={`flex flex-col items-center p-3 rounded-xl border ${conError.length > 0 ? 'bg-red-50 border-red-100' : 'bg-green-50 border-green-100'}`}>
                    <span className={`text-2xl font-bold ${conError.length > 0 ? 'text-red-700' : 'text-green-700'}`}>{conError.length}</span>
                    <span className={`text-xs mt-0.5 text-center ${conError.length > 0 ? 'text-red-500' : 'text-green-500'}`}>Con error</span>
                  </div>
                </div>

                {/* Advertencia si auditoría incompleta */}
                {!auditOk && (
                  <div className="flex items-center gap-2 px-3 py-2 bg-amber-50 border border-amber-100 rounded-lg text-sm text-amber-800">
                    <svg className="w-4 h-4 flex-shrink-0 text-amber-500" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
                    </svg>
                    Auditoría incompleta — algunos documentos no pudieron verificarse
                  </div>
                )}

                {/* Detalle de XMLs con error */}
                {conError.length > 0 && (
                  <details className="rounded-xl border border-red-200 overflow-hidden" open>
                    <summary className="flex items-center justify-between px-4 py-2.5 bg-red-50 text-sm font-semibold text-red-800 cursor-pointer list-none select-none">
                      <span>XMLs con error ({conError.length})</span>
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                      </svg>
                    </summary>
                    <div className="divide-y divide-red-50">
                      {conError.map((xml) => (
                        <div key={xml.documento_id} className="px-4 py-2 bg-white">
                          <p className="font-mono text-xs text-red-700 break-all">{xml.nombre_archivo}</p>
                          <p className="text-xs text-gray-500 mt-0.5">{xml.tipo_documento}</p>
                        </div>
                      ))}
                    </div>
                  </details>
                )}

                {/* Todo bien */}
                {conError.length === 0 && auditOk && (
                  <p className="text-center text-sm text-green-700 font-medium">Todos los XMLs analizados están correctos</p>
                )}
              </div>
            );
          })()}

          {/* Pendientes */}
          {data?.pendientes && data.pendientes.length > 0 && (
            <div className="mt-2">
              <p className="text-sm font-semibold text-gray-700 mb-2">Pendientes ({data.pendientes.length})</p>
              <div className="max-h-32 overflow-y-auto space-y-1">
                {data.pendientes.map((item, i) => (
                  <div key={i} className="flex items-center gap-2 px-3 py-1.5 bg-amber-50 rounded-lg border border-amber-100 text-sm text-amber-800">
                    <svg className="w-3.5 h-3.5 flex-shrink-0 text-amber-500" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
                    </svg>
                    <span className="font-mono text-xs">{item}</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* COVEs para remesa */}
          {tipo === 'rm' && data?.coves && data.coves.length > 0 && (
            <div className="mt-2">
              <p className="text-sm font-semibold text-gray-700 mb-2">COVEs registrados ({data.coves.length})</p>
              <div className="flex flex-wrap gap-1.5">
                {data.coves.map((cove, i) => (
                  <span key={i} className="px-2 py-0.5 bg-blue-50 text-blue-700 border border-blue-100 rounded text-xs font-mono">
                    {cove}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className={`px-6 py-4 flex gap-3 ${mostrarBotonProcesar ? 'justify-between' : 'justify-end'} border-t border-gray-100 bg-gray-50`}>
          {mostrarBotonProcesar && (
            <button
              onClick={onIniciarProcesamiento}
              disabled={iniciandoProcesamiento}
              className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl font-semibold text-sm text-white transition-all duration-200 shadow-sm
                ${iniciandoProcesamiento
                  ? 'bg-gray-400 cursor-not-allowed'
                  : 'bg-blue-600 hover:bg-blue-700 hover:shadow-md active:scale-95'
                }`}
            >
              {iniciandoProcesamiento ? (
                <>
                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Iniciando...
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Iniciar procesamiento
                </>
              )}
            </button>
          )}
          <button
            onClick={onClose}
            className="px-5 py-2.5 rounded-xl font-semibold text-sm text-gray-700 bg-white border border-gray-200 hover:bg-gray-100 transition-colors"
          >
            Cerrar
          </button>
        </div>
      </div>
    </div>
  );
}

// Modal para auditorías globales (tareas en background)
function GlobalAuditModal({ modal, onClose, onConsultar, consultando, onIniciarProceso, iniciandoProceso }) {
  const { label, task_id, resultado } = modal;

  const hayPendientes = resultado && (resultado.result?.con_pendientes > 0 || resultado.result?.con_errores > 0);
  const esCompletado = resultado && !hayPendientes;

  const headerBg = !resultado
    ? 'bg-slate-50 border-b border-slate-100'
    : esCompletado
      ? 'bg-green-50 border-b border-green-100'
      : 'bg-amber-50 border-b border-amber-100';

  const badge = !resultado ? (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold bg-gray-200 text-gray-600">
      <span className="w-2 h-2 rounded-full bg-gray-400"></span>
      En cola
    </span>
  ) : esCompletado ? (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold bg-green-100 text-green-700">
      <span className="w-2 h-2 rounded-full bg-green-500"></span>
      Completado
    </span>
  ) : (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-sm font-semibold bg-amber-100 text-amber-700">
      <span className="w-2 h-2 rounded-full bg-amber-500"></span>
      Pendientes
    </span>
  );

  const handleIniciarCorreccion = () => {
    setIniciandoCorreccion(true);
    setTimeout(() => {
      setIniciandoCorreccion(false);
    }, 1500);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="w-full max-w-2xl bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden flex flex-col max-h-[90vh]">
        {/* Header */}
        <div className={`px-6 py-4 flex-shrink-0 ${headerBg}`}>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs font-medium text-gray-500 uppercase tracking-wide">Auditoría Global</p>
              <h3 className="text-lg font-bold text-gray-900 mt-0.5">{label}</h3>
            </div>
            {badge}
          </div>
        </div>

        {/* Cuerpo scrolleable */}
        <div className="px-6 py-5 space-y-4 overflow-y-auto">
          {!resultado ? (
            /* Fase: tarea lanzada, esperando resultado */
            <>
              <div className="flex items-center justify-center w-12 h-12 mx-auto mb-1 bg-slate-100 rounded-full">
                <svg className="w-6 h-6 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <p className="text-center text-gray-600 text-sm">La tarea fue enviada al worker. Consulta el resultado cuando haya finalizado.</p>
              <div className="flex items-center justify-center gap-2">
                <span className="text-xs text-gray-400">Task ID:</span>
                <span className="font-mono text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded select-all">{task_id}</span>
              </div>
            </>
          ) : (
            /* Fase: resultado disponible */
            <>
              {/* Icono de estado */}
              {esCompletado ? (
                <div className="flex items-center justify-center w-12 h-12 mx-auto mb-1 bg-green-100 rounded-full">
                  <svg className="w-7 h-7 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7" />
                  </svg>
                </div>
              ) : (
                <div className="flex items-center justify-center w-12 h-12 mx-auto mb-1 bg-amber-100 rounded-full">
                  <svg className="w-7 h-7 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
              )}

              <p className="text-center text-gray-700 font-medium text-sm">{resultado.mensaje}</p>

              {/* Grid de cifras */}
              <div className="grid grid-cols-4 gap-2">
                <div className="flex flex-col items-center p-3 bg-gray-50 rounded-xl border border-gray-100">
                  <span className="text-2xl font-bold text-gray-900">{resultado.result?.total_pedimentos ?? '—'}</span>
                  <span className="text-xs text-gray-500 mt-0.5 text-center">Total</span>
                </div>
                <div className="flex flex-col items-center p-3 bg-green-50 rounded-xl border border-green-100">
                  <span className="text-2xl font-bold text-green-700">{resultado.result?.completados ?? '—'}</span>
                  <span className="text-xs text-green-600 mt-0.5 text-center">Completos</span>
                </div>
                <div className="flex flex-col items-center p-3 bg-amber-50 rounded-xl border border-amber-100">
                  <span className="text-2xl font-bold text-amber-700">{resultado.result?.con_pendientes ?? '—'}</span>
                  <span className="text-xs text-amber-600 mt-0.5 text-center">Pendientes</span>
                </div>
                <div className="flex flex-col items-center p-3 bg-red-50 rounded-xl border border-red-100">
                  <span className="text-2xl font-bold text-red-700">{resultado.result?.con_errores ?? '—'}</span>
                  <span className="text-xs text-red-600 mt-0.5 text-center">Errores</span>
                </div>
              </div>

              {/* Tabla de pedimentos con pendientes */}
              {resultado.detalle_pendientes && resultado.detalle_pendientes.length > 0 && (
                <details className="rounded-xl border border-amber-100 overflow-hidden" open>
                  <summary className="flex items-center justify-between px-4 py-2.5 bg-amber-50 text-sm font-semibold text-amber-800 cursor-pointer list-none select-none">
                    <span>Pedimentos con pendientes ({resultado.detalle_pendientes.length})</span>
                    <svg className="w-4 h-4 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </summary>
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-amber-100 text-xs">
                      <thead className="bg-amber-50/60">
                        <tr>
                          <th className="px-4 py-2 text-left font-semibold text-amber-900">Pedimento</th>
                          <th className="px-4 py-2 text-left font-semibold text-amber-900">Documentos faltantes</th>
                          <th className="px-4 py-2 text-center font-semibold text-amber-900">Progreso</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-amber-50 bg-white max-h-52 overflow-y-auto">
                        {resultado.detalle_pendientes.map((item, i) => {
                          const faltantesEntries = Object.entries(item).filter(([k]) => k.startsWith('faltantes_'));
                          const todosLosIds = faltantesEntries.flatMap(([, v]) => Array.isArray(v) ? v : []);
                          return (
                            <tr key={i} className="hover:bg-amber-50/40">
                              <td className="px-4 py-2 font-mono font-semibold text-gray-800 whitespace-nowrap">
                                {item.pedimento}
                              </td>
                              <td className="px-4 py-2">
                                <div className="flex flex-wrap gap-1">
                                  {todosLosIds.map((id, j) => (
                                    <span key={j} className="inline-block px-1.5 py-0.5 bg-amber-100 text-amber-800 rounded font-mono text-xs">
                                      {id}
                                    </span>
                                  ))}
                                  {todosLosIds.length === 0 && (
                                    <span className="text-gray-400 italic">sin detalle</span>
                                  )}
                                </div>
                              </td>
                              <td className="px-4 py-2 text-center whitespace-nowrap text-gray-600">
                                {item.descargados ?? '?'}<span className="text-gray-400">/{item.total ?? '?'}</span>
                              </td>
                            </tr>
                          );
                        })}
                      </tbody>
                    </table>
                  </div>
                </details>
              )}

              {/* Tabla de errores */}
              {resultado.detalle_errores && resultado.detalle_errores.length > 0 && (
                <details className="rounded-xl border border-red-200 overflow-hidden">
                  <summary className="flex items-center justify-between px-4 py-2.5 bg-red-50 text-sm font-semibold text-red-800 cursor-pointer list-none select-none">
                    <span>Errores ({resultado.detalle_errores.length})</span>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </summary>
                  <div className="overflow-x-auto">
                    <table className="min-w-full divide-y divide-red-100 text-xs">
                      <thead className="bg-red-50/60">
                        <tr>
                          <th className="px-4 py-2 text-left font-semibold text-red-900">Pedimento</th>
                          <th className="px-4 py-2 text-left font-semibold text-red-900">Error</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-red-50 bg-white">
                        {resultado.detalle_errores.map((item, i) => (
                          <tr key={i} className="hover:bg-red-50/40">
                            <td className="px-4 py-2 font-mono font-semibold text-gray-800 whitespace-nowrap">{item.pedimento}</td>
                            <td className="px-4 py-2 text-red-700">{item.error || '—'}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </details>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <div className={`px-6 py-4 flex-shrink-0 flex gap-3 border-t border-gray-100 bg-gray-50 ${hayPendientes ? 'justify-between' : 'justify-end'}`}>
          {/* Botón "Consultar estado" cuando aún no hay resultado */}
          {!resultado && (
            <button
              onClick={onConsultar}
              disabled={consultando}
              className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl font-semibold text-sm text-white transition-all duration-200 shadow-sm
                ${consultando ? 'bg-slate-400 cursor-not-allowed' : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md active:scale-95'}`}
            >
              {consultando ? (
                <>
                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Consultando...
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  Consultar estado
                </>
              )}
            </button>
          )}

          {/* Botón "Iniciar Proceso" cuando hay resultado con pendientes/errores */}
          {hayPendientes && (
            <button
              onClick={onIniciarProceso}
              disabled={iniciandoProceso}
              className={`inline-flex items-center gap-2 px-5 py-2.5 rounded-xl font-semibold text-sm text-white transition-all duration-200 shadow-sm
                ${iniciandoProceso ? 'bg-gray-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700 hover:shadow-md active:scale-95'}`}
            >
              {iniciandoProceso ? (
                <>
                  <svg className="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Iniciando...
                </>
              ) : (
                <>
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  Iniciar Proceso
                </>
              )}
            </button>
          )}

          <button
            onClick={onClose}
            className="px-5 py-2.5 rounded-xl font-semibold text-sm text-gray-700 bg-white border border-gray-200 hover:bg-gray-100 transition-colors"
          >
            Cerrar
          </button>
        </div>
      </div>
    </div>
  );
}

function Auditor() {
  const { showMessage } = useNotification();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [pedimentos, setPedimentos] = useState([]);
  const [showInstructions, setShowInstructions] = useState(false);
  const [count, setCount] = useState(0);
  const [page, setPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [auditando, setAuditando] = useState(false);
  const [auditandoPartidas, setAuditandoPartidas] = useState(false);
  const [auditandoRemesas, setAuditandoRemesas] = useState(false);
  const [procesandoPedimento, setProcesandoPedimento] = useState(null);
  const [procesandoPartida, setProcesandoPartida] = useState(null);
  const [procesandoRemesa, setProcesandoRemesa] = useState(null);
  const [procesandoAcuse, setProcesandoAcuse] = useState(null);
  const [procesandoAcuseCove, setProcesandoAcuseCove] = useState(null);
  const [procesandoCove, setProcesandoCove] = useState(null);
  const [procesandoEdocumento, setProcesandoEdocumento] = useState(null);
  const [auditandoAcusesCove, setAuditandoAcusesCove] = useState(false);
  const [pedimentoFilter, setPedimentoFilter] = useState('');
  const [auditandoEDocuments, setAuditandoEDocuments] = useState(false);
  const [auditandoAcuses, setAuditandoAcuses] = useState(false);
  const [showXmlModal, setShowXmlModal] = useState(false);
  const [xmlData, setXmlData] = useState(null);

  // Estados para modal de preview
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewUrl, setPreviewUrl] = useState('');
  const [previewType, setPreviewType] = useState('');
  const [previewLoading, setPreviewLoading] = useState(false);
  const [previewError, setPreviewError] = useState('');
  const [previewXml, setPreviewXml] = useState('');
  const [previewXmlHtml, setPreviewXmlHtml] = useState('');
  const [previewDoc, setPreviewDoc] = useState(null);
  const [previewContent, setPreviewContent] = useState('');
  const [imageZoom, setImageZoom] = useState(1);
  const [previewIframeLoaded, setPreviewIframeLoaded] = useState(false);

  // === Estados Peticiones a VU === //
  const [peticionPedimentoVU, setPeticionPedimentoVU] = useState(null); // ID del pedimento en procesamiento
  const [viewPeticionPedimentoVU, setViewPeticionPedimentoVU] = useState(null); // ID del pedimento para ver XML

  const [detalleModalXml, setDetalleModalXml] = useState(null);

  // Agrega este estado cerca de los otros estados
  const [activeVista, setActiveVista] = useState(null); // 'pc', 'rm', 'pt', 'ac', 'cove', 'ac_cove', 'edoc'

  // Modal de resultado de auditoría individual
  const [auditResultModal, setAuditResultModal] = useState(null); // { tipo, pedimento_app, data }
  const [iniciandoProcesamiento, setIniciandoProcesamiento] = useState(false);

  // Modal de auditoría global (tareas en background)
  const [globalAuditModal, setGlobalAuditModal] = useState(null); // { label, procesamiento, organizacion_id, task_id, resultado }
  const [consultandoTask, setConsultandoTask] = useState(false);
  const [iniciandoProcesoGlobal, setIniciandoProcesoGlobal] = useState(false);

  const handleIniciarProcesoGlobal = async () => {
    if (!globalAuditModal?.procesamiento || !globalAuditModal?.organizacion_id || iniciandoProcesoGlobal) return;
    try {
      setIniciandoProcesoGlobal(true);
      const response = await postWithAuth(`${API_URL}/customs/procesamientopedimentos-ejecutar-comando/`, {
        procesamiento: globalAuditModal.procesamiento,
        organizacionid: globalAuditModal.organizacion_id,
      });
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || errorData.error || `Error ${response.status}`);
      }
      const data = await response.json();
      showMessage(data.message || 'Proceso iniciado correctamente', 'success');
      setGlobalAuditModal(null);
    } catch (error) {
      showMessage(error.message || 'Error al iniciar el proceso', 'error');
    } finally {
      setIniciandoProcesoGlobal(false);
    }
  };

  const handleIniciarProcesamiento = async () => {
    if (!auditResultModal || iniciandoProcesamiento) return;
    const { tipo, pedimento_id } = auditResultModal;
    const urlPath = PROCESAMIENTO_URL_MAP[tipo];
    if (!urlPath) {
      showMessage('No hay endpoint de procesamiento disponible para este tipo', 'info');
      return;
    }
    try {
      setIniciandoProcesamiento(true);
      const response = await postWithAuth(`${API_URL}/customs/pedimentos/${pedimento_id}/${urlPath}/`);
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || errorData.error || `Error ${response.status}`);
      }
      const data = await response.json();
      showMessage(data.status || 'Procesamiento iniciado correctamente', 'success');
      setAuditResultModal(null);
    } catch (error) {
      showMessage(error.message || 'Error al iniciar el procesamiento', 'error');
    } finally {
      setIniciandoProcesamiento(false);
    }
  };

  const handleConsultarTask = async () => {
    if (!globalAuditModal?.task_id || consultandoTask) return;
    try {
      setConsultandoTask(true);
      const response = await getWithAuth(`${API_URL}/tasks/status/${globalAuditModal.task_id}/`);
      if (!response.ok) throw new Error('Error al consultar el estado de la tarea');
      const data = await response.json();
      if (data.ready) {
        setGlobalAuditModal(prev => ({ ...prev, resultado: data }));
      } else {
        showMessage('La tarea aún no ha finalizado, intenta nuevamente en unos segundos', 'info');
      }
    } catch (error) {
      showMessage(error.message || 'Error al consultar tarea', 'error');
    } finally {
      setConsultandoTask(false);
    }
  };

  // Handler para auditar acuses (general)
  const handleAuditarAcuses = async () => {
    if (auditandoAcuses) return;
    try {
      setAuditandoAcuses(true);
      const organizacionId = pedimentos[0]?.organizacion;
      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-acuse/`, {
        organizacion_id: organizacionId
      });
      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría de acuses');
      }
      const data = await response.json();
      setGlobalAuditModal({ label: 'Acuses', procesamiento: 'acuses', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });
    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría de acuses', 'error');
    } finally {
      setAuditandoAcuses(false);
    }
  };

  // Handler para auditar EDocuments (general)
  const handleAuditarEDocuments = async () => {
    if (auditandoEDocuments) return;
    try {
      setAuditandoEDocuments(true);
      const organizacionId = pedimentos[0]?.organizacion;
      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-edocuments/`, {
        organizacion_id: organizacionId
      });
      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría de EDocuments');
      }
      const data = await response.json();
      setGlobalAuditModal({ label: 'EDocuments', procesamiento: 'edocs', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });
    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría de EDocuments', 'error');
    } finally {
      setAuditandoEDocuments(false);
    }
  };

  // Handler para auditar acuses cove (general)
  const handleAuditarAcusesCove = async () => {
    if (auditandoAcusesCove) return;
    try {
      setAuditandoAcusesCove(true);
      const organizacionId = pedimentos[0]?.organizacion;
      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-acuse-cove/`, {
        organizacion_id: organizacionId
      });
      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría de acuses cove');
      }
      const data = await response.json();
      setGlobalAuditModal({ label: 'Acuses de COVE', procesamiento: 'acuse_coves', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });
    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría de acuses cove', 'error');
    } finally {
      setAuditandoAcusesCove(false);
    }
  };

  // Handler para auditar un pedimento específico
  const handleAuditarPedimento = async (pedimentoId) => {
    if (procesandoPedimento) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoPedimento(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-pedimento/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        throw new Error('Error al auditar el pedimento');
      }
      const data = await response.json();
      setAuditResultModal({ tipo: 'pc', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al auditar el pedimento', 'error');
    } finally {
      setProcesandoPedimento(null);
    }
  };

  // Handler para auditar remesas de un pedimento específico
  const handleAuditarRemesaPedimento = async (pedimentoId) => {
    if (procesandoRemesa) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoRemesa(pedimentoId);

      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-remesa/pedimento/`, {
        pedimento_id: pedimentoId
      });

      if (!response.ok) {
        throw new Error('Error al procesar las remesas del pedimento');
      }

      const data = await response.json();
      setAuditResultModal({ tipo: 'rm', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al procesar las remesas del pedimento', 'error');
    } finally {
      setProcesandoRemesa(null);
    }
  };

  const handleAuditarRemesas = async () => {
    if (auditandoRemesas) return;

    try {
      setAuditandoRemesas(true);
      const organizacionId = pedimentos[0]?.organizacion;

      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }

      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-remesas/`, {
        organizacion_id: organizacionId
      });

      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría de remesas');
      }

      const data = await response.json();
      setGlobalAuditModal({ label: 'Remesas', procesamiento: 'remesas', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });

    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría de remesas', 'error');
    } finally {
      setAuditandoRemesas(false);
    }
  };

  const handleAuditarPartidasPedimento = async (pedimentoId) => {
    if (procesandoPartida) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);

    try {
      setProcesandoPartida(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/crear-partidas/pedimento/`, {
        pedimento_id: pedimentoId
      });

      if (!response.ok) {
        throw new Error('Error al procesar las partidas del pedimento');
      }

      const data = await response.json();
      setAuditResultModal({ tipo: 'pt', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al procesar las partidas del pedimento', 'error');
    } finally {
      setProcesandoPartida(null);
    }
  };

  const handleAuditarPartidas = async () => {
    if (auditandoPartidas) return;

    try {
      setAuditandoPartidas(true);
      const organizacionId = pedimentos[0]?.organizacion;

      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }

      const response = await postWithAuth(`${API_URL}/customs/auditor/crear-partidas/organizacion/`, {
        organizacion_id: organizacionId
      });

      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría de partidas');
      }

      const data = await response.json();
      setGlobalAuditModal({ label: 'Partidas', procesamiento: 'partidas', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });

    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría de partidas', 'error');
    } finally {
      setAuditandoPartidas(false);
    }
  };

  const handleAuditarTodos = async () => {
    if (auditando) return;

    try {
      setAuditando(true);
      const organizacionId = pedimentos[0]?.organizacion;

      if (!organizacionId) {
        throw new Error('No hay organización disponible para auditar');
      }

      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-pedimentos/`, {
        organizacion_id: organizacionId
      });

      if (!response.ok) {
        throw new Error('Error al iniciar la auditoría');
      }

      const data = await response.json();
      setGlobalAuditModal({ label: 'Pedimentos', organizacion_id: organizacionId, task_id: data.task_id, resultado: null });

    } catch (error) {
      showMessage(error.message || 'Error al iniciar la auditoría', 'error');
    } finally {
      setAuditando(false);
    }
  };

  const handleAuditarAcusePedimento = async (pedimentoId) => {
    if (procesandoAcuse) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoAcuse(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-acuse/pedimento/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        throw new Error('Error al auditar acuse del pedimento');
      }
      const data = await response.json();
      setAuditResultModal({ tipo: 'ac', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al auditar acuse del pedimento', 'error');
    } finally {
      setProcesandoAcuse(null);
    }
  };

 const handleAuditarAcusesCovePedimento = async (pedimentoId) => {
    if (procesandoAcuseCove) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoAcuseCove(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-acuse-cove/pedimento/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        throw new Error('Error al auditar acuse cove del pedimento');
      }
      const data = await response.json();
      setAuditResultModal({ tipo: 'ac_cove', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al auditar acuse cove del pedimento', 'error');
    } finally {
      setProcesandoAcuseCove(null);
    }

 };

const handleAuditarEDocumentPedimento = async (pedimentoId) => {
    if (procesandoEdocumento) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoEdocumento(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-edocument/pedimento/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        throw new Error('Error al auditar eDocument del pedimento');
      }
      const data = await response.json();
      setAuditResultModal({ tipo: 'edoc', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al auditar eDocument del pedimento', 'error');
    } finally {
      setProcesandoEdocumento(null);
    }
  };

  const handleAuditarCovePedimento = async (pedimentoId) => {
    if (procesandoCove) return;
    const pedimento = pedimentos.find(p => p.id === pedimentoId);
    try {
      setProcesandoCove(pedimentoId);
      const response = await postWithAuth(`${API_URL}/customs/auditor/auditar-cove/pedimento/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        throw new Error('Error al auditar COVE del pedimento');
      }
      const data = await response.json();
      setAuditResultModal({ tipo: 'cove', pedimento_id: pedimentoId, pedimento_app: pedimento?.pedimento_app, data });
    } catch (error) {
      showMessage(error.message || 'Error al auditar COVE del pedimento', 'error');
    } finally {
      setProcesandoCove(null);
    }
  };

  const handlePeticionPedimentoVU = async (pedimentoId, pedimentoApp) => {
    if(peticionPedimentoVU) return;

    try
    {
      setPeticionPedimentoVU(pedimentoId);
      const response = await postWithAuth(`${API_URL}/record/microservice/pedimento-completo/`, {
        pedimento_id: pedimentoId
      });
      if (!response.ok) {
        showMessage('Error al intentar realizar la peticion de pedimento VU', 'warning');
        return;
      }

      // const dataResponse = await response.json();

      // alert('El pedimento VU se está auditando. ID Tarea: '+dataResponse.task_id);
      
      showMessage(`Pedimento ${pedimentoApp} en proceso peticion VU (prueba)`, 'success');
    }catch(error)
    {
      showMessage(error.message || 'Error peticion pedimento VU', 'error');
    }finally
    {
      setPeticionPedimentoVU(null);
    }
  }; 

//  const handleViewXmlPedimentoVURequest= async (pedimentoId) => {
     
//      setShowXmlModal(false);
  
//      if (viewPeticionPedimentoVU) return;

//     try {

//         setViewPeticionPedimentoVU(pedimentoId);

//         const response = await postWithAuth(`${API_URL}/customs/auditor/peticion-respuesta/pedimento-vu/`, {
//           pedimento_id: pedimentoId
//         });

//         if (!response.ok) {
//           showMessage('Error al intentar mostrar la peticion de pedimento VU', 'error');
//           setViewPeticionPedimentoVU(null);
//           return;
//         }
//         const data = await response.json();
//         // ¡IMPORTANTE! Extraer los datos JSON de la respuesta

//         console.log('Respuesta peticion pedimento VU:', data);
//         setXmlData(data);
//         setShowXmlModal(true);

//     }catch(error) {
//       showMessage(error.message || 'Error en vista de peticion pedimento VU', 'error');
//     }finally
//     {
//       setViewPeticionPedimentoVU(null);
//     }


//     // showMessage(`${API_URL}/customs/auditor/peticion-respuesta/pedimento-vu/`, 'error');
//   };

  // const handleModalPeticionRespuesta = async (pedimento, vista_auditar) => {

  //    setShowXmlModal(false);

  //    if (detalleModalXml) return;

  //    try{

  //       setDetalleModalXml(pedimento);

  //       // Crear el objeto de datos basado en 'pedimento'
  //       // const data = {
  //       //   id: pedimento.id,
  //       //   pedimento_app: pedimento.pedimento_app,
  //       //   organizacion: pedimento.organizacion ? pedimento.organizacion : null,
  //       //   contribuyente: pedimento.contribuyente ? pedimento.contribuyente.rfc : null,
  //       //   creado: pedimento.created_at,
  //       // };

  //       const response = await postWithAuth(`${API_URL}/customs/auditor/peticion-respuesta/pedimento-vu/`, {
  //         pedimento_id: pedimento.id
  //       });

  //       if (!response.ok) {
  //         showMessage('Error al intentar mostrar la peticion de pedimento VU', 'error');
  //         setDetalleModalXml(null);
  //         return;
  //       }
  //       const data = await response.json();
  //       data.vista = vista_auditar;

  //       // console.log('Respuesta peticion pedimento VU:', data);
  //       setXmlData(data);
  //       setShowXmlModal(true);

  //       console.log('pedimento para modal peticion/response VU:', pedimento);

  //    } catch(error) {
  //       showMessage(error.message || 'Error en vista de peticion pedimento VU', 'error');
  //    }finally {
  //       setDetalleModalXml(null);
  //    }

  //   // console.log('Mostrar modal peticion/response para pedimento:', pedimento);
  // };

  const handleModalPeticionRespuesta = async (pedimento, vista_auditar) => {

    setShowXmlModal(false);
    setActiveVista(vista_auditar);

    if (detalleModalXml) return;

    try {

      setDetalleModalXml(pedimento);
      let endpoint = `${API_URL}/customs/auditor/peticion-respuesta/pedimento-vu/`;

      const response = await postWithAuth(endpoint, {
        pedimento_id: pedimento.id,
        vista: vista_auditar
      });

      if (!response.ok) {
        // Obtener el JSON de error que devuelve Django
        const errorData = await response.json();
        const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;
        
        showMessage(`No se encontró datos para auditoría: ${getVistaNombre(vista_auditar)}. Detalle: ${errorMessage}`, 'warning');
                    
        // showMessage(`Error al obtener datos para vista ${vista_auditar}`, 'error');
        setDetalleModalXml(null);
        return;
      }

      const data = await response.json();
      data.vista = vista_auditar;
      data.vista_nombre = getVistaNombre(vista_auditar); // Función helper

      setXmlData(data);
      setShowXmlModal(true);

    } catch (error) {
      showMessage(error.message || `Error en vista ${vista_auditar}`, 'error');
    }
    finally {
      setDetalleModalXml(null);
    }

  };

  const getVistaNombre = (vista) => {
    const nombres = {
      'pc': 'Pedimento Completo',
      'rm': 'Remesas',
      'pt': 'Partidas',
      'ac': 'Acuse',
      'cove': 'COVE',
      'ac_cove': 'Acuse de COVE',
      'edoc': 'E-Document'
    };
  return nombres[vista] || vista;
};

  const formatFileSize = (bytes) => {
    if (!bytes) return 'N/A';
    const kb = bytes / 1024;
    if (kb < 1024) {
      return `${kb.toFixed(1)} KB`;
    }
    const mb = kb / 1024;
    return `${mb.toFixed(1)} MB`;
  };

  const previewDocument = async (doc) => {
    await handlePreview(doc);
  };

  // Vista previa de documento
  const handlePreview = async (doc) => {
      setPreviewLoading(true);
      setPreviewError('');
      setPreviewUrl('');
      setPreviewType('');
      setPreviewXml('');
      setPreviewDoc(doc);
      setImageZoom(1);
      setPreviewContent('');
      setPreviewIframeLoaded(false);
      setPreviewOpen(true);
      try {
        const res = await fetchWithAuth(`${API_URL}/record/documents/descargar/${doc.id}/`);
        
        if (!res.ok) {
          setPreviewError('Error al obtener el archivo');
          setPreviewLoading(false);
          return;
        }
        
        // Detectar tipo de archivo
        let type = '';
        if (doc.extension) {
          if (doc.extension.toLowerCase() === 'pdf') type = 'pdf';
          else if (["jpg","jpeg","png","gif","bmp","webp"].includes(doc.extension.toLowerCase())) type = 'img';
          else if (doc.extension.toLowerCase() === 'xml') type = 'xml';
          else if (["txt","log","csv"].includes(doc.extension.toLowerCase())) type = 'txt';
          else type = 'other';
        }
        setPreviewType(type);
        
        if (type === 'xml') {
          const text = await res.text();
          const prettyText = formatXml(text);
          setPreviewXml(prettyText);
          // Formatear y resaltar XML
          try {
            const highlighted = hljs.highlight(prettyText, { language: 'xml' }).value;
            setPreviewXmlHtml(highlighted);
          } catch (e) {
            setPreviewXmlHtml(prettyText);
          }
          setPreviewLoading(false);
        } else if (type === 'txt') {
          const text = await res.text();
          setPreviewContent(text);
          setPreviewLoading(false);
        } else {
          const blob = await res.blob();
          if (blob.size === 0) {
            setPreviewError('El archivo está vacío o no está disponible en el servidor.');
            setPreviewLoading(false);
            return;
          }
          const url = window.URL.createObjectURL(blob);
          setPreviewUrl(url);
          setPreviewLoading(false);
        }
      } catch (err) {
        console.error('Error en vista previa:', err);
        if (err.message === 'SESSION_EXPIRED') {
          setPreviewError('Tu sesión ha expirado, por favor inicia sesión de nuevo.');
        } else {
          setPreviewError('Error al obtener el archivo');
        }
        setPreviewLoading(false);
      }
  };

  const handleSwitchPeticion = (vista_auditar, pedimentoId, doc = null) => {

     // Si se pasa un documento específico, úsalo
    if (doc) {
      previewDocument(doc);
      return;
    }

    switch (vista_auditar) {
      case 'pc':
        handlePreviewPeticionPedimentoVU(pedimentoId);
        break;
      case 'rm':
        handlePreviewPeticionRemesaVU(pedimentoId);
        break;
      case 'pt':
        handlePreviewPeticionPartidasVU(pedimentoId);
        break;
      case 'ac':
        handlePreviewPeticionAcuseVU(pedimentoId);
        break;
      case 'cove':
        handlePreviewPeticionCoveVU(pedimentoId);
        break;
      case 'ac_cove':
        handlePreviewPeticionAcuseCoveVU(pedimentoId);
        break;
      case 'edoc':
        handlePreviewPeticionEdocVU(pedimentoId);
        break;
      default:
        // handlePreviewPeticionPedimentoVU(pedimentoId);
        showMessage('Vista no reconocida para petición VU', 'warning');
        break;
    }
  };

  const handleSwitchRespuesta= (vista_auditar, pedimentoId, doc = null) => {

    if (doc) {
      previewDocument(doc);
      return;
    }

    switch (vista_auditar) {
      case 'pc':
        handlePreviewRespuestaPedimentoVU(pedimentoId);
        break;
      case 'rm':
        handlePreviewRespuestaRemesaVU(pedimentoId);
        break;
      case 'pt':
        handlePreviewRespuestaPartidasVU(pedimentoId);
        break;
      case 'ac':
        handlePreviewRespuestaAcuseVU(pedimentoId);
        break;
      case 'cove':
        handlePreviewRespuestaCoveVU(pedimentoId);
        break;
      case 'ac_cove':
        handlePreviewRespuestaAcuseCoveVU(pedimentoId);
        break;
      case 'edoc':
        handlePreviewRespuestaEdocVU(pedimentoId);
        break;
      default:
        // handlePreviewPeticionPedimentoVU(pedimentoId);
        showMessage('Vista no reconocida para respuesta VU', 'warning');
        break;
    }
  };

  // Vista previa de petición Pedimento VU
  const handlePreviewPeticionPedimentoVU = async (pedimentoId) => {
    
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/pedimento-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      console.error('Error al obtener petición VU:', error);
      showMessage('Error al cargar la petición VU', 'error');
    }
  };

  // Vista previa de respuesta Pedimento VU
  const handlePreviewRespuestaPedimentoVU = async (pedimentoId) => {
        try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/pedimento-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      console.error('Error al obtener petición VU:', error);
      showMessage('Error al cargar la petición VU', 'error');
    }
  };

    // Vista previa de petición Remesa VU
  const handlePreviewPeticionRemesaVU = async (pedimentoId) => {
    
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/remesa-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      console.error('Error al obtener petición VU:', error);
      showMessage('Error al cargar la petición VU', 'error');
    }
  };

  // Vista previa de respuesta Remesa VU
  const handlePreviewRespuestaRemesaVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/remesa-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de petición Partidas VU
  const handlePreviewPeticionPartidasVU = async (pedimentoId) => {
    // Obtener el documento de petición
        try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/partidas-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      showMessage(`Error al cargar la petición VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de respuesta Partidas VU
  const handlePreviewRespuestaPartidasVU = async (pedimentoId) => {
    try {
        // Obtener el documento de respuesta
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/partidas-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de petición Acuse VU
  const handlePreviewPeticionAcuseVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/acuse-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la petición VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de respuesta Acuse VU
  const handlePreviewRespuestaAcuseVU = async (pedimentoId) => {
    try {
        // Obtener el documento de respuesta
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/acuse-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de petición COVE VU
  const handlePreviewPeticionCoveVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/cove-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la petición VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de respuesta COVE VU
  const handlePreviewRespuestaCoveVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/cove-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de petición Acuse COVE VU
  const handlePreviewPeticionAcuseCoveVU = async (pedimentoId) => {
    // Obtener el documento de petición
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/acuse-cove-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      showMessage(`Error al cargar la petición VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };
    
  // Vista previa de respuesta Acuse COVE VU
  const handlePreviewRespuestaAcuseCoveVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/acuse-cove-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de petición E-Document VU
  const handlePreviewPeticionEdocVU = async (pedimentoId) => {
    // Obtener el documento de petición
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-peticion/edocument-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de petición VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {
      showMessage(`Error al cargar la petición VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  // Vista previa de respuesta E-Document VU
  const handlePreviewRespuestaEdocVU = async (pedimentoId) => {
    try {
        // Obtener el documento de petición
        const response = await postWithAuth(`${API_URL}/customs/auditor/obtener-respuesta/edocument-vu/`, {
          pedimento_id: pedimentoId
        });

        if (!response.ok) {
           // Obtener el JSON de error que devuelve Django
          const errorData = await response.json();

          const errorMessage = errorData.error || 
                          `Error ${response.status}: ${response.statusText}`;

          showMessage(`No se encontró archivo de respuesta VU: ${errorMessage}`, 'warning');
          return;
        }

        const documento = await response.json();

        // Llamar a la función de vista previa existente
        await previewDocument(documento);

    }catch(error) {

      showMessage(`Error al cargar la respuesta VU: ${error.message|| 'Error desconocido'}`, 'error');
    }
  };

  const downloadDocument = async (doc) => {
    const fileName = doc.archivo ? doc.archivo.split('/').pop() : `documento_${doc.id}`;
    await downloadFile(doc.id, fileName, showMessage);
  };

  // Cerrar modal y limpiar blob
  const handleClosePreview = () => {
    setPreviewOpen(false);
    if (previewUrl) window.URL.revokeObjectURL(previewUrl);
    setPreviewUrl('');
    setPreviewType('');
    setPreviewError('');
    setPreviewXml('');
    setPreviewXmlHtml('');
    setPreviewDoc(null);
    setPreviewContent('');
    setImageZoom(1);
    setPreviewIframeLoaded(false);
  };

// Función para formatear XML (pretty print)
function formatXml(xml) {
  const PADDING = '  ';
  const reg = /(>)(<)(\/*)/g;
  let formatted = '';
  let pad = 0;
  xml = xml.replace(reg, '$1\r\n$2$3');
  xml.split(/\r?\n/).forEach((node) => {
    let indent = 0;
    if (node.match(/.+<\/\w[^>]*>$/)) {
      indent = 0;
    } else if (node.match(/^<\/\w/)) {
      if (pad !== 0) pad -= 1;
    } else if (node.match(/^<\w[^>]*[^\/]>/)) {
      indent = 1;
    }
    formatted += PADDING.repeat(pad) + node + '\r\n';
    pad += indent;
  });
  return formatted.trim();
}

  useEffect(() => {
    const fetchPedimentos = async () => {
      setLoading(true);
      try {
        const queryParams = new URLSearchParams({
          page: page.toString(),
          page_size: itemsPerPage.toString(),
          ...(pedimentoFilter && { search: pedimentoFilter })
        });
        const response = await getWithAuth(`${API_URL}/customs/pedimentos/?${queryParams}`);
        if (!response.ok) throw new Error('Error al cargar los pedimentos');
        const data = await response.json();
        setPedimentos(data.results);
        setCount(data.count);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    // Aplicar debounce al fetchPedimentos
    const timeoutId = setTimeout(() => {
      fetchPedimentos();
    }, 300);

    return () => clearTimeout(timeoutId);
  }, [page, itemsPerPage, pedimentoFilter]);

  return (
    <div className="min-h-screen p-4 bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 sm:p-6 lg:p-8">
      <div className="mx-auto max-w-7xl">
        {/* Header mejorado y responsivo */}
        <div className="relative flex items-center gap-4 p-6 mb-6 overflow-hidden shadow-2xl opacity-0 sm:mb-8 rounded-3xl bg-gradient-to-r from-blue-600 via-blue-700 to-blue-800 sm:p-8 sm:gap-6 animate-fadein-slideup"
          style={{ animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.05s forwards' }}>
          <div className="flex-shrink-0 p-3 rounded-full shadow-lg bg-white/20 backdrop-blur-sm sm:p-4 animate-bounce-slow">
            <svg className="w-8 h-8 text-white sm:h-10 sm:w-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
            </svg>
          </div>
          <div className="flex-1 min-w-0">
            <h1 className="mb-1 text-2xl font-extrabold tracking-tight text-white sm:text-3xl lg:text-4xl">
              Panel de Auditoría
            </h1>
            <div className="flex items-center gap-4">
              <p className="text-sm font-medium leading-relaxed text-blue-100 sm:text-lg">
                Monitoreo y control de operaciones
              </p>
              <button
                onClick={() => setShowInstructions(true)}
                className="inline-flex items-center px-3 py-1 text-sm font-medium leading-4 text-blue-700 transition-colors duration-200 bg-blue-100 border border-transparent rounded-md hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                <svg className="mr-1.5 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Instrucciones
              </button>
            </div>
          </div>
          {/* Efectos decorativos de fondo */}
          <div className="absolute pointer-events-none select-none -top-10 -right-10 opacity-20">
            <div className="w-32 h-32 rounded-full bg-white/10 blur-xl"></div>
          </div>
          <div className="absolute pointer-events-none select-none -bottom-6 -left-6 opacity-15">
            <div className="w-24 h-24 rounded-full bg-white/10 blur-lg"></div>
          </div>
          {/* Partículas flotantes */}
          <div className="absolute inset-0 overflow-hidden pointer-events-none">
            <div className="absolute w-2 h-2 rounded-full top-1/4 left-1/4 bg-white/30 animate-ping"></div>
            <div className="absolute w-1 h-1 rounded-full top-3/4 right-1/3 bg-white/40 animate-pulse"></div>
            <div className="absolute w-3 h-3 rounded-full top-1/2 right-1/4 bg-white/20 animate-bounce"></div>
          </div>
        </div>

        {/* Contenido principal */}
        <div className="p-4 bg-white border border-gray-100 shadow-2xl opacity-0 rounded-3xl sm:p-6 lg:p-8 animate-fadein-slideup"
          style={{ animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.15s forwards' }}>

          {loading ? (
            <div className="flex flex-col items-center justify-center py-12">
              <div className="relative">
                <div className="w-16 h-16 border-b-2 border-blue-600 rounded-full animate-spin"></div>
                <div className="absolute inset-0 rounded-full bg-blue-500/10 blur-xl animate-pulse"></div>
              </div>
              <p className="mt-4 font-medium text-gray-600">Cargando datos...</p>
            </div>
          ) : error ? (
            <div className="p-6 text-center border border-red-200 bg-red-50 rounded-2xl">
              <div className="flex items-center justify-center w-12 h-12 p-3 mx-auto mb-4 bg-red-100 rounded-full">
                <svg className="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <h3 className="mb-2 text-lg font-semibold text-red-800">Error al cargar</h3>
              <p className="text-red-600">{error}</p>
            </div>
          ) : (
            <div className="space-y-6">
              <div className="p-4 bg-white border border-gray-200 shadow-sm rounded-2xl sm:p-6">

                <div className="flex items-center justify-between mb-6">
                  <h3 className="flex items-center gap-2 text-xl font-semibold text-gray-900">
                    <svg className="w-6 h-6 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                    </svg>
                    Servicios de Auditoría
                  </h3>
                  <div className="flex flex-wrap gap-2 justify-end">
                    <button
                      onClick={handleAuditarAcusesCove}
                      disabled={auditandoAcusesCove || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditandoAcusesCove
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditandoAcusesCove ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="hidden sm:inline">Auditando </span>Acuses Cove...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          <span className="hidden sm:inline">Auditar</span> Acuses Cove
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleAuditarEDocuments}
                      disabled={auditandoEDocuments || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditandoEDocuments
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditandoEDocuments ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="hidden sm:inline">Auditando </span>EDocuments...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          <span className="hidden sm:inline">Auditar </span>EDocuments
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleAuditarAcuses}
                      disabled={auditandoAcuses || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditandoAcuses
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditandoAcuses ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="hidden sm:inline">Auditando </span>Acuses...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          <span className="hidden sm:inline">Auditar </span>Acuses
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleAuditarTodos}
                      disabled={auditando || auditandoPartidas || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditando || auditandoPartidas
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditando ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          Auditando...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01" />
                          </svg>
                          <span className="hidden sm:inline">Auditar </span>Pedimentos
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleAuditarPartidas}
                      disabled={auditando || auditandoPartidas || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditando || auditandoPartidas
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditandoPartidas ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="hidden sm:inline">Auditando </span>Partidas...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                          </svg>
                          <span className="hidden sm:inline">Auditar </span>Partidas
                        </>
                      )}
                    </button>

                    <button
                      onClick={handleAuditarRemesas}
                      disabled={auditando || auditandoRemesas || pedimentos.length === 0}
                      className={`inline-flex items-center px-3 py-2 text-sm rounded-lg shadow-sm text-white transition-all duration-200
                        ${auditando || auditandoRemesas
                          ? 'bg-slate-400 cursor-not-allowed'
                          : 'bg-slate-600 hover:bg-slate-700 hover:shadow-md'
                        }
                      `}
                    >
                      {auditandoRemesas ? (
                        <>
                          <svg className="w-4 h-4 mr-2 text-white animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="hidden sm:inline">Auditando </span>Remesas...
                        </>
                      ) : (
                        <>
                          <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                          </svg>
                          <span className="hidden sm:inline">Auditar </span>Remesas
                        </>
                      )}
                    </button>
                  </div>
                </div>

                {/* Sección de Filtros */}
                <div className="p-6 mt-6 bg-white border border-gray-200 rounded-lg">
                  <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
                    {/* Contenedor para los filtros - esperando instrucciones */}
                    <div className="col-span-full">
                      <h3 className="mb-4 text-lg font-medium text-gray-900">
                        Filtros de Búsqueda
                      </h3>
                    </div>
                    <div className="col-span-1">
                      <label htmlFor="pedimento" className="block mb-2 text-sm font-medium text-gray-700">
                        Número de Pedimento
                      </label>
                      <div className="relative rounded-md shadow-sm">
                        <input
                          type="text"
                          name="pedimento"
                          id="pedimento"
                          value={pedimentoFilter}
                          onChange={(e) => setPedimentoFilter(e.target.value)}
                          className="block w-full py-2 pl-3 pr-10 border-gray-300 rounded-md focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                          placeholder="Buscar por pedimento..."
                        />
                        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                          <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                          </svg>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Tabla de pedimentos */}
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-300">
                    <thead>
                      <tr>
                        <th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
                          Pedimento
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900 group">
                          PC
                          <span className="block text-xs text-gray-500">Pedimento Completo</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          RM
                          <span className="block text-xs text-gray-500">Remesas</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          PT
                          <span className="block text-xs text-gray-500">Partidas</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          AC
                          <span className="block text-xs text-gray-500">Acuse</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          COVE
                          <span className="block text-xs text-gray-500">Cove</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          AC_COVE
                          <span className="block text-xs text-gray-500">Acuse de Cove</span>
                        </th>
                        <th scope="col" className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">
                          EDoc
                          <span className="block text-xs text-gray-500">EDocument</span>
                        </th>
                      </tr>
                    </thead>
                    <tbody className="bg-white divide-y divide-gray-200">
                      {pedimentos.map((pedimento) => (
                        <tr key={pedimento.id} className="hover:bg-gray-50">
                          <td className="py-4 pl-4 pr-3 text-sm font-medium text-gray-900 whitespace-nowrap">
                            <Link to={`/expedientes/pedimento/${pedimento.id}`} className='hover:text-blue-500 hover:text-bold hover:text-underline'>{pedimento.pedimento_app}</Link>
                          </td>
                          {/* PC - Pedimento Completo */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button 
                              onClick={() => handleAuditarPedimento(pedimento.id)}
                              // onClick={handlePeticionPedimentoVU(pedimento.id)}
                              // disabled = {peticionPedimentoVU}
                              title='Auditar Pedimento Completo'
                              className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110">
                                <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                  <path d="M8 5v14l11-7z" />
                                </svg>
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleModalPeticionRespuesta(pedimento,"pc")}
                              title='Ver Petición y Respuesta de Pedimento Completo'
                              >
                                <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                </svg>
                              </button>
                            </div>
                          </td>
                          {/* RM - Remesas */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button
                              onClick={() => handleAuditarRemesaPedimento(pedimento.id)}
                              title='Auditar Remesa'
                              disabled={procesandoRemesa === pedimento.id}
                              className={`inline-flex items-center justify-center w-8 h-8 rounded-full bg-white border border-gray-200 
                                ${procesandoRemesa === pedimento.id
                                  ? 'opacity-50 cursor-not-allowed'
                                  : 'shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200 hover:scale-110'
                                }
                              `}
                              >
                              {procesandoRemesa === pedimento.id ? (
                                <svg className="w-4 h-4 text-gray-600 animate-spin" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                              ) : (
                                <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                  <path d="M8 5v14l11-7z" />
                                </svg>
                              )}
                            </button>
                            {/* nuevo botón “view” */}
                            <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                             onClick={() => handleModalPeticionRespuesta(pedimento,"rm")}
                             title='Ver Petición y Respuesta de Remesas'
                             >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                            </button>
                            </div>
                          </td>
                          {/* PT - Partidas */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button
                              onClick={() => handleAuditarPartidasPedimento(pedimento.id)}
                              title='Auditar Partidas'
                              disabled={procesandoPartida === pedimento.id}
                              className={`inline-flex items-center justify-center w-8 h-8 rounded-full bg-white border border-gray-200 
                                ${procesandoPartida === pedimento.id
                                  ? 'opacity-50 cursor-not-allowed'
                                  : 'shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200 hover:scale-110'
                                }
                              `}
                            >
                              {procesandoPartida === pedimento.id ? (
                                <svg className="w-4 h-4 text-gray-600 animate-spin" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                              ) : (
                                <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                  <path d="M8 5v14l11-7z" />
                                </svg>
                              )}
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleModalPeticionRespuesta(pedimento,"pt")}
                              title='Ver Petición y Respuesta de Partidas'
                              >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                              </button>
                            </div>
                          </td>
                          {/* AC - Acuse */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button
                              onClick={() => handleAuditarAcusePedimento(pedimento.id)}
                              title='Auditar Acuse'
                              disabled={procesandoAcuse === pedimento.id}
                              className={`inline-flex items-center justify-center w-8 h-8 rounded-full bg-white border border-gray-200 ${procesandoAcuse === pedimento.id
                                ? 'opacity-50 cursor-not-allowed'
                                : 'shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200 hover:scale-110'
                                }`}
                            >
                              {procesandoAcuse === pedimento.id ? (
                                <svg className="w-4 h-4 text-gray-600 animate-spin" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                              ) : (
                                <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                  <path d="M8 5v14l11-7z" />
                                </svg>
                              )}
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleModalPeticionRespuesta(pedimento,"ac")}
                              title='Ver Petición y Respuesta de Acuse'
                              >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                              </button>
                            </div>
                          </td>
                          {/* COVE */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button
                              onClick={() => handleAuditarCovePedimento(pedimento.id)}
                              title='Auditar Cove'
                              disabled={procesandoCove === pedimento.id}
                              className={`inline-flex items-center justify-center w-8 h-8 rounded-full bg-white border border-gray-200 ${procesandoCove === pedimento.id
                                ? 'opacity-50 cursor-not-allowed'
                                : 'shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-all duration-200 hover:scale-110'
                                }`}
                            >
                              {procesandoCove === pedimento.id ? (
                                <svg className="w-4 h-4 text-gray-600 animate-spin" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                              ) : (
                                <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                  <path d="M8 5v14l11-7z" />
                                </svg>
                              )}
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleModalPeticionRespuesta(pedimento,"cove")}
                              title='Ver Petición y Respuesta de Cove'
                              >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                              </button>
                            </div>
                          </td>
                          {/* AC_COVE */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleAuditarAcusesCovePedimento(pedimento.id)}
                              title='Auditar Acuse COVE'>
                              <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M8 5v14l11-7z" />
                              </svg>
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleModalPeticionRespuesta(pedimento,"ac_cove")}
                              title='Ver Petición y Respuesta de Acuse COVE'
                              >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                              </button>
                            </div>
                          </td>
                          {/* EDoc */}
                          <td className="px-3 py-4 text-sm text-center text-gray-500 whitespace-nowrap">
                            <div className="inline-flex items-center gap-2">
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                              onClick={() => handleAuditarEDocumentPedimento(pedimento.id)}
                              title='Auditar EDocument'>
                              <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M8 5v14l11-7z" />
                              </svg>
                              </button>
                              {/* nuevo botón “view” */}
                              <button className="inline-flex items-center justify-center w-8 h-8 transition-all duration-200 bg-white border border-gray-200 rounded-full shadow-sm hover:shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 hover:scale-110"
                             onClick={() => handleModalPeticionRespuesta(pedimento,"edoc")}
                             title='Ver Petición y Respuesta de EDocument'
                             >
                              <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                              </svg>
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Paginación */}
                {count > 0 && (
                  <div className="flex items-center justify-between mt-4">
                    <div className="flex justify-between flex-1 sm:hidden">
                      <button
                        onClick={() => setPage(page => Math.max(1, page - 1))}
                        disabled={page === 1}
                        className="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                      >
                        Anterior
                      </button>
                      <button
                        onClick={() => setPage(page => page + 1)}
                        disabled={page >= Math.ceil(count / itemsPerPage)}
                        className="relative inline-flex items-center px-4 py-2 ml-3 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
                      >
                        Siguiente
                      </button>
                    </div>
                    <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                      <div>
                        <p className="text-sm text-gray-700">
                          Mostrando <span className="font-medium">{((page - 1) * itemsPerPage) + 1}</span> a{' '}
                          <span className="font-medium">{Math.min(page * itemsPerPage, count)}</span> de{' '}
                          <span className="font-medium">{count}</span> resultados
                        </p>
                      </div>
                      <div>
                        <nav className="relative z-0 inline-flex -space-x-px rounded-md shadow-sm">
                          <button
                            onClick={() => setPage(1)}
                            disabled={page === 1}
                            className="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-l-md hover:bg-gray-50"
                          >
                            <span className="sr-only">Primera</span>
                            ««
                          </button>
                          <button
                            onClick={() => setPage(page => Math.max(1, page - 1))}
                            disabled={page === 1}
                            className="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 hover:bg-gray-50"
                          >
                            <span className="sr-only">Anterior</span>
                            «
                          </button>
                          <span className="relative inline-flex items-center px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300">
                            Página {page}
                          </span>
                          <button
                            onClick={() => setPage(page => page + 1)}
                            disabled={page >= Math.ceil(count / itemsPerPage)}
                            className="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 hover:bg-gray-50"
                          >
                            <span className="sr-only">Siguiente</span>
                            »
                          </button>
                          <button
                            onClick={() => setPage(Math.ceil(count / itemsPerPage))}
                            disabled={page >= Math.ceil(count / itemsPerPage)}
                            className="relative inline-flex items-center px-2 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-r-md hover:bg-gray-50"
                          >
                            <span className="sr-only">Última</span>
                            »»
                          </button>
                        </nav>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Modal de Instrucciones */}
      {showInstructions && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50">
          <div className="w-full max-w-2xl transition-all transform bg-white rounded-lg shadow-xl">
            <div className="flex items-center justify-between px-6 py-4 border-b">
              <h3 className="flex items-center gap-2 text-xl font-semibold text-gray-900">
                <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Instrucciones de Auditoría
              </h3>
              <button
                onClick={() => setShowInstructions(false)}
                className="text-gray-400 hover:text-gray-500 focus:outline-none"
              >
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="px-6 py-4 space-y-6">
              <div className="space-y-4">
                <div>
                  <h4 className="flex items-center gap-2 mb-2 text-lg font-medium text-gray-900">
                    <svg className="w-5 h-5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                    </svg>
                    Auditar Todos los Pedimentos
                  </h4>
                  <p className="text-gray-600 ml-7">Este proceso revisará uno a uno cada XML del pedimento completo y agregará los campos restantes en nuestra tabla de pedimentos. Si el documento tiene COVEs y E-Docs, también los subirá a nuestra base de datos.</p>
                </div>
                <div>
                  <h4 className="flex items-center gap-2 mb-2 text-lg font-medium text-gray-900">
                    <svg className="w-5 h-5 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    Auditar Partidas
                  </h4>
                  <p className="text-gray-600 ml-7">Creará todas las partidas de cada uno de los pedimentos, extrayendo la información detallada de cada una.</p>
                </div>
                <div>
                  <h4 className="flex items-center gap-2 mb-2 text-lg font-medium text-gray-900">
                    <svg className="w-5 h-5 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                    </svg>
                    Auditar Remesas
                  </h4>
                  <p className="text-gray-600 ml-7">Obtendrá y agregará todos los COVEs existentes en el documento a nuestra base de datos.</p>
                </div>
              </div>
            </div>
            <div className="px-6 py-4 rounded-b-lg bg-gray-50">
              <button
                onClick={() => setShowInstructions(false)}
                className="inline-flex items-center justify-center w-full px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
              >
                Entendido
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal de auditoría global */}
      {globalAuditModal && (
        <GlobalAuditModal
          modal={globalAuditModal}
          onClose={() => setGlobalAuditModal(null)}
          onConsultar={handleConsultarTask}
          consultando={consultandoTask}
          onIniciarProceso={handleIniciarProcesoGlobal}
          iniciandoProceso={iniciandoProcesoGlobal}
        />
      )}

      {/* Modal de resultado de auditoría individual */}
      {auditResultModal && (
        <AuditResultModal
          modal={auditResultModal}
          iniciandoProcesamiento={iniciandoProcesamiento}
          onClose={() => setAuditResultModal(null)}
          onIniciarProcesamiento={handleIniciarProcesamiento}
        />
      )}

      {/* Modal de Vista Previa XML */}
      {/* {showXmlModal && xmlData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-40">
          <div className="flex flex-col w-full max-w-sm p-8 bg-white border border-blue-200 shadow-2xl rounded-xl animate-fade-in">
            <h3 className="mb-2 text-lg font-bold text-blue-900">Detalle de Xml</h3>
            <div className="mb-1"><b>Pedimento:</b> {xmlData.pedimento_app}</div>
            <div className="mb-1"><b>Archivo Petición:</b>Vista Previa</div>
            <div className="mb-1"><b>Archivo de Respuesta:</b>Vista Previa</div>
            <div className="mb-1"><b>Contribuyente:</b> {xmlData.contribuyente || 'N/A'}</div>
            <div className="mb-1"><b>Organización:</b> {xmlData.organizacion || 'N/A'}</div>
            <div className="mb-1"><b>Creado:</b>{new Date(xmlData.creado).toLocaleString('es-MX') || 'N/A'}</div>
            <button onClick={() => setShowXmlModal(false)} className="px-3 py-1 mt-2 transition bg-gray-300 rounded hover:bg-gray-400">Cerrar</button>
            <pre className="p-4 overflow-auto text-xs bg-gray-100">{JSON.stringify(xmlData, null, 2)}</pre>
          </div>
        </div>    
      )} */}
      {/* Modal de Vista Previa XML */}
      {showXmlModal && xmlData && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-40">
          <div className="flex flex-col w-full max-w-4xl p-8 bg-white border border-blue-200 shadow-2xl rounded-xl animate-fade-in max-h-[80vh]">
            <h3 className="mb-4 text-lg font-bold text-blue-900">
              {getVistaNombre(xmlData.vista)} - {xmlData.pedimento_app}
            </h3>
            
            <div className="space-y-4 overflow-y-auto pr-2 max-h-[60vh]">
              <div className="mb-4">
                <div className="mb-2"><b>Contribuyente:</b> {xmlData.contribuyente || 'N/A'}</div>
                <div className="mb-2"><b>Organización:</b> {xmlData.organizacion || 'N/A'}</div>
                <div className="mb-4"><b>Creado:</b> {new Date(xmlData.creado).toLocaleString('es-MX') || 'N/A'}</div>
              </div>
              
              {/* Si hay múltiples documentos - nueva funcionalidad para manejar listado */}
              {(xmlData.documentos_peticiones || xmlData.documentos_respuestas) ? (
                <>
                  {/* Mostrar documentos de peticiones si existen */}
                  {xmlData.documentos_peticiones && xmlData.documentos_peticiones.length > 0 && (
                    <div className="mb-6">
                      <details className="group">
                        <summary className="flex items-center justify-between p-3 font-semibold text-gray-800 list-none bg-gray-100 rounded-lg cursor-pointer hover:bg-gray-200">
                          <div className="flex items-center gap-2">
                            <svg className="w-5 h-5 text-blue-600 transition-transform group-open:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                            </svg>
                            <span>Peticiones ({xmlData.total_documentos_peticiones || 0})</span>
                          </div>
                          <div className="flex items-center gap-2 text-sm font-normal text-gray-600">
                            <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                            </svg>
                            <span>Click para expandir/colapsar</span>
                          </div>
                        </summary>
                        <div className="p-4 mt-2 space-y-3 border border-gray-200 rounded-lg">
                          {xmlData.documentos_peticiones.map((doc, index) => (
                            <div key={doc.id || index} className="p-4 transition-colors border border-gray-200 rounded-lg hover:bg-gray-50">
                              <div className="flex items-center justify-between mb-2">
                                <div className="flex-1 min-w-0">
                                  <div className="font-medium text-gray-900 truncate">
                                    {doc.archivo_original || `Documento ${index + 1}`}
                                  </div>
                                  <div className="flex items-center gap-3 mt-1 text-sm text-gray-500">
                                    {doc.tipo && (
                                      <span className="bg-blue-100 text-blue-800 px-2 py-0.5 rounded text-xs">
                                        {doc.tipo}
                                      </span>
                                    )}
                                    {doc.size && (
                                      <span className="text-xs text-gray-600">
                                        {formatFileSize(doc.size)}
                                      </span>
                                    )}
                                    {doc.extension && (
                                      <span className="text-xs text-gray-600">
                                        {doc.extension.toUpperCase()}
                                      </span>
                                    )}
                                  </div>
                                </div>
                                
                                <div className="flex flex-col gap-2 ml-4">
                                  <button 
                                    onClick={() => previewDocument(doc)}
                                    className="px-3 py-1.5 text-blue-600 transition-colors rounded bg-blue-50 hover:bg-blue-100 hover:text-blue-800 text-sm whitespace-nowrap"
                                    title="Vista previa del documento"
                                  >
                                    Vista Previa
                                  </button>
                                </div>
                              </div>
                              
                              {/* Información adicional del documento */}
                              <div className="mt-2 text-xs text-gray-500">
                                <div className="grid grid-cols-2 gap-2">
                                  {doc.creado_en && (
                                    <div>
                                      <span className="font-medium">Creado:</span> {new Date(doc.creado_en).toLocaleString('es-MX')}
                                    </div>
                                  )}
                                  {doc.actualizado_en && (
                                    <div>
                                      <span className="font-medium">Actualizado:</span> {new Date(doc.actualizado_en).toLocaleString('es-MX')}
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </details>
                    </div>
                  )}
                  
                  {/* Mostrar documentos de respuestas si existen */}
                  {xmlData.documentos_respuestas && xmlData.documentos_respuestas.length > 0 && (
                    <div className="mb-6">
                      <details className="group" >
                        <summary className="flex items-center justify-between p-3 font-semibold text-gray-800 list-none bg-gray-100 rounded-lg cursor-pointer hover:bg-gray-200">
                          <div className="flex items-center gap-2">
                            <svg className="w-5 h-5 text-green-600 transition-transform group-open:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                            </svg>
                            <span>Respuestas ({xmlData.total_documentos_respuestas || 0})</span>
                          </div>
                          <div className="flex items-center gap-2 text-sm font-normal text-gray-600">
                            <svg className="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                            <span>Click para expandir/colapsar</span>
                          </div>
                        </summary>
                        <div className="p-4 mt-2 space-y-3 border border-gray-200 rounded-lg">
                          {xmlData.documentos_respuestas.map((doc, index) => (
                            <div key={doc.id || index} className="p-4 transition-colors border border-gray-200 rounded-lg hover:bg-gray-50">
                              <div className="flex items-center justify-between mb-2">
                                <div className="flex-1 min-w-0">
                                  <div className="font-medium text-gray-900 truncate">
                                    {doc.archivo_original || `Documento ${index + 1}`}
                                  </div>
                                  <div className="flex items-center gap-3 mt-1 text-sm text-gray-500">
                                    {doc.tipo && (
                                      <span className="bg-green-100 text-green-800 px-2 py-0.5 rounded text-xs">
                                        {doc.tipo}
                                      </span>
                                    )}
                                    {doc.size && (
                                      <span className="text-xs text-gray-600">
                                        {formatFileSize(doc.size)}
                                      </span>
                                    )}
                                    {doc.extension && (
                                      <span className="text-xs text-gray-600">
                                        {doc.extension.toUpperCase()}
                                      </span>
                                    )}
                                  </div>
                                </div>
                                
                                <div className="flex flex-col gap-2 ml-4">
                                  <button 
                                    onClick={() => previewDocument(doc)}
                                    className="px-3 py-1.5 text-green-600 transition-colors rounded bg-green-50 hover:bg-green-100 hover:text-green-800 text-sm whitespace-nowrap"
                                    title="Vista previa del documento"
                                  >
                                    Vista Previa
                                  </button>
                                </div>
                              </div>
                              
                              {/* Información adicional del documento */}
                              <div className="mt-2 text-xs text-gray-500">
                                <div className="grid grid-cols-2 gap-2">
                                  {doc.creado_en && (
                                    <div>
                                      <span className="font-medium">Creado:</span> {new Date(doc.creado_en).toLocaleString('es-MX')}
                                    </div>
                                  )}
                                  {doc.actualizado_en && (
                                    <div>
                                      <span className="font-medium">Actualizado:</span> {new Date(doc.actualizado_en).toLocaleString('es-MX')}
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </details>
                    </div>
                  )}
                </>
              ) : (
                /* Para compatibilidad hacia atrás - caso de un solo documento */
                <>
                  {/* Enlace para Archivo de Petición */}
                  <div className="p-3 border border-gray-200 rounded-lg hover:bg-gray-50">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="font-medium text-gray-900">Archivo de Petición</div>
                        <div className="text-sm text-gray-500">XML enviado a VU</div>
                      </div>
                      <button 
                        onClick={() => handleSwitchPeticion(xmlData.vista, xmlData.id)}
                        className="px-3 py-1 text-blue-600 transition-colors rounded bg-blue-50 hover:bg-blue-100 hover:text-blue-800"
                      >
                        Vista Previa
                      </button>
                    </div>
                  </div>
                  
                  {/* Enlace para Archivo de Respuesta */}
                  <div className="p-3 border border-gray-200 rounded-lg hover:bg-gray-50">
                    <div className="flex items-center justify-between">
                      <div>
                        <div className="font-medium text-gray-900">Archivo de Respuesta</div>
                        <div className="text-sm text-gray-500">XML recibido de VU</div>
                      </div>
                      <button 
                        onClick={() => handleSwitchRespuesta(xmlData.vista, xmlData.id)}
                        className="px-3 py-1 text-green-600 transition-colors rounded bg-green-50 hover:bg-green-100 hover:text-green-800"
                      >
                        Vista Previa
                      </button>
                    </div>
                  </div>
                </>
              )}
              
              {/* Botón para ver datos crudos (opcional) */}
              {/* <details className="mt-4">
                <summary className="px-3 py-2 text-sm text-gray-600 bg-gray-100 rounded cursor-pointer hover:bg-gray-200">
                  Ver datos completos
                </summary>
                <pre className="p-3 mt-2 overflow-auto text-xs bg-gray-100 border border-gray-300 rounded max-h-60">
                  {JSON.stringify(xmlData, null, 2)}
                </pre>
              </details> */}
            </div>
            
            <div className="flex justify-end gap-2 mt-6">
              <button 
                onClick={() => setShowXmlModal(false)} 
                className="w-full px-4 py-3 font-medium text-gray-700 transition-colors bg-gray-100 rounded-lg hover:bg-gray-200"
              >
                Cerrar
              </button>
            </div>
          </div>
        </div>    
      )}

      
      {/* Modal de vista previa mejorado */}
      {previewOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
          <div className="bg-white/95 backdrop-blur-xl rounded-2xl shadow-2xl border border-blue-200/50 overflow-hidden relative flex flex-col w-full max-w-6xl h-full max-h-[95vh]">
            {/* Header del modal con gradiente e información del archivo */}
            <div className="flex items-center justify-between px-6 py-4 text-white bg-gradient-to-r from-blue-600 to-blue-800">
              <div className="flex items-center flex-1 min-w-0 gap-4">
                <div className="flex-shrink-0 p-2 bg-white/20 rounded-xl">
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                  </svg>
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="text-xl font-bold truncate">Vista previa de documento</h3>
                  {previewDoc && (
                    <div className="flex items-center gap-3 mt-1 text-sm text-blue-100">
                      <span className="truncate">{previewDoc.archivo_original || 'Sin nombre'}</span>
                      {previewDoc.size && (
                        <span className="bg-white/20 px-2 py-0.5 rounded-lg text-xs font-medium">
                          {formatFileSize(previewDoc.size)}
                        </span>
                      )}
                      {previewDoc.extension && (
                        <span className="bg-white/20 px-2 py-0.5 rounded-lg text-xs font-medium uppercase">
                          {previewDoc.extension}
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </div>
              
              {/* Controles del header */}
              <div className="flex items-center flex-shrink-0 gap-2">
                {/* Botón de descarga siempre visible */}
                {previewDoc && (
                  <button
                    onClick={() => downloadDocument(previewDoc)}
                    className="p-2 transition-colors duration-200 bg-white/20 hover:bg-white/30 rounded-xl group"
                    title="Descargar documento"
                  >
                    <svg className="w-5 h-5 transition-transform group-hover:scale-110" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                  </button>
                )}
                
                {/* Controles de zoom para imágenes */}
                {previewType === 'img' && (
                  <div className="flex items-center gap-1 p-1 bg-white/20 rounded-xl">
                    <button
                      onClick={() => setImageZoom(Math.max(0.2, imageZoom - 0.2))}
                      className="p-1.5 hover:bg-white/20 rounded-lg transition-colors text-xs"
                      title="Alejar"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M20 12H4" />
                      </svg>
                    </button>
                    <span className="px-2 text-xs font-medium">{Math.round(imageZoom * 100)}%</span>
                    <button
                      onClick={() => setImageZoom(Math.min(3, imageZoom + 0.2))}
                      className="p-1.5 hover:bg-white/20 rounded-lg transition-colors text-xs"
                      title="Acercar"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                    </button>
                    <button
                      onClick={() => setImageZoom(1)}
                      className="p-1.5 hover:bg-white/20 rounded-lg transition-colors text-xs"
                      title="Tamaño original"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 8V4m0 0h4M4 4l5 5m11-5v4m0-4h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                      </svg>
                    </button>
                  </div>
                )}
                
                {/* Botón cerrar */}
                <button
                  onClick={handleClosePreview}
                  className="p-2 transition-colors duration-200 bg-white/20 hover:bg-red-500/80 rounded-xl"
                  title="Cerrar vista previa"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>

            {/* Contenido del modal */}
            <div className="flex flex-col flex-1 min-h-0 bg-gray-50">
              {previewLoading ? (
                <div className="flex items-center justify-center flex-1">
                  <div className="text-center">
                    <div className="inline-flex items-center space-x-3 text-blue-600">
                      <svg className="w-10 h-10 animate-spin" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span className="text-lg font-medium">Cargando documento...</span>
                    </div>
                    <p className="mt-2 text-gray-500">Preparando vista previa</p>
                  </div>
                </div>
              ) : previewError ? (
                <div className="flex items-center justify-center flex-1">
                  <div className="max-w-md text-center text-red-600">
                    <div className="flex items-center justify-center w-20 h-20 mx-auto mb-4 rounded-full bg-red-50">
                      <svg className="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                    </div>
                    <h4 className="mb-2 text-lg font-semibold">Error al cargar documento</h4>
                    <p className="text-sm text-gray-600">{previewError}</p>
                    <button
                      onClick={() => { setPreviewError(null); if (previewDoc) handlePreview(previewDoc); }}
                      className="px-4 py-2 mt-4 text-red-800 transition-colors bg-red-100 rounded-lg hover:bg-red-200"
                    >
                      Volver a cargar
                    </button>
                  </div>
                </div>
              ) : previewType === 'pdf' ? (
                <div className="relative flex-1 bg-white">
                  {/* Spinner hasta que el iframe confirme carga */}
                  {!previewIframeLoaded && (
                    <div className="absolute inset-0 z-10 flex items-center justify-center bg-white">
                      <div className="text-center">
                        <div className="inline-flex items-center space-x-3 text-blue-600">
                          <svg className="w-10 h-10 animate-spin" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                          </svg>
                          <span className="text-lg font-medium">Cargando documento...</span>
                        </div>
                      </div>
                    </div>
                  )}
                  <iframe
                    src={previewUrl}
                    title="PDF Preview"
                    className="w-full h-full border-0"
                    style={{ minHeight: '500px' }}
                    onLoad={() => {
                      setPreviewIframeLoaded(true);
                      setPreviewLoading(false);
                    }}
                    onError={() => {
                      setPreviewError('No se pudo cargar el documento PDF.');
                      setPreviewLoading(false);
                    }}
                  />
                </div>
              ) : previewType === 'img' ? (
                <div className="flex items-center justify-center flex-1 p-4 overflow-auto bg-gray-100">
                  <div className="relative">
                    <img 
                      src={previewUrl} 
                      alt="Vista previa" 
                      className="border-2 border-white rounded-lg shadow-lg max-w-none"
                      style={{ 
                        transform: `scale(${imageZoom})`,
                        transformOrigin: 'center',
                        transition: 'transform 0.2s ease'
                      }}
                    />
                  </div>
                </div>
              ) : previewType === 'xml' ? (
                // <div className="flex flex-col flex-1 bg-white">
                <div className="flex flex-col h-full bg-white">
                  <div className="flex items-center justify-between px-6 py-3 bg-gray-100 border-b border-gray-200">
                    <div className="flex items-center gap-2">
                      <div className="bg-green-100 p-1.5 rounded-lg">
                        <svg className="w-4 h-4 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                      </div>
                      <span className="font-medium text-gray-700">Documento XML</span>
                    </div>
                    <button
                      className="inline-flex items-center gap-2 px-4 py-2 text-sm text-blue-600 transition-colors border border-blue-300 rounded-lg hover:text-blue-800 bg-blue-50 hover:bg-blue-100"
                      onClick={() => {
                        navigator.clipboard.writeText(previewXml);
                        // Mostrar notificación de copiado
                      }}
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                      </svg>
                      Copiar XML
                    </button>
                  </div>
                  <pre
                    className="flex-1 p-6 overflow-x-auto overflow-y-auto text-sm bg-white border-l-4 border-green-400"
                    // className="flex-1 p-6 overflow-auto text-sm bg-white border-l-4 border-green-400"
                    style={{ 
                      fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Consolas, "Liberation Mono", Menlo, monospace',
                      lineHeight: '1.6',
                      // minHeight: '400px',
                      width: '100%',
                      whiteSpace: 'pre'
                    }}
                    dangerouslySetInnerHTML={{ __html: previewXmlHtml }}
                  />
                </div>
              ) : previewType === 'txt' ? (
                <div className="flex-1 p-6 overflow-auto bg-white">
                  <div className="p-4 border border-gray-200 rounded-lg bg-gray-50">
                    <div className="flex items-center gap-2 mb-4">
                      <div className="bg-blue-100 p-1.5 rounded-lg">
                        <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                        </svg>
                      </div>
                      <span className="font-medium text-gray-700">Documento de texto</span>
                    </div>
                    <pre className="font-mono text-sm leading-relaxed text-gray-800 whitespace-pre-wrap">
                      {previewContent || 'Contenido no disponible'}
                    </pre>
                  </div>
                </div>
              ) : previewUrl ? (
                <div className="flex items-center justify-center flex-1 p-8 bg-gray-50">
                  <div className="text-center">
                    <div className="flex items-center justify-center w-20 h-20 mx-auto mb-6 rounded-full bg-blue-50">
                      <svg className="w-10 h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                    </div>
                    <h4 className="mb-2 text-lg font-semibold text-gray-900">Vista previa no disponible</h4>
                    <p className="mb-6 text-gray-600">Este tipo de archivo no se puede mostrar en el navegador</p>
                    <a 
                      href={previewUrl} 
                      target="_blank" 
                      rel="noopener noreferrer" 
                      className="inline-flex items-center px-6 py-3 space-x-2 font-medium text-white transition-colors bg-blue-600 shadow-lg hover:bg-blue-700 rounded-xl hover:shadow-xl"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                      </svg>
                      <span>Descargar archivo</span>
                    </a>
                  </div>
                </div>
              ) : (
                <div className="flex items-center justify-center flex-1 p-8">
                  <div className="text-center text-gray-500">
                    <svg className="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <p className="text-lg">No se pudo cargar el documento</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Animaciones CSS */}
      <style>{`
        @keyframes bounce-slow {
          0%, 100% { transform: translateY(0) scale(1); }
          50% { transform: translateY(-8px) scale(1.05); }
        }
        .animate-bounce-slow {
          animation: bounce-slow 3s infinite;
        }
        @keyframes fadein-slideup {
          0% { opacity: 0; transform: translateY(40px); }
          100% { opacity: 1; transform: translateY(0); }
        }
        .animate-fadein-slideup {
          animation: fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.05s forwards;
        }
        @keyframes fade-in {
          from { opacity: 0; transform: scale(0.9) translateY(10px); }
          to { opacity: 1; transform: scale(1) translateY(0); }
        }
        .animate-fade-in {
          animation: fade-in 0.8s ease-out;
        }
      `}</style>
    </div>
  );
}

export default Auditor;
