// ==UserScript==
// @name         ӂ΃J^OID\
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  ӂ΃J^OID\
// @author       Your Name
// @match        https://*.2chan.net/*/futaba.php?mode=cat*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // yzJĂURLi...mode=cat*jumode=jsonvɏ
    const jsonUrl = window.location.href.replace(/mode=cat[^\s&]*/, 'mode=json');

    // URLJSONf[^擾
    fetch(jsonUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('lbg[NG[܂');
            }
            return response.json();
        })
        .then(data => {
            if (!data) return;
            const resData = data.res || data;
            const idMap = {};
            if (typeof resData === 'object') {
                Object.keys(resData).forEach(threadNum => {
                    const item = resData[threadNum];
                    if (item && item.id) {
                        const cleanId = item.id.replace("ID:", "");
                        if (cleanId.trim() !== "") {
                            idMap[threadNum] = cleanId;
                        }
                    }
                });
            }
            embedIdsToCatalog(idMap);
        })
        .catch(error => {
            console.error('JSON̎擾܂͏Ɏs܂:', error);
        });

    // J^OID𖄂ߍފ֐
    function embedIdsToCatalog(idMap) {
        const links = document.querySelectorAll("td a[href^='res/']");
        links.forEach(link => {
            const href = link.getAttribute("href");
            const match = href.match(/res\/(\d+)\.htm/);
            if (match) {
                const threadNum = match[1];
                const idText = idMap[threadNum];
                if (idText) {
                    const td = link.parentElement;
                    if (td) {
                        if (td.innerText.includes(idText)) return;
                        const small = td.querySelector("small");
                        if (small) {
                            const idContainer = document.createElement("span");
                            idContainer.innerHTML = `<br>${idText}`;
                            idContainer.style.fontSize = "small";
                            idContainer.style.color = "#d10000";
                            small.after(idContainer);
                        }
                    }
                }
            }
        });
    }
})();
