/**
 * WordPress dependencies
 */
import { useRef } from '@wordpress/element';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import clsx from 'clsx';
import { usePageAttribute } from '@nab/data';

/**
 * Internal dependencies
 */
import './style.scss';

export type CssPreviewProps = {
	readonly className?: string;
	readonly previewUrl?: string;
	readonly value: string;
};

export const CssPreview = ( {
	className,
	previewUrl,
}: CssPreviewProps ): JSX.Element => {
	const initialUrl = useRef( previewUrl );
	const currentPreviewResolution = useActiveResolution();
	return (
		<div className={ clsx( [ className, 'nab-css-preview' ] ) }>
			<iframe
				className={ clsx( [
					'nab-css-preview__iframe',
					`nab-css-preview__iframe--${ currentPreviewResolution }`,
				] ) }
				title={ _x( 'CSS Preview', 'text', 'nelio-ab-testing' ) }
				src={ initialUrl.current }
			></iframe>
		</div>
	);
};

// =====
// HOOKS
// =====

const useActiveResolution = () =>
	usePageAttribute( 'css-preview/activeResolution', 'desktop' )[ 0 ];
