<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 expandedGroups = $state<Set<string>>(new Set());

  function toggleGroup(key: string) {
    const next = new Set(expandedGroups);
    if (next.has(key)) next.delete(key);
    else next.add(key);
    expandedGroups = next;
  }

  // Small symbols use grid layout (2 columns)
  const GRID_GROUPS = new Set(['I/O Modules', 'Sensors', 'Controls', 'Other']);
</script>

<div class="palette">
  {#each grouped as group (group.name)}
    {@const isGrid = GRID_GROUPS.has(group.name)}
    {@const groupKey = group.name}

    <!-- Group header (collapsible) -->
    <button class="group-header" onclick={() => toggleGroup(groupKey)}>
      <span class="chevron" class:open={expandedGroups.has(groupKey)}></span>
      {group.name}
      <span class="count">{group.subgroups.reduce((n, s) => n + s.symbols.length, 0) + group.symbols.length}</span>
    </button>

    {#if expandedGroups.has(groupKey)}
      <!-- Subgroups -->
      {#if group.subgroups.length > 0}
        {#each group.subgroups as sub (sub.name)}
          <div class="sub-label">{sub.name}</div>
          <div class="items" class:grid={isGrid}>
            {#each sub.symbols as sym (sym.id)}
              <button
                class="item"
                class:grid-item={isGrid}
                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 class="item-name">{sym.name}</span>
              </button>
            {/each}
          </div>
        {/each}
      {/if}

      <!-- Ungrouped symbols -->
      {#if group.symbols.length > 0}
        <div class="items" class:grid={isGrid}>
          {#each group.symbols as sym (sym.id)}
            <button
              class="item"
              class:grid-item={isGrid}
              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 class="item-name">{sym.name}</span>
            </button>
          {/each}
        </div>
      {/if}
    {/if}
  {/each}
</div>

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

  /* Scrollbar */
  .palette::-webkit-scrollbar {
    width: 4px;
  }
  .palette::-webkit-scrollbar-track {
    background: transparent;
  }
  .palette::-webkit-scrollbar-thumb {
    background: #374151;
    border-radius: 2px;
  }

  .group-header {
    display: flex;
    align-items: center;
    gap: 6px;
    width: 100%;
    padding: 6px 4px;
    background: none;
    border: none;
    border-bottom: 1px solid #1f2937;
    color: #e5e7eb;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.8px;
    cursor: pointer;
    transition: color 0.15s;
    text-align: left;
    position: sticky;
    top: 0;
    background: #111827;
    z-index: 1;
  }

  .group-header:hover {
    color: #3b82f6;
  }

  .count {
    margin-left: auto;
    font-size: 9px;
    color: #4b5563;
    font-weight: 400;
  }

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

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

  .sub-label {
    font-size: 9px;
    color: #6b7280;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    font-weight: 600;
    padding: 4px 4px 2px 14px;
  }

  /* List layout (conveyance) */
  .items {
    display: flex;
    flex-direction: column;
    gap: 1px;
    padding: 0 2px 2px;
  }

  /* Grid layout (small symbols) */
  .items.grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2px;
  }

  .item {
    display: flex;
    align-items: center;
    gap: 5px;
    width: 100%;
    padding: 3px 5px;
    background: transparent;
    border: 1px solid transparent;
    border-radius: 3px;
    cursor: grab;
    user-select: none;
    transition: all 0.12s ease;
    color: #9ca3af;
    text-align: left;
  }

  .item:hover {
    background: #1f2937;
    border-color: #374151;
    color: #e5e7eb;
  }

  .item:active {
    cursor: grabbing;
    background: #374151;
  }

  /* Grid items are more compact */
  .item.grid-item {
    flex-direction: column;
    align-items: center;
    gap: 2px;
    padding: 4px 2px 3px;
  }

  .item.grid-item .item-name {
    text-align: center;
    font-size: 8px;
  }

  .item img {
    width: 28px;
    height: 18px;
    object-fit: contain;
    flex-shrink: 0;
    filter: invert(1);
    opacity: 0.8;
  }

  .item:hover img {
    opacity: 1;
  }

  .item.grid-item img {
    width: 24px;
    height: 20px;
  }

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