<?php
/**
 * Partial — Production detail, RUNNING state (also handles REPROCESS via $is_reprocess).
 *
 * @package Contentosapp_Studio
 * @since   3.2.0
 *
 * Expected scope (all provided by page-detalhe.php shell):
 *   @var object $production
 *   @var int    $production_id
 *   @var string $nonce
 *   @var bool   $is_reprocess
 *   @var int    $reprocess_from
 *   @var int    $current_agent
 *   @var array  $agent_defs
 *   @var array  $word_counts
 *   @var int    $progress_pct
 *   @var int    $agents_done_count
 *   @var string $started_label
 *   @var string $eta_label
 *   @var string $st
 *   @var array  $pipeline_log
 *   @var array  $pipeline_diag
 *   @var bool   $is_finalizing
 */

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

<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 of Agents', '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( 'Click on any agent to see the output', 'contentosapp-studio' ); ?>
		</span>
	</div>

	<?php if ( ! empty( $is_finalizing ) ) : ?>
		<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( 'Todos os agentes terminaram. Publicação em andamento.', 'contentosapp-studio' ); ?></div>
				<div class="fos-finalizing-notice__text"><?php esc_html_e( 'Agora o Contentosapp Studio transforma os outputs em post WordPress: referências, imagens, schema, metadados e rascunho final.', 'contentosapp-studio' ); ?></div>
			</div>
		</div>
	<?php endif; ?>

	<?php foreach ( $agent_defs as $num => $def ) :
		$col      = $production->map_step_to_column( $num );
		$has_out  = $col && ! empty( $production->$col );
		
		// Determine Agent State
		if ( $is_reprocess && $num < $reprocess_from ) {
			$agent_state = 'done'; // In reprocess, earlier agents are "preserved" which maps to done visual
		} elseif ( $has_out ) {
			$agent_state = 'done';
		} elseif ( $num === $current_agent && 'running' === $st ) {
			$agent_state = 'running';
		} elseif ( $num === $current_agent && 'awaiting_approval' === $st ) {
			$agent_state = 'approval';
		} else {
			$agent_state = 'queued';
		}

		$states_map = [
			'done'     => [ 'label' => __( 'Done', 'contentosapp-studio' ),    'bg' => 'var(--fos-success-light)', 'fg' => 'var(--fos-success-dark)', 'dot' => 'var(--fos-success)', 'glyph' => '✓' ],
			'running'  => [ 'label' => __( 'Running', 'contentosapp-studio' ), 'bg' => 'var(--fos-primary-faint)',  'fg' => 'var(--fos-primary)',      'dot' => 'var(--fos-primary)', 'glyph' => '●', 'animated' => true ],
			'approval' => [ 'label' => __( 'Waiting', 'contentosapp-studio' ), 'bg' => '#DBEAFE',                  'fg' => '#1D4ED8',                 'dot' => '#3B82F6',            'glyph' => '⏳' ],
			'revision' => [ 'label' => __( 'Ajustando Texto', 'contentosapp-studio' ), 'bg' => '#FFFBEB',          'fg' => '#B45309',                 'dot' => '#F59E0B',            'glyph' => '↺', 'animated' => true ],
			'queued'   => [ 'label' => __( 'Waiting', 'contentosapp-studio' ), 'bg' => 'var(--fos-bg-soft)',       'fg' => 'var(--fos-text-dim)',     'dot' => 'var(--fos-border)',  'glyph' => $num ],
			'skipped'  => [ 'label' => __( 'Skipped', 'contentosapp-studio' ), 'bg' => 'var(--fos-bg-soft)',       'fg' => 'var(--fos-text-dim)',     'dot' => 'var(--fos-border)',  'glyph' => '⏭' ],
		];

		// Override for Revision state
		if ( $num === 4 && $agent_state === 'running' && ! empty( $is_revising ) ) {
			$agent_state = 'revision';
		}

		// Permanently-skipped flag: independent of $has_out, this marks rows
		// that are conceptually skipped for the whole production lifecycle.
		// JS polling reads data-skipped and refuses to overwrite the visual
		// state with "Done"/"Running" while the SKIPPED marker is being
		// written to the output column.
		$is_perm_skipped = false;
		if ( $article_type === Costudio_Article_Types::NEWS && $num === 1 ) {
			$is_perm_skipped = true;
		} elseif ( $article_type === Costudio_Article_Types::UPDATE && $num !== 4 ) {
			$is_perm_skipped = true;
		}

		if ( $is_perm_skipped && $has_out ) {
			$agent_state = 'skipped';
		}

		$s = $states_map[ $agent_state ];
		$output_id = 'fos-run-out-' . $num;
	?>
		<div class="fos-pipeline-row fos-pipeline-row--<?php echo esc_attr( $agent_state ); ?>" id="agent-row-<?php echo (int) $num; ?>"<?php if ( $is_perm_skipped ) : ?> data-skipped="1"<?php endif; ?>>
			<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" style="<?php echo esc_attr( $agent_state === 'queued' ? 'visibility:hidden;' : '' ); ?>">
					<div class="fos-pipeline-row__duration fos-row-duration"><?php echo esc_html( $agent_durations[ $num ] ?? '—' ); ?></div>
					<div class="fos-pipeline-row__meta-label"><?php esc_html_e( 'duration', 'contentosapp-studio' ); ?></div>
				</div>

				<div class="fos-pipeline-row__meta" style="min-width: 80px; <?php echo esc_attr( $agent_state === 'queued' ? 'visibility:hidden;' : '' ); ?>">
					<div class="fos-pipeline-row__duration fos-row-words"><?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>
				</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>

				<?php
				$actions_enabled = $has_out || ( $is_reprocess && $num < $reprocess_from );
				// Keep the live row on the same visual grid as completed rows. The
				// actions become interactive only after an authoritative output exists.
				$show_row_actions = $actions_enabled || in_array( $agent_state, [ 'running', 'revision' ], true );
				?>
				<div class="fos-pipeline-row__actions fos-agent-row-actions" style="<?php echo esc_attr( $show_row_actions ? 'display:flex;' : 'display:none;' ); ?> gap: 4px; min-width: 160px; justify-content: flex-end;">
					<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; ?>" <?php disabled( ! $actions_enabled ); ?> aria-disabled="<?php echo $actions_enabled ? 'false' : 'true'; ?>">
						<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>
					<?php if ( $agent_state !== 'skipped' ) : ?>
						<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 ); ?>" <?php disabled( ! $actions_enabled ); ?> aria-disabled="<?php echo $actions_enabled ? 'false' : 'true'; ?>">
							<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 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>

			<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 && $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:', '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; ?>

					<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 fos-agent-duration-val"><?php echo esc_html( $agent_durations[ $num ] ?? '—' ); ?></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 fos-agent-words-val"><?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 fos-agent-model-val" 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 fos-agent-start-val" style="font-size:11px;"><?php echo esc_html( $agent_start_times[ $num ] ?? '—' ); ?></div>
						</div>
					</div>
					
					<?php 
					$output_content = $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 fos-agent-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 class="fos-agent-running-status" style="<?php echo esc_attr( $agent_state === 'running' ? '' : 'display:none;' ); ?>">
						<div class="fos-pipeline-row__output-preview">
							<div class="fos-preview-label"><?php esc_html_e( 'Status do agente', 'contentosapp-studio' ); ?></div>
							<div style="font-size:13px; color:var(--fos-text-sub); display:flex; align-items:center; gap:8px;">
								<span class="fos-detalhe-spinner" style="width:14px; height:14px; border-width:2px;"></span>
								<?php esc_html_e( 'A processar estágio atual...', 'contentosapp-studio' ); ?>
							</div>
						</div>
					</div>

					<div class="fos-agent-done-actions" style="<?php echo esc_attr( $has_out ? 'display: flex;' : 'display:none;' ); ?> 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>
					</div>
				</div>
		</div>
	<?php endforeach; ?>
