<script lang="ts">
  import type { Suggestion } from './types';

  export let suggestions: Suggestion[] = [];
  export let onConfirm: (selected: Suggestion[]) => void;

  let selectedIndexes: number[] = [];

  function toggle(index: number) {
    selectedIndexes = selectedIndexes.includes(index)
      ? selectedIndexes.filter((item) => item !== index)
      : [...selectedIndexes, index];
  }

  function confirm() {
    onConfirm(selectedIndexes.map((index) => suggestions[index]));
  }
</script>

<section aria-label="AI 整理建议" class="suggestions">
  {#each suggestions as suggestion, index}
    <label class="suggestion">
      <input
        aria-label={`选择 ${suggestion.title}`}
        type="checkbox"
        checked={selectedIndexes.includes(index)}
        on:change={() => toggle(index)}
      />
      <span class="suggestion-body">
        <strong>{suggestion.title}</strong>
        <small>{suggestion.kind}</small>
        <span>{suggestion.body}</span>
      </span>
    </label>
  {/each}
  <button type="button" on:click={confirm}>创建选中项</button>
</section>
