/**
 * 註冊頁：帳號、暱稱、Email 輸入時 AJAX 檢查是否與既有會員重複。
 */
(function () {
    'use strict';

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

    var DEBOUNCE_MS = 380;
    var timers = {};
    var state = {
        username: { pending: false, available: null, valid: null },
        display_name: { pending: false, available: null, valid: null },
        email: { pending: false, available: null, valid: null }
    };

    var fields = [
        { name: 'username', input: document.getElementById('username'), hint: document.getElementById('username-check') },
        { name: 'display_name', input: document.getElementById('display_name'), hint: document.getElementById('display_name-check') },
        { name: 'email', input: document.getElementById('email'), hint: document.getElementById('email-check') }
    ];

    function setHint(el, text, kind) {
        if (!el) {
            return;
        }
        el.textContent = text || '';
        el.hidden = text === '';
        el.classList.remove('field-check--ok', 'field-check--bad', 'field-check--wait');
        if (kind) {
            el.classList.add('field-check--' + kind);
        }
    }

    function setInputState(input, kind) {
        if (!input) {
            return;
        }
        input.classList.remove('input--ok', 'input--bad', 'input--wait');
        if (kind) {
            input.classList.add('input--' + kind);
        }
    }

    function updateSubmit() {
        var submit = form.querySelector('button[type="submit"]');
        if (!submit) {
            return;
        }
        var blocked = false;
        fields.forEach(function (f) {
            if (!f.input || f.input.disabled) {
                return;
            }
            var s = state[f.name];
            if (!s) {
                return;
            }
            if (s.pending) {
                blocked = true;
                return;
            }
            if (f.name === 'display_name' && (f.input.value || '').trim() === '') {
                return;
            }
            if (f.name === 'email' && !f.input.required && (f.input.value || '').trim() === '') {
                return;
            }
            if (s.available === false || s.valid === false) {
                blocked = true;
            }
        });
        submit.disabled = blocked;
    }

    function checkField(fieldName, input, hintEl) {
        if (!input) {
            return;
        }
        var value = input.value;
        if (fieldName === 'display_name' && value.trim() === '') {
            state[fieldName] = { pending: false, available: null, valid: null };
            setHint(hintEl, '', null);
            setInputState(input, null);
            updateSubmit();
            return;
        }
        if (fieldName === 'email' && !input.required && value.trim() === '') {
            state[fieldName] = { pending: false, available: null, valid: null };
            setHint(hintEl, '', null);
            setInputState(input, null);
            updateSubmit();
            return;
        }

        state[fieldName] = { pending: true, available: null, valid: null };
        setHint(hintEl, '檢查中…', 'wait');
        setInputState(input, 'wait');
        updateSubmit();

        var url = 'api/register_check.php?field=' + encodeURIComponent(fieldName) + '&value=' + encodeURIComponent(value);
        fetch(url, { method: 'GET', credentials: 'same-origin', headers: { Accept: 'application/json' } })
            .then(function (res) {
                return res.json();
            })
            .then(function (data) {
                if (!data || data.ok !== true) {
                    state[fieldName] = { pending: false, available: false, valid: false };
                    setHint(hintEl, (data && data.message) || '無法檢查，請稍後再試。', 'bad');
                    setInputState(input, 'bad');
                    updateSubmit();
                    return;
                }
                state[fieldName] = {
                    pending: false,
                    available: !!data.available,
                    valid: !!data.valid
                };
                var msg = typeof data.message === 'string' ? data.message : '';
                if (msg === '' && data.available) {
                    msg = fieldName === 'username' ? '此帳號可以使用。' : fieldName === 'email' ? '此 Email 可以使用。' : '此暱稱可以使用。';
                }
                var kind = data.available && data.valid ? 'ok' : 'bad';
                if (!data.valid && fieldName !== 'display_name') {
                    kind = 'bad';
                }
                setHint(hintEl, msg, kind);
                setInputState(input, kind);
                updateSubmit();
            })
            .catch(function () {
                state[fieldName] = { pending: false, available: null, valid: null };
                setHint(hintEl, '連線失敗，請稍後再試。', 'bad');
                setInputState(input, 'bad');
                updateSubmit();
            });
    }

    function schedule(fieldName, input, hintEl) {
        if (timers[fieldName]) {
            clearTimeout(timers[fieldName]);
        }
        timers[fieldName] = setTimeout(function () {
            checkField(fieldName, input, hintEl);
        }, DEBOUNCE_MS);
    }

    fields.forEach(function (f) {
        if (!f.input) {
            return;
        }
        f.input.addEventListener('input', function () {
            schedule(f.name, f.input, f.hint);
        });
        f.input.addEventListener('blur', function () {
            if (timers[f.name]) {
                clearTimeout(timers[f.name]);
            }
            checkField(f.name, f.input, f.hint);
        });
    });

    form.addEventListener('submit', function (e) {
        updateSubmit();
        var submit = form.querySelector('button[type="submit"]');
        if (submit && submit.disabled) {
            e.preventDefault();
        }
    });

    fields.forEach(function (f) {
        if (f.input && (f.input.value || '').trim() !== '') {
            checkField(f.name, f.input, f.hint);
        }
    });
})();
