<script lang="ts">
  import type { LeafNode } from "../lib/layout/tree";

  let {
    leaves,
    onPick,
    onClose,
  }: {
    leaves: LeafNode[];
    onPick: (leafId: string) => void;
    onClose: () => void;
  } = $props();

  let query = $state("");
  let inputEl: HTMLInputElement | null = $state(null);
  let highlightIndex = $state(0);

  $effect(() => {
    queueMicrotask(() => inputEl?.focus());
  });

  const filtered = $derived.by(() => {
    const q = query.trim().toLowerCase();
    if (!q) return leaves;
    return leaves.filter((l) => {
      const blob = `${l.label ?? ""} ${l.distro ?? ""} ${l.cwd ?? ""}`.toLowerCase();
      return blob.includes(q);
    });
  });

  // Clamp highlight whenever the filtered list changes.
  $effect(() => {
    if (highlightIndex >= filtered.length) highlightIndex = Math.max(0, filtered.length - 1);
  });

  function pick(idx: number) {
    const l = filtered[idx];
    if (l) onPick(l.id);
  }

  function onKey(e: KeyboardEvent) {
    if (e.key === "Escape") {
      e.preventDefault();
      onClose();
    } else if (e.key === "ArrowDown") {
      e.preventDefault();
      if (filtered.length > 0) {
        highlightIndex = (highlightIndex + 1) % filtered.length;
      }
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      if (filtered.length > 0) {
        highlightIndex = (highlightIndex - 1 + filtered.length) % filtered.length;
      }
    } else if (e.key === "Enter") {
      e.preventDefault();
      pick(highlightIndex);
    }
  }
</script>

<button
  class="backdrop"
  onclick={onClose}
  aria-label="Close palette"
></button>

<div class="palette" role="dialog" aria-label="Jump to pane">
  <input
    bind:this={inputEl}
    bind:value={query}
    onkeydown={onKey}
    placeholder="Jump to pane — type to filter, ↑/↓ + Enter"
    class="palette-input"
  />
  <ul class="palette-list">
    {#if filtered.length === 0}
      <li class="empty">No matching panes.</li>
    {:else}
      {#each filtered as leaf, i}
        <li>
          <button
            class="palette-item"
            class:highlight={i === highlightIndex}
            onclick={() => pick(i)}
            onmouseenter={() => (highlightIndex = i)}
          >
            <span class="name">{leaf.label ?? "(unnamed)"}</span>
            <span class="meta">{leaf.distro ?? "default"}</span>
            {#if leaf.cwd}<span class="meta cwd">{leaf.cwd}</span>{/if}
            {#if leaf.broadcast}<span class="meta bcast">📡</span>{/if}
          </button>
        </li>
      {/each}
    {/if}
  </ul>
</div>

<style>
  .backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.55);
    backdrop-filter: blur(2px);
    z-index: 99;
    border: 0;
    padding: 0;
    cursor: default;
  }
  .palette {
    position: fixed;
    top: 12vh;
    left: 50%;
    transform: translateX(-50%);
    width: min(520px, 90vw);
    background: #181818;
    border: 1px solid #2a2a2a;
    border-radius: 6px;
    box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
    z-index: 100;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  .palette-input {
    font: inherit;
    font-size: 14px;
    color: #fff;
    background: #1f1f1f;
    border: none;
    border-bottom: 1px solid #2a2a2a;
    padding: 10px 14px;
    outline: none;
  }
  .palette-list {
    list-style: none;
    margin: 0;
    padding: 4px;
    max-height: 50vh;
    overflow-y: auto;
  }
  .palette-item {
    width: 100%;
    text-align: left;
    background: transparent;
    border: none;
    color: #ccc;
    padding: 6px 10px;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: baseline;
    gap: 10px;
    font: inherit;
    font-size: 12px;
  }
  .palette-item.highlight {
    background: #1a3a5c;
    color: #cce6ff;
  }
  .name {
    font-family: "Cascadia Mono", "JetBrains Mono", "Consolas", monospace;
    font-weight: 600;
  }
  .meta {
    color: #888;
    font-size: 11px;
  }
  .palette-item.highlight .meta {
    color: #9bd;
  }
  .meta.cwd {
    font-family: "Cascadia Mono", "JetBrains Mono", "Consolas", monospace;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .meta.bcast {
    margin-left: auto;
  }
  .empty {
    color: #777;
    font-style: italic;
    padding: 8px 10px;
    list-style: none;
  }
</style>
