Ahab / Trash TC Chain Report Ranks

// ==UserScript==
// @name         Trash TC Chain Report Ranks
// @namespace    torn.com
// @version      1.6
// @description  Highlights user, scrolls to user on sort, removes bonus hits from average respect, sort by attack on load and adds rank numbers
// @author       ahab
// @match       *.torn.com/war.php*
// @license     MIT
// @updateURL   https://openuserjs.org/meta/Ahab/Trash_TC_Chain_Report_Ranks.meta.js
// @require     https://greasyfork.org/scripts/5392-waitforkeyelements/code/WaitForKeyElements.js?version=115012
// @require     https://code.jquery.com/jquery-3.6.0.min.js
// @require     https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js
// @run-at      document-start
// @grant       unsafeWindow
// ==/UserScript==

var uid = Cookies.get('uid');
var a = {}
const original_fetch = fetch

unsafeWindow.fetch = async (input, init) => {
    const response = await original_fetch(input, init)
    const consumed_res = await response.json()
    if(consumed_res['chainID'] == window.location.href.split('=')[2]){
        $.each(consumed_res['bonuses'], function(i){
            var id = consumed_res['bonuses'][i]['attacker']['userID']
            var bonus = consumed_res['bonuses'][i]['respect']
            if(a[id]){
                a[id]['bonus'] = bonus + a[id]['bonus']
                a[id]['hits'] = a[id]['hits'] + 1
            }else{
                a[id] = {'bonus':bonus, 'hits':1}
            }
        })
        $.each(consumed_res['members'], function(i){
            if(a[this['userID']]){
                this['avg'] = (this['respect']-a[this['userID']]['bonus'])/(this['attacks']-a[this['userID']]['hits']).toFixed(2)
            }
        })
        consumed_res['members'].sort(function (a, b) {
            return b.attacks - a.attacks;
        });
    }
    const b = new Blob([JSON.stringify(consumed_res, null, 2)], {type : 'application/json'})
    return new Response(b)
}

function highlight(){
    var line = $("div[class*='member icons'] a[href*='/profiles.php?XID="+uid+"']").closest('li').index()
    $("li[class*='members-stats-row']")[line].style.backgroundColor = "#ceebce"
    $("div[class*='member icons'] a[href*='/profiles.php?XID="+uid+"']").parent().parent()[0].style.backgroundColor = "#ceebce"
    rank()
}

$(document).on('click', '.report-stats-titles', function(event) {
    rank()
    $("div[class*='member icons'] a[href*='/profiles.php?XID="+uid+"']").get(0).scrollIntoView({ behavior: 'smooth', block: 'center' });
})

function rank(){
    var pos = 1
    setTimeout(function(){
        $("ul[class*='members-names-rows'] a[class*='faction']").each(function(){
            this.children[0].outerHTML = '<span>'+pos+'</span>'
            pos += 1
        })
    },10);
}

waitForKeyElements(".report-members-stats-content", highlight);