import { useEffect, useRef } from "react";
import { useInput, useApp } from "ink";
const EXIT_WARNING_TIMEOUT = 3e3;
function useKeyboardShortcuts({ state, dispatch, agent }) {
  const { exit } = useApp();
  const sessionIdRef = useRef(state.session.id);
  useEffect(() => {
    sessionIdRef.current = state.session.id;
  }, [state.session.id]);
  useEffect(() => {
    if (!state.ui.exitWarningShown || !state.ui.exitWarningTimestamp) return;
    const elapsed = Date.now() - state.ui.exitWarningTimestamp;
    const remaining = EXIT_WARNING_TIMEOUT - elapsed;
    if (remaining <= 0) {
      dispatch({ type: "EXIT_WARNING_CLEAR" });
      return;
    }
    const timer = setTimeout(() => {
      dispatch({ type: "EXIT_WARNING_CLEAR" });
    }, remaining);
    return () => clearTimeout(timer);
  }, [state.ui.exitWarningShown, state.ui.exitWarningTimestamp, dispatch]);
  useInput(
    (inputChar, key) => {
      if (state.approval) {
        return;
      }
      if (state.ui.activeOverlay !== "none" && state.ui.activeOverlay !== "approval") {
        return;
      }
      if (key.ctrl && inputChar === "c") {
        if (state.ui.exitWarningShown) {
          exit();
        } else {
          dispatch({ type: "EXIT_WARNING_SHOW" });
        }
        return;
      }
      if (key.escape) {
        if (state.ui.exitWarningShown) {
          dispatch({ type: "EXIT_WARNING_CLEAR" });
          return;
        }
        if (state.ui.isProcessing) {
          const currentSessionId = sessionIdRef.current;
          if (!currentSessionId) {
            return;
          }
          void agent.cancel(currentSessionId).catch(() => {
          });
          dispatch({ type: "CANCEL_START" });
        } else if (state.ui.activeOverlay !== "none") {
          dispatch({ type: "CLOSE_OVERLAY" });
        }
      }
    },
    // Always active - we handle guards internally for more reliable behavior
    { isActive: true }
  );
}
export {
  useKeyboardShortcuts
};
