// Componente de la tabla de referencias
function ReferenciasTable({ referencias, loading, activeFilter }) {
    const [openActions, setOpenActions] = React.useState(null);
    const [hoveredVehiculo, setHoveredVehiculo] = React.useState(null);
    const [tooltipPosition, setTooltipPosition] = React.useState({ x: 0, y: 0 });
    const [selectedImages, setSelectedImages] = React.useState(null);
    const [currentImageIndex, setCurrentImageIndex] = React.useState(0);

    // Función para cerrar todos los menús de acciones
    const closeAllActions = () => {
        setOpenActions(null);
    };

    // Función para obtener campos completos del vehículo
    const getVehiculoCompleto = (categorias) => {
        if (!categorias || !Array.isArray(categorias) || categorias.length === 0) return [];
        
        const vehiculo = categorias[0]; // Tomamos el primer vehículo de las categorías
        if (!vehiculo) return [];
        
        const campos = [
            { key: 'marca', label: 'Marca', value: vehiculo.marca },
            { key: 'modelo', label: 'Modelo', value: vehiculo.modelo },
            { key: 'version', label: 'Versión', value: vehiculo.version },
            { key: 'anio', label: 'Año', value: vehiculo.anio },
            { key: 'color', label: 'Color', value: vehiculo.color },
            { key: 'combustible', label: 'Combustible', value: vehiculo.combustible },
            { key: 'kilometraje', label: 'Kilometraje', value: vehiculo.kilometraje },
            { key: 'numero_puertas', label: 'Puertas', value: vehiculo.numero_puertas },
            { key: 'chasis', label: 'Chasis', value: vehiculo.chasis },
            { key: 'codigo_motor', label: 'Código Motor', value: vehiculo.codigo_motor },
            { key: 'matricula', label: 'Matrícula', value: vehiculo.matricula },
            { key: 'codigo_cambio', label: 'Código Cambio', value: vehiculo.codigo_cambio },
            { key: 'observaciones', label: 'Observaciones', value: vehiculo.observaciones }
        ];
        
        return campos.filter(campo => 
            campo.value && 
            campo.value !== '' && 
            campo.value !== 0 && 
            campo.value !== '0' &&
            campo.value !== null &&
            campo.value !== undefined
        );
    };

    // Función para alternar menú de acciones
    const toggleActions = (id) => {
        if (openActions === id) {
            setOpenActions(null);
        } else {
            setOpenActions(id);
        }
    };

    // Función para obtener imágenes de CAT
    const getCatImages = (categorias) => {
        if (!categorias || !Array.isArray(categorias) || categorias.length === 0) return [];
        
        const firstCategory = categorias[0];
        if (!firstCategory || !firstCategory.imagenes) return [];
        
        return firstCategory.imagenes.map(img => img.ruta_imagen);
    };

    // Función para abrir modal de imágenes
    const openImageModal = (images, index = 0) => {
        setSelectedImages(images);
        setCurrentImageIndex(index);
    };

    // Función para cerrar modal de imágenes
    const closeImageModal = () => {
        setSelectedImages(null);
        setCurrentImageIndex(0);
    };

    // Función para navegar entre imágenes
    const navigateImage = (direction) => {
        if (!selectedImages) return;
        
        const newIndex = direction === 'next' 
            ? (currentImageIndex + 1) % selectedImages.length
            : (currentImageIndex - 1 + selectedImages.length) % selectedImages.length;
        
        setCurrentImageIndex(newIndex);
    };

    // Cerrar menús al hacer click fuera
    React.useEffect(() => {
        const handleClickOutside = (event) => {
            if (!event.target.closest('.actions-menu')) {
                closeAllActions();
            }
        };

        document.addEventListener('click', handleClickOutside);
        return () => document.removeEventListener('click', handleClickOutside);
    }, []);

    // Cerrar modal con tecla Escape
    React.useEffect(() => {
        const handleKeyDown = (event) => {
            if (event.key === 'Escape' && selectedImages) {
                closeImageModal();
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [selectedImages]);

    if (loading) {
        return (
            <div className="text-center py-12">
                <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-800"></div>
                <p className="mt-4 text-blue-800 font-medium">Cargando referencias...</p>
            </div>
        );
    }

    return (
        <div className="bg-white rounded-lg overflow-hidden shadow-lg">
            {/* Vista de escritorio - Tabla */}
            <div className="hidden lg:block">
                <table className="w-full border-collapse border-0">
                    <thead className="bg-gradient-to-r from-blue-800 to-blue-900">
                        <tr>
                            <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                REFERENCIA
                            </th>
                            <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                MARCA
                            </th>
                            <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                DESCRIPCION
                            </th>
                            {(activeFilter === 'cat' || activeFilter === 'all') && (
                                <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                    VEHICULO
                                </th>
                            )}
                            {(activeFilter === 'cat' || activeFilter === 'all') && (
                                <th className="px-4 py-3 text-center text-sm font-bold text-white uppercase tracking-wider border-0">
                                    IMAGENES
                                </th>
                            )}
                            <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                VENDEDOR
                            </th>
                            <th className="px-4 py-3 text-left text-sm font-bold text-white uppercase tracking-wider border-0">
                                PRECIO
                            </th>
                            <th className="px-4 py-3 text-center text-sm font-bold text-white uppercase tracking-wider border-0">
                                ACCIONES
                            </th>
                        </tr>
                    </thead>
                    <tbody className="bg-white">
                        {referencias.length > 0 ? (
                            referencias.map((referencia, index) => (
                                <tr key={referencia.id} className={`transition-colors duration-150 ${
                                    index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
                                } hover:bg-blue-50`}>
                                    <td className="px-4 py-3 whitespace-nowrap text-sm text-gray-800 font-medium border-0">
                                        {referencia.referencia}
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-700 border-0">
                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            {referencia.marca}
                                        </span>
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-700 max-w-xs truncate border-0">
                                        {referencia.descripcion}
                                    </td>
                                    {(activeFilter === 'cat' || activeFilter === 'all') && (
                                        <td 
                                            className="px-4 py-3 text-sm text-gray-700 max-w-xs truncate border-0 relative cursor-help"
                                            onMouseEnter={(e) => {
                                                if (referencia.categorias && referencia.categorias.length > 0) {
                                                    setHoveredVehiculo(referencia.id);
                                                    setTooltipPosition({ x: e.clientX + 10, y: e.clientY - 10 });
                                                }
                                            }}
                                            onMouseLeave={() => setHoveredVehiculo(null)}
                                        >
                                            {referencia.vehiculo}
                                            
                                            {/* Tooltip del vehículo */}
                                            {hoveredVehiculo === referencia.id && referencia.categorias && referencia.categorias.length > 0 && (
                                                <div 
                                                    className="fixed z-50 w-80 bg-white border border-gray-200 rounded-lg shadow-xl p-4"
                                                    style={{
                                                        left: tooltipPosition.x,
                                                        top: tooltipPosition.y
                                                    }}
                                                >
                                                    <div className="text-sm font-medium text-gray-900 mb-3 border-b border-gray-100 pb-2">
                                                        Detalles del Vehículo
                                                    </div>
                                                    <div className="space-y-2">
                                                        {getVehiculoCompleto(referencia.categorias).map((campo) => (
                                                            <div key={campo.key} className="flex justify-between">
                                                                <span className="text-xs font-medium text-gray-600">{campo.label}:</span>
                                                                <span className="text-xs text-gray-800">{campo.value}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>
                                            )}
                                        </td>
                                    )}
                                    {(activeFilter === 'cat' || activeFilter === 'all') && (
                                        <td className="px-4 py-3 text-center border-0">
                                            {(() => {
                                                const images = getCatImages(referencia.categorias);
                                                if (images.length > 0) {
                                                    return (
                                                        <div className="flex justify-center space-x-1">
                                                            {images.slice(0, 3).map((imageUrl, index) => (
                                                                <img
                                                                    key={index}
                                                                    src={imageUrl}
                                                                    alt={`Imagen ${index + 1}`}
                                                                    className="w-12 h-12 object-cover rounded-lg border-2 border-gray-200 cursor-pointer hover:border-orange-500 transition-colors duration-200"
                                                                    onClick={() => openImageModal(images, index)}
                                                                    onError={(e) => {
                                                                        e.target.style.display = 'none';
                                                                    }}
                                                                />
                                                            ))}
                                                            {images.length > 3 && (
                                                                <div 
                                                                    className="w-12 h-12 bg-gray-100 border-2 border-gray-200 rounded-lg flex items-center justify-center cursor-pointer hover:border-orange-500 transition-colors duration-200"
                                                                    onClick={() => openImageModal(images, 3)}
                                                                >
                                                                    <span className="text-xs font-medium text-gray-600">
                                                                        +{images.length - 3}
                                                                    </span>
                                                                </div>
                                                            )}
                                                        </div>
                                                    );
                                                }
                                                return (
                                                    <span className="text-gray-400 text-sm">Sin imágenes</span>
                                                );
                                            })()}
                                        </td>
                                    )}
                                    <td className="px-4 py-3 text-sm text-gray-700 border-0">
                                        <div className="flex items-center">
                                            {referencia.usuario?.imagen && (
                                                <img 
                                                    src={referencia.usuario.imagen} 
                                                    alt={referencia.vendedor}
                                                    className="w-6 h-6 rounded-full mr-2 object-cover"
                                                />
                                            )}
                                            <span className="font-medium truncate">{referencia.vendedor}</span>
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-700 border-0">
                                        <div className="flex flex-col">
                                            <span className="font-bold text-green-600">
                                                {referencia.precio}
                                            </span>
                                            {parseFloat(referencia.importe_casco) > 0 && (
                                                <span className="text-xs text-gray-500">
                                                    Casco: €{parseFloat(referencia.importe_casco).toFixed(2)}
                                                </span>
                                            )}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-sm text-gray-700 text-center border-0">
                                        <div className="actions-menu inline-block">
                                            <button
                                                onClick={() => toggleActions(referencia.id)}
                                                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition-colors duration-200"
                                            >
                                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
                                                </svg>
                                            </button>
                                            
                                            {/* Menú desplegable */}
                                            {openActions === referencia.id && (
                                                <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-50 border border-gray-200">
                                                                                                    <div className="py-1">
                                                                                                            {referencia.usuario?.whatsapp && (
                                                            <a 
                                                                href={`https://wa.me/${referencia.usuario.whatsapp}?text=Hola, vengo de onrecambio.com y me interesa la referencia ${referencia.referencia}`}
                                                                target="_blank"
                                                                rel="noopener noreferrer"
                                                                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 transition-colors duration-150 flex items-center"
                                                                style={{ textDecoration: 'none' }}
                                                            >
                                                                <svg className="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 24 24">
                                                                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893A11.821 11.821 0 0020.885 3.488"/>
                                                                </svg>
                                                                WhatsApp
                                                            </a>
                                                        )}
                                                        
                                                        {referencia.usuario?.telefono && (
                                                            <a 
                                                                href={`tel:${referencia.usuario.telefono}`}
                                                                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 transition-colors duration-150 flex items-center"
                                                                style={{ textDecoration: 'none' }}
                                                            >
                                                                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                                                                </svg>
                                                                Llamar
                                                            </a>
                                                        )}
                                                        
                                                        {referencia.usuario?.email && (
                                                            <a 
                                                                href={`mailto:${referencia.usuario.email}`}
                                                                className="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 hover:text-blue-700 transition-colors duration-150 flex items-center"
                                                                style={{ textDecoration: 'none' }}
                                                            >
                                                                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                                                                </svg>
                                                                Email
                                                            </a>
                                                        )}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))
                        ) : (
                            <tr>
                                <td colSpan={activeFilter === 'cat' || activeFilter === 'all' ? "7" : "5"} className="px-6 py-12 text-center text-gray-500 bg-gray-50">
                                    <div className="flex flex-col items-center">
                                        <svg className="w-12 h-12 text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                        </svg>
                                        <p className="text-lg font-medium">No se encontraron referencias</p>
                                        <p className="text-sm text-gray-400">Intenta con otros criterios de búsqueda</p>
                                    </div>
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            {/* Vista móvil - Cards */}
            <div className="lg:hidden">
                {referencias.length > 0 ? (
                    <div className="p-4 space-y-4">
                        {referencias.map((referencia, index) => (
                            <div key={referencia.id} className={`border rounded-lg p-4 ${
                                index % 2 === 0 ? 'bg-white' : 'bg-gray-50'
                            } hover:shadow-md transition-shadow duration-200`}>
                                {/* Header de la card */}
                                <div className="flex justify-between items-start mb-3">
                                    <div className="flex items-center space-x-2">
                                        <span className="text-lg font-bold text-gray-800">
                                            {referencia.referencia}
                                        </span>
                                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                            {referencia.marca}
                                        </span>
                                    </div>
                                    <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                        referencia.stock > 10 
                                            ? 'bg-green-100 text-green-800' 
                                            : referencia.stock > 0 
                                                ? 'bg-yellow-100 text-yellow-800' 
                                                : 'bg-red-100 text-red-800'
                                    }`}>
                                        {referencia.stock} uds
                                    </span>
                                </div>

                                {/* Contenido principal */}
                                <div className="space-y-2 mb-3">
                                    <div>
                                        <span className="text-sm font-medium text-gray-600">Descripción:</span>
                                        <p className="text-sm text-gray-800">{referencia.descripcion}</p>
                                    </div>
                                    {(activeFilter === 'cat' || activeFilter === 'all') && (
                                        <div 
                                            className="relative cursor-help"
                                            onMouseEnter={(e) => {
                                                if (referencia.categorias && referencia.categorias.length > 0) {
                                                    setHoveredVehiculo(referencia.id);
                                                    setTooltipPosition({ x: e.clientX + 10, y: e.clientY - 10 });
                                                }
                                            }}
                                            onMouseLeave={() => setHoveredVehiculo(null)}
                                        >
                                            <span className="text-sm font-medium text-gray-600">Vehículo:</span>
                                            <p className="text-sm text-gray-800">{referencia.vehiculo}</p>
                                            
                                            {/* Tooltip del vehículo en móvil */}
                                            {hoveredVehiculo === referencia.id && referencia.categorias && referencia.categorias.length > 0 && (
                                                <div 
                                                    className="fixed z-50 w-72 bg-white border border-gray-200 rounded-lg shadow-xl p-3"
                                                    style={{
                                                        left: tooltipPosition.x,
                                                        top: tooltipPosition.y
                                                    }}
                                                >
                                                    <div className="text-sm font-medium text-gray-900 mb-2 border-b border-gray-100 pb-2">
                                                        Detalles del Vehículo
                                                    </div>
                                                    <div className="space-y-1">
                                                        {getVehiculoCompleto(referencia.categorias).map((campo) => (
                                                            <div key={campo.key} className="flex justify-between">
                                                                <span className="text-xs font-medium text-gray-600">{campo.label}:</span>
                                                                <span className="text-xs text-gray-800">{campo.value}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>
                                            )}
                                        </div>
                                    )}
                                    {(activeFilter === 'cat' || activeFilter === 'all') && (() => {
                                        const images = getCatImages(referencia.categorias);
                                        if (images.length > 0) {
                                            return (
                                                <div>
                                                    <span className="text-sm font-medium text-gray-600">Imágenes:</span>
                                                    <div className="flex space-x-2 mt-1">
                                                        {images.slice(0, 4).map((imageUrl, index) => (
                                                            <img
                                                                key={index}
                                                                src={imageUrl}
                                                                alt={`Imagen ${index + 1}`}
                                                                className="w-16 h-16 object-cover rounded-lg border-2 border-gray-200 cursor-pointer hover:border-orange-500 transition-colors duration-200"
                                                                onClick={() => openImageModal(images, index)}
                                                                onError={(e) => {
                                                                    e.target.style.display = 'none';
                                                                }}
                                                            />
                                                        ))}
                                                        {images.length > 4 && (
                                                            <div 
                                                                className="w-16 h-16 bg-gray-100 border-2 border-gray-200 rounded-lg flex items-center justify-center cursor-pointer hover:border-orange-500 transition-colors duration-200"
                                                                onClick={() => openImageModal(images, 4)}
                                                            >
                                                                <span className="text-xs font-medium text-gray-600">
                                                                    +{images.length - 4}
                                                                </span>
                                                            </div>
                                                        )}
                                                    </div>
                                                </div>
                                            );
                                        }
                                        return null;
                                    })()}
                                    <div>
                                        <span className="text-sm font-medium text-gray-600">Ubicación:</span>
                                        <p className="text-sm text-gray-800">{referencia.poblacion}, {referencia.provincia}</p>
                                    </div>
                                </div>

                                {/* Vendedor y precio */}
                                <div className="flex justify-between items-center mb-3">
                                    <div className="flex items-center">
                                        {referencia.usuario?.imagen && (
                                            <img 
                                                src={referencia.usuario.imagen} 
                                                alt={referencia.vendedor}
                                                className="w-8 h-8 rounded-full mr-2 object-cover"
                                            />
                                        )}
                                        <span className="text-sm font-medium text-gray-800">{referencia.vendedor}</span>
                                    </div>
                                    <div className="text-right">
                                        <span className="text-lg font-bold text-green-600 block">
                                            {referencia.precio}
                                        </span>
                                        {parseFloat(referencia.importe_casco) > 0 && (
                                            <span className="text-xs text-gray-500">
                                                Casco: €{parseFloat(referencia.importe_casco).toFixed(2)}
                                            </span>
                                        )}
                                    </div>
                                </div>

                                {/* Acciones */}
                                <div className="flex space-x-2">
                                    {referencia.usuario?.whatsapp && (
                                        <a 
                                            href={`https://wa.me/${referencia.usuario.whatsapp}?text=Hola, vengo de onrecambio.com y me interesa la referencia ${referencia.referencia}`}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="flex-1 px-4 py-2 bg-orange-500 hover:bg-orange-600 text-white text-sm rounded-lg transition-all duration-200 hover:shadow-md font-medium text-center"
                                        >
                                            WhatsApp
                                        </a>
                                    )}
                                    {referencia.usuario?.telefono && (
                                        <a 
                                            href={`tel:${referencia.usuario.telefono}`}
                                            className="flex-1 px-4 py-2 bg-blue-800 hover:bg-blue-900 text-white text-sm rounded-lg transition-all duration-200 hover:shadow-md font-medium text-center"
                                        >
                                            Llamar
                                        </a>
                                    )}
                                    {referencia.usuario?.email && (
                                        <a 
                                            href={`mailto:${referencia.usuario.email}`}
                                            className="flex-1 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded-lg transition-all duration-200 hover:shadow-md font-medium text-center"
                                        >
                                            Email
                                        </a>
                                    )}
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div className="p-6 text-center text-gray-500 bg-gray-50">
                        <div className="flex flex-col items-center">
                            <svg className="w-12 h-12 text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                            </svg>
                            <p className="text-lg font-medium">No se encontraron referencias</p>
                            <p className="text-sm text-gray-400">Intenta con otros criterios de búsqueda</p>
                        </div>
                    </div>
                )}
            </div>

            {/* Modal de imágenes */}
            {selectedImages && (
                <div className="fixed inset-0 bg-black bg-opacity-75 flex items-end justify-center z-50 pb-16" onClick={closeImageModal}>
                    <div className="relative max-w-4xl max-h-[85vh] p-4" onClick={(e) => e.stopPropagation()}>
                        {/* Botón cerrar */}
                        <button
                            onClick={closeImageModal}
                            className="absolute top-2 right-2 z-10 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-2 transition-all duration-200"
                        >
                            <svg className="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                        </button>

                        {/* Imagen principal */}
                        <div className="relative">
                            <img
                                src={selectedImages[currentImageIndex]}
                                alt={`Imagen ${currentImageIndex + 1}`}
                                className="max-w-full max-h-[70vh] object-contain rounded-lg shadow-2xl"
                                onError={(e) => {
                                    e.target.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjNmNGY2Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIgZm9udC1zaXplPSIxOCIgZmlsbD0iIzZiNzI4MCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkVycm9yIGFsIGNhcmdhciBpbWFnZW48L3RleHQ+PC9zdmc+';
                                }}
                            />

                            {/* Navegación */}
                            {selectedImages.length > 1 && (
                                <>
                                    {/* Botón anterior */}
                                    <button
                                        onClick={() => navigateImage('prev')}
                                        className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-3 transition-all duration-200"
                                    >
                                        <svg className="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                        </svg>
                                    </button>

                                    {/* Botón siguiente */}
                                    <button
                                        onClick={() => navigateImage('next')}
                                        className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white bg-opacity-80 hover:bg-opacity-100 rounded-full p-3 transition-all duration-200"
                                    >
                                        <svg className="w-6 h-6 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                        </svg>
                                    </button>
                                </>
                            )}

                            {/* Contador de imágenes - Dentro de la imagen, abajo centrado */}
                            {selectedImages.length > 1 && (
                                <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 bg-black bg-opacity-90 text-white px-4 py-2 rounded-full text-base font-semibold shadow-lg border border-white border-opacity-30">
                                    {currentImageIndex + 1} / {selectedImages.length}
                                </div>
                            )}
                        </div>

                        {/* Miniaturas */}
                        {selectedImages.length > 1 && (
                            <div className="flex justify-center space-x-2 mt-4">
                                {selectedImages.map((imageUrl, index) => (
                                    <img
                                        key={index}
                                        src={imageUrl}
                                        alt={`Miniatura ${index + 1}`}
                                            className={`w-16 h-16 object-cover rounded-lg border-2 cursor-pointer transition-all duration-200 ${
                                            index === currentImageIndex 
                                                ? 'border-orange-500 opacity-100' 
                                                : 'border-gray-300 opacity-70 hover:opacity-100'
                                        }`}
                                        onClick={() => setCurrentImageIndex(index)}
                                        onError={(e) => {
                                            e.target.style.display = 'none';
                                        }}
                                    />
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}
        </div>
    );
}
