/**
 * Basic SEO Helper Admin JavaScript
 */

(function ($) {
	'use strict';

	/**
	 * Media uploader functionality
	 */
	function initMediaUploader() {

		// Logo uploader
		$( '#upload_logo_button' ).on(
			'click',
			function (e) {
				e.preventDefault();

				var mediaUploader = wp.media(
					{
						title: 'Select Logo',
						button: {
							text: 'Use this logo'
						},
						multiple: false,
						library: {
							type: 'image'
						}
					}
				);

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

				mediaUploader.open();
			}
		);

		// Default image uploader
		$( '#upload_image_button' ).on(
			'click',
			function (e) {
				e.preventDefault();

				var mediaUploader = wp.media(
					{
						title: 'Select Default Social Image',
						button: {
							text: 'Use this image'
						},
						multiple: false,
						library: {
							type: 'image'
						}
					}
				);

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

				mediaUploader.open();
			}
		);
	}

	/**
	 * Initialize when document is ready
	 */
	$( document ).ready(
		function () {
			console.log( 'Basic SEO Helper admin JS loaded' );
			console.log( 'wp.media available:', typeof wp !== 'undefined' && typeof wp.media !== 'undefined' );

			// Only initialize media uploader if wp.media exists
			if (typeof wp !== 'undefined' && typeof wp.media !== 'undefined') {
				console.log( 'Initializing media uploader' );
				initMediaUploader();
			} else {
				console.error( 'wp.media not available. Make sure wp_enqueue_media() is called.' );

				// Fallback: show alert when buttons are clicked
				$( '#upload_logo_button, #upload_image_button' ).on(
					'click',
					function (e) {
						e.preventDefault();
						alert( 'Media uploader not available. Please make sure you are on a WordPress admin page.' );
					}
				);
			}
		}
	);

})( jQuery );