<?php
/**
 * Partial — Settings / AI Provider tab.
 *
 * Expected scope (inherited from page-settings.php):
 *   @var array $all_settings
 *   @var array $masked_settings
 * @package Contentosapp_Studio
 * @since   3.2.0
 */

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

$_ai_has_key    = ! empty($all_settings['ai_api_key']);
$_ai_provider   = $all_settings['ai_provider'] ?? 'gemini';
$_ai_model      = $all_settings['ai_model']    ?? '';

// AI mode: 'contentos' uses ContentOS Auto service quota; 'byok' uses own key.
// Default: 'contentos' when no key is set, 'byok' when a key has been configured.
$_ai_mode_saved = $all_settings['ai_mode'] ?? '';
if ($_ai_mode_saved === '') {
	$_ai_mode = ! $_ai_has_key ? 'contentos' : 'byok';
} else {
	$_ai_mode = $_ai_mode_saved;
}
$_byok_active     = ($_ai_mode === 'byok');
$_service_image_limit = class_exists( 'Costudio_Standalone_License' )
	? Costudio_Standalone_License::get_instance()->get_managed_image_limit_per_article()
	: 0;
$_managed_images_unavailable = (
	! $_byok_active &&
	$_service_image_limit <= 0
);
if (
	! $_byok_active &&
	class_exists( 'Costudio_Standalone_License' ) &&
	! empty( get_option( Costudio_Standalone_License::OPT_KEY, '' ) )
) {
	Costudio_Standalone_License::sync_remote_usage( true );
}
?>
<div id="fos-tab-ai" class="fos-tab-panel is-active">
	<form id="fos-settings-ai-form" class="fos-settings-form" data-managed-images-unavailable="<?php echo esc_attr( $_managed_images_unavailable ? '1' : '0' ); ?>">

		<p class="fos-int-zone-label"><?php esc_html_e('Production mode', 'contentosapp-studio'); ?></p>
		<div class="fos-int-card fos-execution-model-card">
			<div class="fos-int-card__header">
				<div class="fos-int-card__left">
					<span class="fos-int-card__icon fos-execution-model-card__icon">⚙️</span>
					<div>
						<p class="fos-int-card__title"><?php esc_html_e('Execution model', 'contentosapp-studio'); ?></p>
						<p class="fos-int-card__subtitle"><?php esc_html_e('Who provides text, image generation and web search for new productions.', 'contentosapp-studio'); ?></p>
					</div>
				</div>
				<div id="fos-execution-status" class="fos-int-status fos-int-status--ok">
					<span class="fos-int-status__dot"></span>
					<span class="fos-int-status__text"><?php esc_html_e('Configured', 'contentosapp-studio'); ?></span>
				</div>
			</div>
			<div class="fos-int-card__body">
				<input type="hidden" name="ai_mode" id="fos-ai-mode-input" value="<?php echo esc_attr($_ai_mode); ?>">
				<div class="fos-aimode-grid fos-production-mode-grid">
					<div class="fos-aimode-card fos-aimode-card--row fos-execution-option<?php echo esc_attr( ! $_byok_active ? ' fos-img-mode-card--active' : '' ); ?>"
						id="fos-aimode-contentos"
						data-ai-mode="contentos">
						<div class="fos-img-mode-icon fos-img-mode-icon--purple">⚡</div>
						<div>
							<div class="fos-img-mode-title"><?php esc_html_e('ContentOS Auto', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-desc"><?php esc_html_e('Uses ContentOS managed text, search and image services. Consumes ContentOS Auto service quota.', 'contentosapp-studio'); ?></div>
							<div class="fos-execution-option__tags">
								<span><?php esc_html_e('Recommended', 'contentosapp-studio'); ?></span>
								<span><?php esc_html_e('No API key', 'contentosapp-studio'); ?></span>
							</div>
						</div>
						<div class="fos-img-mode-radio"></div>
					</div>

					<div class="fos-aimode-card fos-aimode-card--row fos-execution-option<?php echo esc_attr( $_byok_active ? ' fos-img-mode-card--active' : '' ); ?>"
						id="fos-aimode-byok"
						data-ai-mode="byok">
						<div class="fos-img-mode-icon fos-img-mode-icon--teal">🔑</div>
						<div>
							<div class="fos-img-mode-title"><?php esc_html_e('BYOK - Bring Your Own Key', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-desc"><?php esc_html_e('Uses your own provider keys. Costs are charged by Gemini, OpenAI, Claude or search/image providers.', 'contentosapp-studio'); ?></div>
							<div class="fos-execution-option__tags">
								<span><?php esc_html_e('No quota', 'contentosapp-studio'); ?></span>
								<span><?php esc_html_e('You manage costs', 'contentosapp-studio'); ?></span>
							</div>
						</div>
						<div class="fos-img-mode-radio"></div>
					</div>
				</div>
			</div>
		</div>

		<p class="fos-int-zone-label"><?php esc_html_e('Text generation', 'contentosapp-studio'); ?></p>
		<div class="fos-int-card">

			<div class="fos-int-card__header">
				<div class="fos-int-card__left">
					<span class="fos-int-card__icon">✍️</span>
					<div>
						<p class="fos-int-card__title"><?php esc_html_e('Text Provider', 'contentosapp-studio'); ?></p>
						<p class="fos-int-card__subtitle">
							<?php esc_html_e('Text generation engine used by all Contentosapp Studio agents.', 'contentosapp-studio'); ?>
							· <a href="<?php echo esc_url( admin_url('admin.php?page=costudio-setup') ); ?>" style="color:var(--fos-primary);text-decoration:none;font-weight:500">
								<?php esc_html_e('↺ Setup wizard', 'contentosapp-studio'); ?>
							</a>
						</p>
					</div>
				</div>
				<div id="fos-ai-status" class="fos-int-status <?php echo esc_attr( ( $_byok_active && $_ai_has_key ) ? 'fos-int-status--ok' : ( ! $_byok_active ? 'fos-int-status--ok' : 'fos-int-status--warn' ) ); ?>">
					<span class="fos-int-status__dot"></span>
					<span class="fos-int-status__text" id="fos-ai-status-text">
						<?php 
						$usage_count = Costudio_Standalone_License::get_monthly_count();
						$usage_limit = Costudio_Standalone_License::get_instance()->get_api_production_limit();
						
						if (! $_byok_active) : ?>
							<?php if ($usage_count >= $usage_limit) : ?>
								<span style="color:var(--fos-error)"><?php esc_html_e('Monthly limit reached', 'contentosapp-studio'); ?> (<?php echo (int) $usage_count; ?>/<?php echo (int) $usage_limit; ?>)</span>
							<?php else : ?>
								<?php esc_html_e('Using ContentOS Auto quota', 'contentosapp-studio'); ?> (<?php echo (int) $usage_count; ?>/<?php echo (int) $usage_limit; ?>)
							<?php endif; ?>
							<button type="button" class="fos-sync-quota-inline" id="fos-settings-sync-quota" title="<?php esc_attr_e('Sync quota', 'contentosapp-studio'); ?>">
								<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M23 4v6h-6"></path><path d="M1 20v-6h6"></path><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>
							</button>
						<?php elseif ($_ai_has_key) : ?>
							<?php esc_html_e('API key saved', 'contentosapp-studio'); ?>
						<?php else : ?>
							<?php esc_html_e('API key pending', 'contentosapp-studio'); ?>
						<?php endif; ?>
					</span>
				</div>
			</div><!-- /.fos-int-card__header -->

			<div class="fos-int-card__body">
				<!-- ContentOS mode info (shown when ContentOS mode is active) -->
				<div id="fos-aimode-contentos-info" style="<?php echo esc_attr( $_byok_active ? 'display:none' : '' ); ?>">
					<div class="fos-contentos-auto-banner">
						<div class="fos-int-pro-notice fos-contentos-auto-banner__notice">
							⚡ <?php esc_html_e('ContentOS Auto mode active. All agents use the managed service quota. Switch to BYOK to use OpenAI, Claude or your own Gemini key.', 'contentosapp-studio'); ?>
						</div>
						<div class="fos-contentos-auto-banner__diagnose" style="display:none;">
							<button type="button" id="fos-diagnose-api-btn" class="cts-btn cts-btn--secondary fos-diagnose-api-btn">
								<?php esc_html_e('Diagnose API connectivity', 'contentosapp-studio'); ?>
							</button>
						</div>
					</div>
					<div id="fos-diagnose-api-result" class="fos-diagnose-api-result" style="display:none"></div>
				</div>


				<!-- BYOK fields (hidden when ContentOS mode is active) -->
				<div id="fos-aimode-byok-fields" style="<?php echo esc_attr( ! $_byok_active ? 'display:none' : '' ); ?>">
					<div class="fos-int-grid">
						<div class="fos-int-field">
							<label for="ai_provider"><?php esc_html_e('Provider', 'contentosapp-studio'); ?> <span class="fos-plan-field__required">*</span></label>
							<select name="ai_provider" id="ai_provider" class="cts-select fos-int-select">
								<option value="gemini" <?php selected($_ai_provider, 'gemini'); ?>>Google Gemini</option>
								<option value="openai" <?php selected($_ai_provider, 'openai'); ?>>OpenAI</option>
								<option value="claude" <?php selected($_ai_provider, 'claude'); ?>>Anthropic Claude</option>
							</select>
							<p class="fos-int-hint"><?php esc_html_e('All agents use this provider by default.', 'contentosapp-studio'); ?></p>
						</div>
						<div class="fos-int-field">
							<label for="fos-ai-api-key"><?php esc_html_e('API Key', 'contentosapp-studio'); ?> <span class="fos-plan-field__required">*</span></label>
							<div class="fos-int-key-row">
								<div class="fos-int-apikey-wrap">
									<input type="password" id="fos-ai-api-key" name="ai_api_key" class="cts-input"
										value="<?php echo esc_attr($masked_settings['ai_api_key'] ?? ''); ?>"
										placeholder="<?php esc_attr_e('Paste your API key here', 'contentosapp-studio'); ?>"
										autocomplete="off">
									<button type="button" class="fos-int-toggle-vis"
										data-target="fos-ai-api-key"
										aria-label="<?php esc_attr_e('Toggle API key visibility', 'contentosapp-studio'); ?>">
										<span class="dashicons dashicons-visibility"></span>
									</button>
								</div>
								<button type="button" id="fos-ai-test-connection" class="fos-int-test-btn">
									⚡ <?php esc_html_e('Test connection', 'contentosapp-studio'); ?>
								</button>
							</div>
							<div style="min-height: 22px; margin-top: 4px; display: flex; align-items: center;">
								<div id="fos-ai-test-result" class="fos-int-result" aria-live="polite" style="flex: 1; margin: 0;"></div>
								<p id="fos-ai-api-hint" class="fos-int-result-hint fos-int-hint" style="margin: 0; flex: 1;">🔒 <?php esc_html_e('Stored encrypted in the database. Never shared externally.', 'contentosapp-studio'); ?></p>
							</div>
						</div>
					</div><!-- /.fos-int-grid -->

					<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 14px; align-items: center;margin-top:6px;">
						<div class="fos-int-field">
							<label for="fos-ai-model"><?php esc_html_e('Model', 'contentosapp-studio'); ?></label>
							<div class="fos-int-model-row">
								<?php
								$_models_cache    = get_option('costudio_models_cache', []);
								$_cached_models   = $_models_cache[$_ai_provider] ?? [];
								if ( class_exists( 'Costudio_Admin_Model_Discovery' ) ) {
									$_cached_models = Costudio_Admin_Model_Discovery::normalize_model_rows( (array) $_cached_models );
								}
								?>
								<select id="fos-ai-model" name="ai_model" class="cts-select fos-int-select"
									data-current="<?php echo esc_attr($_ai_model); ?>">
									<?php if (! empty($_cached_models)) : ?>
										<?php foreach ($_cached_models as $_cm) : ?>
											<option value="<?php echo esc_attr($_cm['value']); ?>"
												<?php selected($_ai_model, $_cm['value']); ?>>
												<?php echo esc_html($_cm['label']); ?>
											</option>
										<?php endforeach; ?>
									<?php elseif (! empty($_ai_model)) : ?>
										<option value="<?php echo esc_attr($_ai_model); ?>" selected><?php echo esc_html($_ai_model); ?></option>
									<?php else : ?>
										<option value=""><?php esc_html_e('— Click 🔄 to load —', 'contentosapp-studio'); ?></option>
									<?php endif; ?>
								</select>
								<button type="button" id="fos-ai-fetch-models" class="fos-int-fetch-btn"
									title="<?php esc_attr_e('Refresh models from API', 'contentosapp-studio'); ?>">🔄</button>
							</div>
							<p class="fos-int-hint" id="fos-ai-model-hint">
								<?php if (! empty($_cached_models)) : ?>
									<?php printf(
										/* translators: %d: number of models */
										esc_html__('%d models available. Click 🔄 to refresh.', 'contentosapp-studio'),
										count($_cached_models)
									); ?>
								<?php else : ?>
									<?php esc_html_e('Click 🔄 to load available models from API.', 'contentosapp-studio'); ?>
								<?php endif; ?>
							</p>
						</div>

						<div id="fos-provider-tip-container" style="display: none;">
							<div class="fos-provider-tip-card">
								<span class="fos-provider-tip-icon"></span>
								<p class="fos-provider-tip-content"></p>
							</div>
						</div>
					</div>

				</div><!-- /#fos-aimode-byok-fields -->

			</div><!-- /.fos-int-card__body -->
		</div><!-- /.fos-int-card -->

		<?php
		$_img_provider  = $all_settings['ai_image_provider'] ?? '';
		if ($_img_provider === '' && ! $_byok_active) {
			$_img_provider = 'contentos';
		}
		$_img_model     = $all_settings['ai_image_model']    ?? '';
		$_img_has_key   = ! empty($all_settings['ai_image_api_key']);
		$_can_image     = true;
		$_img_mode      = $all_settings['costudio_image_mode']     ?? 'generate';
		if ( $_managed_images_unavailable && 'generate' === $_img_mode ) {
			$_img_mode = 'placeholder';
		}
		$_img_byok_max = class_exists( 'Costudio_Standalone_Settings' )
			? Costudio_Standalone_Settings::IMAGE_QUANTITY_MAX
			: 3;
		$_img_contentos_max = class_exists( 'Costudio_Standalone_Settings' )
			? Costudio_Standalone_Settings::image_quantity_max_for_mode( 'contentos' )
			: 3;
		$_img_qty_max   = class_exists( 'Costudio_Standalone_Settings' )
			? Costudio_Standalone_Settings::image_quantity_max_for_mode( $_ai_mode )
			: 3;
		$_img_qty       = class_exists( 'Costudio_Standalone_Settings' )
			? Costudio_Standalone_Settings::clamp_image_quantity( $all_settings['costudio_image_quantity'] ?? 2, $_ai_mode )
			: max( 1, min( 3, intval( $all_settings['costudio_image_quantity'] ?? 2 ) ) );
		?>

		<!-- ── Image generation ──────────────────────────────────────────────── -->
		<p class="fos-int-zone-label"><?php esc_html_e('Image Generation', 'contentosapp-studio'); ?></p>
		<div class="fos-int-card">

			<div class="fos-int-card__header">
				<div class="fos-int-card__left">
					<span class="fos-int-card__icon">🖼️</span>
					<div>
						<p class="fos-int-card__title"><?php esc_html_e('Image Provider', 'contentosapp-studio'); ?></p>
						<p class="fos-int-card__subtitle"><?php esc_html_e('Used by the Visual Designer agent to generate article images.', 'contentosapp-studio'); ?></p>
					</div>
				</div>
				<?php
					if ( $_img_mode === 'none' ) {
						$_img_status_class = 'fos-int-status--warn';
						$_img_status_text  = __( 'No images', 'contentosapp-studio' );
					} elseif ( $_img_mode === 'placeholder' ) {
						$_img_status_class = 'fos-int-status--ok';
						$_img_status_text  = __( 'Suggesting placements', 'contentosapp-studio' );
					} elseif ( $_img_provider === 'contentos' ) {
						$_img_status_class = 'fos-int-status--ok';
						$_img_status_text  = __( 'Using ContentOS Auto quota', 'contentosapp-studio' );
					} elseif ( $_img_provider && $_img_has_key ) {
						$_img_status_class = 'fos-int-status--ok';
						$_img_status_text  = __( 'API key saved', 'contentosapp-studio' );
					} elseif ( $_img_provider ) {
						$_img_status_class = 'fos-int-status--warn';
						$_img_status_text  = __( 'API key pending', 'contentosapp-studio' );
					} else {
						$_img_status_class = 'fos-int-status--warn';
						$_img_status_text  = __( 'Provider not selected', 'contentosapp-studio' );
					}
					?>
					<div id="fos-image-status" class="fos-int-status <?php echo esc_attr( $_img_status_class ); ?>">
						<span class="fos-int-status__dot"></span>
						<span class="fos-int-status__text"><?php echo esc_html( $_img_status_text ); ?></span>
					</div>
			</div><!-- /.fos-int-card__header -->

			<div class="fos-int-card__body">

				<fieldset>

					<!-- SELETOR DE MODO -->
					<div class="fos-img-field-label">
						<?php esc_html_e('Generation mode', 'contentosapp-studio'); ?>
					</div>

					<?php
					$_img_mode_display = $_img_mode;
					?>
					<div class="fos-img-mode-grid">
						<!-- MODO: Sem imagens -->
						<div class="fos-img-mode-card<?php echo esc_attr( $_img_mode_display === 'none' ? ' fos-img-mode-card--active' : '' ); ?>" data-mode="none">
							<div class="fos-img-mode-radio"></div>
							<div class="fos-img-mode-icon fos-img-mode-icon--gray">
								<svg width="15" height="15" viewBox="0 0 15 15" fill="none">
									<path d="M2 2L13 13M13 2L2 13" stroke="#888780" stroke-width="1.3" stroke-linecap="round" />
								</svg>
							</div>
							<div class="fos-img-mode-title"><?php esc_html_e('No images', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-desc"><?php esc_html_e('Publishes the article as text-only, with no generated images.', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-hint"><?php esc_html_e('The Designer agent still generates schema.org structured data.', 'contentosapp-studio'); ?></div>
						</div>

						<!-- MODO: Sugerir locais -->
						<div class="fos-img-mode-card<?php echo esc_attr( $_img_mode_display === 'placeholder' ? ' fos-img-mode-card--active' : '' ); ?>" data-mode="placeholder">
							<div class="fos-img-mode-radio"></div>
							<div class="fos-img-mode-icon fos-img-mode-icon--teal">
								<svg width="15" height="15" viewBox="0 0 15 15" fill="none">
									<rect x="1" y="1" width="13" height="13" rx="2" stroke="#0F6E56" stroke-width="1.2" stroke-dasharray="2.5 2" />
									<path d="M5 7.5H10M7.5 5V10" stroke="#0F6E56" stroke-width="1.2" stroke-linecap="round" />
								</svg>
							</div>
							<div class="fos-img-mode-title"><?php esc_html_e('Suggest placements', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-desc"><?php esc_html_e('Marks where to manually insert images in the article, without generating them.', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-hint">
								<?php esc_html_e('The Designer agent marks image positions with', 'contentosapp-studio'); ?>
								<code>[IMG:imagem2.webp | description]</code>
								<?php esc_html_e('markers — add images manually after publishing.', 'contentosapp-studio'); ?>
							</div>
						</div>

						<!-- MODO: Gerar com IA -->
						<div class="fos-img-mode-card<?php echo esc_attr( $_img_mode_display === 'generate' ? ' fos-img-mode-card--active' : '' ); ?><?php echo esc_attr( $_managed_images_unavailable ? ' fos-img-mode-card--service-gated' : '' ); ?>" data-mode="generate">
							<div class="fos-img-mode-radio"></div>
							<div class="fos-img-mode-icon-row">
								<div class="fos-img-mode-icon fos-img-mode-icon--purple">
									<svg width="15" height="15" viewBox="0 0 15 15" fill="none">
										<path d="M7.5 1L9.18 5.32L13.5 5.32L10.16 7.87L11.09 12.5L7.5 9.5L3.91 12.5L4.84 7.87L1.5 5.32L5.82 5.32L7.5 1Z" stroke="#534AB7" stroke-width="1.2" stroke-linejoin="round" />
									</svg>
								</div>
								<?php if ( $_managed_images_unavailable ) : ?><span class="fos-img-mode-plan-badge"><?php esc_html_e( 'Unavailable on this plan', 'contentosapp-studio' ); ?></span><?php endif; ?>
							</div>
							<div class="fos-img-mode-title"><?php esc_html_e('Generate with AI', 'contentosapp-studio'); ?></div>
							<div class="fos-img-mode-desc"><?php esc_html_e('Generates and inserts images automatically via the configured provider.', 'contentosapp-studio'); ?></div>
						</div>
					</div><!-- /.fos-img-mode-grid -->

					<!-- SEÇÃO: Gerar com IA -->
					<div id="fos-img-section-generate" class="fos-img-section<?php echo esc_attr( $_img_mode_display === 'generate' ? ' fos-img-section--active' : '' ); ?>">

						<!-- Quantity. The generation engine follows the global Execution model. -->
						<div class="fos-img-quantity-row">
							<div class="fos-img-quantity-row__notice">
								<div id="fos-img-contentos-info" style="<?php echo esc_attr( $_byok_active ? 'display:none;' : '' ); ?>">
									<div class="fos-int-pro-notice">
										⚡ <?php esc_html_e('ContentOS Auto active. Generated images consume ContentOS Auto service quota.', 'contentosapp-studio'); ?>
									</div>
								</div>
								<?php if ( $_managed_images_unavailable ) : ?>
									<p class="fos-img-service-note" style="margin:0;">
										ℹ️ <?php esc_html_e( 'Managed image generation is unavailable on your current ContentOS Auto plan. Use placement suggestions instead, or switch to BYOK to generate images with your own provider key.', 'contentosapp-studio' ); ?>
									</p>
								<?php endif; ?>
							</div>

							<div class="fos-img-quantity-row__control">
								<div class="fos-img-quantity-row__label">
									<span class="fos-img-field-label">
										<?php esc_html_e('Image quantity per article', 'contentosapp-studio'); ?>
									</span>
									<i class="fos-tooltip-icon" title="<?php esc_attr_e('The 1st always becomes the featured image (thumbnail). The others are inserted through the text.', 'contentosapp-studio'); ?>">?</i>
								</div>
								<div class="fos-img-qty-stepper" data-min="1" data-max="<?php echo esc_attr( $_img_qty_max ); ?>" data-byok-max="<?php echo esc_attr( $_img_byok_max ); ?>" data-contentos-max="<?php echo esc_attr( $_img_contentos_max ); ?>">
									<button type="button" class="fos-img-qty-btn" id="fos-img-qty-minus">−</button>
									<span class="fos-img-qty-val" id="fos-img-qty-display"><?php echo esc_attr($_img_qty); ?></span>
									<button type="button" class="fos-img-qty-btn" id="fos-img-qty-plus">+</button>
								</div>
								<input type="hidden" name="costudio_image_quantity" id="fos-img-qty-value" value="<?php echo esc_attr( $_img_qty ); ?>">
							</div>
						</div>

						<!-- BYOK fields (hidden in ContentOS mode) -->
						<div id="fos-img-byok-fields" style="<?php echo esc_attr( $_byok_active ? '' : 'display:none;' ); ?>">
							<!-- Linha 1: Provedor + Chave de API -->
							<div class="fos-img-byok-provider-grid">
								<div>
									<div class="fos-img-field-label"><?php esc_html_e('Provider', 'contentosapp-studio'); ?> <span class="fos-plan-field__required">*</span></div>
									<select name="ai_image_provider" id="fos-image-provider" class="cts-select fos-int-select">
										<option value="contentos" style="display:none;" <?php selected($_img_provider, 'contentos'); ?>></option>
										<option value="" <?php selected($_img_provider, ''); ?>><?php esc_html_e('— None —', 'contentosapp-studio'); ?></option>
										<option value="gemini_imagen" <?php selected($_img_provider, 'gemini_imagen'); ?>>Google Imagen</option>
										<option value="openai_dalle" <?php selected($_img_provider, 'openai_dalle'); ?>>OpenAI DALL·E</option>
									</select>
									<p style="font-size: 11px; color: var(--fos-text-dim); margin-top: 6px;">
										🖼️ <?php esc_html_e('Image generation engine used by the Designer agent.', 'contentosapp-studio'); ?>
									</p>
								</div>

								<div id="fos-image-api-key-block" class="fos-img-byok-key-row">
									<div class="fos-img-field-label"><?php esc_html_e('API Key', 'contentosapp-studio'); ?> <span class="fos-plan-field__required">*</span></div>
									<div class="fos-img-byok-key-row__control">
										<div class="fos-int-apikey-wrap">
											<input type="password" id="fos-image-api-key" name="ai_image_api_key" class="cts-input"
												value="<?php echo esc_attr($masked_settings['ai_image_api_key'] ?? ''); ?>"
												placeholder="<?php esc_attr_e('Paste your API key here', 'contentosapp-studio'); ?>"
												autocomplete="off">
											<button type="button" class="fos-int-toggle-vis"
												data-target="fos-image-api-key"
												aria-label="<?php esc_attr_e('Show/hide API key', 'contentosapp-studio'); ?>">
												<span class="dashicons dashicons-visibility"></span>
											</button>
										</div>
										<button type="button" id="fos-image-test-connection" class="fos-int-test-btn">
											⚡ <?php esc_html_e('Test connection', 'contentosapp-studio'); ?>
										</button>
									</div>
									<div class="fos-img-byok-key-row__hint">
										<div id="fos-image-test-result" class="fos-int-result" aria-live="polite"></div>
										<p id="fos-image-api-hint" class="fos-int-result-hint">
											🔒 <?php esc_html_e('Stored encrypted in the database. Never shared externally.', 'contentosapp-studio'); ?>
										</p>
									</div>
								</div>
							</div> <!-- /.fos-img-byok-provider-grid -->

							<!-- Linha 2: Modelo + dica contextual -->
							<div class="fos-img-byok-model-grid">
								<div>
									<div class="fos-img-field-label">
										<?php esc_html_e('Model', 'contentosapp-studio'); ?> <span class="fos-plan-field__required">*</span>
										<i class="fos-tooltip-icon" title="<?php esc_attr_e('Click the refresh button beside it to load available models from the API.', 'contentosapp-studio'); ?>">?</i>
									</div>
									<div style="display: flex; gap: 6px; align-items: center;">
										<?php
										$_image_models_cache  = get_option('costudio_image_models_cache', []);
										$_cached_image_models = $_image_models_cache[$_img_provider] ?? [];
										if ( class_exists( 'Costudio_Admin_Model_Discovery' ) ) {
											$_cached_image_models = Costudio_Admin_Model_Discovery::normalize_model_rows( (array) $_cached_image_models );
										}
										?>
										<select id="fos-image-model" name="ai_image_model" class="cts-select fos-int-select"
											style="flex: 1;"
											data-current="<?php echo esc_attr($_img_model); ?>">
											<?php if (! empty($_cached_image_models)) : ?>
												<?php foreach ($_cached_image_models as $_im) : ?>
													<option value="<?php echo esc_attr($_im['value']); ?>"
														<?php selected($_img_model, $_im['value']); ?>>
														<?php echo esc_html($_im['label']); ?>
													</option>
												<?php endforeach; ?>
											<?php elseif (! empty($_img_model)) : ?>
												<option value="<?php echo esc_attr($_img_model); ?>" selected><?php echo esc_html($_img_model); ?></option>
											<?php else : ?>
												<option value=""><?php esc_html_e('— Select provider —', 'contentosapp-studio'); ?></option>
											<?php endif; ?>
										</select>
										<button type="button" id="fos-image-fetch-models" class="fos-int-fetch-btn"
											style="flex-shrink: 0; width: 36px; height: 36px;"
											title="<?php esc_attr_e('Refresh models from API', 'contentosapp-studio'); ?>">🔄</button>
									</div>
									<p class="fos-int-hint" id="fos-image-model-hint" style="font-size: 11px; color: var(--fos-text-dim); margin-top: 6px;">
										<?php if (! empty($_cached_image_models)) : ?>
											<?php printf(
												/* translators: %d: number of models */
												esc_html__('%d models available. Click 🔄 to refresh.', 'contentosapp-studio'),
												count($_cached_image_models)
											); ?>
										<?php else : ?>
											<?php esc_html_e('Click 🔄 to load available models from API.', 'contentosapp-studio'); ?>
										<?php endif; ?>
									</p>
									<p class="fos-int-hint" id="fos-image-selected-model" style="font-size: 11px; color: var(--fos-text-dim); margin-top: 4px;<?php echo esc_attr( empty($_img_model) ? ' display:none;' : '' ); ?>">
										<?php if (! empty($_img_model)) : ?>
											<?php esc_html_e('Selected model:', 'contentosapp-studio'); ?>
											<code><?php echo esc_html($_img_model); ?></code>
										<?php endif; ?>
									</p>
								</div>

								<div class="fos-provider-tip-card">
									<span class="fos-provider-tip-icon">ℹ️</span>
									<p class="fos-provider-tip-content">
										<strong><?php esc_html_e('BYOK (Bring Your Own Key)', 'contentosapp-studio'); ?>:</strong>
										<?php esc_html_e('Images are billed directly by your chosen provider. ContentOS quotas are preserved.', 'contentosapp-studio'); ?>
									</p>
								</div>
							</div>
						</div> <!-- /#fos-img-byok-fields -->

					</div><!-- /#fos-img-section-generate -->

					<!-- Input hidden que persiste o modo selecionado -->
					<input type="hidden" name="costudio_image_mode" id="fos-img-mode-value" value="<?php echo esc_attr($_img_mode); ?>">

				</fieldset>

			</div><!-- /.fos-int-card__body -->
		</div><!-- /.fos-int-card -->

		<?php
		$_search_provider  = $all_settings['search_api_provider'] ?? '';
		$_search_model     = $all_settings['search_api_model']    ?? '';
		if ( 'exa' === $_search_provider ) {
			$_search_model_lc = strtolower( (string) $_search_model );
			if ( 0 === strpos( $_search_model_lc, 'exa:' ) ) {
				$_search_model_lc = substr( $_search_model_lc, 4 );
			}
			if ( in_array( $_search_model_lc, array( 'neural', 'keyword' ), true ) ) {
				$_search_model = 'auto';
			}
		}
		$_search_has_key   = ! empty($all_settings['search_api_key']);
		$_search_max_results = class_exists( 'Costudio_Standalone_Settings' )
			? Costudio_Standalone_Settings::clamp_search_results( $all_settings['search_max_results'] ?? 5 )
			: max( 1, min( 20, intval( $all_settings['search_max_results'] ?? 5 ) ) );
		// In Auto mode native grounding defaults ON and follows the same helper
		// used by the pipeline. In BYOK it stays off-by-default so the external
		// provider fields show.
		$_settings = function_exists('costudio_settings') ? costudio_settings() : null;
		$_search_grounding = $_byok_active
			? ! empty($all_settings['search_grounding'])
			: ( ( $_settings && method_exists($_settings, 'contentos_native_search_enabled') )
				? (bool) $_settings->contentos_native_search_enabled('contentos')
				: ( $_settings ? (bool) $_settings->get('search_grounding', true) : true ) );
		$_can_search       = true;

		if (! $_byok_active) {
			if ($_search_grounding) {
				$_search_status_class = 'fos-int-status--ok';
				$_search_status_text  = __('Grounding active', 'contentosapp-studio');
			} else {
				$_search_status_class = 'fos-int-status--warn';
				$_search_status_text  = __('Search disabled', 'contentosapp-studio');
			}
		} elseif ($_search_provider && $_search_has_key) {
			$_search_status_class = 'fos-int-status--ok';
			$_search_status_text  = __('API key saved', 'contentosapp-studio');
		} elseif ($_search_provider) {
			$_search_status_class = 'fos-int-status--warn';
			$_search_status_text  = __('API key pending', 'contentosapp-studio');
		} else {
			$_search_status_class = 'fos-int-status--warn';
			$_search_status_text  = __('Not configured', 'contentosapp-studio');
		}
		?>

		<!-- ── Web search ────────────────────────────────────────────────────── -->
		<p class="fos-int-zone-label"><?php esc_html_e('Web search', 'contentosapp-studio'); ?></p>
		<div class="fos-int-card">

			<div class="fos-int-card__header">
				<div class="fos-int-card__left">
					<span class="fos-int-card__icon">🔍</span>
					<div>
						<p class="fos-int-card__title"><?php esc_html_e('Web Search', 'contentosapp-studio'); ?></p>
						<p class="fos-int-card__subtitle"><?php esc_html_e('Enriches content with current data. Used by the Discoverer and Researcher agents.', 'contentosapp-studio'); ?></p>
					</div>
				</div>
				<div id="fos-search-status" class="fos-int-status <?php echo esc_attr($_search_status_class); ?>">
					<span class="fos-int-status__dot"></span>
					<span class="fos-int-status__text"><?php echo esc_html($_search_status_text); ?></span>
				</div>
			</div><!-- /.fos-int-card__header -->

			<div class="fos-int-card__body">

				<fieldset>

					<!-- Google Grounding toggle -->
					<div class="fos-int-toggle-row" <?php if ( $_byok_active ) : ?>style="display:none"<?php endif; ?>>
						<div class="fos-int-toggle-row__info">
							<div class="fos-int-toggle-row__title"><?php esc_html_e('Use ContentOS Real-time Search (native)', 'contentosapp-studio'); ?></div>
							<p class="fos-int-toggle-row__desc"><?php esc_html_e('Uses the built-in ContentOS search engine to enrich agents with current data. When active, the external provider below is ignored.', 'contentosapp-studio'); ?></p>
						</div>
						<div class="fos-int-toggle-row__control">
							<input type="hidden" name="search_grounding" value="0">
							<label class="fos-switch fos-switch--compact">
								<input type="checkbox" id="fos-search-grounding" name="search_grounding" value="1"
									<?php checked($_search_grounding && ! $_byok_active); ?>
									aria-label="<?php esc_attr_e('Use ContentOS Real-time Search (native)', 'contentosapp-studio'); ?>">
								<span class="fos-switch__slider"></span>
							</label>
						</div>
					</div>

					<?php if ( $_managed_images_unavailable ) : ?>
						<p class="fos-img-service-note" <?php if ( $_byok_active ) : ?>style="display:none"<?php endif; ?>>
							ℹ️ <?php esc_html_e( 'Your plan already grounds articles with standard web research (~6 sources). Pro and Studio research deeper — more sources per article for stronger, more factual content. BYOK search providers below work on every plan.', 'contentosapp-studio' ); ?>
						</p>
					<?php endif; ?>

					<!-- External provider -->
					<div id="fos-search-external-fields" class="fos-int-search-external-grid"
						<?php if ( ! $_byok_active || ( $_search_grounding && $_can_search ) ) : ?>style="display:none"<?php endif; ?>>
						<div class="fos-int-grid">
							<div class="fos-int-field">
								<label for="fos-search-provider"><?php esc_html_e('External provider', 'contentosapp-studio'); ?></label>
								<select id="fos-search-provider" name="search_api_provider" class="cts-select fos-int-select">
									<option value="" <?php selected($_search_provider, ''); ?>><?php esc_html_e('— None —', 'contentosapp-studio'); ?></option>
									<option value="gemini" <?php selected($_search_provider, 'gemini'); ?>>Google Gemini (Grounding)</option>
									<option value="tavily" <?php selected($_search_provider, 'tavily'); ?>>Tavily AI</option>
									<option value="serper" <?php selected($_search_provider, 'serper'); ?>>Serper.dev</option>
									<option value="exa" <?php selected($_search_provider, 'exa'); ?>>Exa.ai Search</option>
								</select>
								<p class="fos-int-hint"><?php esc_html_e('Alternative to native Google Grounding.', 'contentosapp-studio'); ?></p>
							</div>
							<div class="fos-int-field" id="fos-search-api-key-block">
								<label for="fos-search-api-key"><?php esc_html_e('API Key', 'contentosapp-studio'); ?></label>
								<div class="fos-int-key-row">
									<div class="fos-int-apikey-wrap">
										<input type="password" id="fos-search-api-key" name="search_api_key" class="cts-input"
											value="<?php echo esc_attr($masked_settings['search_api_key'] ?? ''); ?>"
											placeholder="<?php esc_attr_e('Your provider API key', 'contentosapp-studio'); ?>"
											autocomplete="off">
										<button type="button" class="fos-int-toggle-vis"
											data-target="fos-search-api-key"
											aria-label="<?php esc_attr_e('Toggle API key visibility', 'contentosapp-studio'); ?>">
											<span class="dashicons dashicons-visibility"></span>
										</button>
									</div>
									<button type="button" id="fos-search-test-connection" class="fos-int-test-btn">
										⚡ <?php esc_html_e('Test connection', 'contentosapp-studio'); ?>
									</button>
								</div>
								<div style="min-height: 22px; margin-top: 4px; display: flex; align-items: center;">
									<div id="fos-search-test-result" class="fos-int-result" aria-live="polite" style="flex: 1; margin: 0;"></div>
									<p id="fos-search-api-hint" class="fos-int-result-hint fos-int-hint" style="margin: 0; flex: 1;">🔒 <?php esc_html_e('Stored encrypted in the database. Never shared externally.', 'contentosapp-studio'); ?></p>
								</div>
							</div>
						</div>

						<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 14px; align-items: center;margin-top:6px;">
							<div class="fos-int-field" id="fos-search-model-block">
								<label for="fos-search-model" id="fos-search-model-label"><?php esc_html_e('Model / Mode', 'contentosapp-studio'); ?></label>
								<div class="fos-int-model-row">
									<?php
									$_search_models_cache  = get_option('costudio_search_models_cache', []);
									$_cached_search_models = $_search_models_cache[$_search_provider] ?? [];
									if ( 'exa' === $_search_provider ) {
										$_cached_search_models = array(
											array( 'value' => 'auto', 'label' => 'Auto (Recommended)' ),
											array( 'value' => 'fast', 'label' => 'Fast' ),
											array( 'value' => 'deep', 'label' => 'Deep' ),
										);
									} elseif ( 'serper' === $_search_provider ) {
										$_cached_search_models = array(
											array( 'value' => 'search', 'label' => 'Web (Default)' ),
											array( 'value' => 'news', 'label' => 'News' ),
										);
									} elseif ( 'tavily' === $_search_provider && empty( $_cached_search_models ) ) {
										$_cached_search_models = array(
											array( 'value' => 'advanced', 'label' => 'Advanced (Recommended)' ),
											array( 'value' => 'basic', 'label' => 'Basic' ),
										);
									}
									?>
									<select id="fos-search-model" name="search_api_model" class="cts-select fos-int-select"
										data-current="<?php echo esc_attr($_search_model); ?>">
										<?php if (! empty($_cached_search_models)) : ?>
											<?php foreach ($_cached_search_models as $_sm) : ?>
												<option value="<?php echo esc_attr($_sm['value']); ?>"
													<?php selected($_search_model, $_sm['value']); ?>>
													<?php echo esc_html($_sm['label']); ?>
												</option>
											<?php endforeach; ?>
										<?php elseif (! empty($_search_model)) : ?>
											<option value="<?php echo esc_attr($_search_model); ?>" selected><?php echo esc_html($_search_model); ?></option>
										<?php else : ?>
											<option value=""><?php esc_html_e('— Click 🔄 to load —', 'contentosapp-studio'); ?></option>
										<?php endif; ?>
									</select>
									<button type="button" id="fos-search-fetch-models" class="fos-int-fetch-btn"
										title="<?php esc_attr_e('Refresh models from API', 'contentosapp-studio'); ?>">🔄</button>
								</div>
								<p class="fos-int-hint" id="fos-search-model-hint">
									<?php if (! empty($_cached_search_models)) : ?>
										<?php printf(
											/* translators: %d: number of models */
											esc_html__('%d models available. Click 🔄 to refresh.', 'contentosapp-studio'),
											count($_cached_search_models)
										); ?>
									<?php else : ?>
										<?php esc_html_e('Click 🔄 to load available models from API.', 'contentosapp-studio'); ?>
									<?php endif; ?>
								</p>
							</div>

							<div>
								<div class="fos-int-field" id="fos-search-results-block">
									<label for="fos-search-max-results"><?php esc_html_e('Sources per search', 'contentosapp-studio'); ?></label>
									<input type="number" id="fos-search-max-results" name="search_max_results" class="cts-input fos-int-input fos-search-results-input"
										min="1" max="20" step="1"
										value="<?php echo esc_attr( $_search_max_results ); ?>">
									<p class="fos-int-hint"><?php esc_html_e('Controls how many structured sources are sent to the Researcher agent.', 'contentosapp-studio'); ?></p>
								</div>
								<div class="fos-provider-tip-card" id="fos-search-provider-tip">
									<span class="fos-provider-tip-icon">ℹ️</span>
									<p class="fos-provider-tip-content">
										<?php esc_html_e('Search engines have different provider-specific modes. Choose the one that best fits your needs.', 'contentosapp-studio'); ?>
									</p>
								</div>
							</div>
						</div>
					</div><!-- /#fos-search-external-fields -->

				</fieldset>

			</div><!-- /.fos-int-card__body -->
		</div><!-- /.fos-int-card -->

		<div class="fos-settings-save-bar" id="fos-settings-save-bar">
			<div>
				<span class="fos-settings-save-bar__hint">💾 <?php esc_html_e('AI settings are shared across all ContentOS modules.', 'contentosapp-studio'); ?></span>
			</div>
			<div class="fos-settings-save-bar__actions">
				<span class="fos-settings-save-bar__msg" id="fos-settings-ai-msg"></span>
				<button type="submit" class="cts-btn cts-btn--primary"><?php esc_html_e('Save Settings', 'contentosapp-studio'); ?></button>
			</div>
		</div>

	</form>
</div><!-- #fos-tab-ai -->
