<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Claude MPM Socket.IO Dashboard</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cmVjdCB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHJ4PSI2IiBmaWxsPSIjNDI5OWUxIi8+CiAgPHRleHQgeD0iMTYiIHk9IjIxIiBmb250LWZhbWlseT0iSGVsdmV0aWNhLCBBcmlhbCwgc2Fucy1zZXJpZiIgZm9udC1zaXplPSIxMCIgZm9udC13ZWlnaHQ9ImJvbGQiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5NUE08L3RleHQ+Cjwvc3ZnPgo=">

    <!-- Browser Extension Error Handler - Load First -->
    <script type="module">
        // Load extension error handler before anything else to catch early errors
        import extensionErrorHandler from '/static/js/extension-error-handler.js';
        // Handler is automatically initialized on import
    </script>

    <!-- External Dependencies -->
    <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
    
    <!-- D3.js for Activity Tree Visualization -->
    <script src="https://d3js.org/d3.v7.min.js"></script>
    
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Syntax Highlighting - Prism.js -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.css" rel="stylesheet">

    <!-- Stylesheets -->
    <link rel="stylesheet" href="/static/css/dashboard.css">
    <link rel="stylesheet" href="/static/css/connection-status.css">
    <link rel="stylesheet" href="/static/css/activity.css">
    <link rel="stylesheet" href="/static/css/code-tree.css">

    <!-- Additional styles for file operations -->
    <style>
        .file-item {
            background: white;
            border-radius: 6px;
            padding: 12px;
            margin-bottom: 8px;
            border-left: 4px solid #4299e1;
            cursor: pointer;
            transition: all 0.2s;
        }

        .file-item:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            transform: translateX(2px);
        }

        .file-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;
        }

        .file-icon {
            font-size: 16px;
            min-width: 20px;
        }

        .file-path {
            flex: 1;
            font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
            font-size: 13px;
            color: #2d3748;
            word-break: break-all;
        }

        .file-timestamp {
            font-size: 12px;
            color: #718096;
        }

        .file-summary {
            font-size: 12px;
            color: #4a5568;
            margin-left: 28px;
        }

        .operation-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            padding: 10px;
            margin-bottom: 8px;
        }

        .operation-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
        }

        .operation-icon {
            font-size: 14px;
            min-width: 16px;
        }

        .operation-type {
            font-weight: 600;
            color: #2d3748;
        }

        .operation-timestamp {
            margin-left: auto;
            font-size: 11px;
            color: #718096;
        }

        .operation-details {
            font-size: 12px;
            color: #4a5568;
            line-height: 1.4;
        }

        .file-details {
            background: white;
            border-radius: 6px;
            padding: 15px;
        }

        .file-path-display {
            font-size: 14px;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e2e8f0;
        }

        .operations-list {
            max-height: 400px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <!-- Connection Notifications Area -->
    <div id="connection-notifications" class="connection-notifications"></div>
    
    <div class="container">
        <!-- Header Section -->
        <div class="header">
            <!-- Row 1: Title, Status, Metrics -->
            <div class="header-row">
                <div class="header-title">
                    <h1>🚀 Claude MPM Monitor</h1>
                    <div id="connection-status" class="status-badge status-disconnected">
                        <span>●</span> Disconnected
                    </div>
                    <div id="connection-quality" class="connection-quality" style="display: none;">
                        <div class="quality-bar">
                            <div class="quality-fill"></div>
                        </div>
                        <span class="quality-text">--</span>
                    </div>
                    <span id="connection-latency" class="connection-latency" style="display: none;">--ms</span>
                    <!-- Version display will be inserted here by BuildTracker component -->
                </div>
                <div class="metrics-widget">
                    <div class="metric-mini">
                        <div class="metric-mini-value" id="total-events">0</div>
                        <div class="metric-mini-label">Events</div>
                    </div>
                    <div class="metric-mini">
                        <div class="metric-mini-value" id="events-per-minute">0</div>
                        <div class="metric-mini-label">Per Min</div>
                    </div>
                    <div class="metric-mini">
                        <div class="metric-mini-value" id="unique-types">0</div>
                        <div class="metric-mini-label">Types</div>
                    </div>
                    <div class="metric-mini">
                        <div class="metric-mini-value" id="error-count">0</div>
                        <div class="metric-mini-label">Errors</div>
                    </div>
                    <!-- Debug metrics for troubleshooting -->
                    <div class="metric-mini" style="background: rgba(255,255,255,0.05);">
                        <div class="metric-mini-value" id="debug-events-received">0</div>
                        <div class="metric-mini-label">Received</div>
                    </div>
                    <div class="metric-mini" style="background: rgba(255,255,255,0.05);">
                        <div class="metric-mini-value" id="debug-events-rendered">0</div>
                        <div class="metric-mini-label">Rendered</div>
                    </div>
                </div>
            </div>

            <!-- Row 2: Main Controls (Always Visible) -->
            <div class="header-row main-controls">
                <div class="session-group">
                    <label>Session:</label>
                    <select id="session-select" class="session-select">
                        <option value="">All Sessions</option>
                    </select>
                </div>
                <div class="working-dir-group">
                    <label>Working Dir:</label>
                    <div class="working-dir-display">
                        <span id="working-dir-path" class="working-dir-path" title="Click to browse files • Shift+Click to change directory">Loading...</span>
                        <button id="change-dir-btn" class="btn-icon" title="Change working directory">📁</button>
                    </div>
                </div>
                <div class="action-buttons">
                    <button id="export-btn" class="btn-success">Export</button>
                </div>
                <div class="connection-toggle">
                    <button id="connection-toggle-btn" class="btn-secondary">Connection Settings</button>
                </div>
            </div>

            <!-- Row 3: Connection Controls (Hidden by Default) -->
            <div class="header-row connection-controls-row" id="connection-controls-row" style="display: none;">
                <div class="connection-controls">
                    <button id="connect-btn">Connect</button>
                    <button id="disconnect-btn" class="btn-secondary">Disconnect</button>
                    <input type="text" id="port-input" value="8765" placeholder="Port">
                    <label>Session:</label>
                </div>
            </div>
        </div>

        <!-- Main Content Area -->
        <div class="events-wrapper">
            <!-- Split container for module viewer and tabbed content -->
            <div class="split-container" id="normal-view">
                <!-- Left: Module Viewer -->
                <div class="module-viewer">
                    <!-- Single pane layout: Structured Data with collapsible JSON -->
                    <div class="module-panes" id="module-content">
                        <!-- Data Pane -->
                        <div class="module-data-pane">
                            <div class="module-data-header">
                                <h5>📊 Structured Data</h5>
                            </div>
                            <div class="module-data-content" id="module-data-content">
                                <div class="module-empty">
                                    <p>Click on an event to view structured data</p>
                                    <p class="module-hint">Data is organized by event type</p>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>

                <!-- Right: Tabbed Content -->
                <div class="events-container">
                    <!-- Tab Navigation - Using hash-based navigation -->
                    <div class="tab-nav">
                        <a href="#events" class="tab-button" data-tab="events">📊 Events</a>
                        <a href="#agents" class="tab-button" data-tab="agents">🤖 Agents</a>
                        <a href="#tools" class="tab-button" data-tab="tools">🔧 Tools</a>
                        <a href="#files" class="tab-button" data-tab="files">📁 Files</a>
                        <a href="#activity" class="tab-button" data-tab="activity">🌳 Activity</a>
                        <a href="#file_tree" class="tab-button" data-tab="claude-tree">📝 File Tree</a>
                    </div>

                    <!-- Events Tab -->
                    <div class="tab-content" id="events-tab">
                        <div class="tab-filters">
                            <input type="text" id="events-search-input" placeholder="Search events...">
                            <select id="events-type-filter">
                                <option value="">All Events</option>
                                <!-- Event types will be dynamically populated from actual event data -->
                            </select>
                        </div>
                        <div class="events-list" id="events-list">
                            <div class="no-events">
                                Connect to Socket.IO server to see events...
                            </div>
                        </div>
                    </div>

                    <!-- Agents Tab -->
                    <div class="tab-content" id="agents-tab">
                        <div class="tab-filters">
                            <input type="text" id="agents-search-input" placeholder="Search agents...">
                            <select id="agents-type-filter">
                                <option value="">All Agents</option>
                                <option value="research">Research</option>
                                <option value="engineer">Engineer</option>
                                <option value="pm">Project Manager</option>
                                <option value="ops">Operations</option>
                            </select>
                        </div>
                        <div class="events-list" id="agents-list">
                            <div class="no-events">
                                No agent events found...
                            </div>
                        </div>
                    </div>

                    <!-- Tools Tab -->
                    <div class="tab-content" id="tools-tab">
                        <div class="tab-filters">
                            <input type="text" id="tools-search-input" placeholder="Search tools...">
                            <select id="tools-type-filter">
                                <option value="">All Tools</option>
                                <option value="Read">Read</option>
                                <option value="Write">Write</option>
                                <option value="Edit">Edit</option>
                                <option value="Bash">Bash</option>
                                <option value="Grep">Grep</option>
                                <option value="Glob">Glob</option>
                            </select>
                        </div>
                        <div class="events-list" id="tools-list">
                            <div class="no-events">
                                No tool events found...
                            </div>
                        </div>
                    </div>

                    <!-- Files Tab -->
                    <div class="tab-content" id="files-tab">
                        <div class="tab-filters">
                            <input type="text" id="files-search-input" placeholder="Search files...">
                            <select id="files-type-filter">
                                <option value="">All Operations</option>
                                <option value="read">Read</option>
                                <option value="write">Write</option>
                                <option value="edit">Edit</option>
                                <option value="search">Search</option>
                            </select>
                        </div>
                        <div class="events-list" id="files-list">
                            <div class="no-events">
                                No file operations found...
                            </div>
                        </div>
                    </div>

                    <!-- Activity Tab -->
                    <div class="tab-content" id="activity-tab">
                        <div class="activity-container">
                            <div class="activity-header">
                                <div class="activity-controls">
                                    <button id="expand-all" class="btn-sm">Expand All</button>
                                    <button id="collapse-all" class="btn-sm">Collapse All</button>
                                    <select id="time-range">
                                        <option value="all">All Time</option>
                                        <option value="hour">Last Hour</option>
                                        <option value="30min" selected>Last 30 Minutes</option>
                                        <option value="10min">Last 10 Minutes</option>
                                    </select>
                                    <input type="text" id="activity-search" placeholder="Search nodes...">
                                </div>
                                <div class="activity-stats">
                                    <span class="stat-item">
                                        <span class="stat-label">Nodes:</span>
                                        <span id="node-count" class="stat-value">0</span>
                                    </span>
                                    <span class="stat-item">
                                        <span class="stat-label">Active:</span>
                                        <span id="active-count" class="stat-value">0</span>
                                    </span>
                                    <span class="stat-item">
                                        <span class="stat-label">Depth:</span>
                                        <span id="tree-depth" class="stat-value">0</span>
                                    </span>
                                </div>
                            </div>
                            <div id="activity-tree-container" class="activity-tree-container">
                                <div id="activity-tree"></div>
                                <div class="tree-legend">
                                    <div class="legend-item">
                                        <span class="legend-icon">📁</span>
                                        <span>Project Root</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-icon pm">🎯</span>
                                        <span>PM Session</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-icon todowrite">📝</span>
                                        <span>Todo Item</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-icon agent">🤖</span>
                                        <span>Agent</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-icon tool">🔧</span>
                                        <span>Tool</span>
                                    </div>
                                </div>
                            </div>
                            <div class="activity-breadcrumb" id="activity-breadcrumb">
                                PM > Click a node to see path
                            </div>
                        </div>
                    </div>

                    <!-- File Tree Tab -->
                    <div class="tab-content" id="claude-tree-tab">
                        <div id="claude-tree-container" style="width: 100%; height: 100%; position: relative;">
                            <!-- File activity tree will be rendered here by code-viewer.js -->
                            <!-- This container is ISOLATED from other tabs -->
                        </div>
                    </div>


                </div>
            </div>
        </div>
    </div>


    <!-- Footer -->
    <div class="footer">
        <div class="footer-content">
            <div class="footer-item">
                <span class="footer-label">Session:</span>
                <span class="footer-value" id="footer-session">All Sessions</span>
            </div>
            <span class="footer-divider">|</span>
            <div class="footer-item">
                <span class="footer-label">Directory:</span>
                <span class="footer-value" id="footer-working-dir">Loading...</span>
            </div>
            <span class="footer-divider">|</span>
            <div class="footer-item">
                <span class="footer-label">Branch:</span>
                <span class="footer-value" id="footer-git-branch">Unknown</span>
            </div>
            <!-- Analysis Status (hidden by default) -->
            <div class="footer-item" id="footer-analysis-container" style="display: none;">
                <span class="footer-divider">|</span>
                <span class="footer-label">Analysis:</span>
                <span class="footer-value" id="footer-analysis-status">
                    <span class="analysis-progress" id="footer-analysis-progress"></span>
                </span>
            </div>
        </div>
    </div>

    <!-- JavaScript Modules -->
    <!-- Load bundled dashboard assets (built with Vite) - with proper initialization order -->
    <script type="module">
        // Set up working directory environment variables
        // These will be used by the working-directory component
        // The server will inject these values through a separate API call
        
        // Get the current working directory from the server
        fetch('/api/working-directory')
            .then(response => response.json())
            .then(data => {
                window.processWorkingDirectory = data.working_directory || '/Users/masa/Projects/claude-mpm';
                window.homeDirectory = data.home_directory || '/Users/masa';
                
                // Store in session storage for persistence
                if (window.processWorkingDirectory && window.processWorkingDirectory !== '/') {
                    sessionStorage.setItem('currentWorkingDirectory', window.processWorkingDirectory);
                }
                
                // Dispatch event to notify components that working directory is ready
                window.dispatchEvent(new CustomEvent('workingDirectoryInitialized', {
                    detail: {
                        working_directory: window.processWorkingDirectory,
                        home_directory: window.homeDirectory
                    }
                }));
            })
            .catch(error => {
                console.error('Failed to get working directory from server:', error);
                // Use defaults as fallback
                window.processWorkingDirectory = '/Users/masa/Projects/claude-mpm';
                window.homeDirectory = '/Users/masa';
            });
        
        // Add timestamp-based cache busting and ensure proper loading order
        const timestamp = Date.now();
        
        // Load modules sequentially to ensure dashboard.js loads first
        const loadModule = (src) => {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.type = 'module';
                script.src = `${src}?t=${timestamp}`;
                script.onload = resolve;
                script.onerror = reject;
                document.body.appendChild(script);
            });
        };
        
        // Load shared services first, then tree modules, then components
        // Load services sequentially to ensure dependencies are available
        loadModule('/static/js/shared/tooltip-service.js')
            .then(() => loadModule('/static/js/shared/dom-helpers.js'))
            .then(() => loadModule('/static/js/shared/event-bus.js'))
            .then(() => loadModule('/static/js/shared/logger.js'))
            .then(() => loadModule('/static/js/components/code-tree/tree-utils.js'))
            .then(() => loadModule('/static/js/components/code-tree/tree-constants.js'))
            .then(() => loadModule('/static/js/components/code-tree/tree-search.js'))
            .then(() => loadModule('/static/js/components/code-tree/tree-breadcrumb.js'))
            .then(() => {
                // CRITICAL: Load socket-client.js FIRST (dependency of socket-manager)
                return loadModule('/static/js/socket-client.js');
            })
            .then(() => {
                // CRITICAL: Load socket-manager BEFORE dashboard.js
                // The source version must be loaded to make SocketManager globally available
                return loadModule('/static/js/components/socket-manager.js');
            })
            .then(() => {
                // Load all required dashboard dependencies BEFORE dashboard.js
                // These must be available globally for the dist/dashboard.js to work
                return Promise.all([
                    loadModule('/static/js/components/event-viewer.js'),
                    loadModule('/static/js/components/module-viewer.js'),
                    loadModule('/static/js/components/session-manager.js'),
                    loadModule('/static/js/components/agent-inference.js'),
                    loadModule('/static/js/components/agent-hierarchy.js'),
                    loadModule('/static/js/components/ui-state-manager.js'),
                    loadModule('/static/js/components/event-processor.js'),
                    loadModule('/static/js/components/export-manager.js'),
                    loadModule('/static/js/components/working-directory.js'),
                    loadModule('/static/js/components/file-tool-tracker.js'),
                    loadModule('/static/js/components/build-tracker.js')
                ]);
            })
            .then(() => {
                // Now load main components including dashboard.js which depends on the above
                return Promise.all([
                    loadModule('/static/dist/dashboard.js'),  // Use dist version that requires above components
                    loadModule('/static/dist/components/activity-tree.js'),
                    loadModule('/static/js/components/code-tree.js'),  // TEMPORARY: Direct source for debugging
                    loadModule('/static/js/components/code-viewer.js').catch(err => {
                        console.error('[CRITICAL] Failed to load code-viewer.js:', err);
                        throw err;
                    }),  // Code viewer now includes file change tracking
                    loadModule('/static/dist/components/file-viewer.js')  // File viewer for viewing file contents
                ]);
            })
            .then(() => {
            console.log('All dashboard modules loaded successfully');
            
            // Debug: Check if CodeViewer loaded
            if (window.CodeViewer) {
                console.log('[DEBUG] CodeViewer is available on window object');
            } else {
                console.error('[ERROR] CodeViewer NOT FOUND on window object!');
            }
            
            // CodeViewer will auto-initialize and handle tab switching internally
            
            // Browser Log Viewer initialization is now handled by UIStateManager
            // This prevents duplicate event handlers and tab selection conflicts
            
            // Load bulletproof tab isolation fix
            loadModule('/static/js/tab-isolation-fix.js')
                .then(() => {
                    console.log('✅ Tab isolation fix loaded successfully');
                })
                .catch(err => {
                    console.error('❌ Failed to load tab isolation fix:', err);
                });

            // Hash navigation will handle default tab based on URL
            // If no hash, default will be 'events' as per hashToTab mapping
            // To start with File Tree, we can set hash if not present
            setTimeout(() => {
                if (!window.location.hash) {
                    console.log('No hash present, setting default to File Tree tab...');
                    window.location.hash = '#file_tree';
                } else {
                    console.log('Hash present:', window.location.hash);
                }
            }, 500);
            })
            .catch(error => {
                console.error('[CRITICAL] Error loading dashboard modules:', error);
                console.error('Stack trace:', error.stack);
            });
            
            // Give modules time to execute and initialize dashboard
            setTimeout(() => {
                console.log('Checking dashboard initialization...');
                
                if (window.dashboard) {
                    console.log('Dashboard found, checking auto-connect status...');
                    
                    // Force auto-connect if not already connected
                    if (window.dashboard.socketManager) {
                        const socketManager = window.dashboard.socketManager;
                        
                        if (!socketManager.isConnected() && !socketManager.isConnecting()) {
                            console.log('Dashboard loaded but not connected, forcing auto-connect...');
                            
                            // Try to trigger auto-connect manually
                            const params = new URLSearchParams(window.location.search);
                            socketManager.initializeFromURL(params);
                        } else {
                            console.log('Dashboard already connected or connecting');
                        }
                    } else {
                        console.warn('Dashboard found but socketManager not available');
                    }
                } else {
                    console.warn('Dashboard still not initialized after module loading');
                    
                    // Try to manually trigger initialization
                    if (document.readyState === 'complete' || document.readyState === 'interactive') {
                        console.log('Document ready, attempting to trigger dashboard initialization...');
                        document.dispatchEvent(new Event('DOMContentLoaded'));
                    }
                }
                
                // Debug: Test connection settings button
                const connectionToggleBtn = document.getElementById('connection-toggle-btn');
                if (connectionToggleBtn) {
                    console.log('Connection toggle button found, testing functionality...');
                    
                    // Add a debug click handler to ensure the button works
                    connectionToggleBtn.addEventListener('click', () => {
                        console.log('Connection toggle button clicked (debug handler)');
                        
                        if (window.dashboard && window.dashboard.socketManager) {
                            console.log('Calling socketManager.toggleConnectionControls()');
                            window.dashboard.socketManager.toggleConnectionControls();
                        } else {
                            console.log('Manual toggle fallback');
                            const controlsRow = document.getElementById('connection-controls-row');
                            if (controlsRow) {
                                const isVisible = controlsRow.style.display !== 'none';
                                controlsRow.style.display = isVisible ? 'none' : 'block';
                                connectionToggleBtn.textContent = isVisible ? 'Connection Settings' : 'Hide Settings';
                                console.log(`Manually toggled controls visibility: ${!isVisible}`);
                            }
                        }
                    });
                } else {
                    console.error('Connection toggle button not found in DOM');
                }
            }, 1000);
    </script>
</body>
</html>
