<?php
/**
 * Contentosapp Studio — Production Detail view (shell).
 *
 * Renders one of 4 states via partials under partials/detalhe/:
 *   - state-running.php    ($st === 'running', handles reprocess via $is_reprocess)
 *   - state-completed.php  ($st === 'completed')
 *   - state-error.php      ($st === 'error')
 *   - state-pending.php    (fallback for any other status)
 *
 * Common bits (header, meta bar, preview modal, JS polling data) stay here.
 *
 * Loaded via Costudio_Admin::page_detalhe() inside:
 *   <div class="wrap fos-standalone-wrap">
 *
 * @package Contentosapp_Studio
 * @since   3.0.0
 */

defined( 'ABSPATH' ) || exit;
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- View template variables are scoped to this included admin file.

// ── 1. Load production ──────────────────────────────────────────────────────

$production_id = isset( $production_id ) ? absint( $production_id ) : 0;
$production    = $production_id ? Costudio_Production::get_by_id( $production_id ) : null;

if ( ! $production ) {
	require __DIR__ . '/partials/detalhe/not-found.php';
	return;
}

// ── 2. Derived data ─────────────────────────────────────────────────────────

$st      = $production->status ?? 'pending';
$nonce   = wp_create_nonce( Costudio_Admin::NONCE );
$hub_url = admin_url( 'admin.php?page=costudio-studio&tab=hub' );

$version    = $production->get_pipeline_version();
$agent_defs_raw = Costudio_Pipeline::get_agent_definitions( $version );
$agent_defs = [];

foreach ( $agent_defs_raw as $id => $name ) {
	$meta = [
		1 => [ 'emoji' => '🔍', 'desc' => __( 'Competitive analysis + LSI + gaps', 'contentosapp-studio' ) ],
		2 => [ 'emoji' => '🎯', 'desc' => __( 'Editorial brief + outline', 'contentosapp-studio' ) ],
		3 => [ 'emoji' => '🔬', 'desc' => __( 'Fact-checking + E-E-A-T + sources', 'contentosapp-studio' ) ],
		4 => [ 'emoji' => '✍️', 'desc' => __( 'Full article in markdown', 'contentosapp-studio' ) ],
	];

	if ( $version === 6 ) {
		$meta[5] = [ 'emoji' => '🎨', 'desc' => __( 'Image prompts + SEO schemas', 'contentosapp-studio' ) ];
		$meta[6] = [ 'emoji' => '📢', 'desc' => __( 'Posts + WordPress publication', 'contentosapp-studio' ) ];
	} else {
		$meta[5] = [ 'emoji' => '⚖️', 'desc' => __( 'Autonomous editorial review + feedback', 'contentosapp-studio' ) ];
		$meta[6] = [ 'emoji' => '🎨', 'desc' => __( 'Image prompts + SEO schemas', 'contentosapp-studio' ) ];
		$meta[7] = [ 'emoji' => '📢', 'desc' => __( 'Posts + WordPress publication', 'contentosapp-studio' ) ];
	}

	$agent_defs[ $id ] = [
		'emoji' => $meta[ $id ]['emoji'] ?? '🤖',
		'name'  => $name,
		'desc'  => $meta[ $id ]['desc'] ?? '',
	];
}
$agent_qty = count( $agent_defs );

// Site display name and remote URL
$sites_repo = Costudio_Standalone_Sites::get_instance();
$sites      = $sites_repo ? $sites_repo->get_all() : [];
$site_data  = $sites[ $production->site_key ] ?? null;
$site_name  = $site_data
	? costudio_site_display_name( $site_data, $production->site_key )
	: $production->site_key;

// Calculate remote Edit Post URL if site has a mapped domain
$site_base_url = ! empty( $site_data['url'] ) ? rtrim( $site_data['url'], '/' ) : rtrim( site_url(), '/' );
$wp_edit_url   = $site_base_url . '/wp-admin/post.php?post=' . absint( $production->wp_post_id ) . '&action=edit';

// Inputs (JSON stored)
$inputs = json_decode( $production->inputs ?? '{}', true );

// Article type — resolved once here; used in hero badge and context strip below.
$article_type = Costudio_Article_Types::normalize( $inputs['article_type'] ?? '' );
$type_labels  = Costudio_Article_Types::get_labels();
$type_label   = $type_labels[ $article_type ] ?? __( 'Satellite', 'contentosapp-studio' );
$_type_meta   = [
	Costudio_Article_Types::PILLAR     => [ 'emoji' => '🏛️', 'css' => 'pillar' ],
	Costudio_Article_Types::SATELLITE  => [ 'emoji' => '🛰️', 'css' => 'satellite' ],
	Costudio_Article_Types::COMPARISON => [ 'emoji' => '⚖️', 'css' => 'comparison' ],
	Costudio_Article_Types::NEWS       => [ 'emoji' => '📰', 'css' => 'news' ],
	Costudio_Article_Types::UPDATE     => [ 'emoji' => '🔄', 'css' => 'update' ],
];
$type_cfg = $_type_meta[ $article_type ] ?? $_type_meta[ Costudio_Article_Types::SATELLITE ];

// Settings to get AI provider + model (best-effort, prefers data saved at production time)
$settings     = costudio_settings();
$prod_ai_mode = $inputs['ai_mode'] ?? ( $settings ? $settings->get( 'ai_mode', '' ) : '' );

if ( 'contentos' === $prod_ai_mode ) {
	$provider_lbl = 'ContentOS Auto';
	$ai_model     = 'ContentOS Auto';
} else {
	$ai_provider  = $inputs['ai_provider'] ?? ( $settings ? $settings->get( 'ai_provider', '' ) : '' );
	$ai_model     = $inputs['ai_model'] ?? ( $settings ? $settings->get( 'ai_model', '' ) : '' );
	$provider_lbl = $ai_provider ? ( strtoupper( $ai_provider ) . ( $ai_model ? ' — ' . $ai_model : '' ) ) : '—';
}

// Determine current_agent for running states.
$current_agent = (int) ( $production->current_agent ?? 0 );
if ( $st === 'running' && $current_agent < 1 ) {
	for ( $i = $agent_qty; $i >= 1; $i-- ) {
		$col = sprintf( 'output_%02d', $i );
		if ( ! empty( $production->$col ) ) {
			$current_agent = min( $i + 1, $agent_qty );
			break;
		}
	}
	if ( $current_agent < 1 ) {
		$current_agent = 1;
	}
}
if ( 'pending' === $st && $current_agent < 1 ) {
	$current_agent = 1;
}

