import { useEffect, useRef } from '@wordpress/element';
import {
	getEnabledBreakpoints,
	migrateAttributesForBreakpointChange,
	initBreakpointTracking,
} from './breakpoints';

export const useBreakpointMigration = ( attributes, setAttributes ) => {
	const previousBPsRef = useRef( null );
	const isInitializedRef = useRef( false );

	useEffect( () => {
		if ( ! isInitializedRef.current ) {
			previousBPsRef.current = initBreakpointTracking();
			isInitializedRef.current = true;
			return;
		}

		const currentBPs = getEnabledBreakpoints();
		const previousBPs = previousBPsRef.current;

		if (
			! previousBPs ||
			JSON.stringify( previousBPs ) === JSON.stringify( currentBPs )
		) {
			return;
		}

		const migratedAttrs = migrateAttributesForBreakpointChange(
			attributes,
			previousBPs,
			currentBPs
		);

		if ( Object.keys( migratedAttrs ).length > 0 ) {
			setAttributes( migratedAttrs );
		}

		previousBPsRef.current = [ ...currentBPs ];
	}, [ getEnabledBreakpoints() ] );

	return null;
};

export default useBreakpointMigration;
