import { ToolbarGroup, ToolbarButton } from '@wordpress/components';
import { desktop, tablet, mobile } from '@wordpress/icons';
import { dispatch } from '@wordpress/data';
import { useDevice } from '../DeviceContext';

// Our device keys are lowercase; WP store expects 'Desktop' | 'Tablet' | 'Mobile'.
const toWpDeviceType = ( key ) => key.charAt( 0 ).toUpperCase() + key.slice( 1 );

const setWpPreviewDevice = ( deviceKey ) => {
	const wpType = toWpDeviceType( deviceKey );
	try {
		// WP 6.3+ unified editor
		if ( typeof dispatch( 'core/editor' )?.setDeviceType === 'function' ) {
			dispatch( 'core/editor' ).setDeviceType( wpType );
			return;
		}
		// Older: core/edit-post
		if ( typeof dispatch( 'core/edit-post' )?.__experimentalSetPreviewDeviceType === 'function' ) {
			dispatch( 'core/edit-post' ).__experimentalSetPreviewDeviceType( wpType );
		}
	} catch ( e ) {}
};

export default function ResponsiveControl( { renderControl } ) {
	const { activeDevice, setActiveDevice, devices } = useDevice();

	const handleDeviceChange = ( newDevice ) => {
		// Update local context so StyleTabs / style controls reflect the new device.
		setActiveDevice( newDevice );
		// Dispatch to WP store — editor/index.js subscriber applies the correct
		// canvas width from the axcelersblocks settings page.
		setWpPreviewDevice( newDevice );
	};

	const numberOfDevices = Object.keys( devices ).length;
	const buttonWidth = numberOfDevices > 0 ? `${ 100 / numberOfDevices }%` : '100%';

	return (
		<div className="axcelersblocks-responsive-control">
			<div className="axcelersblocks-responsive-header">
				<ToolbarGroup className="axcelersblocks-device-switcher">
					{ Object.keys( devices ).map( ( deviceKey ) => (
						<div key={ deviceKey } style={ { width: buttonWidth } }>
							<ToolbarButton
								icon={
									deviceKey === 'desktop'
										? desktop
										: deviceKey === 'tablet'
										? tablet
										: mobile
								}
								isPressed={ activeDevice === deviceKey }
								onClick={ () => handleDeviceChange( deviceKey ) }
							/>
						</div>
					) ) }
				</ToolbarGroup>
			</div>

			<div className="axcelersblocks-responsive-content">
				{ renderControl && renderControl() }
			</div>
		</div>
	);
}
