<script lang="ts">
  import { tick } from "svelte";
  import type { TaskList } from "$lib/types/app";
  import { getCurrentWindow } from "@tauri-apps/api/window";
  import {
    tasks, addTask, completeTask, uncompleteTask, deleteTask,
    taskLists, addTaskList, renameTaskList, deleteTaskList, moveTaskList, sortTaskLists,
    moveTaskToList, moveTaskListToProfile, profiles,
  } from "$lib/stores/page.svelte.js";

  let quickInput = $state("");
  let pinned = $state(true);
  let activeListId = $state("all");
  let showCompleted = $state(false);
  let newListName = $state("");
  let showNewList = $state(false);
  let contextMenuListId = $state<string | null>(null);
  let editingListId = $state<string | null>(null);
  let editingName = $state("");
  let showSortMenu = $state(false);
  let draggingTaskId = $state<string | null>(null);
  let dropHighlightId = $state<string | null>(null);
  let editingInputEl = $state<HTMLInputElement | null>(null);
  let newListInputEl = $state<HTMLInputElement | null>(null);

  // Filtered tasks for active list
  let tasksForActiveList = $derived.by(() => {
    const active = tasks.filter((t) => !t.done);
    if (activeListId === "all") return active;
    if (activeListId === "inbox") return active.filter((t) => !t.listId);
    return active.filter((t) => t.listId === activeListId);
  });

  let completedForActiveList = $derived.by(() => {
    const done = tasks.filter((t) => t.done);
    if (activeListId === "all") return done.slice(0, 10);
    if (activeListId === "inbox") return done.filter((t) => !t.listId).slice(0, 10);
    return done.filter((t) => t.listId === activeListId).slice(0, 10);
  });

  function countForList(listId: string) {
    if (listId === "all") return tasks.filter((t) => !t.done).length;
    if (listId === "inbox") return tasks.filter((t) => !t.done && !t.listId).length;
    return tasks.filter((t) => !t.done && t.listId === listId).length;
  }

  let activeListName = $derived(
    taskLists.find((l) => l.id === activeListId)?.name || "Tasks"
  );

  // Split lists into built-in and custom for section divider
  let builtInLists = $derived(taskLists.filter((l) => l.builtIn));
  let customLists = $derived(taskLists.filter((l) => !l.builtIn));

  function handleQuickAdd(e: KeyboardEvent) {
    if (e.key === "Enter" && quickInput.trim()) {
      const listId = (activeListId === "all" || activeListId === "inbox") ? null : activeListId;
      addTask({ text: quickInput.trim(), bucket: "inbox", listId });
      quickInput = "";
    }
  }

  function handleDragStart(e: PointerEvent) {
    if (e.button !== 0) return;
    if ((e.target as HTMLElement | null)?.closest("button")) return;
    if ((e.target as HTMLElement | null)?.closest("input")) return;
    try { (e.currentTarget as HTMLElement | null)?.setPointerCapture?.(e.pointerId); } catch {}
    getCurrentWindow().startDragging();
  }

  async function togglePin() {
    pinned = !pinned;
    await getCurrentWindow().setAlwaysOnTop(pinned);
  }

  function closeWindow() {
    getCurrentWindow().close();
  }

  // List management
  function handleCreateList(e: KeyboardEvent) {
    if (e.key === "Enter" && newListName.trim()) {
      addTaskList(newListName.trim());
      newListName = "";
      showNewList = false;
    }
    if (e.key === "Escape") {
      showNewList = false;
      newListName = "";
    }
  }

  async function startRenaming(list: TaskList) {
    editingListId = list.id;
    editingName = list.name;
    contextMenuListId = null;
    await tick();
    editingInputEl?.focus();
    editingInputEl?.select();
  }

  function finishRenaming() {
    if (editingListId && editingName.trim()) {
      renameTaskList(editingListId, editingName.trim());
    }
    editingListId = null;
    editingName = "";
  }

  function handleRenameKey(e: KeyboardEvent) {
    if (e.key === "Enter") finishRenaming();
    if (e.key === "Escape") { editingListId = null; editingName = ""; }
  }

  function handleDeleteList(id: string) {
    if (activeListId === id) activeListId = "all";
    deleteTaskList(id);
    contextMenuListId = null;
  }

  function toggleContextMenu(e: MouseEvent, listId: string) {
    e.preventDefault();
    e.stopPropagation();
    contextMenuListId = contextMenuListId === listId ? null : listId;
  }

  // Drag-and-drop: tasks between lists
  function handleTaskDragStart(e: DragEvent, taskId: string) {
    draggingTaskId = taskId;
    e.dataTransfer?.setData("text/plain", taskId);
    if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
  }

  function handleTaskDragEnd() {
    draggingTaskId = null;
    dropHighlightId = null;
  }

  function handleListDragOver(e: DragEvent) {
    e.preventDefault();
    if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
  }

  function handleListDragEnter(e: DragEvent, listId: string) {
    e.preventDefault();
    dropHighlightId = listId;
  }

  function handleListDragLeave(_e: DragEvent, listId: string) {
    if (dropHighlightId === listId) dropHighlightId = null;
  }

  function handleListDrop(e: DragEvent, listId: string) {
    e.preventDefault();
    dropHighlightId = null;
    const taskId = e.dataTransfer?.getData("text/plain");
    if (taskId) {
      moveTaskToList(taskId, listId);
    }
  }

  // Close context menu on outside click
  function handleWindowClick() {
    if (contextMenuListId) contextMenuListId = null;
    if (showSortMenu) showSortMenu = false;
  }

  $effect(() => {
    if (showNewList) {
      tick().then(() => {
        newListInputEl?.focus();
        newListInputEl?.select();
      });
    }
  });
