// ==UserScript==
// @name         Soybooru AJAX
// @namespace    https://soybooru.com/
// @version      1
// @description  Nigger
// @match        https://soybooru.com/post/view/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    function bindVoting(section) {
        const forms = section.querySelectorAll('form[action="/numeric_score_vote"]');

        forms.forEach(form => {
            form.addEventListener('submit', function (e) {
                e.preventDefault();

                const formData = new FormData(form);
                const button = form.querySelector('input[type="submit"]');

                button.disabled = true;
                button.style.opacity = "0.6";

                fetch(form.action, {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'
                })
                .then(res => res.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');

                    const newSection = doc.querySelector('#Post_Scoreleft');
                    const currentSection = document.querySelector('#Post_Scoreleft');

                    if (newSection && currentSection) {
                        currentSection.replaceWith(newSection);
                        bindVoting(newSection);
                    }
                })
                .catch(err => {
                    console.error("brap");
                });
            });
        });
    }

    function init() {
        const section = document.querySelector('#Post_Scoreleft');
        if (section) {
            bindVoting(section);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

})();