<script lang="ts">
  import { onMount } from 'svelte';
  import { appRpc } from './rpc.ts';

  interface Props {
    projectId: string;
  }

  let { projectId }: Props = $props();

  interface SshConfig {
    id: string;
    host: string;
    port: number;
    user: string;
    keyPath: string;
  }

  let connections = $state<SshConfig[]>([]);
  let editing = $state<SshConfig | null>(null);
  let showForm = $state(false);

  // Form fields
  let formHost = $state('');
  let formPort = $state(22);
  let formUser = $state('');
  let formKeyPath = $state('~/.ssh/id_rsa');

  function newConnection() {
    formHost = '';
    formPort = 22;
    formUser = '';
    formKeyPath = '~/.ssh/id_rsa';
    editing = null;
    showForm = true;
  }

  function editConnection(conn: SshConfig) {
    formHost = conn.host;
    formPort = conn.port;
    formUser = conn.user;
    formKeyPath = conn.keyPath;
    editing = conn;
    showForm = true;
  }

  function cancelForm() {
    showForm = false;
    editing = null;
  }

  async function saveConnection() {
    if (!formHost.trim() || !formUser.trim()) return;

    const id = editing?.id ?? `ssh-${Date.now()}`;
    const config: SshConfig = {
      id,
      host: formHost.trim(),
      port: formPort,
      user: formUser.trim(),
      keyPath: formKeyPath.trim(),
    };

    if (editing) {
      connections = connections.map(c => c.id === id ? config : c);
    } else {
      connections = [...connections, config];
    }

    // Persist to settings
    await appRpc.request['settings.set']({
      key: `ssh_configs_${projectId}`,
      value: JSON.stringify(connections),
    }).catch(console.error);

    showForm = false;
    editing = null;
  }

  async function deleteConnection(id: string) {
    connections = connections.filter(c => c.id !== id);
    await appRpc.request['settings.set']({
      key: `ssh_configs_${projectId}`,
      value: JSON.stringify(connections),
    }).catch(console.error);
  }

  function connectSsh(conn: SshConfig) {
    // Fix #3: Spawn ssh directly via PTY shell+args — no shell command injection
    const sessionId = `ssh-${conn.id}-${Date.now()}`;
    const args = ['-p', String(conn.port), `${conn.user}@${conn.host}`];
    if (conn.keyPath) args.unshift('-i', conn.keyPath);

    appRpc.request['pty.create']({
      sessionId,
      cols: 120,
      rows: 30,
      shell: '/usr/bin/ssh',
      args,
    }).catch(console.error);
  }

  onMount(async () => {
    try {
      const { value } = await appRpc.request['settings.get']({ key: `ssh_configs_${projectId}` });
      if (value) {
        connections = JSON.parse(value);
      }
    } catch { /* no saved connections */ }
  });
</script>

