NeoNix-UA / SoundCloud Following Enhancer

// ==UserScript==
// @name             SoundCloud Following Enhancer
// @namespace        http://tampermonkey.net/
// @version          0.9.0
// @description      Sort and resize followed artists on SoundCloud's /you/following page (initial load only). Settings are saved.
// @author           NeoNix-UA
// @match            https://soundcloud.com/you/following
// @grant            GM_addStyle
// @grant            GM_getValue
// @grant            GM_setValue
// @run-at           document-idle
// @license          MIT
// @updateURL        https://openuserjs.org/meta/NeoNix-UA/SoundCloud_Following_Enhancer.meta.js
// @downloadURL      https://openuserjs.org/src/scripts/NeoNix-UA/SoundCloud_Following_Enhancer.user.js
// @copyright        2025, NeoNix-UA (https://soundcloud.com/neonix-ua)
// @icon             https://w.soundcloud.com/icon/assets/images/orange_white_48-94fc761.png
// ==/UserScript==

(function() {
    'use strict';

    const SCRIPT_PREFIX = 'SC Following Enhancer:';
    console.log(`${SCRIPT_PREFIX} Script started (v0.8.1). Infinite scroll not supported.`);

    let currentSortCriteria = GM_getValue('sortCriteria', 'none'); // 'none', 'name-asc', 'name-desc', 'followers-asc', 'followers-desc'
    let currentItemSize = GM_getValue('itemSize', 180);      // 180 or 96
    let sizeStyleElement = null;
    let normalSizeButton = null;
    let smallSizeButton = null;
    let originalSortOrder = []; // To store the initial order if "Original" is selected

    // --- UI & Controls ---
    function addControls() {
        const collectionMainDiv = document.querySelector('div.collection > section.collection__section.collection__followingsSection');
        if (!collectionMainDiv) {
            console.warn(`${SCRIPT_PREFIX} Could not find 'collectionMainDiv' to insert controls.`);
            return;
        }

        const controlsContainer = document.createElement('div');
        controlsContainer.id = 'sc-enhancer-controls';
        controlsContainer.innerHTML = `
            <label for="sc-sort-select" style="margin-right: 5px;">Sort by:</label>
            <select id="sc-sort-select" style="padding: 5px; border-radius: 3px; margin-right: 15px;">
                <option value="none">Original</option>
                <option value="name-asc">Name (A-Z)</option>
                <option value="name-desc">Name (Z-A)</option>
                <option value="followers-desc">Followers (Most)</option>
                <option value="followers-asc">Followers (Least)</option>
            </select>
            <label style="margin-right: 5px;">Item size:</label>
            <button id="sc-size-normal-btn" class="sc-enhancer-size-btn" data-size="180">Normal</button>
            <button id="sc-size-small-btn" class="sc-enhancer-size-btn" data-size="96">Small</button> <!-- ЗМІНЕНО data-size з 110 на 96 -->
            <span id="sc-original-sort-note" style="font-size: 0.8em; color: #777; margin-left: 10px; display: none;">(Reloading the page might be necessary to revert to SoundCloud's original order if sorting has already been applied)</span>
        `;

        collectionMainDiv.parentNode.insertBefore(controlsContainer, collectionMainDiv);
        console.log(`${SCRIPT_PREFIX} Controls added.`);

        const sortSelect = document.getElementById('sc-sort-select');
        sortSelect.value = currentSortCriteria; // Set saved value
        sortSelect.addEventListener('change', function() {
            currentSortCriteria = this.value;
            GM_setValue('sortCriteria', currentSortCriteria);
            console.log(`${SCRIPT_PREFIX} Sort criteria changed to ${currentSortCriteria}`);
            document.getElementById('sc-original-sort-note').style.display = (currentSortCriteria === 'none' && originalSortOrder.length > 0) ? 'inline' : 'none';
            sortItems();
        });

        normalSizeButton = document.getElementById('sc-size-normal-btn');
        smallSizeButton = document.getElementById('sc-size-small-btn');

        if (normalSizeButton) {
            normalSizeButton.addEventListener('click', function() {
                currentItemSize = parseInt(this.dataset.size);
                GM_setValue('itemSize', currentItemSize);
                console.log(`${SCRIPT_PREFIX} Size set to Normal (${currentItemSize}px)`);
                applySize();
                updateSizeButtonActiveState();
            });
        } else {
            console.error(`${SCRIPT_PREFIX} 'Normal size' button not found!`);
        }

        if (smallSizeButton) {
            smallSizeButton.addEventListener('click', function() {
                currentItemSize = parseInt(this.dataset.size); // Тепер буде 96, якщо натиснути "Small"
                GM_setValue('itemSize', currentItemSize);
                console.log(`${SCRIPT_PREFIX} Size set to Small (${currentItemSize}px)`);
                applySize();
                updateSizeButtonActiveState();
            });
        } else {
             console.error(`${SCRIPT_PREFIX} 'Small size' button not found!`);
        }
        document.getElementById('sc-original-sort-note').style.display = (currentSortCriteria === 'none' && originalSortOrder.length > 0) ? 'inline' : 'none';

        GM_addStyle(`
            #sc-enhancer-controls {
                margin-bottom: 15px;
                padding: 12px;
                background-color: var(--background-highlight-color, #f3f3f3);
                border: 1px solid var(--imageBorder-color, rgba(18,18,18,0.15));
                border-radius: var(--borderRadiuses-4, 4px);
                display: flex;
                align-items: center;
                gap: 10px;
                color: var(--font-primary-color, #121212);
                font-family: var(--font-sans-serif-family, SoundCloud Sans, system-ui, sans-serif);
                font-size: var(--typography-body2-font-size, 1rem);
                flex-wrap: wrap;
                box-sizing: border-box;
            }
            #sc-enhancer-controls select,
            .sc-enhancer-size-btn {
                font-family: inherit;
                font-size: var(--typography-captions-font-size, 0.857rem);
                color: var(--input-default-font-color, #121212);
                background-color: var(--button-tertiary-background-color, #fff);
                border: 1px solid var(--input-focused-border-color, #666);
                border-radius: var(--borderRadiuses-4, 4px);
                padding: 7px 10px;
                cursor: pointer;
                transition: background-color 0.2s, color 0.2s, border-color 0.2s;
            }
            #sc-enhancer-controls select {
                margin-right: 10px;
            }
            #sc-enhancer-controls label {
                color: var(--font-secondary-color, #666);
                margin-right: 3px;
            }
            .sc-enhancer-size-btn:hover {
                background-color: var(--button-secondary-background-color, #f3f3f3);
                border-color: var(--font-primary-color, #121212);
            }
            .sc-enhancer-size-btn.active {
                background-color: var(--button-primary-background-color, #121212);
                color: var(--button-primary-font-color, #fff);
                border-color: var(--button-primary-background-color, #121212);
            }
        `);
    }

    function updateSizeButtonActiveState() {
        if (!normalSizeButton || !smallSizeButton) {
            console.warn(`${SCRIPT_PREFIX} Size buttons not initialized to update state.`);
            return;
        }
        if (currentItemSize === 180) {
            normalSizeButton.classList.add('active');
            smallSizeButton.classList.remove('active');
        } else if (currentItemSize === 96) { // ЗМІНЕНО з 110 на 96
            smallSizeButton.classList.add('active');
            normalSizeButton.classList.remove('active');
        } else { // Якщо збережений розмір не 180 і не 96 (наприклад, старий 110)
            normalSizeButton.classList.remove('active');
            smallSizeButton.classList.remove('active');
        }
        console.log(`${SCRIPT_PREFIX} Active button state updated. Current size: ${currentItemSize}px`);
    }

    function applySize() {
        const css = `
            body #content div.l-main div.collection section.collection__section.collection__followingsSection div.collectionSection__list ul.lazyLoadingList__list > li.badgeList__item {
                width: ${currentItemSize}px !important;
                max-width: ${currentItemSize}px !important;
                flex-basis: ${currentItemSize}px !important;
                min-width: ${currentItemSize}px !important;
            }
        `;
        if (sizeStyleElement) {
            sizeStyleElement.textContent = css;
        } else {
            sizeStyleElement = GM_addStyle(css);
        }
        console.log(`${SCRIPT_PREFIX} Applied size ${currentItemSize}px via CSS using specific selector.`);

        const items = document.querySelectorAll('ul.lazyLoadingList__list li.badgeList__item');
        items.forEach(item => {
            item.style.width = `${currentItemSize}px`;
            item.style.maxWidth = `${currentItemSize}px`;
            item.style.flexBasis = `${currentItemSize}px`;
            item.style.minWidth = `${currentItemSize}px`;
        });
        if(items.length > 0) console.log(`${SCRIPT_PREFIX} Directly styled ${items.length} elements.`);
    }

    // --- Data Extraction & Sorting ---
    function parseFollowerCount(followerText) {
        if (!followerText) return 0;
        let text = followerText.toLowerCase()
            .replace(/,/g, '')
            .replace(/\s*(?:followers|follower|підписників|підписника)/, '') // Keep Ukrainian terms for parsing
            .trim();

        let multiplier = 1;
        if (text.endsWith('k') || text.endsWith('к')) { // Keep Ukrainian 'к'
            multiplier = 1000;
            text = text.slice(0, -1);
        } else if (text.endsWith('m') || text.endsWith('м')) { // Keep Ukrainian 'м'
            multiplier = 1000000;
            text = text.slice(0, -1);
        }
        const number = parseFloat(text.replace(',', '.'));
        return isNaN(number) ? 0 : number * multiplier;
    }

    function getItemData(itemElement, index) {
        const nameEl = itemElement.querySelector('a.userBadgeListItem__heading');
        const name = nameEl ? nameEl.textContent.trim() : '';

        let followers = 0;
        const followersSpanEl = itemElement.querySelector('.userBadgeListItem__subtitle .sc-ministats-followers span[aria-hidden="true"]');
        if (followersSpanEl && followersSpanEl.textContent) {
            followers = parseFollowerCount(followersSpanEl.textContent.trim());
        } else {
            const followersTitleEl = itemElement.querySelector('.userBadgeListItem__subtitle .sc-ministats-item');
            if (followersTitleEl && followersTitleEl.title) {
                 followers = parseFollowerCount(followersTitleEl.title);
            } else {
                 const ministatsFollowers = itemElement.querySelector('.userBadgeListItem__subtitle .sc-ministats-followers');
                 if (ministatsFollowers) {
                     followers = parseFollowerCount(ministatsFollowers.textContent.trim());
                 }
            }
        }
        return { element: itemElement, name: name.toLowerCase(), displayName: name, followers, originalIndex: index };
    }

    function storeOriginalOrderIfNeeded() {
        if (originalSortOrder.length > 0) return;

        const listContainer = document.querySelector('ul.lazyLoadingList__list');
        if (!listContainer) return;

        const items = Array.from(listContainer.querySelectorAll('li.badgeList__item'));
        if (items.length > 0) {
            originalSortOrder = items.map(el => el.cloneNode(true));
            console.log(`${SCRIPT_PREFIX} Initial order of ${originalSortOrder.length} items saved.`);
        }
    }

    function sortItems() {
        const listContainer = document.querySelector('ul.lazyLoadingList__list');
        if (!listContainer) {
            console.warn(`${SCRIPT_PREFIX} List container not found for sorting.`);
            return;
        }

        storeOriginalOrderIfNeeded();

        const items = Array.from(listContainer.querySelectorAll('li.badgeList__item'));
        if (items.length === 0 && !listContainer.querySelector('.loading.m-padded')) {
            console.log(`${SCRIPT_PREFIX} No items to sort.`);
            return;
        }

        if (currentSortCriteria === 'none') {
            console.log(`${SCRIPT_PREFIX} Sort set to 'none'. Attempting to restore original order.`);
            if (originalSortOrder.length > 0) {
                listContainer.innerHTML = '';
                originalSortOrder.forEach(el => listContainer.appendChild(el.cloneNode(true)));
                console.log(`${SCRIPT_PREFIX} Restored original order with ${originalSortOrder.length} items.`);
            } else {
                console.log(`${SCRIPT_PREFIX} Original order was not saved. To revert to SoundCloud's original order, please refresh the page.`);
            }
            applySize();
            return;
        }

        const itemsData = items.map((item, index) => getItemData(item, index));

        // Sorting logic with Ukrainian locale for names
        if (currentSortCriteria === 'name-asc') {
            itemsData.sort((a, b) => a.name.localeCompare(b.name, 'uk'));
        } else if (currentSortCriteria === 'name-desc') {
            itemsData.sort((a, b) => b.name.localeCompare(a.name, 'uk'));
        } else if (currentSortCriteria === 'followers-asc') {
            itemsData.sort((a, b) => a.followers - b.followers || a.name.localeCompare(b.name, 'uk'));
        } else if (currentSortCriteria === 'followers-desc') {
            itemsData.sort((a, b) => b.followers - a.followers || a.name.localeCompare(b.name, 'uk'));
        }

        const loadingIndicator = listContainer.querySelector('.loading.m-padded');
        if (loadingIndicator) {
            listContainer.removeChild(loadingIndicator);
        }

        itemsData.forEach(data => listContainer.appendChild(data.element));

        if (loadingIndicator) {
            listContainer.appendChild(loadingIndicator);
        }
        console.log(`${SCRIPT_PREFIX} Items sorted by ${currentSortCriteria}. Count: ${itemsData.length}`);
        applySize();
    }

    // --- Initialization ---
    function waitForElement(selector, callback, timeout = 15000, interval = 500) {
        let elapsedTime = 0;
        console.log(`${SCRIPT_PREFIX} Waiting for element "${selector}"...`);
        const timer = setInterval(() => {
            const element = document.querySelector(selector);
            if (element) {
                console.log(`${SCRIPT_PREFIX} Element "${selector}" found.`);
                clearInterval(timer);
                callback(element);
            } else {
                elapsedTime += interval;
                if (elapsedTime >= timeout) {
                    clearInterval(timer);
                    console.warn(`${SCRIPT_PREFIX} Element "${selector}" not found after ${timeout/1000}s.`);
                }
            }
        }, interval);
    }

    function init() {
        console.log(`${SCRIPT_PREFIX} Initializing script...`);
        waitForElement('div.collection > section.collection__section.collection__followingsSection', (followingSection) => {
            addControls();
            applySize(); // Застосує розмір, збережений раніше (може бути 180, 110 або новий 96)
            updateSizeButtonActiveState(); // Оновить стан кнопок відповідно до currentItemSize

            waitForElement('ul.lazyLoadingList__list', (listContainerNode) => {
                if (listContainerNode.querySelector('li.badgeList__item')) {
                     storeOriginalOrderIfNeeded();
                }

                const checkInitialItems = () => {
                    if (listContainerNode.querySelector('li.badgeList__item')) {
                        console.log(`${SCRIPT_PREFIX} Initial items found. Attempting initial sort if needed.`);
                        if (currentSortCriteria !== 'none') {
                             setTimeout(sortItems, 350);
                        } else {
                             console.log(`${SCRIPT_PREFIX} Initial sort not needed (criterion: 'none').`);
                        }
                    } else if (!listContainerNode.querySelector('.loading.m-padded')) {
                         console.log(`${SCRIPT_PREFIX} List is empty or contains only loading indicator initially.`);
                    } else {
                        console.log(`${SCRIPT_PREFIX} Loading indicator present, waiting for items...`);
                        setTimeout(checkInitialItems, 700);
                    }
                };
                checkInitialItems();

            }, 10000);
        });
    }

    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        console.log(`${SCRIPT_PREFIX} Document ready, initializing.`);
        setTimeout(init, 600);
    } else {
        window.addEventListener('DOMContentLoaded', () => {
            console.log(`${SCRIPT_PREFIX} DOMContentLoaded, initializing.`);
            setTimeout(init, 600);
        });
    }

})();