// ==UserScript==
// @name         Sort M6 first
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       >(You)
// @match        https://boards.4channel.org/mlp/thread/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    const m6_order = ['Applejack', 'Fluttershy', 'Pinkie Pie', 'Rainbow Dash', 'Rarity', 'Twilight Sparkle'];
    // Your code here...
    for (const ele of document.querySelectorAll('.flagSelector')) {
        let childlist = [...ele.children];
        childlist.sort( (a, b) => {
            let aHasM6 = m6_order.includes(a.innerHTML);
            let bHasM6 = m6_order.includes(b.innerHTML);

            if(a.innerHTML == "None") {
                return -1;
            }
            if(b.innerHTML == "None") {
               return 1;
            }
            if(aHasM6 && bHasM6){
                return m6_order.indexOf(a.innerHTML) - m6_order.indexOf(b.innerHTML);
            }

            if(aHasM6 && !bHasM6){
                return -1;
            }

            if(!aHasM6 && bHasM6){
                return 1;
            }

            return a.innerHTML.localeCompare(b.innerHTML);
        });

        ele.replaceChildren(...childlist);
        ele.value = '0';
    }
})();