(function () {
    // --- Global Error Logger for Mobile Web App ---

    const logs = [];
    const MAX_LOGS = 50;
    let overlayOpen = false;

    // 1. Create UI Elements
    const styles = `
        #debug-fab {
            position: fixed;
            bottom: 20px;
            left: 20px;
            width: 40px;
            height: 40px;
            background: rgba(220, 38, 38, 0.9);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 99999;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            font-size: 20px;
            cursor: pointer;
            border: 2px solid white;
        }
        #debug-overlay {
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.85);
            backdrop-filter: blur(5px);
            z-index: 99998;
            display: none;
            flex-direction: column;
            padding: safe-area-inset-top 20px 20px 20px;
            padding-top: max(20px, env(safe-area-inset-top));
            font-family: monospace;
        }
        #debug-overlay.open { display: flex; }
        #debug-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #333;
            color: white;
        }
        #debug-list {
            flex: 1;
            overflow-y: auto;
            margin-top: 10px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .log-entry {
            background: #1e1e1e;
            padding: 8px;
            border-radius: 4px;
            border-left: 3px solid #ccc;
            font-size: 11px;
            color: #ccc;
            word-break: break-all;
        }
        .log-error { border-color: #ef4444; background: #2f1515; color: #fca5a5; }
        .log-warn { border-color: #f59e0b; background: #2b2311; color: #fcd34d; }
        .log-info { border-color: #3b82f6; }
    `;

    const styleSheet = document.createElement("style");
    styleSheet.innerText = styles;
    document.head.appendChild(styleSheet);

    const fab = document.createElement('div');
    fab.id = 'debug-fab';
    fab.innerHTML = '🐛'; // Bug icon
    fab.onclick = toggleOverlay;
    document.body.appendChild(fab);

    const overlay = document.createElement('div');
    overlay.id = 'debug-overlay';
    overlay.innerHTML = `
        <div id="debug-header">
            <h3 style="font-weight:bold; font-size:16px;">System Logs</h3>
            <div style="display:flex; gap:10px;">
                <button onclick="window.clearLogs()" style="color:#aaa; background:none; border:none; font-weight:bold;">Clear</button>
                <button onclick="window.toggleOverlay()" style="color:white; background:none; border:none; font-weight:bold; font-size:18px;">×</button>
            </div>
        </div>
        <div id="debug-list"></div>
    `;
    document.body.appendChild(overlay);

    // 2. Logging Logic
    function addLog(type, args) {
        const msg = args.map(a => {
            if (a instanceof Error) return a.stack || a.message;
            if (typeof a === 'object') {
                try { return JSON.stringify(a); } catch (e) { return '[Object]'; }
            }
            return String(a);
        }).join(' ');

        logs.push({ type, msg, time: new Date().toLocaleTimeString() });
        if (logs.length > MAX_LOGS) logs.shift();

        // Auto-flash FAB on error
        if (type === 'error') {
            fab.style.background = '#ef4444';
            setTimeout(() => fab.style.background = 'rgba(220, 38, 38, 0.9)', 500);
        }

        renderLogs();
    }

    function renderLogs() {
        if (!overlayOpen) return;
        const list = document.getElementById('debug-list');
        list.innerHTML = logs.map(l => `
            <div class="log-entry log-${l.type}">
                <span style="opacity:0.5; font-size:9px;">${l.time}</span><br/>
                ${l.msg.replace(/</g, '&lt;')}
            </div>
        `).reverse().join('');
    }

    window.toggleOverlay = function () {
        overlayOpen = !overlayOpen;
        overlay.className = overlayOpen ? 'open' : '';
        if (overlayOpen) renderLogs();
    };

    window.clearLogs = function () {
        logs.length = 0;
        renderLogs();
    };

    // 3. Interceptors
    const originalConsole = {
        log: console.log,
        warn: console.warn,
        error: console.error
    };

    console.log = function (...args) {
        originalConsole.log.apply(console, args);
        // addLog('info', args); // Too noisy usually
    };

    console.warn = function (...args) {
        originalConsole.warn.apply(console, args);
        addLog('warn', args);
    };

    console.error = function (...args) {
        originalConsole.error.apply(console, args);
        addLog('error', args);
    };

    window.onerror = function (msg, url, line, col, error) {
        addLog('error', [`[Window Error] ${msg} at ${line}:${col}`]);
        return false; // Let default handler run too
    };

    window.onunhandledrejection = function (e) {
        addLog('error', [`[Unhandled Promise] ${e.reason}`]);
    };

    console.log("Logger Initialized");

})();
