<?php
/**
 * Partial — Production detail, ERROR state.
 *
 * @package Contentosapp_Studio
 * @since   3.2.0
 *
 * Expected scope:
 *   @var object $production
 *   @var int    $production_id
 *   @var string $nonce
 *   @var int    $error_agent
 *   @var array  $agent_defs
 *   @var array  $word_counts
 *   @var array  $links_lines
 */

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

$error_agent_name = $error_agent > 0 && isset( $agent_defs[ $error_agent ] )
	? sprintf( 'Agent %02d — %s', $error_agent, $agent_defs[ $error_agent ]['name'] )
	: __( 'Unknown agent', 'contentosapp-studio' );
$agent_qty = isset( $agent_qty ) ? (int) $agent_qty : count( $agent_defs );
$is_publish_error = $error_agent > $agent_qty;
if ( $is_publish_error ) {
	$error_agent_name = __( 'Final publishing', 'contentosapp-studio' );
}

$error_summary = $production->error_message
	? mb_substr( $production->error_message, 0, 120 )
	: '';
if ( mb_strlen( $production->error_message ?? '' ) > 120 ) {
	$error_summary .= '…';
}
?>

<?php // ── 1. Error Hero ─────────────────────────────────────────────────── ?>
<div style="background:var(--fos-danger-light); border:1px solid #FCA5A5; border-radius:var(--fos-radius-lg); padding:20px 24px; box-shadow:var(--fos-shadow-soft); display:flex; gap:16px; align-items:center;">
	<div style="font-size:32px;">⚠️</div>
	<div style="flex:1;">
		<div style="font-size:10px; font-weight:700; color:var(--fos-danger); text-transform:uppercase; letter-spacing:0.8px; margin-bottom:4px;">
			<?php esc_html_e( 'Production interrupted', 'contentosapp-studio' ); ?>
		</div>
		<h2 style="font-size:18px; font-weight:700; color:var(--fos-text); letter-spacing:-0.4px; margin:0 0 4px;">
			<?php echo esc_html( $production->title ?: $production->keyword ); ?>
		</h2>
		<div style="font-size:12.5px; color:var(--fos-danger); line-height:1.5;">
			<?php 
			if ( $is_publish_error ) {
				esc_html_e( 'Failed during final publishing.', 'contentosapp-studio' );
			} elseif ( $error_agent > 0 ) {
				/* translators: 1: agent number (e.g. 01), 2: agent name */
				printf(
					/* translators: 1: two-digit agent number, 2: agent name. */
					esc_html__( 'Failed on Agent %1$02d — %2$s.', 'contentosapp-studio' ),
					(int) $error_agent,
					esc_html( $agent_defs[$error_agent]['name'] ?? '' )
				);
			} else {
				esc_html_e( 'An unexpected error occurred during production.', 'contentosapp-studio' );
			}
			?>
		</div>
	</div>
</div>

<?php // ── 2. Error Detail Box ────────────────────────────────────────── ?>
<?php if ( ! empty( $production->error_message ) ) : 
	$msg = (string) $production->error_message;
	$is_provider_issue = (
		false !== stripos( $msg, 'prepayment credits are depleted' )
		|| false !== stripos( $msg, 'billing#prepay' )
		|| false !== stripos( $msg, 'manage your project and billing' )
		|| false !== stripos( $msg, 'project and billing' )
		|| false !== stripos( $msg, 'managed ai provider quota or billing credits are exhausted' )
		|| false !== stripos( $msg, 'managed ai provider needs attention' )
	);
	$is_quota = ! $is_provider_issue && ( false !== stripos( $msg, 'quota' ) || false !== stripos( $msg, 'limit' ) || false !== stripos( $msg, 'expired' ) );
