import { useEffect, useRef } from '@wordpress/element';
import { settingsToCssVars } from '../utils/settings-to-css-vars';

/**
 * Wire the preview iframe ref so it receives live CSS var updates.
 *
 * @param {object} params
 * @param {object} params.iframeRef  React ref for the iframe element.
 * @param {object} params.settings   Current settings state.
 * @param {string} params.previewOrigin Origin used when posting messages.
 * @param {boolean} params.isReady  Whether the iframe has signaled readiness.
 */
export function usePreviewBridge( { iframeRef, settings, previewOrigin, isReady, device = 'desktop' } ) {
	const debounceTimer = useRef( null );

	useEffect( () => {
		if ( ! isReady || ! iframeRef.current ) {
			return;
		}
		if ( debounceTimer.current ) {
			clearTimeout( debounceTimer.current );
		}
		debounceTimer.current = setTimeout( () => {
			try {
				const bodyClasses = [
					`calm-header-mode-${ settings.header_desktop_behavior || 'scroll' }`,
					`calm-header-mobile-${ settings.header_mobile_behavior || 'sticky-glass' }`,
				];
				iframeRef.current.contentWindow.postMessage(
					{ type: 'wuppi:vars', vars: settingsToCssVars( settings, { device } ), bodyClasses },
					previewOrigin
				);
			} catch ( e ) {
				/* noop */
			}
		}, 60 );

		return () => {
			if ( debounceTimer.current ) {
				clearTimeout( debounceTimer.current );
			}
		};
	}, [ settings, isReady, iframeRef, previewOrigin, device ] );
}
