/**
 * WordPress dependencies
 */
import { useDispatch, useSelect } from '@wordpress/data';

/**
 * Internal dependencies
 */
import { store as NAB_CHECKER } from '../store';
import { State } from '../store/types';

export const Position = (): JSX.Element => (
	<div style={ RELATIVE_WRAPPER_STYLE }>
		<div style={ POSITION_STYLE }>
			<PositionButton name="top-left" />
			<PositionButton name="top-right" />
			<PositionButton name="bottom-left" />
			<PositionButton name="bottom-right" />
		</div>
	</div>
);

// =====
// VIEWS
// =====

function PositionButton( { name }: { name: State[ 'position' ] } ) {
	const activePosition = useSelect(
		( select ) => select( NAB_CHECKER ).getPosition(),
		[]
	);

	const { setPosition } = useDispatch( NAB_CHECKER );

	return (
		<button
			style={ { ...BUTTON_STYLE, ...getCornerStyle( name ) } }
			disabled={ name === activePosition }
			onClick={ () => setPosition( name ) }
		>
			<span style={ VISUALLY_HIDDEN }>{ name.replace( '-', ' ' ) }</span>
		</button>
	);
}

function getCornerStyle( name: State[ 'position' ] ) {
	const radius = '3px';
	switch ( name ) {
		case 'top-left':
			return {
				borderRight: 'none' as const,
				borderBottom: 'none' as const,
				borderTopLeftRadius: radius,
			};

		case 'top-right':
			return {
				borderLeft: 'none' as const,
				borderBottom: 'none' as const,
				borderTopRightRadius: radius,
			};

		case 'bottom-left':
			return {
				borderRight: 'none' as const,
				borderTop: 'none' as const,
				borderBottomLeftRadius: radius,
			};

		case 'bottom-right':
			return {
				borderLeft: 'none' as const,
				borderTop: 'none' as const,
				borderBottomRightRadius: radius,
			};
	}
}

// ======
// STYLES
// ======

const RELATIVE_WRAPPER_STYLE = { position: 'relative' as const };

const POSITION_STYLE = {
	display: 'grid' as const,
	gridTemplateColumns: '1fr 1fr',
	position: 'absolute' as const,
	top: '0',
	right: '0',
};

const BUTTON_STYLE = {
	border: '1px solid gray',
	borderRadius: 0,
	fontSize: '11px',
	height: '1em',
	lineHeight: '0',
	width: '1em',
};

const VISUALLY_HIDDEN = {
	position: 'absolute' as const,
	width: '1px',
	height: '1px',
	padding: '0',
	margin: '-1px',
	overflow: 'hidden' as const,
	clip: 'rect(0, 0, 0, 0)',
	whiteSpace: 'nowrap' as const,
	border: '0',
};
