// packages/core/src/components/command-palette/command-palette-item.tsx
import type { JSX } from "solid-js";
import { onCleanup, onMount, splitProps } from "solid-js";
import { useCommandPaletteContext } from "./command-palette-context";
import type { CommandPaletteItemProps } from "./command-palette.props";

/**
 * An individual action item in CommandPalette. Registers itself with the root
 * for filtering, and delegates navigation/activation to createListNavigation.
 */
export function CommandPaletteItem(props: CommandPaletteItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "keywords", "disabled", "onSelect", "children"]);
  const ctx = useCommandPaletteContext();

  onMount(() => {
    ctx.registerItem({ value: local.value, keywords: local.keywords, disabled: local.disabled });
  });

  onCleanup(() => {
    ctx.unregisterItem(local.value);
  });

  const itemProps = () => ctx.navigation.getItemProps(local.value);

  function handleClick(): void {
    if (local.disabled) return;
    local.onSelect?.();
    ctx.onActivate(local.value);
  }

  return (
    <div
      aria-disabled={local.disabled || undefined}
      data-disabled={local.disabled || undefined}
      {...itemProps()}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </div>
  );
}
