(function() {
	if ( typeof window.tinymce === 'undefined' ) {
		return;
	}

	tinymce.PluginManager.add( 'pixelmole_followup_button', function( editor ) {
		var defaultColor = '#635BFF';

		if ( typeof window.PixelMoleFollowup === 'object' && PixelMoleFollowup && PixelMoleFollowup.colors && PixelMoleFollowup.colors.accent ) {
			defaultColor = PixelMoleFollowup.colors.accent;
		}

		function sanitizeColor( value, fallback ) {
			if ( typeof value !== 'string' ) {
				return fallback;
			}

			value = value.trim();

			if ( /^#[0-9a-fA-F]{3,6}$/.test( value ) ) {
				return value;
			}

			return fallback;
		}

		function insertButton( data ) {
			var text = data.text ? editor.dom.encode( data.text ) : editor.dom.encode( 'Click here' );
			var url = data.url ? editor.dom.encode( data.url ) : '#';
			var color = sanitizeColor( data.color, defaultColor );
			var textColor = sanitizeColor( data.textColor, '#ffffff' );

			var style = 'display:inline-block;padding:12px 20px;background-color:' + color +
				';color:' + textColor +
				';text-decoration:none;border-radius:6px;font-weight:600;';

			if ( data.fullWidth ) {
				style += 'display:block;text-align:center;';
			}

			var buttonHtml = '<a href="' + url + '" class="pixelmole-email-button" style="' + style + '">' + text + '</a>';
			editor.insertContent( buttonHtml );
		}

		editor.addButton( 'pixelmoleFollowupButton', {
			text: '',
			icon: 'ico-button',
			tooltip: editor.getLang( 'pixelmole_followup_button.tooltip', 'Insert a styled button' ),
			onclick: function() {
				editor.windowManager.open( {
					title: editor.getLang( 'pixelmole_followup_button.modal_title', 'Insert button' ),
					body: [
						{
							type: 'textbox',
							name: 'text',
							label: editor.getLang( 'pixelmole_followup_button.text_label', 'Button text' ),
							value: ''
						},
						{
							type: 'textbox',
							name: 'url',
							label: editor.getLang( 'pixelmole_followup_button.url_label', 'Link URL' ),
							value: ''
						},
						{
							type: 'textbox',
							name: 'color',
							label: editor.getLang( 'pixelmole_followup_button.color_label', 'Background color (hex)' ),
							value: defaultColor
						},
						{
							type: 'textbox',
							name: 'textColor',
							label: editor.getLang( 'pixelmole_followup_button.text_color_label', 'Text color (hex)' ),
							value: '#ffffff'
						},
						// {
						// 	type: 'checkbox',
						// 	name: 'fullWidth',
						// 	label: editor.getLang( 'pixelmole_followup_button.full_width_label', 'Full width button' ),
						// 	checked: false
						// }
					],
					onsubmit: function( e ) {
						insertButton( e.data );
					}
				} );
			}
		} );
	} );
})();
