// Componente Header del directorio de vendedores
function Header() {
    return (
        <div className="text-center mb-8">
            <h1 className="text-4xl md:text-5xl font-bold text-gray-800 mb-4">
                Directorio de Vendedores
            </h1>
            <p className="text-lg text-gray-600 max-w-3xl mx-auto">
                Encuentra vendedores de confianza en tu provincia. Explora sus perfiles y descubre sus productos.
            </p>
        </div>
    );
}

// Componente de búsqueda y filtros
function SearchFilters({ searchTerm, setSearchTerm, selectedProvince, setSelectedProvince, showFavoritesOnly, setShowFavoritesOnly }) {
    const provinces = [
        "Todas",
        "Álava",
        "Albacete",
        "Alicante",
        "Almería",
        "Asturias",
        "Ávila",
        "Badajoz",
        "Barcelona",
        "Burgos",
        "Cáceres",
        "Cádiz",
        "Cantabria",
        "Castellón",
        "Ciudad Real",
        "Córdoba",
        "Cuenca",
        "Girona",
        "Granada",
        "Guadalajara",
        "Guipúzcoa",
        "Huelva",
        "Huesca",
        "Islas Baleares",
        "Jaén",
        "La Coruña",
        "La Rioja",
        "Las Palmas",
        "León",
        "Lleida",
        "Lugo",
        "Madrid",
        "Málaga",
        "Murcia",
        "Navarra",
        "Ourense",
        "Palencia",
        "Pontevedra",
        "Salamanca",
        "Santa Cruz de Tenerife",
        "Segovia",
        "Sevilla",
        "Soria",
        "Tarragona",
        "Teruel",
        "Toledo",
        "Valencia",
        "Valladolid",
        "Vizcaya",
        "Zamora",
        "Zaragoza"
    ];


    return (
        <div className="rounded-lg shadow-sm p-6 mb-6">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* Búsqueda */}
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        Buscar
                    </label>
                    <div className="relative">
                        <input
                            type="text"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            placeholder="Buscar por nombre o negocio..."
                            className="block w-full pl-3 pr-11 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:placeholder-gray-400 focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                        />
                        <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                            <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <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 Provincia */}
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        Provincia
                    </label>
                    <div className="relative">
                        <select
                            value={selectedProvince}
                            onChange={(e) => setSelectedProvince(e.target.value)}
                            className="block w-full pr-10 py-2 border border-gray-300 rounded-md leading-5 bg-white focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                        >
                            {provinces.map(province => (
                                <option key={province} value={province}>{province}</option>
                            ))}
                        </select>
                    </div>
                </div>

                {/* Filtro Favoritos */}
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                        Filtros
                    </label>
                    <div className="flex items-center">
                        <label className="flex items-center cursor-pointer">
                            <input
                                type="checkbox"
                                checked={showFavoritesOnly}
                                onChange={(e) => setShowFavoritesOnly(e.target.checked)}
                                className="w-4 h-4 text-red-600 bg-gray-100 border-gray-300 rounded focus:ring-red-500 focus:ring-2"
                            />
                            <span className="ml-2 text-sm text-gray-700 flex items-center">
                                <svg className="w-4 h-4 text-red-500 mr-1" fill="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                </svg>
                                Solo favoritos
                            </span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    );
}

// Componente para mostrar el contador de resultados
function ResultsCount({ count, loading }) {
    if (loading) {
        return null;
    }

    return (
        <div className="mb-6">
            <p className="text-gray-700 font-medium">
                Mostrando {count} vendedor{count !== 1 ? 'es' : ''}
            </p>
        </div>
    );
}

