<script lang="ts">
  import { page, tasks, addTask, completeTask, uncompleteTask } from "$lib/stores/page.svelte.js";
  import { BUCKET_DOT_COLORS, SIDEBAR_MAX_TASKS } from "$lib/utils/constants.js";

  let quickInput = $state("");
  let recentlyAdded = $state(new Set<string>());

  let activeTasks = $derived(tasks.filter((t) => !t.done).slice(0, SIDEBAR_MAX_TASKS));
  let taskCount = $derived(tasks.filter((t) => !t.done).length);

  function handleQuickAdd(e: KeyboardEvent) {
    if (e.key === "Enter" && quickInput.trim()) {
      addTask({ text: quickInput.trim(), bucket: "inbox" });
      quickInput = "";
    }
  }

  function close() {
    page.taskSidebarOpen = false;
  }

  // Track recently added tasks for highlight animation
  // Use a plain variable (not $state) for previous IDs to avoid
  // read-write loop inside the $effect.
  let prevTaskIds = new Set(tasks.map((t) => t.id));
  $effect(() => {
    const currentIds = new Set(tasks.map((t) => t.id));
    for (const id of currentIds) {
      if (!prevTaskIds.has(id)) {
        recentlyAdded.add(id);
        setTimeout(() => { recentlyAdded.delete(id); }, 2000);
      }
    }
    prevTaskIds = currentIds;
  });
</script>

<aside class="flex flex-col w-[280px] min-w-[280px] bg-sidebar border-l border-border-subtle h-full animate-slide-in-right">
  <!-- Header -->
  <div class="flex items-center gap-2 px-4 pt-4 pb-3">
    <h3 class="text-[13px] font-semibold text-text">Tasks</h3>
    <span class="text-[12px] px-1.5 py-0.5 rounded-full bg-bg-elevated text-text-secondary">
      {taskCount}
    </span>
    <div class="flex-1"></div>
    <button
      class="text-[12px] text-text-secondary hover:text-accent"
      onclick={() => page.current = "tasks"}
    >View all</button>
    <button
      class="w-5 h-5 flex items-center justify-center text-text-tertiary hover:text-text rounded"
      onclick={close}
      aria-label="Close task sidebar"
    >
      <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
      </svg>
    </button>
  </div>

  <!-- Quick add -->
  <div class="px-3 pb-3">
    <input
      type="text"
      class="w-full bg-bg-input border border-border rounded-lg px-3 py-1.5 text-[12px] text-text
             placeholder:text-text-tertiary focus:border-accent"
      placeholder="Add task..."
      bind:value={quickInput}
      onkeydown={handleQuickAdd}
      data-no-transition
    />
  </div>

  <!-- Task list -->
  <div class="flex-1 overflow-y-auto px-3 pb-3 min-h-0">
    {#if activeTasks.length === 0}
      <p class="text-[12px] text-text-secondary text-center py-6 opacity-60">No active tasks</p>
    {:else}
      <div class="flex flex-col gap-0.5">
        {#each activeTasks as task (task.id)}
          <div
            class="group flex items-start gap-2 px-2.5 py-1.5 rounded-lg hover:bg-hover
              {recentlyAdded.has(task.id) ? 'animate-highlight-warm' : ''}"
          >
            <button
              class="mt-0.5 w-4 h-4 rounded border-[1.5px] border-border-subtle hover:border-accent flex-shrink-0"
              onclick={() => completeTask(task.id)}
              aria-label="Complete task"
            ></button>
            <span class="text-[12px] text-text leading-snug flex-1 min-w-0">{task.text}</span>
            <span class="w-2 h-2 rounded-full mt-1 flex-shrink-0 {BUCKET_DOT_COLORS[task.bucket] || 'bg-text-tertiary'}"></span>
          </div>
        {/each}
      </div>
    {/if}
  </div>
</aside>
