<?php
/**
 * Register Admin Page for Antimanual
 *
 * @package Antimanual
 * @since   1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action( 'admin_menu', 'antimanual_admin_menu' );
function antimanual_admin_menu() {
	$icon_svg = file_get_contents( ANTIMANUAL_DIR . 'assets/icons/antimanual.svg' );
	$icon     = 'data:image/svg+xml;base64,' . base64_encode( $icon_svg );

	$hook = add_menu_page(
		esc_html__( 'Antimanual', 'antimanual' ),
		esc_html__( 'Antimanual', 'antimanual' ),
		'manage_options',
		'antimanual',
		'antimanual_admin_page',
		$icon,
		56
	);

	foreach ( $GLOBALS['ATML_STORE']['menus'] as $sub_menu ) {
		$hook = add_submenu_page(
			'antimanual',
			$sub_menu['title'],
			$sub_menu['title'],
			'manage_options',
			$sub_menu['slug'],
			$sub_menu['callback'] ?? 'antimanual_admin_page',
		);
	}
}

function antimanual_admin_scripts( $hook ) {
	if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
		return;
	}

	$post_type = get_post_type();
	
	// Data to localize
	$antimanual_ajax = array(
		'ajaxurl' => admin_url( 'admin-ajax.php' ),
		'post_id' => get_the_ID(),
		'nonce'   => wp_create_nonce( 'antimanual_process' )
	);

	// 1. AI Excerpt Generator (chatbot-admin.js)
	if ( post_type_supports( $post_type, 'excerpt' ) ) {
		wp_enqueue_script( 
			'antimanual-chatbot-admin-js', 
			ANTIMANUAL_URL . 'assets/js/chatbot-admin.js', 
			array( 'wp-element', 'wp-i18n', 'wp-data', 'wp-dom-ready' ), 
			ANTIMANUAL_VERSION, 
			true 
		);
		wp_localize_script( 'antimanual-chatbot-admin-js', 'antimanual_ajax', $antimanual_ajax );
		wp_set_script_translations( 'antimanual-chatbot-admin-js', 'antimanual', ANTIMANUAL_DIR . 'languages' );
	}

	// 2. AI Categories & Tags Generator (tags.js)
	if ( post_type_supports( $post_type, 'post_tag' ) || post_type_supports( $post_type, 'category' ) || $post_type == 'post' ) {
		wp_enqueue_script( 
			'antimanual-chatbot-tags-js', 
			ANTIMANUAL_URL . 'assets/js/tags.js', 
			array( 'wp-element', 'wp-components', 'wp-plugins', 'wp-edit-post', 'wp-i18n', 'wp-data' ), 
			ANTIMANUAL_VERSION, 
			true 
		);
		wp_localize_script( 'antimanual-chatbot-tags-js', 'antimanual_ajax', $antimanual_ajax );
		wp_set_script_translations( 'antimanual-chatbot-tags-js', 'antimanual', ANTIMANUAL_DIR . 'languages' );
	}
}

add_action( 'admin_enqueue_scripts', 'antimanual_admin_scripts' );

/**
 * Enqueue the inline AI Copilot ("Magic Wand") bundle in the block editor.
 *
 * Registers a formatting-toolbar button on RichText fields that transforms the
 * current selection via the antimanual/v1/copilot REST endpoint. Loaded only
 * for users who can edit posts and only when the built asset exists.
 */
