Alcazi / Spamurai Pro by Alcazi

// ==UserScript==
// @name         Spamurai Pro by Alcazi
// @namespace    http://tampermonkey.net/
// @version      1.3
// @description  Professional TikTok Share Bot - Matrix Edition with Background Toggle
// @author       Alcazi
// @license      MIT
// @match        https://www.tiktok.com/*
// @match        https://tiktok.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_notification
// @grant        unsafeWindow
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    let CONFIG = {
        copyInterval: 1000,
        randomMode: true,
        randomVariance: 300,
        minInterval: 500,
        maxInterval: 3000,
        speedLevel: 3,
        debug: true,
        backgroundVisible: false // New feature
    };

    const CSS = `
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        @import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css');

        .spamurai-overlay {
            position: fixed !important;
            top: 0 !important; left: 0 !important;
            width: 100vw !important; height: 100vh !important;
            background: rgba(0, 0, 0, 0.75) !important;
            backdrop-filter: blur(25px) saturate(120%) !important;
            -webkit-backdrop-filter: blur(25px) saturate(120%) !important;
            z-index: 999999 !important;
            display: flex !important;
            justify-content: center !important;
            align-items: center !important;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
            animation: overlayFadeIn 0.6s cubic-bezier(0.4, 0, 0.2, 1) !important;
            transition: background 0.3s ease, backdrop-filter 0.3s ease !important;
        }

        .spamurai-overlay.background-visible {
            background: rgba(0, 0, 0, 0.3) !important;
            backdrop-filter: blur(5px) saturate(150%) !important;
            -webkit-backdrop-filter: blur(5px) saturate(150%) !important;
        }

        @keyframes overlayFadeIn {
            from {
                opacity: 0;
                backdrop-filter: blur(0px);
            }
            to {
                opacity: 1;
                backdrop-filter: blur(25px);
            }
        }

        .matrix-canvas {
            position: absolute !important;
            top: 0 !important; left: 0 !important;
            width: 100% !important; height: 100% !important;
            z-index: 1 !important;
            pointer-events: none !important;
            opacity: 0.4 !important;
            transition: opacity 0.3s ease !important;
        }

        .spamurai-overlay.background-visible .matrix-canvas {
            opacity: 0.2 !important;
        }

        .spamurai-container {
            background: linear-gradient(145deg, rgba(18, 18, 18, 0.98), rgba(28, 28, 30, 0.95)) !important;
            border: 1px solid rgba(255, 255, 255, 0.08) !important;
            border-radius: 20px !important;
            padding: 24px !important;
            width: 380px !important;
            backdrop-filter: blur(40px) !important;
            -webkit-backdrop-filter: blur(40px) !important;
            box-shadow:
                0 32px 64px rgba(0, 0, 0, 0.8),
                0 0 0 1px rgba(255, 255, 255, 0.03),
                inset 0 1px 0 rgba(255, 255, 255, 0.08) !important;
            position: relative !important;
            z-index: 1000000 !important;
            animation: containerSlideIn 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important;
            transition: all 0.3s ease !important;
        }

        .spamurai-overlay.background-visible .spamurai-container {
            background: linear-gradient(145deg, rgba(18, 18, 18, 0.95), rgba(28, 28, 30, 0.9)) !important;
            backdrop-filter: blur(30px) !important;
            -webkit-backdrop-filter: blur(30px) !important;
            box-shadow:
                0 32px 64px rgba(0, 0, 0, 0.6),
                0 0 0 1px rgba(255, 255, 255, 0.05),
                inset 0 1px 0 rgba(255, 255, 255, 0.12) !important;
        }

        @keyframes containerSlideIn {
            from {
                opacity: 0;
                transform: translateY(30px) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .spamurai-header {
            text-align: center !important;
            margin-bottom: 24px !important;
            position: relative !important;
            padding-bottom: 16px !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.06) !important;
        }

        .spamurai-logo {
            background: linear-gradient(135deg, #ff0050 0%, #ff4458 25%, #ff6b35 50%, #ff8e53 75%, #ffad71 100%) !important;
            -webkit-background-clip: text !important;
            -webkit-text-fill-color: transparent !important;
            background-clip: text !important;
            font-size: 28px !important;
            font-weight: 700 !important;
            margin-bottom: 6px !important;
            letter-spacing: -1px !important;
            text-shadow: 0 0 30px rgba(255, 0, 80, 0.3) !important;
        }

        .spamurai-subtitle {
            color: rgba(255, 255, 255, 0.8) !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            margin-bottom: 4px !important;
        }

        .spamurai-version {
            color: rgba(255, 255, 255, 0.4) !important;
            font-size: 11px !important;
            font-weight: 400 !important;
        }

        .spamurai-close {
            position: absolute !important;
            top: -12px !important; right: -12px !important;
            background: rgba(255, 59, 92, 0.9) !important;
            border: 2px solid rgba(255, 255, 255, 0.1) !important;
            color: white !important;
            width: 32px !important; height: 32px !important;
            border-radius: 50% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            cursor: pointer !important;
            font-size: 14px !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            z-index: 1000001 !important;
            backdrop-filter: blur(20px) !important;
            -webkit-backdrop-filter: blur(20px) !important;
        }
        .spamurai-close:hover {
            background: rgba(255, 59, 92, 1) !important;
            transform: scale(1.1) rotate(90deg) !important;
            box-shadow: 0 8px 25px rgba(255, 59, 92, 0.4) !important;
        }
        .spamurai-close:active {
            transform: scale(0.95) rotate(90deg) !important;
        }

        .background-toggle {
            position: absolute !important;
            top: -12px !important; right: 28px !important;
            background: rgba(64, 224, 208, 0.9) !important;
            border: 2px solid rgba(255, 255, 255, 0.1) !important;
            color: white !important;
            width: 32px !important; height: 32px !important;
            border-radius: 50% !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            cursor: pointer !important;
            font-size: 14px !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            z-index: 1000001 !important;
            backdrop-filter: blur(20px) !important;
            -webkit-backdrop-filter: blur(20px) !important;
        }
        .background-toggle:hover {
            background: rgba(64, 224, 208, 1) !important;
            transform: scale(1.1) !important;
            box-shadow: 0 8px 25px rgba(64, 224, 208, 0.4) !important;
        }
        .background-toggle:active {
            transform: scale(0.95) !important;
        }
        .background-toggle.active {
            background: rgba(255, 165, 0, 0.9) !important;
        }
        .background-toggle.active:hover {
            background: rgba(255, 165, 0, 1) !important;
            box-shadow: 0 8px 25px rgba(255, 165, 0, 0.4) !important;
        }

        .stats-professional {
            display: grid !important;
            grid-template-columns: repeat(3, 1fr) !important;
            gap: 12px !important;
            margin-bottom: 20px !important;
        }

        .stat-card-pro {
            background: rgba(255, 255, 255, 0.02) !important;
            border: 1px solid rgba(255, 255, 255, 0.06) !important;
            border-radius: 12px !important;
            padding: 16px 12px !important;
            text-align: center !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            position: relative !important;
            overflow: hidden !important;
        }
        .stat-card-pro::before {
            content: '' !important;
            position: absolute !important;
            top: 0 !important; left: 0 !important;
            right: 0 !important; height: 2px !important;
            background: linear-gradient(90deg, transparent, rgba(255, 0, 80, 0.6), transparent) !important;
            opacity: 0 !important;
            transition: opacity 0.3s ease !important;
        }
        .stat-card-pro:hover {
            border-color: rgba(255, 0, 80, 0.3) !important;
            background: rgba(255, 0, 80, 0.03) !important;
            transform: translateY(-2px) !important;
        }
        .stat-card-pro:hover::before {
            opacity: 1 !important;
        }

        .stat-number-pro {
            color: #ff0050 !important;
            font-size: 20px !important;
            font-weight: 700 !important;
            line-height: 1.2 !important;
            margin-bottom: 4px !important;
        }

        .stat-label-pro {
            color: rgba(255, 255, 255, 0.6) !important;
            font-size: 10px !important;
            font-weight: 500 !important;
            text-transform: uppercase !important;
            letter-spacing: 0.8px !important;
        }

        .control-section {
            background: rgba(255, 255, 255, 0.02) !important;
            border: 1px solid rgba(255, 255, 255, 0.06) !important;
            border-radius: 16px !important;
            padding: 18px !important;
            margin-bottom: 16px !important;
        }

        .control-row-pro {
            display: flex !important;
            align-items: center !important;
            justify-content: space-between !important;
            margin-bottom: 12px !important;
        }
        .control-row-pro:last-child {
            margin-bottom: 0 !important;
        }

        .control-label-pro {
            color: rgba(255, 255, 255, 0.9) !important;
            font-size: 13px !important;
            font-weight: 600 !important;
            display: flex !important;
            align-items: center !important;
            gap: 8px !important;
        }

        .control-icon {
            color: #ff0050 !important;
            font-size: 14px !important;
        }

        .speed-control-pro {
            display: flex !important;
            align-items: center !important;
            gap: 8px !important;
        }

        .speed-display {
            background: rgba(255, 0, 80, 0.1) !important;
            border: 1px solid rgba(255, 0, 80, 0.2) !important;
            border-radius: 8px !important;
            padding: 6px 12px !important;
            color: #ff0050 !important;
            font-size: 11px !important;
            font-weight: 600 !important;
            cursor: pointer !important;
            transition: all 0.2s ease !important;
            text-transform: uppercase !important;
        }
        .speed-display:hover {
            background: rgba(255, 0, 80, 0.15) !important;
            border-color: rgba(255, 0, 80, 0.3) !important;
        }

        .toggle-professional {
            position: relative !important;
            width: 48px !important; height: 24px !important;
            background: rgba(255, 255, 255, 0.1) !important;
            border: 1px solid rgba(255, 255, 255, 0.15) !important;
            border-radius: 12px !important;
            cursor: pointer !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
        }
        .toggle-professional.active {
            background: linear-gradient(45deg, #ff0050, #ff4458) !important;
            border-color: rgba(255, 0, 80, 0.3) !important;
            box-shadow: 0 0 20px rgba(255, 0, 80, 0.3) !important;
        }

        .toggle-knob-pro {
            position: absolute !important;
            top: 1px !important; left: 1px !important;
            width: 20px !important; height: 20px !important;
            background: white !important;
            border-radius: 10px !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2) !important;
        }
        .toggle-professional.active .toggle-knob-pro {
            transform: translateX(24px) !important;
        }

        .status-grid {
            display: grid !important;
            grid-template-columns: repeat(4, 1fr) !important;
            gap: 8px !important;
            margin-bottom: 20px !important;
            padding: 12px !important;
            background: rgba(0, 0, 0, 0.2) !important;
            border: 1px solid rgba(255, 255, 255, 0.05) !important;
            border-radius: 12px !important;
        }

        .status-indicator {
            display: flex !important;
            flex-direction: column !important;
            align-items: center !important;
            gap: 4px !important;
        }

        .status-dot-pro {
            width: 8px !important; height: 8px !important;
            border-radius: 50% !important;
            transition: all 0.3s ease !important;
        }
        .status-dot-pro.active {
            background: #00ff88 !important;
            box-shadow: 0 0 12px rgba(0, 255, 136, 0.6) !important;
            animation: statusPulse 2s infinite !important;
        }
        .status-dot-pro.inactive {
            background: rgba(255, 255, 255, 0.2) !important;
        }
        .status-dot-pro.random {
            background: #ffaa00 !important;
            animation: randomPulse 1.5s infinite !important;
        }
        .status-dot-pro.background {
            background: #40e0d0 !important;
            animation: backgroundPulse 2s infinite !important;
        }

        @keyframes statusPulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.6; transform: scale(1.2); }
        }

        @keyframes randomPulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.7; transform: scale(1.1); }
        }

        @keyframes backgroundPulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.8; transform: scale(1.15); }
        }

        .status-text-pro {
            color: rgba(255, 255, 255, 0.7) !important;
            font-size: 8px !important;
            font-weight: 500 !important;
            text-transform: uppercase !important;
            text-align: center !important;
        }

        .btn-professional {
            width: 100% !important;
            padding: 14px 20px !important;
            border: none !important;
            border-radius: 12px !important;
            font-family: inherit !important;
            font-size: 13px !important;
            font-weight: 600 !important;
            cursor: pointer !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            margin-bottom: 10px !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            gap: 8px !important;
            text-transform: uppercase !important;
            letter-spacing: 0.5px !important;
            position: relative !important;
            overflow: hidden !important;
        }

        .btn-professional::before {
            content: '' !important;
            position: absolute !important;
            top: 0 !important; left: -100% !important;
            width: 100% !important; height: 100% !important;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent) !important;
            transition: left 0.6s ease !important;
        }
        .btn-professional:hover::before {
            left: 100% !important;
        }

        .btn-toggle {
            background: linear-gradient(135deg, #ff0050, #ff4458) !important;
            color: white !important;
            border: 1px solid rgba(255, 0, 80, 0.3) !important;
            box-shadow: 0 8px 25px rgba(255, 0, 80, 0.3) !important;
        }
        .btn-toggle:hover {
            transform: translateY(-2px) !important;
            box-shadow: 0 12px 35px rgba(255, 0, 80, 0.4) !important;
        }
        .btn-toggle:active {
            transform: translateY(0) !important;
        }

        .btn-toggle.running {
            background: linear-gradient(135deg, #ff3b5c, #ff6b6b) !important;
            border-color: rgba(255, 107, 107, 0.3) !important;
            box-shadow: 0 8px 25px rgba(255, 107, 107, 0.3) !important;
        }
        .btn-toggle.running:hover {
            box-shadow: 0 12px 35px rgba(255, 107, 107, 0.4) !important;
        }

        .btn-support {
            background: linear-gradient(135deg, #667eea, #764ba2) !important;
            color: white !important;
            border: 1px solid rgba(102, 126, 234, 0.3) !important;
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.2) !important;
            font-size: 11px !important;
            padding: 10px 16px !important;
        }
        .btn-support:hover {
            transform: translateY(-1px) !important;
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3) !important;
        }

        .mini-spamurai-button {
            position: fixed !important;
            bottom: 24px !important;
            right: 24px !important;
            width: 64px !important;
            height: 64px !important;
            background: linear-gradient(145deg, rgba(18, 18, 18, 0.9), rgba(28, 28, 30, 0.8)) !important;
            border: 2px solid #ff0050 !important;
            border-radius: 20px !important;
            color: #ff0050 !important;
            cursor: pointer !important;
            z-index: 999998 !important;
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
            font-size: 24px !important;
            font-weight: 700 !important;
            font-family: 'Inter', sans-serif !important;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
            backdrop-filter: blur(20px) !important;
            -webkit-backdrop-filter: blur(20px) !important;
            box-shadow: 0 12px 30px rgba(255, 0, 80, 0.3) !important;
        }
        .mini-spamurai-button:hover {
            transform: scale(1.05) translateY(-2px) !important;
            border-color: #ff4458 !important;
            box-shadow: 0 20px 45px rgba(255, 0, 80, 0.5) !important;
            background: linear-gradient(145deg, rgba(28, 28, 30, 0.9), rgba(18, 18, 18, 0.8)) !important;
        }

        .notification-pro {
            position: fixed !important;
            top: 20px !important; right: 20px !important;
            padding: 16px 20px !important;
            background: rgba(18, 18, 18, 0.98) !important;
            border: 1px solid rgba(255, 0, 80, 0.3) !important;
            border-radius: 12px !important;
            color: rgba(255, 255, 255, 0.9) !important;
            font-size: 13px !important;
            font-weight: 500 !important;
            z-index: 1000000 !important;
            backdrop-filter: blur(30px) !important;
            -webkit-backdrop-filter: blur(30px) !important;
            max-width: 320px !important;
            box-shadow: 0 12px 32px rgba(0, 0, 0, 0.6) !important;
            animation: notificationSlide 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important;
            font-family: 'Inter', sans-serif !important;
        }

        @keyframes notificationSlide {
            from { transform: translateX(100%) translateY(-10px); opacity: 0; }
            to { transform: translateX(0) translateY(0); opacity: 1; }
        }

        .footer-professional {
            text-align: center !important;
            margin-top: 16px !important;
            padding-top: 16px !important;
            border-top: 1px solid rgba(255, 255, 255, 0.06) !important;
        }

        .footer-text-pro {
            color: rgba(255, 255, 255, 0.4) !important;
            font-size: 10px !important;
            font-weight: 400 !important;
            margin-bottom: 4px !important;
        }

        .support-link-pro {
            color: #ff0050 !important;
            text-decoration: none !important;
            font-weight: 600 !important;
            transition: all 0.2s ease !important;
        }
        .support-link-pro:hover {
            color: #ff4458 !important;
            text-decoration: underline !important;
        }
    `;

    let isRunning = false;
    let modalSetupDone = false;
    let totalCopies = 0;
    let successCount = 0;
    let errorCount = 0;
    let copyInterval = null;
    let gui = null;
    let miniSpamurai = null;
    let lastFoundCopyButton = null;
    let startTime = null;
    let matrixCanvas = null;
    let matrixCtx = null;
    let matrixAnimation = null;
    let copyObserver = null;

    // ===== BACKGROUND TOGGLE FUNCTION =====
    function toggleBackground() {
        CONFIG.backgroundVisible = !CONFIG.backgroundVisible;

        const overlay = document.querySelector('.spamurai-overlay');
        const backgroundBtn = document.getElementById('background-toggle');

        if (overlay && backgroundBtn) {
            if (CONFIG.backgroundVisible) {
                overlay.classList.add('background-visible');
                backgroundBtn.classList.add('active');
                backgroundBtn.innerHTML = '<i class="fas fa-eye-slash"></i>';
                backgroundBtn.title = 'Hide Background';
                showNotification('Background visible - Click to hide', 'info');
                console.log('🌟 Background now visible');
            } else {
                overlay.classList.remove('background-visible');
                backgroundBtn.classList.remove('active');
                backgroundBtn.innerHTML = '<i class="fas fa-eye"></i>';
                backgroundBtn.title = 'Show Background';
                showNotification('Background hidden - Click to show', 'info');
                console.log('🌑 Background now hidden');
            }

            updateStats();
        }
    }

    // ===== ENHANCED MATRIX EFFECT =====
    function createMatrixCanvas() {
        matrixCanvas = document.createElement('canvas');
        matrixCanvas.className = 'matrix-canvas';
        matrixCanvas.width = window.innerWidth;
        matrixCanvas.height = window.innerHeight;
        matrixCtx = matrixCanvas.getContext('2d');

        const overlay = document.querySelector('.spamurai-overlay');
        if (overlay) {
            overlay.appendChild(matrixCanvas);
        }

        return matrixCanvas;
    }

    function startMatrixEffect() {
        if (!matrixCanvas) createMatrixCanvas();

        const chars = 'SPAMURAI01Alcazi';
        const fontSize = 14;
        const columns = Math.floor(matrixCanvas.width / fontSize);
        const drops = Array(columns).fill(1);

        function drawMatrix() {
            // Semi-transparent black background to create trail effect
            matrixCtx.fillStyle = 'rgba(0, 0, 0, 0.05)';
            matrixCtx.fillRect(0, 0, matrixCanvas.width, matrixCanvas.height);

            // Set text properties
            matrixCtx.fillStyle = '#ff0050';
            matrixCtx.font = `${fontSize}px 'Inter', monospace`;
            matrixCtx.shadowColor = '#ff0050';
            matrixCtx.shadowBlur = 8;

            // Draw characters
            for (let i = 0; i < drops.length; i++) {
                const text = chars[Math.floor(Math.random() * chars.length)];
                const x = i * fontSize;
                const y = drops[i] * fontSize;

                // Add some randomness to the glow
                matrixCtx.shadowBlur = Math.random() * 10 + 5;
                matrixCtx.fillText(text, x, y);

                // Reset drops when they reach bottom or randomly
                if (y > matrixCanvas.height && Math.random() > 0.975) {
                    drops[i] = 0;
                }
                drops[i]++;
            }
        }

        function animate() {
            drawMatrix();
            if (isRunning) {
                matrixAnimation = requestAnimationFrame(animate);
            }
        }

        animate();
    }

    function stopMatrixEffect() {
        if (matrixAnimation) {
            cancelAnimationFrame(matrixAnimation);
            matrixAnimation = null;
        }
        if (matrixCanvas && matrixCanvas.parentNode) {
            matrixCanvas.parentNode.removeChild(matrixCanvas);
            matrixCanvas = null;
            matrixCtx = null;
        }
    }

    // ===== KOPIERT COUNTER =====
    function startCopyObserver() {
        // Stop existing observer
        if (copyObserver) {
            copyObserver.disconnect();
        }

        copyObserver = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) { // Element node
                        // Check if this is the "Kopiert" notification
                        const kopiertElement = node.querySelector('.css-oe45gz-notice-content');
                        if (kopiertElement) {
                            const alertElement = kopiertElement.querySelector('[role="alert"]');
                            if (alertElement && alertElement.textContent.includes('Kopiert')) {
                                totalCopies++;
                                successCount++;
                                updateStats();

                                if (totalCopies % 5 === 0) {
                                    showNotification(`${totalCopies} shares completed!`, 'success');
                                }
                            }
                        }

                        // Also check direct matches
                        if (node.querySelector && node.querySelector('span')) {
                            const spans = node.querySelectorAll('span');
                            spans.forEach(span => {
                                if (span.textContent && span.textContent.trim() === 'Kopiert') {
                                    totalCopies++;
                                    successCount++;
                                    updateStats();
                                }
                            });
                        }
                    }
                });
            });
        });

        // Observe the entire document for changes
        copyObserver.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    function stopCopyObserver() {
        if (copyObserver) {
            copyObserver.disconnect();
            copyObserver = null;
        }
    }

    // ===== SPEED CONTROL =====
    function updateSpeed() {
        const speedLevels = [
            { interval: 2000, label: "Slow" },
            { interval: 1500, label: "Medium-" },
            { interval: 1000, label: "Medium" },
            { interval: 750, label: "Fast" },
            { interval: 500, label: "Ultra" }
        ];

        const level = speedLevels[CONFIG.speedLevel - 1];
        CONFIG.copyInterval = level.interval;

        const speedValue = document.getElementById('speed-value');
        if (speedValue) {
            speedValue.textContent = level.label;
        }

        if (isRunning && copyInterval) {
            clearInterval(copyInterval);
            startCopyInterval();
        }

        showNotification(`Speed: ${level.label}`, 'info');
    }

    function cycleSpeed() {
        CONFIG.speedLevel = CONFIG.speedLevel >= 5 ? 1 : CONFIG.speedLevel + 1;
        updateSpeed();
    }

    function getRandomInterval() {
        if (!CONFIG.randomMode) return CONFIG.copyInterval;
        const variance = CONFIG.randomVariance;
        const randomOffset = (Math.random() - 0.5) * 2 * variance;
        const interval = CONFIG.copyInterval + randomOffset;
        return Math.max(CONFIG.minInterval, Math.min(CONFIG.maxInterval, interval));
    }

    // ===== NOTIFICATION SYSTEM =====
    function showNotification(message, type = 'info') {
        const existingNotifications = document.querySelectorAll('.notification-pro');
        existingNotifications.forEach(notif => notif.remove());

        const notification = document.createElement('div');
        notification.className = 'notification-pro';

        let icon = '';
        switch(type) {
            case 'success': icon = '<i class="fas fa-check" style="color: #00ff88; margin-right: 8px;"></i>'; break;
            case 'error': icon = '<i class="fas fa-times" style="color: #ff6b6b; margin-right: 8px;"></i>'; break;
            case 'info': icon = '<i class="fas fa-info" style="color: #ff0050; margin-right: 8px;"></i>'; break;
        }

        notification.innerHTML = icon + message;
        document.body.appendChild(notification);

        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 4000);
    }

    // ===== MODAL OPENING =====
    function findShareButton() {
        const selectors = [
            'i[data-e2e="share-icon"]',
            '[data-e2e="share-icon"]',
            'button[data-e2e="share-icon"]',
            '[role="button"][data-e2e="share-icon"]',
            'div[data-e2e="share-icon"]'
        ];

        for (const selector of selectors) {
            const elements = document.querySelectorAll(selector);
            for (const element of elements) {
                const rect = element.getBoundingClientRect();
                if (rect.width > 0 && rect.height > 0) {
                    return element;
                }
            }
        }
        return null;
    }

    function openModalFixed() {
        return new Promise(async (resolve) => {
            try {
                const shareButton = findShareButton();
                if (!shareButton) {
                    showNotification('Share button not found!', 'error');
                    resolve(false);
                    return;
                }

                shareButton.scrollIntoView({ behavior: 'instant', block: 'center' });
                await sleep(300);

                const rect = shareButton.getBoundingClientRect();
                const x = rect.left + rect.width / 2;
                const y = rect.top + rect.height / 2;

                const events = [
                    new MouseEvent('mouseenter', { bubbles: true, clientX: x, clientY: y }),
                    new MouseEvent('mouseover', { bubbles: true, clientX: x, clientY: y }),
                    new MouseEvent('mousemove', { bubbles: true, clientX: x, clientY: y })
                ];

                events.forEach((event, i) => {
                    setTimeout(() => {
                        try {
                            shareButton.dispatchEvent(event);
                        } catch (e) {}
                    }, i * 100);
                });

                await sleep(800);

                try {
                    shareButton.click();
                } catch (e) {
                    showNotification('Click failed', 'error');
                }

                await sleep(1200);
                modalSetupDone = true;
                resolve(true);

            } catch (error) {
                showNotification('Modal failed', 'error');
                resolve(false);
            }
        });
    }

    // ===== COPY BUTTON SEARCH =====
    function findCopyButton() {
        const copyButtons = document.querySelectorAll('button, div[role="button"], a');

        for (const button of copyButtons) {
            const text = button.textContent?.toLowerCase() || '';
            const title = button.title?.toLowerCase() || '';
            const ariaLabel = button.getAttribute('aria-label')?.toLowerCase() || '';

            if (text.includes('link kopieren') ||
                text.includes('copy link') ||
                title.includes('kopieren') ||
                title.includes('copy') ||
                ariaLabel.includes('kopieren') ||
                ariaLabel.includes('copy')) {

                const rect = button.getBoundingClientRect();
                if (rect.width > 10 && rect.height > 10) {
                    return button;
                }
            }
        }
        return null;
    }

    function performCopy() {
        return new Promise(async (resolve) => {
            try {
                const copyButton = findCopyButton();
                if (!copyButton) {
                    resolve(false);
                    return;
                }

                for (let i = 0; i < 3; i++) {
                    try {
                        copyButton.click();
                        await sleep(50);
                    } catch (e) {}
                }

                resolve(true);

            } catch (error) {
                resolve(false);
            }
        });
    }

    // ===== MAIN BOT LOGIC =====
    function performSpamuraiAction() {
        return new Promise(async (resolve) => {
            try {
                if (!window.location.href.includes('/live')) {
                    showNotification('Not in live stream!', 'error');
                    stopSpamurai();
                    resolve(false);
                    return;
                }

                if (!modalSetupDone) {
                    const modalSuccess = await openModalFixed();
                    if (!modalSuccess) {
                        resolve(false);
                        return;
                    }
                }

                const success = await performCopy();
                resolve(success);

            } catch (error) {
                resolve(false);
            }
        });
    }

    function startCopyInterval() {
        const interval = getRandomInterval();
        copyInterval = setTimeout(() => {
            if (isRunning) {
                performSpamuraiAction().then(() => {
                    if (isRunning) {
                        startCopyInterval();
                    }
                });
            }
        }, interval);
    }

    function toggleSpamurai() {
        if (isRunning) {
            stopSpamurai();
        } else {
            startSpamurai();
        }
    }

    function startSpamurai() {
        if (isRunning) return;

        if (!window.location.href.includes('/live')) {
            showNotification('Please navigate to a TikTok Live stream first!', 'error');
            return;
        }

        isRunning = true;
        modalSetupDone = false;
        totalCopies = 0;
        successCount = 0;
        errorCount = 0;
        startTime = Date.now();

        startMatrixEffect();
        startCopyObserver();
        startCopyInterval();
        updateStats();
        updateButtons();

        showNotification('Spamurai Pro ACTIVATED with Matrix Effect!', 'success');
    }

    function stopSpamurai() {
        if (!isRunning) return;

        isRunning = false;
        modalSetupDone = false;

        if (copyInterval) {
            clearTimeout(copyInterval);
            copyInterval = null;
        }

        stopMatrixEffect();
        stopCopyObserver();

        const runtime = startTime ? ((Date.now() - startTime) / 1000).toFixed(1) : 0;
        showNotification(`Stopped. Runtime: ${runtime}s, Total: ${totalCopies}`, 'info');

        updateStats();
        updateButtons();
    }

    // ===== UTILITY =====
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // ===== FORCE HIDE GUI FUNCTION =====
    function forceHideGUI() {
        console.log('🚀 FORCE HIDE GUI CALLED!');
        try {
            // Remove the overlay completely
            const overlay = document.querySelector('.spamurai-overlay');
            if (overlay) {
                overlay.remove();
                console.log('✅ Overlay removed!');
            }

            // Reset GUI variable
            gui = null;

            // Show mini button
            if (miniSpamurai) {
                miniSpamurai.style.display = 'block';
                console.log('✅ Mini button shown!');
            } else {
                createMiniButton();
                console.log('✅ Mini button recreated!');
            }
        } catch (error) {
            console.error('❌ Force hide error:', error);
        }
    }

    // ===== MINI BUTTON =====
    function createMiniButton() {
        const existing = document.querySelector('.mini-spamurai-button');
        if (existing) existing.remove();

        miniSpamurai = document.createElement('button');
        miniSpamurai.className = 'mini-spamurai-button';
        miniSpamurai.innerHTML = 'S';
        miniSpamurai.title = 'Spamurai Pro v1.3 - Alcazi Edition - 2025-05-30 11:26:59';

        miniSpamurai.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            showGUI();
        });

        document.body.appendChild(miniSpamurai);
    }

    function createGUI() {
        // Force remove any existing GUI
        const existing = document.querySelector('.spamurai-overlay');
        if (existing) existing.remove();

        gui = document.createElement('div');
        gui.className = 'spamurai-overlay';
        gui.style.display = 'none';

        gui.innerHTML = `
            <div class="spamurai-container">
                <div class="spamurai-header">
                    <div class="spamurai-logo">SPAMURAI PRO</div>
                    <div class="spamurai-subtitle">Professional TikTok Share Bot</div>
                    <div class="spamurai-version">v1.3 • Alcazi Edition • 2025-05-30 11:26:59</div>
                    <button class="background-toggle" id="background-toggle" title="Show Background">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="spamurai-close" id="close-gui" title="Close Spamurai">
                        <i class="fas fa-times"></i>
                    </button>
                </div>

                <div class="stats-professional">
                    <div class="stat-card-pro">
                        <div class="stat-number-pro" id="copy-count">0</div>
                        <div class="stat-label-pro">Total Shares</div>
                    </div>
                    <div class="stat-card-pro">
                        <div class="stat-number-pro" id="success-count">0</div>
                        <div class="stat-label-pro">Successful</div>
                    </div>
                    <div class="stat-card-pro">
                        <div class="stat-number-pro" id="success-rate">0%</div>
                        <div class="stat-label-pro">Success Rate</div>
                    </div>
                </div>

                <div class="control-section">
                    <div class="control-row-pro">
                        <div class="control-label-pro">
                            <i class="fas fa-tachometer-alt control-icon"></i>
                            Speed
                        </div>
                        <div class="speed-control-pro">
                            <div class="speed-display" id="speed-value">Medium</div>
                        </div>
                    </div>
                    <div class="control-row-pro">
                        <div class="control-label-pro">
                            <i class="fas fa-dice control-icon"></i>
                            Anti-Detection Mode
                        </div>
                        <div class="toggle-professional active" id="random-switch">
                            <div class="toggle-knob-pro"></div>
                        </div>
                    </div>
                </div>

                <div class="status-grid">
                    <div class="status-indicator">
                        <div class="status-dot-pro" id="status-dot"></div>
                        <span class="status-text-pro" id="status-text">Offline</span>
                    </div>
                    <div class="status-indicator">
                        <div class="status-dot-pro" id="random-dot"></div>
                        <span class="status-text-pro">Random</span>
                    </div>
                    <div class="status-indicator">
                        <div class="status-dot-pro" id="live-dot"></div>
                        <span class="status-text-pro">Live</span>
                    </div>
                    <div class="status-indicator">
                        <div class="status-dot-pro" id="background-dot"></div>
                        <span class="status-text-pro">View</span>
                    </div>
                </div>

                <button class="btn-professional btn-toggle" id="toggle-btn">
                    <i class="fas fa-play" id="toggle-icon"></i>
                    <span id="toggle-text">START SPAMURAI</span>
                </button>

                <button class="btn-professional btn-support" id="donate-btn">
                    <i class="fas fa-coffee"></i> Support Developer
                </button>

                <div class="footer-professional">
                    <div class="footer-text-pro">Professional TikTok Automation Tool with Background Toggle</div>
                    <div class="footer-text-pro">
                        Support: <a href="https://t.me/A1cazi" class="support-link-pro" target="_blank">@A1cazi</a>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(gui);
        setupEventListeners();
        updateSpeed();
    }

    function setupEventListeners() {
        try {
            console.log('🔧 Setting up event listeners...');

            // ✅ ULTIMATE CLOSE BUTTON FIX - Multiple methods
            const closeBtn = document.getElementById('close-gui');
            if (closeBtn) {
                console.log('🎯 Close button found, setting up listeners...');

                // Method 1: Direct onclick
                closeBtn.onclick = function(e) {
                    console.log('🔥 Method 1: Direct onclick triggered!');
                    e.preventDefault();
                    e.stopPropagation();
                    forceHideGUI();
                    return false;
                };

                // Method 2: addEventListener click
                closeBtn.addEventListener('click', function(e) {
                    console.log('🔥 Method 2: addEventListener triggered!');
                    e.preventDefault();
                    e.stopPropagation();
                    forceHideGUI();
                }, { once: false, capture: true });

                // Method 3: addEventListener mousedown
                closeBtn.addEventListener('mousedown', function(e) {
                    console.log('🔥 Method 3: mousedown triggered!');
                    e.preventDefault();
                    e.stopPropagation();
                    forceHideGUI();
                }, { once: false, capture: true });

                // Method 4: Touch events for mobile
                closeBtn.addEventListener('touchstart', function(e) {
                    console.log('🔥 Method 4: touchstart triggered!');
                    e.preventDefault();
                    e.stopPropagation();
                    forceHideGUI();
                }, { once: false, capture: true });

                console.log('✅ All close button listeners attached!');
            } else {
                console.error('❌ Close button not found!');
            }

            // ✅ NEW: Background Toggle Button
            const backgroundBtn = document.getElementById('background-toggle');
            if (backgroundBtn) {
                console.log('🎯 Background button found, setting up listeners...');

                backgroundBtn.onclick = function(e) {
                    console.log('🔥 Background toggle clicked!');
                    e.preventDefault();
                    e.stopPropagation();
                    toggleBackground();
                    return false;
                };

                backgroundBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleBackground();
                }, { once: false, capture: true });

                console.log('✅ Background toggle listeners attached!');
            }

            // Toggle button (Start/Stop)
            const toggleBtn = document.getElementById('toggle-btn');
            if (toggleBtn) {
                toggleBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleSpamurai();
                });
            }

            // Speed control
            const speedValue = document.getElementById('speed-value');
            if (speedValue) {
                speedValue.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    cycleSpeed();
                });
            }

            // Random toggle
            const randomSwitch = document.getElementById('random-switch');
            if (randomSwitch) {
                randomSwitch.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    CONFIG.randomMode = !CONFIG.randomMode;
                    randomSwitch.classList.toggle('active', CONFIG.randomMode);
                    updateStats();
                    showNotification(`Anti-Detection ${CONFIG.randomMode ? 'ENABLED' : 'DISABLED'}`, 'info');
                });
            }

            // Donate button
            const donateBtn = document.getElementById('donate-btn');
            if (donateBtn) {
                donateBtn.addEventListener('click', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    try {
                        window.open('https://buymeacoffee.com/alcazi', '_blank');
                        showNotification('Thank you for your support! ❤️', 'success');
                    } catch (e) {
                        showNotification('Could not open donation link', 'error');
                    }
                });
            }

            // Overlay click to close (backup method)
            const overlay = document.querySelector('.spamurai-overlay');
            if (overlay) {
                overlay.addEventListener('click', (e) => {
                    if (e.target === overlay) {
                        console.log('🔥 Overlay click triggered!');
                        forceHideGUI();
                    }
                });
            }

            // ESC key to close
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && gui && gui.style.display === 'flex') {
                    console.log('🔥 ESC key triggered!');
                    forceHideGUI();
                }
            });

            console.log('✅ All event listeners setup complete!');

        } catch (error) {
            console.error('❌ Event listener error:', error);
        }
    }

    function showGUI() {
        try {
            if (!gui) createGUI();
            gui.style.display = 'flex';
            if (miniSpamurai) miniSpamurai.style.display = 'none';
            updateStats();
            console.log('✅ GUI shown successfully!');
        } catch (error) {
            console.error('❌ Show GUI error:', error);
        }
    }

    function hideGUI() {
        try {
            console.log('🔧 hideGUI called (legacy method)');
            forceHideGUI(); // Use the force method instead
        } catch (error) {
            console.error('❌ Hide GUI error:', error);
        }
    }

    function updateStats() {
        try {
            const elements = {
                'copy-count': totalCopies,
                'success-count': successCount,
                'success-rate': totalCopies > 0 ? Math.round((successCount / totalCopies) * 100) + '%' : '0%'
            };

            Object.entries(elements).forEach(([id, value]) => {
                const el = document.getElementById(id);
                if (el) el.textContent = value;
            });

            const statusDot = document.getElementById('status-dot');
            const statusText = document.getElementById('status-text');
            if (statusDot && statusText) {
                if (isRunning) {
                    statusDot.className = 'status-dot-pro active';
                    statusText.textContent = modalSetupDone ? 'Active' : 'Setup';
                } else {
                    statusDot.className = 'status-dot-pro inactive';
                    statusText.textContent = 'Offline';
                }
            }

            const randomDot = document.getElementById('random-dot');
            if (randomDot) {
                randomDot.className = CONFIG.randomMode ? 'status-dot-pro random' : 'status-dot-pro inactive';
            }

            const liveDot = document.getElementById('live-dot');
            if (liveDot) {
                const inLive = window.location.href.includes('/live');
                liveDot.className = inLive ? 'status-dot-pro active' : 'status-dot-pro inactive';
            }

            // NEW: Background status dot
            const backgroundDot = document.getElementById('background-dot');
            if (backgroundDot) {
                backgroundDot.className = CONFIG.backgroundVisible ? 'status-dot-pro background' : 'status-dot-pro inactive';
            }
        } catch (error) {
            console.error('Stats update error:', error);
        }
    }

    function updateButtons() {
        try {
            const toggleBtn = document.getElementById('toggle-btn');
            const toggleIcon = document.getElementById('toggle-icon');
            const toggleText = document.getElementById('toggle-text');

            if (toggleBtn && toggleIcon && toggleText) {
                if (isRunning) {
                    toggleBtn.classList.add('running');
                    toggleIcon.className = 'fas fa-stop';
                    toggleText.textContent = 'STOP SPAMURAI';
                } else {
                    toggleBtn.classList.remove('running');
                    toggleIcon.className = 'fas fa-play';
                    toggleText.textContent = 'START SPAMURAI';
                }
            }
        } catch (error) {
            console.error('Button update error:', error);
        }
    }

    // ===== INIT =====
    function init() {
        try {
            const style = document.createElement('style');
            style.textContent = CSS;
            document.head.appendChild(style);

            setTimeout(() => {
                createMiniButton();
                setInterval(updateStats, 1000);
                showNotification('Spamurai Pro v1.3 with Background Toggle loaded! 🚀', 'success');
                console.log('🚀 Spamurai Pro v1.3 - Alcazi Edition with Background Toggle initialized!');
            }, 1000);
        } catch (error) {
            console.error('Init error:', error);
        }
    }

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

    // SPA Handler
    let lastUrl = location.href;
    new MutationObserver(() => {
        const url = location.href;
        if (url !== lastUrl) {
            lastUrl = url;
            setTimeout(() => {
                if (!document.querySelector('.mini-spamurai-button')) {
                    createMiniButton();
                }
            }, 1000);
        }
    }).observe(document, { subtree: true, childList: true });

})();