import { useReducer as I, useCallback as o } from "../../../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
import p from "../../../../hooks/useReflex.js";
import { InteractionKeyCode as n } from "../../../types.js";
import { INITIAL_STATE as u } from "../DataGrid.js";
const T = ({ totalRows: r }) => {
  const [t, d] = I(
    (e, i) => {
      const s = r;
      if (s > 1) {
        const x = i.index;
        if (x < s && x >= 0)
          return i.type === "ACTIVE" ? Object.freeze({ ...e, index: i.index ?? 0, activeIndex: i.index }) : Object.freeze({ ...e, index: i.index ?? 0, activeIndex: -1 });
      }
      return e;
    },
    u
  ), a = p(
    o(
      (e) => {
        if (!(e instanceof Element)) return;
        const i = Number(e.dataset?.index);
        t.activeIndex === -1 && i === 0 || i === t.index ? e.setAttribute("tabindex", "0") : e.setAttribute("tabindex", "-1"), i === t.activeIndex && e?.focus();
      },
      [t.activeIndex, t.index]
    )
  ), c = o(
    (e) => {
      if (!(e.target?.getAttribute("role") === "row")) {
        e.code === n.ARROW_LEFT && d({
          type: "ACTIVE",
          index: t.index
        });
        return;
      }
      switch (e.code) {
        case n.ARROW_DOWN:
        case n.ARROW_UP:
          d({
            type: "ACTIVE",
            index: e.code === n.ARROW_DOWN ? t.index + 1 : t.index - 1
          });
          break;
        case n.HOME:
          d({
            type: "ACTIVE",
            index: 0
          });
          break;
        case n.END:
          d({
            type: "ACTIVE",
            index: r - 1
          });
          break;
        case n.ENTER:
          e.currentTarget?.click();
          break;
        default:
          return;
      }
      e.stopPropagation();
    },
    [r, t.index]
  ), f = o(
    (e) => (i) => {
      (!(i.target?.localName === "tr") || t.index === -1) && d({ type: "CURRENT", index: e });
    },
    [t.index]
  );
  return { listeners: { onKeyDownCapture: c, onFocusCapture: f }, ref: a, activeIndex: t.activeIndex, currentIndex: t.index };
};
export {
  T as useInteractiveDataGrid
};
