<?php
/** Bedienoberfläche für Site Context und Designprofil. */

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

function wpagent_companion_agent_state_menu(): void {
	add_submenu_page(
		'wpagently',
		__( 'Agent-Wissen', 'wp-agent-companion' ),
		__( 'Agent-Wissen', 'wp-agent-companion' ),
		'manage_options',
		'wpagently-context',
		'wpagent_companion_agent_state_page'
	);
}
add_action( 'admin_menu', 'wpagent_companion_agent_state_menu', 21 );

/** @return array<string,string>|WP_Error */
function wpagent_companion_decode_token_map( $json, string $field ) {
	if ( ! is_string( $json ) && ! is_numeric( $json ) ) {
		/* translators: %s: admin form field name containing invalid JSON. */
		return new WP_Error( 'wpagent_design_bad_json', sprintf( __( '%s enthält kein gültiges JSON-Objekt.', 'wp-agent-companion' ), $field ) );
	}
	$json = (string) $json;
	if ( '' === trim( $json ) ) {
		return array();
	}
	if ( strlen( $json ) > 20000 ) {
		/* translators: %s: admin form field name containing invalid JSON. */
		return new WP_Error( 'wpagent_design_bad_json', sprintf( __( '%s enthält kein gültiges JSON-Objekt.', 'wp-agent-companion' ), $field ) );
	}
	$object  = json_decode( $json );
	$decoded = json_decode( $json, true );
	if ( JSON_ERROR_NONE !== json_last_error() || ! $object instanceof stdClass || ! is_array( $decoded ) ) {
		/* translators: %s: admin form field name containing invalid JSON. */
		return new WP_Error( 'wpagent_design_bad_json', sprintf( __( '%s enthält kein gültiges JSON-Objekt.', 'wp-agent-companion' ), $field ) );
	}
	return $decoded;
}

/**
 * Validates the complete combined admin payload before writing either option,
 * then persists Site Context and Design Profile as one compensated operation.
 *
 * @return array<string,mixed>|WP_Error
 */
function wpagent_companion_save_agent_state( $context_input, $design_input ) {
	$context = wpagent_validate_site_context( $context_input );
	if ( is_wp_error( $context ) ) {
		return $context;
	}
	$design = wpagent_validate_design_profile( $design_input );
	if ( is_wp_error( $design ) ) {
		return $design;
	}
	$persisted = wpagent_state_persist_options(
		array(
			WPAGENT_COMPANION_OPT_SITE_CONTEXT   => $context,
			WPAGENT_COMPANION_OPT_DESIGN_PROFILE => $design,
		),
		'wpagent_agent_state_persist_failed',
		__( 'Site Context und Designprofil konnten nicht gemeinsam gespeichert werden.', 'wp-agent-companion' )
	);
	if ( is_wp_error( $persisted ) ) {
		return $persisted;
	}
	return array(
		'context'  => $context,
		'profile'  => wpagent_design_profile_for_output( $design ),
		'verified' => true,
	);
}