// Componente de tarjeta individual de vendedor
function VendorCard({ vendor, isFavorite, onToggleFavorite }) {
    // Función para generar slug
    const generateSlug = (text) => {
        if (!text) return 'vendedor';
        return text
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '') // Remover acentos
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/^-+|-+$/g, '');
    };

    const vendorSlug = generateSlug(vendor.businessName);
    const profileUrl = `/vendedores/${vendorSlug}`;

    return (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow duration-200">
            {/* Header de la tarjeta */}
            <div className="flex items-start mb-4">
                {/* Avatar */}
                <div className="w-12 h-12 bg-gray-200 rounded-full flex items-center justify-center mr-4 flex-shrink-0 overflow-hidden">
                    {vendor.image ? (
                        <img
                            src={vendor.image}
                            alt={`Perfil de ${vendor.vendorName}`}
                            className="w-full h-full object-cover rounded-full"
                            onError={(e) => {
                                e.target.style.display = 'none';
                                e.target.nextElementSibling.style.display = 'flex';
                            }}
                        />
                    ) : null}
                    <svg
                        className={`w-6 h-6 text-gray-400 ${vendor.image ? 'hidden' : ''}`}
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                        style={{ display: vendor.image ? 'none' : 'block' }}
                        xmlns="http://www.w3.org/2000/svg"
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                </div>

                {/* Información del vendedor */}
                <div className="flex-1 min-w-0">
                    <h3 className="text-lg font-semibold text-gray-900 truncate">
                        {vendor.businessName}
                    </h3>
                </div>

                {/* Botón de favoritos */}
                <button
                    onClick={() => onToggleFavorite(vendor.id)}
                    className="ml-2 p-2 rounded-full hover:bg-gray-50 transition-colors duration-200 focus:outline-none focus:ring-0 focus:bg-transparent active:bg-gray-100 active:scale-95 transform border-0 bg-transparent"
                    style={{ outline: 'none', boxShadow: 'none' }}
                    title={isFavorite ? 'Quitar de favoritos' : 'Añadir a favoritos'}
                >
                    {isFavorite ? (
                        <svg
                            className="w-5 h-5 text-red-500"
                            fill="currentColor"
                            viewBox="0 0 24 24"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <path d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                        </svg>
                    ) : (
                        <svg
                            className="w-5 h-5 text-gray-400 hover:text-red-400 transition-colors duration-200"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            xmlns="http://www.w3.org/2000/svg"
                        >
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                        </svg>
                    )}
                </button>
            </div>

            {/* Descripción */}
            <p className="text-sm text-gray-600 mb-4 line-clamp-2">
                {vendor.description}
            </p>

            {/* Información de contacto */}
            <div className="space-y-2 mb-4">
                {/* Ubicación */}
                <div className="flex items-center text-sm text-gray-600">
                    <svg className="w-4 h-4 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    <span>{vendor.location}</span>
                </div>

                {/* Teléfono */}
                <div className="flex items-center text-sm text-gray-600">
                    <svg className="w-4 h-4 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <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>
                    <span>{vendor.phone}</span>
                </div>

                {/* Email */}
                <div className="flex items-center text-sm text-gray-600">
                    <svg className="w-4 h-4 mr-2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <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>
                    <span className="truncate">{vendor.email}</span>
                </div>

                {/* Botón Ver Perfil */}
                <div className="pt-2">
                    <a
                        href={profileUrl}
                        className="hover:text-white bg-blue-800 hover:bg-blue-600 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors duration-200 w-full inline-block text-center"
                    >
                        Ver Perfil
                    </a>
                </div>
            </div>
        </div>
    );
}

// Componente de grid de vendedores
function VendorGrid({ vendors, loading, favorites, onToggleFavorite }) {
    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-600"></div>
                <p className="mt-4 text-gray-600">Cargando vendedores...</p>
            </div>
        );
    }

    if (vendors.length === 0) {
        return (
            <div className="text-center py-12">
                <svg className="w-16 h-16 text-gray-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                </svg>
                <h3 className="text-lg font-medium text-gray-900 mb-2">
                    No se encontraron vendedores
                </h3>
                <p className="text-gray-500">
                    Intenta ajustar los filtros de búsqueda
                </p>
            </div>
        );
    }

    return (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {vendors.map((vendor, index) => (
                <VendorCard
                    key={vendor.id || index}
                    vendor={vendor}
                    isFavorite={favorites.includes(vendor.id)}
                    onToggleFavorite={onToggleFavorite}
                />
            ))}
        </div>
    );
}

