// ==UserScript==
// @name         B站智能最常访问点击器
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  全场景覆盖的智能点击方案
// @author       平凡的世界
// @match        https://space.bilibili.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // 配置中心
    const CONFIG = {
        TARGET_TEXT: "最常访问",      // 目标按钮文字
        CHECK_INTERVAL: 500,         // 基础检查间隔
        MAX_WAIT_TIME: 10000,        // 最大等待时间(ms)
        OBSERVE_DEEP: true           // 深度DOM监听
    };

    // 核心控制器
    class ClickController {
        constructor() {
            this.observer = null;
            this.timer = null;
            this.isRunning = false;
            this.init();
        }

        // 初始化监控
        init() {
            this.setupRouterListener();
            this.setupDOMObserver();
            this.startCheckCycle();
        }

        // 路由变化监听
        setupRouterListener() {
            let lastUrl = location.href;
            setInterval(() => {
                if (location.href !== lastUrl) {
                    lastUrl = location.href;
                    this.onRouteChange();
                }
            }, 1000);
        }

        // DOM深度监控
        setupDOMObserver() {
            this.observer = new MutationObserver(mutations => {
                if (this.isTargetPage()) this.attemptClick();
            });
            this.observer.observe(document, {
                childList: true,
                subtree: CONFIG.OBSERVE_DEEP
            });
        }

        // 周期性检查
        startCheckCycle() {
            this.timer = setInterval(() => {
                if (this.isTargetPage()) this.attemptClick();
            }, CONFIG.CHECK_INTERVAL);
        }

        // 智能点击逻辑
        attemptClick() {
            if (this.isRunning) return;

            const btn = this.findTargetButton();
            if (btn) {
                this.isRunning = true;
                console.log('触发智能点击');
                btn.click();
                setTimeout(() => this.isRunning = false, 1000);
            }
        }

        // 精准按钮定位
        findTargetButton() {
            return [...document.querySelectorAll('.be-radio, .radio-filter__item')]
              .find(btn => btn.textContent.includes(CONFIG.TARGET_TEXT));
        }

        // 路由变化处理
        onRouteChange() {
            if (this.isTargetPage()) {
                this.attemptClick();
                this.resetObserver();
            }
        }

        // 页面类型判断
        isTargetPage() {
            return /\/relation\/follow|\/fans\/follow/.test(location.pathname);
        }

        // 重置观察器
        resetObserver() {
            this.observer.disconnect();
            this.setupDOMObserver();
        }
    }

    // 启动控制器
    new ClickController();
})();