/**
 * Shared row-activation contract for `KviewCrudTable` and `KviewDetailTable`:
 * a full-width clickable/keyboard-activatable row that must never swallow a
 * keystroke meant for a real control inside it (a checkbox, a nested link, a
 * button). Kept as one implementation so this guard cannot silently diverge
 * between the two table engines again — see the shared engine's contract in
 * `table-contract.md` for why this matters (Space toggling a selection
 * checkbox, Enter following a row's primary link).
 */
export const ROW_INTERACTIVE_SELECTOR = 'a, button, input, select, textarea, label, form';

export const isInteractiveTarget = (event: Event): boolean =>
    event.target instanceof HTMLElement && event.target.closest(ROW_INTERACTIVE_SELECTOR) !== null;

/** Stable id for a row's hidden primary link, shared by both table engines. */
export const rowLinkId = (idPrefix: string, rowId: string | number): string =>
    `${idPrefix}_row_${String(rowId).replace(/[^a-zA-Z0-9_-]/g, '_')}_link`;

/**
 * Builds a keydown handler for a keyboard-activatable row: Enter/Space
 * activate it, UNLESS the event originates from a real interactive control
 * inside the row. The interactive-target guard runs BEFORE `preventDefault`,
 * so a nested checkbox still toggles on Space and a nested link still
 * follows on Enter — only the row's own background activates on these keys.
 */
export const createRowKeydownHandler = <TRow>(
    activate: (row: TRow, event: KeyboardEvent) => void,
) => (row: TRow, event: KeyboardEvent): void => {
    if (!['Enter', ' '].includes(event.key)) {
        return;
    }

    if (isInteractiveTarget(event)) {
        return;
    }

    event.preventDefault();
    activate(row, event);
};
