// ==UserScript==
// @name         Geocaching: Show Background Image 
// @namespace    http://tampermonkey.net/
// @version      1.5
// @copyright    2026 
// @author       OUT14ND3R
// @description  Shows background images ONLY inside CacheDetailsPage or <body background>, with Next/Prev and UI filtering
// @match        https://www.geocaching.com/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    let popup = null;
    let bgList = [];
    let currentIndex = 0;

    // Hard-blocked GC UI background
    const BLOCK_BG = "ui-bg_flat_100_ede5dc_40x100.png";

    /************************************************************
     *  Extract background-image URLs
     *  Priority:
     *   1. <body class="CacheDetailsPage" background="...">
     *   2. Elements inside .CacheDetailsPage
     ************************************************************/
    function findBackgroundImages() {
        const urls = new Set();
        const body = document.body;

        /***********************
         * 1. BODY BACKGROUND
         ***********************/
        if (body.classList.contains("CacheDetailsPage") && body.getAttribute("background")) {
            const bg = body.getAttribute("background");

            // Hard-block UI background
            if (bg.includes(BLOCK_BG)) {
                return ["__BLOCKED__"];
            }

            urls.add(bg);
            return Array.from(urls); // Body background overrides everything else
        }

        /*******************************
         * 2. SCAN .CacheDetailsPage
         *******************************/
        const container = document.querySelector(".CacheDetailsPage");
        if (!container) return [];

        const all = container.querySelectorAll("*");

        for (const el of all) {
            const style = window.getComputedStyle(el);
            const bg = style.backgroundImage;

            if (bg && bg !== "none") {
                const match = bg.match(/url\(["']?(.*?)["']?\)/);
                if (match && match[1]) {
                    const url = match[1];

                    // Hard-block UI background
                    if (url.includes(BLOCK_BG)) {
                        return ["__BLOCKED__"];
                    }

                    // Normal filtering
                    if (!url.includes("data:image") &&
                        !url.includes("sprite") &&
                        !url.includes("icons") &&
                        !url.includes("map") &&
                        !url.includes("logo")) {
                        urls.add(url);
                    }
                }
            }
        }

        return Array.from(urls);
    }

    /************************************************************
     *  Create popup window (once)
     ************************************************************/
    function createPopup() {
        if (popup) return popup;

        popup = document.createElement("div");
        popup.style.position = "fixed";
        popup.style.top = "120px";
        popup.style.right = "20px";
        popup.style.width = "520px";
        popup.style.height = "420px";
        popup.style.background = "white";
        popup.style.border = "3px solid #333";
        popup.style.borderRadius = "6px";
        popup.style.boxShadow = "0 0 12px rgba(0,0,0,0.6)";
        popup.style.padding = "10px";
        popup.style.overflow = "auto";
        popup.style.zIndex = "999999999";
        popup.style.display = "none";
        popup.style.resize = "both";

        // Header
        const header = document.createElement("div");
        header.style.display = "flex";
        header.style.justifyContent = "space-between";
        header.style.alignItems = "center";
        header.style.marginBottom = "8px";

        const title = document.createElement("span");
        title.textContent = "Background Image URLs";
        header.appendChild(title);

        // Prev button
        const prevBtn = document.createElement("input");
        prevBtn.type = "submit";
        prevBtn.value = "<";
        prevBtn.style.marginLeft = "10px";
        prevBtn.style.cursor = "pointer";
        prevBtn.setAttribute("onclick", "return false;");
        prevBtn.addEventListener("click", () => {
            currentIndex--;
            updatePopup();
        });
        header.appendChild(prevBtn);

        // Next button
        const nextBtn = document.createElement("input");
        nextBtn.type = "submit";
        nextBtn.value = ">";
        nextBtn.style.marginLeft = "6px";
        nextBtn.style.cursor = "pointer";
        nextBtn.setAttribute("onclick", "return false;");
        nextBtn.addEventListener("click", () => {
            currentIndex++;
            updatePopup();
        });
        header.appendChild(nextBtn);

        // Close button
        const closeBtn = document.createElement("input");
        closeBtn.type = "submit";
        closeBtn.value = "X";
        closeBtn.style.color = "white";
        closeBtn.style.background = "red";
        closeBtn.style.border = "1px solid #900";
        closeBtn.style.borderRadius = "4px";
        closeBtn.style.padding = "2px 8px";
        closeBtn.style.cursor = "pointer";
        closeBtn.setAttribute("onclick", "return false;");
        closeBtn.addEventListener("click", () => popup.style.display = "none");
        header.appendChild(closeBtn);

        // Content area
        const content = document.createElement("div");
        content.id = "bg_content";

        popup.appendChild(header);
        popup.appendChild(content);
        document.body.appendChild(popup);

        return popup;
    }

    /************************************************************
     *  Populate popup with ONE background URL (with navigation)
     ************************************************************/
    function updatePopup() {
        const content = document.getElementById("bg_content");
        if (!content) return;

        // Hard-block condition
        if (bgList.length === 1 && bgList[0] === "__BLOCKED__") {
            content.innerHTML = "<p>No background images found.</p>";
            return;
        }

        if (bgList.length === 0) {
            content.innerHTML = "<p>No background images found.</p>";
            return;
        }

        // Wrap index
        if (currentIndex < 0) currentIndex = bgList.length - 1;
        if (currentIndex >= bgList.length) currentIndex = 0;

        const url = bgList[currentIndex];

        content.innerHTML = `
            <div style="margin-bottom: 12px;">
                <strong>Image ${currentIndex + 1} of ${bgList.length}</strong><br>
                <a href="${url}" target="_blank">${url}</a><br>
                <img src="${url}" style="max-width: 100%; margin-top: 6px; border: 1px solid #ccc;">
            </div>
        `;
    }

    /************************************************************
     *  Add button to GC Download section
     ************************************************************/
    function addButton() {
        if (document.getElementById("btnShowBG")) return;

        const btn = document.createElement("input");
        btn.id = "btnShowBG";
        btn.type = "submit";
        btn.value = "Show Background Image";
        btn.style.color = "red";
        btn.style.float = "right";
        btn.style.marginLeft = "10px";
        btn.setAttribute("onclick", "return false;");

        btn.addEventListener("click", function () {
            const p = createPopup();

            if (p.style.display === "none") {
                bgList = findBackgroundImages();
                currentIndex = 0;
                updatePopup();
                p.style.display = "";
                btn.value = "Hide Background Image";
            } else {
                p.style.display = "none";
                btn.value = "Show Background Image";
            }
        });

        const dd = document.getElementById("Download")?.getElementsByTagName("dd")[0];
        if (dd) dd.insertBefore(btn, dd.firstChild);
    }

    /************************************************************
     *  React-safe: keep button alive
     ************************************************************/
    const observer = new MutationObserver(addButton);
    observer.observe(document.documentElement, { childList: true, subtree: true });

    addButton();

})();
