nascent / Metacritic score in IMDB reference view

// ==UserScript==
// @name         Metacritic score in IMDB reference view
// @namespace    https://openuserjs.org/users/nascent
// @version      1.0
// @description  Add Metacritic score in IMDB reference view
// @author       nascent
// @match        https://imdb.com/title/tt*/reference*
// @match        https://*.imdb.com/title/tt*/reference*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=imdb.com
// @grant        GM_xmlhttpRequest
// @connect      www.imdb.com
// @updateURL    https://openuserjs.org/meta/nascent/Metacritic_score_in_IMDB_reference_view.meta.js
// @license      GPL-3.0-or-later
// ==/UserScript==

(function () {
    'use strict';

    const titleMatch = location.href.match(/title\/(tt\d+)/);
    if (!titleMatch) return;

    const titleId = titleMatch[1];

    GM_xmlhttpRequest({
        method: "GET",
        url: `https://www.imdb.com/title/${titleId}/`,
        anonymous: true,
        headers: {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5'
        },
        onload: function (response) {
            const html = response.responseText;

            // Parse response into a DOM we can query
            const doc = new DOMParser().parseFromString(html, 'text/html');

            // Extract score from the metacritic-score-box element
            // HTML: <span class="metacritic-score-box" style="background-color:#54A72A">67</span>
            const scoreBox = doc.querySelector('.metacritic-score-box');
            if (!scoreBox) {
                console.log('[MetacriticScore] No Metacritic score found for this title.');
                return;
            }

            const score = parseInt(scoreBox.textContent.trim(), 10);
            if (isNaN(score) || score < 0 || score > 100) return;

            // Get the background color IMDB already computed
            const bgColor = scoreBox.style.backgroundColor || getScoreColor(score);

            // Get the criticreviews URL from the parent link
            const parentLink = scoreBox.closest('a');
            const url = parentLink ? parentLink.getAttribute('href') : `/title/${titleId}/criticreviews`;

            insertScore(score, bgColor, url);
        },
        onerror: function (err) {
            console.error('[MetacriticScore] Failed to fetch title page:', err);
        }
    });

    function getScoreColor(score) {
        if (score >= 61) return '#54A72A';
        if (score >= 40) return '#FFCC33';
        return '#FF0000';
    }

    function insertScore(score, bgColor, url) {
        // Build the score element matching IMDB's own style
        const li = document.createElement('li');
        li.setAttribute('role', 'presentation');
        li.className = 'ipc-inline-list__item';

        const link = document.createElement('a');
        link.href = url;
        link.style.cssText = 'display:inline-flex; align-items:center; gap:6px; text-decoration:none; color:inherit;';

        const badge = document.createElement('span');
        badge.className = 'metacritic-score-box';
        badge.style.cssText = `
            background-color:${bgColor}; color:#fff;
            font-weight:bold; font-size:14px;
            padding:2px 7px; border-radius:4px;
            display:inline-block; text-align:center;
        `;
        badge.textContent = score;

        const label = document.createElement('span');
        label.className = 'metacritic-score-label';
        label.textContent = 'Metascore';
        label.style.cssText = 'font-size:13px;';

        link.appendChild(badge);
        link.appendChild(label);
        li.appendChild(link);

        // Try insertion strategies in order
        if (insertNearRating(li)) return;
        if (insertNearTitle(li)) return;

        console.warn('[MetacriticScore] Could not find insertion point on reference page.');
    }

    function insertNearRating(el) {
        // Look for the ratings area on the reference page
        const selectors = [
            '[data-testid="hero-rating-bar"]',
            '.ipc-rating-star--imdb',
            'ul.ipc-inline-list',               // inline list containing ratings
            '[class*="RatingBar"]',
        ];

        for (const sel of selectors) {
            const target = document.querySelector(sel);
            if (target) {
                // Find the containing inline list or rating bar
                const list = target.closest('ul.ipc-inline-list')
                    || target.closest('[data-testid="hero-rating-bar"]');
                if (list) {
                    list.appendChild(el);
                    return true;
                }
                // Otherwise just append next to the target's parent
                target.parentElement.appendChild(el);
                return true;
            }
        }
        return false;
    }

    function insertNearTitle(el) {
        const titleEl = document.querySelector(
            '[data-testid="hero__pageTitle"], h1, h3[itemprop="name"]'
        );
        if (titleEl) {
            titleEl.parentElement.insertBefore(el, titleEl.nextSibling);
            return true;
        }
        return false;
    }
})();