'use client'; import { useState, useEffect } from 'react'; import { Bug, X, Settings, Shield, Activity } from 'lucide-react'; import { getGlobalErrorHandler } from '@/lib/infrastructure/GlobalErrorHandler'; import { getGlobalApiLogger } from '@/lib/infrastructure/ApiRequestLogger'; interface DebugModeToggleProps { /** * Whether to show the toggle (auto-detected from environment) */ show?: boolean; } /** * Debug Mode Toggle Component * Provides a floating interface to control debug features and view real-time metrics */ export function DebugModeToggle({ show }: DebugModeToggleProps) { const [isOpen, setIsOpen] = useState(false); const [debugEnabled, setDebugEnabled] = useState(false); const [metrics, setMetrics] = useState({ errors: 0, apiRequests: 0, apiFailures: 0, }); const isDev = process.env.NODE_ENV === 'development'; const shouldShow = show ?? isDev; useEffect(() => { if (!shouldShow) return; // Load debug state from localStorage const saved = localStorage.getItem('gridpilot_debug_enabled'); if (saved === 'true') { setDebugEnabled(true); initializeDebugFeatures(); } // Update metrics every 2 seconds const interval = setInterval(updateMetrics, 2000); return () => clearInterval(interval); }, [shouldShow]); useEffect(() => { // Save debug state if (shouldShow) { localStorage.setItem('gridpilot_debug_enabled', debugEnabled.toString()); } }, [debugEnabled, shouldShow]); const updateMetrics = () => { if (!debugEnabled) return; const globalHandler = getGlobalErrorHandler(); const apiLogger = getGlobalApiLogger(); const errorStats = globalHandler.getStats(); const apiStats = apiLogger.getStats(); setMetrics({ errors: errorStats.total, apiRequests: apiStats.total, apiFailures: apiStats.failed, }); }; const initializeDebugFeatures = () => { const globalHandler = getGlobalErrorHandler(); const apiLogger = getGlobalApiLogger(); // Initialize global error handler globalHandler.initialize(); // Override fetch with logging if (!(window as any).__GRIDPILOT_FETCH_LOGGED__) { const loggedFetch = apiLogger.createLoggedFetch(); window.fetch = loggedFetch as any; (window as any).__GRIDPILOT_FETCH_LOGGED__ = true; } // Expose to window for easy access (window as any).__GRIDPILOT_GLOBAL_HANDLER__ = globalHandler; (window as any).__GRIDPILOT_API_LOGGER__ = apiLogger; console.log('%c[DEBUG MODE] Enabled', 'color: #00ff88; font-weight: bold; font-size: 14px;'); console.log('Available globals:', { __GRIDPILOT_GLOBAL_HANDLER__: globalHandler, __GRIDPILOT_API_LOGGER__: apiLogger, __GRIDPILOT_REACT_ERRORS__: (window as any).__GRIDPILOT_REACT_ERRORS__ || [], }); }; const toggleDebug = () => { const newEnabled = !debugEnabled; setDebugEnabled(newEnabled); if (newEnabled) { initializeDebugFeatures(); } else { // Disable debug features const globalHandler = getGlobalErrorHandler(); globalHandler.destroy(); console.log('%c[DEBUG MODE] Disabled', 'color: #ff4444; font-weight: bold; font-size: 14px;'); } }; const triggerTestError = () => { if (!debugEnabled) return; // Trigger a test API error const testError = new Error('This is a test error for debugging'); (testError as any).type = 'TEST_ERROR'; const globalHandler = getGlobalErrorHandler(); globalHandler.report(testError, { test: true, timestamp: Date.now() }); console.log('%c[TEST] Error triggered', 'color: #ffaa00; font-weight: bold;', testError); }; const triggerTestApiCall = async () => { if (!debugEnabled) return; try { // This will fail and be logged await fetch('https://httpstat.us/500'); } catch (error) { // Already logged by interceptor console.log('%c[TEST] API call completed', 'color: #00aaff; font-weight: bold;'); } }; const clearAllLogs = () => { const globalHandler = getGlobalErrorHandler(); const apiLogger = getGlobalApiLogger(); globalHandler.clearHistory(); apiLogger.clearHistory(); setMetrics({ errors: 0, apiRequests: 0, apiFailures: 0 }); console.log('%c[DEBUG] All logs cleared', 'color: #00ff88; font-weight: bold;'); }; const copyDebugInfo = async () => { const globalHandler = getGlobalErrorHandler(); const apiLogger = getGlobalApiLogger(); const debugInfo = { timestamp: new Date().toISOString(), environment: { mode: process.env.NODE_ENV, version: process.env.NEXT_PUBLIC_APP_VERSION, }, browser: { userAgent: navigator.userAgent, language: navigator.language, platform: navigator.platform, }, errors: globalHandler.getStats(), api: apiLogger.getStats(), reactErrors: (window as any).__GRIDPILOT_REACT_ERRORS__ || [], }; try { await navigator.clipboard.writeText(JSON.stringify(debugInfo, null, 2)); console.log('%c[DEBUG] Debug info copied to clipboard', 'color: #00ff88; font-weight: bold;'); } catch (err) { console.error('Failed to copy:', err); } }; if (!shouldShow) { return null; } return (