function searchMods() {
    const query = document.getElementById("mod-search").value;
    fetch('/api/config')
        .then(response => response.json())
        .then(configData => {
            console.log(configData);
            if (configData.success) {
                const serverType = configData.type;
                const serverVersion = configData.version;
                if (serverType && serverVersion) {
                    fetch(`/api/modrinth/search?query=${encodeURIComponent(query)}&type=${serverType}&version=${serverVersion}`)
                        .then(r => r.json())
                        .then(data => {
                            const results = document.getElementById("mod-results");
                            results.innerHTML = "";
                            data.hits.forEach(mod => {
                                const modEl = document.createElement("div");
                                modEl.innerHTML = `
                                    <strong>${mod.title}</strong> - <a onclick="installMod('${mod.project_id}')">Zainstaluj</a><hr>`;
                                results.appendChild(modEl);
                            });
                        });
                } else {
                    console.error('Server type or version not available');
                }
            } else {
                console.error('Server config not found');
            }
        })
        .catch(err => {
            console.error('Error fetching server config:', err);
        });
}

function installMod(projectId) {
    fetch('/api/config')
    .then(response => response.json())
    .then(configData => {
        if (configData.success) {
            const serverType = configData.type;
            const serverVersion = configData.version;
            if (serverType && serverVersion) {
                fetch('/api/modrinth/download', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ project_id: projectId, username, type: serverType, version: serverVersion }),
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        const modFiles = data.downloaded.map(mod => "- " + mod.filename).join("\n");
                        alert(`Zainstalowano:\n${modFiles}`);
                        loadFileList();
                    } else {
                        alert("Nie udało się zainstalować moda.");
                    }
                });
            } else {
                console.error('Server type or version not available');
            }
        } else {
            console.error('Server config not found');
        }
    })
    .catch(err => {
        console.error('Error fetching server config:', err);
    });
}