?>
	<?php if ( $is_quota ) : ?>
		<div style="background:linear-gradient(135deg, var(--fos-primary-faint), #fff); border:1px solid var(--fos-primary-border); border-left:4px solid var(--fos-primary); border-radius:12px; padding:20px 24px; margin-bottom:16px; display:flex; gap:16px; align-items:flex-start;">
			<div style="font-size:24px;">💎</div>
			<div style="flex:1;">
				<h3 style="font-size:15px; font-weight:700; color:var(--fos-text); margin:0 0 6px;">
					<?php esc_html_e( 'Managed service quota needs attention', 'contentosapp-studio' ); ?>
				</h3>
				<p style="font-size:13px; color:var(--fos-text-sub); line-height:1.5; margin:0 0 12px;">
					<?php echo esc_html( $msg ); ?><br>
					<?php esc_html_e( 'Review your ContentOS Auto service quota or switch the production mode to BYOK.', 'contentosapp-studio' ); ?>
				</p>
				<a href="<?php echo esc_url( admin_url('admin.php?page=costudio-license') ); ?>" class="fos-btn fos-btn--primary fos-btn--sm">
					💎 <?php esc_html_e( 'Manage service plan', 'contentosapp-studio' ); ?>
				</a>
			</div>
		</div>
	<?php else : ?>
		<div style="background:#fff; border:1px solid var(--fos-border); border-left:4px solid var(--fos-danger); border-radius:12px; padding:16px 20px;">
			<div style="font-size:10px; font-weight:700; color:var(--fos-text-dim); text-transform:uppercase; letter-spacing:0.8px; margin-bottom:6px;">
				<?php esc_html_e( 'Error details', 'contentosapp-studio' ); ?>
			</div>
			<div style="font-size:13px; color:var(--fos-danger); font-family:var(--fos-font-mono); line-height:1.5;">
				<?php echo esc_html( $msg ); ?>
			</div>
		</div>
	<?php endif; ?>
<?php endif; ?>