// Componente principal de la aplicación Vendedores
function VendedoresApp() {
    const [searchTerm, setSearchTerm] = React.useState('');
    const [selectedProvince, setSelectedProvince] = React.useState('Todas');
    const [showFavoritesOnly, setShowFavoritesOnly] = React.useState(false);
    const [vendors, setVendors] = React.useState([]);
    const [loading, setLoading] = React.useState(false);
    const [allVendors, setAllVendors] = React.useState([]);
    const [favorites, setFavorites] = React.useState([]);

    // Cargar favoritos al inicializar
    React.useEffect(() => {
        loadFavorites();
    }, []);

    // Función para cargar favoritos
    const loadFavorites = async () => {
        try {
            const form = new URLSearchParams();
            form.append('action', 'vendedores_get_favorites');
            form.append('nonce', (window.vendedoresPlugin && window.vendedoresPlugin.nonce) || '');
            const res = await fetch((window.vendedoresPlugin && window.vendedoresPlugin.ajax_url) || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: form.toString()
            });
            const json = await res.json();
            if (json && json.success && Array.isArray(json.data.favorites)) {
                // Convertir a strings para asegurar consistencia
                const favoritesAsStrings = json.data.favorites.map(id => String(id));
                setFavorites(favoritesAsStrings);
            }
        } catch (e) {
            console.error('Error loading favorites:', e);
        }
    };

    // Función para toggle favoritos con actualización optimista
    const handleToggleFavorite = async (vendorId) => {
        const isFavorite = favorites.includes(vendorId);

        // Actualización optimista: cambiar el estado inmediatamente
        if (isFavorite) {
            setFavorites(prev => prev.filter(id => id !== vendorId));
        } else {
            setFavorites(prev => [...prev, vendorId]);
        }

        const action = isFavorite ? 'vendedores_remove_favorite' : 'vendedores_add_favorite';

        try {
            const form = new URLSearchParams();
            form.append('action', action);
            form.append('vendor_id', vendorId);
            form.append('nonce', (window.vendedoresPlugin && window.vendedoresPlugin.nonce) || '');

            const res = await fetch((window.vendedoresPlugin && window.vendedoresPlugin.ajax_url) || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                body: form.toString()
            });
            const json = await res.json();

            if (json && json.success && Array.isArray(json.data.favorites)) {
                // Sincronizar con el servidor
                const favoritesAsStrings = json.data.favorites.map(id => String(id));
                setFavorites(favoritesAsStrings);
            } else if (json && !json.success) {
                // Revertir cambio optimista si hay error
                if (isFavorite) {
                    setFavorites(prev => [...prev, vendorId]);
                } else {
                    setFavorites(prev => prev.filter(id => id !== vendorId));
                }

                if (json.data && json.data.message) {
                    alert(json.data.message);
                }
            }
        } catch (e) {
            // Revertir cambio optimista si hay error de red
            if (isFavorite) {
                setFavorites(prev => [...prev, vendorId]);
            } else {
                setFavorites(prev => prev.filter(id => id !== vendorId));
            }
            console.error('Error toggling favorite:', e);
            alert('Error al procesar favoritos. Por favor, inténtalo de nuevo.');
        }
    };

    // Cargar vendedores desde AJAX de WP (que proxy a la API)
    React.useEffect(() => {
        let abort = false;
        async function loadVendors() {
            try {
                setLoading(true);
                const form = new URLSearchParams();
                form.append('action', 'vendedores_list');
                form.append('nonce', (window.vendedoresPlugin && window.vendedoresPlugin.nonce) || '');
                const res = await fetch((window.vendedoresPlugin && window.vendedoresPlugin.ajax_url) || '/wp-admin/admin-ajax.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    body: form.toString()
                });
                const json = await res.json();
                if (!abort) {
                    if (json && json.success && json.data && Array.isArray(json.data.items)) {
                        // Mapear a formato de UI
                        const mapped = json.data.items.map((item) => ({
                            id: String(item.id), // Asegurar que sea string
                            businessName: item.nombre || 'Sin nombre',
                            vendorName: item.nombre || 'Sin nombre',
                            category: 'General',
                            description: `${item.ciudad || ''}${item.ciudad && item.provincia ? ', ' : ''}${item.provincia || ''}`.trim() || 'Sin descripción',
                            location: `${item.ciudad || ''}${item.ciudad && item.provincia ? ', ' : ''}${item.provincia || ''}`.trim(),
                            phone: item.telefono || item.whatsapp || '',
                            email: item.email || '',
                            rating: '-',
                            views: '-',
                            image: item.imagen || ''
                        }));

                        setAllVendors(mapped);
                    } else {
                        setAllVendors([]);
                    }
                }
            } catch (e) {
                if (!abort) setAllVendors([]);
            } finally {
                if (!abort) setLoading(false);
            }
        }
        loadVendors();
        return () => { abort = true; };
    }, []);

    // Función para filtrar vendedores
    const filterVendors = React.useCallback(() => {
        return allVendors.filter(vendor => {
            const matchesSearch = !searchTerm ||
                vendor.businessName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                vendor.vendorName.toLowerCase().includes(searchTerm.toLowerCase());

            const matchesProvince = selectedProvince === 'Todas' ||
                vendor.location.includes(selectedProvince);

            const matchesFavorites = !showFavoritesOnly || favorites.includes(vendor.id);

            return matchesSearch && matchesProvince && matchesFavorites;
        });
    }, [searchTerm, selectedProvince, showFavoritesOnly, allVendors, favorites]);

    // Efecto para aplicar filtros
    React.useEffect(() => {
        const filteredVendors = filterVendors();
        setVendors(filteredVendors);
    }, [filterVendors]);

    return (
        <div className="vendedores-app min-h-screen">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* Header */}
                <Header />

                {/* Búsqueda y filtros */}
                <SearchFilters
                    searchTerm={searchTerm}
                    setSearchTerm={setSearchTerm}
                    selectedProvince={selectedProvince}
                    setSelectedProvince={setSelectedProvince}
                    showFavoritesOnly={showFavoritesOnly}
                    setShowFavoritesOnly={setShowFavoritesOnly}
                />

                {/* Contador de resultados */}
                <ResultsCount count={vendors.length} loading={loading} />

                {/* Grid de vendedores */}
                <VendorGrid
                    vendors={vendors}
                    loading={loading}
                    favorites={favorites}
                    onToggleFavorite={handleToggleFavorite}
                />
            </div>
        </div>
    );
}

// Renderizar la aplicación
function initReactApp() {
    const container = document.getElementById('vendedores-container');

    if (container) {
        const root = ReactDOM.createRoot(container);
        root.render(React.createElement(VendedoresApp));
    }
}

// Inicializar aplicación
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initReactApp);
} else {
    initReactApp();
}