// ==UserScript==
// @name         VK Video Unlocker (Fixed Bookmarks Handling)
// @namespace    http://tampermonkey.net/
// @version      2.6
// @description  Unlocks VK videos with proper click handling (fixed bookmarks behavior)
// @author       1axx
// @license      MIT
// @icon         https://www.google.com/s2/favicons?sz=64&domain=vk.com
// @match        *://vk.com/*
// @match        *://*.vk.com/*
// @match        *://vkvideo.ru/*
// @match        *://*.vkvideo.ru/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Configuration
    const config = {
        maxAttempts: 5,
        delayBetweenAttempts: 1000,
        playButtonWaitTime: 1500,
        blurRemovalInterval: 2000,
        isBookmarksPage: window.location.href.includes('vk.com/bookmarks')
    };

    // Track video elements we've processed
    const processedVideos = new WeakSet();

    // Main processor
    function processAll() {
        if (window.location.host.includes('vkvideo.ru')) {
            handleVkVideoRuPlayer();
        } else if (config.isBookmarksPage) {
            handleBookmarks();
        }
        removeBlurRestrictions();
    }

    // Special handling for vkvideo.ru player
    function handleVkVideoRuPlayer() {
        // Remove restriction elements
        document.querySelectorAll('.VideoRestriction, .videoplayer--hasRestriction').forEach(el => {
            el.style.display = 'none';
            el.remove();
        });

        // Unblur the video
        document.querySelectorAll('.videoplayer--blur, .videoplayer_thumb_blur').forEach(el => {
            el.style.filter = 'none';
            el.style.webkitFilter = 'none';
            el.style.pointerEvents = 'auto';
        });

        const videoElement = document.querySelector('video.videoplayer_media_provider');
        if (!videoElement || processedVideos.has(videoElement)) return;

        // Mark this video as processed
        processedVideos.add(videoElement);

        // Fix click handling - proper pause/play toggle
        videoElement.addEventListener('click', (e) => {
            if (e.target === videoElement) {
                if (videoElement.paused) {
                    videoElement.play().catch(() => {});
                } else {
                    videoElement.pause();
                }
                e.stopImmediatePropagation();
                e.preventDefault();
            }
        }, true);

        // Make video controls always visible and clickable
        document.querySelectorAll('.videoplayer_controls').forEach(controls => {
            controls.style.pointerEvents = 'auto';
            controls.style.opacity = '1';
        });

        // Initialize playback
        let attempts = 0;
        const tryPlay = setInterval(() => {
            attempts++;

            if (videoElement.readyState > 2) {
                videoElement.play().catch(() => {
                    const playBtn = document.querySelector('.videoplayer_btn_play');
                    if (playBtn) playBtn.style.display = 'block';
                });
                clearInterval(tryPlay);
            }

            if (attempts >= config.maxAttempts) {
                clearInterval(tryPlay);
                const playBtn = document.querySelector('.videoplayer_btn_play');
                if (playBtn) playBtn.style.display = 'block';
            }
        }, config.delayBetweenAttempts);
    }

    // Handle bookmarks page - only remove restrictions, don't interact with videos
    function handleBookmarks() {
        // Remove blur and restrictions from thumbnails
        document.querySelectorAll('.bookmarks_row_type_video .VideoRestriction').forEach(el => {
            el.style.display = 'none';
            el.remove();
        });

        // Remove blur filters
        document.querySelectorAll('.bookmarks_row_type_video [class*="blur"]').forEach(el => {
            el.style.filter = 'none';
            el.style.webkitFilter = 'none';
        });

        // Make video thumbnails visible
        document.querySelectorAll('.bookmarks_row_type_video .page_post_sized_thumbs').forEach(el => {
            el.style.display = 'block';
        });

        // Remove click handlers that show restrictions
        document.querySelectorAll('.bookmarks_row_type_video .post_video_desc a').forEach(link => {
            link.onclick = null;
            link.addEventListener('click', (e) => {
                // Allow normal navigation but prevent restriction popup
                return true;
            });
        });
    }

    // General blur and restriction removal
    function removeBlurRestrictions() {
        // Remove blur filters
        document.querySelectorAll('[style*="blur"], [class*="blur"]').forEach(el => {
            el.style.filter = 'none !important';
            el.style.webkitFilter = 'none !important';
        });

        // Remove restriction elements
        document.querySelectorAll('.VideoRestriction, .vkitVideoCardRestrictionOverlay').forEach(el => {
            el.style.display = 'none !important';
            el.style.pointerEvents = 'none !important';
        });
    }

    // Initialize
    function init() {
        // Don't run on bookmarks page if it's causing issues
        if (config.isBookmarksPage) {
            // Only handle bookmarks-specific elements
            handleBookmarks();
            setInterval(handleBookmarks, config.blurRemovalInterval);
        } else {
            processAll();

            const observer = new MutationObserver(() => {
                processAll();
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });

            setInterval(processAll, config.blurRemovalInterval);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();