#ifndef INDEX_H
#define INDEX_H

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Byun CAN Logger</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 10px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        .header h1 { font-size: 1.8em; margin-bottom: 5px; }
        .header p { opacity: 0.9; font-size: 0.9em; }
        .nav {
            background: #2c3e50;
            padding: 10px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
        }
        .nav a {
            color: white;
            text-decoration: none;
            padding: 10px 15px;
            border-radius: 5px;
            transition: all 0.3s;
            font-size: 0.9em;
            white-space: nowrap;
        }
        .nav a:hover { background: #34495e; }
        .nav a.active { background: #3498db; }
        .content { padding: 15px; }
        
        /* 전력 경고 배너 */
        .power-warning {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: none;
            align-items: center;
            gap: 10px;
            box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
            animation: pulse 2s ease-in-out infinite;
        }
        .power-warning.show { display: flex; }
        .power-warning-icon { font-size: 1.5em; }
        .power-warning-text { flex: 1; font-weight: 600; }
        .power-voltage { 
            font-family: 'Courier New', monospace; 
            font-size: 1.2em; 
            font-weight: 700;
            background: rgba(255,255,255,0.2);
            padding: 5px 12px;
            border-radius: 5px;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.85; }
        }
        
        /* 전력 상태 표시 */
        .power-status {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 3px 10px rgba(86, 171, 47, 0.3);
            flex-wrap: wrap;
            gap: 10px;
        }
        .power-status.low {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
            box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3);
        }
        .power-status-label {
            font-size: 0.85em;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .power-status-values {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        .power-status-item {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }
        .power-status-item-label {
            font-size: 0.7em;
            opacity: 0.9;
        }
        .power-status-value {
            font-family: 'Courier New', monospace;
            font-size: 1.2em;
            font-weight: 700;
        }
        
        /* 큐 상태 표시 */
        .queue-status {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
        }
        .queue-status.warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            box-shadow: 0 3px 10px rgba(240, 147, 251, 0.3);
        }
        .queue-status.critical {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
            box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3);
            animation: pulse 2s ease-in-out infinite;
        }
        .queue-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .queue-bar-container {
            flex: 1;
            min-width: 150px;
            height: 20px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            overflow: hidden;
            position: relative;
        }
        .queue-bar {
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 10px;
            transition: width 0.3s ease;
        }
        .queue-text {
            position: absolute;
            width: 100%;
            text-align: center;
            line-height: 20px;
            font-size: 0.75em;
            font-weight: 700;
            color: white;
            text-shadow: 0 1px 2px rgba(0,0,0,0.3);
        }
        
        .time-sync-banner {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
            box-shadow: 0 4px 15px rgba(240, 147, 251, 0.4);
        }
        .time-sync-info {
            display: flex;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }
        .time-info-item {
            display: flex;
            flex-direction: column;
            gap: 3px;
        }
        .time-label {
            font-size: 0.75em;
            opacity: 0.9;
            font-weight: 600;
        }
        .time-value {
            font-family: 'Courier New', monospace;
            font-size: 1.1em;
            font-weight: 700;
        }
        .btn-time-sync {
            background: white;
            color: #f5576c;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 1em;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 3px 10px rgba(0,0,0,0.2);
        }
        .btn-time-sync:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
        .btn-time-sync:active {
            transform: translateY(-1px);
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 20px;
        }
        .status-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
        }
        .status-card h3 { font-size: 0.75em; opacity: 0.9; margin-bottom: 8px; }
        .status-card .value { font-size: 1.5em; font-weight: bold; word-break: break-all; }
        .status-on { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%) !important; }
        .status-off { background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%) !important; }
        
        /* SD 카드 용량 표시 */
        .sd-capacity {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 3px 10px rgba(79, 172, 254, 0.3);
            flex-wrap: wrap;
            gap: 10px;
        }
        .sd-capacity-label {
            font-size: 0.85em;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .sd-capacity-values {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        .sd-capacity-item {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
        }
        .sd-capacity-item-label {
            font-size: 0.7em;
            opacity: 0.9;
        }
        .sd-capacity-value {
            font-family: 'Courier New', monospace;
            font-size: 1.2em;
            font-weight: 700;
        }
        
        /* 파일 선택 체크박스 */
        .file-checkbox {
            width: 20px;
            height: 20px;
            cursor: pointer;
            flex-shrink: 0;
        }
        .file-selection-controls {
            background: #f8f9fa;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 10px;
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
        }
        .file-selection-controls button {
            padding: 8px 16px;
            font-size: 0.85em;
        }
        .selection-info {
            flex: 1;
            min-width: 150px;
            color: #666;
            font-weight: 600;
            font-size: 0.9em;
        }
        
        .control-panel {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .control-row {
            display: flex;
            gap: 10px;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }
        .control-row:last-child { margin-bottom: 0; }
        label { font-weight: 600; color: #333; font-size: 0.9em; }
        select, button {
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            font-size: 0.9em;
            cursor: pointer;
            transition: all 0.3s;
        }
        select {
            background: white;
            border: 2px solid #667eea;
            color: #333;
        }
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
        }
        button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        button:active { transform: translateY(0); }
        .can-table-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 10px;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        table {
            width: 100%;
            min-width: 500px;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }
        th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 10px 8px;
            text-align: left;
            font-weight: 600;
            font-size: 0.85em;
        }
        td {
            padding: 8px;
            border-bottom: 1px solid #e9ecef;
            font-family: 'Courier New', monospace;
            font-size: 0.8em;
        }
        tr:hover { background: #f8f9fa; }
        .flash-row {
            animation: flashAnimation 0.3s ease-in-out;
        }
        @keyframes flashAnimation {
            0%, 100% { background-color: transparent; }
            50% { background-color: #fff3cd; }
        }
        .mono { font-family: 'Courier New', monospace; }
        h2 {
            color: #333;
            margin: 20px 0 15px 0;
            padding-bottom: 8px;
            border-bottom: 3px solid #667eea;
            font-size: 1.3em;
        }
        .file-list {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
        }
        .file-item {
            background: white;
            padding: 12px;
            margin-bottom: 8px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s;
            gap: 12px;
            flex-wrap: wrap;
        }
        .file-item:hover { transform: translateX(5px); box-shadow: 0 3px 10px rgba(0,0,0,0.1); }
        .file-item.logging { 
            border: 2px solid #11998e;
            background: linear-gradient(to right, rgba(17, 153, 142, 0.05), white);
        }
        .file-info {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        .file-name { 
            font-weight: 600; 
            color: #333; 
            font-size: 0.9em;
            word-break: break-all;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .logging-badge {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: 700;
            animation: pulse 2s ease-in-out infinite;
        }
        .file-size { 
            color: #666; 
            font-size: 0.85em;
            font-weight: 600;
        }
        .file-comment {
            color: #888;
            font-size: 0.8em;
            font-style: italic;
            margin-top: 2px;
            cursor: pointer;
            transition: color 0.3s;
        }
        .file-comment:hover {
            color: #667eea;
        }
        .file-comment.empty {
            color: #ccc;
        }
        .comment-input {
            width: 100%;
            padding: 6px;
            border: 2px solid #667eea;
            border-radius: 4px;
            font-size: 0.85em;
            margin-top: 4px;
            font-family: inherit;
        }
        .comment-actions {
            display: flex;
            gap: 6px;
            margin-top: 6px;
        }
        .comment-actions button {
            padding: 4px 12px;
            font-size: 0.8em;
        }
        .file-actions {
            display: flex;
            gap: 8px;
            flex-shrink: 0;
        }
        .download-btn, .delete-btn {
            padding: 8px 16px;
            font-size: 0.85em;
            white-space: nowrap;
            flex-shrink: 0;
            min-width: 80px;
        }
        .delete-btn {
            background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
        }
        .delete-btn:hover {
            background: linear-gradient(135deg, #d32f3f 0%, #e53935 100%);
        }
        .delete-btn:disabled {
            background: #cccccc;
            cursor: not-allowed;
            opacity: 0.6;
        }
        
        @media (max-width: 768px) {
            body { padding: 5px; }
            .header h1 { font-size: 1.5em; }
            .header p { font-size: 0.85em; }
            .content { padding: 10px; }
            .status-grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
            .status-card { padding: 10px; }
            .status-card h3 { font-size: 0.7em; }
            .status-card .value { font-size: 1.2em; }
            h2 { font-size: 1.1em; }
            .nav a { padding: 8px 12px; font-size: 0.85em; }
            table { min-width: 400px; }
            th, td { padding: 6px 4px; font-size: 0.75em; }
            .time-sync-banner {
                flex-direction: column;
                align-items: stretch;
                padding: 12px 15px;
            }
            .time-sync-info {
                gap: 10px;
            }
            .time-value {
                font-size: 1em;
            }
            .btn-time-sync {
                width: 100%;
                padding: 10px 20px;
            }
            .file-actions {
                width: 100%;
                justify-content: stretch;
            }
            .download-btn, .delete-btn {
                flex: 1;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚗 Byun CAN Logger v1.6</h1>
            <p>Listen-Only Mode - No CAN Bus Impact (RX Only)</p>
        </div>
        
        <div class="nav">
            <a href="/" class="active">📊 Monitor</a>
            <a href="/transmit">📤 Transmit</a>
            <a href="/graph">📈 Graph</a>
            <a href="/graph-view">📊 Graph View</a>
            <a href="/settings">⚙️ Settings</a>
        </div>
        
        <div class="content">
            <div class="time-sync-banner">
                <div class="time-sync-info">
                    <div class="time-info-item">
                        <div class="time-label">CURRENT TIME</div>
                        <div class="time-value" id="current-time">--:--:--</div>
                    </div>
                    <div class="time-info-item">
                        <div class="time-label">CONNECTION</div>
                        <div class="time-value" id="sync-status">연결 중...</div>
                    </div>
                </div>
                <button class="btn-time-sync" onclick="syncTime()">🕐 Sync Time</button>
            </div>
            
            <div class="power-status" id="power-status">
                <div class="power-status-label">
                    <span>⚡</span>
                    <span>POWER STATUS</span>
                </div>
                <div class="power-status-values">
                    <div class="power-status-item">
                        <div class="power-status-item-label">CURRENT</div>
                        <div class="power-status-value" id="voltage-current">-.--V</div>
                    </div>
                    <div class="power-status-item">
                        <div class="power-status-item-label">MIN (1s)</div>
                        <div class="power-status-value" id="voltage-min">-.--V</div>
                    </div>
                </div>
            </div>
            
            <div class="queue-status" id="queue-status">
                <div class="queue-info">
                    <span style="font-size: 1.2em;">📦</span>
                    <span style="font-weight: 700; font-size: 0.9em;">QUEUE STATUS</span>
                </div>
                <div class="queue-bar-container">
                    <div class="queue-bar" id="queue-bar" style="width: 0%;"></div>
                    <div class="queue-text" id="queue-text">0 / 1000</div>
                </div>
            </div>
            
            <div class="sd-capacity" id="sd-capacity">
                <div class="sd-capacity-label">
                    <span>💾</span>
                    <span>SD CARD CAPACITY</span>
                </div>
                <div class="sd-capacity-values">
                    <div class="sd-capacity-item">
                        <div class="sd-capacity-item-label">TOTAL</div>
                        <div class="sd-capacity-value" id="sd-total">0 MB</div>
                    </div>
                    <div class="sd-capacity-item">
                        <div class="sd-capacity-item-label">USED</div>
                        <div class="sd-capacity-value" id="sd-used">0 MB</div>
                    </div>
                    <div class="sd-capacity-item">
                        <div class="sd-capacity-item-label">FREE</div>
                        <div class="sd-capacity-value" id="sd-free">0 MB</div>
                    </div>
                </div>
            </div>
            
            <div class="status-grid">
                <div class="status-card status-off" id="logging-status">
                    <h3>LOGGING</h3>
                    <div class="value">OFF</div>
                </div>
                <div class="status-card status-off" id="sd-status">
                    <h3>SD CARD</h3>
                    <div class="value">NOT READY</div>
                </div>
                <div class="status-card">
                    <h3>MESSAGES</h3>
                    <div class="value" id="msg-count">0</div>
                </div>
                <div class="status-card">
                    <h3>SPEED</h3>
                    <div class="value" id="msg-speed">0/s</div>
                </div>
                <div class="status-card" id="time-sync-card">
                    <h3>TIME SYNC</h3>
                    <div class="value" id="sync-count">0</div>
                </div>
                <div class="status-card" id="file-status">
                    <h3>CURRENT FILE</h3>
                    <div class="value" id="current-file" style="font-size: 0.85em;">-</div>
                </div>
                <div class="status-card" id="filesize-status">
                    <h3>FILE SIZE</h3>
                    <div class="value" id="current-file-size">0 B</div>
                </div>
            </div>
            
            <div class="control-panel">
                <h2>Control Panel</h2>
                <div class="control-row">
                    <label for="can-speed">CAN Speed:</label>
                    <select id="can-speed">
                        <option value="0">125 Kbps</option>
                        <option value="1">250 Kbps</option>
                        <option value="2">500 Kbps</option>
                        <option value="3" selected>1 Mbps</option>
                    </select>
                    <button onclick="setCanSpeed()">Apply</button>
                    <span id="speed-status" style="color: #11998e; font-size: 0.85em; font-weight: 600;"></span>
                </div>
                <div class="control-row">
                    <button onclick="startLogging()" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">Start Logging</button>
                    <button onclick="stopLogging()" style="background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);">Stop Logging</button>
                    <button onclick="refreshFiles()">Refresh Files</button>
                    <button onclick="clearMessages()">Clear Display</button>
                </div>
            </div>
            
            <h2>CAN Messages (by ID)</h2>
            <div class="can-table-container">
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>DLC</th>
                            <th>Data</th>
                            <th>Count</th>
                            <th>Time(ms)</th>
                        </tr>
                    </thead>
                    <tbody id="can-messages"></tbody>
                </table>
            </div>
            
            <h2>Log Files</h2>
            <div class="file-selection-controls">
                <button onclick="selectAllFiles()">Select All</button>
                <button onclick="deselectAllFiles()">Deselect All</button>
                <button onclick="downloadSelectedFiles()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">Download Selected</button>
                <button onclick="deleteSelectedFiles()" style="background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);">Delete Selected</button>
                <div class="selection-info">
                    <span id="selection-count">0 files selected</span>
                </div>
            </div>
            <div class="file-list" id="file-list">
                <p style="text-align: center; color: #666; font-size: 0.9em;">Loading...</p>
            </div>
        </div>
    </div>
    
    <script>
        let ws;
        let canMessages = {};
        let messageOrder = [];
        let lastMessageData = {};
        const speedNames = {0: '125K', 1: '250K', 2: '500K', 3: '1M'};
        let currentLoggingFile = '';
        let selectedFiles = new Set();
        
        function updateSelectionCount() {
            document.getElementById('selection-count').textContent = selectedFiles.size + ' files selected';
        }
        
        function selectAllFiles() {
            document.querySelectorAll('.file-checkbox').forEach(cb => {
                if (!cb.disabled) {
                    cb.checked = true;
                    selectedFiles.add(cb.dataset.filename);
                }
            });
            updateSelectionCount();
        }
        
        function deselectAllFiles() {
            document.querySelectorAll('.file-checkbox').forEach(cb => {
                cb.checked = false;
            });
            selectedFiles.clear();
            updateSelectionCount();
        }
        
        function toggleFileSelection(filename, checked) {
            if (checked) {
                selectedFiles.add(filename);
            } else {
                selectedFiles.delete(filename);
            }
            updateSelectionCount();
        }
        
        function downloadSelectedFiles() {
            if (selectedFiles.size === 0) {
                alert('Please select files to download');
                return;
            }
            
            // 각 파일을 순차적으로 다운로드
            let filesArray = Array.from(selectedFiles);
            let index = 0;
            
            function downloadNext() {
                if (index < filesArray.length) {
                    downloadFile(filesArray[index]);
                    index++;
                    setTimeout(downloadNext, 500); // 500ms 간격으로 다운로드
                }
            }
            
            downloadNext();
        }
        
        function deleteSelectedFiles() {
            if (selectedFiles.size === 0) {
                alert('Please select files to delete');
                return;
            }
            
            let filesArray = Array.from(selectedFiles);
            let fileList = filesArray.join('\\n');
            
            if (!confirm('Are you sure you want to delete ' + selectedFiles.size + ' files?\\n\\n' + fileList + '\\n\\nThis action cannot be undone.')) {
                return;
            }
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                let filenames = JSON.stringify(filesArray);
                ws.send(JSON.stringify({cmd: 'deleteFiles', filenames: filesArray}));
                console.log('Delete multiple files command sent:', filesArray);
                
                // 선택 해제
                selectedFiles.clear();
                updateSelectionCount();
            }
        }
        
        function editComment(filename, currentComment) {
            const fileItem = event.target.closest('.file-item');
            const commentDiv = fileItem.querySelector('.file-comment');
            
            // 이미 편집 중이면 무시
            if (fileItem.querySelector('.comment-input')) {
                return;
            }
            
            // 코멘트 편집 UI 생성
            const input = document.createElement('textarea');
            input.className = 'comment-input';
            input.value = currentComment;
            input.rows = 2;
            input.placeholder = 'Enter comment for this log file...';
            
            const actions = document.createElement('div');
            actions.className = 'comment-actions';
            
            const saveBtn = document.createElement('button');
            saveBtn.textContent = 'Save';
            saveBtn.style.background = 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)';
            saveBtn.onclick = function() {
                saveComment(filename, input.value, fileItem);
            };
            
            const cancelBtn = document.createElement('button');
            cancelBtn.textContent = 'Cancel';
            cancelBtn.style.background = 'linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%)';
            cancelBtn.onclick = function() {
                cancelEditComment(fileItem, currentComment);
            };
            
            actions.appendChild(saveBtn);
            actions.appendChild(cancelBtn);
            
            // 기존 코멘트 숨기고 편집 UI 표시
            commentDiv.style.display = 'none';
            fileItem.querySelector('.file-info').appendChild(input);
            fileItem.querySelector('.file-info').appendChild(actions);
            
            input.focus();
        }
        
        function saveComment(filename, comment, fileItem) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                // JSON 이스케이프
                const escapedComment = comment.replace(/\n/g, '\\n').replace(/"/g, '\\"');
                ws.send(JSON.stringify({cmd: 'saveComment', filename: filename, comment: escapedComment}));
                console.log('Save comment:', filename, comment);
                
                // UI 업데이트
                const commentDiv = fileItem.querySelector('.file-comment');
                const input = fileItem.querySelector('.comment-input');
                const actions = fileItem.querySelector('.comment-actions');
                
                if (comment.trim() === '') {
                    commentDiv.textContent = '💬 Click to add comment';
                    commentDiv.className = 'file-comment empty';
                } else {
                    commentDiv.textContent = '💬 ' + comment;
                    commentDiv.className = 'file-comment';
                }
                
                commentDiv.style.display = 'block';
                commentDiv.onclick = function() { editComment(filename, comment); };
                
                if (input) input.remove();
                if (actions) actions.remove();
            }
        }
        
        function cancelEditComment(fileItem, originalComment) {
            const commentDiv = fileItem.querySelector('.file-comment');
            const input = fileItem.querySelector('.comment-input');
            const actions = fileItem.querySelector('.comment-actions');
            
            commentDiv.style.display = 'block';
            
            if (input) input.remove();
            if (actions) actions.remove();
        }
        
        function updateCurrentTime() {
            const now = new Date();
            const timeStr = now.toLocaleTimeString('ko-KR', {hour12: false});
            document.getElementById('current-time').textContent = timeStr;
        }
        setInterval(updateCurrentTime, 1000);
        updateCurrentTime();
        
        function saveCanSpeed() {
            const speed = document.getElementById('can-speed').value;
            localStorage.setItem('canSpeed', speed);
        }
        
        function loadCanSpeed() {
            const savedSpeed = localStorage.getItem('canSpeed');
            if (savedSpeed !== null) {
                document.getElementById('can-speed').value = savedSpeed;
            }
        }
        
        function syncTime() {
            const now = new Date();
            const timeData = {
                cmd: 'syncTime',
                year: now.getFullYear(),
                month: now.getMonth() + 1,
                day: now.getDate(),
                hour: now.getHours(),
                minute: now.getMinutes(),
                second: now.getSeconds()
            };
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify(timeData));
                console.log('Time sync command sent:', timeData);
            }
        }
        
        function initWebSocket() {
            ws = new WebSocket('ws://' + window.location.hostname + ':81/');
            
            ws.onopen = function() {
                console.log('WebSocket connected');
                document.getElementById('sync-status').textContent = '연결됨';
                document.getElementById('sync-status').style.color = '#38ef7d';
            };
            
            ws.onclose = function() {
                console.log('WebSocket disconnected');
                document.getElementById('sync-status').textContent = '연결 끊김';
                document.getElementById('sync-status').style.color = '#f45c43';
                setTimeout(initWebSocket, 3000);
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket error:', error);
            };
            
            ws.onmessage = function(event) {
                try {
                    const data = JSON.parse(event.data);
                    
                    if (data.type === 'status') {
                        updateStatus(data);
                    } else if (data.type === 'canMessage') {
                        addCanMessage(data);
                        updateCanTable();
                    } else if (data.type === 'canBatch') {
                        updateCanBatch(data.messages);
                    } else if (data.type === 'files') {
                        updateFileList(data.files);
                    } else if (data.type === 'deleteResult') {
                        handleDeleteResult(data);
                    } else if (data.type === 'autoTimeSyncRequest') {
                        // 서버에서 자동 시간 동기화 요청
                        console.log('Auto time sync requested by server');
                        syncTime();
                        // 동기화 완료 알림
                        setTimeout(() => {
                            ws.send(JSON.stringify({cmd: 'requestAutoTimeSync'}));
                        }, 500);
                    } else if (data.type === 'commentResult') {
                        if (data.success) {
                            console.log('Comment saved successfully');
                        } else {
                            alert('Failed to save comment: ' + data.message);
                        }
                    }
                } catch (e) {
                    console.error('Parse error:', e);
                }
            };
        }
        
        function updateStatus(data) {
            const loggingCard = document.getElementById('logging-status');
            const sdCard = document.getElementById('sd-status');
            const timeSyncCard = document.getElementById('time-sync-card');
            const fileCard = document.getElementById('file-status');
            const filesizeCard = document.getElementById('filesize-status');
            
            if (data.logging) {
                loggingCard.classList.add('status-on');
                loggingCard.classList.remove('status-off');
                loggingCard.querySelector('.value').textContent = 'ON';
            } else {
                loggingCard.classList.add('status-off');
                loggingCard.classList.remove('status-on');
                loggingCard.querySelector('.value').textContent = 'OFF';
            }
            
            if (data.sdReady) {
                sdCard.classList.add('status-on');
                sdCard.classList.remove('status-off');
                sdCard.querySelector('.value').textContent = 'READY';
            } else {
                sdCard.classList.add('status-off');
                sdCard.classList.remove('status-on');
                sdCard.querySelector('.value').textContent = 'NOT READY';
            }
            
            if (data.timeSync) {
                timeSyncCard.classList.add('status-on');
                timeSyncCard.classList.remove('status-off');
            } else {
                timeSyncCard.classList.add('status-off');
                timeSyncCard.classList.remove('status-on');
            }
            
            if (data.syncCount !== undefined) {
                document.getElementById('sync-count').textContent = data.syncCount;
            }
            
            if (data.currentFile && data.currentFile !== '') {
                fileCard.classList.add('status-on');
                fileCard.classList.remove('status-off');
                const filename = data.currentFile.startsWith('/') ? data.currentFile.substring(1) : data.currentFile;
                document.getElementById('current-file').textContent = filename;
                currentLoggingFile = filename;
            } else {
                fileCard.classList.remove('status-on', 'status-off');
                document.getElementById('current-file').textContent = '-';
                currentLoggingFile = '';
            }
            
            // 실시간 파일 크기 표시
            if (data.currentFileSize !== undefined) {
                const sizeStr = formatBytes(data.currentFileSize);
                document.getElementById('current-file-size').textContent = sizeStr;
                
                if (data.currentFileSize > 0) {
                    filesizeCard.classList.add('status-on');
                    filesizeCard.classList.remove('status-off');
                } else {
                    filesizeCard.classList.remove('status-on', 'status-off');
                }
            }
            
            document.getElementById('msg-count').textContent = data.msgCount.toLocaleString();
            document.getElementById('msg-speed').textContent = data.msgSpeed + '/s';
            
            // 큐 상태 업데이트
            if (data.queueUsed !== undefined && data.queueSize !== undefined) {
                const queueStatus = document.getElementById('queue-status');
                const queueBar = document.getElementById('queue-bar');
                const queueText = document.getElementById('queue-text');
                
                const percentage = (data.queueUsed / data.queueSize) * 100;
                queueBar.style.width = percentage + '%';
                queueText.textContent = data.queueUsed + ' / ' + data.queueSize;
                
                queueStatus.classList.remove('warning', 'critical');
                if (percentage >= 90) {
                    queueStatus.classList.add('critical');
                } else if (percentage >= 70) {
                    queueStatus.classList.add('warning');
                }
            }
            
            // 전력 상태 업데이트
            if (data.voltage !== undefined) {
                document.getElementById('voltage-current').textContent = data.voltage.toFixed(2) + 'V';
            }
            if (data.minVoltage !== undefined) {
                document.getElementById('voltage-min').textContent = data.minVoltage.toFixed(2) + 'V';
            }
            if (data.lowVoltage !== undefined && data.lowVoltage) {
                document.getElementById('power-status').classList.add('low');
            } else {
                document.getElementById('power-status').classList.remove('low');
            }
            
            // SD 카드 용량 업데이트
            if (data.sdTotalMB !== undefined) {
                const totalGB = (data.sdTotalMB / 1024).toFixed(2);
                const usedMB = data.sdUsedMB || 0;
                const freeMB = data.sdFreeMB || 0;
                
                document.getElementById('sd-total').textContent = totalGB + ' GB';
                
                if (usedMB >= 1024) {
                    document.getElementById('sd-used').textContent = (usedMB / 1024).toFixed(2) + ' GB';
                } else {
                    document.getElementById('sd-used').textContent = usedMB + ' MB';
                }
                
                if (freeMB >= 1024) {
                    document.getElementById('sd-free').textContent = (freeMB / 1024).toFixed(2) + ' GB';
                } else {
                    document.getElementById('sd-free').textContent = freeMB + ' MB';
                }
            }
        }
        
        function addCanMessage(data) {
            const canId = data.id;
            if (!canMessages[canId]) {
                messageOrder.push(canId);
            }
            canMessages[canId] = {
                timestamp: data.timestamp,
                dlc: data.dlc,
                data: data.data,
                updateCount: data.count
            };
        }
        
        function updateCanBatch(messages) {
            messages.forEach(msg => {
                const canId = msg.id;
                if (!canMessages[canId]) {
                    messageOrder.push(canId);
                }
                canMessages[canId] = {
                    timestamp: msg.timestamp,
                    dlc: msg.dlc,
                    data: msg.data,
                    updateCount: msg.count
                };
            });
            updateCanTable();
        }
        
        function updateCanTable() {
            const tbody = document.getElementById('can-messages');
            const existingRows = new Map();
            Array.from(tbody.rows).forEach(row => {
                existingRows.set(row.dataset.canId, row);
            });
            
            messageOrder.forEach(canId => {
                const msg = canMessages[canId];
                let row = existingRows.get(canId);
                
                const prevData = lastMessageData[canId];
                const hasChanged = !prevData || 
                    prevData.data !== msg.data || 
                    prevData.dlc !== msg.dlc ||
                    prevData.timestamp !== msg.timestamp;
                
                // Extended CAN ID 처리 (bit 31 제거)
                let displayId = parseInt(canId, 16);
                if (displayId & 0x80000000) {
                    displayId = displayId & 0x1FFFFFFF;
                }
                const displayIdStr = '0x' + displayId.toString(16).toUpperCase().padStart(8, '0');
                
                if (row) {
                    // ID 셀 업데이트
                    row.cells[0].textContent = displayIdStr;
                    row.cells[1].textContent = msg.dlc;
                    row.cells[2].textContent = msg.data;
                    row.cells[3].textContent = msg.updateCount;
                    row.cells[4].textContent = msg.timestamp;
                    
                    if (hasChanged) {
                        row.classList.add('flash-row');
                        setTimeout(() => row.classList.remove('flash-row'), 300);
                    }
                } else {
                    row = tbody.insertRow();
                    row.dataset.canId = canId;
                    row.innerHTML = 
                        '<td class="mono">' + displayIdStr + '</td>' +
                        '<td>' + msg.dlc + '</td>' +
                        '<td class="mono">' + msg.data + '</td>' +
                        '<td>' + msg.updateCount + '</td>' +
                        '<td>' + msg.timestamp + '</td>';
                    row.classList.add('flash-row');
                    setTimeout(() => row.classList.remove('flash-row'), 300);
                }
                
                lastMessageData[canId] = {
                    data: msg.data,
                    dlc: msg.dlc,
                    timestamp: msg.timestamp,
                    updateCount: msg.updateCount
                };
            });
        }
        
        function updateFileList(files) {
            const fileList = document.getElementById('file-list');
            
            if (!files || files.length === 0) {
                fileList.innerHTML = '<p style="text-align: center; color: #666; font-size: 0.9em;">No log files</p>';
                return;
            }
            
            files.sort((a, b) => {
                return b.name.localeCompare(a.name);
            });
            
            fileList.innerHTML = '';
            files.forEach(file => {
                const isLogging = (currentLoggingFile && file.name === currentLoggingFile);
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item' + (isLogging ? ' logging' : '');
                
                let nameHtml = '<div class="file-name">' + file.name;
                if (isLogging) {
                    nameHtml += '<span class="logging-badge">LOGGING</span>';
                }
                nameHtml += '</div>';
                
                // 코멘트 표시
                const comment = file.comment || '';
                let commentHtml = '';
                if (comment.trim() === '') {
                    commentHtml = '<div class="file-comment empty" onclick="editComment(\'' + file.name + '\', \'\')">💬 Click to add comment</div>';
                } else {
                    const escapedComment = comment.replace(/'/g, "\\'");
                    commentHtml = '<div class="file-comment" onclick="editComment(\'' + file.name + '\', \'' + escapedComment + '\')">💬 ' + comment + '</div>';
                }
                
                const isChecked = selectedFiles.has(file.name);
                
                fileItem.innerHTML = 
                    '<input type="checkbox" class="file-checkbox" data-filename="' + file.name + '" ' +
                    'onchange="toggleFileSelection(\'' + file.name + '\', this.checked)" ' +
                    (isLogging ? 'disabled' : '') + (isChecked ? ' checked' : '') + '>' +
                    '<div class="file-info">' +
                        nameHtml +
                        '<div class="file-size">' + formatBytes(file.size) + '</div>' +
                        commentHtml +
                    '</div>' +
                    '<div class="file-actions">' +
                        '<button class="download-btn" onclick="downloadFile(\'' + file.name + '\')">Download</button>' +
                        '<button class="delete-btn" onclick="deleteFile(\'' + file.name + '\')" ' + 
                        (isLogging ? 'disabled title="Cannot delete file being logged"' : '') + '>Delete</button>' +
                    '</div>';
                fileList.appendChild(fileItem);
            });
            
            updateSelectionCount();
        }
        
        function formatBytes(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
        }
        
        function setCanSpeed() {
            const speed = document.getElementById('can-speed').value;
            const speedName = speedNames[speed];
            
            ws.send(JSON.stringify({cmd: 'setSpeed', speed: parseInt(speed)}));
            
            saveCanSpeed();
            
            const statusSpan = document.getElementById('speed-status');
            if (statusSpan) {
                statusSpan.textContent = '✓ Applied: ' + speedName;
                statusSpan.style.color = '#11998e';
                
                setTimeout(() => {
                    statusSpan.textContent = '';
                }, 3000);
            }
            
            console.log('CAN speed set to:', speedName);
        }
        
        function startLogging() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({cmd: 'startLogging'}));
                console.log('Start logging command sent');
            }
        }
        
        function stopLogging() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({cmd: 'stopLogging'}));
                console.log('Stop logging command sent');
            }
        }
        
        function refreshFiles() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({cmd: 'getFiles'}));
            }
        }
        
        function clearMessages() {
            canMessages = {};
            messageOrder = [];
            lastMessageData = {};
            document.getElementById('can-messages').innerHTML = '';
        }
        
        function downloadFile(filename) {
            window.location.href = '/download?file=' + encodeURIComponent(filename);
        }
        
        function deleteFile(filename) {
            if (!confirm('Are you sure you want to delete "' + filename + '"?\n\nThis action cannot be undone.')) {
                return;
            }
            
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({cmd: 'deleteFile', filename: filename}));
                console.log('Delete file command sent:', filename);
            }
        }
        
        function handleDeleteResult(data) {
            if (data.success) {
                if (data.deletedCount !== undefined) {
                    // 복수 파일 삭제 결과
                    let message = 'Deleted ' + data.deletedCount + ' file(s) successfully';
                    if (data.failedCount > 0) {
                        message += '\nFailed: ' + data.failedCount + ' file(s)';
                    }
                    alert(message);
                    console.log('Multiple files deleted:', data);
                } else {
                    // 단일 파일 삭제 결과
                    console.log('File deleted successfully');
                }
                // 파일 목록은 서버에서 자동으로 갱신됨
            } else {
                alert('Failed to delete file: ' + data.message);
                console.error('Delete failed:', data.message);
            }
        }
        
        window.addEventListener('load', function() {
            loadCanSpeed();
        });
        
        initWebSocket();
        setTimeout(() => { refreshFiles(); }, 2000);
    </script>
</body>
</html>
)rawliteral";

#endif