LonKeyDotae / BREAK OUT - Enhanced

// ==UserScript==
// @name         BREAK OUT - Enhanced
// @namespace    http://tampermonkey.net/
// @version      2025-10-26-enhanced
// @description  Configure and automate Google Takeout form interactions with enhanced click handling
// @author       You
// @match        https://takeout.google.com/manage
// @icon         https://www.google.com/s2/favicons?sz=64&domain=google.com
// @grant        unsafeWindow
// @grant        GM.notification
// @grant        GM.registerMenuCommand
// @license      MIT
// ==/UserScript==

/* jshint esversion: 8 */
/* eslint-env es2017 */

(function() {
    'use strict';
    
    // CONFIGURATION - Edit these elements to match what you want to click
    const elementsToClick = [
        {
            "element": "<div class=\"VfPpkd-Jh9lGc\"></div>",
            "delay": 5,
            "description": "Main button"
        },
        {
            "element": "<button class=\"VfPpkd-LgbsSe\"></button>",
            "delay": 3,
            "description": "Confirmation button"
        }
    ];
    
    const TIMEOUT_SECONDS = 15;
    
    // Banner management
    let currentBanner = null;
    let debugLog = [];
    
    function logDebug(message) {
        debugLog.push(message);
        console.log(message);
    }
    
    function createDebugBanner(message, color = '#00ff00', showLog = false) {
        if (currentBanner) {
            currentBanner.remove();
        }
        const banner = document.createElement('div');
        banner.id = 'breakout-banner';
        banner.style.cssText = `
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            right: 0 !important;
            background: black !important;
            color: ${color} !important;
            padding: 20px !important;
            font-size: 18px !important;
            font-weight: bold !important;
            z-index: 2147483647 !important;
            text-align: center !important;
            font-family: monospace !important;
            border-bottom: 3px solid ${color} !important;
            max-height: 200px !important;
            overflow-y: auto !important;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5) !important;
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
        `;
        
        if (showLog && debugLog.length > 0) {
            const logText = debugLog.slice(-5).join('\n');
            banner.innerHTML = `<div style="font-size: 14px; margin-bottom: 10px;">${logText.replace(/\n/g, '<br>')}</div><div>${message}</div>`;
        } else {
            banner.textContent = message;
        }
        
        // Force append even if body isn't ready
        if (document.body) {
            document.body.appendChild(banner);
        } else {
            document.addEventListener('DOMContentLoaded', () => {
                document.body.appendChild(banner);
            });
        }
        
        currentBanner = banner;
        console.log('[BANNER] Banner created:', message);
        return banner;
    }
    
    function updateBanner(message, color) {
        console.log('[BANNER] Updating banner:', message, 'color:', color);
        if (currentBanner) {
            currentBanner.textContent = message;
            currentBanner.style.color = color + ' !important';
            currentBanner.style.borderBottomColor = color + ' !important';
            currentBanner.style.display = 'block !important';
            console.log('[OK] Banner updated successfully');
        } else {
            console.log('[WARN] No banner exists, creating new one');
            createDebugBanner(message, color);
        }
    }
    
    // Show initial load message
    console.log('[BREAK OUT] Attempting to create initial banner...');
    
    // Try immediately
    if (document.body) {
        createDebugBanner('BREAK OUT ENHANCED - Ready with advanced click handling', '#00ff00');
    } else {
        // Retry when DOM is ready
        console.log('[WAIT] Waiting for document.body...');
        const checkBody = setInterval(() => {
            if (document.body) {
                clearInterval(checkBody);
                createDebugBanner('BREAK OUT ENHANCED - Ready with advanced click handling', '#00ff00');
                console.log('[OK] Banner created after waiting for body');
            }
        }, 100);
    }
    
    console.log('=================================');
    console.log('BREAK OUT ENHANCED SCRIPT LOADED');
    console.log('=================================');
    
    // Function to get all event listeners (Chrome DevTools API)
    function getEventListeners(element) {
        console.log('[EVENTS] Checking for event listeners:');
        try {
            // This only works in Chrome DevTools
            if (unsafeWindow.getEventListeners) {
                const listeners = unsafeWindow.getEventListeners(element);
                console.log('  Found listeners:', Object.keys(listeners));
                for (const [eventType, handlers] of Object.entries(listeners)) {
                    console.log(`  - ${eventType}: ${handlers.length} handler(s)`);
                }
                return listeners;
            } else {
                console.log('  [WARN] getEventListeners not available (not in DevTools)');
            }
        } catch (e) {
            console.warn('  [FAIL] Could not retrieve listeners:', e.message);
        }
        return null;
    }
    
    // Function to extract selector from HTML string
    function extractSelector(htmlString) {
        const classMatch = htmlString.match(/class=["']([^"']+)["']/);
        if (classMatch) {
            const classes = classMatch[1].split(' ').map(c => `.${c}`).join('');
            return classes;
        }
        
        const tagMatch = htmlString.match(/<(\w+)/);
        return tagMatch ? tagMatch[1] : null;
    }
    
    // Function to highlight element
    function highlightElement(element) {
        element.style.outline = '3px solid red';
        element.style.backgroundColor = 'rgba(255, 255, 0, 0.3)';
        element.style.transition = 'all 0.3s ease';
    }
    
    // Function to remove highlight
    function removeHighlight(element) {
        element.style.outline = '';
        element.style.backgroundColor = '';
    }
    
    // Function to wait/delay
    function wait(seconds) {
        return new Promise(resolve => setTimeout(resolve, seconds * 1000));
    }
    
    // Wait for element to appear in the DOM
    function waitForElement(selector, timeout) {
        return new Promise((resolve, reject) => {
            if (document.querySelector(selector)) {
                return resolve(document.querySelector(selector));
            }

            const observer = new MutationObserver(() => {
                if (document.querySelector(selector)) {
                    observer.disconnect();
                    resolve(document.querySelector(selector));
                }
            });

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

            setTimeout(() => {
                observer.disconnect();
                reject(new Error(`Timeout waiting for element: ${selector}`));
            }, timeout * 1000);
        });
    }
    
    // Diagnostic function to check element properties
    function diagnoseElement(element) {
        const rect = element.getBoundingClientRect();
        const style = window.getComputedStyle(element);
        
        console.log('[INSPECT] Element Diagnosis:');
        console.log('  - Tag:', element.tagName);
        console.log('  - Classes:', element.className);
        console.log('  - ID:', element.id || 'none');
        console.log('  - Visible:', style.visibility !== 'hidden');
        console.log('  - Display:', style.display);
        console.log('  - Opacity:', style.opacity);
        console.log('  - Size:', rect.width, 'x', rect.height);
        console.log('  - Position:', rect.left, rect.top);
        console.log('  - Disabled:', element.disabled);
        console.log('  - Pointer Events:', style.pointerEvents);
        console.log('  - Z-Index:', style.zIndex);
        
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        const elementAtPoint = document.elementFromPoint(centerX, centerY);
        console.log('  - Element at center point:', elementAtPoint?.tagName, elementAtPoint?.className);
        console.log('  - Is same element:', elementAtPoint === element);
        
        // Check for event listeners (requires Chrome/Edge)
        console.log('  - onclick attribute:', element.getAttribute('onclick') || 'none');
        console.log('  - onclick property:', element.onclick ? 'exists' : 'none');
        
        // Check for Angular/React/Vue attributes
        const ngClick = element.getAttribute('ng-click');
        const reactClick = Object.keys(element).find(k => k.startsWith('__react'));
        const vueClick = element.__vue__;
        
        console.log('  - ng-click:', ngClick || 'none');
        console.log('  - React handlers:', reactClick ? 'exists' : 'none');
        console.log('  - Vue instance:', vueClick ? 'exists' : 'none');
        
        // Check for data attributes that might indicate handlers
        const dataAttrs = Array.from(element.attributes)
            .filter(attr => attr.name.startsWith('data-'))
            .map(attr => `${attr.name}="${attr.value}"`);
        console.log('  - Data attributes:', dataAttrs.join(', ') || 'none');
        
        // Get event listeners
        getEventListeners(element);
        
        return {
            rect,
            style,
            elementAtPoint,
            isBlocked: elementAtPoint !== element,
            hasNgClick: !!ngClick,
            hasReact: !!reactClick,
            hasVue: !!vueClick
        };
    }
    
    // Find clickable parent element
    function findClickableParent(element) {
        let current = element;
        let depth = 0;
        const maxDepth = 5;
        
        while (current && current !== document.body && depth < maxDepth) {
            const hasClickHandler = current.onclick || 
                                   current.getAttribute('onclick') ||
                                   current.hasAttribute('ng-click') ||
                                   current.hasAttribute('data-click');
            
            const isClickable = current.tagName === 'BUTTON' || 
                               current.tagName === 'A' ||
                               current.getAttribute('role') === 'button' ||
                               current.getAttribute('role') === 'link' ||
                               hasClickHandler;
            
            if (isClickable) {
                console.log(`[OK] Found clickable parent at depth ${depth}:`, current.tagName, current.className);
                return current;
            }
            
            current = current.parentElement;
            depth++;
        }
        
        console.log('[WARN] No clickable parent found, using original element');
        return element;
    }
    
    // Enhanced click function with multiple methods
    async function clickElement(element, description) {
        console.log(`\n[TARGET] Attempting enhanced click on: ${description}`);
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        
        // Diagnose the element first
        const diagnosis = diagnoseElement(element);
        
        // Check if element is actually clickable
        const rect = diagnosis.rect;
        const style = diagnosis.style;
        const clickable = rect.width > 0 && rect.height > 0 && 
                          style.visibility !== 'hidden' &&
                          style.display !== 'none' &&
                          style.opacity !== '0';
        
        if (!clickable) {
            console.warn('[WARN] Element not clickable (hidden, 0 size, or invisible)');
            return false;
        }
        
        // Try to find better click target if current element is blocked
        let clickTarget = element;
        if (diagnosis.isBlocked) {
            console.warn('[WARN] Element is blocked by another element, trying parent...');
            clickTarget = findClickableParent(element);
            
            // Re-diagnose the new target
            if (clickTarget !== element) {
                console.log('[RETRY] Using alternative click target');
                diagnoseElement(clickTarget);
            }
        }
        
        // Step 1: Scroll into view
        console.log('Step 1: Scrolling element into view');
        clickTarget.scrollIntoView({ behavior: 'smooth', block: 'center' });
        await wait(0.5);
        
        // Step 2: Focus the element
        if (clickTarget.focus) {
            console.log('Step 2: Focusing element');
            clickTarget.focus();
            await wait(0.2);
        }
        
        // Step 3: Remove any potential overlays
        console.log('Step 3: Checking for overlays');
        const targetRect = clickTarget.getBoundingClientRect();
        const centerX = targetRect.left + targetRect.width / 2;
        const centerY = targetRect.top + targetRect.height / 2;
        
        // Step 4: Try PointerEvents (modern standard, best for Material Design)
        console.log('Step 4: Dispatching PointerEvents');
        try {
            const pointerDownEvent = new PointerEvent('pointerdown', {
                bubbles: true,
                cancelable: true,
                view: unsafeWindow,
                pointerId: 1,
                pointerType: 'mouse',
                isPrimary: true,
                clientX: centerX,
                clientY: centerY
            });
            clickTarget.dispatchEvent(pointerDownEvent);
            await wait(0.1);
            
            const pointerUpEvent = new PointerEvent('pointerup', {
                bubbles: true,
                cancelable: true,
                view: unsafeWindow,
                pointerId: 1,
                pointerType: 'mouse',
                isPrimary: true,
                clientX: centerX,
                clientY: centerY
            });
            clickTarget.dispatchEvent(pointerUpEvent);
            await wait(0.1);
            
            console.log('  [SUCCESS] PointerEvents dispatched');
        } catch (e) {
            console.warn('  [FAIL] PointerEvents failed:', e.message);
        }
        
        // Step 5: MouseEvents with proper coordinates
        console.log('Step 5: Dispatching MouseEvents sequence');
        try {
            const mouseEvents = ['mouseenter', 'mouseover', 'mousedown', 'mouseup', 'click'];
            for (const eventType of mouseEvents) {
                const evt = new MouseEvent(eventType, {
                    bubbles: true,
                    cancelable: true,
                    view: unsafeWindow,
                    button: 0,
                    buttons: eventType === 'mousedown' ? 1 : 0,
                    clientX: centerX,
                    clientY: centerY,
                    screenX: centerX,
                    screenY: centerY
                });
                clickTarget.dispatchEvent(evt);
                await wait(0.05);
            }
            console.log('  [SUCCESS] MouseEvents sequence completed');
        } catch (e) {
            console.warn('  [FAIL] MouseEvents failed:', e.message);
        }
        
        // Step 6: Native click() method
        console.log('Step 6: Native click() method');
        try {
            clickTarget.click();
            console.log('  [SUCCESS] Native click() executed');
        } catch (e) {
            console.warn('  [FAIL] Native click() failed:', e.message);
        }
        
        // Step 7: Touch events for mobile compatibility
        console.log('Step 7: Touch events (mobile compatibility)');
        try {
            const touchObj = new Touch({
                identifier: Date.now(),
                target: clickTarget,
                clientX: centerX,
                clientY: centerY,
                radiusX: 2.5,
                radiusY: 2.5,
                rotationAngle: 0,
                force: 1
            });
            
            const touchStartEvent = new TouchEvent('touchstart', {
                bubbles: true,
                cancelable: true,
                view: unsafeWindow,
                touches: [touchObj],
                targetTouches: [touchObj],
                changedTouches: [touchObj]
            });
            clickTarget.dispatchEvent(touchStartEvent);
            await wait(0.1);
            
            const touchEndEvent = new TouchEvent('touchend', {
                bubbles: true,
                cancelable: true,
                view: unsafeWindow,
                touches: [],
                targetTouches: [],
                changedTouches: [touchObj]
            });
            clickTarget.dispatchEvent(touchEndEvent);
            console.log('  [SUCCESS] Touch events dispatched');
        } catch (e) {
            console.warn('  [FAIL] Touch events failed:', e.message);
        }
        
        // Step 8: Try direct event handlers
        console.log('Step 8: Checking for direct event handlers');
        if (clickTarget.onclick) {
            try {
                console.log('  --> Invoking onclick handler directly');
                clickTarget.onclick.call(clickTarget, new MouseEvent('click', { bubbles: true }));
                console.log('  [SUCCESS] onclick handler invoked');
            } catch (e) {
                console.warn('  [FAIL] onclick handler failed:', e.message);
            }
        }
        
        // Step 9: Try Angular-specific click trigger
        console.log('Step 9: Angular/framework-specific triggers');
        if (diagnosis.hasNgClick) {
            try {
                console.log('  --> Triggering Angular click');
                const ngClickAttr = clickTarget.getAttribute('ng-click');
                console.log('  --> ng-click value:', ngClickAttr);
                // Try to get Angular scope and execute
                const scope = unsafeWindow.angular?.element(clickTarget).scope();
                if (scope) {
                    scope.$apply(() => {
                        scope.$eval(ngClickAttr);
                    });
                    console.log('  [SUCCESS] Angular click triggered');
                }
            } catch (e) {
                console.warn('  [FAIL] Angular trigger failed:', e.message);
            }
        }
        
        // Step 10: Try to trigger React handlers
        if (diagnosis.hasReact) {
            try {
                console.log('  --> Attempting React handler trigger');
                const reactKey = Object.keys(clickTarget).find(k => k.startsWith('__react'));
                if (reactKey) {
                    const reactProps = clickTarget[reactKey];
                    console.log('  --> Found React props:', reactProps);
                }
            } catch (e) {
                console.warn('  [FAIL] React trigger failed:', e.message);
            }
        }
        
        // Step 11: Dispatch all related events in proper sequence
        console.log('Step 11: Complete event sequence (including input events)');
        try {
            const eventSequence = [
                'mouseenter', 'mouseover', 'mousemove', 
                'mousedown', 'focusin', 'focus',
                'mouseup', 'click', 
                'focusout', 'blur'
            ];
            
            for (const eventType of eventSequence) {
                const evt = new MouseEvent(eventType, {
                    bubbles: true,
                    cancelable: true,
                    view: unsafeWindow,
                    button: 0,
                    buttons: eventType === 'mousedown' ? 1 : 0,
                    clientX: centerX,
                    clientY: centerY
                });
                clickTarget.dispatchEvent(evt);
                
                // Also dispatch on unsafeWindow if different
                if (unsafeWindow !== window) {
                    const unsafeEvt = unsafeWindow.document.createEvent('MouseEvents');
                    unsafeEvt.initMouseEvent(
                        eventType, true, true, unsafeWindow, 
                        0, 0, 0, centerX, centerY, 
                        false, false, false, false, 0, null
                    );
                    clickTarget.dispatchEvent(unsafeEvt);
                }
            }
            console.log('  [SUCCESS] Complete event sequence dispatched');
        } catch (e) {
            console.warn('  [FAIL] Event sequence failed:', e.message);
        }
        
        // Step 12: Try clicking ALL child elements (sometimes the actual handler is on a child)
        console.log('Step 12: Attempting click on all clickable children');
        try {
            const clickableChildren = clickTarget.querySelectorAll('button, a, [role="button"], [onclick]');
            console.log(`  --> Found ${clickableChildren.length} clickable children`);
            if (clickableChildren.length > 0 && clickableChildren.length < 5) {
                for (const child of clickableChildren) {
                    console.log(`  --> Clicking child: ${child.tagName}.${child.className}`);
                    child.click();
                    await wait(0.1);
                }
                console.log('  [SUCCESS] Child clicks completed');
            }
        } catch (e) {
            console.warn('  [FAIL] Child click failed:', e.message);
        }
        
        // Step 13: Nuclear option - try to submit any parent form
        console.log('Step 13: Checking for parent form');
        try {
            let parentForm = clickTarget.closest('form');
            if (parentForm) {
                console.log('  --> Found parent form, checking submit');
                // Don't actually submit, just log it
                console.log('  [WARN] Parent form exists but not auto-submitting');
            }
        } catch (e) {
            console.warn('  [FAIL] Form check failed:', e.message);
        }
        
        console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
        console.log('[OK] All click methods completed\n');
        return true;
    }
    
    // Main function to process clicks sequentially
    async function processClicks() {
        console.log('\n[START] Starting click sequence');
        console.log('═════════════════════════════════════════\n');
        updateBanner('[START] Starting click sequence...', '#00ffff');
        
        for (let i = 0; i < elementsToClick.length; i++) {
            const item = elementsToClick[i];
            const description = item.description || `Item ${i + 1}`;
            
            console.log(`\n> Processing ${i + 1}/${elementsToClick.length}: ${description}`);
            
            const selector = extractSelector(item.element);
            
            if (!selector) {
                console.log(`[ERROR] Could not extract selector from: ${item.element}`);
                updateBanner(`[WARN] Could not extract selector for: ${description}`, '#ff9900');
                await wait(2);
                continue;
            }
            
            try {
                updateBanner(`[WAIT] Looking for: ${description}`, '#ffff00');
                logDebug(`Looking for selector: ${selector}`);
                
                console.log(`[INSPECT] Waiting for element: ${selector}`);
                const element = await waitForElement(selector, TIMEOUT_SECONDS);
                
                logDebug(`[OK] Found element: ${selector}`);
                console.log(`[OK] Element found!`);
                console.log(`   Tag: ${element.tagName}`);
                console.log(`   Classes: ${element.className}`);
                console.log(`   Text content: "${element.textContent?.trim().substring(0, 50)}..."`);
                
                updateBanner(`[OK] Found ${description} - waiting ${item.delay}s before click`, '#00ff00', true);
                
                highlightElement(element);
                console.log(`[DELAY] Waiting ${item.delay} seconds before clicking...`);
                await wait(item.delay);
                
                updateBanner(`[CLICK] Clicking: ${description}`, '#ffff00');
                const clickSuccess = await clickElement(element, description);
                
                if (clickSuccess) {
                    console.log(`[OK] Click sequence completed for: ${selector}`);
                    updateBanner(`[OK] Clicked: ${description}`, '#00ff00');
                } else {
                    console.warn(`[WARN] Click may have failed for: ${selector}`);
                    updateBanner(`[WARN] Click attempted: ${description}`, '#ff9900');
                }
                
                removeHighlight(element);
                await wait(1);
                
            } catch (error) {
                console.error(`[ERROR] Error with element ${selector}:`, error.message);
                updateBanner(`[ERROR] Failed to find: ${description}`, '#ff0000');
                await wait(3);
            }
        }
        
        console.log('\n═════════════════════════════════════════');
        console.log('[COMPLETE] All clicks completed!');
        updateBanner('[COMPLETE] All clicks completed successfully! (hiding in 10s)', '#00ff00');
        
        // Hide banner after 10 seconds to let user see results
        setTimeout(() => {
            if (currentBanner && currentBanner.textContent.includes('completed')) {
                currentBanner.remove();
                currentBanner = null;
                console.log('[BANNER] Completion banner hidden');
            }
        }, 10000);
    }
    
    // Create control panel button
    function createControlPanel() {
        const panel = document.createElement('div');
        panel.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: black;
            color: white;
            padding: 15px;
            border-radius: 8px;
            z-index: 999998;
            font-family: monospace;
            border: 2px solid #00ff00;
            box-shadow: 0 4px 6px rgba(0, 255, 0, 0.3);
        `;
        
        const title = document.createElement('div');
        title.textContent = '[CONTROL] BREAK OUT Enhanced';
        title.style.cssText = 'font-weight: bold; margin-bottom: 10px; color: #00ff00; font-size: 14px;';
        panel.appendChild(title);
        
        const startButton = document.createElement('button');
        startButton.textContent = '[START] Start Click Sequence';
        startButton.style.cssText = `
            background: #00ff00;
            color: black;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            width: 100%;
            margin-bottom: 5px;
            font-family: monospace;
        `;
        startButton.onmouseover = () => startButton.style.background = '#00cc00';
        startButton.onmouseout = () => startButton.style.background = '#00ff00';
        startButton.onclick = processClicks;
        panel.appendChild(startButton);
        
        // Add element inspector button
        const inspectButton = document.createElement('button');
        inspectButton.textContent = '[INSPECT] Inspect Element';
        inspectButton.style.cssText = `
            background: #0099ff;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            width: 100%;
            margin-bottom: 5px;
            font-family: monospace;
            font-size: 12px;
        `;
        let inspectorActive = false;
        inspectButton.onclick = () => {
            inspectorActive = !inspectorActive;
            if (inspectorActive) {
                inspectButton.textContent = '[INSPECT] Inspector Active (click element)';
                inspectButton.style.background = '#ff9900';
                document.body.style.cursor = 'crosshair';
                
                const inspector = (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    const target = e.target;
                    console.log('\n[TARGET] MANUAL ELEMENT INSPECTION');
                    console.log('═══════════════════════════════════════');
                    diagnoseElement(target);
                    
                    // Try to dump all properties
                    console.log('\n[PROPS] All Element Properties:');
                    for (const prop in target) {
                        try {
                            const value = target[prop];
                            if (typeof value === 'function') {
                                console.log(`  ${prop}: [Function]`);
                            } else if (value !== null && typeof value === 'object') {
                                console.log(`  ${prop}: [Object]`);
                            } else {
                                console.log(`  ${prop}: ${value}`);
                            }
                        } catch (e) {
                            console.log(`  ${prop}: [Error accessing]`);
                        }
                    }
                    console.log('═══════════════════════════════════════\n');
                    
                    // Highlight it
                    highlightElement(target);
                    setTimeout(() => removeHighlight(target), 3000);
                    
                    // Deactivate inspector
                    document.removeEventListener('click', inspector, true);
                    inspectorActive = false;
                    inspectButton.textContent = '[INSPECT] Inspect Element';
                    inspectButton.style.background = '#0099ff';
                    document.body.style.cursor = '';
                };
                
                document.addEventListener('click', inspector, true);
            } else {
                document.body.style.cursor = '';
                inspectButton.textContent = '[INSPECT] Inspect Element';
                inspectButton.style.background = '#0099ff';
            }
        };
        panel.appendChild(inspectButton);
        
        // Add toggle banner button
        const toggleBannerButton = document.createElement('button');
        toggleBannerButton.textContent = '[BANNER] Toggle Banner';
        toggleBannerButton.style.cssText = `
            background: #9900ff;
            color: white;
            border: none;
            padding: 6px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            width: 100%;
            margin-bottom: 5px;
            font-family: monospace;
            font-size: 11px;
        `;
        toggleBannerButton.onclick = () => {
            if (currentBanner) {
                currentBanner.style.display = currentBanner.style.display === 'none' ? 'block' : 'none';
                console.log('[BANNER] Banner toggled:', currentBanner.style.display);
            } else {
                createDebugBanner('[OK] Banner visible - ready for automation', '#00ff00');
            }
        };
        panel.appendChild(toggleBannerButton);
        
        const closeButton = document.createElement('button');
        closeButton.textContent = '[ERROR] Close Panel';
        closeButton.style.cssText = `
            background: #ff0000;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            width: 100%;
            font-family: monospace;
        `;
        closeButton.onmouseover = () => closeButton.style.background = '#cc0000';
        closeButton.onmouseout = () => closeButton.style.background = '#ff0000';
        closeButton.onclick = () => panel.remove();
        panel.appendChild(closeButton);
        
        document.body.appendChild(panel);
    }
    
    // Wait for page to be fully loaded
    window.addEventListener('load', function() {
        console.log('[PAGE] Page fully loaded');
        updateBanner('[OK] Page loaded - Click "Start" button to begin automation', '#00ff00');
        createControlPanel();
        console.log('[CONTROL] Control panel created');
        
        // Keep banner visible longer (10 seconds instead of 5)
        setTimeout(() => {
            if (currentBanner && currentBanner.textContent.includes('Page loaded')) {
                currentBanner.remove();
                currentBanner = null;
                console.log('[BANNER] Initial banner hidden after 10s');
            }
        }, 10000);
    });
    
})();