import { useState, useEffect, useRef } from '@wordpress/element';

export function usePreviewedDevice() {

	const [previewedDevice, setPreviewedDevice] = useState<device>('desktop');

	// Changing devices in footer controls.
	wp.customize.previewedDevice.bind(function (newDevice: device) {
		setPreviewedDevice(newDevice);
	});

	function handleDeviceClick(device: device): void {
		setPreviewedDevice(device);
		wp.customize.previewedDevice.set(device);
	}


	const props = {
		previewedDevice,
		setPreviewedDevice,
		handleDeviceClick,
	};

	return props;
}


type controlSettingProps = {
	controlSetting: {
		get: () => any;
		set: (a: any) => void;
	};
	value: any;
}

export function useControlSettingSet({ controlSetting, value }: controlSettingProps) {
	// 初回マウント時は set() を呼ばない（Customizerが変更済み状態になるのを防ぐ）.
	const isMounted = useRef(false);

	useEffect(() => {
		if ( ! isMounted.current ) {
			isMounted.current = true;
			return;
		}
		controlSetting.set(value);
	}, [value]);
}