// Detect reprocess: status === 'running' and at least one previous agent output
// still exists while the current_agent is > 1.
// When reset_for_retry($id, $from_agent) is called, outputs from $from_agent
// onward are NULLed, and outputs before that are preserved.
$is_reprocess    = false;
$reprocess_from  = 0;
if ( $st === 'running' && $current_agent > 1 && $current_agent <= $agent_qty ) {
	$prev_col = sprintf( 'output_%02d', $current_agent - 1 );
	if ( ! empty( $production->$prev_col ) ) {
		$is_reprocess   = true;
		$reprocess_from = $current_agent;
	}
}

// Error agent
$error_agent = (int) ( $production->error_agent ?? 0 );
$is_publish_error = $error_agent > $agent_qty;

// Word counts per agent (count words in output)
$word_counts = [];
for ( $i = 1; $i <= $agent_qty; $i++ ) {
	$col = sprintf( 'output_%02d', $i );
	$txt = $production->$col ?? '';
	if ( $txt ) {
		$word_counts[ $i ] = Costudio_Content_Word_Count::format_editorial_words( $txt );
	}
}

// Total word count (output_04 = Writer, the main article agent)
// For Update, output_04 contains [SECTION N] protocol text (~160 words), not the
// rebuilt article — show "—" to avoid a misleading count.
$total_words = ( $article_type === Costudio_Article_Types::UPDATE )
	? '—'
	: ( ! empty( $production->output_04 )
		? Costudio_Content_Word_Count::format_editorial_words( $production->output_04 )
		: '—' );

// Article preview (Meta Description)
$article_preview = '';
if ( 'completed' === $st ) {
	// Extract from Designer (Agent 05 in v6, Agent 06 in v7)
	$designer_step = ( $version === 7 ) ? 6 : 5;
	$designer_col  = $production->map_step_to_column( $designer_step );
	$designer_out  = $designer_col ? ( $production->$designer_col ?? '' ) : '';

	if ( ! empty( $designer_out ) ) {
		if ( preg_match( '/\[META_DESC\](.*?)\[\/META_DESC\]/si', $designer_out, $m ) ) {
			$article_preview = trim( wp_strip_all_tags($m[1] ) );
		} elseif ( preg_match( '/(?:^|\n)\*?\*?(?:Meta Description|Descrição Meta|Meta Descrição|Meta-descrição)\*?\*?:?\s*(.+?)(?:\n|$)/i', $designer_out, $m ) ) {
			$article_preview = trim( str_replace( array( '**', '__' ), '', wp_strip_all_tags($m[1] ) ) );
		}
	}
	// Fallback to Agent 02 (Brief)
	if ( empty( $article_preview ) && ! empty( $production->output_02 ) ) {
		if ( preg_match( '/1\.2 Meta Description:\s*([^\n]+)/i', $production->output_02, $m ) ) {
			$article_preview = trim( str_replace( array( '**', '__' ), '', wp_strip_all_tags($m[1] ) ) );
		}
	}
}
// Final fallback to content snippet if meta desc is totally missing.
// For Update type, output_04 contains the [SECTION N] protocol text — not
// a readable preview. Use the update instructions as the summary instead.
if ( empty( $article_preview ) ) {
	if ( $article_type === Costudio_Article_Types::UPDATE ) {
		$update_instructions = trim( $inputs['update_instructions'] ?? '' );
		$update_title        = trim( $inputs['update_post_title']   ?? '' );
		if ( $update_instructions !== '' ) {
			$article_preview = mb_substr( $update_instructions, 0, 350 );
			if ( mb_strlen( $update_instructions ) > 350 ) {
				$article_preview .= '…';
			}
		} elseif ( $update_title !== '' ) {
			/* translators: %s: original article title being updated */
			$article_preview = sprintf(
				/* translators: %s: title of the post being updated. */
				__( 'Surgical update of: %s', 'contentosapp-studio' ),
				$update_title
			);
		}
	} elseif ( ! empty( $production->output_04 ) ) {
		$article_plain   = wp_strip_all_tags($production->output_04 );
		$article_preview = mb_substr( $article_plain, 0, 350 );
		if ( mb_strlen( $article_plain ) > 350 ) {
			$article_preview .= '…';
		}
	}
}

// Real wall-clock session duration. Keep the historical processing sum only
// as a compatibility data point; the visible hero no longer uses it.
$total_processing_s = $production->get_total_processing_seconds();
$elapsed_total_s    = $production->get_elapsed_seconds();
$mins               = floor( $elapsed_total_s / 60 );
$remaining_s        = $elapsed_total_s % 60;
$duration_lbl       = $elapsed_total_s > 0
	? ( $mins > 0 ? sprintf( '%dm %ds', $mins, $remaining_s ) : sprintf( '%ds', $elapsed_total_s ) )
	: '—';

// Parsed links data (JSON)
$links_data = [ 'internal' => [], 'external' => [] ];
if ( ! empty( $production->links_internos ) ) {
	$decoded = json_decode( $production->links_internos, true );
	if ( is_array( $decoded ) ) {
		$links_data = $decoded;
	} else {
		// Fallback if it's just raw text with URLs
		$links_lines = array_filter( array_map( 'trim', explode( "\n", $production->links_internos ) ) );
		foreach ( $links_lines as $line ) {
			$links_data['internal'][] = [ 'title' => $line, 'url' => $line ];
		}
	}
}

// ── 2b. Metrics (Usage & Duration) ──────────────────────────────────────────

$agent_durations   = [];
$agent_start_times = [];
$usage_rows        = Costudio_Usage::get_production_latency_rows( $production_id );

foreach ( $usage_rows as $row ) {
	$usage_agent = (int) $row->agent;
	$output_col  = $production->map_step_to_column( $usage_agent );
	if ( $usage_agent < 1 || ! $output_col || empty( $production->$output_col ) ) {
		continue;
	}

	$ms = (int) $row->latency_ms;
	$s  = (int) round( $ms / 1000 );
	
	// Duration
	if ( $s >= 60 ) {
		$agent_durations[ $row->agent ] = sprintf( '%dm %ds', floor( $s / 60 ), $s % 60 );
	} else {
		$agent_durations[ $row->agent ] = sprintf( '%ds', $s );
	}

	// Stable boundary for v1.2.9+, historical arithmetic fallback otherwise.
	$start_ts = ! empty( $row->started_at )
		? strtotime( $row->started_at . ' UTC' )
		: strtotime( $row->created_at . ' UTC' ) - ( $ms / 1000 );
	$agent_start_times[ $row->agent ] = wp_date( 'H:i:s', $start_ts ) . ' ' . wp_timezone_string();
}

