( () => {
	const { __ } = wp.i18n;

	window.JeoLegendTypes.registerLegendType( 'barscale', {
	label: __( 'Color scale', 'jeowp' ),

	/**
	 * Returns the schema fo the legend_type_options for this legend type
	 */
	getSchema() {
		return {
			type: 'object',
			properties: {
				left_label: {
					type: 'string',
					description: __( 'The label shown at the left end of the bar', 'jeowp' ),
				},
				right_label: {
					type: 'string',
					description: __( 'The label shown at the right end of the bar', 'jeowp' ),
				},
				colors: {
					type: 'array',
					description: __( 'An array of hexadecimal color values', 'jeowp' ),
					items: {
						type: 'string',
					},
				},
			},
		};
	},

	render( map, attributes ) {
		const container = document.createElement( 'div' );
		container.classList.add( 'barscale-container' );

		const barContainer = document.createElement( 'div' );
		barContainer.classList.add( 'barscale-scale-container' );

		const size = attributes.legend_type_options.colors.length;
		const eachSize = 100 / size;

		const left = document.createElement( 'span' );
		left.classList.add( 'barscale-left-label' );
		left.innerHTML = attributes.legend_type_options.left_label;

		const right = document.createElement( 'span' );
		right.classList.add( 'barscale-right-label' );
		right.innerHTML = attributes.legend_type_options.right_label;

		attributes.legend_type_options.colors.forEach( ( c ) => {
			const color = document.createElement( 'div' );
			color.classList.add( 'barscale-color' );
			color.style.backgroundColor = c.color;
			color.style.width = eachSize + '%';
			barContainer.appendChild( color );
		} );

		const labelContainer = document.createElement( 'div' );
		labelContainer.classList.add( 'barscale-labels-container' );
		labelContainer.appendChild( left );
		labelContainer.appendChild( right );

		container.appendChild( barContainer );
		container.appendChild( labelContainer );

		return container;
	},
	} );
} )();
