Bobber / OGame Splitscrap

// ==UserScript==
// @name         OGame Splitscrap
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Unified Split tab with switch, auto-filtered dropdown, full reset, and scrap value calculator
// @license	 MIT
// @author       R3aper
// @match        https://*.gameforge.com/game/index.php?page=ingame&component=fleetdispatch*
// @grant        none
// ==/UserScript==

        (function () {
            'use strict';

            const SHIP_IDS = {
                transporterSmall: '202',
                transporterLarge: '203',
                explorer: '219',
                reaper: '218',
                destroyer: '213',
                bomber: '211',
                interceptor: '215',
                fighterLight: '204',
                fighterHeavy: '205',
                cruiser: '206',
                battleship: '207',
                colonyShip: '208',
                recycler: '209',
                espionageProbe: '210',
                deathstar: '214'
            };

            const SHIP_SCRAP_VALUES = {
                '202': { metal: 2000, crystal: 2000, deuterium: 0 },     // Kleiner Transporter
                '203': { metal: 6000, crystal: 6000, deuterium: 0 },     // Großer Transporter
                '204': { metal: 3000, crystal: 1000, deuterium: 0 },     // Leichter Jäger
                '205': { metal: 6000, crystal: 4000, deuterium: 0 },     // Schwerer Jäger
                '206': { metal: 20000, crystal: 7000, deuterium: 2000 }, // Kreuzer
                '207': { metal: 45000, crystal: 15000, deuterium: 0 },   // Schlachtschiff
                '208': { metal: 10000, crystal: 20000, deuterium: 10000 }, // Kolonieschiff
                '209': { metal: 10000, crystal: 6000, deuterium: 2000 }, // Recycler
                '210': { metal: 0, crystal: 1000, deuterium: 0 },        // Spionagesonde
                '211': { metal: 50000, crystal: 25000, deuterium: 15000 }, // Bomber
                '212': { metal: 0, crystal: 2000, deuterium: 500 },      // Solarsatellit
                '213': { metal: 60000, crystal: 50000, deuterium: 15000 }, // Zerstörer
                '214': { metal: 5000000, crystal: 4000000, deuterium: 1000000 }, // Todesstern
                '215': { metal: 30000, crystal: 40000, deuterium: 15000 }, // Schlachtkreuzer
                '216': { metal: 2000, crystal: 2000, deuterium: 1000 },  // Crawler
                '218': { metal: 85000, crystal: 55000, deuterium: 20000 }, // Reaper
                '219': { metal: 8000, crystal: 15000, deuterium: 8000 }  // Pathfinder
            };

            const LOCAL_STORAGE_SCRAP_PERCENT = 'scrapPercentage';

            const LOCAL_STORAGE_KEY_SHIP = 'splitSelectedCombatShip';
            const LOCAL_STORAGE_KEY_MODE = 'splitMode';

            function createSplitTab() {
                const panel = document.querySelector('#ago_panel');
                const toolsTab = document.querySelector('#ago_panel_Tools');
                if (!panel || !toolsTab) return;

                const tabId = 'Split';
                const newTab = document.createElement('div');
                newTab.id = `ago_panel_${tabId}`;
                newTab.className = 'ago_panel_tab';
                newTab.setAttribute('ago-data', `{"update":{"tab":"${tabId}","status":"toggle"}}`);
                newTab.innerHTML = `Split<span class="ago_panel_tab_info"></span>`;
                toolsTab.parentNode.insertBefore(newTab, toolsTab.nextSibling);

                const tabContent = document.createElement('div');
                tabContent.id = `ago_panel_${tabId}_Content`;
                tabContent.className = 'ago_panel_tab_content';
                tabContent.style.display = 'none';

                tabContent.innerHTML = `
                    <style>
                        .switch-wrapper {
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                            margin: 10px 0;
                            font-weight: bold;
                            color: #ccc;
                        }
                        .switch {
                            position: relative;
                            display: inline-block;
                            width: 50px;
                            height: 24px;
                        }
                        .switch input {
                            opacity: 0;
                            width: 0;
                            height: 0;
                        }
                        .slider {
                            position: absolute;
                            cursor: pointer;
                            top: 0; left: 0;
                            right: 0; bottom: 0;
                            background-color: #666;
                            transition: .4s;
                            border-radius: 24px;
                        }
                        .slider:before {
                            position: absolute;
                            content: "";
                            height: 18px;
                            width: 18px;
                            left: 3px;
                            bottom: 3px;
                            background-color: white;
                            transition: .4s;
                            border-radius: 50%;
                        }
                        input:checked + .slider {
                            background-color: #2196F3;
                        }
                        input:checked + .slider:before {
                            transform: translateX(26px);
                        }
                        .tooltip-text {
                            position: relative;
                            cursor: help;
                        }
                        .tooltip-text:hover::after {
                            content: attr(data-tooltip);
                            position: absolute;
                            top: 50%;
                            left: calc(100% + 15px);
                            transform: translateY(-50%);
                            background-color: #1a1a2e;
                            color: #fff;
                            padding: 10px 15px;
                            border-radius: 6px;
                            border: 1px solid #444;
                            box-shadow: 0 5px 15px rgba(0,0,0,0.5);
                            white-space: normal;
                            width: 250px;
                            font-size: 12px;
                            font-weight: normal;
                            z-index: 1000;
                            line-height: 1.4;
                        }
                        .tooltip-text:hover::before {
                            content: "";
                            position: absolute;
                            top: 50%;
                            left: calc(100% + 9px);
                            transform: translateY(-50%);
                            border: 6px solid transparent;
                            border-right-color: #1a1a2e;
                            z-index: 1000;
                        }
                    </style>

                    <div style="background: #111017; padding: 10px;">
                        <div class="switch-wrapper">
                            <span>Standard Split</span>
                            <label class="switch">
                                <input type="checkbox" id="${tabId}_modeSwitch">
                                <span class="slider"></span>
                            </label>
                            <span class="tooltip-text" data-tooltip="This mode should only be used for universe start. It sets 1 Pathfinder and optionally 1 combat ship, while transporters are split evenly.">Expedition Split</span>
                        </div>

                        <div style="margin-bottom: 10px;">
                            <input type="number" id="${tabId}_splitNumber" min="1" step="1"
                                placeholder="Split count"
                                style="display: block; width: 100%; margin-top: 10px; box-sizing: border-box; text-align: center; font-weight: bold; height: 30px;">
                            <input id="${tabId}_splitButton" type="button" value="Execute Split"
                                style="display: block; width: 100%; margin-top: 10px; box-sizing: border-box; cursor: pointer; background: #3b4858; color: #c8c8c8; height: 30px; border: none; border-radius: 3px;">
                        </div>

                        <div id="${tabId}_combatShipSection" style="display:none; margin-top:10px;">
                            <div>Select 1 combat ship (optional):</div>
                            <select id="${tabId}_shipSelect" style="width: 100%; margin-top: 5px; height: 24px; font-weight: bold;">
                                <option value="">-- No combat ship --</option>
                            </select>
                        </div>

                    </div>
                `;
                newTab.insertAdjacentElement('afterend', tabContent);

                const switchInput = document.getElementById(`${tabId}_modeSwitch`);
                const shipSelect = document.getElementById(`${tabId}_shipSelect`);
                const shipSection = document.getElementById(`${tabId}_combatShipSection`);

                newTab.addEventListener('click', () => {
                    const isActive = tabContent.style.display === 'block';
                    document.querySelectorAll('.ago_panel_tab_content').forEach(c => c.style.display = 'none');
                    tabContent.style.display = isActive ? 'none' : 'block';

                    if (!isActive) {
                        const savedMode = localStorage.getItem(LOCAL_STORAGE_KEY_MODE) || 'normal';
                        switchInput.checked = savedMode === 'expo';
                        shipSection.style.display = switchInput.checked ? 'block' : 'none';
                        populateCombatShipDropdown(shipSelect);
                    }
                });

                switchInput.addEventListener('change', function () {
                    const mode = this.checked ? 'expo' : 'normal';
                    localStorage.setItem(LOCAL_STORAGE_KEY_MODE, mode);
                    shipSection.style.display = mode === 'expo' ? 'block' : 'none';
                    clearAllInputs();
                });

                shipSelect.addEventListener('change', function () {
                    localStorage.setItem(LOCAL_STORAGE_KEY_SHIP, this.value);
                    clearAllInputs();
                });

                document.getElementById(`${tabId}_splitButton`).addEventListener('click', () => {
                    const splitNumber = parseInt(document.getElementById(`${tabId}_splitNumber`).value);
                    const mode = switchInput.checked ? 'expo' : 'normal';
                    const selectedShip = shipSelect.value;
                    if (splitNumber > 0) {
                        if (mode === 'expo') {
                            doExpoSplit(splitNumber, selectedShip);
                        } else {
                            doNormalSplit(splitNumber);
                        }
                    } else {
                        alert("Please enter a valid split number.");
                    }
                });
            }

            function createScrapTab() {
                const panel = document.querySelector('#ago_panel');
                const splitTab = document.querySelector('#ago_panel_Split');
                if (!panel || !splitTab) return;

                const tabId = 'Scrap';
                const newTab = document.createElement('div');
                newTab.id = `ago_panel_${tabId}`;
                newTab.className = 'ago_panel_tab';
                newTab.setAttribute('ago-data', `{"update":{"tab":"${tabId}","status":"toggle"}}`);
                newTab.innerHTML = `Scrap<span class="ago_panel_tab_info"></span>`;
                splitTab.parentNode.insertBefore(newTab, splitTab.nextSibling);

                const tabContent = document.createElement('div');
                tabContent.id = `ago_panel_${tabId}_Content`;
                tabContent.className = 'ago_panel_tab_content';
                tabContent.style.display = 'none';

                tabContent.innerHTML = `
                    <div style="background: #111017; padding: 10px;">
                        <div style="padding: 8px; background: rgba(0,0,0,0.2); border-radius: 4px; margin-bottom: 8px; display: flex; align-items: center; justify-content: space-between;">
                            <div style="color: #4dabf7; font-size: 11px; font-weight: 600;">Scrap Value (%):</div>
                            <input type="number" id="${tabId}_scrapPercent" min="0" max="100" value="30"
                                style="width: 70px; text-align: center; background: #1a1a1a; color: #fff; border: 1px solid #444; padding: 5px; border-radius: 3px; font-size: 14px; font-weight: bold;">
                        </div>
                        <div style="padding: 8px; background: rgba(0,0,0,0.2); border-radius: 4px;">
                            <div style="text-align: center; color: #4dabf7; font-size: 11px; font-weight: 600; margin-bottom: 6px;">MSE Ratio (M:C:D)</div>
                            <div style="display: flex; gap: 6px; align-items: center; justify-content: center;">
                                <input type="number" id="${tabId}_mseRatioMetal" min="0" step="0.1" value="3"
                                    style="width: 50px; text-align: center; background: #1a1a1a; color: #fff; border: 1px solid #444; padding: 5px; border-radius: 3px; font-size: 13px; font-weight: bold;">
                                <span style="color: #888; font-size: 14px;">:</span>
                                <input type="number" id="${tabId}_mseRatioCrystal" min="0" step="0.1" value="2"
                                    style="width: 50px; text-align: center; background: #1a1a1a; color: #fff; border: 1px solid #444; padding: 5px; border-radius: 3px; font-size: 13px; font-weight: bold;">
                                <span style="color: #888; font-size: 14px;">:</span>
                                <input type="number" id="${tabId}_mseRatioDeut" min="0" step="0.1" value="1"
                                    style="width: 50px; text-align: center; background: #1a1a1a; color: #fff; border: 1px solid #444; padding: 5px; border-radius: 3px; font-size: 13px; font-weight: bold;">
                            </div>
                        </div>
                        <div id="${tabId}_scrapResult" style="margin-top: 10px; padding: 8px; background: #1a1a2e; border-radius: 3px; display: none;">
                            <div class="scrap-resource" data-tab="${tabId}" data-resource="all" style="position: relative; padding: 15px 10px 10px 10px; cursor: pointer; background: rgba(77, 171, 247, 0.1); border-radius: 4px; margin: 5px 0;">
                                <div style="position: absolute; top: 5px; right: 5px; color: #4dabf7; cursor: pointer;" title="Click for Details">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                        <circle cx="12" cy="12" r="10"></circle>
                                        <line x1="12" y1="16" x2="12" y2="12"></line>
                                        <line x1="12" y1="8" x2="12.01" y2="8"></line>
                                    </svg>
                                </div>
                                <div style="margin-top: 10px; padding: 8px; background: rgba(0,0,0,0.2); border-radius: 4px;">
                                    <div style="margin-bottom: 8px;">
                                        <span style="display: inline-block; width: 80px;">Metal:</span>
                                        <span id="${tabId}_scrapMetal" style="color: #ff9d00; font-weight: bold; text-align: right; display: inline-block; width: calc(100% - 90px);">0</span>
                                    </div>
                                    <div style="margin-bottom: 8px;">
                                        <span style="display: inline-block; width: 80px;">Crystal:</span>
                                        <span id="${tabId}_scrapCrystal" style="color: #00b2ff; font-weight: bold; text-align: right; display: inline-block; width: calc(100% - 90px);">0</span>
                                    </div>
                                    <div style="margin-bottom: 8px;">
                                        <span style="display: inline-block; width: 80px;">Deuterium:</span>
                                        <span id="${tabId}_scrapDeuterium" style="color: #b36bff; font-weight: bold; text-align: right; display: inline-block; width: calc(100% - 90px);">0</span>
                                    </div>
                                    <div style="border-top: 1px solid #444; margin-top: 8px; padding-top: 8px;">
                                        <span style="display: inline-block; width: 80px;">Total:</span>
                                        <span id="${tabId}_scrapTotal" style="color: #fff; font-weight: bold; text-align: right; display: inline-block; width: calc(100% - 90px);">0</span>
                                    </div>
                                    <div style="margin-top: 4px;">
                                        <span style="display: inline-block; width: 80px;">MSE:</span>
                                        <span id="${tabId}_scrapMSE" style="color: #4dabf7; font-weight: bold; text-align: right; display: inline-block; width: calc(100% - 90px);">0</span>
                                    </div>
                                </div>
                            </div>

                            <!-- Modal for detailed scrap breakdown -->
                            <div id="${tabId}_scrapDetailsModal" style="display: none; position: fixed; z-index: 10000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.8);">
                                <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: auto; max-width: 1100px; max-height: 90vh; background-color: #1a1a2e; border: 1px solid #444; border-radius: 8px; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.5);">
                                    <div style="display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; background-color: #0f0f1a; border-bottom: 1px solid #444;">
                                        <div>
                                            <h3 style="margin: 0; color: #fff; font-size: 16px;">Detailed Breakdown</h3>
                                            <div id="${tabId}_modalPercentText" style="margin-top: 4px; color: #aaa; font-size: 12px;"></div>
                                        </div>
                                        <span style="cursor: pointer; font-size: 24px; color: #aaa;" id="${tabId}_closeModal">&times;</span>
                                    </div>
                                    <div id="${tabId}_scrapDetailsContent" style="padding: 20px; max-height: 60vh; overflow-y: auto;"></div>
                                    <div style="padding: 15px 20px; background-color: #0f0f1a; border-top: 1px solid #444;">
                                        <div id="${tabId}_modalFooterTotals"></div>
                                    </div>
                                </div>
                            </div>
                            <style>
                                .scrap-resource {
                                    padding: 6px 8px;
                                    margin: 2px 0;
                                    border-radius: 4px;
                                    cursor: pointer;
                                    transition: background-color 0.2s;
                                }
                                .scrap-resource:hover {
                                    background-color: rgba(255,255,255,0.1);
                                }
                                #${tabId}_scrapDetailsContent table {
                                    width: 100%;
                                    border-collapse: collapse;
                                    margin-top: 10px;
                                }
                                #${tabId}_scrapDetailsContent th {
                                    text-align: left;
                                    padding: 10px 15px;
                                    background-color: #252538;
                                    color: #fff;
                                    font-weight: 600;
                                    font-size: 13px;
                                    white-space: nowrap;
                                }
                                #${tabId}_scrapDetailsContent td {
                                    padding: 10px 15px;
                                    border-bottom: 1px solid #2d2d4a;
                                    vertical-align: middle;
                                    font-size: 13px;
                                }
                                #${tabId}_scrapDetailsContent tr:last-child td {
                                    border-bottom: none;
                                }
                                #${tabId}_scrapDetailsContent tr:hover {
                                    background-color: rgba(255,255,255,0.05);
                                }
                            </style>
                        </div>
                    </div>
                `;
                newTab.insertAdjacentElement('afterend', tabContent);

                newTab.addEventListener('click', () => {
                    const isActive = tabContent.style.display === 'block';
                    document.querySelectorAll('.ago_panel_tab_content').forEach(c => c.style.display = 'none');
                    tabContent.style.display = isActive ? 'none' : 'block';
                });
            }

            function setInputValue(element, value) {
                element.value = value;
                ['input', 'change', 'blur'].forEach(eventType => {
                    element.dispatchEvent(new Event(eventType, { bubbles: true }));
                });
            }

            function clearAllInputs() {
                const shipInputs = document.querySelectorAll('#shipsChosen input[type="text"]');
                shipInputs.forEach(input => {
                    if (!input.disabled) setInputValue(input, 0);
                });

                ['metal', 'crystal', 'deuterium'].forEach(res => {
                    const input = document.getElementById(`ago_calc_resource_${res}`);
                    if (input) setInputValue(input, 0);
                });
            }

            function getShipMap() {
                const shipMap = {};

                // Get all ship input fields
                const shipInputs = document.querySelectorAll('input[type="text"][name][data-ipi-highlight-step^="ipiFleetselect"]');

                shipInputs.forEach(input => {
                    const shipName = input.name;
                    const shipId = Object.entries(SHIP_IDS).find(([key, value]) =>
                        key.toLowerCase() === shipName.toLowerCase()
                    )?.[1];

                    if (shipId && !input.disabled) {
                        // Get available amount from the stock display
                        const listItem = input.closest('li');
                        const stockElement = listItem?.querySelector('.amount .stockAmount');
                        const availableAmount = stockElement ? parseInt(stockElement.textContent.replace(/\./g, '')) : 0;

                        if (availableAmount > 0) {
                            shipMap[shipId] = {
                                amount: availableAmount,
                                input: input,
                                name: shipName
                            };
                        }
                    }
                });

                return shipMap;
            }

            function populateCombatShipDropdown(selectElement) {
                const previous = localStorage.getItem(LOCAL_STORAGE_KEY_SHIP) || "";
                const shipMap = getShipMap();

                const validShips = {
                    '218': 'Reaper',
                    '213': 'Destroyer',
                    '211': 'Bomber',
                    '215': 'Battlecruiser',
                    '204': 'Light Fighter',
                    '205': 'Heavy Fighter',
                    '206': 'Cruiser',
                    '207': 'Battleship'
                };

                selectElement.innerHTML = '<option value="">-- No combat ship --</option>';

                Object.entries(validShips).forEach(([id, name]) => {
                    if (shipMap[id] && shipMap[id].amount > 0) {
                        const opt = document.createElement('option');
                        opt.value = id;
                        opt.textContent = name;
                        selectElement.appendChild(opt);
                    }
                });

                if (previous && selectElement.querySelector(`option[value="${previous}"]`)) {
                    selectElement.value = previous;
                } else {
                    selectElement.value = "";
                    localStorage.removeItem(LOCAL_STORAGE_KEY_SHIP);
                }
            }

            function doNormalSplit(splitNumber) {
                const shipMap = getShipMap();

                ['metal', 'crystal', 'deuterium'].forEach(res => {
                    const available = parseInt(document.getElementById(`ago_calc_available_${res}`)?.textContent.replace(/\./g, '') || '0');
                    const input = document.getElementById(`ago_calc_resource_${res}`);
                    if (input) setInputValue(input, Math.floor(available / splitNumber));
                });

                Object.entries(shipMap).forEach(([shipId, ship]) => {
                    if (ship.amount > 0) {
                        const newAmount = Math.floor(ship.amount / splitNumber);
                        setInputValue(ship.input, newAmount);
                    }
                });
            }

            function doExpoSplit(splitNumber, selectedShipId) {
                const shipMap = getShipMap();

                if (shipMap[SHIP_IDS.explorer]) {
                    setInputValue(shipMap[SHIP_IDS.explorer].input, 1);
                }

                [SHIP_IDS.transporterSmall, SHIP_IDS.transporterLarge].forEach(id => {
                    if (shipMap[id]) {
                        setInputValue(shipMap[id].input, Math.floor(shipMap[id].amount / splitNumber));
                    }
                });

                if (selectedShipId && shipMap[selectedShipId] && shipMap[selectedShipId].amount > 0) {
                    setInputValue(shipMap[selectedShipId].input, 1);
                }
            }

            // Store the detailed scrap data for each ship
            let scrapDetails = {};

            // Ship ID to class name mapping for icons
            const SHIP_CLASSES = {
                '202': 'transporterSmall',
                '203': 'transporterLarge',
                '204': 'fighterLight',
                '205': 'fighterHeavy',
                '206': 'cruiser',
                '207': 'battleship',
                '208': 'colonyShip',
                '209': 'recycler',
                '210': 'espionageProbe',
                '211': 'bomber',
                '213': 'destroyer',
                '214': 'deathstar',
                '215': 'interceptor',
                '218': 'reaper',
                '219': 'explorer'
            };

            // Function to get ship names dynamically from the page
            function getShipNames() {
                const shipNames = {};
                const shipElements = document.querySelectorAll('li[data-technology]');

                shipElements.forEach(element => {
                    const shipId = element.getAttribute('data-technology');
                    const nameElement = element.querySelector('.ago_items_textName');
                    if (shipId && nameElement) {
                        shipNames[shipId] = nameElement.textContent.trim();
                    }
                });

                return shipNames;
            }

            // Make function available globally
            window.showScrapDetails = function(clickedElement, tabId) {
                const modal = document.getElementById(`${tabId}_scrapDetailsModal`);
                const content = document.getElementById(`${tabId}_scrapDetailsContent`);

                // Get dynamic ship names from the page
                const SHIP_NAMES = getShipNames();

                let html = `
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                `;

                let totalMetal = 0;
                let totalCrystal = 0;
                let totalDeuterium = 0;

                // Sort ships by name for better readability
                const sortedShips = Object.entries(scrapDetails).sort((a, b) => {
                    return a[0].localeCompare(b[0]);
                });

                sortedShips.forEach(([shipId, data]) => {
                    if (data.amount > 0) {
                        const shipName = SHIP_NAMES[shipId] || `Ship ${shipId}`;
                        const shipClass = SHIP_CLASSES[shipId] || 'default';

                        totalMetal += data.metal || 0;
                        totalCrystal += data.crystal || 0;
                        totalDeuterium += data.deuterium || 0;

                        html += `
                            <div style="background: rgba(0,0,0,0.3); padding: 12px; border-radius: 6px; border: 1px solid #2d2d4a;">
                                <div style="display: flex; align-items: center; margin-bottom: 8px; padding-bottom: 8px; border-bottom: 1px solid #2d2d4a;">
                                    <span class="sprite sprite_small small ${shipClass}" style="display: inline-block; margin-right: 8px;"></span>
                                    <div style="flex: 1;">
                                        <div style="font-weight: 600; color: #fff; font-size: 13px; margin-bottom: 4px;">${shipName}</div>
                                        <div style="color: #aaa; font-size: 11px;">Amount: ${data.amount.toLocaleString()}</div>
                                    </div>
                                </div>
                                <div style="display: flex; gap: 15px; font-size: 11px;">
                                    <div style="flex: 1;">
                                        <div style="color: #888; margin-bottom: 4px; font-size: 10px;">Value/Unit</div>
                                        <div style="color: #ff9d00; margin-bottom: 2px;">M: ${(data.metalPerUnit || 0).toLocaleString()}</div>
                                        <div style="color: #00b2ff; margin-bottom: 2px;">C: ${(data.crystalPerUnit || 0).toLocaleString()}</div>
                                        <div style="color: #b36bff;">D: ${(data.deuteriumPerUnit || 0).toLocaleString()}</div>
                                    </div>
                                    <div style="flex: 1;">
                                        <div style="color: #888; margin-bottom: 4px; font-size: 10px;">Total</div>
                                        <div style="color: #ff9d00; margin-bottom: 2px;">M: ${(data.metal || 0).toLocaleString()}</div>
                                        <div style="color: #00b2ff; margin-bottom: 2px;">C: ${(data.crystal || 0).toLocaleString()}</div>
                                        <div style="color: #b36bff;">D: ${(data.deuterium || 0).toLocaleString()}</div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }
                });

                html += `</div>`;

                content.innerHTML = html;

                // Update the percentage text in the header
                const percentText = document.getElementById(`${tabId}_modalPercentText`);
                if (percentText) {
                    percentText.textContent = `Based on ${document.getElementById(`${tabId}_scrapPercent`).value}% of scrap value`;
                }

                // Calculate MSE (Metal Standard Equivalent)
                // Ratios represent relative value: M:C:D = 3:2:1 means C is worth 2/3 of M, D is worth 1/3 of M
                const mseRatioMetal = parseFloat(document.getElementById(`${tabId}_mseRatioMetal`).value) || 3;
                const mseRatioCrystal = parseFloat(document.getElementById(`${tabId}_mseRatioCrystal`).value) || 2;
                const mseRatioDeut = parseFloat(document.getElementById(`${tabId}_mseRatioDeut`).value) || 1;

                const totalMSE = Math.floor(
                    totalMetal +
                    (totalCrystal * (mseRatioMetal / mseRatioCrystal)) +
                    (totalDeuterium * (mseRatioMetal / mseRatioDeut))
                );

                // Calculate total resources sum
                const totalResourcesSum = totalMetal + totalCrystal + totalDeuterium;

                // Update the total resources in the footer
                const footerContent = document.getElementById(`${tabId}_modalFooterTotals`);
                if (footerContent) {
                    footerContent.innerHTML = `
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <div style="font-weight: bold; font-size: 14px; color: #fff;">Total Resources:</div>
                            <div style="display: flex; gap: 30px;">
                                <div style="color: #ff9d00;">Metal: ${totalMetal.toLocaleString()}</div>
                                <div style="color: #00b2ff;">Crystal: ${totalCrystal.toLocaleString()}</div>
                                <div style="color: #b36bff;">Deuterium: ${totalDeuterium.toLocaleString()}</div>
                            </div>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 10px; border-top: 1px solid #444; margin-bottom: 10px;">
                            <div style="font-weight: bold; font-size: 14px; color: #fff;">Total Sum:</div>
                            <div style="color: #fff; font-size: 16px; font-weight: bold;">${totalResourcesSum.toLocaleString()}</div>
                        </div>
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div style="font-weight: bold; font-size: 14px; color: #fff;">MSE (${mseRatioMetal}:${mseRatioCrystal}:${mseRatioDeut}):</div>
                            <div style="color: #4dabf7; font-size: 16px; font-weight: bold;">${totalMSE.toLocaleString()}</div>
                        </div>
                    `;
                }

                modal.style.display = 'block';
                document.body.style.overflow = 'hidden'; // Prevent scrolling when modal is open
            }

            // Initialize modal close handlers
            function setupModalCloseHandlers(tabId) {
                const modal = document.getElementById(`${tabId}_scrapDetailsModal`);
                if (!modal) return;

                // Close when clicking the X button
                const closeBtn = document.getElementById(`${tabId}_closeModal`);
                const closeBtn2 = document.getElementById(`${tabId}_closeModalBtn`);

                if (closeBtn) {
                    closeBtn.onclick = function() {
                        modal.style.display = 'none';
                        document.body.style.overflow = 'auto';
                    };
                }

                if (closeBtn2) {
                    closeBtn2.onclick = function() {
                        modal.style.display = 'none';
                        document.body.style.overflow = 'auto';
                    };
                }

                // Close when clicking outside the modal
                modal.onclick = function(event) {
                    if (event.target === modal) {
                        modal.style.display = 'none';
                        document.body.style.overflow = 'auto';
                    }
                };

                // Add click handlers for resource rows
                const resourceElements = document.querySelectorAll(`#${tabId}_scrapResult .scrap-resource`);
                resourceElements.forEach(el => {
                    el.onclick = function() {
                        window.showScrapDetails(el, tabId);
                    };
                });
            }

            function calculateScrapValue(tabId) {
                const percent = parseInt(document.getElementById(`${tabId}_scrapPercent`).value) || 100;

                let totalMetal = 0;
                let totalCrystal = 0;
                let totalDeuterium = 0;

                // Reset scrap details
                scrapDetails = {};

                // Get all ship input fields and read their values
                const shipInputs = document.querySelectorAll('input[type="text"][name][data-ipi-highlight-step^="ipiFleetselect"]');

                shipInputs.forEach(input => {
                    const shipName = input.name;
                    const shipId = Object.entries(SHIP_IDS).find(([key, value]) =>
                        key.toLowerCase() === shipName.toLowerCase()
                    )?.[1];

                    if (shipId && SHIP_SCRAP_VALUES[shipId]) {
                        // Read the amount from the input field value
                        const amount = parseInt(input.value.replace(/\./g, '') || '0');

                        if (amount > 0) {
                            const scrap = SHIP_SCRAP_VALUES[shipId];
                            const metal = Math.floor(scrap.metal * amount * (percent / 100));
                            const crystal = Math.floor(scrap.crystal * amount * (percent / 100));
                            const deuterium = Math.floor(scrap.deuterium * amount * (percent / 100));

                            totalMetal += metal;
                            totalCrystal += crystal;
                            totalDeuterium += deuterium;

                            // Store detailed information using shipId as key
                            scrapDetails[shipId] = {
                                amount: amount,
                                metal,
                                crystal,
                                deuterium,
                                metalPerUnit: Math.round(scrap.metal * (percent / 100)),
                                crystalPerUnit: Math.round(scrap.crystal * (percent / 100)),
                                deuteriumPerUnit: Math.round(scrap.deuterium * (percent / 100))
                            };
                        }
                    }
                });

                // Save the percentage for next time
                GM_setValue(LOCAL_STORAGE_SCRAP_PERCENT, percent);

                // Calculate MSE (Metal Standard Equivalent)
                // Ratios represent relative value: M:C:D = 3:2:1 means C is worth 3/2=1.5x M, D is worth 3/1=3x M
            const mseRatioMetal = parseFloat(document.getElementById(`${tabId}_mseRatioMetal`).value) || 3;
            const mseRatioCrystal = parseFloat(document.getElementById(`${tabId}_mseRatioCrystal`).value) || 2;
            const mseRatioDeut = parseFloat(document.getElementById(`${tabId}_mseRatioDeut`).value) || 1;

            const totalMSE = Math.floor(
                totalMetal +
                (totalCrystal * (mseRatioMetal / mseRatioCrystal)) +
                (totalDeuterium * (mseRatioMetal / mseRatioDeut))
            );

                // Calculate total resources
                const totalResources = totalMetal + totalCrystal + totalDeuterium;

                // Update the UI
                document.getElementById(`${tabId}_scrapMetal`).textContent = totalMetal.toLocaleString();
                document.getElementById(`${tabId}_scrapCrystal`).textContent = totalCrystal.toLocaleString();
                document.getElementById(`${tabId}_scrapDeuterium`).textContent = totalDeuterium.toLocaleString();
                document.getElementById(`${tabId}_scrapTotal`).textContent = totalResources.toLocaleString();
                document.getElementById(`${tabId}_scrapMSE`).textContent = totalMSE.toLocaleString();
                document.getElementById(`${tabId}_scrapResult`).style.display = 'block';
            }

            window.addEventListener('load', () => {
                createSplitTab();
                createScrapTab();

                // Initialize scrap percentage from storage if available
                setTimeout(() => {
                    const tabId = 'Scrap';
                    const savedPercent = GM_getValue(LOCAL_STORAGE_SCRAP_PERCENT, 30);
                    const percentInput = document.getElementById(`${tabId}_scrapPercent`);
                    if (percentInput) {
                        percentInput.value = savedPercent;

                        // Add event listener for percentage input changes
                        percentInput.addEventListener('input', () => {
                            const scrapResult = document.getElementById(`${tabId}_scrapResult`);
                            if (scrapResult && scrapResult.style.display !== 'none') {
                                calculateScrapValue(tabId);
                            }
                        });

                        // Add event listeners for MSE ratio inputs
                        const mseRatioInputs = [
                            document.getElementById(`${tabId}_mseRatioMetal`),
                            document.getElementById(`${tabId}_mseRatioCrystal`),
                            document.getElementById(`${tabId}_mseRatioDeut`)
                        ];

                        mseRatioInputs.forEach(input => {
                            if (input) {
                                input.addEventListener('input', () => {
                                    const scrapResult = document.getElementById(`${tabId}_scrapResult`);
                                    if (scrapResult && scrapResult.style.display !== 'none') {
                                        calculateScrapValue(tabId);
                                    }
                                });
                            }
                        });

                        // Setup modal handlers
                        setupModalCloseHandlers(tabId);

                        // Add event listeners to all ship input fields for automatic updates
                        const shipInputs = document.querySelectorAll('input[type="text"][name][data-ipi-highlight-step^="ipiFleetselect"]');
                        shipInputs.forEach(input => {
                            input.addEventListener('input', () => {
                                const scrapTabContent = document.getElementById(`ago_panel_${tabId}_Content`);
                                if (scrapTabContent && scrapTabContent.style.display !== 'none') {
                                    calculateScrapValue(tabId);
                                }
                            });

                            input.addEventListener('change', () => {
                                const scrapTabContent = document.getElementById(`ago_panel_${tabId}_Content`);
                                if (scrapTabContent && scrapTabContent.style.display !== 'none') {
                                    calculateScrapValue(tabId);
                                }
                            });
                        });
                    }
                }, 1000);
            });
        })();