(function () {
    'use strict';

    var form = document.getElementById('email-settings-form');
    if (!form) {
        return;
    }

    var imapResult = document.getElementById('test-imap-result');
    var sendResult = document.getElementById('test-send-result');
    var sendVerifyResult = document.getElementById('test-send-verify-result');
    var previewSubject = document.getElementById('preview-subject');
    var previewPlain = document.getElementById('preview-plain');
    var previewHtmlFrame = document.getElementById('preview-html-frame');

    function formPayload(extra) {
        var fd = new FormData(form);
        if (extra) {
            Object.keys(extra).forEach(function (k) {
                fd.set(k, extra[k]);
            });
        }
        return fd;
    }

    function selectedVerifyMethod() {
        var checked = form.querySelector('input[name="verify_method"]:checked');
        return checked ? checked.value : 'reverse';
    }

    function syncVerifyPanels() {
        var method = selectedVerifyMethod();
        var showToken = method === 'token' || method === 'both';
        var showReverse = method === 'reverse' || method === 'both';
        form.querySelectorAll('.js-verify-token-panel').forEach(function (el) {
            el.hidden = !showToken;
        });
        form.querySelectorAll('.js-verify-reverse-panel').forEach(function (el) {
            el.hidden = !showReverse;
        });
    }

    function setPreviewTab(tab) {
        var plainOn = tab === 'plain';
        form.querySelectorAll('[data-preview-tab]').forEach(function (btn) {
            btn.classList.toggle('on', btn.getAttribute('data-preview-tab') === tab);
        });
        if (previewPlain) {
            previewPlain.hidden = !plainOn;
        }
        if (previewHtmlFrame) {
            previewHtmlFrame.hidden = plainOn;
        }
    }

    function applyPreview(data) {
        if (previewSubject) {
            previewSubject.textContent = data.subject || '';
        }
        if (previewPlain) {
            previewPlain.textContent = data.plaintext || '';
        }
        if (previewHtmlFrame) {
            var html = data.html || '';
            if (html === '') {
                previewHtmlFrame.removeAttribute('srcdoc');
            } else {
                previewHtmlFrame.srcdoc = html;
            }
        }
    }

    function refreshPreview() {
        return (window.fateAdminApiFetch || fetch)('email_settings_api.php', {
            method: 'POST',
            body: formPayload({ action: 'preview_verify' }),
            credentials: 'same-origin',
        })
            .then(function (r) {
                return r.json();
            })
            .then(function (j) {
                if (j && j.ok) {
                    applyPreview(j);
                }
            })
            .catch(function () {
                // 略過
            });
    }

    function runTest(action, resultEl, okNotice) {
        var testEmail = form.querySelector('#test_email');
        if (!resultEl) {
            return Promise.resolve();
        }
        if (!testEmail || !testEmail.value.trim()) {
            resultEl.style.display = 'block';
            resultEl.textContent = '請填寫測試收件信箱';
            resultEl.className = 'msg bad';
            return Promise.resolve();
        }
        resultEl.style.display = 'block';
        resultEl.textContent = '發信中…';
        resultEl.className = 'msg';
        return (window.fateAdminApiFetch || fetch)('email_settings_api.php', {
            method: 'POST',
            body: formPayload({ action: action }),
            credentials: 'same-origin',
        })
            .then(function (r) {
                return r.json();
            })
            .then(function (j) {
                if (j && j.ok) {
                    var parts = [j.notice || okNotice || '已送出'];
                    if (j.transport) {
                        parts.push('管道：' + j.transport);
                    }
                    if (j.detail) {
                        parts.push(j.detail);
                    }
                    resultEl.textContent = parts.join('　');
                    resultEl.className = 'msg ok';
                } else {
                    resultEl.textContent = (j && j.error) ? j.error : '發信失敗';
                    resultEl.className = 'msg bad';
                }
            })
            .catch(function () {
                resultEl.textContent = '網路或伺服器錯誤';
                resultEl.className = 'msg bad';
            });
    }

    form.querySelectorAll('input[name="verify_method"]').forEach(function (radio) {
        radio.addEventListener('change', syncVerifyPanels);
    });
    syncVerifyPanels();

    form.querySelectorAll('[data-preview-tab]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            setPreviewTab(btn.getAttribute('data-preview-tab') || 'plain');
        });
    });
    setPreviewTab('plain');

    if (previewHtmlFrame && previewHtmlFrame.getAttribute('srcdoc') == null) {
        refreshPreview().then(function () {
            setPreviewTab('plain');
        });
    }

    document.querySelectorAll('[data-preview-verify]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            btn.disabled = true;
            refreshPreview().then(function () {
                btn.disabled = false;
            });
        });
    });

    document.querySelectorAll('[data-test-imap]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!imapResult) {
                return;
            }
            btn.disabled = true;
            imapResult.style.display = 'block';
            imapResult.textContent = '連線測試中…';
            imapResult.className = 'msg';
            (window.fateAdminApiFetch || fetch)('email_settings_api.php', {
                method: 'POST',
                body: formPayload({ action: 'test_imap' }),
                credentials: 'same-origin',
            })
                .then(function (r) {
                    return r.json();
                })
                .then(function (j) {
                    if (j && j.ok) {
                        var parts = [j.notice || '連線成功'];
                        if (j.address) {
                            parts.push('信箱：' + j.address);
                        }
                        parts.push('總信數：' + (j.total || 0) + '，未讀：' + (j.unseen || 0));
                        imapResult.textContent = parts.join('　');
                        imapResult.className = 'msg ok';
                    } else {
                        imapResult.textContent = (j && j.error) ? j.error : 'IMAP 連線失敗';
                        imapResult.className = 'msg bad';
                    }
                })
                .catch(function () {
                    imapResult.textContent = '網路或伺服器錯誤';
                    imapResult.className = 'msg bad';
                })
                .then(function () {
                    btn.disabled = false;
                });
        });
    });

    document.querySelectorAll('[data-test-send]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            btn.disabled = true;
            runTest('test_send', sendResult, '管道測試信已送出').then(function () {
                btn.disabled = false;
            });
        });
    });

    document.querySelectorAll('[data-test-send-verify]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            btn.disabled = true;
            runTest('test_send_verify', sendVerifyResult, '驗證信測試已送出').then(function () {
                btn.disabled = false;
            });
        });
    });
})();
