<!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>

    <!-- 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>
                </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 -->
                    <div class="tab-nav">
                        <button class="tab-button active" data-tab="events">📊 Events</button>
                        <button class="tab-button" data-tab="agents">🤖 Agents</button>
                        <button class="tab-button" data-tab="tools">🔧 Tools</button>
                        <button class="tab-button" data-tab="files">📁 Files</button>
                        <button class="tab-button" data-tab="activity">🌳 Activity</button>
                        <button class="tab-button" data-tab="code">🧬 Code</button>
                    </div>

                    <!-- Events Tab -->
                    <div class="tab-content active" 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>

                    <!-- Code Tab -->
                    <div class="tab-content" id="code-tab">
                        <div class="code-container">
                            <div class="code-split-container">
                                <div id="code-tree-container" class="code-tree-container">
                                <!-- Top-left corner: Language selector -->
                                <div class="tree-corner-controls top-left">
                                    <div class="control-group">
                                        <label class="control-label">Languages:</label>
                                        <div class="checkbox-group">
                                            <label class="checkbox-label"><input type="checkbox" class="language-checkbox" value="python" checked> Python</label>
                                            <label class="checkbox-label"><input type="checkbox" class="language-checkbox" value="javascript" checked> JS</label>
                                            <label class="checkbox-label"><input type="checkbox" class="language-checkbox" value="typescript" checked> TS</label>
                                        </div>
                                    </div>
                                </div>

                                <!-- Top-right corner: Layout and search -->
                                <div class="tree-corner-controls top-right">
                                    <div class="control-group">
                                        <select id="code-layout" class="select-compact">
                                            <option value="tree">Tree</option>
                                            <option value="radial">Radial</option>
                                        </select>
                                        <input type="text" id="code-search" placeholder="Search..." class="search-compact">
                                    </div>
                                </div>

                                <!-- Bottom-left corner: Stats and Status -->
                                <div class="tree-corner-controls bottom-left">
                                    <div class="stats-display" id="code-stats">
                                        <span id="stats-files">0 files</span> •
                                        <span id="stats-classes">0 classes</span> •
                                        <span id="stats-functions">0 functions</span> •
                                        <span id="stats-methods">0 methods</span>
                                    </div>
                                    <div class="status-display" id="code-breadcrumb">
                                        <div class="breadcrumb-ticker" id="breadcrumb-ticker">
                                            <span id="breadcrumb-content">Ready to analyze...</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Bottom-right corner: Ignore patterns -->
                                <div class="tree-corner-controls bottom-right">
                                    <div class="control-group">
                                        <label class="control-label">Ignore:</label>
                                        <input type="text" id="ignore-patterns" placeholder="test*, *.spec.js, node_modules" class="input-compact">
                                    </div>
                                </div>
                                <div id="code-tree"></div>
                                <!-- Collapsible legend -->
                                <div class="tree-legend collapsed" id="tree-legend" style="display: none;">
                                    <button class="legend-close" onclick="document.getElementById('tree-legend').style.display='none'">✕</button>
                                    <div class="legend-content">
                                        <div class="legend-column">
                                            <div class="legend-item"><span class="legend-icon">📦</span> Module</div>
                                            <div class="legend-item"><span class="legend-icon">🏛️</span> Class</div>
                                            <div class="legend-item"><span class="legend-icon">⚡</span> Function</div>
                                            <div class="legend-item"><span class="legend-icon">🔧</span> Method</div>
                                        </div>
                                        <div class="legend-column">
                                            <div class="legend-item"><span class="legend-icon complexity-low">●</span> Low</div>
                                            <div class="legend-item"><span class="legend-icon complexity-medium">●</span> Med</div>
                                            <div class="legend-item"><span class="legend-icon complexity-high">●</span> High</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </div>
                    </div>

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

    <!-- Code Viewer Modal -->
    <div id="code-viewer-modal" class="modal" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="code-viewer-title">Code Viewer</h2>
                <button class="close" onclick="closeCodeViewer()">&times;</button>
            </div>
            <div class="modal-body">
                <pre><code id="code-viewer-content"></code></pre>
            </div>
            <div class="modal-footer">
                <div class="code-viewer-info">
                    <span id="code-viewer-path"></span>
                    <span id="code-viewer-lines"></span>
                    <span id="code-viewer-language"></span>
                </div>
                <button onclick="closeCodeViewer()">Close</button>
            </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(() => {
                // Now load main components in parallel
                return Promise.all([
                    loadModule('/static/dist/dashboard.js'),
                    loadModule('/static/dist/components/activity-tree.js'),
                    loadModule('/static/js/components/code-tree.js'),  // TEMPORARY: Direct source for debugging
                    loadModule('/static/dist/components/code-viewer.js'),
                    loadModule('/static/dist/components/file-viewer.js')  // File viewer for viewing file contents
                ]);
            })
            .then(() => {
            console.log('All dashboard modules loaded successfully');
            
            // 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);
        }).catch(error => {
            console.error('Failed to load dashboard modules:', error);
        });
    </script>
</body>
</html>
