/**
 * Console Logger - Captures all browser console output to localStorage
 * This allows viewing logs from /public/logs.html across all pages
 */

(function() {
  // Capture all console methods
  const originalLog = console.log;
  const originalError = console.error;
  const originalWarn = console.warn;
  const originalInfo = console.info;
  const originalDebug = console.debug;

  function formatTimestamp() {
    return new Date().toISOString();
  }

  function captureLog(level, args) {
    const message = args.map(arg => {
      if (typeof arg === 'object') {
        try {
          return JSON.stringify(arg, null, 2);
        } catch (e) {
          return String(arg);
        }
      }
      return String(arg);
    }).join(' ');

    const logEntry = {
      timestamp: formatTimestamp(),
      level,
      message
    };

    // Save to localStorage for logs viewer
    try {
      const stored = localStorage.getItem('console_logs');
      let logs = stored ? JSON.parse(stored) : [];
      logs.push(logEntry);
      // Keep last 100 logs in localStorage
      if (logs.length > 100) {
        logs = logs.slice(-100);
      }
      localStorage.setItem('console_logs', JSON.stringify(logs));
    } catch (e) {
      // localStorage might be unavailable or full - silently fail
    }
  }

  // Override console methods
  console.log = function(...args) {
    originalLog(...args);
    captureLog('LOG', args);
  };

  console.error = function(...args) {
    originalError(...args);
    captureLog('ERROR', args);
  };

  console.warn = function(...args) {
    originalWarn(...args);
    captureLog('WARN', args);
  };

  console.info = function(...args) {
    originalInfo(...args);
    captureLog('INFO', args);
  };

  console.debug = function(...args) {
    originalDebug(...args);
    captureLog('DEBUG', args);
  };

  // Capture uncaught errors and unhandled promise rejections (module load failures go here)
  window.addEventListener('error', function(e) {
    const msg = e.message || 'Unknown error';
    const src = e.filename ? ` @ ${e.filename}:${e.lineno}` : '';
    captureLog('ERROR', [`[WINDOW-ERROR] ${msg}${src}`]);
    originalError('[WINDOW-ERROR]', msg, src, e.error);
  });

  window.addEventListener('unhandledrejection', function(e) {
    const reason = e.reason instanceof Error
      ? `${e.reason.message}\n${e.reason.stack}`
      : String(e.reason);
    captureLog('ERROR', [`[UNHANDLED-REJECTION] ${reason}`]);
    originalError('[UNHANDLED-REJECTION]', e.reason);
  });

  // Initial message
  originalLog('🔍 Console Logger initialized - capturing to localStorage');
})();
