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

    window.AgentFrontendModules.createWhatsAppModule = function createWhatsAppModule(deps) {
        let qrPollTimer = null;

        function updateUi(info) {
            const status = info.status || 'disconnected';
            const colors = { connected: '#22c55e', qr_ready: '#f59e0b', connecting: '#3b82f6', reconnecting: '#f59e0b', disconnected: '#888' };
            const labels = { connected: 'Connected', qr_ready: 'Scan QR code...', connecting: 'Connecting...', reconnecting: 'Reconnecting...', disconnected: 'Not connected' };

            if (deps.refs.statusDot) deps.refs.statusDot.style.background = colors[status] || '#888';
            if (deps.refs.statusText) deps.refs.statusText.textContent = labels[status] || status;
            if (deps.refs.setupProgress) deps.refs.setupProgress.style.display = status === 'connecting' ? 'block' : 'none';
            if (deps.refs.setupStep) deps.refs.setupStep.textContent = labels[status] || '';
            if (deps.refs.qrContainer) deps.refs.qrContainer.style.display = (status === 'qr_ready' && info.qrDataUrl) ? 'block' : 'none';
            if (deps.refs.qrImage && info.qrDataUrl) deps.refs.qrImage.src = info.qrDataUrl;
            if (deps.refs.connectedInfo) deps.refs.connectedInfo.style.display = status === 'connected' ? 'block' : 'none';
            if (deps.refs.phoneDisplay && info.phoneNumber) deps.refs.phoneDisplay.textContent = '+' + info.phoneNumber;
            if (deps.refs.connectedSince && info.connectedAt) deps.refs.connectedSince.textContent = 'Connected since ' + new Date(info.connectedAt).toLocaleString();

            if (deps.refs.errorBox) {
                if (info.lastError) {
                    deps.refs.errorBox.style.display = 'block';
                    deps.refs.errorBox.textContent = info.lastError;
                } else {
                    deps.refs.errorBox.style.display = 'none';
                }
            }

            if (deps.refs.startButton) deps.refs.startButton.style.display = ['connected', 'qr_ready', 'connecting'].includes(status) ? 'none' : '';
            if (deps.refs.relinkButton) deps.refs.relinkButton.style.display = ['connected', 'qr_ready'].includes(status) ? '' : 'none';
            if (deps.refs.disconnectButton) deps.refs.disconnectButton.style.display = ['connected', 'qr_ready', 'connecting', 'reconnecting'].includes(status) ? '' : 'none';
            if (deps.refs.testPanel) deps.refs.testPanel.style.display = status === 'connected' ? 'block' : 'none';
            if (deps.refs.testSendButton) deps.refs.testSendButton.disabled = status !== 'connected';
            if (deps.refs.testResult && status !== 'connected') {
                deps.refs.testResult.style.display = 'none';
                deps.refs.testResult.textContent = '';
            }

            if (status === 'qr_ready' || status === 'connecting' || status === 'reconnecting') {
                startQrPoll();
            } else {
                stopQrPoll();
            }
        }

        async function refreshStatus() {
            try {
                const response = await deps.authFetchJson('/api/integrations/whatsapp/status');
                if (response.ok !== false) updateUi(response);
            } catch (_) {}
        }

        function startQrPoll() {
            if (qrPollTimer) return;
            qrPollTimer = setInterval(async () => {
                try {
                    const response = await deps.authFetchJson('/api/integrations/whatsapp/status');
                    if (response.ok !== false) updateUi(response);
                } catch (_) {}
            }, 3000);
        }

        function stopQrPoll() {
            if (qrPollTimer) {
                clearInterval(qrPollTimer);
                qrPollTimer = null;
            }
        }

        function setError(message) {
            if (!deps.refs.errorBox) return;
            deps.refs.errorBox.style.display = 'block';
            deps.refs.errorBox.textContent = message;
        }

        function bindUi() {
            if (deps.refs.startButton) deps.refs.startButton.addEventListener('click', async () => {
                deps.refs.startButton.disabled = true;
                updateUi({ status: 'connecting' });
                try {
                    const response = await deps.authFetchJson('/api/integrations/whatsapp/start', { method: 'POST' });
                    updateUi(response);
                } catch (error) {
                    setError(error.message);
                    updateUi({ status: 'disconnected' });
                }
                deps.refs.startButton.disabled = false;
            });

            if (deps.refs.relinkButton) deps.refs.relinkButton.addEventListener('click', async () => {
                deps.refs.relinkButton.disabled = true;
                try {
                    const response = await deps.authFetchJson('/api/integrations/whatsapp/relink', { method: 'POST' });
                    updateUi(response);
                } catch (error) {
                    setError(error.message);
                }
                deps.refs.relinkButton.disabled = false;
            });

            if (deps.refs.disconnectButton) deps.refs.disconnectButton.addEventListener('click', async () => {
                deps.refs.disconnectButton.disabled = true;
                try {
                    await deps.authFetch('/api/integrations/whatsapp/disconnect', { method: 'DELETE' });
                    updateUi({ status: 'disconnected' });
                } catch (error) {
                    setError(error.message);
                }
                deps.refs.disconnectButton.disabled = false;
            });

            if (deps.refs.testSendButton) deps.refs.testSendButton.addEventListener('click', async () => {
                deps.refs.testSendButton.disabled = true;
                if (deps.refs.testResult) {
                    deps.refs.testResult.style.display = 'block';
                    deps.refs.testResult.textContent = 'Sending...';
                }
                try {
                    const response = await deps.authFetchJson('/api/integrations/whatsapp/send', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({}),
                    });
                    if (deps.refs.testResult) {
                        deps.refs.testResult.textContent = response.ok
                            ? '\u2705 Test message sent to linked WhatsApp.'
                            : ('\u274c ' + (response.error || 'Failed'));
                    }
                } catch (error) {
                    if (deps.refs.testResult) deps.refs.testResult.textContent = '\u274c ' + error.message;
                }
                deps.refs.testSendButton.disabled = false;
            });
        }

        function dispose() {
            stopQrPoll();
        }

        return {
            refreshStatus,
            bindUi,
            dispose,
        };
    };
})();