<script lang="ts">
  // v0.2 Phase 5 primitive — Lumotia-tinted Bits UI DropdownMenu.
  // Used by HistoryPage row actions, future overflow menus. Caller
  // owns the trigger (any element); the wrapper takes the items list.
  import { DropdownMenu } from "bits-ui";
  import type { Snippet } from "svelte";

  // `icon` accepts both Svelte 5 Component<…> and lucide-svelte's
  // legacy SvelteComponentTyped shape. See LumotiaIconButton for the
  // same rationale.
  type MenuItem =
    | {
        kind?: "item";
        value: string;
        label: string;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        icon?: any;
        destructive?: boolean;
        disabled?: boolean;
        onSelect: () => void;
      }
    | { kind: "separator" };

  interface Props {
    items: MenuItem[];
    align?: "start" | "center" | "end";
    sideOffset?: number;
    trigger: Snippet;
    triggerClass?: string;
  }

  let { items, align = "end", sideOffset = 6, trigger, triggerClass = "" }: Props = $props();
</script>

<DropdownMenu.Root>
  <DropdownMenu.Trigger class={triggerClass}>
    {@render trigger()}
  </DropdownMenu.Trigger>
  <DropdownMenu.Portal>
    <DropdownMenu.Content
      {align}
      {sideOffset}
      class="z-50 min-w-[180px] rounded-md bg-bg-card border border-border-subtle shadow-xl py-1"
    >
      {#each items as item, i (i)}
        {#if item.kind === "separator"}
          <DropdownMenu.Separator class="my-1 h-px bg-border-subtle" />
        {:else}
          <DropdownMenu.Item
            disabled={item.disabled}
            onSelect={item.onSelect}
            class="px-3 py-1.5 text-[13px] flex items-center gap-2 cursor-pointer
              data-[highlighted]:bg-hover
              data-[disabled]:opacity-50 data-[disabled]:cursor-not-allowed
              {item.destructive ? 'text-danger' : 'text-text'}"
          >
            {#if item.icon}
              {@const I = item.icon}
              <I size={14} class="text-text-tertiary shrink-0" />
            {/if}
            <span class="truncate">{item.label}</span>
          </DropdownMenu.Item>
        {/if}
      {/each}
    </DropdownMenu.Content>
  </DropdownMenu.Portal>
</DropdownMenu.Root>
