// Import necessary WordPress modules.
const { ButtonGroup, Button, Dashicon } = wp.components;
const { dispatch } = wp.data;

// Import custom hook for device context.
import { useDevice } from './DeviceContext';

// List of supported devices for preview mode.
const devices = [ 'desktop', 'tablet', 'mobile' ];

/**
 * DeviceSwitcher Component.
 *
 * Renders a button group with device icons that let users switch between
 * desktop, tablet, and mobile preview modes in the WordPress block editor.
 */
const DeviceSwitcher = () => {
    const { activeDevice, setActiveDevice } = useDevice(); // Access device context.

    /**
     * Handles switching the preview device in both:
     * - WordPress editor preview (via dispatch).
     * - Local context (via setActiveDevice).
     *
     * @param {string} device - The device name (desktop/tablet/mobile).
     */
    const handleChange = ( device ) => {
        const previewDispatcher = dispatch( 'core/edit-post' );1;

        // Update the editor preview mode using WordPress internal function.
        if ( 'function' === typeof previewDispatcher.__experimentalSetPreviewDeviceType ) {
            previewDispatcher.__experimentalSetPreviewDeviceType(
                device.charAt( 0 ).toUpperCase() + device.slice( 1 ) // Capitalize device name
            );
        }

        // Update device state in context.
        setActiveDevice( device );
    };

    return (
        <ButtonGroup>
            {/* Render a button for each device. */}
            {devices.map( ( device ) => (
                <Button
                    key={device}
                    isPressed={activeDevice === device} // Highlight active device.
                    onClick={() => handleChange( device )} // Change preview on click.
                    className={`device-tab-btn ${activeDevice === device ? 'is-active' : ''}`}
                >
                    {/* Set icon based on device type.  */}
                    <Dashicon
                        icon={
                            'desktop' === device ?
                                'desktop' :
                                'tablet' === device ?
                                'tablet' :
                                'smartphone'
                        }
                    />
                </Button>
            ) )}
        </ButtonGroup>
    );
};

export default DeviceSwitcher;
