/**
 * Making a legend row behave like a link.
 *
 * Three lists on the promo pages drill into something when clicked — the
 * breakdown panel's legend, the Promo Code Distribution legend, and the "all
 * campaigns" modal. Each is a `Group`, not an anchor, so each needs the same
 * button semantics: a role, a tab stop, Enter/Space handling, a pointer cursor,
 * and a chevron saying the row goes somewhere.
 *
 * That is easy to get subtly wrong three times over — a row that is clickable but
 * not focusable, or focusable but ignores Space. Declaring it once means a row is
 * either fully interactive or plainly inert.
 *
 * `component="button"` isn't an option: Mantine's `Group` doesn't type a dynamic
 * component, and a button element would fight the row's grid layout.
 */

import { IconChevronRight } from "@tabler/icons-react";
import type { KeyboardEvent } from "react";
import styles from "./promo.module.css";

/**
 * Props that turn a row into a button, or nothing at all when `onActivate` is
 * absent.
 *
 * Spread onto the row element. Passing `undefined` for every prop rather than
 * omitting them keeps the result usable as a plain spread while leaving a
 * non-drillable row without a stray `role` or tab stop.
 */
export function drillProps(
  onActivate: (() => void) | undefined,
  /** Used for the row's tooltip, e.g. "View India". */
  label?: string,
) {
  if (!onActivate) {
    return {
      role: undefined,
      tabIndex: undefined,
      onClick: undefined,
      onKeyDown: undefined,
      style: undefined,
      title: undefined,
    };
  }
  return {
    role: "button",
    tabIndex: 0,
    onClick: onActivate,
    onKeyDown: (e: KeyboardEvent) => {
      // Enter and Space are what a real button responds to.
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        onActivate();
      }
    },
    style: { cursor: "pointer" as const },
    title: label ? `View ${label}` : undefined,
  };
}

/**
 * The drill-in arrow for a drillable row.
 *
 * Always laid out rather than revealed on hover — a pointer cursor only shows
 * once you are already hovering, which left the link undiscoverable. Sitting in
 * the layout permanently also means the row's width never shifts; the CSS only
 * changes its colour and nudges it right.
 */
export function DrillChevron() {
  return (
    <IconChevronRight
      size={15}
      stroke={2}
      className={styles.legendChevron}
      aria-hidden
    />
  );
}
