// packages/core/src/components/command-palette/command-palette-context.ts
import type { Accessor } from "solid-js";
import { createContext, useContext } from "solid-js";
import type { ListNavigationState } from "../../primitives/create-list-navigation";

/** A registered item entry held by the root. */
export interface RegisteredItem {
  value: string;
  keywords?: string[];
  disabled?: boolean;
}

/** Internal context shared between all CommandPalette sub-components. */
export interface CommandPaletteContextValue {
  /** Current search string. */
  searchValue: Accessor<string>;
  /** Update the search string. */
  setSearch: (value: string) => void;
  /** Items that pass the current filter. */
  filteredItems: Accessor<RegisteredItem[]>;
  /** Register an item with the root. */
  registerItem: (item: RegisteredItem) => void;
  /** Unregister an item from the root. */
  unregisterItem: (value: string) => void;
  /** Called when an item is activated (from item click or keyboard). */
  onActivate: (value: string) => void;
  /** List navigation state for keyboard handling and item props. */
  navigation: ListNavigationState;
}

const CommandPaletteContext = createContext<CommandPaletteContextValue>();

/**
 * Returns the internal CommandPalette context. Throws if used outside CommandPalette.
 */
export function useCommandPaletteContext(): CommandPaletteContextValue {
  const ctx = useContext(CommandPaletteContext);
  if (!ctx) {
    throw new Error(
      "[PettyUI] CommandPalette parts must be used inside <CommandPalette>.\n" +
        "  Fix: <CommandPalette>\n" +
        "         <CommandPalette.Input />\n" +
        "         <CommandPalette.List>\n" +
        '           <CommandPalette.Item value="action">Action</CommandPalette.Item>\n' +
        "         </CommandPalette.List>\n" +
        "       </CommandPalette>",
    );
  }
  return ctx;
}

export const CommandPaletteContextProvider = CommandPaletteContext.Provider;