</div>

<?php // ── Runtime Debug Strip ────────────────────────────────────────── ?>
<div style="background:var(--fos-surface); border:1px solid var(--fos-border); border-radius:var(--fos-radius-lg); margin-top:12px; overflow:hidden;">
	<div style="padding:10px 20px; background:var(--fos-bg-soft); border-bottom:1px solid var(--fos-border); display:flex; align-items:center; gap:14; font-size:11.5px;">
		<span style="color:var(--fos-text-sub)">
			<strong>● <?php esc_html_e( 'Runner state:', 'contentosapp-studio' ); ?></strong>
			<span id="fos-detalhe-debug-runner-state"><?php echo esc_html( $pipeline_diag['runner_state'] ?? 'waiting' ); ?></span>
			<span class="fos-sep">·</span>
			<?php esc_html_e( 'heartbeat', 'contentosapp-studio' ); ?> <strong id="fos-heartbeat-timer" style="color:var(--fos-text); font-family:var(--fos-font-mono)">0s</strong> <?php esc_html_e( 'ago', 'contentosapp-studio' ); ?>
			<input type="hidden" id="fos-detalhe-debug-heartbeat-ts" value="<?php echo (int) ( $pipeline_diag['last_heartbeat_at'] ?? 0 ); ?>">
		</span>
		<button type="button" class="fos-btn-debug-toggle" style="border:none; background:transparent; padding:0; cursor:pointer; font-size:11.5px; color:var(--fos-primary); font-weight:600; font-family:inherit; display:flex; align-items:center; gap:4px;margin-left:10px">
			<?php esc_html_e( 'Technical details', 'contentosapp-studio' ); ?>
			<svg class="fos-debug-caret" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="transition: transform 0.2s ease;"><polyline points="6 9 12 15 18 9"/></svg>
		</button>
		<div style="flex:1"></div>
		<span style="color:var(--fos-text-dim); font-family:var(--fos-font-mono); font-size:10.5px;">
			<?php echo esc_html( gmdate( 'H:i:s', current_time( 'timestamp' ) ) ); ?> UTC
		</span>
	</div>

	<div id="fos-detalhe-debug-content" style="display:none; padding:16px 20px 6px 20px; background:#FAFBFC; border-top:1px solid var(--fos-border); display:grid; grid-template-columns:repeat(4, 1fr); gap:16px;">
		<?php $publication_debug = is_array( $pipeline_diag['publication_job'] ?? null ) ? $pipeline_diag['publication_job'] : []; ?>
		<div class="fos-pipeline-mini-stat">
			<div class="fos-pipeline-mini-stat__label"><?php echo esc_html( $publication_debug ? __( 'Publication status', 'contentosapp-studio' ) : __( 'Current stage', 'contentosapp-studio' ) ); ?></div>
			<div class="fos-pipeline-mini-stat__value" id="fos-detalhe-debug-stage"><?php echo esc_html( $publication_debug['job_status'] ?? $pipeline_diag['current_stage'] ?? 'boot' ); ?></div>
		</div>
		<div class="fos-pipeline-mini-stat">
			<div class="fos-pipeline-mini-stat__label"><?php echo esc_html( $publication_debug ? __( 'Publication stage', 'contentosapp-studio' ) : __( 'Pending token', 'contentosapp-studio' ) ); ?></div>
			<div class="fos-pipeline-mini-stat__value" id="fos-detalhe-debug-token"><?php echo esc_html( $publication_debug['stage'] ?? ( ! empty( $pipeline_diag['has_pending_token'] ) ? __( 'Yes', 'contentosapp-studio' ) : __( 'No', 'contentosapp-studio' ) ) ); ?></div>
		</div>
		<div class="fos-pipeline-mini-stat">
			<div class="fos-pipeline-mini-stat__label"><?php echo esc_html( $publication_debug ? __( 'Executor', 'contentosapp-studio' ) : __( 'Token source', 'contentosapp-studio' ) ); ?></div>
			<div class="fos-pipeline-mini-stat__value" id="fos-detalhe-debug-token-source"><?php echo esc_html( $publication_debug['driver'] ?? $pipeline_diag['pending_token_source'] ?? '—' ); ?></div>
		</div>
		<div class="fos-pipeline-mini-stat">
			<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'Last Heartbeat', 'contentosapp-studio' ); ?></div>
			<div class="fos-pipeline-mini-stat__value" id="fos-detalhe-debug-heartbeat">
				<?php echo esc_html( ! empty( $publication_debug['heartbeat_at'] ) ? $publication_debug['heartbeat_at'] . ' UTC' : ( ! empty( $pipeline_diag['last_heartbeat_at'] ) ? gmdate( 'H:i:s', (int) $pipeline_diag['last_heartbeat_at'] ) : '—' ) ); ?>
			</div>
		</div>
	</div>
</div>

<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__( 'Waiting for runtime events…', 'contentosapp-studio' ) . '</div>';
			endif; 
			?>
		</div>
	</div>
</div>

<div style="margin-top:20px; display:flex; justify-content:space-between; align-items:center;">
	<button type="button" class="fos-btn" id="fos-resume-pipeline-btn" data-id="<?php echo (int) $production_id; ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>">
		<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-right:6px"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><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"/></svg>
		<?php esc_html_e( 'Resume pipeline', 'contentosapp-studio' ); ?>
	</button>
	<button type="button" class="fos-btn fos-btn--ghost fos-cancel-btn" id="fos-cancel-production-btn" data-id="<?php echo (int) $production_id; ?>" data-nonce="<?php echo esc_attr( $nonce ); ?>" style="color: var(--fos-danger)">
		<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="margin-right:6px"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
		<?php echo esc_html( $is_reprocess ? __( 'Cancel reprocess', 'contentosapp-studio' ) : __( 'Cancel production', 'contentosapp-studio' ) ); ?>
	</button>
</div>
