// ==UserScript==
// @name         JKForum Highlight Usernames
// @namespace    http://tampermonkey.net/
// @version      2.3
// @description  Highlight usernames from the ratings in thread replies on JKForum when a specified title is present
// @author       Your Name
// @match        https://www.jkforum.net/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function highlightUsernames() {
        const currentThreadId = getThreadIdFromUrl();
        const storedThreadId = localStorage.getItem('jkforumThreadId');
        const storedNames = JSON.parse(localStorage.getItem('jkforumUsernames') || '[]');

        if (currentThreadId && currentThreadId === storedThreadId) {
            const replyNames = document.querySelectorAll('a.name.xi2 span');
            replyNames.forEach(replyName => {
                if (storedNames.includes(replyName.textContent.trim())) {
                    replyName.style.backgroundColor = '#FFFF00'; // Highlight with yellow
                }
            });
        }
    }

    function extractUsernames() {
        const names = [];
        const ratingWindow = document.querySelector('#fwin_viewratings .floatwrap .list');

        if (ratingWindow) {
            ratingWindow.querySelectorAll('tbody tr > td:nth-child(2) a').forEach(nameCell => {
                const username = nameCell.textContent.trim();
                names.push(username);
                console.log('Captured username:', username);
            });
        } else {
            console.log('Rating window or list not found.');
        }

        const currentThreadId = getThreadIdFromUrl();
        if (names.length > 0 && currentThreadId) {
            localStorage.setItem('jkforumUsernames', JSON.stringify(names));
            localStorage.setItem('jkforumThreadId', currentThreadId);
            highlightUsernames();
        } else {
            console.log('No Usernames Captured or Thread ID is missing.');
        }
    }

    function getThreadIdFromUrl() {
        const urlMatches = window.location.href.match(/thread-(\d+)-\d+-\d+\.html/);
        if (urlMatches) {
            return urlMatches[1];
        }
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('tid');
    }

    window.addEventListener('load', function() {
        const maestroElement = document.querySelector('a.name.xi2[title="maestro"]');
        if (!maestroElement) {
            console.log('Element with title "maestro" not found.');
            return;
        }

        const ratingsLink = document.querySelector('a[title="查看全部評分"]');

        if (ratingsLink && window.location.href.includes('thread-') && window.location.href.includes('-1-1.html')) {
            ratingsLink.addEventListener('click', function(event) {
                event.preventDefault();

                const observer = new MutationObserver((mutations, obs) => {
                    const modal = document.getElementById('fwin_viewratings');
                    if (modal && modal.style.display !== 'none') {
                        obs.disconnect();
                        setTimeout(() => {
                            extractUsernames();

                            const closeButton = modal.querySelector('a.flbc[title="關閉"]');
                            if (closeButton) {
                                console.log('Attempting to close popup window.');
                                closeButton.click();
                            } else {
                                console.log('Close button not found.');
                            }
                        }, 500); // Reduce delay to 0.5 seconds
                    }
                });

                observer.observe(document.body, { childList: true, subtree: true });

                if (typeof window.showWindow === 'function') {
                    window.showWindow('viewratings', ratingsLink.href);
                } else {
                    console.log('showWindow function is not available.');
                }
            });

            ratingsLink.click();
        } else {
            highlightUsernames();
        }
    });
})();

I have added a condition of seeing maestro in the title of a.name.xi2 before proceeding with the script.  However I want the script to run on every page of the thread once the name maestro is found on the first page.  At this moment, names are only highlighted on the first page.  Can you help me fix it?