function wpagent_companion_agent_state_save(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_agent_state_save' );
	$fields  = array( 'site_name', 'audience', 'voice', 'goals', 'constraints', 'notes' );
	$context = array();
	foreach ( $fields as $field ) {
		$context[ $field ] = isset( $_POST[ $field ] ) ? wp_unslash( $_POST[ $field ] ) : '';
	}
	$colors  = wpagent_companion_decode_token_map( isset( $_POST['colors'] ) ? wp_unslash( $_POST['colors'] ) : '', 'colors' );
	$spacing = wpagent_companion_decode_token_map( isset( $_POST['spacing'] ) ? wp_unslash( $_POST['spacing'] ) : '', 'spacing' );
	$radius  = wpagent_companion_decode_token_map( isset( $_POST['radius'] ) ? wp_unslash( $_POST['radius'] ) : '', 'radius' );
	foreach ( array( $colors, $spacing, $radius ) as $map ) {
		if ( is_wp_error( $map ) ) {
			wp_die( esc_html( $map->get_error_message() ), esc_html__( 'Designprofil ungültig', 'wp-agent-companion' ), array( 'response' => 400 ) );
		}
	}
	$raw_fonts = isset( $_POST['font_families'] ) ? wp_unslash( $_POST['font_families'] ) : '';
	$fonts     = null;
	if ( ( is_string( $raw_fonts ) || is_numeric( $raw_fonts ) ) && strlen( (string) $raw_fonts ) <= 2000 ) {
		$font_lines = preg_split( '/\r\n|\r|\n/', (string) $raw_fonts );
		$fonts      = array_values(
			array_filter(
				array_map( 'trim', false === $font_lines ? array() : $font_lines ),
				static fn( string $font ): bool => '' !== $font
			)
		);
	}
	$result = wpagent_companion_save_agent_state(
		$context,
		array(
			'colors'        => $colors,
			'font_families' => $fonts,
			'base_size'     => isset( $_POST['base_size'] ) ? wp_unslash( $_POST['base_size'] ) : '',
			'spacing'       => $spacing,
			'radius'        => $radius,
			'notes'         => isset( $_POST['design_notes'] ) ? wp_unslash( $_POST['design_notes'] ) : '',
		)
	);
	if ( is_wp_error( $result ) ) {
		$data   = $result->get_error_data();
		$status = is_array( $data ) ? absint( $data['status'] ?? 400 ) : 400;
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Agent-State konnte nicht gespeichert werden.', 'wp-agent-companion' ), array( 'response' => $status ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'updated' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_save_agent_state', 'wpagent_companion_agent_state_save' );

function wpagent_companion_skill_save(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_skill_save' );
	$result = wpagent_exec_upsert_skill(
		array(
			'id'             => isset( $_POST['skill_id'] ) ? wp_unslash( $_POST['skill_id'] ) : '',
			'title'          => isset( $_POST['skill_title'] ) ? wp_unslash( $_POST['skill_title'] ) : '',
			'description'    => isset( $_POST['skill_description'] ) ? wp_unslash( $_POST['skill_description'] ) : '',
			'instructions'   => isset( $_POST['skill_instructions'] ) ? wp_unslash( $_POST['skill_instructions'] ) : '',
			'enable_agentic' => isset( $_POST['skill_enable_agentic'] ),
			'enable_prompt'  => isset( $_POST['skill_enable_prompt'] ),
		)
	);
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Skill ungültig', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'skill_saved' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_save_skill', 'wpagent_companion_skill_save' );

function wpagent_companion_skill_delete(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_skill_delete' );
	$id     = isset( $_POST['skill_id'] ) ? wp_unslash( $_POST['skill_id'] ) : '';
	$result = wpagent_exec_delete_skill( array( 'id' => $id ) );
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Skill konnte nicht gelöscht werden.', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'skill_deleted' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_delete_skill', 'wpagent_companion_skill_delete' );

function wpagent_companion_design_capture(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_design_capture' );
	$result = wpagent_companion_capture_theme_design_profile();
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Designprofil konnte nicht übernommen werden.', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'design_captured' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_capture_design', 'wpagent_companion_design_capture' );

/** @return array{source:string}|array{profile:array<string,mixed>} */
function wpagent_companion_design_direction_profile_payload( ?array $existing, string $source, bool $use_current_profile ): array {
	if ( '' !== trim( $source ) ) {
		return array( 'source' => $source );
	}
	if ( null !== $existing && ! $use_current_profile ) {
		return array( 'profile' => $existing['profile'] );
	}
	return array( 'profile' => wpagent_normalized_design_profile() );
}

function wpagent_companion_design_direction_save(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_design_direction_save' );
	$lines = static function ( string $name ): array {
		$value = isset( $_POST[ $name ] ) ? (string) wp_unslash( $_POST[ $name ] ) : '';
		return array_values( array_filter( array_map( 'trim', preg_split( '/\r\n|\r|\n/', $value ) ?: array() ) ) );
	};
	$id = isset( $_POST['direction_id'] ) ? sanitize_key( wp_unslash( $_POST['direction_id'] ) ) : '';
	$existing = wpagent_normalized_design_directions()[ $id ] ?? null;
	$source = isset( $_POST['direction_source'] ) ? (string) wp_unslash( $_POST['direction_source'] ) : '';
	$profile_payload = wpagent_companion_design_direction_profile_payload( $existing, $source, isset( $_POST['direction_use_current_profile'] ) );
	$result = wpagent_exec_upsert_design_direction(
		array_merge(
			array(
			'id' => $id,
			'title' => isset( $_POST['direction_title'] ) ? wp_unslash( $_POST['direction_title'] ) : '',
			'summary' => isset( $_POST['direction_summary'] ) ? wp_unslash( $_POST['direction_summary'] ) : '',
			'voice' => isset( $_POST['direction_voice'] ) ? wp_unslash( $_POST['direction_voice'] ) : '',
			'rules' => $lines( 'direction_rules' ),
			'avoid' => $lines( 'direction_avoid' ),
			'expected_version' => $existing ? $existing['version'] : 0,
			),
			$profile_payload
		)
	);
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Designrichtung ungültig', 'wp-agent-companion' ), array( 'response' => 400 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'direction_saved' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_save_design_direction', 'wpagent_companion_design_direction_save' );

function wpagent_companion_design_direction_activate(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_design_direction_activate' );
	$result = wpagent_exec_activate_design_direction(
		array(
			'id' => isset( $_POST['direction_id'] ) ? sanitize_key( wp_unslash( $_POST['direction_id'] ) ) : '',
			'expected_version' => isset( $_POST['direction_version'] ) ? absint( $_POST['direction_version'] ) : 0,
			'approve_warnings' => isset( $_POST['approve_warnings'] ),
		)
	);
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Designrichtung konnte nicht aktiviert werden.', 'wp-agent-companion' ), array( 'response' => 409 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'direction_activated' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_activate_design_direction', 'wpagent_companion_design_direction_activate' );

function wpagent_companion_design_direction_delete(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Keine Berechtigung.', 'wp-agent-companion' ) );
	}
	check_admin_referer( 'wpagent_companion_design_direction_delete' );
	$result = wpagent_exec_delete_design_direction(
		array(
			'id' => isset( $_POST['direction_id'] ) ? sanitize_key( wp_unslash( $_POST['direction_id'] ) ) : '',
			'expected_version' => isset( $_POST['direction_version'] ) ? absint( $_POST['direction_version'] ) : 0,
		)
	);
	if ( is_wp_error( $result ) ) {
		wp_die( esc_html( $result->get_error_message() ), esc_html__( 'Designrichtung konnte nicht gelöscht werden.', 'wp-agent-companion' ), array( 'response' => 409 ) );
	}
	wp_safe_redirect( add_query_arg( array( 'page' => 'wpagently-context', 'direction_deleted' => '1' ), admin_url( 'admin.php' ) ) );
	exit;
}
add_action( 'admin_post_wpagently_delete_design_direction', 'wpagent_companion_design_direction_delete' );

