jQuery( document ).ready(
	function ( $ ) {
		// Media uploader for meta box
		$( '#upload_meta_image_button' ).on(
			'click',
			function ( e ) {
				e.preventDefault();

				if ( typeof wp !== 'undefined' && typeof wp.media !== 'undefined' ) {
					var mediaUploader = wp.media(
						{
							title: cspgbaseMetaBox.selectImageTitle,
							button: {
								text: cspgbaseMetaBox.useImageText
							},
							multiple: false,
							library: {
								type: 'image'
							}
						}
					);

					mediaUploader.on(
						'select',
						function () {
							var attachment = mediaUploader.state().get( 'selection' ).first().toJSON();
							$( '#basic_seo_helper_image' ).val( attachment.url );

							// Update preview
							var preview = $( '.image-preview' );
							if ( preview.length ) {
								preview.find( 'img' ).attr( 'src', attachment.url );
							} else {
								$( '#basic_seo_helper_image' ).after(
									'<div class="image-preview" style="margin-top: 10px;"><img src="' + attachment.url + '" style="max-width: 300px; max-height: 150px; border: 1px solid #ddd;" alt="Social Image Preview" /></div>'
								);
							}
						}
					);

					mediaUploader.open();
				} else {
					alert( cspgbaseMetaBox.mediaUnavailable );
				}
			}
		);
	}
);
