import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTaskProgress } from '../context/TaskProgressContext';
import { getCurrentUser } from '../api/users';
// Helper to get current user with fetchWithAuth
const fetchCurrentUserWithAuth = async () => {
  const url = `${API_URL}/user/users/me/`;
  const res = await fetchWithAuth(url);
  if (!res.ok) throw new Error('No se pudo obtener el usuario actual');
  return res.json();
};
import { fetchWithAuth } from '../fetchWithAuth';
import { useNotification } from '../context/NotificationContext';
import { extractApiError } from '../api/apiError';
import datastageModelsData from '../data/datastageModels.json';
import pedimentosModelsData from '../data/pedimentosModels.json';

const API_URL = import.meta.env.VITE_EFC_API_URL;

// Animaciones
const animations = `
  @keyframes fadein-slideup {
    0% { opacity: 0; transform: translateY(40px); }
    100% { opacity: 1; transform: translateY(0); }
  }
  @keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
  }
  @keyframes bounce-slow {
    0%, 100% { transform: translateY(0) scale(1); }
    50% { transform: translateY(-8px) scale(1.05); }
  }
  @keyframes pulse-soft {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.8; }
  }
`;

// Inyectar estilos de animación
if (typeof document !== 'undefined' && !document.getElementById('reports-animations')) {
  const style = document.createElement('style');
  style.id = 'reports-animations';
  style.innerHTML = animations;
  document.head.appendChild(style);
}


