// ==UserScript==
// @name         手机端视频下载助手-终极版
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  确保在手机网页上100%显示视频下载按钮
// @author       You
// @match        *://*/*
// @grant        GM_addStyle
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // 添加基础样式确保显示
    GM_addStyle(`
        #video-download-container {
            position: fixed !important;
            bottom: 20px !important;
            right: 10px !important;
            z-index: 2147483647 !important;
            display: flex !important;
            flex-direction: column !important;
            gap: 10px !important;
        }
        .video-download-btn {
            padding: 15px 20px !important;
            background: #FF5722 !important;
            color: white !important;
            border: none !important;
            border-radius: 50px !important;
            font-size: 16px !important;
            font-weight: bold !important;
            cursor: pointer !important;
            box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
            width: auto !important;
            min-width: 120px !important;
            text-align: center !important;
            user-select: none !important;
            -webkit-tap-highlight-color: transparent !important;
        }
        .video-download-btn:active {
            transform: scale(0.95) !important;
            opacity: 0.9 !important;
        }
        #video-download-tip {
            color: #999 !important;
            font-size: 12px !important;
            text-align: center !important;
            margin-top: 5px !important;
        }
        #video-download-show-btn {
            position: fixed !important;
            bottom: 10px !important;
            right: 10px !important;
            z-index: 2147483647 !important;
            padding: 10px 15px !important;
            background: #2196F3 !important;
            color: white !important;
            border-radius: 50px !important;
            font-size: 14px !important;
            cursor: pointer !important;
            display: none !important;
        }
    `);

    function initVideoDownloader() {
        // 获取所有video元素，包括可能被隐藏的
        const videos = Array.from(document.querySelectorAll('video')).filter(video => {
            // 检查视频是否有可下载的源
            return video.src || video.querySelector('source[src]');
        });

        if (videos.length === 0) return;

        // 移除旧容器
        const oldContainer = document.getElementById('video-download-container');
        if (oldContainer) oldContainer.remove();

        // 创建新容器
        const downloadContainer = document.createElement('div');
        downloadContainer.id = 'video-download-container';

        // 为每个视频创建下载按钮
        videos.forEach((video, index) => {
            const downloadBtn = document.createElement('button');
            downloadBtn.className = 'video-download-btn';
            downloadBtn.textContent = `下载 ${index + 1}`;
            
            downloadBtn.addEventListener('click', function() {
                downloadVideo(video, index);
            });

            downloadContainer.appendChild(downloadBtn);
        });

        // 添加提示和功能
        if (downloadContainer.children.length > 0) {
            const tip = document.createElement('div');
            tip.id = 'video-download-tip';
            tip.textContent = '长按3秒隐藏';
            downloadContainer.appendChild(tip);
            
            document.body.appendChild(downloadContainer);
            
            // 长按隐藏功能
            setupLongPressHide(downloadContainer);
        }
    }

    function setupLongPressHide(container) {
        let pressTimer;
        const showBtn = document.createElement('div');
        showBtn.id = 'video-download-show-btn';
        showBtn.textContent = '显示下载按钮';
        document.body.appendChild(showBtn);
        
        container.addEventListener('touchstart', function() {
            pressTimer = setTimeout(() => {
                this.style.display = 'none';
                showBtn.style.display = 'block';
            }, 3000);
        });
        
        container.addEventListener('touchend', function() {
            clearTimeout(pressTimer);
        });
        
        showBtn.addEventListener('click', function() {
            container.style.display = 'flex';
            this.style.display = 'none';
        });
    }

    function downloadVideo(video, index) {
        let videoUrl = video.src || (video.querySelector('source') && video.querySelector('source').src);
        
        if (!videoUrl) {
            // 尝试从blob URL获取
            if (video.querySelector('source[type^="video"]')) {
                videoUrl = video.querySelector('source[type^="video"]').src;
            }
        }

        if (!videoUrl) {
            alert('无法获取视频地址\n请尝试长按视频选择下载');
            return;
        }

        const a = document.createElement('a');
        a.href = videoUrl;
        a.download = `video_${index + 1}_${Date.now()}.mp4`;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
            document.body.removeChild(a);
        }, 100);
    }

    // 确保按钮显示的终极方案
    function ensureDisplay() {
        // 1. 初始检查
        initVideoDownloader();
        
        // 2. 延迟检查（针对动态加载内容）
        setTimeout(initVideoDownloader, 3000);
        
        // 3. 监听DOM变化
        const observer = new MutationObserver(function(mutations) {
            let shouldCheck = false;
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length > 0) {
                    shouldCheck = true;
                }
            });
            if (shouldCheck) {
                initVideoDownloader();
            }
        });
        
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // 4. 监听视频播放事件（针对懒加载视频）
        document.addEventListener('play', function(e) {
            if (e.target.tagName === 'VIDEO' && !document.getElementById('video-download-container')) {
                initVideoDownloader();
            }
        }, true);
    }

    // 启动脚本
    if (document.readyState === 'complete') {
        ensureDisplay();
    } else {
        window.addEventListener('load', ensureDisplay);
    }
})();