import { useEditorStore, type EditorObject } from "../../store/editorStore";

export const useMaskGroupState = (selectedObjectId: string | null) => {
  const { objects } = useEditorStore();

  if (!selectedObjectId) {
    return {
      isGroupedWithMask: false,
      hasMask: false,
      maskObject: null,
      canGroup: false,
      canUngroup: false,
      selectedObject: null,
    };
  }

  const selectedObject = objects.find((obj) => obj.id === selectedObjectId);
  if (!selectedObject) {
    return {
      isGroupedWithMask: false,
      hasMask: false,
      maskObject: null,
      canGroup: false,
      canUngroup: false,
      selectedObject: null,
    };
  }

  const isGroup = selectedObject.type === "group";

  // بررسی امکان group/ungroup با mask
  let isGroupedWithMask = false;
  let hasMask = false;
  let maskObject: EditorObject | null = null;

  if (isGroup) {
    // اگر این یک group است، بررسی کن که آیا از یک object با mask تشکیل شده
    const groupMembers = objects.filter((o) => o.groupId === selectedObject.id);
    const objectWithMask = groupMembers.find((m) => m.maskId);
    if (objectWithMask) {
      maskObject = groupMembers.find((m) => m.id === objectWithMask.maskId) || null;
      isGroupedWithMask = !!maskObject;
    }
  } else {
    // اگر یک object معمولی است
    hasMask = !!selectedObject.maskId;
    maskObject = hasMask ? objects.find((m) => m.id === selectedObject.maskId) || null : null;
    isGroupedWithMask = !!(selectedObject.groupId && maskObject?.groupId === selectedObject.groupId);
  }

  const canGroup = !!(hasMask && !isGroupedWithMask && maskObject && !selectedObject.isMask);
  const canUngroup = Boolean(isGroupedWithMask && isGroup);

  return {
    isGroupedWithMask,
    hasMask,
    maskObject,
    canGroup,
    canUngroup,
    selectedObject,
  };
};