<?php // ── 3. Unified Agent Timeline ────────────────────────────────────── ?>
<div class="fos-pipeline-body">
	<div class="fos-pipeline-body__header">
		<div style="font-size:13px; font-weight:700; color:var(--fos-text)">
			<?php esc_html_e( 'Pipeline History', 'contentosapp-studio' ); ?>
		</div>
		<span class="cts-badge cts-badge--neutral"><?php echo (int) $agent_qty; ?> <?php esc_html_e( 'stages', 'contentosapp-studio' ); ?></span>
		<div style="flex:1"></div>
		<span style="font-size:11px; color:var(--fos-text-dim)">
			<?php esc_html_e( 'Stages completed before the failure', 'contentosapp-studio' ); ?>
		</span>
	</div>

	<?php if ( $is_publish_error ) : ?>
		<div id="fos-finalizing-notice" class="fos-finalizing-notice">
			<div class="fos-finalizing-notice__icon">↻</div>
			<div>
				<div class="fos-finalizing-notice__title"><?php esc_html_e( 'Os agentes foram preservados.', 'contentosapp-studio' ); ?></div>
				<div class="fos-finalizing-notice__text"><?php esc_html_e( 'Apenas a etapa final de publicação precisa ser tentada novamente; o conteúdo já gerado não será refeito.', 'contentosapp-studio' ); ?></div>
			</div>
		</div>
	<?php endif; ?>

	<?php foreach ( $agent_defs as $num => $def ) :
		$col      = sprintf( 'output_%02d', $num );
		$has_out  = ! empty( $production->$col );
		$is_err   = ( $num === $error_agent );

		// Agents permanently bypassed for this article type (News skips #1,
		// Update skips everything except #4). Their output columns contain a
		// SKIPPED placeholder, so $has_out is true — but they must show as
		// IGNORADO, not CONCLUÍDO.
		$is_skipped_agent = ! $is_err && $has_out && (
			( $article_type === Costudio_Article_Types::NEWS   && $num === 1 ) ||
			( $article_type === Costudio_Article_Types::UPDATE && $num !== 4 )
		);

		if ( $is_err ) {
			$agent_state = 'error';
			$s = [ 'label' => __( 'Failed', 'contentosapp-studio' ),  'bg' => 'var(--fos-danger-light)',  'fg' => 'var(--fos-danger)',      'dot' => 'var(--fos-danger)',  'glyph' => '!' ];
		} elseif ( $is_skipped_agent ) {
			$agent_state = 'skipped';
			$s = [ 'label' => __( 'Skipped', 'contentosapp-studio' ), 'bg' => 'var(--fos-bg-soft)',        'fg' => 'var(--fos-text-dim)',    'dot' => 'var(--fos-border)', 'glyph' => '⏭' ];
		} elseif ( $has_out ) {
			$agent_state = 'done';
			$s = [ 'label' => __( 'Done', 'contentosapp-studio' ),    'bg' => 'var(--fos-success-light)', 'fg' => 'var(--fos-success-dark)', 'dot' => 'var(--fos-success)', 'glyph' => '✓' ];
		} else {
			$agent_state = 'queued';
			$s = [ 'label' => __( 'Skipped', 'contentosapp-studio' ), 'bg' => 'var(--fos-bg-soft)',        'fg' => 'var(--fos-text-dim)',    'dot' => 'var(--fos-border)', 'glyph' => $num ];
		}

		$output_id = 'fos-err-out-' . $num;
	?>
		<div class="fos-pipeline-row fos-pipeline-row--<?php echo esc_attr( $agent_state ); ?>" id="agent-row-<?php echo (int) $num; ?>">
			<div class="fos-pipeline-row__trigger" data-target="<?php echo esc_attr( $output_id ); ?>">
				<div class="fos-pipeline-node">
					<div class="fos-pipeline-node__glyph"><?php echo esc_html( $s['glyph'] ); ?></div>
				</div>

				<div class="fos-pipeline-row__icon"><?php echo esc_html( $def['emoji'] ); ?></div>
				
				<div class="fos-pipeline-row__info">
					<div class="fos-pipeline-row__agent-tag"><?php
					/* translators: %02d: agent number (zero-padded, e.g. 01) */
					printf(
						/* translators: %02d: two-digit agent number. */
						esc_html__( 'AGENT %02d', 'contentosapp-studio' ),
						(int) $num
					); ?></div>
					<div class="fos-pipeline-row__agent-name"><?php echo esc_html( $def['name'] ); ?></div>
					<div class="fos-pipeline-row__agent-desc"><?php echo esc_html( $def['desc'] ); ?></div>
				</div>

				<div class="fos-pipeline-row__meta">
					<?php if ( $has_out ) : ?>
						<div class="fos-pipeline-row__duration">—</div>
						<div class="fos-pipeline-row__meta-label"><?php esc_html_e( 'duration', 'contentosapp-studio' ); ?></div>
					<?php endif; ?>
				</div>

				<div class="fos-pipeline-row__meta" style="min-width: 80px;">
					<?php if ( isset( $word_counts[ $num ] ) ) : ?>
						<div class="fos-pipeline-row__duration"><?php echo esc_html( $word_counts[ $num ] ); ?></div>
						<div class="fos-pipeline-row__meta-label" title="<?php esc_attr_e( 'Não inclui schema, metadados e blocos técnicos do WordPress.', 'contentosapp-studio' ); ?>"><?php esc_html_e( 'palavras editoriais', 'contentosapp-studio' ); ?></div>
					<?php endif; ?>
				</div>

				<div class="fos-pipeline-row__badge" style="background: <?php echo esc_attr( $s['bg'] ); ?>; color: <?php echo esc_attr( $s['fg'] ); ?>;">
					<?php echo esc_html( $s['label'] ); ?>
				</div>

				<div class="fos-pipeline-row__actions" style="display: flex; gap: 4px; min-width: 160px; justify-content: flex-end;">
					<?php if ( $has_out ) : ?>
						<button type="button" class="fos-btn fos-btn--ghost-primary fos-btn--sm" data-action="fos-view-output" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px"><circle cx="12" cy="12" r="3"/><path d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
							<?php esc_html_e( 'Ver', 'contentosapp-studio' ); ?>
						</button>
						<button type="button" class="fos-btn fos-btn--ghost fos-btn--sm" data-action="fos-edit-output" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
							<?php esc_html_e( 'Editar', 'contentosapp-studio' ); ?>
						</button>
					<?php elseif ( $is_err ) : ?>
						<button type="button" class="fos-btn fos-btn--primary fos-btn--sm fos-retry-btn" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>">
							↻ <?php esc_html_e( 'Retry', 'contentosapp-studio' ); ?>
						</button>
					<?php endif; ?>
				</div>
				<span class="fos-pipeline-row__caret">
				<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
			</span>
			</div>

			<?php if ( $has_out || $is_err ) : ?>
				<div class="fos-pipeline-row__details" id="<?php echo esc_attr( $output_id ); ?>" style="display: none;">
					
					<?php // ── Reviewer Feedback Callout (v7 only) ─────────────────── ?>
					<?php if ( $num === 4 && ! empty( $is_revising ) && ! empty( $last_feedback ) ) : ?>
						<div class="fos-reviewer-note" style="background:#FFFBEB; border:1px solid #FDE68A; border-radius:8px; padding:16px; margin-bottom:16px;">
							<div style="display:flex; align-items:center; gap:8px; margin-bottom:10px;">
								<span style="font-size:18px;">⚖️</span>
								<div style="font-weight:700; color:#92400E; font-size:13px; text-transform:uppercase; letter-spacing:0.5px;">
									<?php esc_html_e( 'Feedback do Revisor Editorial', 'contentosapp-studio' ); ?>
								</div>
								<div style="margin-left:auto; background:#F59E0B; color:#fff; padding:2px 8px; border-radius:4px; font-size:11px; font-weight:700;">
									<?php
									/* translators: %d: editorial reviewer score from 0 to 10 */
									printf(
										/* translators: %d: editorial review score from 0 to 10. */
										esc_html__( 'SCORE: %d/10', 'contentosapp-studio' ),
										(int) ( $last_feedback['score'] ?? 0 )
									); ?>
								</div>
							</div>
							<div style="font-size:13px; color:#92400E; line-height:1.5; margin-bottom:12px;">
								<strong><?php esc_html_e( 'Motivo:', 'contentosapp-studio' ); ?></strong> <?php echo esc_html( $last_feedback['feedback'] ?? '' ); ?>
							</div>
							<?php if ( ! empty( $last_feedback['fixes'] ) ) : ?>
								<div style="font-size:12px; color:#B45309; background:rgba(255,255,255,0.5); padding:10px; border-radius:6px; border:1px dashed #FDE68A;">
									<div style="font-weight:700; margin-bottom:4px; font-size:11px;"><?php esc_html_e( 'AJUSTES SOLICITADOS ANTES DA FALHA:', 'contentosapp-studio' ); ?></div>
									<ul style="margin:0; padding-left:18px;">
										<?php foreach ( (array) $last_feedback['fixes'] as $fix ) : ?>
											<li><?php echo esc_html( $fix ); ?></li>
										<?php endforeach; ?>
									</ul>
								</div>
							<?php endif; ?>
						</div>
					<?php endif; ?>

					<?php if ( $is_err ) : ?>
						<div style="background:var(--fos-danger-light); border:1px solid #FCA5A5; border-radius:8px; padding:12px 16px; margin-bottom:12px;">
							<div style="font-size:12.5px; color:var(--fos-danger); line-height:1.5;">
								<strong><?php esc_html_e( 'Error:', 'contentosapp-studio' ); ?></strong> <?php echo esc_html( $msg ); ?>
							</div>
						</div>
						<div style="display: flex; gap: 6px;">
							<button type="button" class="fos-btn fos-btn--primary fos-btn--sm fos-retry-btn" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>">
								↻ <?php esc_html_e( 'Retry Agent', 'contentosapp-studio' ); ?>
							</button>
							<button type="button" class="fos-btn fos-btn--ghost fos-btn--sm" id="fos-skip-agent-btn" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>">
								<?php esc_html_e( 'Skip Agent', 'contentosapp-studio' ); ?>
							</button>
						</div>
					<?php else : ?>
						<div class="fos-pipeline-grid-mini">
							<div class="fos-pipeline-mini-stat">
								<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'DURAÇÃO', 'contentosapp-studio' ); ?></div>
								<div class="fos-pipeline-mini-stat__value">—</div>
							</div>
							<div class="fos-pipeline-mini-stat">
								<div class="fos-pipeline-mini-stat__label" title="<?php esc_attr_e( 'Não inclui schema, metadados e blocos técnicos do WordPress.', 'contentosapp-studio' ); ?>"><?php esc_html_e( 'PALAVRAS EDITORIAIS', 'contentosapp-studio' ); ?></div>
								<div class="fos-pipeline-mini-stat__value"><?php echo esc_html( $word_counts[ $num ] ?? '—' ); ?></div>
							</div>
							<div class="fos-pipeline-mini-stat">
								<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'MODELO', 'contentosapp-studio' ); ?></div>
								<div class="fos-pipeline-mini-stat__value" style="font-size:11px;"><?php echo esc_html( $ai_model ?? '—' ); ?></div>
							</div>
							<div class="fos-pipeline-mini-stat">
								<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'INICIADO', 'contentosapp-studio' ); ?></div>
								<div class="fos-pipeline-mini-stat__value" style="font-size:11px;"><?php echo esc_html( $production->created_at ? wp_date( 'H:i:s', strtotime( $production->created_at ) ) . ' ' . wp_timezone_string() : '—' ); ?></div>
							</div>
						</div>
						<?php 
						$output_content = $col ? ( $production->$col ?? '' ) : '';
						if ( $output_content ) :
							if ( ! class_exists( '\\Costudio_Vendor\\Markdown' ) ) {
								require_once dirname( __DIR__, 3 ) . '/includes/class-costudio-markdown.php';
							}
							$parsedown = new \Costudio_Vendor\Markdown();
							$parsedown->setSafeMode( true );
							$preview_html = $parsedown->text( mb_substr( $output_content, 0, 600 ) );
						?>
							<div class="fos-pipeline-row__output-preview">
								<div class="fos-preview-label"><?php esc_html_e( 'Prévia do output', 'contentosapp-studio' ); ?></div>
								<?php echo wp_kses_post( $preview_html ); ?>
							</div>
						<?php endif; ?>
						<div style="display: flex; gap: 6px; margin-top: 4px;">
							<button type="button" class="fos-btn fos-btn--ghost-primary fos-btn--sm" data-action="fos-view-output" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>">
								<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px"><circle cx="12" cy="12" r="3"/><path d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
								<?php esc_html_e( 'Ver output', 'contentosapp-studio' ); ?>
							</button>
							<button type="button" class="fos-btn fos-btn--ghost fos-btn--sm" data-action="fos-edit-output" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>">
								<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
								<?php esc_html_e( 'Editar', 'contentosapp-studio' ); ?>
							</button>
							<button type="button" class="fos-btn fos-btn--ghost fos-btn--sm" data-action="fos-retry-agent" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $num; ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>">
								↺ <?php esc_html_e( 'Reprocessar daqui', 'contentosapp-studio' ); ?>
							</button>
						</div>
					<?php endif; ?>
				</div>
			<?php endif; ?>
		</div>
	<?php endforeach; ?>
