<script lang="ts">
  import {onDestroy, onMount} from 'svelte';

  import NodePicker from './core/NodePicker.svelte';
  import type {NodePaletteItem} from './utils/nodePalette';

  const { nodes = [], onSelectNode }: {
    nodes: NodePaletteItem[];
    onSelectNode?: (node: NodePaletteItem) => void;
  } = $props();

  let panelVisible = $state(false);
  let toolbarElement: HTMLDivElement | null = null;

  function togglePanel() {
    panelVisible = !panelVisible;
  }

  function handleSelect(node: NodePaletteItem) {
    onSelectNode?.(node);
    panelVisible = false;
  }

  function handlePointerDown(event: PointerEvent) {
    if (!panelVisible || !toolbarElement) {
      return;
    }
    const target = event.target as Node | null;
    if (target && !toolbarElement.contains(target)) {
      panelVisible = false;
    }
  }

  onMount(() => {
    window.addEventListener('pointerdown', handlePointerDown);
  });

  onDestroy(() => {
    window.removeEventListener('pointerdown', handlePointerDown);
  });
</script>

<div class="tf-toolbar" bind:this={toolbarElement}>
  {#if panelVisible}
    <div class="tf-toolbar-panel">
      <NodePicker nodes={nodes} onSelect={handleSelect} />
    </div>
  {/if}

  <button type="button" class="tf-toolbar-trigger tf-bar-add-btn" onclick={togglePanel}>
    <span class="tf-toolbar-trigger-icon">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
        <path d="M11 11V6H13V11H18V13H13V18H11V13H6V11H11Z"></path>
      </svg>
    </span>
    {panelVisible ? '收起节点' : '增加节点'}
  </button>
</div>
