import { useRef as i, useState as j, useEffect as m, useCallback as d, useMemo as D } from "react";
import { calculateVisibleChipsCount as S } from "../helpers/calculateVisibleChipsCount.js";
function K(t) {
  const h = i(null), v = i(null), R = i(null), C = i(null), p = i(/* @__PURE__ */ new Map()), s = i(/* @__PURE__ */ new Map()), [a, u] = j(null);
  m(() => {
    const e = new Set(t.map((r) => r.id));
    for (const r of s.current.keys())
      e.has(r) || s.current.delete(r);
    t.some((r) => !s.current.has(r.id)) && u(null);
  }, [t]);
  const o = d(() => {
    const e = h.current, n = v.current;
    if (!e || !n || t.length === 0) {
      u(null);
      return;
    }
    if (t.forEach((c) => {
      const g = p.current.get(c.id);
      g && g.offsetWidth > 0 && s.current.set(c.id, g.offsetWidth);
    }), !t.every((c) => s.current.has(c.id)))
      return;
    const b = getComputedStyle(e), f = getComputedStyle(n), k = parseFloat(b.paddingLeft) || 0, I = parseFloat(b.paddingRight) || 0, U = parseFloat(f.paddingLeft) || 0, V = parseFloat(f.paddingRight) || 0, l = parseFloat(f.gap) || 0, F = e.getBoundingClientRect().width || e.clientWidth;
    if (F === 0)
      return;
    const W = C.current?.offsetWidth ?? 0, q = W > 0 ? W + l : 0, w = F - k - I - U - V - q, M = t.map((c) => s.current.get(c.id) ?? 0);
    if (S(w, l, M) >= t.length) {
      u(t.length);
      return;
    }
    const y = R.current?.offsetWidth ?? 0, x = y > 0 ? y + l : 0, z = w - x, B = S(z, l, M);
    u(B);
  }, [t]), E = d((e, n) => {
    n ? p.current.set(e, n) : p.current.delete(e);
  }, []), A = d(
    (e) => {
      R.current = e, o();
    },
    [o]
  ), L = d(
    (e) => {
      C.current = e, o();
    },
    [o]
  );
  m(() => {
    const e = h.current;
    if (!e)
      return;
    const n = new ResizeObserver(() => {
      o();
    });
    return n.observe(e), () => {
      n.disconnect();
    };
  }, [o]), m(() => {
    const e = requestAnimationFrame(() => {
      o();
    });
    return () => cancelAnimationFrame(e);
  }, [t, o]);
  const { visibleFilters: P, overflowFilters: O } = D(() => a === null || a >= t.length ? { visibleFilters: t, overflowFilters: [] } : {
    visibleFilters: t.slice(0, a),
    overflowFilters: t.slice(a)
  }, [t, a]);
  return {
    visibleFilters: P,
    overflowFilters: O,
    parentRef: h,
    containerRef: v,
    setChipRef: E,
    setMoreChipRef: A,
    setActionsRef: L
  };
}
export {
  K as useChipsOverflow
};
