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

  interface DeviceEntry {
    id: string;
    svg: string;
    zone: string;
  }

  let allDevices = $state<Record<string, DeviceEntry[]>>({});
  let collapsed = $state(false);
  let collapsedZones = $state<Set<string>>(new Set());

  // Load manifest
  async function loadManifest() {
    try {
      const resp = await fetch('/projectes/devices-manifest.json');
      if (resp.ok) allDevices = await resp.json();
    } catch {}
  }
  loadManifest();

  // Devices for current MCM, filtered out already-placed ones
  let mcmDevices = $derived.by(() => {
    const list = allDevices[layout.currentMcm] || [];
    const placedLabels = new Set(layout.symbols.map(s => s.label).filter(Boolean));
    return list.filter(d => !placedLabels.has(d.id));
  });

  // Group by SVG type
  let svgGroups = $derived.by(() => {
    const map = new Map<string, DeviceEntry[]>();
    for (const d of mcmDevices) {
      const name = SYMBOLS.find(s => s.id === d.svg)?.name || d.svg;
      if (!map.has(name)) map.set(name, []);
      map.get(name)!.push(d);
    }
    return [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
  });

  let totalCount = $derived(mcmDevices.length);
  let totalAll = $derived((allDevices[layout.currentMcm] || []).length);

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

  function onMousedown(e: MouseEvent, device: DeviceEntry) {
    if (e.button !== 0) return;
    e.preventDefault();
    const symDef = SYMBOLS.find(s => s.id === device.svg);
    if (!symDef) return;
    startPaletteDrag(e, symDef, device.id);
  }

  function getSymbolFile(svgId: string): string {
    return SYMBOLS.find(s => s.id === svgId)?.file || '';
  }

</script>

<div class="device-dock" class:collapsed>
  <button class="collapse-btn" onclick={() => collapsed = !collapsed}>
    {collapsed ? '<' : '>'}
  </button>

  {#if !collapsed}
    <div class="dock-content">
      <div class="dock-header">
        Devices
        <span class="dock-count">{totalAll - totalCount}/{totalAll}</span>
      </div>

      {#if totalCount === 0}
        <div class="dock-empty">All placed</div>
      {/if}

      <div class="dock-list">
        {#each svgGroups as [groupName, devices] (groupName)}
          <button class="zone-toggle" onclick={() => toggleGroup(groupName)}>
            <span class="chevron" class:open={!collapsedZones.has(groupName)}></span>
            {groupName}
            <span class="zone-count">{devices.length}</span>
          </button>
          {#if !collapsedZones.has(groupName)}
            <div class="zone-items">
              {#each devices as device (device.id)}
                <button
                  class="device-item"
                  title={device.id}
                  onmousedown={(e) => onMousedown(e, device)}
                >
                  <img
                    src={getSymbolFile(device.svg)}
                    alt={device.svg}
                    draggable="false"
                  />
                  <span class="device-label">{device.id}</span>
                </button>
              {/each}
            </div>
          {/if}
        {/each}
      </div>
    </div>
  {/if}
</div>

<style>
  .device-dock {
    width: 200px;
    min-width: 200px;
    background: #16213e;
    border-left: 2px solid #0f3460;
    display: flex;
    flex-direction: column;
    position: relative;
    transition: width 0.2s ease, min-width 0.2s ease;
    overflow: hidden;
  }

  .device-dock.collapsed {
    width: 32px;
    min-width: 32px;
  }

  .collapse-btn {
    position: absolute;
    top: 8px;
    left: 4px;
    width: 24px;
    height: 24px;
    background: #0f3460;
    border: 1px solid #1a1a5e;
    color: #e0e0e0;
    border-radius: 4px;
    cursor: pointer;
    z-index: 10;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.15s;
  }

  .collapse-btn:hover {
    background: #e94560;
  }

  .dock-content {
    padding: 6px;
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .dock-header {
    font-size: 10px;
    color: #e94560;
    text-transform: uppercase;
    letter-spacing: 1px;
    font-weight: 600;
    padding: 5px 6px 6px 30px;
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .dock-count {
    font-size: 9px;
    color: #667;
    font-weight: 400;
  }

  .dock-empty {
    font-size: 11px;
    color: #556;
    text-align: center;
    padding: 20px 0;
  }

  .dock-list {
    flex: 1;
    overflow-y: auto;
    min-height: 0;
  }

  .zone-toggle {
    display: flex;
    align-items: center;
    gap: 4px;
    width: 100%;
    padding: 4px 6px;
    margin-bottom: 1px;
    background: #0d2847;
    border: 1px solid #1a1a5e;
    border-radius: 4px;
    color: #8899aa;
    font-size: 9px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    cursor: pointer;
    text-align: left;
    flex-shrink: 0;
  }

  .zone-toggle:hover {
    color: #e94560;
  }

  .zone-count {
    margin-left: auto;
    font-size: 8px;
    color: #556;
    font-weight: 400;
  }

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

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

  .zone-items {
    display: flex;
    flex-direction: column;
    gap: 1px;
    padding: 1px 0 3px;
  }

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

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

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

  .device-item img {
    width: 28px;
    height: 18px;
    object-fit: contain;
    flex-shrink: 0;
  }

  .device-label {
    font-size: 9px;
    line-height: 1.2;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>
