<?php
/** WordPress-Backend-Oberfläche und REST-Transport für den Live-Editor. */

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

function wpagent_companion_live_editor_menu(): void {
	add_submenu_page(
		'wpagently',
		__( 'Live-Editor', 'wp-agent-companion' ),
		__( 'Live-Editor', 'wp-agent-companion' ),
		'manage_options',
		'wpagently-live-editor',
		'wpagent_companion_live_editor_page'
	);
}
add_action( 'admin_menu', 'wpagent_companion_live_editor_menu', 21 );

function wpagent_companion_live_editor_assets( string $hook ): void {
	if ( 'wpagently_page_wpagently-live-editor' !== $hook ) {
		return;
	}
	$plugin_file = WPAGENT_COMPANION_DIR . 'wp-agent-companion.php';
	wp_enqueue_style( 'wpagently-live-editor', plugins_url( 'assets/live-editor-admin.css', $plugin_file ), array( 'wpagently-admin-base' ), WPAGENT_COMPANION_VERSION );
	wp_enqueue_script( 'wpagently-live-editor-runtime', plugins_url( 'assets/live-editor-runtime.js', $plugin_file ), array(), WPAGENT_COMPANION_VERSION, true );
	wp_enqueue_script( 'wpagently-live-editor-elementor-runtime', plugins_url( 'assets/live-editor-elementor-runtime.js', $plugin_file ), array(), WPAGENT_COMPANION_VERSION, true );
	wp_enqueue_script( 'wpagently-live-editor-provider-finalize-runtime', plugins_url( 'assets/live-editor-provider-finalize-runtime.js', $plugin_file ), array( 'wpagently-live-editor-runtime' ), WPAGENT_COMPANION_VERSION, true );
	wp_enqueue_script( 'wpagently-live-editor', plugins_url( 'assets/live-editor-admin.js', $plugin_file ), array( 'wpagently-live-editor-runtime', 'wpagently-live-editor-elementor-runtime', 'wpagently-live-editor-provider-finalize-runtime' ), WPAGENT_COMPANION_VERSION, true );
	wp_localize_script(
		'wpagently-live-editor',
		'wpagentlyLiveEditor',
		array(
			'createUrl'   => rest_url( 'wp-agent/live-editor/session' ),
			'pollUrl'     => rest_url( 'wp-agent/live-editor/poll' ),
			'leaseUrl'    => rest_url( 'wp-agent/live-editor/lease' ),
			'elementorExecuteUrl' => rest_url( 'wp-agent/live-editor/elementor/execute' ),
			'providerFinalizeExecuteUrl' => rest_url( 'wp-agent/live-editor/provider-finalize/execute' ),
			'resultUrl'   => rest_url( 'wp-agent/live-editor/result' ),
			'heartbeatUrl' => rest_url( 'wp-agent/live-editor/heartbeat' ),
			'closeUrl'    => rest_url( 'wp-agent/live-editor/session/close' ),
			'nonce'       => wp_create_nonce( 'wp_rest' ),
			'adminUrl'    => admin_url(),
			'homeUrl'     => home_url( '/' ),
			'i18n'        => array(
				'active'       => __( 'Live-Editor aktiv. Der gewählte Agent kann jetzt Befehle einreihen.', 'wp-agent-companion' ),
				'closed'       => __( 'Live-Editor beendet.', 'wp-agent-companion' ),
				'failed'       => __( 'Der Live-Editor konnte die Anfrage nicht verarbeiten.', 'wp-agent-companion' ),
				'frameError'   => __( 'Die geöffnete Seite ist nicht als WordPress-Editor verfügbar.', 'wp-agent-companion' ),
				'waiting'      => __( 'Wartet auf deine Freigabe', 'wp-agent-companion' ),
				'running'      => __( 'Wird im sichtbaren Editor ausgeführt …', 'wp-agent-companion' ),
				'approved'     => __( 'Ausgeführt. Der Agent kann das verifizierte Ergebnis jetzt lesen.', 'wp-agent-companion' ),
				'denied'       => __( 'Abgelehnt. Es wurde nichts ausgeführt.', 'wp-agent-companion' ),
				'approve'      => __( 'Einmal ausführen', 'wp-agent-companion' ),
				'deny'         => __( 'Ablehnen', 'wp-agent-companion' ),
				'details'      => __( 'Befehlsdetails', 'wp-agent-companion' ),
				'sessionLabel' => __( 'Sitzung', 'wp-agent-companion' ),
				'postLabel'    => __( 'Beitrag', 'wp-agent-companion' ),
				'saved'        => __( 'gespeichert', 'wp-agent-companion' ),
				'unsaved'      => __( 'ungespeichert', 'wp-agent-companion' ),
				'unsavedConfirm' => __( 'Im Live-Editor gibt es ungespeicherte Änderungen. Sitzung wirklich beenden und diese Änderungen verwerfen?', 'wp-agent-companion' ),
				'elementorDiscardConfirm' => __( 'Elementor wird vor der serverseitigen Änderung neu geladen. Lokale, noch nicht gespeicherte Elementor-Änderungen werden verworfen. Fortfahren?', 'wp-agent-companion' ),
				'commandTitles' => array(
					'open-post'           => __( 'Beitrag im Editor öffnen', 'wp-agent-companion' ),
					'create-block'        => __( 'Block erstellen', 'wp-agent-companion' ),
					'update-block'        => __( 'Blockattribute ändern', 'wp-agent-companion' ),
					'delete-block'        => __( 'Block entfernen', 'wp-agent-companion' ),
					'move-block'          => __( 'Block verschieben', 'wp-agent-companion' ),
					'replace-inner-blocks' => __( 'Innere Blöcke ersetzen', 'wp-agent-companion' ),
					'undo'                => __( 'Letzte Editoränderung rückgängig machen', 'wp-agent-companion' ),
					'redo'                => __( 'Editoränderung wiederholen', 'wp-agent-companion' ),
					'save-post'           => __( 'Sichtbaren Editorzustand speichern', 'wp-agent-companion' ),
					'open-elementor-document' => __( 'Elementor-Dokument öffnen', 'wp-agent-companion' ),
					'elementor-mutate' => __( 'Elementor-Dokument ändern', 'wp-agent-companion' ),
					'finalize-provider-attributes' => __( 'Blockattribute ändern', 'wp-agent-companion' ),
				),
			),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'wpagent_companion_live_editor_assets' );

function wpagent_companion_live_editor_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$users = wpagent_companion_connection_users( false );
	?>
	<div class="wrap wpagently-admin wpagently-live-editor-page">
		<h1><?php esc_html_e( 'Live-Editor', 'wp-agent-companion' ); ?></h1>
		<p class="description"><?php esc_html_e( 'Öffne einen echten WordPress-Editor und sieh jede Agent-Aktion, bevor du sie einzeln freigibst. Änderungen bleiben ungespeichert, bis du auch den Speichervorgang bestätigst.', 'wp-agent-companion' ); ?></p>
		<div class="notice notice-info inline"><p><?php esc_html_e( 'Der Live-Editor nutzt deine bestehende wpagently-MCP-Verbindung. Es ist kein zweiter lokaler Server und keine zusätzliche Agent-Konfiguration nötig.', 'wp-agent-companion' ); ?></p></div>

		<div class="wpagently-live-editor-controls">
			<label for="wpagently-live-editor-user"><?php esc_html_e( 'Gebundener Agent-Nutzer', 'wp-agent-companion' ); ?></label>
			<select id="wpagently-live-editor-user" <?php disabled( empty( $users ) ); ?>>
				<?php foreach ( $users as $user ) : ?>
					<option value="<?php echo esc_attr( (string) $user['id'] ); ?>"><?php echo esc_html( $user['name'] . ' (' . $user['login'] . ')' ); ?></option>
				<?php endforeach; ?>
			</select>
			<button id="wpagently-live-editor-start" class="button button-primary" type="button" <?php disabled( empty( $users ) ); ?>><?php esc_html_e( 'Arbeitsbereich starten', 'wp-agent-companion' ); ?></button>
			<button id="wpagently-live-editor-stop" class="button" type="button" disabled><?php esc_html_e( 'Sitzung beenden', 'wp-agent-companion' ); ?></button>
			<span id="wpagently-live-editor-status" role="status" aria-live="polite"></span>
		</div>
		<?php if ( empty( $users ) ) : ?>
			<div class="notice notice-warning inline"><p><?php esc_html_e( 'Lege unter wpagently > Agent verbinden zuerst einen sicheren Redakteur an.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>

		<div class="wpagently-live-editor-workspace" hidden>
			<aside class="wpagently-live-editor-actions" aria-label="<?php esc_attr_e( 'Agent-Aktionen', 'wp-agent-companion' ); ?>">
				<h2><?php esc_html_e( 'Agent-Aktionen', 'wp-agent-companion' ); ?></h2>
				<p class="description"><?php esc_html_e( 'Lesende Befehle laufen automatisch. Navigation, Blockänderungen, Rückgängig und Speichern benötigen deine einzelne Freigabe.', 'wp-agent-companion' ); ?></p>
				<p id="wpagently-live-editor-session" class="wpagently-live-editor-session"></p>
				<div id="wpagently-live-editor-action-list" aria-live="polite"></div>
			</aside>
			<section class="wpagently-live-editor-frame-panel" aria-label="<?php esc_attr_e( 'Geöffneter WordPress-Editor', 'wp-agent-companion' ); ?>">
				<div class="wpagently-live-editor-frame-status" id="wpagently-live-editor-frame-status"></div>
				<iframe id="wpagently-live-editor-frame" title="<?php esc_attr_e( 'Geöffneter WordPress-Editor', 'wp-agent-companion' ); ?>" src="about:blank"></iframe>
			</section>
		</div>
	</div>
	<?php
}

/** @return array<string,mixed> */
function wpagent_companion_live_editor_rest_params( WP_REST_Request $request ): array {
	$params = $request->get_json_params();
	return is_array( $params ) ? $params : array();
}

function wpagent_companion_live_editor_rest_create( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_create_session( absint( $params['executor_id'] ?? 0 ) );
}

function wpagent_companion_live_editor_rest_poll( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_claim_next( is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '' );
}

function wpagent_companion_live_editor_rest_lease( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_lease_command(
		is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '',
		is_string( $params['command_id'] ?? null ) ? $params['command_id'] : '',
		is_array( $params['page'] ?? null ) ? $params['page'] : array(),
		is_array( $params['active_content'] ?? null ) ? $params['active_content'] : array()
	);
}

function wpagent_companion_live_editor_rest_elementor_execute( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_execute_elementor_command(
		is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '',
		is_string( $params['command_id'] ?? null ) ? $params['command_id'] : ''
	);
}

function wpagent_companion_live_editor_rest_provider_finalize_execute( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_execute_provider_finalize_command(
		is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '',
		is_string( $params['command_id'] ?? null ) ? $params['command_id'] : '',
		$params['capture'] ?? null
	);
}

function wpagent_companion_live_editor_rest_result( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_complete_command(
		is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '',
		is_string( $params['command_id'] ?? null ) ? $params['command_id'] : '',
		is_string( $params['status'] ?? null ) ? $params['status'] : '',
		is_array( $params['result'] ?? null ) ? $params['result'] : array(),
		is_string( $params['error'] ?? null ) ? $params['error'] : '',
		is_string( $params['execution_lease'] ?? null ) ? $params['execution_lease'] : ''
	);
}

function wpagent_companion_live_editor_rest_heartbeat( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_heartbeat(
		is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '',
		is_array( $params['page'] ?? null ) ? $params['page'] : array()
	);
}

function wpagent_companion_live_editor_rest_close( WP_REST_Request $request ) {
	$params = wpagent_companion_live_editor_rest_params( $request );
	return wpagent_companion_live_editor_close_session( is_string( $params['session_id'] ?? null ) ? $params['session_id'] : '' );
}

function wpagent_companion_live_editor_register_routes(): void {
	$permission = static fn(): bool => current_user_can( 'manage_options' );
	register_rest_route( 'wp-agent/live-editor', '/session', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_create', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/poll', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_poll', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/lease', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_lease', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/elementor/execute', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_elementor_execute', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/provider-finalize/execute', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_provider_finalize_execute', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/result', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_result', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/heartbeat', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_heartbeat', 'permission_callback' => $permission ) );
	register_rest_route( 'wp-agent/live-editor', '/session/close', array( 'methods' => 'POST', 'callback' => 'wpagent_companion_live_editor_rest_close', 'permission_callback' => $permission ) );
}
add_action( 'rest_api_init', 'wpagent_companion_live_editor_register_routes' );
