<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());
  let searchQuery = $state('');

  // 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));
  });

  // Apply search filter + always sort by type ascending
  let filteredDevices = $derived.by(() => {
    let devices = mcmDevices;
    if (searchQuery.trim()) {
      const q = searchQuery.trim().toLowerCase();
      devices = devices.filter(d => d.id.toLowerCase().includes(q) || d.svg.toLowerCase().includes(q) || getSymbolName(d.svg).toLowerCase().includes(q));
    }
    devices = [...devices].sort((a, b) => a.svg.localeCompare(b.svg) || a.id.localeCompare(b.id));
    return devices;
  });

  // Group by SVG type
  let svgGroups = $derived.by(() => {
    const map = new Map<string, DeviceEntry[]>();
    for (const d of filteredDevices) {
      const name = getSymbolName(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 || '';
  }

  function getSymbolName(svgId: string): string {
    return SYMBOLS.find(s => s.id === svgId)?.name || svgId;
  }
</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">
        <span class="dock-title">Devices</span>
        <span class="dock-count">{totalAll - totalCount}/{totalAll} placed</span>
      </div>

      <div class="dock-hint">Drop on empty space to place, on symbol to assign ID</div>

      <div class="search-box">
        <input
          type="text"
          placeholder="Search..."
          bind:value={searchQuery}
        />
        {#if searchQuery}
          <button class="clear-search" onclick={() => searchQuery = ''}>x</button>
        {/if}
      </div>

      {#if filteredDevices.length === 0}
        <div class="dock-empty">{searchQuery ? 'No matches' : '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} — drag to place or assign"
                  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;
    padding-top: 38px;
    overflow: hidden;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .dock-header {
    font-size: 10px;
    padding: 2px 6px 2px;
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .dock-title {
    font-size: 10px;
    font-weight: 600;
    color: #8899aa;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

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

  .dock-hint {
    font-size: 8px;
    color: #445;
    padding: 0 6px 4px;
    flex-shrink: 0;
  }

  /* Search */
  .search-box {
    position: relative;
    flex-shrink: 0;
    margin-bottom: 4px;
  }

  .search-box input {
    width: 100%;
    padding: 5px 22px 5px 8px;
    background: #0f3460;
    border: 1px solid #1a1a5e;
    color: #e0e0e0;
    border-radius: 4px;
    font-size: 11px;
    outline: none;
    transition: border-color 0.15s;
    box-sizing: border-box;
  }

  .search-box input:focus {
    border-color: #e94560;
  }

  .search-box input::placeholder {
    color: #556;
  }

  .clear-search {
    position: absolute;
    right: 3px;
    top: 50%;
    transform: translateY(-50%);
    width: 16px;
    height: 16px;
    padding: 0;
    background: none;
    border: none;
    color: #667;
    font-size: 11px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 2px;
  }

  .clear-search:hover {
    color: #e94560;
  }

  .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>
