// 赋能按钮 + 弹窗
(function() {
    var btn = document.getElementById('energizeBtn');
    var overlay = document.getElementById('energizeOverlay');
    var closeBtn = document.getElementById('energizeClose');
    var capHint = document.getElementById('energizeCapHint');
    var lightBtn = document.getElementById('energizeLight');
    var heavyBtn = document.getElementById('energizeHeavy');
    if (!btn || !overlay) return;

    var postId = btn.dataset.id;

    function showOverlay() {
        overlay.style.display = 'flex';
    }
    function hideOverlay() {
        overlay.style.display = 'none';
        capHint.style.display = 'none';
        lightBtn.disabled = false;
        heavyBtn.disabled = false;
    }

    btn.addEventListener('click', function() {
        fetch('/api/energy/info')
            .then(function(r) { return r.json(); })
            .then(function(d) {
                if (d.success && d.data && d.data.daily_exp_cap_reached) {
                    capHint.style.display = 'block';
                }
                showOverlay();
            })
            .catch(function() { showOverlay(); });
    });

    closeBtn.addEventListener('click', hideOverlay);
    overlay.addEventListener('click', function(e) {
        if (e.target === overlay) hideOverlay();
    });

    function doEnergize(amount) {
        lightBtn.disabled = true;
        heavyBtn.disabled = true;

        fetch('/api/energy/energize', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-Token': getCSRFToken()
            },
            body: JSON.stringify({ post_id: parseInt(postId), amount: amount })
        })
        .then(function(r) { return r.json(); })
        .then(function(d) {
            if (d.success) {
                alert(d.data.message || '赋能成功！');
                hideOverlay();
            } else {
                alert(d.message || '赋能失败');
                lightBtn.disabled = false;
                heavyBtn.disabled = false;
            }
        })
        .catch(function() {
            alert('请求失败');
            lightBtn.disabled = false;
            heavyBtn.disabled = false;
        });
    }

    lightBtn.addEventListener('click', function() {
        doEnergize(parseInt(lightBtn.dataset.amount));
    });
    heavyBtn.addEventListener('click', function() {
        doEnergize(parseInt(heavyBtn.dataset.amount));
    });
})();
