// Import necessary WordPress modules.
const { createContext, useContext, useState, useEffect } = wp.element;
const { useSelect } =  wp.data;
const { store: editPostStore } = wp.editPost ;

// Create a React Context to share the active device state across components.
const DeviceContext = createContext();

/**
 * DeviceProvider Component.
 *
 * Provides the current editor preview device type (desktop/tablet/mobile).
 * to all child components via React Context.
 *
 * @param {Object} props
 * @param {React.ReactNode} props.children - Components that consume the device context.
 */
export const DeviceProvider = ({ children }) => {

    // Get the currently selected preview device type from the block editor.
    const editorDevice = useSelect( ( select ) => {
        const store = select( editPostStore );

        // Fallback to 'desktop' if getPreviewDeviceType() is unavailable.
        return 'function' === typeof store.getPreviewDeviceType ?
            store.getPreviewDeviceType().toLowerCase() :
            'desktop';
    });

     // Local state to track the active device.
    const [ activeDevice, setActiveDevice ] = useState( editorDevice );

    // Update local state whenever the editor's preview device changes.
    useEffect( () => {
        setActiveDevice( editorDevice );
    }, [ editorDevice ]);

    // Provide the active device state and setter to child components.
    return (
        <DeviceContext.Provider value={{ activeDevice, setActiveDevice }}>
            {children}
        </DeviceContext.Provider>
    );
};

/**
* Custom hook to access the device context.
 *
 * @returns {{ activeDevice: string, setActiveDevice: Function }}.
 */
export const useDevice = () => useContext( DeviceContext );
