Mug protection

Warns if you are actively selling items in Bazaar or Item Market.

// ==UserScript==
// @name         Mug protection
// @namespace    Nurv.IronNerd.me
// @version      0.2
// @description  Warns if you are actively selling items in Bazaar or Item Market.
// @author       Nurv [669537]
// @match        https://www.torn.com/*
// @exclude      https://www.torn.com/loader.php?sid=attack*
// @exclude      https://www.torn.com/pc.php*
// @grant        GM_xmlhttpRequest
// @license      Copyright IronNerd.me
// ==/UserScript==

(function () {
    'use strict';

    let apiKey = localStorage.getItem('tornApiKey') || null;
    let ghostId = localStorage.getItem('ghostId') || null;
    let hasPrompted = localStorage.getItem('hasPrompted') || null;

    function initialize() {
        if (!hasPrompted) {
            promptForInputs();
        }
    }

    function promptForInputs() {
        const enteredApiKey = prompt("Enter your Torn API key (leave blank to skip):");
        if (enteredApiKey) {
            apiKey = enteredApiKey;
            localStorage.setItem('tornApiKey', apiKey);
            console.log("API key saved successfully.");
        } else {
            console.log("No API key entered. Default features will be active.");
        }

        const enteredGhostId = prompt("Enter Ghost Friend ID (leave blank to skip):");
        if (enteredGhostId) {
            ghostId = enteredGhostId;
            localStorage.setItem('ghostId', ghostId);
            console.log(`Ghost Friend ID saved as: ${ghostId}`);
        } else {
            console.log("No Ghost Friend ID entered. Ghost Friend feature will be inactive.");
        }

        // Set the flag to prevent further prompts
        localStorage.setItem('hasPrompted', 'true');
    }

    function addGhostIcon() {
        const tradeUrl = ghostId
            ? `https://www.torn.com/trade.php#step=start&userID=${ghostId}`
            : "https://www.torn.com/trade.php";

        const ghostIconHtml = `
            <li class="icon-ghost">
                <a href="${tradeUrl}" aria-label="Ghost Friend" tabindex="0" style="color: white;" data-is-tooltip-opened="false">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24px" height="24px">
                        <path d="M12 2C7.59 2 4 5.59 4 10c0 3.91 2.82 7.19 6.68 7.89l.32.06v3.15l-1.32-1.32-.71-.71-.71.71-1.82 1.83v-5.35c.58.25 1.19.4 1.82.49v4.55l2.53-2.53c.22-.22.51-.34.82-.34h1.03c.31 0 .6.12.82.34l2.53 2.53v-4.55c.63-.09 1.24-.24 1.82-.49v5.35l-1.82-1.83-.71-.71-.71.71-1.32 1.32V18l.32-.06C17.18 17.19 20 13.91 20 10c0-4.41-3.59-8-8-8zm-3 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm6 0c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
                    </svg>
                </a>
            </li>
        `;

        const iconContainerSelector = window.innerWidth <= 784
            ? ".status-icons___gPkXF.mobile___MWm2o"
            : ".status-icons___gPkXF";

        const statusIcons = document.querySelector(iconContainerSelector);
        if (statusIcons) {
            statusIcons.insertAdjacentHTML("beforeend", ghostIconHtml);
            console.log("Ghost Friend icon added.");
        }
    }

    function isInHospital() {
        const hospitalSelector = window.innerWidth <= 784
            ? "li.icon15___IohoO > a[aria-label*='Hospital']"
            : "li[class*='icon15'] a[aria-label*='Hospital']";

        return document.querySelector(hospitalSelector) !== null;
    }

    async function displayBanner(message) {
        console.log("Displaying Banner:", message);

        removeBanner();

        $("body").append(`
            <div id="selling-warning-banner" style="background-color: red; position: fixed; top: 0; width: 100%; z-index: 99999; padding: 12px; text-align: center; color: white; font-weight: bold; cursor: pointer; word-wrap: break-word; white-space: normal;">
                <a href="https://www.torn.com/item.php#medical-items" target="_blank" style="color: white; text-decoration: none;">
                    ${message}
                </a>
            </div>
        `);

        setTimeout(() => {
            removeBanner();
        }, 7000);
    }

    function removeBanner() {
        const banner = $("#selling-warning-banner");
        if (banner.length) {
            banner.remove();
            console.log("Banner removed.");
        }
    }

    async function checkSellingStatus() {
        console.log("Executing checkSellingStatus...");

        if (isInHospital()) {
            console.log("User is in the hospital. Adding Ghost Friend icon.");
            if (ghostId) {
                addGhostIcon();
            }
            return;
        }

        const bazaarSelector = window.innerWidth <= 784
            ? "li.icon35___tya65 > a[aria-label*='Bazaar']"
            : "li[class*='icon35'] a[aria-label*='Bazaar']";
        const itemMarketSelector = window.innerWidth <= 784
            ? "li.icon36___cAwTk > a[aria-label*='Item Market']"
            : "li[class*='icon36'] a[aria-label*='Item Market']";

        const isBazaarActive = document.querySelector(bazaarSelector) !== null;
        const isItemMarketActive = document.querySelector(itemMarketSelector) !== null;

        console.log("Bazaar Active:", isBazaarActive, "Item Market Active:", isItemMarketActive);

        if (!isBazaarActive && !isItemMarketActive) {
            console.log("No active selling detected.");
            return;
        }

        if (apiKey) {
            try {
                const bazaarValue = isBazaarActive
                    ? await fetchApiData(`https://api.torn.com/user/?selections=bazaar&key=${apiKey}`)
                          .then(data => calculateTotal(data.bazaar || [], "quantity"))
                          .catch(err => 0)
                    : 0;

                const itemMarketValue = isItemMarketActive
                    ? await fetchApiData(`https://api.torn.com/v2/user/itemmarket?key=${apiKey}`)
                          .then(data => calculateTotal(data.itemmarket || [], "amount"))
                          .catch(err => 0)
                    : 0;

                const totalValue = bazaarValue + itemMarketValue;

                if (totalValue > 0) {
                    await displayBanner(`You have items worth $${totalValue.toLocaleString()} actively listed. Consider Self-Hosping to avoid being mugged!`);
                }
            } catch (error) {
                console.error("Error fetching or processing API data:", error);
            }
        } else {
            if (isBazaarActive) {
                await displayBanner("You are actively selling items in the Bazaar. <a href='https://www.torn.com/item.php#medical-items' style='color: white;'>Consider Self-Hosping to avoid being mugged!</a>");
            }
            if (isItemMarketActive) {
                await displayBanner("You are actively selling items in the Item Market. <a href='https://www.torn.com/item.php#medical-items' style='color: white;'>Consider Self-Hosping to avoid being mugged!</a>");
            }
        }
    }

    function fetchApiData(url) {
        console.log("Fetching API Data:", url);
        return fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .catch(error => {
                console.error("Error fetching API data:", error);
            });
    }

    function calculateTotal(items, key = "amount") {
        return items.reduce((sum, item) => sum + (item.price * (item[key] || 1)), 0);
    }

    initialize();
    $(document).ready(() => {
        checkSellingStatus();
    });
})();