<?php
/**
 * Partial — Settings / Agents tab (v3 — Adjustments-only editor).
 *
 * The raw agent prompts are no longer displayed or edited here: they are the
 * canonical IP served by contentosapp-api and cached read-only locally. This
 * tab now exposes only safe, additive customization ("Adjustments"): per-agent
 * niche override, extra instructions and temperature — plus their History.
 *
 * Expected scope (inherited from page-settings.php):
 *   @var array $agent_defs
 * @package Contentosapp_Studio
 * @since   3.3.0
 */

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Included admin settings template; local presentation variables are scoped to this partial.

$_content_lang   = Costudio_Admin::get_default_content_language();
$_prompts_locale = class_exists( 'Costudio_Agent_Seeder' )
	? (string) costudio_get_option( Costudio_Agent_Seeder::LOCALE_OPTION, '' )
	: '';
$_agent_01_prompt        = (string) costudio_get_option( 'costudio_agent_01', '' );
$_prompt_looks_pt        = preg_match( '/\b(Você|Sua missão)\b/u', $_agent_01_prompt ) === 1;
$_prompt_locale_mismatch = in_array( $_content_lang, array( 'en_US', 'es_ES' ), true ) && $_prompt_looks_pt;

// The canonical prompt cache is always seeder-owned now (users can no longer
// edit prompts), so we can freely re-sync whenever the content language drifts
// from the cached prompt locale — no per-agent custom guard needed.
if ( $_content_lang !== ''
	&& ( $_content_lang !== $_prompts_locale || $_prompt_locale_mismatch )
	&& class_exists( 'Costudio_Agent_Seeder' )
) {
	Costudio_Agent_Seeder::force_sync_from_vault( $_content_lang );
}

$_agents_is_byok = ( ( $all_settings['ai_mode'] ?? '' ) === 'byok' );

