<script>
  import { createEventDispatcher } from 'svelte';

  export let conversation = [];
  export let busy = false;

  let draft = '';
  const dispatch = createEventDispatcher();

  function submit(message = draft) {
    const next = String(message ?? '').trim();
    if (!next || busy) {
      return;
    }

    dispatch('send', next);
    draft = '';
  }
</script>

<section class="sage-shell">
  <div class="conversation">
    {#if conversation.length === 0}
      <article class="message sage">
        <strong>Sage</strong>
        <p>Ask for a hint, a task summary, the target VM, or relevant docs.</p>
      </article>
    {:else}
      {#each conversation as entry}
        <article class={`message ${entry.role}`}>
          <strong>{entry.role === 'user' ? 'You' : 'Sage'}</strong>
          <p>{entry.body}</p>
          {#if entry.followUps?.length}
            <div class="chips">
              {#each entry.followUps as followUp}
                <button disabled={busy} on:click={() => submit(followUp)}>{followUp}</button>
              {/each}
            </div>
          {/if}
        </article>
      {/each}
    {/if}
  </div>

  <form class="composer" on:submit|preventDefault={() => submit()}>
    <textarea bind:value={draft} rows="3" placeholder="Ask Sage for a hint or summary…"></textarea>
    <button class="primary" disabled={busy}>{busy ? 'Thinking…' : 'Send'}</button>
  </form>
</section>

<style>
  .sage-shell {
    display: grid;
    gap: 1rem;
    min-height: 70vh;
    grid-template-rows: minmax(0, 1fr) auto;
  }

  .conversation,
  .composer {
    background: var(--panel);
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 1rem;
    box-shadow: var(--shadow);
  }

  .conversation {
    display: grid;
    gap: 0.9rem;
    align-content: start;
    overflow: auto;
  }

  .message {
    max-width: min(860px, 100%);
    border-radius: 18px;
    padding: 0.9rem 1rem;
    background: rgba(255, 255, 255, 0.03);
  }

  .message.user {
    justify-self: end;
    background: rgba(214, 104, 56, 0.14);
  }

  .message p {
    margin: 0.4rem 0 0;
    white-space: pre-wrap;
    line-height: 1.6;
    color: #f1ede5;
  }

  .chips {
    display: flex;
    flex-wrap: wrap;
    gap: 0.6rem;
    margin-top: 0.8rem;
  }

  .chips button,
  .primary {
    border: 1px solid var(--border);
    border-radius: 14px;
    padding: 0.7rem 0.9rem;
    background: rgba(255, 255, 255, 0.04);
    color: inherit;
  }

  .composer {
    display: grid;
    gap: 0.8rem;
  }

  textarea {
    width: 100%;
    border-radius: 16px;
    border: 1px solid var(--border);
    background: rgba(9, 10, 13, 0.5);
    color: inherit;
    padding: 0.9rem 1rem;
    resize: vertical;
    min-height: 88px;
    box-sizing: border-box;
  }

  .primary {
    justify-self: start;
    background: var(--accent);
    color: #fff7f1;
    border: 0;
  }
</style>
