<script lang="ts">
  // Global floating-window layer — mounted once in App.svelte, above every
  // page, so an entity opened from Knowledge Base, chat, or anywhere else
  // lands in the same window stack instead of each page owning its own
  // single-entity sidebar/sheet. See $lib/stores/windows.ts.
  import { dk, wmState, openEntityWindow } from '$lib/stores/windows'
  import EntityDetailContent from './EntityDetailContent.svelte'
  import XIcon from '@lucide/svelte/icons/x'
  import MinusIcon from '@lucide/svelte/icons/minus'
</script>

<div use:dk.desktop class="pointer-events-none fixed inset-0 z-40">
  {#each $wmState.order as id (id)}
    {@const win = $wmState.windows[id]}
    {#if win}
      <section use:dk.window={{ id }} class="min-w-0" aria-label={win.title}>
        <header data-wm-drag class="flex shrink-0 cursor-move items-center justify-between gap-2 border-b bg-muted/40 px-3 py-1.5">
          <span data-wm-title class="min-w-0 flex-1 truncate font-mono text-xs font-medium">{win.title}</span>
          <div class="flex shrink-0 items-center gap-0.5">
            <button
              type="button"
              data-wm-minimize
              class="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
              aria-label="Minimize {win.title}"
            >
              <MinusIcon class="size-3.5" />
            </button>
            <button
              type="button"
              data-wm-close
              class="rounded p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
              aria-label="Close {win.title}"
            >
              <XIcon class="size-3.5" />
            </button>
          </div>
        </header>
        <div data-wm-content class="min-h-0 flex-1 overflow-hidden">
          {#key id}
            <EntityDetailContent slug={id} onSelectEntity={openEntityWindow} />
          {/key}
        </div>
      </section>
    {/if}
  {/each}
</div>
