import { useRef as p, useState as l, useEffect as i, useCallback as I } from "react";
const S = "user_toggled_expandables", b = () => {
  try {
    const e = sessionStorage.getItem(
      S
    );
    return e ? JSON.parse(e) : {};
  } catch {
    return {};
  }
}, h = (e, s) => {
  try {
    const n = { ...b(), [e]: s };
    sessionStorage.setItem(
      S,
      JSON.stringify(n)
    );
  } catch {
  }
}, M = (e, s = !1) => {
  const o = p(null), [n, u] = l(!1), [y, c] = l(!1), [E, a] = l(s);
  i(() => {
    if (!e)
      return;
    const t = b();
    e in t && (a(!!t[e]), u(!0), c(!0));
  }, [e]), i(() => {
    const t = new IntersectionObserver(
      (g) => {
        g[0] && g[0].isIntersecting && !n && s && a((f) => f || !0);
      },
      {
        rootMargin: "100px",
        threshold: 0
      }
    ), r = o.current;
    return r && t.observe(r), () => {
      r && t.unobserve(r);
    };
  }, [n, s]);
  const m = I(
    (t) => {
      a(t), u(!0), c(!0), e && h(e, t);
    },
    [e]
  );
  return { ref: o, isExpanded: E, onManualToggle: m, isInSessionStorage: y };
};
export {
  M as useExpandableMemory
};
