<?php
/**
 * Meta Generator Meta Box.
 *
 * Editor panel: one click drafts an SEO meta title (≤60) and description
 * (≤155) from the article, with live character counts and copy buttons.
 * Suggestion-only; you paste the result into Yoast.
 *
 * @package Platform\Helm\Modules\Meta_Gen
 */

declare( strict_types = 1 );

namespace Platform\Helm\Modules\Meta_Gen;

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 MetaGenMetaBox {

	private const NONCE = 'platform_helm_meta_gen';

	public function register_hooks(): void {
		add_action( 'add_meta_boxes', [ $this, 'add' ] );
		add_action( 'wp_ajax_platform_helm_meta_generate', [ $this, 'ajax_generate' ] );
	}

	public function add(): void {
		add_meta_box(
			'platform-helm-meta-gen',
			__( "Helm — AI Meta (title + description)", 'platform-helm' ),
			[ $this, 'render' ],
			PostTypes::content(),
			'normal',
			'default'
		);
	}

	public function render(): void {
		if ( ! LlmSettings::is_configured() ) {
			echo '<p>' . wp_kses_post( sprintf(
				/* translators: %s settings URL */
				__( 'Connect an AI key under <a href="%s">AI Assistant</a> to use this.', 'platform-helm' ),
				esc_url( admin_url( 'admin.php?page=platform-helm-ai' ) )
			) ) . '</p>';
			return;
		}
		$nonce = wp_create_nonce( self::NONCE );
		?>
		<div class="ph-metagen">
			<p class="description"><?php esc_html_e( 'Drafts an SEO title and meta description from this article. Copy what you like into Yoast — nothing is written automatically.', 'platform-helm' ); ?></p>
			<p><button type="button" class="button button-primary" id="ph-meta-gen"><?php esc_html_e( 'Generate title + description (AI)', 'platform-helm' ); ?></button>
				<span id="ph-meta-msg" aria-live="polite" style="margin-left:8px;color:#646970;"></span></p>

			<p><strong><?php esc_html_e( 'Meta title', 'platform-helm' ); ?></strong> <span id="ph-meta-title-count" style="color:#646970;font-size:12px;"></span><br />
				<input type="text" id="ph-meta-title" class="widefat" />
				<button type="button" class="button button-small ph-meta-copy" data-target="ph-meta-title" style="margin-top:4px;"><?php esc_html_e( 'Copy', 'platform-helm' ); ?></button></p>

			<p><strong><?php esc_html_e( 'Meta description', 'platform-helm' ); ?></strong> <span id="ph-meta-desc-count" style="color:#646970;font-size:12px;"></span><br />
				<textarea id="ph-meta-desc" class="widefat" rows="3"></textarea>
				<button type="button" class="button button-small ph-meta-copy" data-target="ph-meta-desc" style="margin-top:4px;"><?php esc_html_e( 'Copy', 'platform-helm' ); ?></button></p>
		</div>
		<script>
		( function () {
			var ajaxUrl = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;
			var nonce = <?php echo wp_json_encode( $nonce ); ?>;
			var btn = document.getElementById( 'ph-meta-gen' );
			var msg = document.getElementById( 'ph-meta-msg' );
			var titleEl = document.getElementById( 'ph-meta-title' );
			var descEl = document.getElementById( 'ph-meta-desc' );
			if ( ! btn ) { return; }

			function counts() {
				var tc = document.getElementById( 'ph-meta-title-count' );
				var dc = document.getElementById( 'ph-meta-desc-count' );
				if ( tc ) { tc.textContent = titleEl.value.length + '/60'; tc.style.color = titleEl.value.length > 60 ? '#b32d2e' : '#646970'; }
				if ( dc ) { dc.textContent = descEl.value.length + '/155'; dc.style.color = descEl.value.length > 155 ? '#b32d2e' : '#646970'; }
			}
			titleEl.addEventListener( 'input', counts );
			descEl.addEventListener( 'input', counts );

			function getPostId() {
				try { if ( window.wp && wp.data && wp.data.select( 'core/editor' ) ) { var id = wp.data.select( 'core/editor' ).getCurrentPostId(); if ( id ) { return id; } } } catch ( e ) {}
				var el = document.getElementById( 'post_ID' );
				return el ? el.value : '';
			}

			btn.addEventListener( 'click', function () {
				var id = getPostId();
				if ( ! id ) { msg.textContent = 'Save the post once, then try again.'; return; }
				btn.disabled = true; var lbl = btn.textContent; btn.textContent = 'Reading the article…'; msg.textContent = '';
				var body = new URLSearchParams();
				body.append( 'action', 'platform_helm_meta_generate' );
				body.append( 'nonce', nonce );
				body.append( 'post_id', id );
				fetch( ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
					.then( function ( r ) { return r.json(); } )
					.then( function ( res ) {
						btn.disabled = false; btn.textContent = lbl;
						if ( res && res.success && res.data ) {
							titleEl.value = res.data.title || '';
							descEl.value = res.data.description || '';
							counts();
							msg.textContent = 'Drafted — review, edit, and copy into Yoast.';
						} else { msg.textContent = ( res && res.data && res.data.message ) ? res.data.message : 'Could not generate.'; }
					} )
					.catch( function () { btn.disabled = false; btn.textContent = lbl; msg.textContent = 'Request failed — try again.'; } );
			} );

			document.addEventListener( 'click', function ( e ) {
				var t = e.target;
				if ( ! t || ! t.classList || ! t.classList.contains( 'ph-meta-copy' ) ) { return; }
				e.preventDefault();
				var el = document.getElementById( t.getAttribute( 'data-target' ) );
				if ( el && navigator.clipboard ) { navigator.clipboard.writeText( el.value || '' ); t.textContent = 'Copied'; setTimeout( function () { t.textContent = 'Copy'; }, 1500 ); }
			} );
		}() );
		</script>
		<?php
	}

	public function ajax_generate(): void {
		check_ajax_referer( self::NONCE, 'nonce' );
		Authorization::require_master_admin_ajax();

		$post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0;
		$post    = $post_id > 0 ? get_post( $post_id ) : null;
		if ( ! $post ) {
			wp_send_json_error( [ 'message' => __( 'Post not found.', 'platform-helm' ) ] );
		}

		$title   = get_the_title( $post );
		$content = wp_strip_all_tags( strip_shortcodes( (string) $post->post_content ) );
		$content = mb_substr( trim( (string) preg_replace( '/\s+/', ' ', $content ) ), 0, 6000 );

		$system = 'You write SEO metadata for web articles. '
			. 'From the article, produce a meta title (MAX 60 characters, compelling and keyword-forward) and a meta description '
			. '(MAX 155 characters, benefit-led with a clear reason to click), in clear plain English. '
			. 'Return ONLY minified JSON — no markdown, no commentary — exactly: {"title":"","description":""}';
		$user = 'Title: ' . $title . "\n\nArticle:\n" . $content;

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

		$json = (string) preg_replace( '/^```(?:json)?\s*/i', '', trim( $res ) );
		$json = (string) preg_replace( '/\s*```$/', '', $json );
		$s    = strpos( $json, '{' );
		$e    = strrpos( $json, '}' );
		if ( false !== $s && false !== $e && $e > $s ) {
			$json = substr( $json, $s, $e - $s + 1 );
		}
		$data = json_decode( $json, true );
		if ( ! is_array( $data ) ) {
			wp_send_json_error( [ 'message' => __( 'Could not parse the AI response. Try again.', 'platform-helm' ) ] );
		}

		wp_send_json_success( [
			'title'       => sanitize_text_field( (string) ( $data['title'] ?? '' ) ),
			'description' => sanitize_text_field( (string) ( $data['description'] ?? '' ) ),
		] );
	}
}
