
(function () {
    // Create Debug Overlay
    const overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:200px;background:rgba(0,0,0,0.8);color:#ff5555;z-index:9999;overflow:auto;padding:10px;font-family:monospace;font-size:12px;pointer-events:none;';
    overlay.id = 'debug-overlay';
    document.body.appendChild(overlay);

    function log(msg, type = 'INFO') {
        const line = document.createElement('div');
        line.textContent = `[${type}] ${msg}`;
        if (type === 'ERROR') line.style.color = '#ff5555';
        if (type === 'SUCCESS') line.style.color = '#55ff55';
        overlay.appendChild(line);
        console.log(`[${type}] ${msg}`);
    }

    log("Debug Logger Active. Waiting for scripts...");

    // Catch Global Errors
    window.onerror = function (msg, url, line, col, error) {
        log(`Global Error: ${msg} at ${url}:${line}:${col}`, 'ERROR');
        return false;
    };

    // Catch Promise Failures
    window.onunhandledrejection = function (e) {
        log(`Unhandled Promise: ${e.reason}`, 'ERROR');
    };

    // Hook Console
    const origLog = console.log;
    console.log = function (...args) {
        // origLog.apply(console, args);
        // log(args.join(' ')); // Too noisy?
    };

    const origErr = console.error;
    console.error = function (...args) {
        origErr.apply(console, args);
        log(args.join(' '), 'ERROR');
    };

    // Check Key Globals
    window.addEventListener('load', () => {
        log("Window Loaded.");
        if (typeof initMap === 'function') log("initMap exists.", 'SUCCESS');
        else log("initMap MISSING!", 'ERROR');

        if (typeof renderBrowseFeed === 'function') log("renderBrowseFeed exists.", 'SUCCESS');
        else log("renderBrowseFeed MISSING!", 'ERROR');

        if (document.getElementById('item-sheet')) log("Item Sheet HTML Found.", 'SUCCESS');
        else log("Item Sheet HTML MISSING!", 'ERROR');
    });

})();
