// ==UserScript==
// @name         name-color: cohost edition!
// @namespace    https://terezi.pyrope.net
// @version      0.2
// @description  colors names based on `name-color:` statements in profiles. there are no other editions
// @author       mehbark
// @match        https://*.cohost.org/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=cohost.org
// @grant        none
// ==/UserScript==

const mentionee = elem => elem.href.split("/").at(-1);

function doit() {
    "use strict";

    // not just literal mentions btw
    const mentions = [
        ...document.querySelectorAll("a[href^='https://cohost.org/']"),
    ].filter(
        a =>
            !(
                a.href.includes("/rc/") ||
                // sorry, @post
                a.href.includes("/post/") ||
                // sorry, @tagged
                a.href.includes("/tagged/") ||
                // sorry, @ask
                a.href.endsWith("/ask") ||
                a.href.endsWith("/")
            )
    );

    const names = [...new Set(mentions.map(mentionee))];
    names.sort();

    const requester = document
        .querySelector("header")
        .querySelector("span")
        .innerText.slice(1);

    const url = new URL("https://pyrope.net/name-color/style.css");
    url.searchParams.append("requester", requester);

    for (const name of names) {
        url.searchParams.append("name", name);
    }

    let style = document.head.querySelector(".name-color-stylesheet");
    if (style) {
        const style2 = document.createElement("link");
        style2.rel = "stylesheet";
        style2.href = url.toString();
        style2.onload = () => {
            document.head.querySelectorAll(".name-color-stylesheet").forEach(s => s.remove());
            style2.className = "name-color-stylesheet";
        };
        document.head.appendChild(style2);
    } else {
        style = document.createElement("link");
        style.className = "name-color-stylesheet";
        style.rel = "stylesheet";
        style.href = url.toString();
        document.head.appendChild(style);
    }
}

new MutationObserver(doit).observe(document.body, {
    subtree: true,
    childList: true,
});

doit();
