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

/**
 * External dependencies
 */
import { ConversionActionScopeView } from '@nab/components';
import { formatDuration } from '@nab/utils';
import type { CAViewProps, ConversionActionScope } from '@nab/types';

/**
 * Internal dependencies
 */
import type { Attributes } from './types';

export const View = ( props: CAViewProps< Attributes > ): JSX.Element => (
	<>
		<div>
			<ActualView { ...props } />
		</div>
		<ConversionActionScopeView scope={ props.scope } />
	</>
);

const ActualView = ( {
	attributes: { value },
	scope,
}: CAViewProps< Attributes > ): JSX.Element => {
	const label = useLabel( scope );
	const duration = formatDuration( value, 'seconds' );
	return createInterpolateElement(
		sprintf( label, `<strong>${ duration }</strong>` ),
		{ strong: <strong /> }
	);
};

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

const useLabel = ( scope: ConversionActionScope ): string => {
	switch ( scope.type ) {
		case 'all-pages':
			/* translators: %s: Time duration, such as "3 minutes, 2 seconds". */
			return _x(
				'A visitor has spent %s on any page.',
				'text',
				'nelio-ab-testing'
			);

		case 'test-scope':
			/* translators: %s: Time duration, such as "3 minutes, 2 seconds". */
			return _x(
				'A visitor has spent %s on a tested page.',
				'text',
				'nelio-ab-testing'
			);

		case 'urls':
		case 'post-ids':
		case 'php-function':
			/* translators: %s: Time duration, such as "3 minutes, 2 seconds". */
			return _x(
				'A visitor has spent %s on certain pages.',
				'text',
				'nelio-ab-testing'
			);
	}
};