function antimanual_enqueue_editor_copilot() {
	if ( ! current_user_can( 'edit_posts' ) ) {
		return;
	}

	$asset_path  = ANTIMANUAL_DIR . 'build/editor.asset.php';
	$script_path = ANTIMANUAL_DIR . 'build/editor.js';

	if ( ! file_exists( $asset_path ) || ! file_exists( $script_path ) ) {
		return;
	}

	$asset = require $asset_path;

	wp_enqueue_script(
		'antimanual-editor-copilot',
		ANTIMANUAL_URL . 'build/editor.js',
		$asset['dependencies'] ?? [],
		$asset['version'] ?? ANTIMANUAL_VERSION,
		true
	);

	wp_set_script_translations( 'antimanual-editor-copilot', 'antimanual', ANTIMANUAL_DIR . 'languages' );

	wp_localize_script(
		'antimanual-editor-copilot',
		'antimanualCopilot',
		[
			'provider'  => \Antimanual\AIProvider::get_display_name(),
			'hasKey'    => \Antimanual\AIProvider::has_api_key(),
			'languages' => [
				'Spanish',
				'French',
				'German',
				'Arabic',
				'Chinese',
				'Korean',
				'Russian',
				'Bengali',
			],
		]
	);
}
add_action( 'enqueue_block_editor_assets', 'antimanual_enqueue_editor_copilot' );

/**
 * Determine whether the current admin screen should show the Generate Post CTA.
 *
 * @return bool
 */
function antimanual_should_show_generate_post_cta() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return false;
	}

	$module_prefs = wp_parse_args(
		get_option( 'antimanual_module_prefs', [] ),
		\Antimanual\Api\PreferencesController::MODULE_DEFAULTS
	);
	if ( empty( $module_prefs['generate_post'] ) ) {
		return false;
	}

	global $pagenow;

	$screen    = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	$post_type = $screen->post_type ?? '';

	if ( '' === $post_type ) {
		$post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : 'post';
	}

	if ( 'post' !== $post_type ) {
		return false;
	}

	if ( ! $screen ) {
		return in_array( $pagenow, [ 'edit.php', 'post.php', 'post-new.php' ], true );
	}

	return in_array( $screen->base, [ 'edit', 'post' ], true );
}

/**
 * Print styles for the Generate Post CTA on post list/editor screens.
 */
function antimanual_generate_post_cta_styles() {
	if ( ! antimanual_should_show_generate_post_cta() ) {
		return;
	}
	?>
	<style>
		.atml-create-with-ai-button {
			display: inline-flex !important;
			align-items: center;
			gap: 6px;
			white-space: nowrap;
			top: 0 !important;
			left: 2px;
		}

		.atml-create-with-ai-editor-button {
			margin-left: 8px;
		}

		.atml-create-with-ai-editor-slot {
			display: inline-flex;
			align-items: center;
			flex-shrink: 0;
			margin-left: 8px;
		}

		.edit-post-header > .atml-create-with-ai-editor-slot {
			align-self: center;
		}

		.atml-create-with-ai-editor-slot .atml-create-with-ai-button {
			height: 32px;
			text-decoration: none;
		}
	</style>
	<?php
}
add_action( 'admin_head', 'antimanual_generate_post_cta_styles' );

/**
 * Print the Generate Post CTA on post archive and editor screens.
 */
