'use strict';

const React = require('react');
const layerStore = require('../store/layer-store.cjs');
const editorStore = require('../store/editor-store.cjs');
const layerUtils = require('../store/layer-utils.cjs');

const useDropValidation = (activeLayerId, isLayerDescendantOf, newComponentType) => {
  const findLayerById = layerStore.useLayerStore((state) => state.findLayerById);
  const componentRegistry = editorStore.useEditorStore((state) => state.registry);
  const canDropOnLayer = React.useCallback((layerId) => {
    if (!layerId) return false;
    const targetLayer = findLayerById(layerId);
    if (!targetLayer) return false;
    if (!activeLayerId && !newComponentType) {
      return layerUtils.canLayerAcceptChildren(targetLayer, componentRegistry);
    }
    if (newComponentType) {
      const componentDef = componentRegistry[newComponentType];
      if (componentDef?.childOf && !componentDef.childOf.includes(targetLayer.type)) {
        return false;
      }
      return layerUtils.canLayerAcceptChildren(targetLayer, componentRegistry);
    }
    if (activeLayerId) {
      if (isLayerDescendantOf(layerId, activeLayerId)) {
        return false;
      }
      const draggedLayer = findLayerById(activeLayerId);
      if (!draggedLayer) {
        return layerUtils.canLayerAcceptChildren(targetLayer, componentRegistry);
      }
      const draggedDef = componentRegistry[draggedLayer.type];
      if (draggedDef?.childOf && !draggedDef.childOf.includes(targetLayer.type)) {
        return false;
      }
    }
    return layerUtils.canLayerAcceptChildren(targetLayer, componentRegistry);
  }, [activeLayerId, newComponentType, isLayerDescendantOf, findLayerById, componentRegistry]);
  return { canDropOnLayer };
};

exports.useDropValidation = useDropValidation;
