const { useState, useEffect } = React;

// --- SISTEMA DE ÍCONOS VECTORIALES (Sin dependencias externas, carga ultrarrápida) ---
const SvgIcon = ({ name, className, style }) => {
    const icons = {
        FileText: <><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" /><polyline points="10 9 9 9 8 9" /></>,
        Video: <><polygon points="23 7 16 12 23 17 23 7" /><rect x="1" y="5" width="15" height="14" rx="2" ry="2" /></>,
        Mic: <><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" /><path d="M19 10v2a7 7 0 0 1-14 0v-2" /><line x1="12" y1="19" x2="12" y2="23" /><line x1="8" y1="23" x2="16" y2="23" /></>,
        Tag: <><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" /><line x1="7" y1="7" x2="7.01" y2="7" /></>,
        BookOpen: <><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" /><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" /></>,
        ImageIcon: <><rect x="3" y="3" width="18" height="18" rx="2" ry="2" /><circle cx="8.5" cy="8.5" r="1.5" /><polyline points="21 15 16 10 5 21" /></>,
        Headphones: <><path d="M3 18v-6a9 9 0 0 1 18 0v6" /><path d="M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z" /></>,
        Globe: <><circle cx="12" cy="12" r="10" /><line x1="2" y1="12" x2="22" y2="12" /><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" /></>,
        Newspaper: <><path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2" /><path d="M18 14h-8" /><path d="M15 18h-5" /><path d="M10 6h8v4h-8V6Z" /></>,
        Search: <><circle cx="11" cy="11" r="8" /><line x1="21" y1="21" x2="16.65" y2="16.65" /></>,
        Pin: <><line x1="12" y1="17" x2="12" y2="22" /><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 11.24V6a3 3 0 0 0-6 0v5.24a2 2 0 0 1-1.11 1.31l-1.78.9A2 2 0 0 0 5 15.24Z" /></>,
        ArrowLeft: <><line x1="19" y1="12" x2="5" y2="12" /><polyline points="12 19 5 12 12 5" /></>,
        ArrowRight: <><line x1="5" y1="12" x2="19" y2="12" /><polyline points="12 5 19 12 12 19" /></>,
        LinkIcon: <><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" /><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" /></>
    };
    return (
        <svg className={className} style={style} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            {icons[name] || icons.LinkIcon}
        </svg>
    );
};