// Pre-compute per-agent adjustments. "Adjusted" = the agent carries any
// non-default adjustment (niche / extra / temperature).
$_agents_data = array();
foreach ( $agent_defs as $n => $def ) {
	$niche = (string) costudio_get_option( sprintf( 'costudio_agent_%02d_niche', $n ), '' );
	$extra = (string) costudio_get_option( sprintf( 'costudio_agent_%02d_extra', $n ), '' );
	$temp  = (string) costudio_get_option( sprintf( 'costudio_agent_%02d_temperature', $n ), '' );

	$is_adjusted = ( '' !== $niche || '' !== $extra || ( '' !== $temp && (float) $temp !== 0.7 ) );

	$_agents_data[ $n ] = array(
		'is_adjusted' => $is_adjusted,
		'niche'       => $niche,
		'extra'       => $extra,
		'temperature' => $temp,
	);
}
?>
<div id="fos-tab-agents" class="fos-tab-panel">

	<div class="fos-agents-editor" id="fos-agents-editor">

		<!-- ── Sidebar ─────────────────────────────────────────────────────── -->
		<aside class="fos-agents-sidebar" role="list" aria-label="<?php esc_attr_e( 'Pipeline agents', 'contentosapp-studio' ); ?>">
			<?php foreach ( $agent_defs as $n => $def ) :
				$d = $_agents_data[ $n ];
			?>
			<div class="fos-agents-sidebar__item<?php echo esc_attr( 1 === $n ? ' is-active' : '' ); ?>"
				role="listitem"
				data-agent="<?php echo (int) $n; ?>"
				tabindex="0">
				<span class="fos-agents-sidebar__num"><?php echo esc_html( sprintf( '%02d', (int) $n ) ); ?></span>
				<span class="fos-agents-sidebar__icon"><?php echo esc_html( $def['icon'] ); ?></span>
				<div class="fos-agents-sidebar__meta">
					<span class="fos-agents-sidebar__name"><?php echo esc_html( $def['label'] ); ?></span>
					<span class="fos-agents-sidebar__badge <?php echo esc_attr( $d['is_adjusted'] ? 'fos-agents-sidebar__badge--custom' : 'fos-agents-sidebar__badge--default' ); ?>">
						<?php echo esc_html( $d['is_adjusted'] ? __( 'Adjusted', 'contentosapp-studio' ) : __( 'Default', 'contentosapp-studio' ) ); ?>
					</span>
				</div>
				<span class="fos-agents-sidebar__dirty" aria-hidden="true"></span>
			</div>
			<?php endforeach; ?>
			<div class="fos-agents-sidebar__footer">
				<button type="button" id="fos-restore-all-btn" class="fos-agents-sidebar__restore-all">
					↩ <?php esc_html_e( 'Reset all adjustments', 'contentosapp-studio' ); ?>
				</button>
			</div>
		</aside><!-- /.fos-agents-sidebar -->

		<!-- ── Detail Panel ─────────────────────────────────────────────────── -->
		<div class="fos-agents-detail" id="fos-agents-detail">
			<?php foreach ( $agent_defs as $n => $def ) :
				$d        = $_agents_data[ $n ];
				$temp_val = '' !== $d['temperature'] ? (float) $d['temperature'] : 0.7;
			?>
			<div class="fos-agents-detail__agent<?php echo esc_attr( 1 === $n ? ' is-active' : '' ); ?>"
				id="fos-agent-detail-<?php echo (int) $n; ?>"
				data-agent="<?php echo (int) $n; ?>">

				<!-- Agent Header -->
				<div class="fos-agents-detail__header">
					<div class="fos-agents-detail__header-left">
						<span class="fos-agents-detail__icon"><?php echo esc_html( $def['icon'] ); ?></span>
						<div>
							<div class="fos-agents-detail__name">
								<span class="fos-agents-detail__num"><?php echo esc_html( sprintf( '%02d', (int) $n ) ); ?></span>
								<?php echo esc_html( $def['label'] ); ?>
							</div>
							<div class="fos-agents-detail__role"><?php echo esc_html( $def['role'] ); ?></div>
						</div>
					</div>
					<div class="fos-agents-detail__status" id="fos-agent-status-<?php echo (int) $n; ?>"></div>
				</div><!-- /.fos-agents-detail__header -->

				<!-- Tab Nav -->
				<nav class="fos-agents-tabs" role="tablist">
					<button type="button" class="fos-agents-tab-btn is-active"
						data-agent-tab="studio" role="tab"
						aria-selected="true">
						<?php esc_html_e( 'Adjustments', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-agents-tab-btn"
						data-agent-tab="history" role="tab"
						aria-selected="false">
						<?php esc_html_e( 'History', 'contentosapp-studio' ); ?>
					</button>
				</nav><!-- /.fos-agents-tabs -->

				<!-- Tab: Adjustments -->
				<div class="fos-agents-tab-panel is-active" data-agent-panel="studio">
					<div class="fos-agent-studio">

						<?php if ( ! $_agents_is_byok ) : ?>
						<p class="fos-agent-prompt-actions__note">
							ℹ️ <?php esc_html_e( 'These adjustments apply immediately to your own-key (BYOK) generations on every plan. In ContentOS Auto (managed service), they are applied on the Pro and Studio plans.', 'contentosapp-studio' ); ?>
						</p>
						<?php endif; ?>

						<div class="fos-int-field">
							<label for="fos-agent-temp-<?php echo (int) $n; ?>"><?php esc_html_e( 'Temperature', 'contentosapp-studio' ); ?></label>
							<div class="fos-agent-temp-row">
								<input type="range"
									id="fos-agent-temp-<?php echo (int) $n; ?>"
									class="fos-agent-temp-slider"
									data-agent="<?php echo (int) $n; ?>"
									min="0" max="2" step="0.1"
									value="<?php echo esc_attr( $temp_val ); ?>" />
								<span class="fos-agent-temp-value" id="fos-agent-temp-val-<?php echo (int) $n; ?>"><?php echo esc_html( number_format( $temp_val, 1 ) ); ?></span>
							</div>
							<p class="description"><?php esc_html_e( 'Controls randomness. Lower = more focused, higher = more creative. Default: 0.7', 'contentosapp-studio' ); ?></p>
						</div>

						<div class="fos-int-field">
							<label for="fos-agent-niche-<?php echo (int) $n; ?>"><?php esc_html_e( 'Niche Override', 'contentosapp-studio' ); ?></label>
							<input type="text"
								id="fos-agent-niche-<?php echo (int) $n; ?>"
								class="fos-int-input fos-agent-niche-input"
								data-agent="<?php echo (int) $n; ?>"
								value="<?php echo esc_attr( $d['niche'] ); ?>"
								placeholder="<?php esc_attr_e( 'Leave blank to use global niche', 'contentosapp-studio' ); ?>" />
							<p class="description"><?php esc_html_e( 'Overrides [NICHE] for this agent only. Useful for fine-tuning context per pipeline step.', 'contentosapp-studio' ); ?></p>
						</div>

						<div class="fos-int-field">
							<label for="fos-agent-extra-<?php echo (int) $n; ?>"><?php esc_html_e( 'Extra Instructions', 'contentosapp-studio' ); ?></label>
							<?php if ( ! empty( $def['vars'] ) ) : ?>
							<div class="fos-agent-vars">
								<span class="fos-agent-vars__label"><?php esc_html_e( 'Variables:', 'contentosapp-studio' ); ?></span>
								<?php foreach ( $def['vars'] as $var ) : ?>
									<span class="fos-agent-var"
										data-var="[<?php echo esc_attr( $var ); ?>]"
										data-target="extra"
										title="<?php esc_attr_e( 'Click to insert', 'contentosapp-studio' ); ?>">[<?php echo esc_html( $var ); ?>]</span>
								<?php endforeach; ?>
							</div>
							<?php endif; ?>
							<textarea
								id="fos-agent-extra-<?php echo (int) $n; ?>"
								class="fos-agent-card__textarea fos-agent-card__textarea--sm fos-agent-extra-input"
								data-agent="<?php echo (int) $n; ?>"
								rows="5"
								placeholder="<?php esc_attr_e( 'Additional instructions appended after the main prompt. Supports [VARIABLE] placeholders.', 'contentosapp-studio' ); ?>"><?php echo esc_textarea( $d['extra'] ); ?></textarea>
							<p class="description"><?php esc_html_e( 'Appended at the end of the prompt, after all default instructions.', 'contentosapp-studio' ); ?></p>
						</div>

						<div class="fos-agent-studio-actions">
							<button type="button" class="cts-btn cts-btn--primary cts-btn--sm fos-agent-save-btn"
								data-agent="<?php echo (int) $n; ?>">
								<?php esc_html_e( 'Save Agent', 'contentosapp-studio' ); ?>
							</button>
						</div>
					</div><!-- /.fos-agent-studio -->
				</div><!-- [panel:studio] -->

				<!-- Tab: History -->
				<div class="fos-agents-tab-panel" data-agent-panel="history">
					<div class="fos-agent-history" id="fos-agent-history-<?php echo (int) $n; ?>">
						<p class="fos-agent-history__empty"><?php esc_html_e( 'Click to load history.', 'contentosapp-studio' ); ?></p>
					</div>
				</div><!-- [panel:history] -->

			</div><!-- .fos-agents-detail__agent -->
			<?php endforeach; ?>
		</div><!-- /.fos-agents-detail -->

	</div><!-- /.fos-agents-editor -->

</div><!-- #fos-tab-agents -->