export default function Reports() {
  // Estado para organizacion_id
  const [organizacionId, setOrganizacionId] = useState('');
  
  useEffect(() => {
    async function fetchOrgId() {
      try {
        const user = await fetchCurrentUserWithAuth();
        if (user && user.organizacion) {
          setOrganizacionId(user.organizacion);
        }
      } catch (err) {
        setOrganizacionId('');
      }
    }
    fetchOrgId();
  }, []);

  const { tasks, addTask } = useTaskProgress();
  const pendingReportTasksRef = useRef(new Set());
  const pollingIntervalRef = useRef(null);

  // Handler for Generar Reporte in Cumplimiento tab
  const handleGenerarReporteCumplimiento = async () => {
    if (!organizacionId) {
      showMessage('No se pudo obtener el ID de organización. Intenta de nuevo más tarde.', 'warning');
      return;
    }
    const paramsObj = { ...filtersCumplimiento, organizacion_id: organizacionId };
    const params = Object.entries(paramsObj)
      .filter(([_, v]) => v)
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      .join('&');
    const url = `${import.meta.env.VITE_EFC_API_URL}/reports/table-summary/${params ? `?${params}` : ''}`;
    try {
      const res = await fetchWithAuth(url);
      if (!res.ok) {
        const errMsg = await extractApiError(res);
        throw new Error(errMsg);
      }
      const data = await res.json();
      if (data.task_id) {
        addTask({
          task_id:        data.task_id,
          label:          'Reporte de Cumplimiento',
          organizacion_id: organizacionId,
          taskType:       'report',
          report_id:      data.report_id,
          status:         'submitted',
        });
        pendingReportTasksRef.current.add(data.task_id);
      }
      showMessage('Reporte solicitado. Puedes ver el progreso en la barra inferior.', 'success');
    } catch (err) {
      showMessage(err.message || 'No se pudo generar el reporte', 'error');
    }
  };
  // Filtros replicados de TableroAlmacenamiento
  const initialFiltersCumplimiento = {
    pedimento_app: '',
    aduana: '',
    patente: '',
    regimen: '',
    agente_aduanal: '',
    tipo_operacion: '',
    fecha_pago_gte: '',
    fecha_pago_lte: '',
    contribuyente__rfc: '',
  };
  const [filtersCumplimiento, setFiltersCumplimiento] = useState(initialFiltersCumplimiento);
  const handleFilterChangeCumplimiento = (e) => {
    setFiltersCumplimiento({ ...filtersCumplimiento, [e.target.name]: e.target.value });
  };
  const [summaryData, setSummaryData] = useState(null);

  const initialFiltersControlPedimento = {
    pedimento_app: '',
    fecha_pago__gte: '',
    fecha_pago__lte: '',
    organizacion_id: organizacionId || '',
  };

  // control_pedimento 
  const [filtersControlPedimento, setFiltersControlPedimento] = useState(initialFiltersControlPedimento);
  const handleFilterChangeControlPedimento = (e) => {
    setFiltersControlPedimento({ ...filtersControlPedimento, [e.target.name]: e.target.value });
  };

  const handleGenerarReporteControlPedimento = async () => {
    // if (!organizacionId ) {
    //   alert('No se pudo obtener el organizacion_id. Intenta de nuevo más tarde.');
    //   return;
    // }
    // Build query params from filtersCumplimiento and add organizacion_id
    const paramsObj = { ...filtersControlPedimento };

    if (paramsObj.organizacion_id === '') {
      showMessage('Selecciona tu organización antes de generar el reporte.', 'warning');
      return;
    }

    const params = Object.entries(paramsObj)
      .filter(([_, v]) => v)
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      .join('&');
    const url = `${import.meta.env.VITE_EFC_API_URL}/reports/control-pedimento/${params ? `?${params}` : ''}`;
    try {
      const res = await fetchWithAuth(url);
      if (!res.ok) {
        const errMsg = await extractApiError(res);
        throw new Error(errMsg);
      }
      showMessage('Reporte solicitado correctamente. Aparecerá en el historial cuando esté listo.', 'success');
      fetchReports();
      startPolling();
    } catch (err) {
      showMessage(err.message || 'No se pudo generar el reporte', 'error');
    }
  };

  // Fetch summary data for dashboard/cards
  const fetchSummary = async () => {
    try {
      const url = `${import.meta.env.VITE_EFC_API_URL}/reports/dashboard/summary/`;
      const res = await fetch(url, {
        method: 'GET',
        credentials: 'include',
        mode: 'cors',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
          'Accept': '*/*',
        },
        referrer: window.location.href,
      });
      if (!res.ok) throw new Error('Error al obtener el resumen');
      const data = await res.json();
      setSummaryData(data);
    } catch (err) {
      setSummaryData(null);
    }
  };
  const [reports, setReports] = useState([]);
  // Leer DEBUG_MODE desde variables de entorno
  const isDebugMode = import.meta.env.VITE_DEBUG_MODE === 'true';
  const { showMessage } = useNotification();

  const handleDownloadReport = async (reportId) => {
    try {
      const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-download/${reportId}/`;
      const res = await fetchWithAuth(url);
      if (!res.ok) {
        const errMsg = await extractApiError(res);
        throw new Error(errMsg);
      }
      const blob = await res.blob();
      const disposition = res.headers.get('Content-Disposition');
      let filename = '';
      if (disposition) {
        const match = disposition.match(/filename="?([^";\s]+)"?/);
        if (match) filename = match[1];
      }
      if (!filename) {
        const isXlsx = blob.type.includes('spreadsheetml') || blob.type.includes('openxmlformats');
        filename = `reporte_${reportId}.${isXlsx ? 'xlsx' : 'csv'}`;
      }
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (err) {
      showMessage(err.message || 'No se pudo descargar el reporte', 'error');
    }
  };

  const [isExporting, setIsExporting] = useState(false);
  const [exportFormat, setExportFormat] = useState('excel');
  const [showExportSuccess, setShowExportSuccess] = useState(false);
  const [showHelp, setShowHelp] = useState(false);
  const [showTour, setShowTour] = useState(false);
  const [tourStep, setTourStep] = useState(0);

  const [organizaciones, setOrganizaciones] = useState([]);
  const [importadores, setImportadores] = useState([]);
  const [rfcOptions, setRfcOptions] = useState([]);
  const [rfcsCumplimiento, setRfcsCumplimiento] = useState([]);

  useEffect(() => {
    const fetchOrganizaciones = async () => {
      try {
        const url = `${import.meta.env.VITE_EFC_API_URL}/organization/organizaciones/`;
        const res = await fetchWithAuth(url); // ← USA fetchWithAuth
        if (!res.ok) throw new Error('Error al obtener las organizaciones');
        const data = await res.json();
        setOrganizaciones(data);
      } catch (err) {
        console.error('Error fetching organizaciones:', err);
        setOrganizaciones([]); // ← Asegurar que siempre sea un array
      }
    };
    fetchOrganizaciones();
  }, []);

  useEffect(() => {
    const fetchImportadores = async () => {
      try {
        const res = await fetch(
          `${import.meta.env.VITE_EFC_API_URL}/customs/importadores/`, 
          { method: 'GET', headers: { 'Authorization': `Bearer ${localStorage.getItem('access')}` } 
        });
        const data = await res.json();
        setImportadores(data);
      } catch {
        console.error('Error fetching importadores:', err);
        setImportadores([]);
      }
    };
    fetchImportadores();
  }, []);

  useEffect(() => {
    if (!organizacionId) return;
    const load = async () => {
      try {
        const url = `${API_URL}/reports/exportmodel/datastage/?organizacion=${organizacionId}`;
        const res = await fetchWithAuth(url);
        if (!res.ok) return;
        const data = await res.json();
        setRfcsCumplimiento(data.rfcs || []);
      } catch {
        setRfcsCumplimiento([]);
      }
    };
    load();
  }, [organizacionId]);

  const [globalFilters, setGlobalFilters] = useState({
    rfc: '',
    fecha_pago_desde: '',
    fecha_pago_hasta: '',
    organizacion: '',
    patente: '',
    pedimento: ''
  });

  // Cargar RFCs cuando cambia la organización seleccionada en filtros globales
  useEffect(() => {
    const fetchRfcs = async () => {
      if (!globalFilters.organizacion) {
        setRfcOptions([]);
        return;
      }
      try {
        const url = `${import.meta.env.VITE_EFC_API_URL}/reports/exportmodel/datastage/?organizacion=${globalFilters.organizacion}`;
        const res = await fetchWithAuth(url);
        if (!res.ok) throw new Error('Error al obtener RFCs');
        const data = await res.json();
        setRfcOptions(data.rfcs || []);
      } catch (err) {
        console.error('Error fetching RFCs:', err);
        setRfcOptions([]);
      }
    };
    fetchRfcs();
  }, [globalFilters.organizacion]);

  const renderGlobalFilters = () => (
    <div className="mb-6">
      <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-blue-100">
        <div className="p-4 border-b border-blue-50">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
            </div>
            <div>
              <h3 className="font-bold text-gray-900">Filtros globales</h3>
              <p className="text-sm text-gray-500">Filtros aplicables a todos los modelos</p>
            </div>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {/* Filtro por Organización */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Organización
              </label>
              <div className="relative rounded-lg shadow-sm">
                <select
                  value={globalFilters.organizacion || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    organizacion: e.target.value,
                    rfc: ''
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white appearance-none"
                >
                  <option value="" disabled>Selecciona una organización</option>
                  {organizaciones.results && organizaciones.results.map(org => (
                    <option key={org.id} value={org.id}>
                      {org.nombre}
                    </option>
                  ))}
                </select>
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
            </div>

            {/* Filtro por RFC */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                RFC
              </label>
              {/* modificar de input a select */}
              <div className="relative rounded-lg shadow-sm">
                {/* <input
                  type="text"
                  value={globalFilters.rfc || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    rfc: e.target.value
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white"
                  placeholder="Ej: ABC123456789"
                /> */}
                <select
                  name="rfc"
                  value={globalFilters.rfc || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    rfc: e.target.value
                  }))}
                  className="w-full px-3 py-2 border border-green-300 rounded-md shadow-sm focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-all duration-200 bg-white text-slate-900 text-sm font-mono uppercase"
                  style={{ textTransform: 'uppercase' }}
                  disabled={!globalFilters.organizacion}
                >
                  <option value="">Todos los RFC</option>
                  {rfcOptions.map(rfc => (
                    <option key={rfc} value={rfc}>{rfc}</option>
                  ))}
                </select>
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <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>

            {/* Filtro por Fecha Pago Desde */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Fecha Pago Desde
              </label>
              <div className="relative rounded-lg shadow-sm">
                <input
                  type="date"
                  value={globalFilters.fecha_pago_desde || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    fecha_pago_desde: e.target.value
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white"
                />
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                </div>
              </div>
            </div>

            {/* Filtro por Fecha Pago Hasta */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Fecha Pago Hasta
              </label>
              <div className="relative rounded-lg shadow-sm">
                <input
                  type="date"
                  value={globalFilters.fecha_pago_hasta || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    fecha_pago_hasta: e.target.value
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white"
                />
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                </div>
              </div>
            </div>

            {/* Filtro por Patente */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Patente
              </label>
              <div className="relative rounded-lg shadow-sm">
                <input
                  type="text"
                  value={globalFilters.patente || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    patente: e.target.value
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white"
                  placeholder="Ej: 1234"
                />
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <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>

            {/* Filtro por Pedimento */}
            <div className="group">
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Pedimento
              </label>
              <div className="relative rounded-lg shadow-sm">
                <input
                  type="text"
                  value={globalFilters.pedimento || ''}
                  onChange={(e) => setGlobalFilters(prev => ({
                    ...prev,
                    pedimento: e.target.value
                  }))}
                  className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                    focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                    transition-all duration-200 bg-white"
                  placeholder="Ej: 1234567"
                />
                <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <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>

          {/* Botón para limpiar filtros globales */}
          <div className="mt-4 flex justify-end">
            <button
              onClick={() => setGlobalFilters({
                rfc: '',
                fecha_pago_desde: '',
                fecha_pago_hasta: '',
                organizacion: '',
                patente: '',
                pedimento: ''
              })}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 
                focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors"
            >
              Limpiar filtros globales
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  // Estado para formato de exportación personalizado
  const [showFormatSelector, setShowFormatSelector] = useState(false);

  // Estado para pestañas — persiste en URL (?tab=...)
  const VALID_TABS = ['pedimentos', 'control_pedimentos', 'datastage', 'Cumplimiento', 'coves'];
  const [activeTab, setActiveTab] = useState(() => {
    const params = new URLSearchParams(window.location.search);
    const tab = params.get('tab');
    return VALID_TABS.includes(tab) ? tab : 'pedimentos';
  });

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    params.set('tab', activeTab);
    history.replaceState(null, '', `${window.location.pathname}?${params.toString()}`);
  }, [activeTab]);

  // Mostrar Cumplimiento en producción: eliminar lógica que oculta la pestaña

  // Importar modelos
  const datastageModels = datastageModelsData?.models || [];
  const pedimentosModels = pedimentosModelsData?.models || [];

  // Obtener el modelo inicial según la pestaña activa
  const initialModels = activeTab === 'pedimentos' ? pedimentosModels : datastageModels;
  const defaultModel = initialModels[0] || { model: '', fields: [], filters: {} };

  // esquema para el resto 
  // Estado para modelo seleccionado
  const [selectedModel, setSelectedModel] = useState(defaultModel.model);
  // Estado para campos seleccionados
  const [selectedFields, setSelectedFields] = useState(defaultModel.fields);
  
  // esquema para el nuevo  
  const [modoMultiple, setModoMultiple] = useState(false);
  const [selectedModels, setSelectedModels] = useState(defaultModel.model);
  const [selectedFieldsDataStage, setSelectedFieldsDataStage] = useState([]);
  const [modelFieldsMap, setModelFieldsMap] = useState({});

  const isModoMultiple = Object.keys(modelFieldsMap).length > 1;

  useEffect(() => {
    if (selectedModel) {
      // Cargar campos previamente seleccionados para este modelo
      const camposGuardados = modelFieldsMap[selectedModel] || [];
      setSelectedFieldsDataStage(camposGuardados);
    }
  }, [selectedModel, modelFieldsMap]);

  // Estado para campo seleccionado en lista disponible
  const [availableSelected, setAvailableSelected] = useState(null);

  // Estado para los filtros
  const [filters, setFilters] = useState(defaultModel.filters);

  // Actualizar campos seleccionados al cambiar de modelo o pestaña
  React.useEffect(() => {
    const models = activeTab === 'pedimentos' ? pedimentosModels : datastageModels;
    // Al cambiar de pestaña, seleccionar el primer modelo de la pestaña actual
    const newModel = models[0]?.model || '';
    setSelectedModel(newModel);

    const modelObj = models.find(m => m.model === newModel);
    if (modelObj) {
      setSelectedFields(modelObj.fields);
      setAvailableSelected(null);
      setFilters(modelObj.filters);
    }
  }, [activeTab]);

  // Efecto separado para cambios de modelo dentro de la misma pestaña
  React.useEffect(() => {
    const models = activeTab === 'pedimentos' ? pedimentosModels : datastageModels;
    const modelObj = models.find(m => m.model === selectedModel);
    if (modelObj) {
      setSelectedFields(modelObj.fields);
      setAvailableSelected(null);
      setFilters(modelObj.filters);
    }
  }, [selectedModel]);

  // Obtener los modelos según la pestaña activa
  const models = activeTab === 'pedimentos' ? pedimentosModels : datastageModels;

  // Encontrar el modelo actual dentro de los modelos de la pestaña activa
  const currentModel = models.find(m => m.model === selectedModel) || defaultModel;

  // Campos disponibles (no seleccionados) del modelo actual
  const availableFields = currentModel.fields.filter(f => !selectedFields.includes(f));

  // Mover campo de disponible a seleccionado
  const addField = (field) => {
    setSelectedFields([...selectedFields, field]);
    setAvailableSelected(null);
  };
  // Mover campo de seleccionado a disponible
  const removeField = (field) => {
    setSelectedFields(selectedFields.filter(f => f !== field));
  };
  // Incluir todos los campos
  const includeAllFields = () => {
    setSelectedFields([...currentModel.fields]);
    setAvailableSelected(null);
  };

  // Renderizar selector dual de campos
  // Estado para campo seleccionado en lista de incluidos
  const [includedSelected, setIncludedSelected] = useState(null);

  // Quitar todos los campos
  const removeAllFields = () => {
    setSelectedFields([]);
    setIncludedSelected(null);
  };

  // Quitar campo seleccionado en incluidos
  const removeSelectedField = () => {
    if (includedSelected) {
      removeField(includedSelected);
      setIncludedSelected(null);
    }
  };

  // Tour steps for guided experience
  const tourSteps = [
    {
      target: '.tab-selector',
      content: '🎯 Comienza seleccionando el tipo de reporte que deseas generar',
      position: 'bottom'
    },
    {
      target: '.model-selector',
      content: '📊 Si elegiste Datastage, selecciona el modelo específico aquí',
      position: 'bottom'
    },
    {
      target: '.format-selector',
      content: '📁 Elige el formato de tu archivo: Excel para análisis avanzado o CSV para compatibilidad',
      position: 'bottom'
    },
    {
      target: '.fields-selector',
      content: '✨ Selecciona los campos que quieres incluir en tu reporte. Puedes agregar o quitar campos fácilmente',
      position: 'top'
    },
    {
      target: '.filters-section',
      content: '🔍 Aplica filtros para obtener exactamente los datos que necesitas',
      position: 'top'
    },
    {
      target: '.export-button',
      content: '🚀 ¡Listo! Haz clic aquí para generar y descargar tu reporte',
      position: 'top'
    }
  ];

  const startTour = () => {
    setShowTour(true);
    setTourStep(0);
  };

  const nextTourStep = () => {
    if (tourStep < tourSteps.length - 1) {
      setTourStep(tourStep + 1);
    } else {
      setShowTour(false);
      setTourStep(0);
    }
  };

  const skipTour = () => {
    setShowTour(false);
    setTourStep(0);
  };

  const fetchReports = useCallback(async () => {
    try {
      const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-list/`;
      const res = await fetchWithAuth(url);
      if (!res.ok) throw new Error('Error al obtener el historial de reportes');
      const data = await res.json();
      setReports(data);
    } catch {
      setReports([]);
    }
  }, []);

  const stopPolling = useCallback(() => {
    if (pollingIntervalRef.current) {
      clearInterval(pollingIntervalRef.current);
      pollingIntervalRef.current = null;
    }
  }, []);

  const startPolling = useCallback(() => {
    if (pollingIntervalRef.current) return;
    pollingIntervalRef.current = setInterval(fetchReports, 5000);
  }, [fetchReports]);

  useEffect(() => { fetchReports(); }, [fetchReports]);

  // Detener polling cuando todos los reportes de control_pedimento lleguen a estado terminal
  useEffect(() => {
    const hasPending = reports
      .filter(r => r.report_type === 'control_pedimento')
      .some(r => r.status !== 'ready' && r.status !== 'error');
    if (!hasPending) stopPolling();
  }, [reports, stopPolling]);

  // Limpiar intervalo al desmontar
  useEffect(() => () => stopPolling(), [stopPolling]);

  // Refrescar historial cuando completa una tarea de reporte de cumplimiento
  useEffect(() => {
    if (!tasks || pendingReportTasksRef.current.size === 0) return;
    let changed = false;
    tasks.forEach(t => {
      if (
        pendingReportTasksRef.current.has(t.task_id) &&
        (t.status === 'completed' || t.status === 'failed')
      ) {
        pendingReportTasksRef.current.delete(t.task_id);
        changed = true;
      }
    });
    if (changed) fetchReports();
  }, [tasks, fetchReports]);

  useEffect(() => {
    fetchSummary();
  }, []);

  // Función para manejar la exportación del modelo
  const handleExportModel = async () => {
    if (selectedFields.length === 0) {
      showMessage('Por favor selecciona al menos un campo para exportar', 'error');
      return;
    }

    setIsExporting(true);
    try {
      // Mostrar indicador de progreso
      const progressDiv = document.createElement('div');
      progressDiv.className = 'fixed bottom-4 right-4 bg-white p-4 rounded-lg shadow-xl border border-blue-100';
      progressDiv.innerHTML = `
        <div class="flex items-center gap-3">
          <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500"></div>
          <p class="text-sm text-gray-600">Preparando exportación...</p>
        </div>
      `;
      document.body.appendChild(progressDiv);

      // Construir filtros no vacíos
      const nonEmptyFilters = Object.entries(filters)
        .reduce((acc, [key, value]) => {
          if (value?.trim()) {
            acc[key] = value.trim();
          }
          return acc;
        }, {});

      // Construir payload
      const payload = {
        model: currentModel.model,
        module: currentModel.module,
        fields: selectedFields,
        type: exportFormat,
        ...(Object.keys(nonEmptyFilters).length > 0 && { filters: nonEmptyFilters }),
      };

      // Realizar la petición
      const response = await fetchWithAuth(`${API_URL}/reports/exportmodel/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload)
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || errorData.message || 'Error al exportar el modelo');
      }

      // Actualizar mensaje de progreso
      progressDiv.innerHTML = `
        <div class="flex items-center gap-3">
          <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-green-500"></div>
          <p class="text-sm text-gray-600">Preparando archivo...</p>
        </div>
      `;

      const blob = await response.blob();
      const contentType = exportFormat === 'excel'
        ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        : 'text/csv';

      const url = window.URL.createObjectURL(new Blob([blob], { type: contentType }));
      const link = document.createElement('a');
      const extension = exportFormat === 'excel' ? 'xlsx' : 'csv';
      const fileName = `${currentModel.model}_${new Date().toISOString().split('T')[0]}.${extension}`;

      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      // Mostrar mensaje de éxito
      progressDiv.innerHTML = `
        <div class="flex items-center gap-3 text-green-600">
          <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
          </svg>
          <p class="text-sm">¡Exportación completada!</p>
        </div>
      `;
      setTimeout(() => {
        progressDiv.style.opacity = '0';
        progressDiv.style.transform = 'translateY(100%)';
        setTimeout(() => progressDiv.remove(), 300);
      }, 2000);

      showMessage(`¡Archivo ${fileName} descargado exitosamente!`, 'success');
      setShowExportSuccess(true);
    } catch (error) {
      console.error('Error al exportar:', error);
      showMessage(error.message || 'Error al exportar el modelo. Por favor intente nuevamente.', 'error');
    } finally {
      setIsExporting(false);
      // Remove progress indicator if it exists
      const progressDiv = document.querySelector('.fixed.bottom-4.right-4');
      if (progressDiv) progressDiv.remove();
    }
  };

  // Modificar la función addField para actualizar el mapeo
  const addFieldDataStage = (field) => {
    const nuevosCampos = [...selectedFieldsDataStage, field];
    
    // Actualizar estado local
    setSelectedFieldsDataStage(nuevosCampos);
    
    // Actualizar mapeo global
    setModelFieldsMap(prev => ({
      ...prev,
      [selectedModel]: nuevosCampos
    }));
  };

  // Modificar la función removeField para actualizar el mapeo
  const removeFieldDataStage = (field) => {
    const nuevosCampos = selectedFieldsDataStage.filter(f => f !== field);
    
    // Actualizar estado local
    setSelectedFieldsDataStage(nuevosCampos);
    
    // Actualizar mapeo global
    setModelFieldsMap(prev => ({
      ...prev,
      [selectedModel]: nuevosCampos
    }));
  };

  // Modificar includeAllFields
  const includeAllFieldsDataStage = () => {
    const currentModel = datastageModels.find(m => m.model === selectedModel);
    if (!currentModel) return;
    
    setSelectedFieldsDataStage([...currentModel.fields]);
    setModelFieldsMap(prev => ({
      ...prev,
      [selectedModel]: [...currentModel.fields]
    }));
  };

  // Modificar removeAllFields
  const removeAllFieldsDataStage = () => {
    setSelectedFieldsDataStage([]);
    setModelFieldsMap(prev => ({
      ...prev,
      [selectedModel]: []
    }));
  };

  // Nueva función específica para DataStage múltiple
  const handleExportDataStage = async () => {
    // Verificar que haya al menos un modelo con campos seleccionados
    const modelosConCampos = Object.entries(modelFieldsMap)
      .filter(([_, campos]) => campos.length > 0)
      .map(([modelo]) => modelo);

    if (modelosConCampos.length === 0) {
      showMessage('Por favor selecciona al menos un campo en algún modelo', 'error');
      return;
    }

    if (!globalFilters.organizacion) {
      showMessage('Debes seleccionar una organización antes de generar el reporte', 'error');
      return;
    }

    setIsExporting(true);
    
    try {
      const progressDiv = document.createElement('div');
      progressDiv.className = 'fixed bottom-4 right-4 bg-white p-4 rounded-lg shadow-xl border border-blue-100';
      progressDiv.innerHTML = `
        <div class="flex items-center gap-3">
          <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-blue-500"></div>
          <p class="text-sm text-gray-600">Preparando exportación DataStage...</p>
        </div>
      `;
      document.body.appendChild(progressDiv);

      // DETECCIÓN AUTOMÁTICA DEL MODO
      const modo = modelosConCampos.length > 1 ? 'multiple' : 'simple';
      
      const exportData = {
        modo: modo,
        format: exportFormat,
        globalFilters: globalFilters
      };

      if (modo === 'simple') {
        // MODO SIMPLE: solo un modelo con campos
        const modeloUnico = modelosConCampos[0];
        const modelData = datastageModels.find(m => m.model === modeloUnico);
        
        exportData.model = modeloUnico;
        exportData.fields = modelFieldsMap[modeloUnico];
        
      } else {
        // MODO MÚLTIPLE: varios modelos con campos
        exportData.models = modelosConCampos.map(modelo => {
          const modelData = datastageModels.find(m => m.model === modelo);
          return {
            model: modelo,
            name: modelData?.name || modelo,
            fields: modelFieldsMap[modelo]
          };
        });
      }

      // Resto del código de exportación...
      progressDiv.innerHTML = `
        <div class="flex items-center gap-3">
          <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-green-500"></div>
          <p class="text-sm text-gray-600">Generando archivo DataStage...</p>
        </div>
      `;

      const response = await fetchWithAuth(`${API_URL}/reports/exportmodel/datastage/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(exportData),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.error || errorData.message || 'Error al exportar DataStage');
      }

      const blob = await response.blob();
      
      const contentDisposition = response.headers.get('Content-Disposition');
      
      let fileName = '';
      
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="(.+?)"/) || 
                             contentDisposition.match(/filename=([^;]+)/);
        
        if (filenameMatch) {
          fileName = filenameMatch[1].replace(/"/g, '');
        }
      }
      
      if (!fileName) {
        const isZip = blob.type === 'application/zip';
        const isExcel = blob.type.includes('spreadsheetml');
        
        if (isZip) {
          fileName = modo === 'multiple' 
            ? `datastage_reports_${new Date().toISOString().split('T')[0]}.zip`
            : `datastage_${modelosConCampos[0]}_particionado_${new Date().toISOString().split('T')[0]}.zip`;
        } else if (isExcel) {
          fileName = `datastage_${modelosConCampos[0]}_${new Date().toISOString().split('T')[0]}.xlsx`;
        } else {
          fileName = `datastage_${modelosConCampos[0]}_${new Date().toISOString().split('T')[0]}.csv`;
        }
      }

      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      progressDiv.innerHTML = `
        <div class="flex items-center gap-3 text-green-600">
          <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
          </svg>
          <p class="text-sm">¡Exportación completada! (Modo ${modo})</p>
        </div>
      `;
      setTimeout(() => {
        progressDiv.style.opacity = '0';
        progressDiv.style.transform = 'translateY(100%)';
        setTimeout(() => progressDiv.remove(), 300);
      }, 2000);

      showMessage(`¡Archivo ${fileName} descargado exitosamente! (${modo === 'multiple' ? 'Múltiple' : 'Simple'})`, 'success');
      
    } catch (error) {
      console.error('❌ ERROR AL EXPORTAR DATASTAGE:', error);
      showMessage(error.message || 'Error al exportar DataStage. Por favor intente nuevamente.', 'error');
    } finally {
      setIsExporting(false);
      const progressDiv = document.querySelector('.fixed.bottom-4.right-4');
      if (progressDiv) progressDiv.remove();
    }
  };

  const renderFieldsDataStage = () => {
    const currentModel = datastageModels.find(m => m.model === selectedModel);
    const availableFields = currentModel ? currentModel.fields : [];
    
    // 🔥 CORREGIR: Siempre usar selectedFieldsDataStage para el modelo actual
    const selectedFieldsForModel = selectedFieldsDataStage;

    const formatFieldName = (field) => {
      return field.split('_')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
    };

    return (
      <div className="mb-6">
        <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-blue-100">
          <div className="p-4 border-b border-blue-50">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <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>
                </div>
                <div>
                  <h3 className="font-bold text-gray-900">
                    {modoMultiple ? `Campos de ${selectedModel}` : 'Campos del reporte'}
                  </h3>
                  <p className="text-sm text-gray-500">
                    {modoMultiple 
                      ? `Selecciona campos para ${selectedModel}` 
                      : 'Selecciona los campos a incluir'
                    }
                  </p>
                </div>
              </div>
              <span className="inline-flex items-center px-3 py-1 rounded-full bg-blue-50 text-blue-700 text-sm font-medium">
                {selectedFieldsForModel.length} seleccionados
              </span>
            </div>

            {/* Panel de campos */}
            <div className="flex gap-4 flex-col lg:flex-row">
              {/* Panel izquierdo - Campos disponibles */}
              <div className="flex-1">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-gray-700">Campos disponibles</h4>
                  <button
                    onClick={includeAllFieldsDataStage}
                    disabled={availableFields.length === selectedFieldsForModel.length}
                    className="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded-md text-blue-700 bg-blue-50 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                    </svg>
                    Incluir todos
                  </button>
                </div>
                <div className="bg-gray-50 rounded-lg p-2 max-h-80 overflow-y-auto custom-scrollbar">
                  {availableFields.filter(field => !selectedFieldsForModel.includes(field)).length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 text-gray-400">
                      <svg className="w-12 h-12 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <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>
                      <p className="text-sm">Todos los campos están incluidos</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 gap-1">
                      {availableFields
                        .filter(field => !selectedFieldsForModel.includes(field))
                        .map(field => (
                        <div
                          key={field}
                          onClick={() => addFieldDataStage(field)}
                          className="group flex items-center justify-between p-2 rounded-md cursor-pointer transition-all duration-200 hover:bg-gray-100"
                        >
                          <span className="text-sm font-medium">{formatFieldName(field)}</span>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              addFieldDataStage(field);
                            }}
                            className="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-blue-100 text-blue-600 transition-all duration-200"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Panel derecho - Campos seleccionados */}
              <div className="flex-1">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-gray-700">
                    {modoMultiple ? `Campos incluidos en ${selectedModel}` : 'Campos incluidos'}
                  </h4>
                  <button
                    onClick={removeAllFieldsDataStage}
                    disabled={selectedFieldsForModel.length === 0}
                    className="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded-md text-red-700 bg-red-50 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                    Quitar todos
                  </button>
                </div>
                <div className="bg-gray-50 rounded-lg p-2 max-h-80 overflow-y-auto custom-scrollbar">
                  {selectedFieldsForModel.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 text-gray-400">
                      <svg className="w-12 h-12 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <p className="text-sm">No hay campos seleccionados</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 gap-1">
                      {selectedFieldsForModel.map(field => (
                        <div
                          key={field}
                          className="group flex items-center justify-between p-2 rounded-md cursor-pointer transition-all duration-200 hover:bg-gray-100"
                          onClick={() => removeFieldDataStage(field)}
                        >
                          <span className="text-sm font-medium">
                            {formatFieldName(field)}
                            {modoMultiple && (
                              <span className="text-xs text-gray-500 ml-2">({selectedModel})</span>
                            )}
                          </span>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              removeFieldDataStage(field);
                            }}
                            className="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-red-100 text-red-600 transition-all duration-200"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  const renderFields = () => {
    const formatFieldName = (field) => {
      return field.split('_')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
    };

    return (
      <div className="mb-6">
        <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-blue-100">
          {/* Header con búsqueda y contador */}
          <div className="p-4 border-b border-blue-50">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <div className="h-10 w-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <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>
                </div>
                <div>
                  <h3 className="font-bold text-gray-900">Campos del reporte</h3>
                  <p className="text-sm text-gray-500">Selecciona los campos a incluir</p>
                </div>
              </div>
              <span className="inline-flex items-center px-3 py-1 rounded-full bg-blue-50 text-blue-700 text-sm font-medium">
                {selectedFields.length} seleccionados
              </span>
            </div>

            {/* Panel de campos */}
            <div className="flex gap-4 flex-col lg:flex-row">
              {/* Panel izquierdo - Campos disponibles */}
              <div className="flex-1">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-gray-700">Campos disponibles</h4>
                  <button
                    onClick={includeAllFields}
                    disabled={availableFields.length === 0}
                    className="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded-md text-blue-700 bg-blue-50 hover:bg-blue-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                    </svg>
                    Incluir todos
                  </button>
                </div>
                <div className="bg-gray-50 rounded-lg p-2 max-h-80 overflow-y-auto custom-scrollbar">
                  {availableFields.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 text-gray-400">
                      <svg className="w-12 h-12 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <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>
                      <p className="text-sm">Todos los campos están incluidos</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 gap-1">
                      {availableFields.map(field => (
                        <div
                          key={field}
                          onClick={() => setAvailableSelected(field)}
                          onDoubleClick={() => addField(field)}
                          className={`group flex items-center justify-between p-2 rounded-md cursor-pointer transition-all duration-200 ${availableSelected === field
                              ? 'bg-blue-50 text-blue-700'
                              : 'hover:bg-gray-100'
                            }`}
                        >
                          <span className="text-sm font-medium">{formatFieldName(field)}</span>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              addField(field);
                            }}
                            className="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-blue-100 text-blue-600 transition-all duration-200"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              {/* Panel derecho - Campos seleccionados */}
              <div className="flex-1">
                <div className="flex items-center justify-between mb-2">
                  <h4 className="text-sm font-medium text-gray-700">Campos incluidos</h4>
                  <button
                    onClick={removeAllFields}
                    disabled={selectedFields.length === 0}
                    className="inline-flex items-center px-2.5 py-1.5 text-xs font-medium rounded-md text-red-700 bg-red-50 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                    Quitar todos
                  </button>
                </div>
                <div className="bg-gray-50 rounded-lg p-2 max-h-80 overflow-y-auto custom-scrollbar">
                  {selectedFields.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-8 text-gray-400">
                      <svg className="w-12 h-12 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v3m0 0v3m0-3h3m-3 0H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <p className="text-sm">No hay campos seleccionados</p>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 gap-1">
                      {selectedFields.map(field => (
                        <div
                          key={field}
                          className={`group flex items-center justify-between p-2 rounded-md cursor-pointer transition-all duration-200 ${includedSelected === field
                              ? 'bg-red-50 text-red-700'
                              : 'hover:bg-gray-100'
                            }`}
                          onClick={() => setIncludedSelected(field)}
                          onDoubleClick={() => removeField(field)}
                        >
                          <span className="text-sm font-medium">{formatFieldName(field)}</span>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              removeField(field);
                            }}
                            className="opacity-0 group-hover:opacity-100 p-1 rounded-md hover:bg-red-100 text-red-600 transition-all duration-200"
                          >
                            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          </button>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        <style jsx>{`
          .custom-scrollbar::-webkit-scrollbar {
            width: 4px;
          }
          .custom-scrollbar::-webkit-scrollbar-track {
            background: #f3f4f6;
            border-radius: 2px;
          }
          .custom-scrollbar::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 2px;
          }
          .custom-scrollbar::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
          }
        `}</style>
      </div>
    );
  };

  const renderFilters = () => (
    <div className="mb-4">
      <div className="bg-white rounded-xl shadow-lg overflow-hidden border border-blue-100">
        <div className="p-4 border-b border-blue-50">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 bg-blue-100 rounded-lg flex items-center justify-center">
              <svg className="w-6 h-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
            </div>
            <div>
              <h3 className="font-bold text-gray-900">Filtros de búsqueda</h3>
              <p className="text-sm text-gray-500">Refina los resultados del reporte</p>
            </div>
          </div>
        </div>
        <div className="p-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {Object.entries(currentModel.filters).map(([key, value]) => {
              const label = key.split('_').map(word =>
                word.charAt(0).toUpperCase() + word.slice(1)
              ).join(' ');

              const isDate = key.toLowerCase().includes('fecha');

              return (
                <div key={key} className="group">
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    {label}
                  </label>
                  <div className="relative rounded-lg shadow-sm">
                    <input
                      type={isDate ? "date" : "text"}
                      value={filters[key] || ''}
                      onChange={(e) => setFilters(prev => ({
                        ...prev,
                        [key]: e.target.value
                      }))}
                      className="block w-full rounded-lg border-gray-300 pl-3 pr-10 py-2.5 text-gray-900 placeholder-gray-500 
                        focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm
                        transition-all duration-200 bg-white"
                      placeholder={`Buscar por ${label.toLowerCase()}`}
                    />
                    <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                      {isDate ? (
                        <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                      ) : (
                        <svg className="h-5 w-5 text-gray-400 group-focus-within:text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <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>
      </div>
    </div>
  );

  // Contenido de cada pestaña
  const tabContents = {
    pedimentos: (
      <div className="p-6 bg-white/95 rounded-2xl shadow-xl border border-blue-100">
        <div className="relative mb-8">
          <div className="absolute -left-2 -top-2 w-12 h-12 bg-gradient-to-br from-blue-600 to-blue-700 rounded-2xl shadow-lg flex items-center justify-center transform -rotate-6">
            <svg className="w-6 h-6 text-white" 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>
          <div className="pl-12">
            <h2 className="text-2xl font-bold text-gray-900">Generar reporte de pedimentos</h2>
            <p className="text-gray-600 mt-1">Selecciona los campos y ajusta los filtros para generar el reporte.</p>
          </div>
        </div>

        <div className="mb-6">
          <label className="block text-xs font-semibold text-blue-800 mb-2">Formato de Exportación</label>
          <div className="flex gap-3">
            <button
              onClick={() => setExportFormat('excel')}
              className={`flex-1 py-2.5 rounded-lg transition-all duration-200 border ${exportFormat === 'excel'
                  ? 'bg-gradient-to-br from-green-50 to-green-100 border-green-200 shadow-lg shadow-green-100 scale-[1.02]'
                  : 'bg-white border-gray-200 hover:bg-gray-50'
                }`}
            >
              <div className="flex items-center justify-center gap-2">
                <svg className={`w-5 h-5 ${exportFormat === 'excel' ? 'text-green-600' : 'text-gray-500'}`} viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2v6h6M8 13h8M8 17h8M8 9h2" />
                </svg>
                <span className={exportFormat === 'excel' ? 'font-semibold text-green-700' : 'text-gray-700'}>Excel</span>
              </div>
            </button>

            <button
              onClick={() => setExportFormat('csv')}
              className={`flex-1 py-2.5 rounded-lg transition-all duration-200 border ${exportFormat === 'csv'
                  ? 'bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200 shadow-lg shadow-blue-100 scale-[1.02]'
                  : 'bg-white border-gray-200 hover:bg-gray-50'
                }`}
            >
              <div className="flex items-center justify-center gap-2">
                <svg className={`w-5 h-5 ${exportFormat === 'csv' ? 'text-blue-600' : 'text-gray-500'}`} viewBox="0 0 24 24" fill="none" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2v6h6M10 9v10M14 9v10M6 9v10" />
                </svg>
                <span className={exportFormat === 'csv' ? 'font-semibold text-blue-700' : 'text-gray-700'}>CSV</span>
              </div>
            </button>
          </div>
        </div>

        <div className="mb-6">
          <h3 className="text-md font-bold text-blue-800 mb-3">Campos</h3>
          {renderFields()}
        </div>
        <div className="mb-6">
          <h3 className="text-md font-bold text-blue-800 mb-3">Filtros</h3>
          {renderFilters()}
        </div>

        <button
          onClick={handleExportModel}
          disabled={isExporting}
          className={`group relative w-full py-3 text-lg font-semibold ${isExporting
              ? 'bg-gray-400 cursor-not-allowed'
              : exportFormat === 'excel'
                ? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700'
                : 'bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700'
            } text-white rounded-xl transition-all duration-300 transform hover:scale-[1.02] shadow-lg hover:shadow-xl ${exportFormat === 'excel'
              ? 'shadow-green-500/20 hover:shadow-green-500/30'
              : 'shadow-blue-500/20 hover:shadow-blue-500/30'
            } overflow-hidden`}
        >
          <div className={`absolute inset-0 w-full h-full ${isExporting
              ? 'bg-gradient-to-r from-gray-300/0 via-gray-300/30 to-gray-300/0'
              : exportFormat === 'excel'
                ? 'bg-gradient-to-r from-green-400/0 via-green-400/30 to-green-400/0'
                : 'bg-gradient-to-r from-blue-400/0 via-blue-400/30 to-blue-400/0'
            } skeleton-animation`}></div>
          <span className="relative inline-flex items-center justify-center gap-2 px-4">
            {isExporting ? (
              <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" 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-5 h-5 transform group-hover:scale-110 transition-transform duration-300" 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>{isExporting ? 'Generando archivo...' : `Generar y descargar ${exportFormat.toUpperCase()}`}</span>
          </span>
        </button>
      </div>
    ),
    control_pedimentos: (
      <div className="p-6">
        <h2 className="text-xl font-bold mb-2 text-blue-900">Generar reporte de Control de Requerimiento</h2>
        <p className="mb-4 text-gray-700">Aquí puedes generar y descargar el reporte de Control de Requerimiento.</p>
        {/* Filtros replicados */}
        <div className="max-w-7xl mx-auto mt-6 mb-4 px-4">
          <form onSubmit={(e) => {
            e.preventDefault();
            fetchSummary();
          }} className="bg-white rounded-lg shadow-sm border border-slate-200 p-4">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
              {Object.keys(initialFiltersControlPedimento).map((key) => (
                <div key={key}>
                  <label className="block text-xs font-medium text-slate-600 mb-1" htmlFor={key}>
                    {key.replace(/_/g, ' ').replace('gte', 'desde').replace('lte', 'hasta')}
                  </label>
                  
                  {key === 'organizacion_id' ? (
                    <select
                      name={key}
                      id={key}
                      value={filtersControlPedimento[key]}
                      onChange={handleFilterChangeControlPedimento}
                      className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                    >
                      <option value="">Seleccionar organización</option>
                      {organizaciones.results && organizaciones.results.map(org => (
                        <option key={org.id} value={org.id}>
                          {org.nombre} {/* Usar el campo 'nombre' que sí existe */}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <input
                      type={key.includes('fecha') ? 'date' : 'text'}
                      name={key}
                      id={key}
                      value={filtersControlPedimento[key]}
                      onChange={handleFilterChangeControlPedimento}
                      className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                    />
                  )}
                </div>
              ))}
            </div>
            <div className="flex justify-end">
              <div className="flex gap-2">
                <button
                  type="button"
                  className="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
                  onClick={handleGenerarReporteControlPedimento}
                >
                  Generar Reporte
                </button>
              </div>
            </div>
          </form>
        </div>
        {/* Aquí va la lógica y UI específica para Cumplimiento */}
        {/* Tabla de reportes debajo de las tarjetas */}
        <div className="mt-10">
          <h2 className="text-lg font-bold text-slate-700 mb-4">Historial de Reportes</h2>
          <div className="overflow-x-auto">
            <table className="min-w-full bg-white rounded-lg shadow border border-slate-200">
              <thead>
                <tr className="bg-slate-100">
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">ID</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Estado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Creado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Finalizado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Error</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Descargar</th>
                </tr>
              </thead>
              <tbody>
                {reports.filter(r => r.report_type === 'control_pedimento').length > 0 ? (
                  reports
                    .filter(r => r.report_type === 'control_pedimento')
                    .map((r) => (
                      <tr key={r.report_id}>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.report_id}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.status}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.created_at}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.finished_at}</td>
                        <td className="px-4 py-2 text-xs text-red-500">{r.error_message ? r.error_message : '-'}</td>
                        <td className="px-4 py-2 text-xs">
                          {r.status === 'ready' ? (
                            <button
                              className="text-blue-600 hover:underline"
                              onClick={() => handleDownloadReport(r.report_id)}
                            >
                              Descargar
                            </button>
                          ) : (
                            <span className="text-slate-400">-</span>
                          )}
                        </td>
                      </tr>
                    ))
                ) : (
                  <tr>
                    <td colSpan={6} className="px-4 py-2 text-center text-slate-400">
                      {reports.length > 0 ? 'No hay reportes de control de pedimento' : 'No hay reportes disponibles'}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    ),
    datastage: (
      <div className="p-6 bg-white/95 rounded-2xl shadow-xl border border-blue-100">
        <div className="relative mb-8">
          <div className="absolute -left-2 -top-2 w-12 h-12 bg-gradient-to-br from-blue-600 to-blue-700 rounded-2xl shadow-lg flex items-center justify-center transform -rotate-6">
            <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 7v10c0 2 1.5 3 3 3h10c1.5 0 3-1 3-3V7c0-2-1.5-3-3-3H7C5.5 4 4 5 4 7zm8-1v14m-4-3h8" />
            </svg>
          </div>
          <div className="pl-12">
            <h2 className="text-2xl font-bold text-gray-900">Generar reporte de datastage</h2>
            <p className="text-gray-600 mt-1">Selecciona el modelo, revisa los campos y ajusta los filtros para generar el reporte.</p>
          </div>
        </div>
        <div className="mb-6 space-y-4">
          <div>
            <label className="block text-xs font-semibold text-blue-800 mb-2">Modelo</label>
            <div className="relative">
              <select
                value={selectedModel}
                onChange={e => setSelectedModel(e.target.value)}
                className="w-full border border-blue-200 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-blue-400 bg-white/90 shadow-md appearance-none pr-10 transition-all duration-200 hover:shadow-lg"
              >
                {datastageModels.map(m => (
                  <option key={m.model} value={m.model} className="py-1">
                    {m.model} - {m.name}
                  </option>
                ))}
              </select>
              <div className="absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none">
                <svg className="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
          </div>

          <div>
            <label className="block text-xs font-semibold text-blue-800 mb-2">Formato de Exportación</label>
            <div className="flex gap-3">
              <button
                onClick={() => setExportFormat('excel')}
                className={`flex-1 py-2.5 rounded-lg transition-all duration-200 border ${exportFormat === 'excel'
                    ? 'bg-gradient-to-br from-green-50 to-green-100 border-green-200 shadow-lg shadow-green-100 scale-[1.02]'
                    : 'bg-white border-gray-200 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className={`w-5 h-5 ${exportFormat === 'excel' ? 'text-green-600' : 'text-gray-500'}`} viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2v6h6M8 13h8M8 17h8M8 9h2" />
                  </svg>
                  <span className={exportFormat === 'excel' ? 'font-semibold text-green-700' : 'text-gray-700'}>Excel</span>
                </div>
              </button>

              <button
                onClick={() => setExportFormat('csv')}
                className={`flex-1 py-2.5 rounded-lg transition-all duration-200 border ${exportFormat === 'csv'
                    ? 'bg-gradient-to-br from-blue-50 to-blue-100 border-blue-200 shadow-lg shadow-blue-100 scale-[1.02]'
                    : 'bg-white border-gray-200 hover:bg-gray-50'
                  }`}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className={`w-5 h-5 ${exportFormat === 'csv' ? 'text-blue-600' : 'text-gray-500'}`} viewBox="0 0 24 24" fill="none" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8l-6-6z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.5" d="M14 2v6h6M10 9v10M14 9v10M6 9v10" />
                  </svg>
                  <span className={exportFormat === 'csv' ? 'font-semibold text-blue-700' : 'text-gray-700'}>CSV</span>
                </div>
              </button>
            </div>
          </div>
        </div>
        <div className="mb-6">
          <h3 className="text-md font-bold text-blue-800 mb-3">Campos</h3>
          {renderFieldsDataStage()}

          <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
            <div className="flex items-center justify-between">
              <div>
                <span className="text-sm font-medium text-blue-800">Busqueda por modelo: </span>
                <span className={`text-sm font-bold ${isModoMultiple ? 'text-purple-600' : 'text-green-600'}`}>
                  {isModoMultiple ? 'MÚLTIPLES MODELOS' : 'SINGULAR'}
                </span>
              </div>
              <div className="text-xs text-blue-600">
                {Object.keys(modelFieldsMap).filter(model => modelFieldsMap[model]?.length > 0).length} modelo(s) con campos
              </div>
            </div>
            
            {/* Mostrar modelos activos */}
            {Object.keys(modelFieldsMap).filter(model => modelFieldsMap[model]?.length > 0).length > 0 && (
              <div className="mt-2 text-xs text-blue-700">
                <strong>Modelos activos:</strong> {Object.keys(modelFieldsMap)
                  .filter(model => modelFieldsMap[model]?.length > 0)
                  .map(model => `${model} (${modelFieldsMap[model].length} campos)`)
                  .join(', ')}
              </div>
            )}
          </div>
        </div>
        
        <div className="mb-6">
          <h3 className="text-md font-bold text-blue-800 mb-3">Filtros Globales</h3>
          {renderGlobalFilters()}
        </div>
        {/* <div className="mb-6">
          <h3 className="text-md font-bold text-blue-800 mb-3">Filtros</h3>
          {renderFilters()}
        </div> */}
        <button
          onClick={handleExportDataStage}
          disabled={isExporting}
          className={`group relative w-full py-3 text-lg font-semibold ${isExporting
              ? 'bg-gray-400 cursor-not-allowed'
              : exportFormat === 'excel'
                ? 'bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700'
                : 'bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700'
            } text-white rounded-xl transition-all duration-300 transform hover:scale-[1.02] shadow-lg hover:shadow-xl ${exportFormat === 'excel'
              ? 'shadow-green-500/20 hover:shadow-green-500/30'
              : 'shadow-blue-500/20 hover:shadow-blue-500/30'
            } overflow-hidden`}
        >
          <div className={`absolute inset-0 w-full h-full ${isExporting
              ? 'bg-gradient-to-r from-gray-300/0 via-gray-300/30 to-gray-300/0'
              : exportFormat === 'excel'
                ? 'bg-gradient-to-r from-green-400/0 via-green-400/30 to-green-400/0'
                : 'bg-gradient-to-r from-blue-400/0 via-blue-400/30 to-blue-400/0'
            } skeleton-animation`}></div>
          <span className="relative inline-flex items-center justify-center gap-2 px-4">
            {isExporting ? (
              <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" 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-5 h-5 transform group-hover:scale-110 transition-transform duration-300" 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>{isExporting ? 'Generando archivo...' : `Generar y descargar ${exportFormat.toUpperCase()}`}</span>
          </span>
        </button>

        <style>{`
          .skeleton-animation {
            animation: shimmer 2s linear infinite;
            background-size: 200% 100%;
          }
          @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
          }
        `}</style>
      </div>
    ),
    Cumplimiento: (
      <div className="p-6">
        <h2 className="text-xl font-bold mb-2 text-blue-900">Generar reporte de Cumplimiento</h2>
        <p className="mb-4 text-gray-700">Aquí puedes generar y descargar el reporte de Cumplimiento.</p>
        <div className="max-w-7xl mx-auto mt-6 mb-4 px-4">
          <form onSubmit={(e) => e.preventDefault()} className="bg-white rounded-lg shadow-sm border border-slate-200 p-4">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">

              {/* Organización — solo lectura */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Organización</label>
                <input
                  type="text"
                  readOnly
                  value={organizaciones?.results?.find(o => o.id === organizacionId)?.nombre || organizacionId || ''}
                  className="w-full border border-slate-200 rounded px-2 py-1 text-sm bg-slate-50 text-slate-500 cursor-not-allowed"
                />
              </div>

              {/* RFC Contribuyente — dropdown dinámico */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">RFC Contribuyente</label>
                <select
                  name="contribuyente__rfc"
                  value={filtersCumplimiento.contribuyente__rfc}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500 bg-white"
                >
                  <option value="">Todos los RFC</option>
                  <option value="SIN_RFC">Pedimentos sin RFC</option>
                  {rfcsCumplimiento.map(rfc => (
                    <option key={rfc} value={rfc}>{rfc}</option>
                  ))}
                </select>
              </div>

              {/* Pedimento App */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Pedimento</label>
                <input
                  type="text"
                  name="pedimento_app"
                  value={filtersCumplimiento.pedimento_app}
                  onChange={handleFilterChangeCumplimiento}
                  placeholder="Ej. 21-160-3910-0003357"
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Aduana */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Aduana</label>
                <input
                  type="text"
                  name="aduana"
                  value={filtersCumplimiento.aduana}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Patente */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Patente</label>
                <input
                  type="text"
                  name="patente"
                  value={filtersCumplimiento.patente}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Régimen */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Régimen</label>
                <input
                  type="text"
                  name="regimen"
                  value={filtersCumplimiento.regimen}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Agente Aduanal */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Agente Aduanal</label>
                <input
                  type="text"
                  name="agente_aduanal"
                  value={filtersCumplimiento.agente_aduanal}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Tipo Operación */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Tipo Operación</label>
                <input
                  type="text"
                  name="tipo_operacion"
                  value={filtersCumplimiento.tipo_operacion}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Fecha Pago Desde */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Fecha pago desde</label>
                <input
                  type="date"
                  name="fecha_pago_gte"
                  value={filtersCumplimiento.fecha_pago_gte}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

              {/* Fecha Pago Hasta */}
              <div>
                <label className="block text-xs font-medium text-slate-600 mb-1">Fecha pago hasta</label>
                <input
                  type="date"
                  name="fecha_pago_lte"
                  value={filtersCumplimiento.fecha_pago_lte}
                  onChange={handleFilterChangeCumplimiento}
                  className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
                />
              </div>

            </div>
            <div className="flex justify-end">
              <button
                type="button"
                className="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
                onClick={handleGenerarReporteCumplimiento}
              >
                Generar Reporte
              </button>
            </div>
          </form>
        </div>
        {/* Aquí va la lógica y UI específica para Cumplimiento */}
        {/* Tabla de reportes debajo de las tarjetas */}
        <div className="mt-10">
          <h2 className="text-lg font-bold text-slate-700 mb-4">Historial de Reportes</h2>
          <div className="overflow-x-auto">
            <table className="min-w-full bg-white rounded-lg shadow border border-slate-200">
              <thead>
                <tr className="bg-slate-100">
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">ID</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Estado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Creado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Finalizado</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Error</th>
                  <th className="px-4 py-2 text-left text-xs font-semibold text-slate-600">Descargar</th>
                </tr>
              </thead>
              <tbody>
                {reports.filter(r => r.report_type === 'cumplimiento').length > 0 ? (
                  reports
                    .filter(r => r.report_type === 'cumplimiento')
                    .map((r) => (
                      <tr key={r.report_id}>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.report_id}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.status}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.created_at}</td>
                        <td className="px-4 py-2 text-xs text-slate-700">{r.finished_at}</td>
                        <td className="px-4 py-2 text-xs text-red-500">{r.error_message ? r.error_message : '-'}</td>
                        <td className="px-4 py-2 text-xs">
                          {r.status === 'ready' ? (
                            <button
                              className="text-blue-600 hover:underline"
                              onClick={() => handleDownloadReport(r.report_id)}
                            >
                              Descargar
                            </button>
                          ) : (
                            <span className="text-slate-400">-</span>
                          )}
                        </td>
                      </tr>
                    ))
                ) : (
                  <tr>
                    <td colSpan={6} className="px-4 py-2 text-center text-slate-400">
                      {reports.length > 0 ? 'No hay reportes de cumplimiento' : 'No hay reportes disponibles'}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    ),
    coves: (
      <div className="p-6">
        <h2 className="text-xl font-bold mb-2 text-blue-900">Generar reporte de COVES</h2>
        <p className="mb-4 text-gray-700">Aquí puedes generar y descargar el reporte de COVES.</p>
        {/* Aquí va la lógica y UI específica para COVES */}
      </div>
    ),
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 p-4 sm:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header mejorado y decorativo */}
        <div className="mb-6 sm:mb-8 relative overflow-hidden rounded-3xl shadow-2xl bg-gradient-to-r from-blue-600 via-blue-700 to-blue-800 p-6 sm:p-8 flex items-center gap-4 sm:gap-6 animate-fadein-slideup opacity-0"
          style={{ animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.05s forwards' }}>
          <div className="flex-shrink-0 bg-white/20 backdrop-blur-sm rounded-full p-3 sm:p-4 shadow-lg animate-bounce-slow">
            <svg className="h-8 w-8 sm:h-10 sm:w-10 text-white" 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="text-2xl sm:text-3xl lg:text-4xl font-extrabold text-white tracking-tight mb-1">Centro de Reportes</h1>
            <p className="text-sm sm:text-lg text-blue-100 font-medium leading-relaxed">
              Consulta, genera y descarga reportes relacionados con el sistema aduanero
            </p>
          </div>

          {/* Botones de ayuda */}
          <div className="flex gap-2">
            <button
              onClick={() => setShowHelp(!showHelp)}
              className="bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-xl p-3 transition-all duration-200 group"
              title="Ayuda"
            >
              <svg className="w-6 h-6 text-white group-hover:scale-110 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </button>
            <button
              onClick={startTour}
              className="bg-white/20 hover:bg-white/30 backdrop-blur-sm rounded-xl p-3 transition-all duration-200 group"
              title="Tour guiado"
            >
              <svg className="w-6 h-6 text-white group-hover:scale-110 transition-transform" 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>
            </button>
          </div>

          {/* Efectos decorativos de fondo */}
          <div className="absolute -top-10 -right-10 opacity-20 pointer-events-none select-none">
            <div className="w-32 h-32 bg-white/10 rounded-full blur-xl"></div>
          </div>
          <div className="absolute -bottom-6 -left-6 opacity-15 pointer-events-none select-none">
            <div className="w-24 h-24 bg-white/10 rounded-full blur-lg"></div>
          </div>
          {/* Partículas flotantes */}
          <div className="absolute inset-0 overflow-hidden pointer-events-none">
            <div className="absolute top-1/4 left-1/4 w-2 h-2 bg-white/30 rounded-full animate-ping"></div>
            <div className="absolute top-3/4 right-1/3 w-1 h-1 bg-white/40 rounded-full animate-pulse"></div>
            <div className="absolute top-1/2 right-1/4 w-3 h-3 bg-white/20 rounded-full animate-bounce"></div>
          </div>
        </div>
        {/* Panel de ayuda */}
        {showHelp && (
          <div className="mb-6 bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-6 shadow-lg animate-fadein-slideup">
            <div className="flex items-start gap-4">
              <div className="flex-shrink-0">
                <div className="w-12 h-12 bg-amber-100 rounded-xl flex items-center justify-center">
                  <svg className="w-6 h-6 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
                  </svg>
                </div>
              </div>
              <div className="flex-1">
                <h3 className="text-lg font-bold text-amber-900 mb-3">Guía de uso del Centro de Reportes</h3>
                <div className="space-y-4 text-sm text-amber-800">
                  <div className="bg-white/60 rounded-lg p-4">
                    <h4 className="font-semibold mb-2 text-amber-900">🎯 Paso 1: Selecciona el tipo de reporte</h4>
                    <p>Elige entre <strong>Pedimentos cargados</strong> para documentos de importación/exportación o <strong>Datastage cargados</strong> para datos procesados del sistema.</p>
                  </div>
                  <div className="bg-white/60 rounded-lg p-4">
                    <h4 className="font-semibold mb-2 text-amber-900">📊 Paso 2: Configura tu reporte</h4>
                    <p>Selecciona el <strong>formato</strong> (Excel para análisis o CSV para compatibilidad), elige los <strong>campos</strong> que necesitas y aplica <strong>filtros</strong> específicos.</p>
                  </div>
                  <div className="bg-white/60 rounded-lg p-4">
                    <h4 className="font-semibold mb-2 text-amber-900">🚀 Paso 3: Genera y descarga</h4>
                    <p>Haz clic en el botón de exportación y el archivo se descargará automáticamente a tu dispositivo.</p>
                  </div>
                  <div className="bg-white/60 rounded-lg p-4">
                    <h4 className="font-semibold mb-2 text-amber-900">💡 Consejos útiles</h4>
                    <ul className="list-disc list-inside space-y-1">
                      <li>Usa Excel para reportes con gráficos y análisis avanzado</li>
                      <li>Usa CSV para importar datos en otros sistemas</li>
                      <li>Aplica filtros para reducir el tamaño del archivo</li>
                      <li>Selecciona solo los campos que realmente necesitas</li>
                    </ul>
                  </div>
                </div>
                <button
                  onClick={startTour}
                  className="mt-4 bg-amber-200 hover:bg-amber-300 text-amber-800 px-4 py-2 rounded-lg font-medium transition-colors"
                >
                  🎯 Iniciar tour guiado
                </button>
              </div>
              <button
                onClick={() => setShowHelp(false)}
                className="text-amber-600 hover:text-amber-800 transition-colors"
              >
                <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>
        )}

        {/* Pestañas */}
        <div className="tab-selector mb-4 sm:mb-6 animate-fadein-slideup opacity-0" style={{ animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.15s forwards' }}>
          <div className="bg-white/95 backdrop-blur-xl rounded-2xl shadow-xl border border-blue-100">
            <div className="flex flex-col sm:flex-row border-b border-blue-200/50 p-1 gap-1">
              <button
                className={`flex-1 py-3 px-4 text-sm font-semibold rounded-xl focus:outline-none transition-all duration-200 ${activeTab === 'pedimentos'
                    ? 'bg-gradient-to-br from-blue-600 to-blue-700 text-white shadow-lg shadow-blue-500/20 scale-[1.02]'
                    : 'text-gray-700 hover:bg-blue-50/80'
                  }`}
                onClick={() => setActiveTab('pedimentos')}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className="w-5 h-5" 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>
                  <span>Pedimentos cargados</span>
                </div>
              </button>

              <button
                className={`flex-1 py-3 px-4 text-sm font-semibold rounded-xl focus:outline-none transition-all duration-200 ${activeTab === 'control_pedimentos'
                    ? 'bg-gradient-to-br from-blue-600 to-blue-700 text-white shadow-lg shadow-blue-500/20 scale-[1.02]'
                    : 'text-gray-700 hover:bg-blue-50/80'
                  }`}
                onClick={() => setActiveTab('control_pedimentos')}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className="w-5 h-5" 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>
                  <span>Control de Pedimentos</span>
                </div>
              </button>

              <button
                className={`flex-1 py-3 px-4 text-sm font-semibold rounded-xl focus:outline-none transition-all duration-200 ${activeTab === 'datastage'
                    ? 'bg-gradient-to-br from-blue-600 to-blue-700 text-white shadow-lg shadow-blue-500/20 scale-[1.02]'
                    : 'text-gray-700 hover:bg-blue-50/80'
                  }`}
                onClick={() => setActiveTab('datastage')}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 7v10c0 2 1.5 3 3 3h10c1.5 0 3-1 3-3V7c0-2-1.5-3-3-3H7C5.5 4 4 5 4 7zm8-1v14m-4-3h8" />
                  </svg>
                  <span>Datastage cargados</span>
                </div>
              </button>
              <button
                className={`flex-1 py-3 px-4 text-sm font-semibold rounded-xl focus:outline-none transition-all duration-200 ${activeTab === 'Cumplimiento'
                    ? 'bg-gradient-to-br from-blue-600 to-blue-700 text-white shadow-lg shadow-blue-500/20 scale-[1.02]'
                    : 'text-gray-700 hover:bg-blue-50/80'
                  }`}
                onClick={() => setActiveTab('Cumplimiento')}
              >
                <div className="flex items-center justify-center gap-2">
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                  </svg>
                  <span>Cumplimiento</span>
                </div>
              </button>
              {isDebugMode && (
                <button
                  className={`flex-1 py-3 px-4 text-sm font-semibold rounded-xl focus:outline-none transition-all duration-200 ${activeTab === 'coves'
                      ? 'bg-gradient-to-br from-blue-600 to-blue-700 text-white shadow-lg shadow-blue-500/20 scale-[1.02]'
                      : 'text-gray-700 hover:bg-blue-50/80'
                    }`}
                  onClick={() => setActiveTab('coves')}
                >
                  <div className="flex items-center justify-center gap-2">
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7v8a2 2 0 002 2h6M8 7V5a2 2 0 012-2h4.586a1 1 0 01.707.293l4.414 4.414a1 1 0 01.293.707V15a2 2 0 01-2 2h-2M8 7H6a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2v-2" />
                    </svg>
                    <span>COVES</span>
                  </div>
                </button>
              )}
            </div>
            {/* Contenido de la pestaña activa */}
            <div>{tabContents[activeTab]}</div>
          </div>
        </div>
      </div>

      {/* Tour Overlay */}
      <TourOverlay
        show={showTour}
        step={tourStep}
        steps={tourSteps}
        onNext={nextTourStep}
        onSkip={skipTour}
      />
    </div>
  );
}

// Tour overlay component
const TourOverlay = ({ show, step, steps, onNext, onSkip }) => {
  if (!show || !steps[step]) return null;

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
      <div className="bg-white rounded-2xl p-6 max-w-md mx-4 shadow-2xl">
        <div className="flex items-start gap-4">
          <div className="flex-shrink-0">
            <div className="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
              <span className="text-blue-600 font-bold">{step + 1}</span>
            </div>
          </div>
          <div className="flex-1">
            <h3 className="text-lg font-bold text-gray-900 mb-2">
              Paso {step + 1} de {steps.length}
            </h3>
            <p className="text-gray-600 mb-4">{steps[step].content}</p>
            <div className="flex gap-2">
              <button
                onClick={onNext}
                className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors"
              >
                {step === steps.length - 1 ? 'Finalizar' : 'Siguiente'}
              </button>
              <button
                onClick={onSkip}
                className="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2 rounded-lg font-medium transition-colors"
              >
                Saltar tour
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
