import { useSelect } from '@wordpress/data';
import { useRef, useEffect } from '@wordpress/element';
import { generateUniqueClass } from '../../components/utils/generateUniqueClass';

export function useUniqueBlockClass({ clientId, uniqueClass, setAttributes, blockName }) {
  const { hasDuplicateUniqueClass, ready } = useSelect((select) => {
    const be = select('core/block-editor');
    if (!be || !clientId) return { hasDuplicateUniqueClass: false, ready: false };

    // Get a flat list of ALL clientIds in the post (root + all descendants)
    const allIds = be.getClientIdsWithDescendants();
    // Read all blocks in one call
    const allBlocks = be.getBlocksByClientId(allIds);

    const dup = allBlocks.some(
      (block) =>
        block &&
        block.clientId !== clientId &&
        block.attributes?.uniqueClass === uniqueClass
    );

    return { hasDuplicateUniqueClass: dup, ready: true };
  }, [clientId, uniqueClass]);

  const hasInitialized = useRef(false);

  // Initial assignment (first mount only)
  useEffect(() => {
    if (!ready) return;
    if (hasInitialized.current) return;

    if (!uniqueClass || hasDuplicateUniqueClass) {
      setAttributes({ uniqueClass: generateUniqueClass(blockName) });
    }

    hasInitialized.current = true;
  }, [ready, uniqueClass, hasDuplicateUniqueClass, setAttributes, blockName]);

  // Guard against collisions that appear later (e.g., user pastes another copy)
  useEffect(() => {
    if (!ready) return;
    if (!uniqueClass) return;

    if (hasInitialized.current && hasDuplicateUniqueClass) {
      setAttributes({ uniqueClass: generateUniqueClass(blockName) });
    }
  }, [ready, hasDuplicateUniqueClass, uniqueClass, setAttributes, blockName]);
}
