jQuery(document).ready(function($) {
    const terminalApp = {
        history: [],
        historyIndex: -1,
        currentPath: '/',
        
        init() {
            this.bindEvents();
            this.renderTerminal();
        },
        
        bindEvents() {
            $('#terminal-input').on('keydown', this.handleKeyDown.bind(this));
        },
        
        handleKeyDown(e) {
            if (e.key === 'Enter') {
                this.executeCommand();
            } else if (e.key === 'ArrowUp') {
                this.navigateHistory(-1);
                e.preventDefault();
            } else if (e.key === 'ArrowDown') {
                this.navigateHistory(1);
                e.preventDefault();
            }
        },
        
        navigateHistory(direction) {
            if (this.history.length === 0) return;
            
            this.historyIndex = Math.max(-1, 
                Math.min(this.history.length - 1, this.historyIndex + direction));
            
            if (this.historyIndex === -1) {
                $('#terminal-input').val('');
            } else {
                $('#terminal-input').val(this.history[this.historyIndex]);
            }
        },
        
        executeCommand() {
            const command = $('#terminal-input').val().trim();
            if (!command) return;
            
            this.addToHistory(command);
            this.printLine(`$ ${command}`, 'command');
            $('#terminal-input').val('');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'code_editor_execute_command',
                    command: command,
                    path: this.currentPath,
                    security: codeEditorVars.nonce
                },
                success: (response) => {
                    if (response.success) {
                        this.printLine(response.data.output, 'output');
                        this.currentPath = response.data.currentPath || this.currentPath;
                    } else {
                        this.printLine(response.data.output, 'error');
                    }
                    this.scrollToBottom();
                }
            });
        },
        
        addToHistory(command) {
            this.history.push(command);
            this.historyIndex = -1;
        },
        
        printLine(text, type = 'output') {
            const $output = $('#terminal-output');
            $output.append(`<div class="terminal-line ${type}">${text}</div>`);
        },
        
        scrollToBottom() {
            const $terminal = $('#terminal-container');
            $terminal.scrollTop($terminal[0].scrollHeight);
        },
        
        renderTerminal() {
            $('#terminal-app').html(`
                <div class="terminal-toolbar">
                    <button id="new-ssh-connection" class="button">新建SSH连接</button>
                    <button id="new-rdp-connection" class="button">新建RDP连接</button>
                </div>
                <div id="ssh-connection-modal" style="display:none;">
                    <div class="modal-content">
                        <h3>SSH连接</h3>
                        <div class="form-group">
                            <label>主机</label>
                            <input type="text" id="ssh-host" placeholder="example.com">
                        </div>
                        <div class="form-group">
                            <label>用户名</label>
                            <input type="text" id="ssh-username" placeholder="user">
                        </div>
                        <div class="form-group">
                            <label>密码</label>
                            <input type="password" id="ssh-password">
                        </div>
                        <div class="form-group">
                            <label>私钥(可选)</label>
                            <input type="text" id="ssh-private-key" placeholder="/path/to/private_key">
                        </div>
                        <div class="form-actions">
                            <button id="ssh-connect" class="button button-primary">连接</button>
                            <button id="ssh-cancel" class="button">取消</button>
                        </div>
                    </div>
                </div>
                <div id="terminal-container">
                    <div id="terminal-output"></div>
                    <div class="terminal-input-container">
                        <span class="prompt">${this.currentPath} $</span>
                        <input type="text" id="terminal-input" autocomplete="off">
                    </div>
                </div>
                <div id="rdp-connection-modal" style="display:none;">
                    <div class="modal-content">
                        <h3>RDP连接</h3>
                        <div class="form-group">
                            <label>计算机名</label>
                            <input type="text" id="rdp-host" placeholder="computer-name">
                        </div>
                        <div class="form-group">
                            <label>用户名(可选)</label>
                            <input type="text" id="rdp-username" placeholder="domain\username">
                        </div>
                        <div class="form-group">
                            <label>分辨率</label>
                            <select id="rdp-resolution">
                                <option value="1024x768">1024x768</option>
                                <option value="1280x720">1280x720</option>
                                <option value="1920x1080">1920x1080</option>
                                <option value="fullscreen">全屏</option>
                            </select>
                        </div>
                        <div class="form-actions">
                            <button id="rdp-connect" class="button button-primary">连接</button>
                            <button id="rdp-cancel" class="button">取消</button>
                        </div>
                    </div>
                </div>
            `);

            // SSH连接管理
            $('#new-ssh-connection').on('click', () => {
                $('#ssh-connection-modal').show();
            });

            $('#ssh-cancel').on('click', () => {
                $('#ssh-connection-modal').hide();
            });

            $('#ssh-connect').on('click', () => {
                const host = $('#ssh-host').val().trim();
                const username = $('#ssh-username').val().trim();
                const password = $('#ssh-password').val();
                const privateKey = $('#ssh-private-key').val().trim();

                if (!host || !username) {
                    this.printLine('主机和用户名是必填项', 'error');
                    return;
                }

                // 保存密码（加密存储）
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'code_editor_save_ssh_password',
                        host: host,
                        username: username,
                        password: password,
                        security: codeEditorVars.nonce
                    },
                    success: () => {
                        const command = privateKey 
                            ? `ssh -i ${privateKey} ${username}@${host}`
                            : `ssh ${username}@${host}`;
                        $('#terminal-input').val(command);
                        $('#ssh-connection-modal').hide();
                    }
                });
            });

            // RDP连接管理
            $('#new-rdp-connection').on('click', () => {
                $('#rdp-connection-modal').show();
            });

            $('#rdp-cancel').on('click', () => {
                $('#rdp-connection-modal').hide();
            });

            $('#rdp-connect').on('click', () => {
                const host = $('#rdp-host').val().trim();
                const username = $('#rdp-username').val().trim();
                const resolution = $('#rdp-resolution').val();

                if (!host) {
                    this.printLine('计算机名是必填项', 'error');
                    return;
                }

                const settings = {
                    fullscreen: resolution === 'fullscreen' ? 1 : 0,
                    width: resolution === 'fullscreen' ? 0 : parseInt(resolution.split('x')[0]),
                    height: resolution === 'fullscreen' ? 0 : parseInt(resolution.split('x')[1])
                };

                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'code_editor_rdp_connect',
                        host: host,
                        username: username,
                        settings: settings,
                        security: codeEditorVars.nonce
                    },
                    success: (response) => {
                        if (response.success) {
                            this.downloadRDPFile(response.data.rdp_content, response.data.filename);
                            $('#rdp-connection-modal').hide();
                        } else {
                            this.printLine('RDP Error: ' + response.data, 'error');
                        }
                    }
                });
            });
        },

        downloadRDPFile(content, filename) {
            const blob = new Blob([content], {type: 'application/rdp'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    };

    terminalApp.init();
});
