/**
 * Solid hooks for consuming terminal input events.
 *
 * Uses Solid context to make key/mouse/paste events available
 * to any component in the tree. The Screen wires up the provider.
 */
import { createContext, createSignal, onCleanup, useContext } from "solid-js";

// --- Event bus (signal-based, no EventEmitter overhead) ---

/** Internal dispatch methods — not exposed to components */

export function createInputBus() {
  const keyHandlers = new Set();
  const mouseHandlers = new Set();
  const pasteHandlers = new Set();
  const [keySignal, setKeySignal] = createSignal(0);
  const [lastKey, setLastKey] = createSignal(null);
  return {
    keySignal,
    lastKey,
    addKeyHandler(handler) {
      keyHandlers.add(handler);
      return () => {
        keyHandlers.delete(handler);
      };
    },
    addMouseHandler(handler) {
      mouseHandlers.add(handler);
      return () => {
        mouseHandlers.delete(handler);
      };
    },
    addPasteHandler(handler) {
      pasteHandlers.add(handler);
      return () => {
        pasteHandlers.delete(handler);
      };
    },
    _dispatchKey(key) {
      setLastKey(key);
      setKeySignal(n => n + 1);
      for (const h of keyHandlers) h(key);
    },
    _dispatchMouse(event) {
      for (const h of mouseHandlers) h(event);
    },
    _dispatchPaste(text) {
      for (const h of pasteHandlers) h(text);
    }
  };
}

// --- Solid Context ---
// In Solid 2.0, createContext returns the Provider component directly.
// Use it as: <InputContext value={bus}>{children}</InputContext>

export const InputContext = createContext();

// --- Hooks ---

function getInputBus() {
  const bus = useContext(InputContext);
  if (!bus) throw new Error("useInput() must be used inside a Screen");
  return bus;
}

/**
 * Subscribe to key events. The handler is called for every keypress.
 * Automatically cleaned up when the component unmounts.
 */
export function useInput(handler) {
  const bus = getInputBus();
  const remove = bus.addKeyHandler(handler);
  onCleanup(remove);
}

/**
 * Subscribe to mouse events.
 * Automatically cleaned up when the component unmounts.
 */
export function useMouse(handler) {
  const bus = getInputBus();
  const remove = bus.addMouseHandler(handler);
  onCleanup(remove);
}

/**
 * Subscribe to paste events (decoded text).
 * Automatically cleaned up when the component unmounts.
 */
export function usePaste(handler) {
  const bus = getInputBus();
  const remove = bus.addPasteHandler(handler);
  onCleanup(remove);
}
//# sourceMappingURL=hooks.jsx.map
