<!DOCTYPE html>
<html lang="<%= typeof lang !== 'undefined' ? lang : 'en' %>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= typeof t !== 'undefined' ? t('terminal.title') : 'SSH Terminal' %> - <%= node.name %></title>
    <%- include('partials/favicon') %>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@tabler/icons-webfont@3.19.0/dist/tabler-icons.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            background: #0d1117;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .header {
            background: #161b22;
            border-bottom: 1px solid #30363d;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .header-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .header h1 {
            color: #c9d1d9;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .header h1 i { margin-right: 6px; }
        .header .btn { display: inline-flex; align-items: center; gap: 6px; }
        
        .status {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            color: #8b949e;
        }
        
        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #f85149;
        }
        
        .status-dot.connected { background: #3fb950; }
        .status-dot.connecting { background: #d29922; animation: pulse 1s infinite; }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .header-right {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 6px 12px;
            border: 1px solid #30363d;
            border-radius: 6px;
            background: #21262d;
            color: #c9d1d9;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.15s;
        }
        
        .btn:hover { background: #30363d; }
        .btn-danger { border-color: #f85149; color: #f85149; }
        .btn-danger:hover { background: #f8514922; }
        
        .terminal-container {
            flex: 1;
            padding: 10px;
            overflow: hidden;
        }
        
        #terminal {
            height: 100%;
        }
        
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
        }
        
        .overlay.hidden { display: none; }
        
        .overlay-content {
            text-align: center;
            color: #c9d1d9;
        }
        
        .overlay-content h2 {
            font-size: 18px;
            margin-bottom: 10px;
        }
        
        .overlay-content p {
            color: #8b949e;
            font-size: 14px;
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 3px solid #30363d;
            border-top-color: #58a6ff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .error-message {
            background: #f8514922;
            border: 1px solid #f85149;
            border-radius: 6px;
            padding: 15px;
            color: #f85149;
            max-width: 400px;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <h1><i class="ti ti-device-desktop"></i> <%= node.name %> (<%= node.ip %>)</h1>
            <div class="status">
                <div class="status-dot connecting" id="statusDot"></div>
                <span id="statusText"><%= typeof t !== 'undefined' ? t('terminal.connecting') : 'Connecting...' %></span>
            </div>
        </div>
        <div class="header-right">
            <button class="btn" onclick="reconnect()"><i class="ti ti-refresh"></i> <%= typeof t !== 'undefined' ? t('nodes.reconnect') : 'Reconnect' %></button>
            <button class="btn btn-danger" onclick="disconnect()"><i class="ti ti-x"></i> <%= typeof t !== 'undefined' ? t('common.close') : 'Close' %></button>
        </div>
    </div>
    
    <div class="terminal-container">
        <div id="terminal"></div>
    </div>
    
    <div class="overlay" id="connectingOverlay">
        <div class="overlay-content">
            <div class="spinner"></div>
            <h2><%= typeof t !== 'undefined' ? t('terminal.connectingTo') : 'Connecting to' %> <%= node.name %></h2>
            <p><%= node.ip %>:<%= node.ssh?.port || 22 %></p>
        </div>
    </div>
    
    <div class="overlay hidden" id="errorOverlay">
        <div class="overlay-content">
            <div class="error-message">
                <h2><i class="ti ti-alert-circle"></i> <%= typeof t !== 'undefined' ? t('terminal.connectionError') : 'Connection error' %></h2>
                <p id="errorText"></p>
                <button class="btn" onclick="reconnect()" style="margin-top: 15px;"><%= typeof t !== 'undefined' ? t('terminal.tryAgain') : 'Try Again' %></button>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xterm-addon-web-links@0.9.0/lib/xterm-addon-web-links.min.js"></script>
    <script>
        const nodeId = <%- JSON.stringify(node._id.toString()) %>;
        const i18n = {
            connecting: <%- JSON.stringify(typeof t !== "undefined" ? t("terminal.connecting") : "Connecting...") %>,
            connected: <%- JSON.stringify(typeof t !== "undefined" ? t("terminal.connected") : "Connected") %>,
            disconnected: <%- JSON.stringify(typeof t !== "undefined" ? t("terminal.disconnected") : "Disconnected") %>,
            connectionClosed: <%- JSON.stringify(typeof t !== "undefined" ? t("terminal.connectionClosed") : "[Connection closed]") %>,
            wsError: <%- JSON.stringify(typeof t !== "undefined" ? t("terminal.wsError") : "WebSocket connection error") %>
        };
        
        let ws = null;
        let term = null;
        let fitAddon = null;
        
        function initTerminal() {
            term = new Terminal({
                cursorBlink: true,
                fontSize: 14,
                fontFamily: 'Menlo, Monaco, "Courier New", monospace',
                theme: {
                    background: '#0d1117',
                    foreground: '#c9d1d9',
                    cursor: '#58a6ff',
                    cursorAccent: '#0d1117',
                    selection: '#264f78',
                    black: '#484f58',
                    red: '#ff7b72',
                    green: '#3fb950',
                    yellow: '#d29922',
                    blue: '#58a6ff',
                    magenta: '#bc8cff',
                    cyan: '#39c5cf',
                    white: '#b1bac4',
                    brightBlack: '#6e7681',
                    brightRed: '#ffa198',
                    brightGreen: '#56d364',
                    brightYellow: '#e3b341',
                    brightBlue: '#79c0ff',
                    brightMagenta: '#d2a8ff',
                    brightCyan: '#56d4dd',
                    brightWhite: '#f0f6fc',
                }
            });
            
            fitAddon = new FitAddon.FitAddon();
            term.loadAddon(fitAddon);
            term.loadAddon(new WebLinksAddon.WebLinksAddon());
            
            term.open(document.getElementById('terminal'));
            fitAddon.fit();
            
            term.onData((data) => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({ type: 'input', data }));
                }
            });
            
            window.addEventListener('resize', () => {
                fitAddon.fit();
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({ 
                        type: 'resize', 
                        cols: term.cols, 
                        rows: term.rows 
                    }));
                }
            });
        }
        
        function connect() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/ws/terminal/${nodeId}`;
            
            document.getElementById('connectingOverlay').classList.remove('hidden');
            document.getElementById('errorOverlay').classList.add('hidden');
            updateStatus('connecting', i18n.connecting);
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = () => {
                console.log('WebSocket connected');
            };
            
            ws.onmessage = (event) => {
                const msg = JSON.parse(event.data);
                
                switch (msg.type) {
                    case 'connected':
                        document.getElementById('connectingOverlay').classList.add('hidden');
                        updateStatus('connected', i18n.connected);
                        term.focus();
                        ws.send(JSON.stringify({ 
                            type: 'resize', 
                            cols: term.cols, 
                            rows: term.rows 
                        }));
                        break;
                        
                    case 'output':
                        term.write(msg.data);
                        break;
                        
                    case 'error':
                        showError(msg.message);
                        break;
                        
                    case 'closed':
                        updateStatus('disconnected', i18n.disconnected);
                        term.write('\r\n\x1b[31m' + i18n.connectionClosed + '\x1b[0m\r\n');
                        break;
                }
            };
            
            ws.onerror = (error) => {
                console.error('WebSocket error:', error);
                showError(i18n.wsError);
            };
            
            ws.onclose = () => {
                updateStatus('disconnected', i18n.disconnected);
            };
        }
        
        function updateStatus(status, text) {
            const dot = document.getElementById('statusDot');
            const statusText = document.getElementById('statusText');
            
            dot.className = 'status-dot ' + status;
            statusText.textContent = text;
        }
        
        function showError(message) {
            document.getElementById('connectingOverlay').classList.add('hidden');
            document.getElementById('errorOverlay').classList.remove('hidden');
            document.getElementById('errorText').textContent = message;
            updateStatus('disconnected', i18n.disconnected);
        }
        
        function reconnect() {
            if (ws) {
                ws.close();
            }
            if (term) {
                term.clear();
            }
            connect();
        }
        
        function disconnect() {
            if (ws) {
                ws.close();
            }
            window.close();
            setTimeout(() => {
                window.location.href = '/panel/nodes';
            }, 100);
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            initTerminal();
            connect();
        });
    </script>
</body>
</html>