// Progress calculation for running/reprocess states
$agents_done_count = 0;
for ( $i = 1; $i <= $agent_qty; $i++ ) {
	$col = $production->map_step_to_column( $i );
	if ( ! empty( $production->$col ) ) {
		$agents_done_count++;
	}
}
$progress_pct = (int) round( ( $agents_done_count / $agent_qty ) * 100 );
$is_finalizing = (
	'running' === $st
	&& $agents_done_count >= $agent_qty
);
if ( $is_finalizing ) {
	$is_reprocess   = false;
	$reprocess_from = 0;
}

// Time running (best effort — seconds since started_at)
$base_run_start = ! empty( $production->started_at ) ? $production->started_at : null;
$started_secs   = $base_run_start ? max( 0, time() - strtotime( $base_run_start . ' UTC' ) ) : 0;
$started_min    = (int) floor( $started_secs / 60 );
$started_label  = $started_secs < 120
	/* translators: %d: seconds elapsed since production started */
	? sprintf( _n( '%d second ago', '%d seconds ago', $started_secs, 'contentosapp-studio' ), $started_secs )
	/* translators: %d: minutes elapsed since production started */
	: sprintf( _n( '%d minute ago', '%d minutes ago', $started_min, 'contentosapp-studio' ), $started_min );

$completed_at_label = ! empty( $production->completed_at )
	? wp_date( 'H:i:s', strtotime( $production->completed_at . ' UTC' ) ) . ' ' . wp_timezone_string()
	: '—';
$updated_at_label   = ! empty( $production->updated_at )
	? wp_date( 'H:i:s', strtotime( $production->updated_at . ' UTC' ) ) . ' ' . wp_timezone_string()
	: '—';

// Estimated remaining (rough: ~1min per remaining agent)
$agents_remaining = $agent_qty - $agents_done_count;
$eta_label        = $agents_remaining > 0
	/* translators: %d: estimated minutes remaining (one per remaining agent) */
	? sprintf(
		/* translators: %d: estimated minutes remaining. */
		__( '~%d min', 'contentosapp-studio' ),
		$agents_remaining
	)
	: __( 'finishing…', 'contentosapp-studio' );

$pipeline_log  = class_exists( 'Costudio_Runner' ) ? Costudio_Runner::get_pipeline_log( $production_id ) : [];
$pipeline_diag = class_exists( 'Costudio_Runner' ) ? Costudio_Runner::get_pipeline_diag( $production_id ) : [];
$queue_position = 0;
$queue_total    = 0;

if ( 'pending' === $st ) {
	$queue_total    = Costudio_Production::count( array( 'status' => 'pending' ) );
	$queue_position = class_exists( 'Costudio_Production_Queue' )
		? Costudio_Production_Queue::queue_position( $production_id )
		: 0;
}

// ── 3. UI State Definitions ──────────────────────────────────────────────────

$status_map = [
	'queued'            => [ 'label' => __( 'Queued', 'contentosapp-studio' ),            'bg' => 'var(--fos-bg-soft)',          'fg' => 'var(--fos-text-dim)',    'dot' => 'var(--fos-border)' ],
	'starting'          => [ 'label' => __( 'Starting…', 'contentosapp-studio' ),         'bg' => 'var(--fos-primary-faint)',    'fg' => 'var(--fos-primary)',     'dot' => 'var(--fos-primary)' ],
	'running'           => [ 'label' => __( 'Running', 'contentosapp-studio' ),           'bg' => 'var(--fos-primary-faint)',    'fg' => 'var(--fos-primary)',     'dot' => 'var(--fos-primary)' ],
	'awaiting_approval' => [ 'label' => __( 'Awaiting Approval', 'contentosapp-studio' ), 'bg' => '#DBEAFE',                     'fg' => '#1D4ED8',                 'dot' => '#3B82F6' ],
	'paused'            => [ 'label' => __( 'Paused', 'contentosapp-studio' ),            'bg' => '#FEF3C7',                     'fg' => '#92400E',                 'dot' => '#F59E0B' ],
	'error'             => [ 'label' => __( 'Error', 'contentosapp-studio' ),             'bg' => 'var(--fos-danger-light)',     'fg' => 'var(--fos-danger)',      'dot' => 'var(--fos-danger)' ],
	'completed'         => [ 'label' => __( 'Completed', 'contentosapp-studio' ),         'bg' => 'rgba(255,255,255,0.22)',      'fg' => '#fff',                   'dot' => '#fff' ],
	'cancelled'         => [ 'label' => __( 'Cancelled', 'contentosapp-studio' ),         'bg' => '#F1F5F9',                     'fg' => '#64748B',                 'dot' => '#94A3B8' ],
];

$chip = $status_map[ $st ] ?? $status_map['queued'];

// ── Revision Loop Detection ────────────────────────────────────────────────
$is_revising = ! empty( $inputs['revision_cycles'] );
$last_feedback = $inputs['last_reviewer_feedback'] ?? null;
?>

