/**
 * WordPress dependencies
 */
import { PanelBody } from '@safe-wordpress/components';
import { useSelect } from '@safe-wordpress/data';
import { _x } from '@safe-wordpress/i18n';

/**
 * External dependencies
 */
import { store as NAB_EXPERIMENTS } from '@nab/experiments';

/**
 * Internal dependencies
 */
import './style.scss';
import { CustomUrlScope } from './custom-url-scope';
import { TestedUrlWithQueryArgsScope } from './tested-url-with-query-args-scope';
import { useExperimentAttribute } from '../../hooks';
import { UrlsOrPhpScope } from './urls-or-php-scope';

export const Scope = (): JSX.Element | null => {
	const scopeSupport = useScopeSupport();
	const testAgainstExistingContent = useTestAgainstExistingContent();

	if ( ! scopeSupport ) {
		return null;
	}

	if ( testAgainstExistingContent ) {
		return null;
	}

	switch ( scopeSupport ) {
		case 'tested-url-with-query-args':
			return <TestedUrlWithQueryArgsScope />;

		case 'urls-or-php':
			return (
				<PanelBody
					className="nab-experiment-scope"
					title={ _x( 'Test Scope', 'text', 'nelio-ab-testing' ) }
				>
					<UrlsOrPhpScope />
				</PanelBody>
			);

		case 'urls':
		case 'urls-with-tested-post':
		case 'tested-post-with-consistency':
		case 'tested-product-with-consistency':
			return (
				<PanelBody
					className="nab-experiment-scope"
					title={ _x( 'Test Scope', 'text', 'nelio-ab-testing' ) }
				>
					<CustomUrlScope scopeSupport={ scopeSupport } />
				</PanelBody>
			);
	}
};

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

const useScopeSupport = () => {
	const type = useExperimentAttribute( 'type' ) ?? '';
	return useSelect(
		( select ) =>
			select( NAB_EXPERIMENTS ).getExperimentSupport( type, 'scope' ),
		[ type ]
	);
};

const useTestAgainstExistingContent = () => {
	const alts = useExperimentAttribute( 'alternatives' ) ?? [];
	const control = alts[ 0 ];
	return !! control?.attributes?.testAgainstExistingContent;
};
