<script lang="ts">
  import type { Snippet } from 'svelte';

  let {
    open = false,
    onclose,
    height = '75vh',
    children
  }: {
    open: boolean;
    onclose: () => void;
    height?: string;
    children?: Snippet;
  } = $props();

  $effect(() => {
    if (!open) return;

    function handleKeydown(event: KeyboardEvent) {
      if (event.key === 'Escape') {
        onclose();
      }
    }

    window.addEventListener('keydown', handleKeydown);

    return () => {
      window.removeEventListener('keydown', handleKeydown);
    };
  });
</script>

{#if open}
  <div
    data-testid="bottom-sheet"
    aria-hidden={open ? 'false' : 'true'}
    class="fixed inset-0 z-50 flex items-end"
  >
    <!-- Backdrop -->
    <div
      data-testid="sheet-backdrop"
      class="absolute inset-0"
      style="background: rgba(28,28,24,0.4);"
      onclick={onclose}
      role="presentation"
    ></div>

    <!-- Sheet panel -->
    <div
      class="relative z-10 w-full flex flex-col overflow-hidden"
      style="
        background: var(--color-page);
        border-radius: var(--radius-xl) var(--radius-xl) 0 0;
        box-shadow: var(--shadow-overlay);
        max-height: {height};
      "
      onclick={(e) => e.stopPropagation()}
      onkeydown={(e) => e.stopPropagation()}
      role="dialog"
      aria-modal="true"
      tabindex="-1"
    >
      <!-- Header row: drag handle + close button -->
      <div class="relative flex items-center justify-center pt-3 pb-2 px-4">
        <!-- Drag handle -->
        <div
          data-testid="drag-handle"
          aria-hidden="true"
          class="absolute"
          style="
            width: 32px;
            height: 4px;
            background: var(--color-border);
            border-radius: 9999px;
          "
        ></div>

        <!-- Close button -->
        <button
          type="button"
          aria-label="Schließen"
          class="ml-auto text-xl leading-none"
          onclick={onclose}
        >
          &times;
        </button>
      </div>

      <!-- Body content -->
      <div class="overflow-y-auto flex-1">
        {@render children?.()}
      </div>
    </div>
  </div>
{/if}
