<?php
/**
 * AEO Meta Box — "AI Visibility Check".
 *
 * An editor-side intro linter. The editor pastes the intro, clicks Check, and
 * gets a score plus specific flags explaining how to stay cited (not replaced)
 * by AI answer engines. Runs entirely in the browser — no saving, no server
 * round-trip, no effect on the post.
 *
 * @package Platform\Helm\Modules\Aeo
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Aeo;

use Platform\Helm\Core\Assets;
use Platform\Helm\Core\Authorization;
use Platform\Helm\Core\LlmClient;
use Platform\Helm\Core\LlmSettings;
use Platform\Helm\Core\PostTypes;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class AeoMetaBox {

	private const REWRITE_NONCE = 'platform_helm_aeo_rewrite';

	public function __construct( private Assets $assets ) {}

	public function register_hooks(): void {
		add_action( 'add_meta_boxes', [ $this, 'add' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
		add_action( 'wp_ajax_platform_helm_aeo_rewrite', [ $this, 'ajax_rewrite' ] );
	}

	public function enqueue( string $hook ): void {
		if ( 'post.php' !== $hook && 'post-new.php' !== $hook ) {
			return;
		}
		$screen = get_current_screen();
		if ( ! $screen || ! in_array( $screen->post_type, PostTypes::content(), true ) ) {
			return;
		}
		$this->assets->enqueue_aeo();
		wp_localize_script( 'platform-helm-aeo', 'PlatformHelmAeo', [
			'ajaxUrl'    => admin_url( 'admin-ajax.php' ),
			'nonce'      => wp_create_nonce( self::REWRITE_NONCE ),
			'action'     => 'platform_helm_aeo_rewrite',
			'configured' => LlmSettings::is_configured() ? '1' : '',
		] );
	}

	public function add(): void {
		add_meta_box(
			'platform-helm-aeo',
			__( "Helm — AI Visibility Check", 'platform-helm' ),
			[ $this, 'render' ],
			PostTypes::content(),
			'normal',
			'default'
		);
	}

	public function render(): void {
		$configured = LlmSettings::is_configured();
		?>
		<div class="ph-aeo">
			<p class="ph-aeo-help">
				<?php esc_html_e( 'Paste your intro (first 1–2 paragraphs) and click Check. This scores how well the intro earns an AI citation without handing the whole answer away — so Gemini and friends cite you instead of replacing the click. Nothing is saved; this is a guide only.', 'platform-helm' ); ?>
			</p>
			<textarea id="ph-aeo-input" class="widefat" rows="5" placeholder="<?php esc_attr_e( 'Paste the article intro here…', 'platform-helm' ); ?>"></textarea>
			<p>
				<button type="button" class="button button-primary" id="ph-aeo-run"><?php esc_html_e( 'Check intro', 'platform-helm' ); ?></button>
				<?php if ( $configured ) : ?>
					<button type="button" class="button" id="ph-aeo-rewrite"><?php esc_html_e( 'Suggest a refined intro', 'platform-helm' ); ?></button>
				<?php endif; ?>
				<span id="ph-aeo-score" class="ph-aeo-score" aria-live="polite"></span>
			</p>
			<div id="ph-aeo-results" class="ph-aeo-results"></div>
			<?php if ( $configured ) : ?>
				<div id="ph-aeo-rewrite-box" class="ph-aeo-rewrite" style="display:none;">
					<div class="ph-aeo-rewrite-head">
						<strong><?php esc_html_e( 'Suggested intro', 'platform-helm' ); ?></strong>
						<button type="button" class="button button-small" id="ph-aeo-copy"><?php esc_html_e( 'Copy', 'platform-helm' ); ?></button>
					</div>
					<div id="ph-aeo-rewrite-text" class="ph-aeo-rewrite-text"></div>
					<p class="ph-aeo-help"><?php esc_html_e( 'AI-generated suggestion — review and edit before using. Nothing is saved automatically.', 'platform-helm' ); ?></p>
				</div>
			<?php else : ?>
				<p class="ph-aeo-help">
					<?php
					printf(
						/* translators: %s: settings URL */
						wp_kses_post( __( 'Want an AI-rewritten version? Connect a key under <a href="%s">AI Assistant</a>.', 'platform-helm' ) ),
						esc_url( admin_url( 'admin.php?page=platform-helm-ai' ) )
					);
					?>
				</p>
			<?php endif; ?>
		</div>
		<?php
	}

	public function ajax_rewrite(): void {
		check_ajax_referer( self::REWRITE_NONCE, 'nonce' );
		Authorization::require_master_admin_ajax();

		$intro = isset( $_POST['intro'] ) ? sanitize_textarea_field( wp_unslash( $_POST['intro'] ) ) : '';
		$title = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		if ( '' === trim( $intro ) ) {
			wp_send_json_error( [ 'message' => __( 'Paste an intro first.', 'platform-helm' ) ] );
		}

		$system = 'You are a skilled content editor. '
			. 'Rewrite the given article introduction so it performs well for AI answer engines while still earning the click. Rules: '
			. 'lead with a hook and context; do NOT give the complete answer away (keep the full numbers, lists and steps for the article body); '
			. 'include a concrete, specific detail where natural (a figure, a place, a named tool or standard relevant to the topic); '
			. 'add a light signal of authority or first-hand insight; end with a forward hook to the rest of the article; '
			. 'keep it roughly 50–85 words, in clear plain English, no clichés or filler. '
			. 'Return ONLY the rewritten introduction as plain text, with no preamble, quotes or labels.';

		$user = '' !== $title ? ( 'Article title: ' . $title . "\n\nIntro:\n" . $intro ) : ( "Intro:\n" . $intro );

		$res = LlmClient::chat(
			[
				[ 'role' => 'system', 'content' => $system ],
				[ 'role' => 'user', 'content' => $user ],
			],
			[ 'max_tokens' => 400, 'temperature' => 0.6 ]
		);
		if ( is_wp_error( $res ) ) {
			wp_send_json_error( [ 'message' => $res->get_error_message() ] );
		}
		wp_send_json_success( [ 'intro' => $res ] );
	}
}