</script>

<svelte:window onclick={handleWindowClick} />

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="flex flex-col h-full bg-bg">
  <!-- Drag handle with title -->
  <div
    class="flex items-center h-[36px] bg-bg-elevated select-none px-3"
    onpointerdown={handleDragStart}
  >
    <span class="text-[12px] font-medium text-text-secondary tracking-wide">
      Lumotia - To-do
    </span>

    <div class="flex-1"></div>

    <!-- Pin button -->
    <button
      class="w-7 h-7 flex items-center justify-center rounded-md
        {pinned ? 'bg-accent/15 text-accent' : 'text-text-tertiary hover:bg-hover hover:text-text-secondary'}"
      onclick={togglePin}
      title={pinned ? "Pinned on top (click to unpin)" : "Pin on top"}
    >
      {#if pinned}
        <svg class="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
          <path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2l-2-2Z" />
        </svg>
      {:else}
        <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
          <path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2l-2-2Z" />
        </svg>
      {/if}
    </button>

    <!-- Close button -->
    <button
      class="w-7 h-7 flex items-center justify-center text-text-tertiary hover:text-danger rounded-md hover:bg-hover ml-1"
      onclick={closeWindow}
      aria-label="Close"
    >
      <svg class="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
        <path d="M18 6L6 18M6 6l12 12" stroke-linecap="round" />
      </svg>
    </button>
  </div>

  <!-- Single-column content -->
  <div class="flex flex-col flex-1 min-h-0">
    <!-- List selector pills -->
    <!-- Outer row does not scroll, so the sort dropdown below is not clipped. -->
    <div class="flex items-center gap-1 px-3 py-2 border-b border-border-subtle">
      <div class="flex items-center gap-1 overflow-x-auto flex-1 min-w-0">
      {#each builtInLists as list (list.id)}
        <button
          class="flex items-center gap-1 px-2.5 py-1 rounded-lg text-[12px] whitespace-nowrap flex-shrink-0
            {activeListId === list.id
              ? 'bg-nav-active text-text font-medium'
              : 'text-text-secondary hover:bg-hover hover:text-text'}
            {dropHighlightId === list.id ? 'ring-1 ring-accent scale-105' : ''}"
          onclick={() => { activeListId = list.id; contextMenuListId = null; }}
          ondragover={handleListDragOver}
          ondragenter={(e) => handleListDragEnter(e, list.id)}
          ondragleave={(e) => handleListDragLeave(e, list.id)}
          ondrop={(e) => handleListDrop(e, list.id)}
        >
          {list.name}
          {#if countForList(list.id) > 0}
            <span class="text-[12px] px-1 rounded-full bg-bg-elevated text-text-secondary">
              {countForList(list.id)}
            </span>
          {/if}
        </button>
      {/each}

      <!-- Divider between built-in and custom lists -->
      {#if customLists.length > 0}
        <span class="w-px h-4 bg-border-subtle flex-shrink-0"></span>
      {/if}

      {#each customLists as list (list.id)}
        {#if editingListId === list.id}
          <input
            bind:this={editingInputEl}
            type="text"
            class="bg-bg-input border border-accent rounded px-2 py-0.5 text-[12px] text-text
                   focus:outline-none w-[100px]"
            bind:value={editingName}
            onkeydown={handleRenameKey}
            onblur={finishRenaming}
            data-no-transition
          />
        {:else}
          <div class="relative flex-shrink-0">
            <button
              class="flex items-center gap-1 px-2.5 py-1 rounded-lg text-[12px] whitespace-nowrap
                {activeListId === list.id
                  ? 'bg-nav-active text-text font-medium'
                  : 'text-text-secondary hover:bg-hover hover:text-text'}
                {dropHighlightId === list.id ? 'ring-1 ring-accent scale-105' : ''}"
              onclick={() => { activeListId = list.id; contextMenuListId = null; }}
              ondblclick={() => startRenaming(list)}
              oncontextmenu={(e) => toggleContextMenu(e, list.id)}
              ondragover={handleListDragOver}
              ondragenter={(e) => handleListDragEnter(e, list.id)}
              ondragleave={(e) => handleListDragLeave(e, list.id)}
              ondrop={(e) => handleListDrop(e, list.id)}
            >
              {#if list.profileId}
                <svg class="w-2.5 h-2.5 text-text-tertiary" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 12a5 5 0 1 0 0-10 5 5 0 0 0 0 10Zm0 2c-5.33 0-8 2.67-8 4v2h16v-2c0-1.33-2.67-4-8-4Z" />
                </svg>
              {/if}
              {list.name}
              {#if countForList(list.id) > 0}
                <span class="text-[12px] px-1 rounded-full bg-bg-elevated text-text-secondary">
                  {countForList(list.id)}
                </span>
              {/if}
            </button>

            <!-- Context menu -->
            {#if contextMenuListId === list.id}
              <div class="absolute left-0 top-full mt-1 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[120px]"
                   onpointerdown={(e) => e.stopPropagation()}>
                <button
                  class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
                  onclick={() => startRenaming(list)}
                >Rename</button>
                <button
                  class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
                  onclick={() => { moveTaskList(list.id, -1); contextMenuListId = null; }}
                >Move left</button>
                <button
                  class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
                  onclick={() => { moveTaskList(list.id, 1); contextMenuListId = null; }}
                >Move right</button>
                {#if profiles.length > 0}
                  <div class="my-1 h-px bg-border-subtle"></div>
                  <p class="px-3 py-0.5 text-[12px] text-text-secondary uppercase tracking-wider">Move to profile</p>
                  {#each profiles as profile}
                    <button
                      class="w-full text-left px-3 py-1 text-[12px] hover:bg-hover
                        {list.profileId === profile.name ? 'text-accent' : 'text-text-secondary hover:text-text'}"
                      onclick={() => { moveTaskListToProfile(list.id, profile.name); contextMenuListId = null; }}
                    >{profile.name}</button>
                  {/each}
                  <button
                    class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
                    onclick={() => { moveTaskListToProfile(list.id, null); contextMenuListId = null; }}
                  >None (unlink)</button>
                {/if}
                <div class="my-1 h-px bg-border-subtle"></div>
                <button
                  class="w-full text-left px-3 py-1 text-[12px] text-danger hover:bg-hover"
                  onclick={() => handleDeleteList(list.id)}
                >Delete</button>
              </div>
            {/if}
          </div>
        {/if}
      {/each}

      <!-- New list button -->
      {#if showNewList}
        <input
          bind:this={newListInputEl}
          type="text"
          class="bg-bg-input border border-border rounded px-2 py-0.5 text-[12px] text-text
                 placeholder:text-text-tertiary focus:outline-none focus:border-accent w-[100px] flex-shrink-0"
          placeholder="List name..."
          bind:value={newListName}
          onkeydown={handleCreateList}
          onblur={() => { showNewList = false; newListName = ""; }}
          data-no-transition
        />
      {:else}
        <button
          class="px-2 py-1 rounded-lg text-[12px] text-accent hover:bg-accent/10 whitespace-nowrap flex-shrink-0"
          onclick={(e) => { e.stopPropagation(); showNewList = true; }}
        >+</button>
      {/if}
      </div>

      <!-- Sort — sibling of the scroll container so its dropdown is not clipped -->
      <div class="relative flex-shrink-0 pl-1">
        <button
          class="px-1.5 py-1 rounded text-[12px] text-text-secondary hover:text-text-secondary"
          onclick={(e) => { e.stopPropagation(); showSortMenu = !showSortMenu; }}
          aria-label="Sort task lists"
        >
          <svg class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M3 6h18M3 12h12M3 18h6" stroke-linecap="round" />
          </svg>
        </button>
        {#if showSortMenu}
          <div class="absolute right-0 top-full mt-1 bg-bg-card border border-border rounded-lg shadow-lg py-1 z-20 animate-fade-in min-w-[110px]"
               onpointerdown={(e) => e.stopPropagation()}>
            <button
              class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
              onclick={() => { sortTaskLists("alpha"); showSortMenu = false; }}
            >Alphabetical</button>
            <button
              class="w-full text-left px-3 py-1 text-[12px] text-text-secondary hover:bg-hover hover:text-text"
              onclick={() => { sortTaskLists("date"); showSortMenu = false; }}
            >By date created</button>
          </div>
        {/if}
      </div>
    </div>

    <!-- Quick add (top — capture first) -->
    <div class="px-3 py-2 border-b border-border-subtle">
      <input
        type="text"
        class="w-full bg-bg-input border border-border rounded-lg px-3 py-2 text-[12px] text-text
               placeholder:text-text-tertiary focus:outline-none focus:border-accent"
        placeholder="Add task to {activeListName}..."
        bind:value={quickInput}
        onkeydown={handleQuickAdd}
        data-no-transition
        data-quick-add
      />
    </div>

    <!-- Tasks -->
    <div class="flex-1 overflow-y-auto px-3 py-2 min-h-0">
      {#if tasksForActiveList.length === 0}
        <div class="flex flex-col items-center justify-center h-full opacity-60">
          <p class="text-[12px] text-text-secondary text-center">No active tasks</p>
          <p class="text-[12px] text-text-secondary mt-1">Type above or drag tasks here</p>
        </div>
      {:else}
        <div class="flex flex-col gap-0.5">
          {#each tasksForActiveList as task (task.id)}
            <div
              class="group flex items-start gap-2.5 px-2 py-2 rounded-lg hover:bg-hover cursor-grab active:cursor-grabbing
                {draggingTaskId === task.id ? 'opacity-40' : ''}"
              draggable="true"
              ondragstart={(e) => handleTaskDragStart(e, task.id)}
              ondragend={handleTaskDragEnd}
            >
              <button
                class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-border-subtle hover:border-accent flex-shrink-0
                       flex items-center justify-center"
                onclick={() => completeTask(task.id)}
                aria-label="Complete"
              ></button>
              <div class="flex-1 min-w-0">
                <p class="text-[12px] text-text leading-[1.4]">{task.text}</p>
                {#if task.createdAt}
                  <p class="text-[12px] text-text-secondary mt-0.5">
                    {new Date(task.createdAt).toLocaleDateString("en-GB", { day: "numeric", month: "short" })}
                  </p>
                {/if}
              </div>
              <button
                class="mt-0.5 text-text-tertiary hover:text-danger opacity-0 group-hover:opacity-100"
                onclick={() => deleteTask(task.id)}
                aria-label="Delete"
              >
                <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>
          {/each}
        </div>
      {/if}

      <!-- Completed -->
      {#if completedForActiveList.length > 0}
        <div class="mt-3">
          <button
            class="flex items-center gap-1.5 text-[12px] text-text-secondary hover:text-text-secondary mb-1.5"
            onclick={() => showCompleted = !showCompleted}
          >
            <svg class="w-2.5 h-2.5 transition-transform {showCompleted ? 'rotate-90' : ''}" viewBox="0 0 24 24" fill="currentColor">
              <path d="M8 5l8 7-8 7z" />
            </svg>
            Done ({completedForActiveList.length})
          </button>
          {#if showCompleted}
            <div class="flex flex-col gap-0.5 animate-fade-in">
              {#each completedForActiveList as task (task.id)}
                <div class="group flex items-start gap-2.5 px-2 py-1.5 rounded-lg opacity-50 hover:opacity-70">
                  <button
                    class="mt-0.5 w-[18px] h-[18px] rounded-md border-2 border-accent bg-accent/20 flex-shrink-0
                           flex items-center justify-center animate-scale-pop"
                    onclick={() => uncompleteTask(task.id)}
                    aria-label="Uncomplete"
                  >
                    <svg class="w-3 h-3 text-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3">
                      <path d="M5 12l5 5L20 7" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                  </button>
                  <p class="text-[12px] text-text-secondary line-through flex-1">{task.text}</p>
                </div>
              {/each}
            </div>
          {/if}
        </div>
      {/if}
    </div>
  </div>
</div>
