"use client";
import * as React from "react";
import {
  readJsonFromLocalStorage,
  writeJsonToLocalStorage
} from "@open-mercato/shared/lib/browser/safeLocalStorage";
const STORAGE_PREFIX = "om:group-order:";
function getStorageKey(pageType) {
  return `${STORAGE_PREFIX}${pageType}`;
}
function mergeOrder(saved, defaults) {
  const known = new Set(defaults);
  const result = saved.filter((id) => known.has(id));
  for (const id of defaults) {
    if (!result.includes(id)) result.push(id);
  }
  return result;
}
function arraysEqual(a, b) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i += 1) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}
function useGroupOrder(pageType, defaultGroupIds) {
  const [orderedIds, setOrderedIds] = React.useState(defaultGroupIds);
  const mounted = React.useRef(false);
  React.useEffect(() => {
    mounted.current = true;
    const saved = readJsonFromLocalStorage(getStorageKey(pageType), null);
    if (Array.isArray(saved)) {
      setOrderedIds(mergeOrder(saved, defaultGroupIds));
    }
  }, [pageType]);
  React.useEffect(() => {
    setOrderedIds((prev) => {
      const merged = mergeOrder(prev, defaultGroupIds);
      return arraysEqual(prev, merged) ? prev : merged;
    });
  }, [defaultGroupIds]);
  const reorder = React.useCallback(
    (fromIndex, toIndex) => {
      setOrderedIds((prev) => {
        const next = [...prev];
        const [moved] = next.splice(fromIndex, 1);
        next.splice(toIndex, 0, moved);
        if (mounted.current) {
          writeJsonToLocalStorage(getStorageKey(pageType), next);
        }
        return next;
      });
    },
    [pageType]
  );
  return { orderedIds, reorder };
}
export {
  useGroupOrder
};
//# sourceMappingURL=useGroupOrder.js.map
