<script lang="ts">
  export let runCommand: (command: string, source?: 'terminal' | 'palette') => string | void;

  let input = '';
  let lines: Array<{ kind: 'input' | 'output'; text: string }> = [
    { kind: 'output', text: 'ianOS terminal' },
    { kind: 'output', text: 'Type help for commands. Type no-beige for policy.' }
  ];

  function submit() {
    const command = input.trim();
    if (!command) return;

    lines = [...lines, { kind: 'input', text: `> ${command}` }];
    input = '';

    const response = runCommand(command, 'terminal');
    if (response) {
      lines = [...lines, { kind: 'output', text: response }];
    }
  }

  function inputKeydown(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      event.preventDefault();
      submit();
    }
  }
</script>

<div class="terminal-panel">
  <div class="terminal-output" aria-live="polite">
    {#each lines as line}
      <pre class:terminal-input-line={line.kind === 'input'}>{line.text}</pre>
    {/each}
  </div>
  <form class="terminal-form" on:submit|preventDefault={submit}>
    <label for="terminal-input">&gt;</label>
    <input id="terminal-input" bind:value={input} autocomplete="off" spellcheck="false" on:keydown={inputKeydown} />
    <button type="submit">run</button>
  </form>
</div>
