import { Fragment } from 'react';
import { Kbd } from '@/components/ui/kbd';
import { cn } from '@/lib/utils';

/** Dark-overlay chip restyle of the design-system Kbd, kept in one place. */
const chipClass =
  'rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs font-normal text-current';

interface KeyHintProps {
  /** Key chip(s): "Esc" or ["Esc", "Q"]. */
  keys: string | string[];
  /** Rendered between chips, e.g. "or". Defaults to a plain space. */
  separator?: React.ReactNode;
  /** Text before the first chip, e.g. "Release". */
  prefix?: React.ReactNode;
  /** Trailing label, e.g. "cancel". May contain icons. */
  children?: React.ReactNode;
  /** When set, renders a <button> with hover affordance; otherwise a plain <span>. */
  onClick?: () => void;
  /** Tooltip explaining the action; pass alongside onClick. */
  title?: string;
  className?: string;
  'aria-label'?: string;
}

/**
 * A keyboard-shortcut hint: one or more key chips with optional surrounding
 * text. Keyboard-first, but every hint with an `onClick` is also a real
 * button so mouse users can trigger the same action by clicking it.
 */
export function KeyHint({
  keys,
  separator,
  prefix,
  children,
  onClick,
  title,
  className,
  ...rest
}: KeyHintProps) {
  const keyList = Array.isArray(keys) ? keys : [keys];
  const content = (
    <>
      {prefix != null && <>{prefix} </>}
      {keyList.map((k, i) => (
        <Fragment key={`${k}-${i}`}>
          {i > 0 && (separator != null ? <> {separator} </> : ' ')}
          <Kbd className={chipClass}>{k}</Kbd>
        </Fragment>
      ))}
      {children != null && <> {children}</>}
    </>
  );

  if (!onClick) {
    return (
      <span className={className} {...rest}>
        {content}
      </span>
    );
  }

  return (
    <button
      type="button"
      onClick={onClick}
      // Keep focus where it is (e.g. the compose textarea); the click still fires.
      onMouseDown={(e) => e.preventDefault()}
      title={title}
      className={cn(
        'cursor-pointer rounded transition-colors hover:text-white/80',
        className,
      )}
      {...rest}
    >
      {content}
    </button>
  );
}
