(function () {
    window.AgentFrontendModules = window.AgentFrontendModules || {};

    window.AgentFrontendModules.createAuxUiModule = function createAuxUiModule(deps) {
        let uiBound = false;

        async function refreshLlamacppRunStatus() {
            if (!deps.refs.llamacppRunStatus) return;
            try {
                const status = await deps.authFetchJson(`${deps.getBackendUrl()}/api/llamacpp/status`);
                if (status.running && status.reachable) {
                    deps.refs.llamacppRunStatus.textContent = '● Running & reachable';
                    deps.refs.llamacppRunStatus.style.color = 'var(--green, #4caf50)';
                } else if (status.running) {
                    deps.refs.llamacppRunStatus.textContent = '● Starting…';
                    deps.refs.llamacppRunStatus.style.color = 'var(--text-muted)';
                } else {
                    deps.refs.llamacppRunStatus.textContent = '○ Stopped';
                    deps.refs.llamacppRunStatus.style.color = 'var(--text-muted)';
                }
            } catch {
                deps.refs.llamacppRunStatus.textContent = '';
            }
        }

        function bindSettingsAndHelp() {
            if (deps.refs.settingsBtn) {
                deps.refs.settingsBtn.addEventListener('click', () => {
                    if (deps.refs.settingsOverlay) deps.refs.settingsOverlay.style.display = 'flex';
                    deps.helpers.loadWikiStatus();
                });
            }
            if (deps.refs.settingsCloseBtn) {
                deps.refs.settingsCloseBtn.addEventListener('click', () => {
                    if (deps.refs.settingsOverlay) deps.refs.settingsOverlay.style.display = 'none';
                });
            }
            if (deps.refs.settingsCancelBtn) {
                deps.refs.settingsCancelBtn.addEventListener('click', () => {
                    deps.helpers.resetSettingsPanel();
                });
            }
            if (deps.refs.helpBtn) {
                deps.refs.helpBtn.addEventListener('click', () => {
                    if (deps.refs.helpOverlay) deps.refs.helpOverlay.style.display = 'flex';
                });
            }
            if (deps.refs.helpCloseBtn) {
                deps.refs.helpCloseBtn.addEventListener('click', () => {
                    if (deps.refs.helpOverlay) deps.refs.helpOverlay.style.display = 'none';
                });
            }
            if (deps.refs.helpOverlay) {
                deps.refs.helpOverlay.addEventListener('click', (event) => {
                    if (event.target === deps.refs.helpOverlay) deps.refs.helpOverlay.style.display = 'none';
                });
            }
            document.querySelectorAll('.help-nav .settings-nav-item').forEach((button) => {
                button.addEventListener('click', () => {
                    document.querySelectorAll('.help-nav .settings-nav-item').forEach((item) => item.classList.remove('active'));
                    document.querySelectorAll('.help-pane').forEach((pane) => pane.classList.remove('active'));
                    button.classList.add('active');
                    const pane = document.getElementById(button.dataset.helpPane);
                    if (pane) pane.classList.add('active');
                });
            });
        }

        function bindLlamacppUi() {
            refreshLlamacppRunStatus();
            deps.authFetch(`${deps.getBackendUrl()}/api/llamacpp/install-status`)
                .then((response) => response.json())
                .then((data) => {
                    if (deps.refs.llamacppInstallBtn) deps.refs.llamacppInstallBtn.style.display = data.installed ? 'none' : '';
                })
                .catch(() => {});

            if (deps.refs.llamacppDetectBtn) {
                deps.refs.llamacppDetectBtn.addEventListener('click', async () => {
                    deps.refs.llamacppDetectBtn.disabled = true;
                    deps.refs.llamacppDetectBtn.textContent = '...';
                    try {
                        const response = await deps.authFetch(`${deps.getBackendUrl()}/api/llamacpp/detect-ollama`);
                        const data = await response.json();
                        if (!data.found || !data.models || data.models.length === 0) {
                            if (deps.refs.llamacppRunStatus) {
                                deps.refs.llamacppRunStatus.textContent = 'Geen Ollama-modellen gevonden in ' + (data.models_dir || '~/.ollama/models');
                            }
                            if (deps.refs.llamacppOllamaModelsSel) deps.refs.llamacppOllamaModelsSel.style.display = 'none';
                        } else if (data.models.length === 1) {
                            if (deps.refs.llamacppModelPathInput) deps.refs.llamacppModelPathInput.value = data.models[0].path;
                            if (deps.refs.llamacppOllamaModelsSel) deps.refs.llamacppOllamaModelsSel.style.display = 'none';
                            if (deps.refs.llamacppRunStatus) deps.refs.llamacppRunStatus.textContent = `Pad ingesteld: ${data.models[0].name}`;
                        } else if (deps.refs.llamacppOllamaModelsSel) {
                            deps.refs.llamacppOllamaModelsSel.innerHTML = '<option value="">-- kies een model --</option>'
                                + data.models.map((model) => `<option value="${model.path.replace(/"/g, '&quot;')}">${model.name}</option>`).join('');
                            deps.refs.llamacppOllamaModelsSel.style.display = 'block';
                        }
                    } catch {
                        if (deps.refs.llamacppRunStatus) deps.refs.llamacppRunStatus.textContent = 'Detectie mislukt';
                    } finally {
                        deps.refs.llamacppDetectBtn.disabled = false;
                        deps.refs.llamacppDetectBtn.textContent = 'Zoek Ollama';
                    }
                });
            }

            if (deps.refs.llamacppOllamaModelsSel) {
                deps.refs.llamacppOllamaModelsSel.addEventListener('change', () => {
                    const value = deps.refs.llamacppOllamaModelsSel.value;
                    if (value && deps.refs.llamacppModelPathInput) {
                        deps.refs.llamacppModelPathInput.value = value;
                        deps.refs.llamacppOllamaModelsSel.style.display = 'none';
                        if (deps.refs.llamacppRunStatus) deps.refs.llamacppRunStatus.textContent = '';
                    }
                });
            }

            if (deps.refs.llamacppStopBtn) {
                deps.refs.llamacppStopBtn.addEventListener('click', async () => {
                    deps.refs.llamacppStopBtn.disabled = true;
                    try {
                        await deps.authFetchJson(`${deps.getBackendUrl()}/api/llamacpp/stop`, { method: 'POST' });
                        await refreshLlamacppRunStatus();
                        deps.helpers.refreshProviderNotes();
                    } catch {}
                    deps.refs.llamacppStopBtn.disabled = false;
                });
            }

            if (deps.refs.llamacppInstallBtn) {
                deps.refs.llamacppInstallBtn.addEventListener('click', async () => {
                    deps.refs.llamacppInstallBtn.disabled = true;
                    deps.refs.llamacppInstallBtn.textContent = '⏳ Bezig met downloaden…';
                    if (deps.refs.llamacppRunStatus) {
                        deps.refs.llamacppRunStatus.textContent = 'llama.cpp downloaden van GitHub…';
                        deps.refs.llamacppRunStatus.style.color = '';
                    }
                    try {
                        const response = await deps.authFetch(`${deps.getBackendUrl()}/api/llamacpp/install`, { method: 'POST' });
                        const result = await response.json();
                        if (result.ok) {
                            deps.refs.llamacppInstallBtn.style.display = 'none';
                            if (deps.refs.llamacppRunStatus) {
                                deps.refs.llamacppRunStatus.textContent = `✓ Geïnstalleerd (${result.version || 'latest'}). Klik nu op Start.`;
                                deps.refs.llamacppRunStatus.style.color = 'var(--green, #4caf50)';
                            }
                        } else {
                            if (deps.refs.llamacppRunStatus) {
                                deps.refs.llamacppRunStatus.textContent = result.error || 'Installatie mislukt';
                                deps.refs.llamacppRunStatus.style.color = 'var(--red, #f44336)';
                            }
                            deps.refs.llamacppInstallBtn.disabled = false;
                            deps.refs.llamacppInstallBtn.textContent = '⬇ Installeer llama.cpp';
                        }
                    } catch (error) {
                        if (deps.refs.llamacppRunStatus) {
                            deps.refs.llamacppRunStatus.textContent = String(error);
                            deps.refs.llamacppRunStatus.style.color = 'var(--red, #f44336)';
                        }
                        deps.refs.llamacppInstallBtn.disabled = false;
                        deps.refs.llamacppInstallBtn.textContent = '⬇ Installeer llama.cpp';
                    }
                });
            }
        }

        function bindUi() {
            if (uiBound) return;
            uiBound = true;
            bindSettingsAndHelp();
            bindLlamacppUi();
        }

        return {
            bindUi,
            refreshLlamacppRunStatus,
        };
    };
})();