nautilus_tgs / GetGems - Zargates

// ==UserScript==
// @name         GetGems - Zargates
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  Надстройки для сайта getgems.io, коллекции Unstoppable Tribe from ZarGates
// @match        https://getgems.io/*
// @author       @nautilus_tgs
// @grant        none
// @license      MIT
// @icon         https://img.cryptorank.io/coins/getgems1718019833562.png
// ==/UserScript==

(function() {
    'use strict';

    // Проверка, что мы действительно на getgems (дополнительная защита)
if (!window.location.hostname.includes('getgems.io')) return;

    // 1. СТИЛИ
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `
        .NftProperty__left { --radius_cards_medium: 12px; }

        @keyframes dotPulse {
            0% { transform: scale(0.8); opacity: 0.6; box-shadow: 0 0 2px var(--pulse-color); }
            100% { transform: scale(1.2); opacity: 1; box-shadow: 0 0 8px var(--pulse-color), 0 0 12px var(--pulse-color); }
        }
    `;
    document.head.appendChild(style);

    // 2. ДАННЫЕ (Таблица POWER)
    const powerValues = {
        'Skin Tone': { 'Golden': {power: 50, rarity: 'Legendary'}, 'Lunar': {power: 50, rarity: 'Legendary'}, 'Cosmic': {power: 50, rarity: 'Legendary'}, 'Demonic': {power: 50, rarity: 'Legendary'}, 'Cavern': {power: 20, rarity: 'Epic'}, 'Desert': {power: 20, rarity: 'Epic'}, 'Fairytale': {power: 20, rarity: 'Epic'}, 'Martian': {power: 20, rarity: 'Epic'}, 'Magical': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Forest': {power: 10, rarity: 'Common'}, 'Urban': {power: 10, rarity: 'Common'}, 'Beach': {power: 10, rarity: 'Common'}, 'Mountain': {power: 10, rarity: 'Common'}, 'Meadow': {power: 10, rarity: 'Common'}, 'Swamp': {power: 10, rarity: 'Common'}, 'Tropical': {power: 10, rarity: 'Common'}, 'Taiga': {power: 10, rarity: 'Common'} },
        'Stick': { 'Traffic Police Baton': {power: 500, rarity: 'Mythical'}, 'WС Sign': {power: 50, rarity: 'Legendary'}, 'Stop Sign': {power: 50, rarity: 'Legendary'}, 'Bat': {power: 50, rarity: 'Legendary'}, 'Golf Club': {power: 50, rarity: 'Legendary'}, 'Guitar': {power: 50, rarity: 'Legendary'}, 'Staff': {power: 20, rarity: 'Epic'}, 'Giant Fork': {power: 20, rarity: 'Epic'}, 'Spine': {power: 20, rarity: 'Epic'}, 'Tentacle': {power: 20, rarity: 'Epic'}, 'Rail': {power: 20, rarity: 'Epic'}, 'Spear': {power: 20, rarity: 'Epic'}, 'Crowbar': {power: 20, rarity: 'Epic'}, 'Oar': {power: 20, rarity: 'Epic'}, 'Chair': {power: 10, rarity: 'Common'}, 'Branch': {power: 10, rarity: 'Common'}, 'Mop': {power: 10, rarity: 'Common'}, 'Pipe': {power: 10, rarity: 'Common'} },
        'Earrings': { 'Gold': {power: 50, rarity: 'Legendary'}, 'Spiked Gold': {power: 50, rarity: 'Legendary'}, 'Emerald': {power: 50, rarity: 'Legendary'}, 'Ruby': {power: 50, rarity: 'Legendary'}, 'Diamond': {power: 50, rarity: 'Legendary'}, 'Demonic': {power: 50, rarity: 'Legendary'}, 'Dragon Teeth': {power: 50, rarity: 'Legendary'}, 'No Earrings': {power: 50, rarity: 'Legendary'}, 'Spiked Silver': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Phoenix Feathers': {power: 20, rarity: 'Epic'}, 'Magic Mushrooms': {power: 20, rarity: 'Epic'}, 'Fly Agaric': {power: 10, rarity: 'Common'}, 'Wooden': {power: 10, rarity: 'Common'}, 'Spiked Wooden': {power: 10, rarity: 'Common'}, 'Bones': {power: 10, rarity: 'Common'}, 'Mechanic’s Nuts': {power: 10, rarity: 'Common'}, 'Toadstools': {power: 10, rarity: 'Common'} },
        'Earring': { 'Gold': {power: 50, rarity: 'Legendary'}, 'Spiked Gold': {power: 50, rarity: 'Legendary'}, 'Emerald': {power: 50, rarity: 'Legendary'}, 'Ruby': {power: 50, rarity: 'Legendary'}, 'Diamond': {power: 50, rarity: 'Legendary'}, 'Demonic': {power: 50, rarity: 'Legendary'}, 'Dragon Teeth': {power: 50, rarity: 'Legendary'}, 'No Earrings': {power: 50, rarity: 'Legendary'}, 'Spiked Silver': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Phoenix Feathers': {power: 20, rarity: 'Epic'}, 'Magic Mushrooms': {power: 20, rarity: 'Epic'}, 'Fly Agaric': {power: 10, rarity: 'Common'}, 'Wooden': {power: 10, rarity: 'Common'}, 'Spiked Wooden': {power: 10, rarity: 'Common'}, 'Bones': {power: 10, rarity: 'Common'}, 'Mechanic’s Nuts': {power: 10, rarity: 'Common'}, 'Toadstools': {power: 10, rarity: 'Common'} },
        'Armor': { 'Breastplate Of The Dead': {power: 50, rarity: 'Legendary'}, 'Dragon': {power: 50, rarity: 'Legendary'}, 'Ruby': {power: 50, rarity: 'Legendary'}, 'Cyber': {power: 20, rarity: 'Epic'}, 'Spiked': {power: 20, rarity: 'Epic'}, 'Phoenix': {power: 20, rarity: 'Epic'}, 'Sea': {power: 20, rarity: 'Epic'}, 'Martian': {power: 20, rarity: 'Epic'}, 'Fairytale': {power: 20, rarity: 'Epic'}, 'Magical': {power: 20, rarity: 'Epic'}, 'Leather': {power: 10, rarity: 'Common'}, 'Turtle Shell': {power: 10, rarity: 'Common'}, 'Iron': {power: 10, rarity: 'Common'}, 'Forest': {power: 10, rarity: 'Common'}, 'Wooden': {power: 10, rarity: 'Common'}, 'Paper': {power: 10, rarity: 'Common'}, 'Mountain': {power: 10, rarity: 'Common'}, 'Tropical': {power: 10, rarity: 'Common'} },
        'Heart': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'TON': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'Bitcoin': {power: 50, rarity: 'Legendary'}, 'Tribo Games': {power: 50, rarity: 'Legendary'}, 'Lunar': {power: 50, rarity: 'Legendary'}, 'Ruby': {power: 50, rarity: 'Legendary'}, 'RUB': {power: 20, rarity: 'Epic'}, 'ETH': {power: 20, rarity: 'Epic'}, 'Dollar': {power: 20, rarity: 'Epic'}, 'Pure Silver': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Sea': {power: 20, rarity: 'Epic'}, 'Phoenix': {power: 20, rarity: 'Epic'}, 'Elephant': {power: 10, rarity: 'Common'}, 'Red': {power: 10, rarity: 'Common'}, 'Stone': {power: 10, rarity: 'Common'}, 'Chocolate': {power: 10, rarity: 'Common'} },
        'Ring': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'Golden Bitcoin': {power: 50, rarity: 'Legendary'}, 'TON': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'Tribo Games': {power: 50, rarity: 'Legendary'}, 'Emerald': {power: 50, rarity: 'Legendary'}, 'Lunar': {power: 50, rarity: 'Legendary'}, 'Diamond': {power: 50, rarity: 'Legendary'}, 'ETH': {power: 20, rarity: 'Epic'}, 'RUB': {power: 20, rarity: 'Epic'}, 'Dollar': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Spiked Silver': {power: 20, rarity: 'Epic'}, 'Elephant': {power: 10, rarity: 'Common'}, 'Wooden': {power: 10, rarity: 'Common'}, 'Fake Gold': {power: 10, rarity: 'Common'}, 'Mechanic’s Gear': {power: 10, rarity: 'Common'}, 'Stone': {power: 10, rarity: 'Common'} },
        'Cap': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'Bitcoin': {power: 50, rarity: 'Legendary'}, 'TON': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'Cosmic Black': {power: 50, rarity: 'Legendary'}, 'Demonic Red': {power: 50, rarity: 'Legendary'}, 'Gold': {power: 50, rarity: 'Legendary'}, 'MAGA': {power: 50, rarity: 'Legendary'}, 'ETH': {power: 20, rarity: 'Epic'}, 'RUB': {power: 20, rarity: 'Epic'}, 'Dollar': {power: 20, rarity: 'Epic'}, 'Desert White': {power: 20, rarity: 'Epic'}, 'Phoenix': {power: 20, rarity: 'Epic'}, 'Sea Blue': {power: 20, rarity: 'Epic'}, 'Cavern Brown': {power: 20, rarity: 'Epic'}, 'Elephant': {power: 10, rarity: 'Common'}, 'Mountain Blue': {power: 10, rarity: 'Common'}, 'Forest Green': {power: 10, rarity: 'Common'} },
        'Glasses': { 'Zargates Business': {power: 1000, rarity: 'Mythical+'}, 'Zargates': {power: 500, rarity: 'Mythical'}, 'Bitcoin': {power: 50, rarity: 'Legendary'}, 'Gold': {power: 50, rarity: 'Legendary'}, 'Professor TON': {power: 50, rarity: 'Legendary'}, 'Cosmic': {power: 50, rarity: 'Legendary'}, 'Demonic': {power: 50, rarity: 'Legendary'}, 'Tribo Games': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'Phoenix': {power: 20, rarity: 'Epic'}, 'Fairytale': {power: 20, rarity: 'Epic'}, 'Cyber': {power: 20, rarity: 'Epic'}, 'Sea': {power: 20, rarity: 'Epic'}, 'Desert': {power: 20, rarity: 'Epic'}, 'Martian': {power: 20, rarity: 'Epic'}, 'Steampunk': {power: 10, rarity: 'Common'}, 'Mountain': {power: 10, rarity: 'Common'}, 'Tropical': {power: 10, rarity: 'Common'} },
        'Cup': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'Demonic Wine': {power: 50, rarity: 'Legendary'}, 'Cosmic Cocktail': {power: 50, rarity: 'Legendary'}, 'Lunar Cocktail': {power: 50, rarity: 'Legendary'}, 'Latte': {power: 50, rarity: 'Legendary'}, 'Mystic Smoothie': {power: 20, rarity: 'Epic'}, 'Unicorn Milk': {power: 20, rarity: 'Epic'}, 'Fairytale Champagne': {power: 20, rarity: 'Epic'}, 'Martian Cola': {power: 20, rarity: 'Epic'}, 'Cyber Tonic': {power: 20, rarity: 'Epic'}, 'Forest Beer': {power: 10, rarity: 'Common'}, 'Mushroom Juice': {power: 10, rarity: 'Common'}, 'Taiga Tincture': {power: 10, rarity: 'Common'}, 'Swamp Cocktail': {power: 10, rarity: 'Common'}, 'Protein Shake': {power: 10, rarity: 'Common'}, 'Mechanic’s Cocktail': {power: 10, rarity: 'Common'}, 'Tropical Cocktail': {power: 10, rarity: 'Common'}, 'Chocolate Shake': {power: 10, rarity: 'Common'} },
        'Bracelet': { 'Runed Gold': {power: 50, rarity: 'Legendary'}, 'Spiked Gold': {power: 50, rarity: 'Legendary'}, 'Spiked Cosmic': {power: 50, rarity: 'Legendary'}, 'Spiked Demonic': {power: 50, rarity: 'Legendary'}, 'Spiked Lunar': {power: 50, rarity: 'Legendary'}, 'Gold Braid': {power: 50, rarity: 'Legendary'}, 'Runed Silver': {power: 20, rarity: 'Epic'}, 'Spiked Silver': {power: 20, rarity: 'Epic'}, 'Spiked Stone': {power: 20, rarity: 'Epic'}, 'Spiked Mechanical': {power: 20, rarity: 'Epic'}, 'Fairytale Beads': {power: 20, rarity: 'Epic'}, 'Rope': {power: 10, rarity: 'Common'}, 'Mechanical': {power: 10, rarity: 'Common'}, 'Wooden': {power: 10, rarity: 'Common'}, 'Bone': {power: 10, rarity: 'Common'}, 'Stone': {power: 10, rarity: 'Common'}, 'Paper': {power: 10, rarity: 'Common'}, 'Tropical': {power: 10, rarity: 'Common'} },
        'Pendant Chain': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'Bitcoin': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'TON': {power: 50, rarity: 'Legendary'}, 'Demonic': {power: 50, rarity: 'Legendary'}, 'Tribo Games': {power: 50, rarity: 'Legendary'}, 'Gold': {power: 50, rarity: 'Legendary'}, 'Gold Rope': {power: 50, rarity: 'Legendary'}, 'Lunar': {power: 50, rarity: 'Legendary'}, 'Dollar': {power: 20, rarity: 'Epic'}, 'ETH': {power: 20, rarity: 'Epic'}, 'RUB': {power: 20, rarity: 'Epic'}, 'Silver': {power: 20, rarity: 'Epic'}, 'Phoenix': {power: 20, rarity: 'Epic'}, 'Fairytale': {power: 20, rarity: 'Epic'}, 'Magical': {power: 20, rarity: 'Epic'}, 'Elephant': {power: 10, rarity: 'Common'}, 'Rope': {power: 10, rarity: 'Common'} },
        'Hamster': { 'Zargates': {power: 500, rarity: 'Mythical'}, 'Lunar Blue': {power: 50, rarity: 'Legendary'}, 'Gold': {power: 50, rarity: 'Legendary'}, 'Demonic Red': {power: 50, rarity: 'Legendary'}, 'Cosmic Black': {power: 50, rarity: 'Legendary'}, 'Tribo Games': {power: 50, rarity: 'Legendary'}, 'Bitcoin': {power: 50, rarity: 'Legendary'}, 'Telegram': {power: 50, rarity: 'Legendary'}, 'TON': {power: 50, rarity: 'Legendary'}, 'Cavern Brown': {power: 20, rarity: 'Epic'}, 'Desert White': {power: 20, rarity: 'Epic'}, 'Dollar': {power: 20, rarity: 'Epic'}, 'ETH': {power: 20, rarity: 'Epic'}, 'RUB': {power: 20, rarity: 'Epic'}, 'Elephant': {power: 10, rarity: 'Common'}, 'Forest Green': {power: 10, rarity: 'Common'}, 'Mountain Blue': {power: 10, rarity: 'Common'}, 'Meadow Yellow': {power: 10, rarity: 'Common'} },
        'Sign': { 'Grandma’s Wallpaper': {power: 500, rarity: 'Mythical'}, 'Burnt Paper': {power: 50, rarity: 'Legendary'}, 'Paper': {power: 50, rarity: 'Legendary'}, 'Vintage Wallpaper': {power: 50, rarity: 'Legendary'}, 'Cardboard': {power: 50, rarity: 'Legendary'}, 'Torn Cardboard': {power: 50, rarity: 'Legendary'}, 'Glass': {power: 20, rarity: 'Epic'}, 'Granite': {power: 20, rarity: 'Epic'}, 'Concrete Block': {power: 20, rarity: 'Epic'}, 'Copper Plate': {power: 20, rarity: 'Epic'}, 'Styrofoam': {power: 20, rarity: 'Epic'}, 'New Brick Wall Chunk': {power: 20, rarity: 'Epic'}, 'Aerated Concrete Block': {power: 20, rarity: 'Epic'}, 'Metal': {power: 20, rarity: 'Epic'}, 'Old Brick Wall Chunk': {power: 10, rarity: 'Common'}, 'Stone Slab': {power: 10, rarity: 'Common'}, 'Ripped-Off Plank': {power: 10, rarity: 'Common'}, 'Ripped-Off Fence': {power: 10, rarity: 'Common'} }
    };

    const rarityColors = {
        'Mythical+': '#FF6B35B3',
        'Mythical': '#E6399BB3',
        'Legendary': '#D4AF37B3',
        'Epic': '#6A4C93B3',
        'Common': '#2E8B57B3'
    };

    const flatRarityColors = {
        'Mythical+': '#FF6B35', 'Mythical': '#E6399B', 'Legendary': '#D4AF37', 'Epic': '#6A4C93', 'Common': '#2E8B57'
    };

    const BEAUTIFUL_NUMBERS = {
        ...Object.fromEntries([0,1,2,3,4,5,6,7,8,9].map(n => [n, 1000])),
        ...Object.fromEntries([11,22,33,44,55,66,77,88,99,111,222,333,444,555,666,777,888,999,1111,2222,3333,4444,5555,6666,7777,8888,9999].map(n => [n, 500])),
        11111: 5000
    };

    // Функция нормализации имен для синергии (п.2 и п.3 из ТЗ)
function getNormalizedKeywords(value) {
    if (!value || value === "No Earrings") return [];
    let n = value.trim();

    // Базовые преобразования (не зависит от полного значения)
    const manualOverrides = {
        "Grandma’s Wallpaper": ["paper"],
        "Vintage Wallpaper": ["paper"],
        "Fake Gold": ["fake_gold"]
    };

    // Проверяем полное совпадение только для этих специальных случаев
    if (n in manualOverrides) {
        return manualOverrides[n];
    }

    // Система синонимов для отдельных слов
    const synonymMap = {
        'mechanic': 'mechanical',
        'mechanics': 'mechanical',
        'mechanic’s': 'mechanical',
        'bones': 'bone',
        'golden': 'gold',
        'magic': 'magical',
        'papper': 'paper'
    };


    const blacklist = ['of', 'the', 'and', 'with', 'sign', 'wall', 'chunk', 'earrings', 'no'];

    // Удаляем специальные символы, оставляем буквы, цифры и пробелы
    const normalized = n.toLowerCase()
        .replace(/[^a-zа-я0-9\s]/gi, '');

    // Разбиваем на слова и фильтруем
    const words = normalized.split(/\s+/);
    const filteredWords = [];

    for (let word of words) {
        // Пропускаем короткие слова и слова из черного списка
        if (word.length > 2 && !blacklist.includes(word)) {
            // Преобразуем по карте синонимов
            const normalizedWord = synonymMap[word] || word;
            filteredWords.push(normalizedWord);
        }
    }

    // Убираем дубликаты
    return [...new Set(filteredWords)];
}

    // 3. ЛОГИКА РАСЧЕТА
    function calculatePower() {
        const properties = document.querySelectorAll('.NftPropertyGrid .NftProperty__left');
        if (!properties.length) return null;

        let totalPower = 0;
        const attributes = [];
        const synergyCounts = {};

        // Новые переменные для отдельных плашек
        let numberBonus = null;
        const activeSynergies = [];

        // --- 1. КРАСИВЫЙ НОМЕР (поиск в Title браузера) ---
        const fullText = (document.querySelector('h1')?.textContent || "") + " " + document.title;
        const stickerMatch = fullText.match(/#\s*(\d+)/);

        if (stickerMatch) {
            const numKey = parseInt(stickerMatch[1]);
            if (BEAUTIFUL_NUMBERS[numKey] !== undefined) {
                totalPower += BEAUTIFUL_NUMBERS[numKey];
                numberBonus = { label: '#' + stickerMatch[1], power: BEAUTIFUL_NUMBERS[numKey] };
            }
        }

        // --- 2. БАЗОВЫЕ АТРИБУТЫ ---
        const wordToItems = {}; // Слово -> список индексов предметов

        properties.forEach((property, index) => { // Добавили index
            const titleElement = property.querySelector('.NftProperty__title');
            const subtitleElement = property.querySelector('.NftPropertySubtitle');

            if (titleElement && subtitleElement) {
                const type = titleElement.textContent.trim();
                const rawValue = subtitleElement.textContent.trim();
                const value = rawValue.replace(/[\d,%.]+/g, '').trim();

                if (powerValues[type] && powerValues[type][value]) {
                    const info = powerValues[type][value];
                    totalPower += info.power;
                    attributes.push({ rarity: info.rarity, power: info.power });
                    const color = flatRarityColors[info.rarity] || '#2E8B57';
                    property.style.background = `linear-gradient(90deg, ${color}00 0%, ${color}66 100%)`;
                }

                // Собираем слова и привязываем их к индексу текущего предмета
                if (type !== 'Skin Tone') {
                    const words = getNormalizedKeywords(value);
                    [...new Set(words)].forEach(word => {
                        if (!wordToItems[word]) wordToItems[word] = [];
                        wordToItems[word].push(index);
                    });
                }
            }
        });

        // --- 3. СИНЕРГИЯ ---
        const usedItems = new Set(); // Сюда записываем индексы уже "занятых" предметов

        // Сортируем слова по количеству предметов (сначала самые массовые синергии)
        const sortedWords = Object.entries(wordToItems).sort((a, b) => b[1].length - a[1].length);

        sortedWords.forEach(([word, itemIndices]) => {
            // Берем только те предметы, которые еще не участвовали в других синергиях
            const freshItems = itemIndices.filter(idx => !usedItems.has(idx));
            const count = freshItems.length;

            if (count >= 2) {
                let synergyBonus = (count === 2) ? 100 : 300;
                totalPower += synergyBonus;

                // Помечаем эти предметы как использованные
                freshItems.forEach(idx => usedItems.add(idx));

                const displayWord = word.replace('_', ' ');
                const capitalized = displayWord.charAt(0).toUpperCase() + displayWord.slice(1);
                activeSynergies.push({ name: capitalized, count, bonus: synergyBonus });
            }
        });

        // Не забудьте этот return, который "терялся" в прошлый раз
        return { totalPower, attributes, numberBonus, activeSynergies };
    }

    // 4. ОТОБРАЖЕНИЕ
    function displayResult(result) {
        const headline = document.querySelector('.LibraryHeadline');
        if (!headline || document.getElementById('gg-power-result')) return;

        // --- ЦВЕТ ДЛЯ СИНЕРГИЙ И НОМЕРОВ ---
        const SPECIAL_COLOR = '#8d8d8db3';

        const container = document.createElement('div');
        container.id = 'gg-power-result';
        container.className = 'power-result-container';
        container.style.cssText = `display: flex; align-items: center; color: white; font-family: Arial, sans-serif; margin-bottom: 0px; white-space: nowrap; overflow-x: auto;`;
        container.style.msOverflowStyle = 'none';
        container.style.scrollbarWidth = 'none';

        const rarityCounts = result.attributes.reduce((acc, curr) => {
            acc[curr.rarity] = (acc[curr.rarity] || 0) + 1;
            return acc;
        }, {});

        const rarityOrder = ['Mythical+', 'Mythical', 'Legendary', 'Epic', 'Common'];
        const shortNames = { 'Mythical+': 'Myth+', 'Mythical': 'Myth', 'Legendary': 'Leg', 'Common': 'Com' };

        let badgesHtml = '';

        // 1. Стандартные рарности
        rarityOrder.forEach(r => {
            if (rarityCounts[r]) {
                const label = shortNames[r] || r;
                badgesHtml += `<span style="background: ${rarityColors[r]}; padding: 4px 8px; border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); display: inline-flex; align-items: center; gap: 5px;">${label}: ${rarityCounts[r]}</span>`;
            }
        });

        // 2. Добавляем плашку номера (если есть)
        if (result.numberBonus) {
             badgesHtml += `<span style="background: ${SPECIAL_COLOR}; padding: 4px 8px; border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); display: inline-flex; align-items: center; gap: 5px;">${result.numberBonus.label}: +${result.numberBonus.power}</span>`;
        }

        // 3. Добавляем плашки синергий (если есть)
        result.activeSynergies.forEach(syn => {
             badgesHtml += `<span style="background: ${SPECIAL_COLOR}; padding: 4px 8px; border-radius: 20px; font-size: 12px; font-weight: bold; color: white; text-shadow: 1px 1px 2px rgba(0,0,0,0.5); display: inline-flex; align-items: center; gap: 5px;">Syn: ${syn.name} x${syn.count} (+${syn.bonus})</span>`;
        });

        container.innerHTML = `
            <div style="font-size: 20px; flex-shrink: 0;">⚡</div>
            <div style="flex: 1; display: flex; align-items: center;">
                <div style="font-size: 18px; line-height: 1; color: var(--foreground_primary); flex-shrink: 0;">${result.totalPower}</div>
                <div style="display: flex; gap: 10px; margin-left: 10px; flex-wrap: nowrap;">${badgesHtml}</div>
            </div>
        `;

        headline.parentNode.insertBefore(container, headline.nextSibling);
    }

    // 5. SKIN TONE
    function highlightSkinTone() {
        document.querySelectorAll('.NftProperty__left').forEach(block => {
            const title = block.querySelector('.NftProperty__title');
            if (title?.textContent.trim() === 'Skin Tone' && !block.querySelector('.skin-tone-corner')) {
                const val = block.querySelector('.NftPropertySubtitle')?.textContent.trim() || '';
                let borderColor = '#2E8B57';

                if (['Golden', 'Lunar', 'Cosmic', 'Demonic'].some(s => val.includes(s))) borderColor = '#D4AF37';
                else if (['Cavern', 'Desert', 'Fairytale', 'Martian', 'Magical', 'Silver'].some(s => val.includes(s))) borderColor = '#6A4C93';

                block.style.borderRadius = '12px';
                block.style.position = 'relative';
                block.style.boxShadow = `0 0 10px ${borderColor}40, inset 0 0 5px ${borderColor}40`;

                const dot = document.createElement('div');
                dot.className = 'skin-tone-corner';
                dot.style.cssText = `position: absolute; top: 12px; right: 12px; width: 6px; height: 6px; background: ${borderColor}; border-radius: 50%; z-index: -1; --pulse-color: ${borderColor}; animation: dotPulse 1s infinite alternate; cursor: help;`;
                block.appendChild(dot);
            }
        });
    }

    // 6. МАГИСТРАЛЬНОЕ УПРАВЛЕНИЕ
    function run() {

    // Перемещаем Skin Tone на первое место
    const propertyGrid = document.querySelector('.NftPropertyGrid');
    if (propertyGrid) {
        const blocks = Array.from(propertyGrid.querySelectorAll('.NftProperty__left'));
        const skinToneBlock = blocks.find(block =>
            block.querySelector('.NftProperty__title')?.textContent.trim() === 'Skin Tone'
        );
        if (skinToneBlock && skinToneBlock !== blocks[0]) {
            propertyGrid.insertBefore(skinToneBlock, propertyGrid.firstChild);
        }
    }

    // Расчет мощности
        const result = calculatePower();
        if (result && result.attributes.length > 0) {
            displayResult(result);
            highlightSkinTone();
        }
    }

    // Наблюдатель за появлением элементов
    const observer = new MutationObserver(() => {
        if (document.querySelector('.NftPropertyGrid') && !document.getElementById('gg-power-result')) {
            run();
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });

    // Обработка переходов (SPA)
    let lastUrl = location.href;
    setInterval(() => {
        if (location.href !== lastUrl) {
            lastUrl = location.href;
            const old = document.getElementById('gg-power-result');
            if (old) old.remove();
            // Сбрасываем флаги обработки блоков, если нужно
        }
    }, 1000);


})();