function antimanual_generate_post_cta_script() {
	if ( ! antimanual_should_show_generate_post_cta() ) {
		return;
	}

	$screen       = get_current_screen();
	$screen_base  = $screen->base ?? ( 'edit.php' === $GLOBALS['pagenow'] ? 'edit' : 'post' );
	$generate_url = admin_url( 'admin.php?page=atml-generate-post' );
	$label        = __( 'Create with AI', 'antimanual' );
	?>
	<script>
		(function () {
			var generateUrl = <?php echo wp_json_encode( $generate_url ); ?>;
			var label = <?php echo wp_json_encode( $label ); ?>;
			var screenBase = <?php echo wp_json_encode( $screen_base ); ?>;

			function createIcon() {
				var tmp = document.createElement("div");
				tmp.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" clip-rule="evenodd" d="M9 4.5a.75.75 0 01.721.544l.813 2.846a3.75 3.75 0 002.576 2.576l2.846.813a.75.75 0 010 1.442l-2.846.813a3.75 3.75 0 00-2.576 2.576l-.813 2.846a.75.75 0 01-1.442 0l-.813-2.846a3.75 3.75 0 00-2.576-2.576l-2.846-.813a.75.75 0 010-1.442l2.846-.813A3.75 3.75 0 007.466 7.89l.813-2.846A.75.75 0 019 4.5zM18 1.5a.75.75 0 01.728.568l.258 1.036c.236.94.97 1.674 1.91 1.91l1.036.258a.75.75 0 010 1.456l-1.036.258c-.94.236-1.674.97-1.91 1.91l-.258 1.036a.75.75 0 01-1.456 0l-.258-1.036a2.625 2.625 0 00-1.91-1.91l-1.036-.258a.75.75 0 010-1.456l1.036-.258a2.625 2.625 0 001.91-1.91l.258-1.036A.75.75 0 0118 1.5zM16.5 15a.75.75 0 01.712.513l.394 1.183c.15.447.5.799.948.948l1.183.395a.75.75 0 010 1.422l-1.183.395c-.447.15-.799.5-.948.948l-.395 1.183a.75.75 0 01-1.422 0l-.395-1.183a1.5 1.5 0 00-.948-.948l-1.183-.395a.75.75 0 010-1.422l1.183-.395c.447-.15.799-.5.948-.948l.395-1.183A.75.75 0 0116.5 15z"/></svg>';
				return tmp.firstChild;
			}

			function createButton(className) {
				var button = document.createElement("a");
				button.href = generateUrl;
				button.className = className;
				button.setAttribute("aria-label", label);
				button.appendChild(createIcon());
				button.appendChild(document.createTextNode(label));
				return button;
			}

			function placeArchiveButton() {
				if (document.querySelector(".atml-create-with-ai-archive-button")) {
					return true;
				}

				var heading = document.querySelector(".wrap .wp-heading-inline");
				if (!heading) {
					return false;
				}

				var button = createButton("page-title-action atml-create-with-ai-button atml-create-with-ai-archive-button");
				heading.insertAdjacentElement("afterend", button);
				return true;
			}

			function placeEditorButton() {
				if (document.querySelector(".atml-create-with-ai-editor-button, .atml-create-with-ai-editor-slot")) {
					return true;
				}

				var blockHeader = document.querySelector(".editor-header, .edit-post-header");
				if (blockHeader) {
					var slot = document.createElement("div");
					slot.className = "atml-create-with-ai-editor-slot";
					slot.appendChild(createButton("components-button is-secondary atml-create-with-ai-button"));

					var toolbar = blockHeader.querySelector(".editor-header__toolbar, .edit-post-header__toolbar");
					var actions = blockHeader.querySelector(".editor-header__settings, .edit-post-header__settings");

					if (toolbar && toolbar.parentNode === blockHeader) {
						toolbar.insertAdjacentElement("afterend", slot);
					} else if (actions && actions.parentNode === blockHeader) {
						blockHeader.insertBefore(slot, actions);
					} else {
						blockHeader.appendChild(slot);
					}
					return true;
				}

				var classicTitle = document.querySelector(".wrap h1.wp-heading-inline, .wrap h1");
				if (classicTitle) {
					classicTitle.insertAdjacentElement(
						"afterend",
						createButton("page-title-action atml-create-with-ai-button atml-create-with-ai-editor-button")
					);
					return true;
				}

				return false;
			}

			function placeButton() {
				return screenBase === "edit" ? placeArchiveButton() : placeEditorButton();
			}

			if (placeButton()) {
				return;
			}

			var attempts = 0;
			var interval = window.setInterval(function () {
				attempts += 1;
				if (placeButton() || attempts >= 20) {
					window.clearInterval(interval);
				}
			}, 250);

			if (window.MutationObserver) {
				var observer = new MutationObserver(function () {
					if (placeButton()) {
						observer.disconnect();
						window.clearInterval(interval);
					}
				});
				observer.observe(document.body, { childList: true, subtree: true });

				window.setTimeout(function () {
					observer.disconnect();
				}, 10000);
			}
		})();
	</script>
	<?php
}
add_action( 'admin_footer', 'antimanual_generate_post_cta_script' );
