(function () {
    'use strict';

    function escapeHtml(text) {
        return String(text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function showFlash(block, message, isOk) {
        var flash = block.querySelector('.crowd-reports__flash');
        if (!flash) {
            return;
        }
        flash.hidden = false;
        flash.className = 'crowd-reports__flash member-profile-msg ' + (isOk ? 'member-profile-msg--ok' : 'member-profile-msg--bad');
        flash.textContent = message;
        window.clearTimeout(flash._crowdTimer);
        flash._crowdTimer = window.setTimeout(function () {
            flash.hidden = true;
            flash.textContent = '';
        }, 4200);
    }

    function applyBtnState(btn, label, count, picked) {
        var showAsTag = count > 0 || picked;
        btn.dataset.count = String(count);
        btn.dataset.picked = picked ? '1' : '0';
        btn.disabled = false;
        btn.classList.remove('is-busy');

        if (showAsTag) {
            btn.className = 'crowd-report-btn crowd-report-tag' + (picked ? ' is-active' : '') + ' has-count';
            btn.title = '回報' + label + '（再次點擊可取消）';
            var membersHtml = count > 0
                ? '<span class="crowd-report-tag__members">' + count + '名會員</span>'
                : '';
            btn.innerHTML = '<span class="crowd-report-tag__label">' + escapeHtml(label) + '</span>' + membersHtml;
        } else {
            btn.className = 'crowd-report-btn crowd-report-action';
            btn.title = '回報' + label;
            btn.textContent = '回報' + label;
        }
    }

    function updateBlockHints(block, totalCount) {
        var hasSignal = totalCount > 0;
        block.classList.toggle('crowd-reports--no-signal', !hasSignal);

        var hintSignal = block.querySelector('.crowd-reports__hint--signal');
        var hintAction = block.querySelector('.crowd-reports__hint--action');

        if (hasSignal) {
            if (!hintSignal) {
                hintSignal = document.createElement('p');
                hintSignal.className = 'crowd-reports__hint crowd-reports__hint--signal';
                hintSignal.textContent = '會員回報，不代表本站確認';
                var flash = block.querySelector('.crowd-reports__flash');
                if (flash && flash.nextSibling) {
                    block.insertBefore(hintSignal, flash.nextSibling);
                } else {
                    block.insertBefore(hintSignal, block.firstChild);
                }
            }
            hintSignal.hidden = false;
            if (hintAction) {
                hintAction.hidden = true;
            }
        } else {
            if (hintSignal) {
                hintSignal.hidden = true;
            }
            if (hintAction) {
                hintAction.hidden = false;
            }
        }
    }

    function applyReports(block, reports) {
        var totalCount = 0;
        var buttons = block.querySelectorAll('.crowd-report-btn[data-report-key]');
        buttons.forEach(function (btn) {
            var key = btn.dataset.reportKey || '';
            var label = btn.dataset.label || '';
            var row = reports && reports[key] ? reports[key] : { count: 0, viewer: false };
            var count = parseInt(row.count, 10) || 0;
            var picked = !!row.viewer;
            totalCount += count;
            applyBtnState(btn, label, count, picked);
        });
        updateBlockHints(block, totalCount);
    }

    function resolveApiUrl(block) {
        var api = block.dataset.crowdApi || 'api/crowd_report.php';
        if (/^https?:\/\//i.test(api) || api.charAt(0) === '/') {
            return api;
        }
        var base = window.location.pathname.replace(/[^/]+$/, '');
        return base + api.replace(/^\.\//, '');
    }

    function submitReport(block, btn) {
        if (btn.disabled || btn.classList.contains('is-busy')) {
            return;
        }

        var reportKey = btn.dataset.reportKey || '';
        if (!reportKey) {
            return;
        }

        btn.disabled = true;
        btn.classList.add('is-busy');

        var body = new FormData();
        body.append('ajax', '1');
        body.append('csrf', block.dataset.crowdCsrf || '');
        body.append('entity_type', block.dataset.entityType || '');
        body.append('entity_id', block.dataset.entityId || '');
        body.append('report_key', reportKey);

        fetch(resolveApiUrl(block), {
            method: 'POST',
            credentials: 'same-origin',
            headers: { Accept: 'application/json' },
            body: body,
        })
            .then(function (res) {
                return res.json().then(function (data) {
                    return { res: res, data: data };
                });
            })
            .then(function (payload) {
                var res = payload.res;
                var data = payload.data || {};

                if (res.status === 401 && data.need_login && data.login_url) {
                    window.location.href = data.login_url;
                    return;
                }

                if (!data.ok) {
                    showFlash(block, data.error || '回報失敗。', false);
                    btn.disabled = false;
                    btn.classList.remove('is-busy');
                    return;
                }

                if (data.reports) {
                    applyReports(block, data.reports);
                } else {
                    var label = btn.dataset.label || data.label || '';
                    var count = parseInt(data.member_count, 10) || 0;
                    var picked = !!data.picked;
                    applyBtnState(btn, label, count, picked);
                    updateBlockHints(block, count);
                }

                showFlash(block, data.message || '已更新。', true);
            })
            .catch(function () {
                showFlash(block, '網路錯誤，請稍後再試。', false);
                btn.disabled = false;
                btn.classList.remove('is-busy');
            });
    }

    document.addEventListener('click', function (event) {
        var btn = event.target.closest('.crowd-report-btn');
        if (!btn) {
            return;
        }
        var block = btn.closest('[data-crowd-interactive="1"]');
        if (!block) {
            return;
        }
        event.preventDefault();
        submitReport(block, btn);
    });
})();