</div>

<?php // ── 4. Internal Links ──────────────────────────────────────────── ?>
<?php if ( ! empty( $links_data['internal'] ) || ! empty( $links_data['external'] ) ) : ?>
	<div style="background:#fff; border:1px solid var(--fos-border); border-radius:var(--fos-radius-lg); padding:20px 24px;">
		<div style="font-size:13px; font-weight:700; color:var(--fos-text); margin-bottom:12px; display:flex; align-items:center; gap:8px;">
			🔗 <?php esc_html_e( 'Links Injetados', 'contentosapp-studio' ); ?>
		</div>
		<div style="display:flex; flex-direction:column; gap:8px;">
			<?php 
			$all_links = array_merge( $links_data['internal'] ?? [], $links_data['external'] ?? [] );
			foreach ( $all_links as $link ) : 
				if ( empty( $link['title'] ) || empty( $link['url'] ) ) continue;
			?>
				<a href="<?php echo esc_url( $link['url'] ); ?>" target="_blank" style="display:flex; align-items:center; gap:10px; background:var(--fos-bg-soft); border:1px solid var(--fos-border); padding:8px 12px; border-radius:7px; text-decoration:none; transition:all 0.2s ease;">
					<span style="font-size:14px;">🔗</span>
					<div style="flex:1; min-width:0;">
						<div style="font-size:13px; font-weight:600; color:var(--fos-primary); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_html( $link['title'] ); ?></div>
						<div style="font-size:11px; color:var(--fos-text-sub); margin-top:2px; font-family:var(--fos-font-mono); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?php echo esc_url( $link['url'] ); ?></div>
					</div>
					<span style="font-size:11px; color:var(--fos-text-dim); background:#fff; padding:2px 6px; border-radius:var(--fos-radius-sm); border:1px solid var(--fos-border); white-space:nowrap;">
						<?php echo esc_html( ! empty( $link['site_name'] ) ? $link['site_name'] : __( 'External', 'contentosapp-studio' ) ); ?>
					</span>
				</a>
			<?php endforeach; ?>
		</div>
	</div>