<div class="fos-pipeline-timeline">

	<?php // ── 4. Unified Pipeline Hero Header (v2.0) ─────────────────────────── ?>
	<?php 
	// Map status to Hero Modifiers
	$hero_mod = 'fos-hero--neutral';
	$hero_emoji = '🏭';
	$hero_status_lbl = $chip['label'];
	
	if ( 'completed' === $st ) {
		$hero_mod = 'fos-hero--completed';
		$hero_emoji = '✨';
		$hero_status_lbl = __( 'CONCLUÍDA', 'contentosapp-studio' );
	} elseif ( in_array( $st, [ 'running', 'starting' ], true ) ) {
		$hero_mod = 'fos-hero--running';
		$hero_emoji = '🏭';
		if ( $is_finalizing ) {
			$hero_status_lbl = __( 'FINALIZANDO', 'contentosapp-studio' );
		}

		// Override for Revision State
		if ( $is_revising && 4 === $current_agent ) {
			$hero_mod        = 'fos-hero--warning'; // New modifier for revision
			$hero_emoji      = '↺';
			$hero_status_lbl = __( 'AJUSTANDO TEXTO', 'contentosapp-studio' );
		}
	} elseif ( 'error' === $st ) {
		$hero_mod = 'fos-hero--error';
		$hero_emoji = '⚠️';
	} elseif ( 'paused' === $st ) {
		$hero_mod = 'fos-hero--paused';
		$hero_emoji = '⏸️';
	} elseif ( 'awaiting_approval' === $st ) {
		$hero_mod = 'fos-hero--awaiting';
		$hero_emoji = '⏳';
	} elseif ( 'pending' === $st ) {
		$hero_mod = 'fos-hero--queued';
		$hero_emoji = '⏳';
		$hero_status_lbl = __( 'NA FILA', 'contentosapp-studio' );
	} elseif ( 'cancelled' === $st ) {
		$hero_mod = 'fos-hero--cancelled';
		$hero_emoji = '✖️';
		$hero_status_lbl = __( 'CANCELADA', 'contentosapp-studio' );
	}
	?>

	<header class="fos-hero <?php echo esc_attr( $hero_mod ); ?>">
		
		<?php // -- Top Bar -- ?>
		<div class="fos-hero__top">
			<a href="<?php echo esc_url( $hub_url ); ?>" class="fos-hero__back" title="<?php esc_attr_e( 'Back to Pipeline', 'contentosapp-studio' ); ?>">
				‹
			</a>
			
			<div class="fos-hero__icon">
				<?php echo esc_html( $hero_emoji ); ?>
			</div>

			<div class="fos-hero__info">
				<h1 class="fos-hero__title">
					<?php echo esc_html( $production->title ?: $production->keyword ); ?>
				</h1>
				<div class="fos-hero__meta">
					<?php
					/* translators: %s: production identifier wrapped in <code> tags */
					printf( wp_kses( __( 'Produção %s', 'contentosapp-studio' ), array( 'code' => array() ) ), '<code>prod_' . (int) $production_id . '</code>' ); ?>
					<span class="fos-sep">·</span>
					<?php
					/* translators: %s: destination site name wrapped in <strong> */
					printf( wp_kses( __( 'destino %s', 'contentosapp-studio' ), array( 'strong' => array() ) ), '<strong>' . esc_html( $site_name ) . '</strong>' ); ?>
					<span class="fos-sep">·</span>
					<span class="fos-type-badge fos-type-badge--<?php echo esc_attr( $type_cfg['css'] ); ?>">
						<span aria-hidden="true"><?php echo esc_html( $type_cfg['emoji'] ); ?></span>
						<?php echo esc_html( $type_label ); ?>
					</span>
					<?php
					// Show the news author in the hero meta strip. The byline is
					// also rendered on the published post, but surfacing the chosen
					// author here gives editors a quick "who signed this" glance
					// without opening the post in WordPress.
					if ( $article_type === Costudio_Article_Types::NEWS ) :
						$news_author_id = (int) ( $inputs['news_author_id'] ?? 0 );
						$news_author    = $news_author_id > 0 ? get_userdata( $news_author_id ) : null;
						if ( $news_author ) :
							?>
							<span class="fos-sep">·</span>
							<?php
							printf(
								/* translators: %s: news author display name */
								esc_html__( 'autor %s', 'contentosapp-studio' ),
								'<strong>' . esc_html( $news_author->display_name ) . '</strong>'
							);
							?>
							<?php
						endif;
					endif;
					?>
					<?php if ( 'completed' === $st ) : ?>
						<span class="fos-sep">·</span>
						<?php
					/* translators: %s: completion timestamp wrapped in <strong> */
					printf( wp_kses( __( 'concluída %s', 'contentosapp-studio' ), array( 'strong' => array() ) ), '<strong>' . esc_html( $completed_at_label ) . '</strong>' ); ?>
					<?php elseif ( 'cancelled' === $st ) : ?>
						<span class="fos-sep">·</span>
						<?php
					/* translators: %s: cancellation timestamp wrapped in <strong> */
					printf( wp_kses( __( 'cancelada %s', 'contentosapp-studio' ), array( 'strong' => array() ) ), '<strong>' . esc_html( $updated_at_label ) . '</strong>' ); ?>
					<?php endif; ?>
				</div>
			</div>

			<div class="fos-hero__chip">
				<?php if ( ! in_array( $st, [ 'completed', 'cancelled', 'error' ], true ) ) : ?>
					<span class="fos-hero__chip-dot"></span>
				<?php endif; ?>
				<?php echo esc_html( $hero_status_lbl ); ?>
			</div>
		</div>

		<?php // -- KPI Grid -- ?>
		<div class="fos-hero__kpis">
			
			<?php if ( 'completed' === $st ) : ?>
				
				<?php // Stat 1: Tempo Total ?>
				<div class="fos-hero__stat fos-hero__stat--duration">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'TEMPO TOTAL', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value"><?php echo esc_html( $duration_lbl ); ?></div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'duração final', 'contentosapp-studio' ); ?></div>
				</div>

				<?php // Stat 2: Palavras ?>
				<div class="fos-hero__stat fos-hero__stat--metric" title="<?php esc_attr_e( 'Não inclui schema, metadados e blocos técnicos do WordPress.', 'contentosapp-studio' ); ?>">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'PALAVRAS', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value"><?php echo esc_html( $total_words ); ?></div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'palavras editoriais', 'contentosapp-studio' ); ?></div>
				</div>

				<?php // Stat 3: Agentes ?>
				<div class="fos-hero__stat">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'AGENTES', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value"><?php echo (int) $agent_qty; ?> / <?php echo (int) $agent_qty; ?></div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'todos concluídos', 'contentosapp-studio' ); ?></div>
				</div>

				<?php // Stat 4: Status ?>
				<div class="fos-hero__stat fos-hero__stat--status">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'STATUS', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value" style="font-size: 24px;"><?php esc_html_e( 'Publicado', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-sub"><?php
				/* translators: %s: destination site name */
				printf(
					/* translators: %s: destination site name. */
					esc_html__( 'em %s', 'contentosapp-studio' ),
					esc_html( $site_name )
				); ?></div>
				</div>

			<?php elseif ( 'pending' === $st ) : ?>

				<?php // Stat 1: Queue position ?>
				<div class="fos-hero__stat fos-hero__stat--progress">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Posição na fila', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value"><?php echo esc_html( $queue_position > 0 ? '#' . $queue_position : __( 'Aguardando', 'contentosapp-studio' ) ); ?></div>
					<div class="fos-hero__stat-sub">
						<?php
						$queued_count = max( 1, (int) $queue_total );
						/* translators: %d: number of productions waiting in queue */
						$queued_label = _n( '%d production waiting', '%d productions waiting', $queued_count, 'contentosapp-studio' );
						printf( esc_html( $queued_label ), (int) $queued_count );
						?>
					</div>
				</div>

				<?php // Stat 2: Slot state ?>
				<div class="fos-hero__stat fos-hero__stat--duration">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Slot local', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value" style="font-size: 24px;"><?php esc_html_e( 'Aguardando', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'início automático', 'contentosapp-studio' ); ?></div>
				</div>

				<?php // Stat 3: First Agent ?>
				<div class="fos-hero__stat fos-hero__stat--agent">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Primeira etapa', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value">
						<?php echo esc_html( $agent_defs[ $current_agent ]['name'] ?? __( 'Agent 01', 'contentosapp-studio' ) ); ?>
					</div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'começará aqui', 'contentosapp-studio' ); ?></div>
				</div>

				<?php // Stat 4: Target ?>
				<div class="fos-hero__stat fos-hero__stat--metric">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Publicando em', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value" style="font-size: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px;">
						<?php echo esc_html( $site_name ); ?>
					</div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'site de destino', 'contentosapp-studio' ); ?></div>
				</div>
				
			<?php else : ?>
				
				<?php // Stat 1: Progress ?>
				<div class="fos-hero__stat fos-hero__stat--progress">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Progresso Geral', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value"><?php echo (int) $agents_done_count; ?>/<?php echo (int) $agent_qty; ?></div>
					<div class="fos-hero__progress-track">
						<div class="fos-hero__progress-fill" style="width: <?php echo (int) $progress_pct; ?>%"></div>
					</div>
				</div>

				<?php // Stat 2: Duration ?>
				<div class="fos-hero__stat fos-hero__stat--duration">
					<div class="fos-hero__stat-label">
						<?php echo esc_html( 'paused' === $st ? __( 'Tempo até pausar', 'contentosapp-studio' ) : __( 'Tempo Decorrido', 'contentosapp-studio' ) ); ?>
					</div>
					<div class="fos-hero__stat-value"><?php echo esc_html( $duration_lbl !== '—' ? $duration_lbl : $started_label ); ?></div>
					<div class="fos-hero__stat-sub">
						<?php if ( 'running' === $st ) : ?>
							<span style="opacity: 0.8">● <?php esc_html_e( 'timer ativo', 'contentosapp-studio' ); ?></span>
						<?php else : ?>
							<?php esc_html_e( 'duração da sessão', 'contentosapp-studio' ); ?>
						<?php endif; ?>
					</div>
				</div>

				<?php // Stat 3: Current Agent ?>
				<div class="fos-hero__stat fos-hero__stat--agent">
					<div class="fos-hero__stat-label">
						<?php
						if ( $is_finalizing ) {
							esc_html_e( 'Etapa Atual', 'contentosapp-studio' );
						} else {
							echo 'awaiting_approval' === $st ? esc_html__( 'Próximo Agente', 'contentosapp-studio' ) : esc_html__( 'Agente Atual', 'contentosapp-studio' );
						}
						?>
					</div>
					<div class="fos-hero__stat-value">
						<?php
						if ( 'error' === $st ) {
							echo $is_publish_error ? esc_html__( 'Finalizando publicação', 'contentosapp-studio' ) : esc_html( $agent_defs[ $error_agent ]['name'] ?? '—' );
						} elseif ( $is_finalizing ) {
							esc_html_e( 'Finalizando publicação', 'contentosapp-studio' );
						} elseif ( $current_agent > 0 && $current_agent <= $agent_qty ) {
							echo esc_html( $agent_defs[ $current_agent ]['name'] );
						} else {
							echo '—';
						}
						?>
					</div>
					<div class="fos-hero__stat-sub">
						<?php if ( $is_finalizing ) : ?>
							<?php esc_html_e( 'criando o rascunho no WordPress…', 'contentosapp-studio' ); ?>
						<?php elseif ( 'running' === $st ) : ?>
							<?php esc_html_e( 'processando etapa…', 'contentosapp-studio' ); ?>
						<?php elseif ( 'awaiting_approval' === $st ) : ?>
							<?php esc_html_e( 'aguardando revisão', 'contentosapp-studio' ); ?>
						<?php else : ?>
							<?php esc_html_e( 'status da etapa', 'contentosapp-studio' ); ?>
						<?php endif; ?>
					</div>
				</div>

				<?php // Stat 4: Metrics (Target) ?>
				<div class="fos-hero__stat fos-hero__stat--metric">
					<div class="fos-hero__stat-label"><?php esc_html_e( 'Publicando em', 'contentosapp-studio' ); ?></div>
					<div class="fos-hero__stat-value" style="font-size: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 150px;">
						<?php echo esc_html( $site_name ); ?>
					</div>
					<div class="fos-hero__stat-sub"><?php esc_html_e( 'site de destino', 'contentosapp-studio' ); ?></div>
				</div>

			<?php endif; ?>

			<?php // Stat 5: Actions ?>
			<div class="fos-hero__actions">
				<?php if ( 'completed' === $st ) : ?>
					<a href="<?php echo esc_url( $wp_edit_url ); ?>" class="fos-hero__btn fos-hero__btn--light" target="_blank">
						🌐 <?php esc_html_e( 'Ver post publicado', 'contentosapp-studio' ); ?>
					</a>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-export-zip-btn" data-id="<?php echo (int) $production_id; ?>" data-nonce="<?php echo esc_attr( wp_create_nonce( Costudio_Admin::NONCE ) ); ?>">
						📦 <?php esc_html_e( 'Exportar .zip', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'running' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--light fos-pause-btn" data-id="<?php echo (int) $production_id; ?>">
						⏸️ <?php esc_html_e( 'Pausar', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-cancel-btn" data-id="<?php echo (int) $production_id; ?>">
						🚫 <?php esc_html_e( 'Cancelar', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'paused' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--light fos-resume-btn" data-id="<?php echo (int) $production_id; ?>">
						▶️ <?php esc_html_e( 'Retomar', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-cancel-btn" data-id="<?php echo (int) $production_id; ?>">
						🚫 <?php esc_html_e( 'Cancelar', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'awaiting_approval' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--light fos-approve-btn" data-id="<?php echo (int) $production_id; ?>">
						✓ <?php esc_html_e( 'Aprovar próximo', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-pause-btn" data-id="<?php echo (int) $production_id; ?>">
						⏸️ <?php esc_html_e( 'Manter pausado', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'error' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--light fos-retry-btn" data-id="<?php echo (int) $production_id; ?>" data-agent="<?php echo (int) $error_agent; ?>">
						↻ <?php esc_html_e( 'Retry Agent', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-cancel-btn" data-id="<?php echo (int) $production_id; ?>">
						🚫 <?php esc_html_e( 'Cancelar', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-delete-btn" data-id="<?php echo (int) $production_id; ?>">
						🗑️ <?php esc_html_e( 'Excluir', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'cancelled' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--light fos-retry-btn" style="background: var(--fos-primary); color: #fff;" data-id="<?php echo (int) $production_id; ?>" data-agent="1">
						↻ <?php esc_html_e( 'Recriar produção', 'contentosapp-studio' ); ?>
					</button>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-delete-btn" data-id="<?php echo (int) $production_id; ?>">
						🗑️ <?php esc_html_e( 'Excluir', 'contentosapp-studio' ); ?>
					</button>
				<?php elseif ( 'pending' === $st ) : ?>
					<button type="button" class="fos-hero__btn fos-hero__btn--outline fos-cancel-btn" data-id="<?php echo (int) $production_id; ?>">
						🚫 <?php esc_html_e( 'Cancelar produção', 'contentosapp-studio' ); ?>
					</button>
				<?php endif; ?>
			</div>

		</div>
		<?php // -- Callouts -- ?>
		<?php if ( 'error' === $st ) : ?>
			<div class="fos-hero__callout fos-hero__callout--error">
				<span style="font-size: 16px">🚨</span>
				<div>
					<strong><?php esc_html_e( 'Production Halted:', 'contentosapp-studio' ); ?></strong>
					<?php echo esc_html( ( ! empty( $production->error_message ) ? $production->error_message : '' ) ?: __( 'An unexpected error occurred in the current stage.', 'contentosapp-studio' ) ); ?>
				</div>
			</div>
		<?php elseif ( 'cancelled' === $st ) : ?>
			<div class="fos-hero__callout fos-hero__callout--neutral">
				<span style="font-size: 16px">✖️</span>
				<div>
					<strong><?php esc_html_e( 'Produção cancelada', 'contentosapp-studio' ); ?></strong>
					<?php 
					$done = count( array_filter( [ 
						$production->output_01, 
						$production->output_02, 
						$production->output_03, 
						$production->output_04, 
						$production->output_05, 
						$production->output_06,
						$production->output_07
					] ) );
					/* translators: %d: number of agents that completed before cancellation */
					printf( esc_html( _n( 'Cancelada após %d agente já ter finalizado e fica disponível abaixo.', 'Cancelada após %d agentes já terem finalizado e ficam disponíveis abaixo.', $done, 'contentosapp-studio' ) ), (int) $done );
					?>
				</div>
			</div>
		<?php elseif ( 'awaiting_approval' === $st ) : ?>
			<div class="fos-hero__callout">
				<span style="font-size: 16px">💡</span>
				<div>
					<strong><?php esc_html_e( 'Action Required:', 'contentosapp-studio' ); ?></strong>
					<?php esc_html_e( 'The agent has finished the draft and is waiting for your review below.', 'contentosapp-studio' ); ?>
				</div>
			</div>
		<?php elseif ( $is_finalizing ) : ?>
			<div class="fos-hero__callout fos-hero__callout--publishing">
				<span style="font-size: 16px">🚀</span>
				<div>
					<strong><?php esc_html_e( 'Agentes concluídos:', 'contentosapp-studio' ); ?></strong>
					<?php esc_html_e( 'O Contentosapp Studio está renderizando referências, preparando imagens e metadados, e criando o rascunho no WordPress.', 'contentosapp-studio' ); ?>
				</div>
			</div>
		<?php elseif ( 'completed' === $st && ! empty( $production->error_message ) && (
			strpos( $production->error_message, '[WC_WARNING]' ) === 0
			|| strpos( $production->error_message, '[IMG_WARNING]' ) === 0
		) ) :
			// Advisory warnings on completed productions (word count out of range,
			// image generation hiccups). Yellow callout — publication succeeded
			// but something deserves the user's attention.
			$wc_warn   = strpos( $production->error_message, '[WC_WARNING]' ) === 0;
			$msg_clean = trim( preg_replace( '/^\[(WC|IMG)_WARNING\]\s*/', '', $production->error_message ) );
			?>
			<div class="fos-hero__callout fos-hero__callout--warning">
				<span style="font-size: 16px">⚠️</span>
				<div>
					<strong><?php echo esc_html( $wc_warn ? __( 'Atenção — extensão do artigo:', 'contentosapp-studio' ) : __( 'Atenção — geração de imagens:', 'contentosapp-studio' ) ); ?></strong>
					<?php echo esc_html( $msg_clean ); ?>
				</div>
			</div>
		<?php endif; ?>

		<?php // -- Runtime Strip -- ?>
		<?php if ( ! in_array( $st, [ 'completed', 'cancelled' ], true ) ) : ?>
			<div class="fos-hero__runtime">
				<div style="display: flex; align-items: center; gap: 6px;">
					<span style="width: 8px; height: 8px; border-radius: 50%; background: <?php echo esc_attr( 'running' === $st ? '#10B981' : '#6B7280' ); ?>"></span>
					<?php echo esc_html( 'running' === $st ? __( 'Runner Active', 'contentosapp-studio' ) : __( 'Runner Standby', 'contentosapp-studio' ) ); ?>
				</div>
				<span style="opacity: 0.3">|</span>
				<div>
					<?php esc_html_e( 'Environment:', 'contentosapp-studio' ); ?> <code>Production-v3</code>
				</div>
				<div style="margin-left: auto;">
					<button type="button" class="fos-btn fos-btn--sm fos-btn--ghost-white fos-hero__debug-toggle">
						<?php esc_html_e( 'View Technical Logs', '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; margin-left: 4px;"><polyline points="6 9 12 15 18 9"/></svg>
					</button>
				</div>
			</div>
		<?php endif; ?>

	</header>

	<?php
	// ── 5. State router ──────────────────────────────────────────────────────
	switch ( true ) {
		case $st === 'running':
		case $st === 'paused':
		case $st === 'awaiting_approval':
		case $st === 'cancelled': $_state_partial = 'state-running.php'; break;
		case $st === 'completed':       $_state_partial = 'state-completed.php'; break;
		case $st === 'error':           $_state_partial = 'state-error.php'; break;
		case $st === 'pending_upgrade': $_state_partial = 'state-upgrade-required.php'; break;
		default:                        $_state_partial = 'state-pending.php'; break;
	}
	?>

	<?php
	// "View Technical Logs" target panel. state-running.php renders its own
	// #fos-detalhe-debug-content; every other state that still shows the header
	// button (error, pending, pending_upgrade) needs one here, otherwise the
	// toggle finds no element and the click is a silent no-op — worst exactly
	// on failed productions, where the raw adapter trail matters most.
	if ( 'state-running.php' !== $_state_partial && ! in_array( $st, [ 'completed', 'cancelled' ], true ) ) :
		$tech_log_rows = class_exists( 'Costudio_Logger' )
			? Costudio_Logger::query( [ 'production_id' => $production_id, 'limit' => 40 ] )
			: [];
		?>
		<div id="fos-detalhe-debug-content" style="display:none; margin:0 0 20px; background:#fff; border:1px solid var(--fos-border); border-radius:var(--fos-radius-lg); overflow:hidden;">
			<div style="padding:16px 20px 6px; display:grid; grid-template-columns:repeat(4, 1fr); gap:16px;">
				<div class="fos-pipeline-mini-stat">
					<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'Current stage', 'contentosapp-studio' ); ?></div>
					<div class="fos-pipeline-mini-stat__value"><?php echo esc_html( $pipeline_diag['current_stage'] ?? '—' ); ?></div>
				</div>
				<div class="fos-pipeline-mini-stat">
					<div class="fos-pipeline-mini-stat__label"><?php esc_html_e( 'Pending token', 'contentosapp-studio' ); ?></div>
					<div class="fos-pipeline-mini-stat__value"><?php echo esc_html( ! 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 esc_html_e( 'Token source', 'contentosapp-studio' ); ?></div>
					<div class="fos-pipeline-mini-stat__value"><?php echo esc_html( $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"><?php echo esc_html( ! empty( $pipeline_diag['last_heartbeat_at'] ) ? gmdate( 'H:i:s', (int) $pipeline_diag['last_heartbeat_at'] ) : '—' ); ?></div>
				</div>
			</div>
			<div style="padding:10px 20px 16px;">
				<div style="font-size:12px; font-weight:700; color:var(--fos-text); margin-bottom:6px;"><?php esc_html_e( 'Adapter log (raw)', 'contentosapp-studio' ); ?></div>
				<?php if ( ! empty( $tech_log_rows ) ) : ?>
					<div style="font-family:var(--fos-font-mono); font-size:11px; line-height:1.7; max-height:320px; overflow:auto; background:#0F172A; color:#E2E8F0; border-radius:8px; padding:10px 14px;">
						<?php foreach ( array_reverse( $tech_log_rows ) as $tl ) : ?>
							<div style="margin-bottom:2px;">
								<span style="color:#64748B"><?php echo esc_html( (string) $tl->created_at ); ?></span>
								<span style="color:<?php echo esc_attr( 'error' === $tl->level ? '#F87171' : ( 'warn' === $tl->level ? '#FBBF24' : '#38BDF8' ) ); ?>; font-weight:700;"><?php echo esc_html( strtoupper( (string) $tl->level ) ); ?></span>
								<?php if ( ! empty( $tl->agent ) ) : ?>
									<span style="color:#A78BFA">#<?php echo esc_html( str_pad( (string) (int) $tl->agent, 2, '0', STR_PAD_LEFT ) ); ?></span>
								<?php endif; ?>
								<?php echo esc_html( (string) $tl->message ); ?>
								<?php if ( ! empty( $tl->context_json ) && '[]' !== $tl->context_json && '{}' !== $tl->context_json ) : ?>
									<span style="color:#94A3B8"><?php echo esc_html( mb_substr( (string) $tl->context_json, 0, 300 ) ); ?></span>
								<?php endif; ?>
							</div>
						<?php endforeach; ?>
					</div>
				<?php else : ?>
					<div style="color:var(--fos-text-dim); font-size:12px;"><?php esc_html_e( 'No adapter log entries recorded for this production.', 'contentosapp-studio' ); ?></div>
				<?php endif; ?>
			</div>
		</div>
	<?php endif; ?>

	<?php
	require __DIR__ . '/partials/detalhe/' . $_state_partial;
	?>

</div> <!-- .fos-pipeline-timeline -->

<?php // ── ARTICLE PREVIEW MODAL (common to all states) ────────────────────── ?>
<div id="fos-preview-modal" class="fos-modal" style="display:none">
	<div class="fos-modal__backdrop"></div>
	<div class="fos-modal__content" style="max-width:820px;max-height:90vh;overflow:auto">
		<div class="fos-modal__header">
			<h2 id="fos-preview-modal-title"><?php esc_html_e( 'Article Preview', 'contentosapp-studio' ); ?></h2>
			<button type="button" class="fos-modal__close" data-action="fos-modal-close">&times;</button>
		</div>
		<div id="fos-preview-meta" style="padding:0 20px;margin-bottom:12px">
			<table class="fos-preview-meta-table" style="width:100%;border-collapse:collapse;font-size:13px">
				<tr><td style="font-weight:600;padding:4px 8px;width:130px"><?php esc_html_e( 'SEO Title', 'contentosapp-studio' ); ?></td><td id="fos-preview-seo-title" style="padding:4px 8px"></td></tr>
				<tr><td style="font-weight:600;padding:4px 8px"><?php esc_html_e( 'Slug', 'contentosapp-studio' ); ?></td><td id="fos-preview-slug" style="padding:4px 8px;color:#666"></td></tr>
				<tr><td style="font-weight:600;padding:4px 8px"><?php esc_html_e( 'Meta Description', 'contentosapp-studio' ); ?></td><td id="fos-preview-meta-desc" style="padding:4px 8px;color:#666"></td></tr>
				<tr><td style="font-weight:600;padding:4px 8px"><?php esc_html_e( 'Focus Keyword', 'contentosapp-studio' ); ?></td><td id="fos-preview-focus-kw" style="padding:4px 8px;color:#666"></td></tr>
			</table>
		</div>
		<hr style="margin:0 20px">
		<div id="fos-preview-body" class="fos-preview-article-body" style="padding:20px;line-height:1.7;font-size:15px"></div>
	</div>
</div>

<?php // ── AGENT OUTPUT MODAL (View / Edit) ─────────────────────────────────── ?>
<div id="fos-output-modal" class="fos-modal fos-output-inspector" style="display:none" aria-hidden="true">
	<div class="fos-modal__backdrop" data-action="fos-output-inspector-close"></div>
	<div class="fos-modal__content fos-output-inspector__dialog" role="dialog" aria-modal="true" aria-labelledby="fos-output-modal-title" tabindex="-1">
		<header class="fos-output-inspector__header">
			<div class="fos-output-inspector__identity">
				<span class="fos-output-inspector__agent-badge" id="fos-output-agent-badge" aria-hidden="true">01</span>
				<div>
					<p class="fos-output-inspector__eyebrow" id="fos-output-agent-kicker"><?php esc_html_e( 'Saída do agente', 'contentosapp-studio' ); ?></p>
					<h2 id="fos-output-modal-title"><?php esc_html_e( 'Output do Agente', 'contentosapp-studio' ); ?></h2>
				</div>
			</div>
			<button type="button" class="fos-modal__close" data-action="fos-output-inspector-close" aria-label="<?php esc_attr_e( 'Fechar', 'contentosapp-studio' ); ?>">&times;</button>
		</header>

		<div class="fos-output-inspector__meta" id="fos-output-inspector-meta" aria-live="polite"></div>

		<div class="fos-output-inspector__tabs" role="tablist" aria-label="<?php esc_attr_e( 'Modos de visualização', 'contentosapp-studio' ); ?>">
			<button type="button" class="fos-output-inspector__tab is-active" id="fos-output-tab-preview" data-output-tab="preview" role="tab" aria-selected="true" aria-controls="fos-output-panel-preview"><?php esc_html_e( 'Visualização', 'contentosapp-studio' ); ?></button>
			<button type="button" class="fos-output-inspector__tab" id="fos-output-tab-raw" data-output-tab="raw" role="tab" aria-selected="false" aria-controls="fos-output-panel-raw"><?php esc_html_e( 'Texto bruto', 'contentosapp-studio' ); ?></button>
			<button type="button" class="fos-output-inspector__tab" id="fos-output-tab-edit" data-output-tab="edit" role="tab" aria-selected="false" aria-controls="fos-output-panel-edit"><?php esc_html_e( 'Editar', 'contentosapp-studio' ); ?></button>
		</div>

		<div class="fos-output-inspector__body">
			<section id="fos-output-panel-preview" class="fos-output-inspector__panel is-active" role="tabpanel" aria-labelledby="fos-output-tab-preview">
				<div id="fos-output-view-wrap">
					<div id="fos-output-inspector-structured"></div>
					<div id="fos-output-inspector-toc" hidden></div>
					<div id="fos-output-body-html" class="fos-preview-article-body"></div>
				</div>
			</section>
			<section id="fos-output-panel-raw" class="fos-output-inspector__panel" role="tabpanel" aria-labelledby="fos-output-tab-raw" hidden>
				<pre id="fos-output-raw" class="fos-output-inspector__raw"></pre>
			</section>
			<section id="fos-output-panel-edit" class="fos-output-inspector__panel" role="tabpanel" aria-labelledby="fos-output-tab-edit" hidden>
				<div id="fos-output-edit-wrap">
					<textarea id="fos-output-editor" class="cts-input" aria-label="<?php esc_attr_e( 'Markdown bruto do agente', 'contentosapp-studio' ); ?>"></textarea>
					<p class="fos-output-inspector__hint">💡 <?php esc_html_e( 'Você está editando o Markdown bruto deste agente. Salve para aplicar as mudanças ao pipeline.', 'contentosapp-studio' ); ?></p>
				</div>
			</section>
		</div>

		<div class="fos-modal__footer fos-output-inspector__footer">
			<button type="button" class="fos-btn fos-btn--ghost" id="fos-output-copy-btn">
				<span class="fos-btn__icon">📋</span>
				<span class="fos-btn__text"><?php esc_html_e( 'Copiar', 'contentosapp-studio' ); ?></span>
			</button>
			<button type="button" class="fos-btn fos-btn--ghost" data-action="fos-output-inspector-close"><?php esc_html_e( 'Fechar', 'contentosapp-studio' ); ?></button>
			<button type="button" class="fos-btn fos-btn--primary" id="fos-output-save-btn" hidden>
				<span class="fos-btn__icon">💾</span>
				<span class="fos-btn__text"><?php esc_html_e( 'Salvar Alterações', 'contentosapp-studio' ); ?></span>
			</button>
		</div>
	</div>
</div>

<?php if ( 'pending_upgrade' === $st ) : ?>
	<?php include __DIR__ . '/partials/modal-buy-addon.php'; ?>
<?php endif; ?>

<?php // ── DATA ATTRIBUTES for JS polling ────────────────────────────────── ?>
<div id="fos-detalhe-data"
	style="display:none"
	data-production-id="<?php echo (int) $production_id; ?>"
	data-status="<?php echo esc_attr( $st ); ?>"
	data-total-processing-s="<?php echo (int) $total_processing_s; ?>"
	data-elapsed-total-s="<?php echo (int) $elapsed_total_s; ?>"
	data-nonce="<?php echo esc_attr( $nonce ); ?>"
	data-hub-url="<?php echo esc_url( $hub_url ); ?>"
	data-started-at="<?php echo (int) ( ! empty( $production->started_at ) ? strtotime( $production->started_at . ' UTC' ) : 0 ); ?>"
	data-current-agent="<?php echo (int) $current_agent; ?>"
	data-current-agent-started-at="<?php echo (int) ( ! empty( $production->current_agent_started_at ) ? strtotime( $production->current_agent_started_at . ' UTC' ) : 0 ); ?>"
	data-current-agent-elapsed-s="<?php echo (int) $production->get_current_agent_elapsed_seconds(); ?>"
	data-agent-qty="<?php echo (int) $agent_qty; ?>"
	data-agent-defs="<?php echo esc_attr( wp_json_encode( $agent_defs ) ); ?>"
	data-provider-label="<?php echo esc_attr( $provider_lbl ); ?>">
</div>
