import { unique as v, compare as d, box as h } from "@synnaxlabs/x";
import { useCallback as b, useEffect as q, useState as C } from "react";
import { u as H } from "./Editable-C17ILP50.js";
import { p as k, u as M, a as y, f as x, d as A } from "./Text-2MISZsc5.js";
const R = ({
  triggers: n,
  callback: u,
  region: a,
  loose: r,
  double: e,
  regionMustBeElement: l
}) => {
  const { listen: t } = M();
  let i;
  n != null && n?.length > 0 && typeof n[0] == "string" ? i = [n] : i = n;
  const g = y(
    () => i,
    ([s], [c]) => s == null && c == null ? !0 : s == null || c == null ? !1 : d.primitiveArrays(s.flat(), c.flat()) === d.EQUAL,
    [i]
  );
  q(() => {
    if (!(g == null || g.length === 0))
      return t((s) => {
        const c = x(g, s.prev, { loose: r, double: e }), T = x(g, s.next, { loose: r, double: e }), m = A(T, c);
        let f = m[0];
        const o = m[1];
        if (f.length === 0 && o.length === 0) return;
        f = S(s.target, s.cursor, f, a, l);
        const p = { target: s.target, cursor: s.cursor };
        f.length > 0 && u?.({ ...p, stage: "start", triggers: f, prevTriggers: s.prev }), o.length > 0 && u?.({ ...p, stage: "end", triggers: o, prevTriggers: s.prev });
      });
  }, [u, g, t, r, a, e, l]);
}, S = (n, u, a, r, e) => {
  if (r == null) return a;
  if (r.current == null) return [];
  const l = h.construct(r.current);
  return a.filter((t) => e ?? t.some((g) => g.includes("Mouse")) ? h.contains(l, u) && n === r.current : h.contains(l, u));
}, U = ({
  triggers: n,
  loose: u
}) => {
  const [a, r] = H({
    triggers: [],
    held: !1
  });
  return R({
    triggers: n,
    callback: b((e) => {
      r((l) => {
        let t;
        return e.stage === "start" ? t = v.unique([...l.triggers, ...e.triggers]) : t = k(l.triggers, e.triggers), { triggers: t, held: t.length > 0 };
      });
    }, []),
    loose: u
  }), a;
}, j = ({ triggers: n, loose: u }) => {
  const [a, r] = C({ triggers: [], held: !1 });
  return R({
    triggers: n,
    callback: b((e) => {
      r((l) => {
        let t;
        return e.stage === "start" ? t = v.unique([...l.triggers, ...e.triggers]) : t = k(l.triggers, e.triggers), { triggers: t, held: t.length > 0 };
      });
    }, []),
    loose: u
  }), a;
};
export {
  j as a,
  U as b,
  R as u
};
