(function () {

    'use strict';



    var cfgEl = document.getElementById('members-page-config');

    if (!cfgEl) {

        return;

    }



    var cfg;

    try {

        cfg = JSON.parse(cfgEl.textContent || '{}');

    } catch (e) {

        return;

    }



    var csrf = cfg.csrf || '';

    var hasEmail = !!cfg.hasEmail;

    var hasEmailVerified = !!cfg.hasEmailVerified;

    var hasMemberTier = !!cfg.hasMemberTier;

    var hasLastLogin = !!cfg.hasLastLogin;

    var reviewFilter = cfg.reviewFilter || '';

    var verifyFilter = cfg.verifyFilter || '';

    var statusFilter = cfg.statusFilter || '';

    var tierFilter = cfg.tierFilter || '';



    var flashEl = document.getElementById('member-ajax-flash');

    var flashTimer = null;

    var rowSaveTimers = {};



    function esc(s) {

        return String(s)

            .replace(/&/g, '&amp;')

            .replace(/</g, '&lt;')

            .replace(/>/g, '&gt;')

            .replace(/"/g, '&quot;');

    }



    function showFlash(text, ok) {

        if (!flashEl) {

            return;

        }

        flashEl.textContent = text;

        flashEl.className = 'msg ' + (ok ? 'ok' : 'bad');

        flashEl.hidden = false;

        clearTimeout(flashTimer);

        flashTimer = setTimeout(function () {

            flashEl.hidden = true;

        }, 4200);

    }



    function getRow(memberId) {

        return document.querySelector('tr.member-row[data-member-id="' + memberId + '"]');

    }



    function setRowState(tr, state) {

        if (!tr) {

            return;

        }

        tr.classList.remove('member-row--saving', 'member-row--saved', 'member-row--error');

        if (state) {

            tr.classList.add('member-row--' + state);

        }

    }



    function setBusy(btn, busy) {

        if (!btn) {

            return;

        }

        btn.disabled = busy;

        if (busy) {

            btn.setAttribute('aria-busy', 'true');

            if (!btn.dataset.origText) {

                btn.dataset.origText = btn.textContent || '';

            }

            btn.textContent = '處理中…';

        } else {

            btn.removeAttribute('aria-busy');

            if (btn.dataset.origText) {

                btn.textContent = btn.dataset.origText;

            }

        }

    }



    function shouldRemoveFromList(m) {

        if (reviewFilter === 'pending' && !m.pending_review) {

            return true;

        }

        if (verifyFilter === 'email_pending' && !m.needs_email_verify) {

            return true;

        }

        if (statusFilter === 'active' && !m.active) {

            return true;

        }

        if (statusFilter === 'inactive' && m.active) {

            return true;

        }

        if (tierFilter === 'formal' && m.member_tier !== 'formal') {

            return true;

        }

        if (tierFilter === 'register' && m.member_tier !== 'register') {

            return true;

        }

        if (tierFilter === 'blacklist' && m.member_tier !== 'blacklist') {

            return true;

        }

        return false;

    }



    function buildActionButtons(m) {

        var html = '';

        if (m.show_approve) {

            html += '<form method="post" class="member-inline-form member-ajax-form">'

                + '<input type="hidden" name="csrf" value="' + esc(csrf) + '">'

                + '<input type="hidden" name="action" value="approve">'

                + '<input type="hidden" name="member_id" value="' + esc(m.id) + '">'

                + '<input type="hidden" name="edit_url" value="' + esc(m.edit_url || '') + '">'

                + '<button type="submit" class="btn btn--sm btn--approve">通過審核</button></form>';

        }

        if (m.needs_email_verify) {

            html += '<form method="post" class="member-inline-form member-ajax-form">'

                + '<input type="hidden" name="csrf" value="' + esc(csrf) + '">'

                + '<input type="hidden" name="action" value="verify_email">'

                + '<input type="hidden" name="member_id" value="' + esc(m.id) + '">'

                + '<input type="hidden" name="edit_url" value="' + esc(m.edit_url || '') + '">'

                + '<button type="submit" class="btn btn--sm btn--ghost">驗證信箱</button></form>';

        }

        if (m.edit_url) {

            html += '<a class="btn btn--sm btn--ghost" href="' + esc(m.edit_url) + '">詳細</a>';

        }

        if (m.can_toggle_active) {

            html += '<form method="post" class="member-inline-form member-ajax-form">'

                + '<input type="hidden" name="csrf" value="' + esc(csrf) + '">'

                + '<input type="hidden" name="action" value="toggle_active">'

                + '<input type="hidden" name="member_id" value="' + esc(m.id) + '">'

                + '<input type="hidden" name="edit_url" value="' + esc(m.edit_url || '') + '">'

                + '<button type="submit" class="btn btn--sm btn--ghost">' + (m.active ? '停權' : '啟用') + '</button></form>';

        }

        return html;

    }



    function updateQuickFilterCounts(overview) {

        if (!overview) {

            return;

        }

        document.querySelectorAll('.member-quick-filters__chip').forEach(function (chip) {

            var countEl = chip.querySelector('.member-quick-filters__count');

            if (!countEl) {

                return;

            }

            var href = chip.getAttribute('href') || '';

            if (href.indexOf('review=pending') !== -1 && overview.review_pending != null) {

                countEl.textContent = String(overview.review_pending);

            } else if (href.indexOf('verify=email_pending') !== -1 && overview.email_pending != null) {

                countEl.textContent = String(overview.email_pending);

            }

        });

    }



    function syncInlineControls(tr, m) {

        if (!tr) {

            return;

        }



        var dn = tr.querySelector('input[data-field="display_name"]');

        if (dn && document.activeElement !== dn) {

            dn.value = m.display_name || '';

            dn.dataset.lastSaved = dn.value;

        }



        var roleSel = tr.querySelector('select[data-field="role"]');

        if (roleSel && document.activeElement !== roleSel) {

            roleSel.value = m.role || 'member';

            roleSel.dataset.lastSaved = roleSel.value;

        }



        var tierSel = tr.querySelector('select[data-field="member_tier"]');

        if (tierSel && document.activeElement !== tierSel) {

            tierSel.value = m.member_tier || 'register';

            tierSel.dataset.lastSaved = tierSel.value;

        }



        var reviewCell = tr.querySelector('[data-cell-review]');

        if (reviewCell) {

            reviewCell.innerHTML = '<span class="' + esc(m.review_badge_class || 'badge') + '">'

                + esc(m.review_label || '') + '</span>';

        }



        if (hasEmail) {

            var emailCell = tr.querySelector('.col-email');

            if (emailCell) {

                emailCell.textContent = m.email_masked || '—';

                emailCell.setAttribute('title', m.email_raw || '');

            }

            var emailStatusCell = tr.querySelector('[data-cell-email-status]');

            if (emailStatusCell) {

                emailStatusCell.textContent = m.email_status || '—';

            }

        }



        if (hasLastLogin) {

            var timeCell = tr.querySelector('.col-time');

            if (timeCell) {

                timeCell.textContent = m.last_login || '—';

            }

        }

    }



    function updateListRow(m) {

        var tr = getRow(m.id);

        if (!tr) {

            return;

        }



        if (shouldRemoveFromList(m)) {

            tr.classList.add('member-row--removing');

            setTimeout(function () {

                tr.remove();

            }, 280);

            return;

        }



        tr.classList.toggle('member-row--pending', !!m.pending_review);

        if (m.edit_url) {

            tr.setAttribute('data-edit-url', m.edit_url);

        }



        syncInlineControls(tr, m);



        var actions = tr.querySelector('[data-row-actions] .member-action-btns');

        if (actions) {

            actions.innerHTML = buildActionButtons(m);

            bindAjaxForms(actions);

        }

    }



    function updateEditPanel(m) {

        var panel = document.getElementById('member-edit-panel');

        if (!panel || parseInt(panel.getAttribute('data-member-id'), 10) !== m.id) {

            return;

        }



        var badge = panel.querySelector('[data-edit-review-badge]');

        if (badge) {

            badge.className = m.review_badge_class || 'badge';

            badge.textContent = m.review_label || '';

        }



        var approveForm = panel.querySelector('[data-edit-approve-form]');

        if (approveForm) {

            approveForm.hidden = !m.show_approve;

        }



        var dn = panel.querySelector('#display_name');

        if (dn && document.activeElement !== dn) {

            dn.value = m.display_name || '';

        }



        var roleSel = panel.querySelector('#role');

        if (roleSel && document.activeElement !== roleSel) {

            roleSel.value = m.role || 'member';

        }



        var tierSel = panel.querySelector('#member_tier');

        if (tierSel && document.activeElement !== tierSel) {

            tierSel.value = m.member_tier || 'register';

        }



        var statusSel = panel.querySelector('#status');

        if (statusSel && !statusSel.disabled) {

            statusSel.value = m.active ? '1' : '0';

            var offOpt = statusSel.querySelector('option[value="0"]');

            if (offOpt) {

                offOpt.textContent = m.pending_review ? '待審核（未啟用）' : '停權（未啟用）';

            }

        }



        var emailMeta = panel.querySelector('[data-edit-email-meta]');

        if (emailMeta && hasEmailVerified) {

            emailMeta.textContent = m.email_verified ? '已驗證' : '待驗證';

        }



        var verifyForm = panel.querySelector('[data-edit-verify-form]');

        var clearForm = panel.querySelector('[data-edit-clear-form]');

        if (verifyForm) {

            verifyForm.hidden = !!m.email_verified;

        }

        if (clearForm) {

            clearForm.hidden = !m.email_verified;

        }

    }



    function handleApiResponse(j, tr) {

        if (!j.ok) {

            if (tr) {

                setRowState(tr, 'error');

            }

            showFlash(j.error || '操作失敗', false);

            return;

        }

        if (tr) {

            setRowState(tr, 'saved');

            setTimeout(function () {

                if (tr.classList.contains('member-row--saved')) {

                    setRowState(tr, null);

                }

            }, 1400);

        }

        showFlash(j.message || '已儲存', true);

        if (j.redirect) {

            window.location.href = j.redirect;

            return;

        }

        if (j.overview) {

            updateQuickFilterCounts(j.overview);

        }

        if (j.member) {

            updateListRow(j.member);

            updateEditPanel(j.member);

        }

    }



    function postFormData(fd, submitBtn, tr) {

        if (tr) {

            setRowState(tr, 'saving');

        }

        setBusy(submitBtn, true);



        var apiFetch = window.fateAdminApiFetch || fetch;

        return apiFetch('members_api.php', {

            method: 'POST',

            body: fd,

            credentials: 'same-origin',

            headers: { Accept: 'application/json' },

        })

            .then(function (r) {

                return r.json().then(function (j) {

                    return { status: r.status, body: j };

                });

            })

            .then(function (res) {

                var j = res.body || {};

                handleApiResponse(j, tr);

                return j;

            })

            .catch(function () {

                if (tr) {

                    setRowState(tr, 'error');

                }

                showFlash('網路錯誤，請稍後再試。', false);

            })

            .finally(function () {

                setBusy(submitBtn, false);

            });

    }



    function postAction(form, submitBtn) {

        var tr = form.closest('tr.member-row');

        var fd = new FormData(form);

        if (!fd.get('csrf')) {

            fd.set('csrf', csrf);

        }

        return postFormData(fd, submitBtn, tr);

    }



    function quickSaveField(el) {

        var field = el.getAttribute('data-field') || el.name;

        var memberId = parseInt(el.getAttribute('data-member-id'), 10);

        if (!field || memberId <= 0) {

            return;

        }



        var value = el.value;

        var lastSaved = el.dataset.lastSaved;

        if (lastSaved !== undefined && lastSaved === value) {

            return;

        }



        var tr = getRow(memberId);

        var fd = new FormData();

        fd.set('csrf', csrf);

        fd.set('action', 'quick_save');

        fd.set('member_id', String(memberId));

        fd.set(field, value);

        if (tr) {

            var editUrl = tr.getAttribute('data-edit-url') || '';

            if (editUrl) {

                fd.set('edit_url', editUrl);

            }

        }



        var timerKey = memberId + ':' + field;

        clearTimeout(rowSaveTimers[timerKey]);



        return postFormData(fd, null, tr).then(function (j) {

            if (j && j.ok) {

                el.dataset.lastSaved = value;

            } else if (lastSaved !== undefined) {

                el.value = lastSaved;

            }

        });

    }



    function scheduleQuickSave(el, delay) {

        var field = el.getAttribute('data-field') || el.name;

        var memberId = parseInt(el.getAttribute('data-member-id'), 10);

        if (!field || memberId <= 0) {

            return;

        }

        var timerKey = memberId + ':' + field;

        clearTimeout(rowSaveTimers[timerKey]);

        rowSaveTimers[timerKey] = setTimeout(function () {

            quickSaveField(el);

        }, delay || 0);

    }



    function bindAjaxForms(root) {

        (root || document).querySelectorAll('form.member-ajax-form').forEach(function (form) {

            if (form.dataset.ajaxBound === '1') {

                return;

            }

            form.dataset.ajaxBound = '1';

            form.addEventListener('submit', function (ev) {

                ev.preventDefault();

                var btn = form.querySelector('button[type="submit"]');

                postAction(form, btn);

            });

        });

    }



    function bindInlineEditors(root) {

        (root || document).querySelectorAll('.member-inline-input').forEach(function (input) {

            if (input.dataset.inlineBound === '1') {

                return;

            }

            input.dataset.inlineBound = '1';

            input.dataset.lastSaved = input.value;

            input.addEventListener('blur', function () {

                scheduleQuickSave(input, 0);

            });

            input.addEventListener('keydown', function (ev) {

                if (ev.key === 'Enter') {

                    ev.preventDefault();

                    input.blur();

                }

            });

        });



        (root || document).querySelectorAll('.member-inline-select').forEach(function (select) {

            if (select.dataset.inlineBound === '1') {

                return;

            }

            select.dataset.inlineBound = '1';

            select.dataset.lastSaved = select.value;

            select.addEventListener('change', function () {

                scheduleQuickSave(select, 0);

            });

        });

    }



    bindAjaxForms(document);

    bindInlineEditors(document);

})();