<div class="ssh-tab">
  <div class="ssh-header">
    <span class="ssh-title">SSH Connections</span>
    <button class="ssh-add-btn" onclick={newConnection}>+ Add</button>
  </div>

  {#if showForm}
    <div class="ssh-form">
      <div class="ssh-form-row">
        <label class="ssh-label">Host</label>
        <input class="ssh-input" bind:value={formHost} placeholder="example.com" />
      </div>
      <div class="ssh-form-row">
        <label class="ssh-label">Port</label>
        <input class="ssh-input ssh-port" type="number" bind:value={formPort} min="1" max="65535" />
      </div>
      <div class="ssh-form-row">
        <label class="ssh-label">User</label>
        <input class="ssh-input" bind:value={formUser} placeholder="root" />
      </div>
      <div class="ssh-form-row">
        <label class="ssh-label">Key</label>
        <input class="ssh-input" bind:value={formKeyPath} placeholder="~/.ssh/id_rsa" />
      </div>
      <div class="ssh-form-actions">
        <button class="ssh-cancel" onclick={cancelForm}>Cancel</button>
        <button class="ssh-save" onclick={saveConnection}>Save</button>
      </div>
    </div>
  {/if}

  <div class="ssh-list">
    {#if connections.length === 0 && !showForm}
      <div class="ssh-empty">No SSH connections configured</div>
    {/if}
    {#each connections as conn (conn.id)}
      <div class="ssh-card">
        <div class="ssh-card-info">
          <span class="ssh-card-name">{conn.user}@{conn.host}</span>
          <span class="ssh-card-port">:{conn.port}</span>
        </div>
        <div class="ssh-card-actions">
          <button class="ssh-action-btn" onclick={() => connectSsh(conn)} title="Connect">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="5 3 19 12 5 21 5 3"/></svg>
          </button>
          <button class="ssh-action-btn" onclick={() => editConnection(conn)} title="Edit">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
          </button>
          <button class="ssh-action-btn ssh-delete" onclick={() => deleteConnection(conn.id)} title="Delete">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
          </button>
        </div>
      </div>
    {/each}
  </div>
</div>

<style>
  .ssh-tab { display: flex; flex-direction: column; height: 100%; overflow: hidden; }

  .ssh-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0.375rem 0.625rem;
    border-bottom: 1px solid var(--ctp-surface0);
    background: var(--ctp-mantle);
    flex-shrink: 0;
  }

  .ssh-title { font-size: 0.75rem; font-weight: 600; color: var(--ctp-text); }

  .ssh-add-btn {
    padding: 0.15rem 0.5rem; background: color-mix(in srgb, var(--ctp-green) 15%, transparent);
    border: 1px solid var(--ctp-green); border-radius: 0.25rem; color: var(--ctp-green);
    font-size: 0.6875rem; cursor: pointer; font-family: var(--ui-font-family);
  }
  .ssh-add-btn:hover { background: color-mix(in srgb, var(--ctp-green) 25%, transparent); }

  .ssh-form {
    padding: 0.5rem 0.625rem; background: var(--ctp-surface0);
    border-bottom: 1px solid var(--ctp-surface1);
    display: flex; flex-direction: column; gap: 0.375rem; flex-shrink: 0;
  }

  .ssh-form-row { display: flex; align-items: center; gap: 0.5rem; }
  .ssh-label { width: 2.5rem; font-size: 0.6875rem; color: var(--ctp-overlay0); font-weight: 600; flex-shrink: 0; }

  .ssh-input {
    flex: 1; padding: 0.25rem 0.375rem; background: var(--ctp-base); border: 1px solid var(--ctp-surface1);
    border-radius: 0.25rem; color: var(--ctp-text); font-size: 0.75rem; font-family: var(--term-font-family);
  }
  .ssh-input:focus { outline: none; border-color: var(--ctp-blue); }
  .ssh-port { max-width: 4rem; }

  .ssh-form-actions { display: flex; gap: 0.375rem; justify-content: flex-end; margin-top: 0.25rem; }

  .ssh-cancel, .ssh-save {
    padding: 0.2rem 0.5rem; border-radius: 0.25rem; font-size: 0.6875rem;
    cursor: pointer; font-family: var(--ui-font-family);
  }
  .ssh-cancel { background: transparent; border: 1px solid var(--ctp-surface1); color: var(--ctp-subtext0); }
  .ssh-cancel:hover { background: var(--ctp-surface0); color: var(--ctp-text); }
  .ssh-save { background: color-mix(in srgb, var(--ctp-blue) 20%, transparent); border: 1px solid var(--ctp-blue); color: var(--ctp-blue); }
  .ssh-save:hover { background: color-mix(in srgb, var(--ctp-blue) 35%, transparent); }

  .ssh-list { flex: 1; overflow-y: auto; padding: 0.375rem; display: flex; flex-direction: column; gap: 0.25rem; }

  .ssh-empty { padding: 2rem; text-align: center; color: var(--ctp-overlay0); font-size: 0.8125rem; font-style: italic; }

  .ssh-card {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0.375rem 0.5rem; background: var(--ctp-surface0); border: 1px solid var(--ctp-surface1);
    border-radius: 0.25rem; transition: border-color 0.1s;
  }
  .ssh-card:hover { border-color: var(--ctp-surface2); }

  .ssh-card-info { display: flex; align-items: baseline; gap: 0.125rem; }
  .ssh-card-name { font-size: 0.8125rem; color: var(--ctp-text); font-family: var(--term-font-family); }
  .ssh-card-port { font-size: 0.6875rem; color: var(--ctp-overlay0); }

  .ssh-card-actions { display: flex; gap: 0.25rem; }

  .ssh-action-btn {
    width: 1.375rem; height: 1.375rem; background: transparent; border: none;
    color: var(--ctp-overlay1); cursor: pointer; border-radius: 0.2rem;
    display: flex; align-items: center; justify-content: center; padding: 0;
  }
  .ssh-action-btn:hover { background: var(--ctp-surface1); color: var(--ctp-text); }
  .ssh-action-btn.ssh-delete:hover { color: var(--ctp-red); }
  .ssh-action-btn svg { width: 0.75rem; height: 0.75rem; }
</style>
