<script lang="ts">
  /**
   * Side-by-side probability bars for a single decoding step.
   * `after` is optional: baseline shows only the original distribution.
   */
  export interface BarRow {
    tokenId: number;
    text: string;
    before: number;
    after?: number;
    kind?: 'green' | 'red' | 'neutral';
  }

  let {
    rows,
    chosenTokenId = null,
    showAfter = true,
  }: { rows: BarRow[]; chosenTokenId?: number | null; showAfter?: boolean } = $props();

  const max = $derived(
    Math.max(0.0001, ...rows.flatMap((r) => [r.before, showAfter ? (r.after ?? 0) : 0])),
  );
</script>

<div class="bars">
  {#each rows as r}
    <div class="row" class:chosen={r.tokenId === chosenTokenId}>
      <span class="label mono" title={r.text}>{r.text.replace(/\n/g, '\\n') || '␣'}</span>
      <div class="track">
        <div
          class="bar before {r.kind ?? 'neutral'}"
          style="width: {(r.before / max) * 100}%"
        ></div>
        {#if showAfter && r.after !== undefined}
          <div class="bar after {r.kind ?? 'neutral'}" style="width: {(r.after / max) * 100}%"></div>
        {/if}
      </div>
      <span class="pct mono">
        {(r.before * 100).toFixed(1)}%{#if showAfter && r.after !== undefined}
          <span class="arrow">→</span>{(r.after * 100).toFixed(1)}%{/if}
      </span>
    </div>
  {/each}
</div>

<style>
  .bars {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  .row {
    display: grid;
    grid-template-columns: 96px 1fr 118px;
    align-items: center;
    gap: 8px;
    font-size: 12.5px;
  }
  .row.chosen .label {
    font-weight: 700;
    color: var(--accent);
  }
  .label {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .track {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }
  .bar {
    height: 7px;
    border-radius: 3px;
    background: var(--panel-3);
    min-width: 1px;
    transition: width 0.15s ease-out;
  }
  .bar.before {
    background: var(--border-strong);
  }
  .bar.after.green {
    background: var(--green);
  }
  .bar.after.red {
    background: var(--red);
  }
  .bar.after.neutral {
    background: var(--accent);
  }
  .bar.before.green {
    background: var(--green-border);
  }
  .bar.before.red {
    background: var(--red-border);
  }
  .pct {
    text-align: right;
    color: var(--text-dim);
  }
  .arrow {
    margin: 0 3px;
  }
</style>