/** @param array<string,mixed> $skill */
function wpagent_companion_render_skill_form( array $skill ): void {
	?>
	<form class="wpagently-card wpagently-card--narrow" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="wpagently_save_skill">
		<?php wp_nonce_field( 'wpagent_companion_skill_save' ); ?>
		<table class="form-table"><tbody>
		<tr><th><label><?php esc_html_e( 'ID', 'wp-agent-companion' ); ?></label></th><td><input name="skill_id" required pattern="[a-z0-9][a-z0-9_-]{0,63}" maxlength="64" value="<?php echo esc_attr( $skill['id'] ?? '' ); ?>" <?php wp_readonly( ! empty( $skill['id'] ) ); ?>></td></tr>
		<tr><th><label><?php esc_html_e( 'Titel', 'wp-agent-companion' ); ?></label></th><td><input class="regular-text" name="skill_title" required maxlength="150" value="<?php echo esc_attr( $skill['title'] ?? '' ); ?>"></td></tr>
		<tr><th><label><?php esc_html_e( 'Kurzbeschreibung', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" name="skill_description" rows="2" maxlength="1000"><?php echo esc_textarea( $skill['description'] ?? '' ); ?></textarea></td></tr>
		<tr><th><label><?php esc_html_e( 'Anweisungen', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" name="skill_instructions" rows="8" required maxlength="20000"><?php echo esc_textarea( $skill['instructions'] ?? '' ); ?></textarea><p class="description"><?php esc_html_e( 'Gespeicherter Text hat niemals Vorrang vor System-, Sicherheits- oder aktuellen Nutzeranweisungen.', 'wp-agent-companion' ); ?></p></td></tr>
		<tr><th><?php esc_html_e( 'Verwendung', 'wp-agent-companion' ); ?></th><td><label><input type="checkbox" name="skill_enable_agentic" value="1" <?php checked( $skill['enable_agentic'] ?? true ); ?>> <?php esc_html_e( 'Bei passenden Agent-Aufgaben anbieten', 'wp-agent-companion' ); ?></label><br><label><input type="checkbox" name="skill_enable_prompt" value="1" <?php checked( $skill['enable_prompt'] ?? true ); ?>> <?php esc_html_e( 'Bei passenden direkten Prompts anbieten', 'wp-agent-companion' ); ?></label></td></tr>
		</tbody></table>
		<?php submit_button( empty( $skill['id'] ) ? __( 'Skill anlegen', 'wp-agent-companion' ) : __( 'Skill speichern', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?>
	</form>
	<?php
}

function wpagent_companion_agent_state_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$context = wpagent_state_array_option( WPAGENT_COMPANION_OPT_SITE_CONTEXT );
	$design  = wpagent_state_array_option( WPAGENT_COMPANION_OPT_DESIGN_PROFILE );
	$skills  = wpagent_exec_list_skills();
	$memory  = wpagent_exec_list_memory( array( 'limit' => 10 ) );
	$memory_total = is_wp_error( $memory ) ? 0 : $memory['total'];
	$directions = wpagent_normalized_design_directions();
	?>
	<div class="wrap wpagently-admin">
		<div class="wpagently-admin__head">
			<h1><?php esc_html_e( 'Agent-Wissen', 'wp-agent-companion' ); ?></h1>
			<p><?php esc_html_e( 'Diese Angaben stehen allen verbundenen Agenten über klar begrenzte Abilities zur Verfügung.', 'wp-agent-companion' ); ?></p>
		</div>
		<?php if ( isset( $_GET['updated'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Agent-Wissen gespeichert.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( isset( $_GET['skill_saved'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Skill gespeichert.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( isset( $_GET['skill_deleted'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Skill gelöscht.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( isset( $_GET['design_captured'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Sichere Design-Tokens des aktiven Themes wurden übernommen.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<?php if ( isset( $_GET['direction_saved'] ) || isset( $_GET['direction_activated'] ) || isset( $_GET['direction_deleted'] ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Designrichtungen wurden aktualisiert.', 'wp-agent-companion' ); ?></p></div>
		<?php endif; ?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="wpagently_capture_design"><?php wp_nonce_field( 'wpagent_companion_design_capture' ); ?><?php submit_button( __( 'Design-Tokens aus aktivem Theme übernehmen', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?></form>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="wpagently_save_agent_state">
			<?php wp_nonce_field( 'wpagent_companion_agent_state_save' ); ?>
			<h2><?php esc_html_e( 'Website-Kontext', 'wp-agent-companion' ); ?></h2>
			<p><?php esc_html_e( 'Trage nur ein, was dein Agent bei jeder Aufgabe über diese Website wissen soll. Alle Felder sind optional.', 'wp-agent-companion' ); ?></p>
			<div class="wpagently-card wpagently-card--narrow">
			<table class="form-table"><tbody>
			<?php foreach ( array(
				'site_name'   => array( __( 'Website-Name', 'wp-agent-companion' ), __( 'Der öffentliche Name der Website.', 'wp-agent-companion' ) ),
				'audience'    => array( __( 'Zielgruppe', 'wp-agent-companion' ), __( 'Für wen du schreibst und welche Vorkenntnisse diese Menschen haben.', 'wp-agent-companion' ) ),
				'voice'       => array( __( 'Tonalität', 'wp-agent-companion' ), __( 'Wie Texte klingen sollen, zum Beispiel direkt, sachlich oder persönlich.', 'wp-agent-companion' ) ),
				'goals'       => array( __( 'Ziele', 'wp-agent-companion' ), __( 'Was die Website und ihre Inhalte erreichen sollen.', 'wp-agent-companion' ) ),
				'constraints' => array( __( 'Einschränkungen', 'wp-agent-companion' ), __( 'Was der Agent vermeiden oder immer beachten muss.', 'wp-agent-companion' ) ),
				'notes'       => array( __( 'Weitere Hinweise', 'wp-agent-companion' ), __( 'Zusätzliche Fakten, die in keine andere Zeile passen.', 'wp-agent-companion' ) ),
			) as $field => $field_definition ) : ?>
				<tr><th><label for="<?php echo esc_attr( $field ); ?>"><?php echo esc_html( $field_definition[0] ); ?></label></th><td><?php if ( 'site_name' === $field ) : ?><input class="regular-text" id="<?php echo esc_attr( $field ); ?>" name="<?php echo esc_attr( $field ); ?>" value="<?php echo esc_attr( $context[ $field ] ?? '' ); ?>"><?php else : ?><textarea class="large-text" rows="3" id="<?php echo esc_attr( $field ); ?>" name="<?php echo esc_attr( $field ); ?>"><?php echo esc_textarea( $context[ $field ] ?? '' ); ?></textarea><?php endif; ?><p class="description"><?php echo esc_html( $field_definition[1] ); ?></p></td></tr>
			<?php endforeach; ?>
			</tbody></table>
			</div>

			<details style="margin:20px 0">
			<summary style="cursor:pointer"><strong><?php esc_html_e( 'Optionales Designprofil', 'wp-agent-companion' ); ?></strong> <?php esc_html_e( 'Nur öffnen, wenn der Agent feste Design-Tokens kennen soll.', 'wp-agent-companion' ); ?></summary>
			<p><?php esc_html_e( 'Farben, Abstände und Rundungen sind JSON-Objekte. Farben akzeptieren Hex-Werte. Abstände und Rundungen akzeptieren sichere CSS-Längen.', 'wp-agent-companion' ); ?></p>
			<table class="form-table"><tbody>
			<tr><th><label for="colors"><?php esc_html_e( 'Farben (JSON)', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" rows="4" id="colors" name="colors"><?php echo esc_textarea( wp_json_encode( $design['colors'] ?? array(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></textarea></td></tr>
			<tr><th><label for="font_families"><?php esc_html_e( 'Schriftfamilien', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" rows="3" id="font_families" name="font_families"><?php echo esc_textarea( implode( "\n", $design['font_families'] ?? array() ) ); ?></textarea><p class="description"><?php esc_html_e( 'Eine Schriftfamilie pro Zeile.', 'wp-agent-companion' ); ?></p></td></tr>
			<tr><th><label for="base_size"><?php esc_html_e( 'Basis-Schriftgröße', 'wp-agent-companion' ); ?></label></th><td><input id="base_size" name="base_size" value="<?php echo esc_attr( $design['base_size'] ?? '' ); ?>" placeholder="16px"></td></tr>
			<tr><th><label for="spacing"><?php esc_html_e( 'Abstände (JSON)', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" rows="4" id="spacing" name="spacing"><?php echo esc_textarea( wp_json_encode( $design['spacing'] ?? array(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></textarea></td></tr>
			<tr><th><label for="radius"><?php esc_html_e( 'Rundungen (JSON)', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" rows="4" id="radius" name="radius"><?php echo esc_textarea( wp_json_encode( $design['radius'] ?? array(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) ); ?></textarea></td></tr>
			<tr><th><label for="design_notes"><?php esc_html_e( 'Designhinweise', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" rows="3" id="design_notes" name="design_notes"><?php echo esc_textarea( $design['notes'] ?? '' ); ?></textarea></td></tr>
			</tbody></table>
			</details>
			<?php submit_button( __( 'Agent-Wissen speichern', 'wp-agent-companion' ) ); ?>
		</form>

		<h2><?php esc_html_e( 'Designrichtungen', 'wp-agent-companion' ); ?></h2>
		<p><?php esc_html_e( 'Speichere das aktuelle validierte Designprofil als versionierte Richtung. Eine Richtung wird erst nach ausdrücklicher Aktivierung zum aktiven Profil.', 'wp-agent-companion' ); ?></p>
		<form class="wpagently-card wpagently-card--narrow" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<input type="hidden" name="action" value="wpagently_save_design_direction"><?php wp_nonce_field( 'wpagent_companion_design_direction_save' ); ?>
			<table class="form-table"><tbody>
			<tr><th><label for="direction_id"><?php esc_html_e( 'ID', 'wp-agent-companion' ); ?></label></th><td><input id="direction_id" name="direction_id" required pattern="[a-z0-9][a-z0-9_-]{0,63}" maxlength="64"></td></tr>
			<tr><th><label for="direction_title"><?php esc_html_e( 'Titel', 'wp-agent-companion' ); ?></label></th><td><input class="regular-text" id="direction_title" name="direction_title" required maxlength="150"></td></tr>
			<tr><th><label for="direction_summary"><?php esc_html_e( 'Kurzbeschreibung', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" id="direction_summary" name="direction_summary" rows="2" maxlength="1000"></textarea></td></tr>
			<tr><th><label for="direction_voice"><?php esc_html_e( 'Tonalität', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" id="direction_voice" name="direction_voice" rows="2" maxlength="2000"></textarea></td></tr>
			<tr><th><label for="direction_rules"><?php esc_html_e( 'Gestaltungsregeln', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" id="direction_rules" name="direction_rules" rows="4"></textarea><p class="description"><?php esc_html_e( 'Eine Regel pro Zeile.', 'wp-agent-companion' ); ?></p></td></tr>
			<tr><th><label for="direction_avoid"><?php esc_html_e( 'Zu vermeiden', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" id="direction_avoid" name="direction_avoid" rows="4"></textarea><p class="description"><?php esc_html_e( 'Ein Muster pro Zeile.', 'wp-agent-companion' ); ?></p></td></tr>
			<tr><th><label for="direction_source"><?php esc_html_e( 'Design importieren', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" id="direction_source" name="direction_source" rows="6" maxlength="30000"></textarea><p class="description"><?php esc_html_e( 'Optional. Akzeptiert ein JSON-Designprofil oder sichere CSS-Variablen beziehungsweise beschriftete Zeilen mit je einer Überschriften- und Fließtextschrift. Ohne Import wird das aktuelle Designprofil verwendet.', 'wp-agent-companion' ); ?></p></td></tr>
			</tbody></table><?php submit_button( __( 'Designrichtung speichern', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?>
		</form>
		<?php foreach ( $directions as $direction ) : $output = wpagent_design_direction_for_output( $direction ); ?>
			<div class="wpagently-card wpagently-card--narrow">
				<h3><?php echo esc_html( $direction['title'] ); ?> <code><?php echo esc_html( $direction['id'] ); ?></code><?php if ( $output['active'] ) : ?> <span class="wpagently-badge wpagently-badge--safe"><?php esc_html_e( 'Aktiv', 'wp-agent-companion' ); ?></span><?php endif; ?></h3>
				<p><?php echo esc_html( $direction['summary'] ); ?></p>
				<p><?php foreach ( $direction['profile']['colors'] as $slug => $color ) : ?><span class="wpagently-swatch" title="<?php echo esc_attr( $slug . ': ' . $color ); ?>" style="background:<?php echo esc_attr( $color ); ?>"></span><?php endforeach; ?></p>
				<?php if ( $output['preview']['warnings'] ) : ?><ul class="ul-disc"><?php foreach ( $output['preview']['warnings'] as $warning ) : ?><li><?php echo esc_html( $warning ); ?></li><?php endforeach; ?></ul><?php endif; ?>
				<?php if ( ! $output['active'] ) : ?>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline-block;margin-right:8px"><input type="hidden" name="action" value="wpagently_activate_design_direction"><input type="hidden" name="direction_id" value="<?php echo esc_attr( $direction['id'] ); ?>"><input type="hidden" name="direction_version" value="<?php echo esc_attr( (string) $direction['version'] ); ?>"><?php wp_nonce_field( 'wpagent_companion_design_direction_activate' ); ?><?php if ( $output['preview']['warnings'] ) : ?><label><input type="checkbox" required name="approve_warnings" value="1"> <?php esc_html_e( 'Warnungen geprüft', 'wp-agent-companion' ); ?></label> <?php endif; ?><?php submit_button( __( 'Aktivieren', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?></form>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="display:inline-block"><input type="hidden" name="action" value="wpagently_delete_design_direction"><input type="hidden" name="direction_id" value="<?php echo esc_attr( $direction['id'] ); ?>"><input type="hidden" name="direction_version" value="<?php echo esc_attr( (string) $direction['version'] ); ?>"><?php wp_nonce_field( 'wpagent_companion_design_direction_delete' ); ?><?php submit_button( __( 'Löschen', 'wp-agent-companion' ), 'delete', 'submit', false ); ?></form>
				<?php endif; ?>
				<details style="margin-top:12px"><summary style="cursor:pointer"><strong><?php esc_html_e( 'Bearbeiten oder neu importieren', 'wp-agent-companion' ); ?></strong></summary>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<input type="hidden" name="action" value="wpagently_save_design_direction"><?php wp_nonce_field( 'wpagent_companion_design_direction_save' ); ?>
						<input type="hidden" name="direction_id" value="<?php echo esc_attr( $direction['id'] ); ?>">
						<table class="form-table"><tbody>
						<tr><th><label><?php esc_html_e( 'Titel', 'wp-agent-companion' ); ?></label></th><td><input class="regular-text" name="direction_title" required maxlength="150" value="<?php echo esc_attr( $direction['title'] ); ?>"></td></tr>
						<tr><th><label><?php esc_html_e( 'Kurzbeschreibung', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" name="direction_summary" rows="2" maxlength="1000"><?php echo esc_textarea( $direction['summary'] ); ?></textarea></td></tr>
						<tr><th><label><?php esc_html_e( 'Tonalität', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" name="direction_voice" rows="2" maxlength="2000"><?php echo esc_textarea( $direction['voice'] ); ?></textarea></td></tr>
						<tr><th><label><?php esc_html_e( 'Gestaltungsregeln', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" name="direction_rules" rows="4"><?php echo esc_textarea( implode( "\n", $direction['rules'] ) ); ?></textarea></td></tr>
						<tr><th><label><?php esc_html_e( 'Zu vermeiden', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text" name="direction_avoid" rows="4"><?php echo esc_textarea( implode( "\n", $direction['avoid'] ) ); ?></textarea></td></tr>
						<tr><th><label><?php esc_html_e( 'Design neu importieren', 'wp-agent-companion' ); ?></label></th><td><textarea class="large-text code" name="direction_source" rows="6" maxlength="30000"></textarea><p class="description"><?php esc_html_e( 'Leer lassen, um das gespeicherte Profil dieser Richtung unverändert zu behalten.', 'wp-agent-companion' ); ?></p><label><input type="checkbox" name="direction_use_current_profile" value="1"> <?php esc_html_e( 'Stattdessen das aktuelle globale Designprofil übernehmen', 'wp-agent-companion' ); ?></label></td></tr>
						</tbody></table>
						<?php submit_button( __( 'Designrichtung speichern', 'wp-agent-companion' ), 'secondary', 'submit', false ); ?>
					</form>
				</details>
			</div>
		<?php endforeach; ?>

		<h2><?php esc_html_e( 'Site-Skills', 'wp-agent-companion' ); ?></h2>
		<?php /* translators: 1: number of saved skills, 2: number of saved memories. */ ?>
		<p><?php echo esc_html( sprintf( __( '%1$d Skills und %2$d Memories sind gespeichert. Skill-Inhalte werden vom Agenten erst bei einer passenden Aufgabe geladen.', 'wp-agent-companion' ), $skills['total'], $memory_total ) ); ?></p>
		<?php wpagent_companion_render_skill_form( array() ); ?>
		<?php foreach ( wpagent_normalized_skills() as $skill ) : ?>
			<details style="max-width:960px;margin:12px 0"><summary style="cursor:pointer"><strong><?php echo esc_html( $skill['title'] ); ?></strong> <code><?php echo esc_html( $skill['id'] ); ?></code></summary>
				<?php wpagent_companion_render_skill_form( $skill ); ?>
				<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="wpagently_delete_skill"><input type="hidden" name="skill_id" value="<?php echo esc_attr( $skill['id'] ); ?>"><?php wp_nonce_field( 'wpagent_companion_skill_delete' ); ?><?php submit_button( __( 'Skill löschen', 'wp-agent-companion' ), 'delete', 'submit', false ); ?></form>
			</details>
		<?php endforeach; ?>
		<?php wpagent_companion_render_memory_admin(); ?>
	</div>
	<?php
}
