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

    window.AgentFrontendModules.createSettingsIntegrationsModule = function createSettingsIntegrationsModule(deps) {
        function bindIntegrationHandlers() {
            if (deps.outlookTestBtn) deps.outlookTestBtn.addEventListener('click', async () => {
                deps.outlookTestBtn.disabled = true;
                if (deps.outlookTestResult) {
                    deps.outlookTestResult.textContent = 'Testing…';
                    deps.outlookTestResult.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/outlook/test');
                    if (deps.outlookTestResult) {
                        deps.outlookTestResult.textContent = res.ok ? ('✅ ' + res.message) : ('❌ ' + res.error);
                        deps.outlookTestResult.className = 'settings-note ' + (res.ok ? 'ok' : 'err');
                    }
                } catch (e) {
                    if (deps.outlookTestResult) {
                        deps.outlookTestResult.textContent = '❌ ' + e.message;
                        deps.outlookTestResult.className = 'settings-note err';
                    }
                }
                deps.outlookTestBtn.disabled = false;
            });

            if (deps.googleAuthBtn) deps.googleAuthBtn.addEventListener('click', async () => {
                deps.googleAuthBtn.disabled = true;
                if (deps.googleAuthStatus) {
                    deps.googleAuthStatus.textContent = 'Starting authorization…';
                    deps.googleAuthStatus.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/google/auth');
                    if (res.ok && res.auth_url) {
                        if (deps.googleAuthStatus) {
                            deps.googleAuthStatus.textContent = 'Opening Google consent page…';
                            deps.googleAuthStatus.className = 'settings-note';
                        }
                        window.open(res.auth_url, '_blank', 'width=600,height=700');
                        let tries = 0;
                        const poll = setInterval(async () => {
                            tries++;
                            try {
                                const st = await deps.authFetchJson('/api/integrations/google/status');
                                if (st.authorized) {
                                    clearInterval(poll);
                                    if (deps.googleAuthStatus) {
                                        deps.googleAuthStatus.textContent = '✅ Google authorized successfully!';
                                        deps.googleAuthStatus.className = 'settings-note ok';
                                    }
                                    deps.googleAuthBtn.disabled = false;
                                } else if (tries > 60) {
                                    clearInterval(poll);
                                    if (deps.googleAuthStatus) {
                                        deps.googleAuthStatus.innerHTML = 'Authorization is taking longer than expected. <a href="#" style="color:var(--accent);cursor:pointer" onclick="this.closest(\'.settings-note\').previousElementSibling.querySelector(\'button\').click(); return false;">Click here to try again</a>, or check that you completed the consent in the popup window.';
                                        deps.googleAuthStatus.className = 'settings-note err';
                                    }
                                    deps.googleAuthBtn.disabled = false;
                                }
                            } catch (_) {}
                        }, 2000);
                    } else {
                        if (deps.googleAuthStatus) {
                            deps.googleAuthStatus.textContent = '❌ ' + (res.error || 'Unknown error');
                            deps.googleAuthStatus.className = 'settings-note err';
                        }
                        deps.googleAuthBtn.disabled = false;
                    }
                } catch (e) {
                    if (deps.googleAuthStatus) {
                        deps.googleAuthStatus.textContent = '❌ ' + e.message;
                        deps.googleAuthStatus.className = 'settings-note err';
                    }
                    deps.googleAuthBtn.disabled = false;
                }
            });

            if (deps.googleTestBtn) deps.googleTestBtn.addEventListener('click', async () => {
                deps.googleTestBtn.disabled = true;
                if (deps.googleTestResult) {
                    deps.googleTestResult.textContent = 'Testing…';
                    deps.googleTestResult.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/google/test');
                    if (deps.googleTestResult) {
                        deps.googleTestResult.textContent = res.ok ? ('✅ ' + res.message) : ('❌ ' + res.error);
                        deps.googleTestResult.className = 'settings-note ' + (res.ok ? 'ok' : 'err');
                    }
                } catch (e) {
                    if (deps.googleTestResult) {
                        deps.googleTestResult.textContent = '❌ ' + e.message;
                        deps.googleTestResult.className = 'settings-note err';
                    }
                }
                deps.googleTestBtn.disabled = false;
            });

            if (deps.microsoftAuthBtn) deps.microsoftAuthBtn.addEventListener('click', async () => {
                deps.microsoftAuthBtn.disabled = true;
                if (deps.microsoftAuthStatus) {
                    deps.microsoftAuthStatus.textContent = 'Starting authorization…';
                    deps.microsoftAuthStatus.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/microsoft/auth');
                    if (res.ok && res.auth_url) {
                        if (deps.microsoftAuthStatus) {
                            deps.microsoftAuthStatus.textContent = 'Opening Microsoft consent page…';
                            deps.microsoftAuthStatus.className = 'settings-note';
                        }
                        window.open(res.auth_url, '_blank', 'width=600,height=700');
                        let tries = 0;
                        const poll = setInterval(async () => {
                            tries++;
                            try {
                                const st = await deps.authFetchJson('/api/integrations/microsoft/status');
                                if (st.authorized) {
                                    clearInterval(poll);
                                    if (deps.microsoftAuthStatus) {
                                        deps.microsoftAuthStatus.textContent = '✅ Microsoft authorized successfully!';
                                        deps.microsoftAuthStatus.className = 'settings-note ok';
                                    }
                                    deps.microsoftAuthBtn.disabled = false;
                                } else if (tries > 60) {
                                    clearInterval(poll);
                                    if (deps.microsoftAuthStatus) {
                                        deps.microsoftAuthStatus.innerHTML = 'Authorization is taking longer than expected. <a href="#" style="color:var(--accent);cursor:pointer" onclick="this.closest(\'.settings-note\').previousElementSibling.querySelector(\'button\').click(); return false;">Click here to try again</a>, or check that you completed the consent in the popup window.';
                                        deps.microsoftAuthStatus.className = 'settings-note err';
                                    }
                                    deps.microsoftAuthBtn.disabled = false;
                                }
                            } catch (_) {}
                        }, 2000);
                    } else {
                        if (deps.microsoftAuthStatus) {
                            deps.microsoftAuthStatus.textContent = '❌ ' + (res.error || 'Unknown error');
                            deps.microsoftAuthStatus.className = 'settings-note err';
                        }
                        deps.microsoftAuthBtn.disabled = false;
                    }
                } catch (e) {
                    if (deps.microsoftAuthStatus) {
                        deps.microsoftAuthStatus.textContent = '❌ ' + e.message;
                        deps.microsoftAuthStatus.className = 'settings-note err';
                    }
                    deps.microsoftAuthBtn.disabled = false;
                }
            });

            if (deps.microsoftTestBtn) deps.microsoftTestBtn.addEventListener('click', async () => {
                deps.microsoftTestBtn.disabled = true;
                if (deps.microsoftTestResult) {
                    deps.microsoftTestResult.textContent = 'Testing…';
                    deps.microsoftTestResult.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/microsoft/test');
                    if (deps.microsoftTestResult) {
                        deps.microsoftTestResult.textContent = res.ok ? ('✅ ' + res.message) : ('❌ ' + res.error);
                        deps.microsoftTestResult.className = 'settings-note ' + (res.ok ? 'ok' : 'err');
                    }
                } catch (e) {
                    if (deps.microsoftTestResult) {
                        deps.microsoftTestResult.textContent = '❌ ' + e.message;
                        deps.microsoftTestResult.className = 'settings-note err';
                    }
                }
                deps.microsoftTestBtn.disabled = false;
            });

            if (deps.slackTestBtn) deps.slackTestBtn.addEventListener('click', async () => {
                deps.slackTestBtn.disabled = true;
                if (deps.slackTestResult) {
                    deps.slackTestResult.textContent = 'Testing…';
                    deps.slackTestResult.className = 'settings-note';
                }
                try {
                    const res = await deps.authFetchJson('/api/integrations/slack/test');
                    if (deps.slackTestResult) {
                        deps.slackTestResult.textContent = res.ok ? ('✅ ' + res.message) : ('❌ ' + res.error);
                        deps.slackTestResult.className = 'settings-note ' + (res.ok ? 'ok' : 'err');
                    }
                } catch (e) {
                    if (deps.slackTestResult) {
                        deps.slackTestResult.textContent = '❌ ' + e.message;
                        deps.slackTestResult.className = 'settings-note err';
                    }
                }
                deps.slackTestBtn.disabled = false;
            });
        }

        return {
            bindIntegrationHandlers: bindIntegrationHandlers,
        };
    };
})();