{% extends "base.html" %}

{% block title %}Terminal - {{ client_id }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <a href="{{ url_for('index') }}" class="btn btn-outline-secondary btn-sm me-3">
                        <i class="fas fa-arrow-left"></i> Back to Dashboard
                    </a>
                    <h3 class="card-title mb-0">
                        <i class="fas fa-terminal"></i> SSH Terminal - {{ client_id }}
                    </h3>
                </div>
                <div>
                    <input type="text" id="sshUsername" class="form-control form-control-sm d-inline-block w-auto me-2" placeholder="Username" value="root">
                    <button id="connectBtn" class="btn btn-success btn-sm">
                        <i class="fas fa-play"></i> Connect
                    </button>
                    <button id="disconnectBtn" class="btn btn-danger btn-sm" disabled>
                        <i class="fas fa-stop"></i> Disconnect
                    </button>
                </div>
            </div>
            <div class="card-body p-2">
                <div id="terminal" class="terminal-container w-100"></div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let term = null;
let connected = false;
let requestId = null;
let pollInterval = null;

document.getElementById('connectBtn').addEventListener('click', connect);
document.getElementById('disconnectBtn').addEventListener('click', disconnect);

function connect() {
    const username = document.getElementById('sshUsername').value;
    if (!username) {
        alert('Please enter a username');
        return;
    }

    // Initialize xterm with proper configuration
    if (!term) {
        term = new Terminal({
            cursorBlink: true,
            cursorStyle: 'block',
            fontSize: 14,
            fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
            theme: {
                background: '#1e1e1e',
                foreground: '#f8f8f2',
                cursor: '#f8f8f2',
                cursorAccent: '#1e1e1e',
                selection: 'rgba(248, 248, 242, 0.3)'
            },
            allowTransparency: true,
            scrollback: 1000,
            tabStopWidth: 4,
            convertEol: true,
            disableStdin: false,
            cursorWidth: 2,
            bellStyle: 'none',
            rightClickSelectsWord: true,
            fastScrollModifier: 'alt',
            fastScrollSensitivity: 5,
            screenReaderMode: false,
            macOptionIsMeta: false,
            macOptionClickForcesSelection: false,
            minimumContrastRatio: 1
        });
        term.open(document.getElementById('terminal'));

        // Load fit addon
        const fitAddon = new FitAddon.FitAddon();
        term.loadAddon(fitAddon);

        // Fit terminal to container
        function fitTerminal() {
            fitAddon.fit();
        }

        // Initial fit after a short delay to ensure DOM is ready
        setTimeout(() => {
            fitTerminal();
            // Calculate dimensions after initial fit
            const initialDimensions = fitAddon.proposeDimensions();
            term._initialCols = initialDimensions.cols || 80;
            term._initialRows = initialDimensions.rows || 24;
        }, 100);

        // Fit on window resize and update backend terminal size
        window.addEventListener('resize', () => {
            fitTerminal();
            // Update terminal size on backend if connected
            if (connected && requestId) {
                const newDimensions = fitAddon.proposeDimensions();
                const newCols = newDimensions.cols || 80;
                const newRows = newDimensions.rows || 24;

                fetch('/terminal/{{ client_id }}/resize', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'request_id=' + encodeURIComponent(requestId) +
                          '&cols=' + encodeURIComponent(newCols) +
                          '&rows=' + encodeURIComponent(newRows)
                }).catch(error => {
                    console.error('Resize error:', error);
                });
            }
        });

        term.focus();
    }

    term.write('Connecting to ' + username + '@{{ client_id }}...\r\n');

    connected = true;
    document.getElementById('connectBtn').disabled = true;
    document.getElementById('disconnectBtn').disabled = false;
    document.getElementById('sshUsername').disabled = true;

    // Use calculated dimensions (either from initial fit or current)
    const cols = term._initialCols || fitAddon.proposeDimensions().cols || 80;
    const rows = term._initialRows || fitAddon.proposeDimensions().rows || 24;

    // Send connect request with terminal dimensions
    fetch('/terminal/{{ client_id }}/connect', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'username=' + encodeURIComponent(username) +
              '&cols=' + encodeURIComponent(cols) +
              '&rows=' + encodeURIComponent(rows)
    })
    .then(response => response.json())
    .then(data => {
        if (data.request_id) {
            requestId = data.request_id;
            if (data.command) {
                term.write('Launching: ' + data.command + '\r\n');
            }
            term.write('Connected successfully!\r\n$ ');
            // Start polling for data with shorter interval for better responsiveness
            pollInterval = setInterval(pollData, 100);
        } else {
            term.write('Error: ' + data.error + '\r\n');
            disconnect();
        }
    })
    .catch(error => {
        term.write('Connection failed: ' + error + '\r\n');
        disconnect();
    });

    // Handle input - send all keystrokes to server, let SSH handle echo
    term.onData(data => {
        if (!connected || !requestId) return;

        // Send all input to server, let SSH handle echo and display
        fetch('/terminal/{{ client_id }}/data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'request_id=' + encodeURIComponent(requestId) + '&data=' + encodeURIComponent(data)
        });
    });
}

function disconnect() {
    connected = false;
    document.getElementById('connectBtn').disabled = false;
    document.getElementById('disconnectBtn').disabled = true;
    document.getElementById('sshUsername').disabled = false;

    if (pollInterval) {
        clearInterval(pollInterval);
        pollInterval = null;
    }

    if (requestId) {
        fetch('/terminal/{{ client_id }}/disconnect', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'request_id=' + encodeURIComponent(requestId)
        });
        requestId = null;
    }

    if (term) {
        term.write('\r\nDisconnected.\r\n');
    }
}

function pollData() {
    if (!requestId) return;
    fetch('/terminal/{{ client_id }}/data?request_id=' + encodeURIComponent(requestId))
    .then(response => response.text())
    .then(data => {
        if (data) {
            // Let the server handle all echo and display logic
            term.write(data.replace(/\n/g, '\r\n'));
        }
    })
    .catch(error => {
        console.error('Polling error:', error);
    });
}

// Focus on terminal when connected
document.addEventListener('keydown', function(e) {
    if (connected && term) {
        term.focus();
    }
});
</script>
{% endblock %}