<script lang="ts">
  import { SYMBOLS, SYMBOL_GROUPS } from '$lib/symbols.js';
  import { startPaletteDrag } from '$lib/canvas/interactions.js';

  function onMousedown(e: MouseEvent, sym: (typeof SYMBOLS)[number]) {
    if (e.button !== 0) return;
    e.preventDefault();
    startPaletteDrag(e, sym);
  }

  interface SubgroupData {
    name: string;
    symbols: (typeof SYMBOLS)[number][];
  }

  interface GroupData {
    name: string;
    subgroups: SubgroupData[];
    symbols: (typeof SYMBOLS)[number][]; // symbols without subgroup
  }

  const grouped: GroupData[] = SYMBOL_GROUPS.map(g => {
    const groupSymbols = SYMBOLS.filter(s => s.group === g);
    const subgroupNames = [...new Set(groupSymbols.filter(s => s.subgroup).map(s => s.subgroup!))];
    return {
      name: g,
      subgroups: subgroupNames.map(sg => ({
        name: sg,
        symbols: groupSymbols.filter(s => s.subgroup === sg),
      })),
      symbols: groupSymbols.filter(s => !s.subgroup),
    };
  });

  let expandedSubgroups = $state<Set<string>>(new Set());

  function toggleSubgroup(key: string) {
    const next = new Set(expandedSubgroups);
    if (next.has(key)) next.delete(key);
    else next.add(key);
    expandedSubgroups = next;
  }
</script>

<div class="palette">
  {#each grouped as group (group.name)}
    <div class="group">
      <div class="group-header">{group.name}</div>

      {#if group.subgroups.length > 0}
        {#each group.subgroups as sub (sub.name)}
          {@const key = `${group.name}/${sub.name}`}
          <button class="subgroup-header" onclick={() => toggleSubgroup(key)}>
            <span class="chevron" class:open={expandedSubgroups.has(key)}></span>
            {sub.name}
          </button>
          {#if expandedSubgroups.has(key)}
            <div class="group-items subgroup-items">
              {#each sub.symbols as sym (sym.id)}
                <button
                  class="palette-item"
                  title={sym.name}
                  onmousedown={(e) => onMousedown(e, sym)}
                >
                  <img
                    src={sym.file}
                    alt={sym.name}
                    draggable="false"
                    style={sym.defaultRotation ? `transform: rotate(${sym.defaultRotation}deg)` : ''}
                  />
                  <span>{sym.name}</span>
                </button>
              {/each}
            </div>
          {/if}
        {/each}
      {/if}

      {#if group.symbols.length > 0}
        <div class="group-items">
          {#each group.symbols as sym (sym.id)}
            <button
              class="palette-item"
              title={sym.name}
              onmousedown={(e) => onMousedown(e, sym)}
            >
              <img
                src={sym.file}
                alt={sym.name}
                draggable="false"
                style={sym.defaultRotation ? `transform: rotate(${sym.defaultRotation}deg)` : ''}
              />
              <span>{sym.name}</span>
            </button>
          {/each}
        </div>
      {/if}
    </div>
  {/each}
</div>

<style>
  .palette {
    flex: 1;
    overflow-y: auto;
    padding: 0 2px;
    min-height: 0;
  }

  .group {
    margin-bottom: 6px;
  }

  .group-header {
    font-size: 10px;
    color: #e94560;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: 600;
    padding: 4px 6px 2px;
    position: sticky;
    top: 0;
    background: #16213e;
    z-index: 1;
  }

  .subgroup-header {
    display: flex;
    align-items: center;
    gap: 4px;
    width: 100%;
    padding: 3px 6px 3px 12px;
    background: none;
    border: none;
    color: #8899aa;
    font-size: 9px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
    cursor: pointer;
    user-select: none;
  }

  .subgroup-header:hover {
    color: #e94560;
  }

  .chevron {
    display: inline-block;
    width: 0;
    height: 0;
    border-top: 4px solid transparent;
    border-bottom: 4px solid transparent;
    border-left: 5px solid currentColor;
    transition: transform 0.15s ease;
  }

  .chevron.open {
    transform: rotate(90deg);
  }

  .subgroup-items {
    padding-left: 8px;
  }

  .group-items {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }

  .palette-item {
    display: flex;
    align-items: center;
    gap: 6px;
    width: 100%;
    padding: 4px 6px;
    background: #0f3460;
    border: 1px solid #1a1a5e;
    border-radius: 4px;
    cursor: grab;
    user-select: none;
    transition: all 0.15s ease;
    color: #ccc;
    text-align: left;
  }

  .palette-item:hover {
    background: #1a1a5e;
    border-color: #e94560;
    transform: translateX(2px);
  }

  .palette-item:active {
    cursor: grabbing;
    transform: scale(0.98);
  }

  .palette-item img {
    width: 36px;
    height: 24px;
    object-fit: contain;
    background: transparent;
    border-radius: 3px;
    padding: 2px;
    flex-shrink: 0;
  }

  .palette-item span {
    font-size: 10px;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