function FrontendApp() {
    // Validar conexión a WP
    if (typeof wpdhPublicApi === 'undefined') {
        return <div className="p-4 bg-slate-100 text-slate-500 rounded">Cargando directorio...</div>;
    }

    const [loading, setLoading] = useState(true);
    const [links, setLinks] = useState([]);
    const [featured, setFeatured] = useState([]);
    const [categories, setCategories] = useState([]);
    
    // Filtros
    const [searchQuery, setSearchQuery] = useState('');
    const [selectedCategory, setSelectedCategory] = useState('all');
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 50;

    // Fetch a la Base de Datos
    const fetchPublicData = async () => {
        setLoading(true);
        try {
            const queryParams = new URLSearchParams({
                search: searchQuery,
                cat: selectedCategory
            });
            const res = await fetch(`${wpdhPublicApi.root}/public-data?${queryParams.toString()}`);
            const data = await res.json();
            
            if (data) {
                setCategories(data.categories || []);
                setFeatured(data.featured || []);
                
                // Mezclar los enlaces aleatoriamente para una vista más orgánica
                let mixedLinks = data.links || [];
                for (let i = mixedLinks.length - 1; i > 0; i--) {
                    const j = Math.floor(Math.random() * (i + 1));
                    [mixedLinks[i], mixedLinks[j]] = [mixedLinks[j], mixedLinks[i]];
                }
                setLinks(mixedLinks);
            }
        } catch(e) {
            console.error("Error obteniendo datos públicos:", e);
        }
        setLoading(false);
    };

    // Registrar click silencioso
    const trackClick = (id) => {
        fetch(`${wpdhPublicApi.root}/click/${id}`, { method: 'POST' }).catch(()=>console.log("No se pudo registrar el click"));
    };

    // Traer datos cada vez que cambia el buscador o categoría
    useEffect(() => {
        // Debounce para no saturar el servidor al escribir rápido
        const timer = setTimeout(() => {
            setCurrentPage(1); // Volver a página 1
            fetchPublicData();
        }, 400); 
        return () => clearTimeout(timer);
    }, [searchQuery, selectedCategory]);

    const totalPages = Math.ceil(links.length / itemsPerPage);
    const currentLinks = links.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);

    const getCategoryData = (catId) => {
        return categories.find(c => c.id === catId) || { name: catId, icon: 'LinkIcon', cta: 'Visitar', color: '#64748b' };
    };

    return (
        <div style={{ fontFamily: "'Nunito', sans-serif" }} className="w-full text-slate-800">
            <div className="flex flex-col md:flex-row gap-8">
                
                {/* COLUMNA IZQUIERDA (2/3) - Filtros y Enlaces */}
                <div className="w-full md:w-2/3">
                    <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                        
                        {/* Cabecera dinámica (Buscador + Filtro) */}
                        <div className="p-4 bg-slate-50 border-b border-slate-200 flex flex-col xl:flex-row justify-between items-start xl:items-center gap-4">
                            <h3 className="font-bold text-lg text-slate-700 whitespace-nowrap">
                                {searchQuery.trim().length > 0 ? `Resultados: "${searchQuery}"` : 'Navega el Pasado'}
                            </h3>
                            
                            <div className="flex flex-col sm:flex-row gap-2 w-full xl:w-auto">
                                <div className="relative w-full sm:w-64 group">
                                    <input
                                        type="text"
                                        value={searchQuery}
                                        onChange={(e) => setSearchQuery(e.target.value)}
                                        className="block w-full pl-4 pr-10 py-2 border border-slate-300 rounded-md leading-5 bg-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 sm:text-sm transition-colors"
                                        placeholder="Buscar en el archivo..."
                                    />
                                    <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                                        <SvgIcon name="Search" className="h-4 w-4 text-slate-400 group-focus-within:text-blue-500 transition-colors" />
                                    </div>
                                </div>

                                <select 
                                    value={selectedCategory}
                                    onChange={(e) => setSelectedCategory(e.target.value)}
                                    className="p-2 text-sm font-semibold border border-slate-300 rounded-md bg-white text-slate-700 focus:ring-2 focus:ring-blue-500 focus:outline-none cursor-pointer min-w-[160px] shadow-sm w-full sm:w-auto"
                                >
                                    <option value="all">Todas las Categorías</option>
                                    {categories.map(cat => (
                                        <option key={cat.id} value={cat.id}>{cat.name}</option>
                                    ))}
                                </select>
                            </div>
                        </div>
                        
                        {/* Lista de enlaces */}
                        <ul className="divide-y divide-slate-100 min-h-[300px] relative">
                            {loading && (
                                <div className="absolute inset-0 bg-white/70 backdrop-blur-sm z-10 flex justify-center pt-20">
                                    <span className="font-bold text-slate-500 animate-pulse">Buscando...</span>
                                </div>
                            )}
                            
                            {!loading && currentLinks.length === 0 ? (
                                <li className="p-12 text-center text-slate-500 flex flex-col items-center justify-center">
                                    <SvgIcon name="Search" className="w-12 h-12 text-slate-300 mb-3" />
                                    <p className="font-semibold text-lg text-slate-600">No se encontraron resultados</p>
                                    <p className="text-sm">Intenta buscar con otros términos.</p>
                                </li>
                            ) : (
                                currentLinks.map(link => {
                                    const catData = getCategoryData(link.category);
                                    return (
                                        <li key={link.id} className="p-4 hover:bg-blue-50/50 transition-colors group">
                                            <a 
                                                href={link.url} 
                                                target="_blank" 
                                                rel={link.isFollow ? "noopener noreferrer" : "nofollow noopener noreferrer"}
                                                onClick={() => trackClick(link.id)}
                                                className="flex items-start gap-4"
                                            >
                                                <div className="mt-1 p-2 bg-slate-100 rounded-lg group-hover:bg-white group-hover:shadow-sm transition-all">
                                                    <SvgIcon name={catData.icon} className="w-5 h-5 flex-shrink-0" style={{color: catData.color}} />
                                                </div>
                                                <div>
                                                    <h4 className="text-lg font-semibold text-slate-800 group-hover:text-blue-600 transition-colors leading-tight mb-1">
                                                        {link.title}
                                                    </h4>
                                                    <div className="flex items-center gap-3 text-xs text-slate-400 font-medium uppercase tracking-wider">
                                                        <span>{catData.name}</span>
                                                        <span>•</span>
                                                        <span className="flex items-center gap-1 font-bold text-slate-500 group-hover:text-blue-500 transition-colors">
                                                            {catData.cta}
                                                        </span>
                                                    </div>
                                                </div>
                                            </a>
                                        </li>
                                    );
                                })
                            )}
                        </ul>
                    </div>

                    {/* Paginación */}
                    {totalPages > 1 && (
                        <div className="flex justify-center items-center gap-4 mt-8">
                            <button 
                                disabled={currentPage === 1}
                                onClick={() => setCurrentPage(prev => prev - 1)}
                                className="p-2 rounded-full hover:bg-slate-200 disabled:opacity-50 disabled:hover:bg-transparent transition-colors"
                            >
                                <SvgIcon name="ArrowLeft" className="w-5 h-5 text-slate-600" />
                            </button>
                            <span className="text-sm font-semibold text-slate-600">
                                Página {currentPage} de {totalPages}
                            </span>
                            <button 
                                disabled={currentPage === totalPages}
                                onClick={() => setCurrentPage(prev => prev + 1)}
                                className="p-2 rounded-full hover:bg-slate-200 disabled:opacity-50 disabled:hover:bg-transparent transition-colors"
                            >
                                <SvgIcon name="ArrowRight" className="w-5 h-5 text-slate-600" />
                            </button>
                        </div>
                    )}
                </div>

                {/* COLUMNA DERECHA (1/3) - Destacados */}
                <div className="w-full md:w-1/3">
                    <div className="bg-gradient-to-br from-amber-50 to-orange-50 rounded-xl shadow-sm border border-amber-200 sticky top-4">
                        <div className="p-5 border-b border-amber-200/50 flex items-center gap-2">
                            <SvgIcon name="Pin" className="w-5 h-5 text-amber-600" style={{ fill: '#d97706' }} />
                            <h3 className="font-bold text-lg text-amber-900">Destacados</h3>
                        </div>
                        <ul className="divide-y divide-amber-200/30 p-2">
                            {featured.length === 0 ? (
                                <li className="p-4 text-sm text-amber-700 text-center">No hay enlaces destacados.</li>
                            ) : (
                                featured.map(link => {
                                    const catData = getCategoryData(link.category);
                                    return (
                                        <li key={link.id} className="p-3 hover:bg-amber-100/50 transition-colors rounded-lg group">
                                            <a 
                                                href={link.url} 
                                                target="_blank" 
                                                rel={link.isFollow ? "noopener noreferrer" : "nofollow noopener noreferrer"}
                                                onClick={() => trackClick(link.id)}
                                                className="flex flex-col gap-1"
                                            >
                                                <h4 className="text-base font-bold text-amber-950 group-hover:text-amber-700 transition-colors leading-snug">
                                                    {link.title}
                                                </h4>
                                                <div className="flex items-center gap-1.5 text-xs text-amber-700/70 font-semibold uppercase mt-1">
                                                    <SvgIcon name={catData.icon} className="w-4 h-4" style={{color: catData.color}} />
                                                    <span className="ml-1">{catData.name}</span>
                                                </div>
                                            </a>
                                        </li>
                                    );
                                })
                            )}
                        </ul>
                    </div>
                </div>

            </div>
        </div>
    );
}

const rootElement = document.getElementById('wpdh-frontend-root');
if (rootElement) {
    const root = ReactDOM.createRoot(rootElement);
    root.render(<FrontendApp />);
}