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

    window.AgentFrontendModules.createSystemPanelModule = function createSystemPanelModule(deps) {
        let lastUpdateCheck = null;
        let updateRetryTimer = null;

        function setResetServerNote(text, className = 'settings-note') {
            if (!deps.refs.resetServerNote) return;
            deps.refs.resetServerNote.textContent = text;
            deps.refs.resetServerNote.className = className;
        }

        function setServerButtonsDisabled(disabled) {
            if (deps.refs.startServerBtn) deps.refs.startServerBtn.disabled = disabled;
            if (deps.refs.resetServerBtn) deps.refs.resetServerBtn.disabled = disabled;
            if (deps.refs.stopServerBtn) deps.refs.stopServerBtn.disabled = disabled;
        }

        async function settingsLauncherAction(action) {
            const actionLabel = action === 'start' ? 'Starting' : action === 'restart' ? 'Resetting' : 'Working';
            setResetServerNote(`${actionLabel}…`);
            try {
                const response = await fetch(`${deps.launcherUrl}/api/launcher/${action}`, {
                    method: 'POST',
                    signal: AbortSignal.timeout(30000),
                });
                const result = await response.json();
                if (!result.ok) {
                    throw new Error(result.message || result.error || 'Failed');
                }

                const ready = await deps.helpers.waitForBackendReady(action === 'restart' ? 20000 : 12000);
                if (ready) {
                    setResetServerNote(
                        action === 'start'
                            ? '✅ Server started. Reconnecting…'
                            : '✅ Server restart initiated. Reconnecting…',
                        'settings-note ok'
                    );
                    deps.helpers.connectWebSocket();
                    deps.helpers.pollLauncherStatus();
                    return;
                }

                setResetServerNote(
                    action === 'start'
                        ? '⚠ Launcher started the server, but the backend is not ready yet. Wait a moment or try Reset Server.'
                        : '⚠ Launcher accepted the restart, but the backend is not ready yet. Wait a moment or try Start Server.',
                    'settings-note err'
                );
            } catch (error) {
                try {
                    setResetServerNote('Launcher offline — spawning via backend…');
                    const spawnRes = await fetch(deps.helpers.resolveApiUrl('/api/spawn-launcher'), {
                        method: 'POST',
                        signal: AbortSignal.timeout(15000),
                    });
                    const spawnData = await spawnRes.json();
                    if (spawnData.ok) {
                        const ready = await deps.helpers.waitForBackendReady(15000);
                        if (ready) {
                            setResetServerNote('✅ Launcher + backend live. Reconnecting…', 'settings-note ok');
                            deps.helpers.connectWebSocket();
                            deps.helpers.pollLauncherStatus();
                            return;
                        }
                        setResetServerNote('⚠ Launcher gestart, backend nog niet klaar. Even wachten…', 'settings-note err');
                        return;
                    }
                } catch (_) {}

                if (action === 'restart') {
                    try {
                        const fallback = await deps.authFetchJson('/api/reset', { method: 'POST' });
                        setResetServerNote(
                            fallback.ok ? '✅ Server restart initiated. Reconnecting…' : '❌ ' + (fallback.error || 'Failed'),
                            'settings-note ' + (fallback.ok ? 'ok' : 'err')
                        );
                        return;
                    } catch (_) {}
                }

                setResetServerNote(`❌ ${error.message || error}`, 'settings-note err');
            }
        }

        async function runSystemCheck() {
            if (deps.refs.systemCheckBtn) {
                deps.refs.systemCheckBtn.disabled = true;
                deps.refs.systemCheckBtn.textContent = 'Checking…';
            }
            if (deps.refs.systemCheckResults) deps.refs.systemCheckResults.innerHTML = '';
            try {
                const data = await deps.authFetchJson('/api/health');
                const checks = data.checks || {};
                let html = '<div style="display:grid;gap:4px;margin-top:6px">';
                const labels = {
                    ollama: 'Ollama (Local AI)',
                    outlook: 'Outlook',
                    google: 'Google Workspace',
                    brave_search: 'Brave Search',
                    openai: 'OpenAI',
                    gemini: 'Google Gemini',
                    nvidia: 'NVIDIA',
                    slack: 'Slack',
                    whatsapp: 'WhatsApp',
                    browser: 'Browser (Playwright)',
                };
                for (const [key, check] of Object.entries(checks)) {
                    const label = labels[key] || key;
                    const icon = check.skipped ? '—' : (check.ok ? '✅' : '❌');
                    const detail = check.error || check.detail || '';
                    const color = check.skipped ? 'var(--text-secondary)' : (check.ok ? '#4ade80' : 'var(--danger)');
                    html += `<div style="display:flex;align-items:center;gap:8px;font-size:.8rem;padding:3px 0"><span>${icon}</span><span style="min-width:130px;font-weight:500">${deps.helpers.escapeHtml(label)}</span><span style="color:${color}">${deps.helpers.escapeHtml(detail)}</span></div>`;
                }
                html += '</div>';
                if (deps.refs.systemCheckResults) deps.refs.systemCheckResults.innerHTML = html;
            } catch (error) {
                if (deps.refs.systemCheckResults) {
                    deps.refs.systemCheckResults.innerHTML = `<p class="settings-note err">❌ Failed to run system check: ${deps.helpers.escapeHtml(error.message)}</p>`;
                }
            }
            if (deps.refs.systemCheckBtn) {
                deps.refs.systemCheckBtn.textContent = 'Run System Check';
                deps.refs.systemCheckBtn.disabled = false;
            }
        }

        async function loadVersionInfo() {
            try {
                const data = await deps.authFetchJson('/api/version');
                const version = data.version || 'unknown';
                if (deps.refs.updateCurrentVersionInput) deps.refs.updateCurrentVersionInput.value = `v${version}`;
                if (deps.refs.appVersionEls?.length) {
                    deps.refs.appVersionEls.forEach((el) => { el.textContent = `v${version}`; });
                }
            } catch (_) {
                if (deps.refs.updateCurrentVersionInput) deps.refs.updateCurrentVersionInput.value = 'Unavailable';
            }
        }

        function scheduleUpdateRetry(delayMs) {
            if (updateRetryTimer) clearTimeout(updateRetryTimer);
            updateRetryTimer = setTimeout(() => {
                updateRetryTimer = null;
                checkForUpdate(false);
            }, delayMs || 15000);
        }

        async function checkForUpdate(manual) {
            if (deps.refs.updateCheckBtn) deps.refs.updateCheckBtn.disabled = true;
            if (manual && deps.refs.updateNote) {
                deps.refs.updateNote.textContent = 'Checking for updates…';
                deps.refs.updateNote.className = 'settings-note';
            }
            try {
                const res = await deps.authFetch('/api/update/check');
                const data = await res.json();
                lastUpdateCheck = data;
                if (updateRetryTimer) {
                    clearTimeout(updateRetryTimer);
                    updateRetryTimer = null;
                }
                if (data && data.current_version) {
                    if (deps.refs.updateCurrentVersionInput) deps.refs.updateCurrentVersionInput.value = `v${data.current_version}`;
                    if (deps.refs.appVersionEls?.length) {
                        deps.refs.appVersionEls.forEach((el) => { el.textContent = `v${data.current_version}`; });
                    }
                }
                if (deps.refs.updateLatestVersionInput) {
                    deps.refs.updateLatestVersionInput.value = data.ok ? (`v${data.latest_version || data.current_version || 'unknown'}`) : 'Check failed';
                }
                if (data.ok && data.update_available) {
                    if (deps.refs.updateNote) {
                        deps.refs.updateNote.textContent = `Update available: v${data.latest_version} (current: v${data.current_version}).`;
                        deps.refs.updateNote.className = 'settings-note ok';
                    }
                    if (deps.refs.updateInstallBtn) deps.refs.updateInstallBtn.disabled = false;
                    if (deps.refs.updateDetails) deps.refs.updateDetails.textContent = data.notes || '';
                } else if (data.ok) {
                    if (deps.refs.updateNote) {
                        deps.refs.updateNote.textContent = `No update available. Current version: v${data.current_version}.`;
                        deps.refs.updateNote.className = 'settings-note';
                    }
                    if (deps.refs.updateInstallBtn) deps.refs.updateInstallBtn.disabled = true;
                    if (deps.refs.updateDetails) deps.refs.updateDetails.textContent = data.notes || '';
                } else {
                    if (!manual) scheduleUpdateRetry(15000);
                    if (deps.refs.updateNote && manual) {
                        const friendly = data.user_message || data.error || 'Unknown error';
                        deps.refs.updateNote.textContent = `Update check failed: ${friendly}`;
                        deps.refs.updateNote.className = 'settings-note err';
                    }
                    if (deps.refs.updateInstallBtn) deps.refs.updateInstallBtn.disabled = true;
                    if (deps.refs.updateDetails) {
                        const detail = data.error && data.error !== data.user_message ? data.error : '';
                        const tried = Array.isArray(data.attempted_urls) && data.attempted_urls.length
                            ? `\n\nAttempted URLs:\n${data.attempted_urls.join('\n')}`
                            : '';
                        deps.refs.updateDetails.textContent = `${detail}${tried}`.trim();
                    }
                }
            } catch (error) {
                if (deps.refs.updateLatestVersionInput) deps.refs.updateLatestVersionInput.value = 'Check failed';
                if (!manual) scheduleUpdateRetry(15000);
                if (deps.refs.updateNote && manual) {
                    deps.refs.updateNote.textContent = 'Update check failed: Unable to reach the update server.';
                    deps.refs.updateNote.className = 'settings-note err';
                }
                if (deps.refs.updateInstallBtn) deps.refs.updateInstallBtn.disabled = true;
                if (deps.refs.updateDetails) deps.refs.updateDetails.textContent = error.message || '';
            }
            if (deps.refs.updateCheckBtn) deps.refs.updateCheckBtn.disabled = false;
        }

        async function installUpdate() {
            if (!lastUpdateCheck || !lastUpdateCheck.update_available) {
                if (deps.refs.updateNote) {
                    deps.refs.updateNote.textContent = 'No update available to install.';
                    deps.refs.updateNote.className = 'settings-note';
                }
                return;
            }
            const ok = confirm(`Install update v${lastUpdateCheck.latest_version}?\n\nThis will download and install the update, preserve your settings, and reset the server runtime.`);
            if (!ok) return;

            if (deps.refs.updateInstallBtn) deps.refs.updateInstallBtn.disabled = true;
            if (deps.refs.updateCheckBtn) deps.refs.updateCheckBtn.disabled = true;
            if (deps.refs.updateNote) {
                deps.refs.updateNote.textContent = 'Downloading and installing update…';
                deps.refs.updateNote.className = 'settings-note';
            }
            if (deps.refs.updateDetails) deps.refs.updateDetails.textContent = '';

            try {
                const res = await deps.authFetch('/api/update/install', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ manifest_url: lastUpdateCheck.manifest_url || '' }),
                });
                const data = await res.json();
                if (!res.ok || !data.ok) {
                    throw new Error(data.error || 'Install failed');
                }

                if (deps.refs.updateNote) {
                    deps.refs.updateNote.textContent = `✅ Update installed to v${data.installed_version}. Server reset completed.`;
                    deps.refs.updateNote.className = 'settings-note ok';
                }
                const copied = Number(data.copied_files || 0);
                const skipped = Number(data.skipped_files || 0);
                if (deps.refs.updateDetails) {
                    deps.refs.updateDetails.textContent = `Installed files: ${copied}\nPreserved files: ${skipped}\n${data.notes ? ('\nRelease notes:\n' + data.notes) : ''}`;
                }
                await loadVersionInfo();
                await checkForUpdate(false);
                deps.helpers.loadSettings();
            } catch (error) {
                if (deps.refs.updateNote) {
                    deps.refs.updateNote.textContent = `❌ Update install failed: ${error.message}`;
                    deps.refs.updateNote.className = 'settings-note err';
                }
            }
            if (deps.refs.updateCheckBtn) deps.refs.updateCheckBtn.disabled = false;
        }

        function bindUi() {
            if (deps.refs.startServerBtn) {
                deps.refs.startServerBtn.addEventListener('click', async () => {
                    setServerButtonsDisabled(true);
                    await settingsLauncherAction('start');
                    setServerButtonsDisabled(false);
                });
            }
            if (deps.refs.resetServerBtn) {
                deps.refs.resetServerBtn.addEventListener('click', async () => {
                    setServerButtonsDisabled(true);
                    await settingsLauncherAction('restart');
                    setServerButtonsDisabled(false);
                });
            }
            if (deps.refs.stopServerBtn) {
                deps.refs.stopServerBtn.addEventListener('click', async () => {
                    if (!confirm('Stop the backend server? You can restart it from the offline screen.')) return;
                    deps.refs.stopServerBtn.disabled = true;
                    setResetServerNote('Stopping…');
                    try {
                        const r = await fetch(`${deps.launcherUrl}/api/launcher/stop`, {
                            method: 'POST',
                            signal: AbortSignal.timeout(10000),
                        });
                        const data = await r.json();
                        setResetServerNote(
                            data.ok ? '✅ Server stopped.' : '❌ ' + (data.message || 'Failed'),
                            'settings-note ' + (data.ok ? 'ok' : 'err')
                        );
                    } catch (_) {
                        setResetServerNote('❌ Launcher not reachable. Use Reset Server instead.', 'settings-note err');
                    }
                    deps.refs.stopServerBtn.disabled = false;
                });
            }
            if (deps.refs.systemCheckBtn) {
                deps.refs.systemCheckBtn.addEventListener('click', runSystemCheck);
            }
            if (deps.refs.updateCheckBtn) {
                deps.refs.updateCheckBtn.addEventListener('click', () => {
                    checkForUpdate(true);
                });
            }
            if (deps.refs.updateInstallBtn) {
                deps.refs.updateInstallBtn.addEventListener('click', () => {
                    installUpdate();
                });
            }
        }

        return {
            bindUi,
            loadVersionInfo,
            checkForUpdate,
        };
    };
})();