<script lang="ts">
  // Renders the mascot action tree (actions.ts MASCOT_ACTIONS) as a shadcn
  // context menu. Children → nested ContextMenu.Sub (native hover/click
  // sub-menu navigation, replacing the old manual breadcrumb stack in
  // RadialMenu.svelte); leaves → ContextMenu.Item with onSelect. The
  // content portals to <body> via bits-ui (see
  // ui/context-menu/context-menu-content.svelte), so it escapes the
  // mascot layer's pointer-events-none root — the old menu was
  // non-interactive precisely because it rendered inside that root
  // without re-enabling pointer-events. Visibility predicates are read
  // reactively off ctx.model, so an action's visibility updates live while
  // the menu is open (e.g. "Rename" disappears once the egg hatches).
  //
  // Recursive: a node with children renders a Sub whose SubContent recurses
  // into this same component. Svelte resolves the self-import lazily, so
  // the cycle is fine.
  import * as ContextMenu from '$lib/components/ui/context-menu'
  import type { MascotActionCtx, RadialAction } from './types'
  // Self-import for recursive rendering of nested action groups.
  import MascotMenu from './MascotMenu.svelte'

  let { actions, ctx }: { actions: RadialAction[]; ctx: MascotActionCtx } = $props()

  const visible = $derived(actions.filter((a) => !a.visible || a.visible(ctx.model)))
</script>

{#each visible as a (a.id)}
  {#if a.children && a.children.length > 0}
    <ContextMenu.Sub>
      <ContextMenu.SubTrigger>
        {#if a.icon}<a.icon class="size-4" />{/if}
        {a.label}
      </ContextMenu.SubTrigger>
      <ContextMenu.SubContent class="min-w-56 max-w-72">
        <MascotMenu actions={a.children} {ctx} />
      </ContextMenu.SubContent>
    </ContextMenu.Sub>
  {:else}
    <ContextMenu.Item
      onSelect={() => {
        a.action?.(ctx)
      }}
    >
      {#if a.icon}<a.icon class="size-4" />{/if}
      <span class="flex min-w-0 flex-1 flex-col">
        <span class="truncate">{a.label}</span>
        {#if a.description}
          <span class="text-[11px] leading-snug font-normal text-muted-foreground"
            >{a.description}</span
          >
        {/if}
      </span>
    </ContextMenu.Item>
  {/if}
{/each}