<?php endif; ?>

<?php // ── 5. Event Log ─────────────────────────────────────────────────────── ?>
<div class="fos-detalhe-debug__log" style="background:#fff; border:1px solid var(--fos-border); border-radius:var(--fos-radius-lg); overflow:hidden;">
	<div style="padding:12px 20px; display:flex; align-items:center; gap:10px; cursor:pointer;" class="fos-log-trigger" data-target="fos-log-content">
		<div style="font-size:13px; font-weight:700; color:var(--fos-text)"><?php esc_html_e( 'Event log', 'contentosapp-studio' ); ?></div>
		<span class="cts-badge cts-badge--neutral"><?php echo (int) count( $pipeline_log ); ?> <?php esc_html_e( 'events', 'contentosapp-studio' ); ?></span>
		<div style="flex:1"></div>
		<span class="fos-pipeline-row__caret is-open">
			<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
		</span>
	</div>
	<div id="fos-log-content" class="fos-log-content">
		<div id="fos-detalhe-debug-log-body">
			<?php 
			if ( ! empty( $pipeline_log ) ) : 
				foreach ( $pipeline_log as $entry ) :
					// Backward compatibility for string logs
					if ( is_string( $entry ) ) {
						echo '<div class="fos-log-line">' . esc_html( $entry ) . '</div>';
						continue;
					}
					
					$time  = isset( $entry['ts'] ) ? wp_date( 'H:i:s', $entry['ts'] ) : '—';
					$level = strtoupper( $entry['level'] ?? 'info' );
					if ( $level === 'ERR' ) $level = 'ERR'; // Normalize
					$lvl_class = 'fos-log-level--' . strtolower( $entry['level'] ?? 'info' );
					$agent = ! empty( $entry['agent'] ) ? sprintf( '#%02d', $entry['agent'] ) : '';
					$msg   = $entry['msg'] ?? '';
			?>
				<div class="fos-log-line">
					<span class="fos-log-time"><?php echo esc_html( $time ); ?></span>
					<span class="fos-log-level <?php echo esc_attr( $lvl_class ); ?>"><?php echo esc_html( $level ); ?></span>
					<?php if ( $agent ) : ?>
						<span class="fos-log-agent"><?php echo esc_html( $agent ); ?></span>
					<?php endif; ?>
					<span class="fos-log-msg"><?php echo esc_html( $msg ); ?></span>
				</div>
			<?php 
				endforeach;
			else : 
				echo '<div style="color:var(--fos-text-dim)">' . esc_html__( 'No events recorded.', 'contentosapp-studio' ) . '</div>';
			endif; 
			?>
		</div>
	</div>
</div>
