import type { KeyboardEvent } from "react";

/**
 * Make a non-interactive element behave like a button for keyboard users.
 *
 * The codebase has a long tail of `<div onClick>` / `<span onClick>` that
 * navigate or select — rows that open a detail page, a name that opens a
 * profile, a cell that picks a time. A bare `onClick` is mouse-only: the
 * element takes no focus, carries no role, and answers neither Enter nor
 * Space.
 *
 * A real `<button>` is better where the markup allows it, because it gets all
 * of this from the platform. This helper is for the places it does not: a
 * `<tr>`/`<td>`, or an element whose styling and layout depend on being a
 * `div`/`span`. It supplies the three things the platform would have:
 *
 *   - `role="button"`, so it is announced as one;
 *   - `tabIndex={0}`, so it can be reached;
 *   - `onKeyDown` for Enter and Space, which is what a button responds to.
 *
 * `Space` is `preventDefault`ed because its default action is to scroll the
 * page, and a key that both activates the control and scrolls is worse than
 * one that does neither.
 *
 * Returns the `onClick` too, so a call site spreads one object and cannot
 * accidentally keep the mouse path while dropping the keyboard one.
 */
export function clickable(onActivate: () => void) {
  return {
    role: "button" as const,
    tabIndex: 0,
    onClick: onActivate,
    onKeyDown: (event: KeyboardEvent) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        onActivate();
      }
    },
  };
}

/**
 * The same, for an element standing in for a checkbox.
 *
 * `CheckBox` and `FilterCheckBox` render a `div` with an SVG tick and no
 * `<input>` at all, so before this they were mouse-only: no focus, no role,
 * and nothing announced about checked state. That matters most on the terms
 * checkbox, where being unable to tick it blocks the whole sign-up.
 *
 * `role="checkbox"` plus `aria-checked` is what makes the state readable;
 * Space is the key a checkbox responds to, and Enter is accepted too because
 * users arriving from a button habit will try it.
 */
export function checkable(checked: boolean, onToggle: () => void) {
  return {
    role: "checkbox" as const,
    "aria-checked": checked,
    tabIndex: 0,
    onClick: onToggle,
    onKeyDown: (event: KeyboardEvent) => {
      if (isActivationKey(event.key)) {
        event.preventDefault();
        onToggle();
      }
    },
  };
}

/**
 * Should this key activate a `clickable` element?
 *
 * Exported for the tests, and for the few call sites that already have their
 * own `onKeyDown` and only need the key predicate.
 */
export function isActivationKey(key: string): boolean {
  return key === "Enter" || key === " ";
}
