/**
 * Breakpoint Indicator
 * レスポンシブプレビュー時に現在のブレークポイントを表示
 */

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

const BreakpointIndicator = () => {
	const [ device, setDevice ] = useState( null );
	const [ width, setWidth ] = useState( null );

	useEffect( () => {
		const updateFromBody = () => {
			const d = document.body.getAttribute(
				'data-zenblocks-preview-device'
			);
			const w = document.body.getAttribute(
				'data-zenblocks-preview-width'
			);
			setDevice( d );
			setWidth( w );
		};

		updateFromBody();

		const observer = new MutationObserver( ( mutations ) => {
			mutations.forEach( ( mutation ) => {
				if ( mutation.type === 'attributes' ) {
					updateFromBody();
				}
			} );
		} );

		observer.observe( document.body, {
			attributes: true,
			attributeFilter: [
				'data-zenblocks-preview-device',
				'data-zenblocks-preview-width',
			],
		} );

		return () => observer.disconnect();
	}, [] );

	if ( ! device ) {
		return null;
	}

	return (
		<div className="zenblocks-breakpoint-indicator">
			<span className="zenblocks-breakpoint-indicator__label">
				{ device.toUpperCase() }
			</span>
			{ width && (
				<span className="zenblocks-breakpoint-indicator__width">
					{ width }px
				</span>
			) }
		</div>
	);
};

export default BreakpointIndicator;
