// 确保在DOM加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
    console.log('DOMContentLoaded - Record.js executing');
    
    // 录制相关全局变量
    window.isRecording = false;
    window.isPlaying = false;
    window.recordedActions = [];
    window.recordingStartTime = 0;

    // 获取录制和回放按钮
    const recordBtn = document.getElementById('recordBtn');
    const playbackBtn = document.getElementById('playbackBtn');
    const status = document.getElementById('status');
    
    // 获取轨迹管理相关元素
    const pathNameInput = document.getElementById('pathName');
    const savePathBtn = document.getElementById('savePathBtn');
    const pathList = document.getElementById('pathList');

    // 调试信息
    console.log('Record.js loaded');
    console.log('recordBtn:', recordBtn);
    console.log('playbackBtn:', playbackBtn);
    console.log('status:', status);
    console.log('pathNameInput:', pathNameInput);
    console.log('savePathBtn:', savePathBtn);
    console.log('pathList:', pathList);
    
    // 列出已保存的轨迹
    function listPaths() {
        fetch('/list_paths')
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 清空路径列表
                    pathList.innerHTML = '';
                    
                    // 添加路径到列表
                    data.paths.forEach(path => {
                        const li = document.createElement('li');
                        li.innerHTML = `
                            <span>${path}</span>
                            <div>
                                <button class="load-btn" data-path="${path}">加载</button>
                                <button class="delete-btn" data-path="${path}">删除</button>
                            </div>
                        `;
                        pathList.appendChild(li);
                    });
                    
                    // 添加加载和删除按钮的事件监听器
                    document.querySelectorAll('.load-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const pathName = this.getAttribute('data-path');
                            loadPath(pathName);
                        });
                    });
                    
                    document.querySelectorAll('.delete-btn').forEach(btn => {
                        btn.addEventListener('click', function() {
                            const pathName = this.getAttribute('data-path');
                            deletePath(pathName);
                        });
                    });
                } else {
                    status.innerHTML = `<p>错误: ${data.message}</p>`;
                }
            })
            .catch(error => {
                status.innerHTML = `<p>通信错误: ${error.message}</p>`;
            });
    }
    
    // 保存轨迹
    function savePath() {
        const pathName = pathNameInput.value.trim();
        if (!pathName) {
            status.innerHTML = '<p>请输入轨迹名称</p>';
            return;
        }
        
        if (window.recordedActions.length === 0) {
            status.innerHTML = '<p>没有可保存的轨迹</p>';
            return;
        }
        
        fetch('/save_path', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name: pathName, actions: window.recordedActions })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                status.innerHTML = `<p>${data.message}</p>`;
                // 清空输入框
                pathNameInput.value = '';
                // 更新轨迹列表
                listPaths();
            } else {
                status.innerHTML = `<p>错误: ${data.message}</p>`;
            }
        })
        .catch(error => {
            status.innerHTML = `<p>通信错误: ${error.message}</p>`;
        });
    }
    
    // 加载轨迹
    function loadPath(pathName) {
        fetch(`/load_path?name=${pathName}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    window.recordedActions = data.data.actions;
                    status.innerHTML = `<p>轨迹 ${pathName} 加载成功，共 ${window.recordedActions.length} 个操作</p>`;
                } else {
                    status.innerHTML = `<p>错误: ${data.message}</p>`;
                }
            })
            .catch(error => {
                status.innerHTML = `<p>通信错误: ${error.message}</p>`;
            });
    }
    
    // 删除轨迹
    function deletePath(pathName) {
        if (confirm(`确定要删除轨迹 ${pathName} 吗？`)) {
            fetch('/delete_path', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: pathName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    status.innerHTML = `<p>${data.message}</p>`;
                    // 更新轨迹列表
                    listPaths();
                } else {
                    status.innerHTML = `<p>错误: ${data.message}</p>`;
                }
            })
            .catch(error => {
                status.innerHTML = `<p>通信错误: ${error.message}</p>`;
            });
        }
    }
    
    // 保存轨迹按钮点击事件
    if (savePathBtn) {
        savePathBtn.addEventListener('click', savePath);
    }
    
    // 页面加载时列出已保存的轨迹
    listPaths();

    // 录制按钮点击事件 - 支持鼠标和触摸事件
    function toggleRecording() {
        console.log('toggleRecording called, current isRecording:', window.isRecording);
        if (window.isPlaying) {
            alert('正在回放，不能录制');
            return;
        }
        
        if (window.isRecording) {
            // 停止录制
            window.isRecording = false;
            recordBtn.textContent = '开始录制';
            status.innerHTML = `<p>录制完成，共记录 ${window.recordedActions.length} 个操作</p>`;
            console.log('Recording stopped, actions:', window.recordedActions);
        } else {
            // 开始录制
            window.isRecording = true;
            window.recordedActions = [];
            window.recordingStartTime = Date.now();
            // 重置上一个记录的动作
            if (window.lastRecordedAction !== undefined) {
                window.lastRecordedAction = null;
            }
            recordBtn.textContent = '停止录制';
            status.innerHTML = `<p>开始录制...</p>`;
            console.log('Recording started');
        }
    }

    console.log('Adding click event listener to recordBtn');
    recordBtn.addEventListener('click', toggleRecording);

    // 录制按钮 - 触摸事件
    console.log('Adding touchstart event listener to recordBtn');
    recordBtn.addEventListener('touchstart', (e) => {
        console.log('Touchstart event on recordBtn');
        e.preventDefault(); // 防止默认行为
        toggleRecording();
    });

    // 回放按钮点击事件 - 支持鼠标和触摸事件
    function startPlayback() {
        console.log('startPlayback called, recordedActions:', window.recordedActions);
        if (window.isRecording) {
            alert('请先停止录制');
            return;
        }
        
        if (window.recordedActions.length === 0) {
            status.innerHTML = `<p>没有可回放的操作</p>`;
            console.log('No actions to playback');
            return;
        }
        
        // 保存当前录制状态并禁用录制
        const originalRecordingState = window.isRecording;
        window.isRecording = false;
        window.isPlaying = true;
        
        status.innerHTML = `<p>开始回放...</p>`;
        console.log('Starting playback');
        
        // 按时间顺序回放操作
        let currentTime = 0;
        const totalDuration = window.recordedActions[window.recordedActions.length - 1].timestamp;
        
        // 执行所有操作
        window.recordedActions.forEach((action, index) => {
            if (index === 0) {
                // 第一个操作立即执行
                console.log('Executing action immediately:', action);
                controlMotor(action.direction);
            } else {
                // 计算与前一个操作的时间差
                const prevAction = window.recordedActions[index - 1];
                const delay = action.timestamp - prevAction.timestamp;
                currentTime += delay;
                
                console.log('Scheduling action:', action, 'at delay:', currentTime);
                setTimeout(() => {
                    // 调用控制函数执行操作
                    console.log('Executing action:', action);
                    controlMotor(action.direction);
                }, currentTime);
            }
        });
        
        // 回放完成后，确保发送停止请求
        setTimeout(() => {
            console.log('Playback completed, sending stop command');
            controlMotor('stop');
            status.innerHTML = `<p>回放完成</p>`;
            console.log('Playback completed');
            // 恢复原始录制状态
            window.isRecording = originalRecordingState;
            window.isPlaying = false;
        }, totalDuration + 2000); // 增加延迟，确保所有动作都已执行
    }

    console.log('Adding click event listener to playbackBtn');
    playbackBtn.addEventListener('click', startPlayback);

    // 回放按钮 - 触摸事件
    console.log('Adding touchstart event listener to playbackBtn');
    playbackBtn.addEventListener('touchstart', (e) => {
        console.log('Touchstart event on playbackBtn');
        e.preventDefault(); // 防止默认行为
        startPlayback();
    });
});