<?php
/**
 * Partial — Production detail, UPGRADE REQUIRED state.
 *
 * Rendered when the ContentOS Auto managed service returned a service-side error
 * (e.g. monthly quota exhausted, site limit exceeded). The production is in
 * status 'pending_upgrade'; no retry makes sense until the service condition is resolved.
 *
 * @package Contentosapp_Studio
 * @since   1.2.9
 *
 * Expected scope (inherited from page-detalhe.php):
 *   @var object $production
 *   @var int    $production_id
 *   @var string $nonce
 *   @var int    $error_agent
 *   @var array  $agent_defs
 *   @var array  $word_counts
 *   @var string $article_type
 *   @var string $ai_model
 *   @var int    $agent_qty
 *   @var array  $pipeline_log
 */

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

// ── Decode managed-service context from error_message ────────────────────────
$_raw_ctx     = (string) ( $production->error_message ?? '' );
$_ctx         = json_decode( $_raw_ctx, true );
$_upg_code    = is_array( $_ctx ) ? ( $_ctx['code']        ?? 'quota_exceeded' ) : 'quota_exceeded';
$_upg_message = is_array( $_ctx ) ? ( $_ctx['message']     ?? '' )               : $_raw_ctx;
$_upg_url     = is_array( $_ctx ) ? ( $_ctx['upgrade_url'] ?? '' )               : '';
if ( empty( $_upg_url ) ) {
	$_upg_url = 'https://contentosapp.com/#pricing';
}
if ( empty( $_upg_message ) ) {
	$_upg_message = __( 'ContentOS Auto managed-service quota reached. BYOK remains available with your own provider key.', 'contentosapp-studio' );
}

$_agent_qty = isset( $agent_qty ) ? (int) $agent_qty : count( $agent_defs );

// Show "Buy extra credits" only for quota_exceeded on a paid plan (Pro/Studio).
// site_limit_exceeded is a managed-service activation limit; addons don't help there.
$_can_buy_addon = ( 'quota_exceeded' === $_upg_code )
    && costudio_license() !== null
    && costudio_license()->is_valid();
?>

<?php // ── 1. Service limit hero ──────────────────────────────────────────── ?>
<div style="background:linear-gradient(135deg,#EEF2FF,#F5F3FF); border:1px solid #C7D2FE; border-radius:var(--fos-radius-lg); padding:20px 24px; display:flex; gap:16px; align-items:center;">
	<div style="font-size:36px; line-height:1;">💎</div>
	<div style="flex:1;">
		<div style="font-size:10px; font-weight:700; color:#6366F1; text-transform:uppercase; letter-spacing:0.8px; margin-bottom:4px;">
			<?php esc_html_e( 'Managed service quota needs attention', '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:#6366F1; line-height:1.5;">
			<?php esc_html_e( 'Production paused — managed service limit reached.', 'contentosapp-studio' ); ?>
		</div>
	</div>
</div>

<?php // ── 2. Service limit card ──────────────────────────────────────────── ?>
<div style="background:#fff; border:1px solid #C7D2FE; border-left:4px solid #6366F1; border-radius:12px; padding:20px 24px;">
	<div style="font-size:13px; color:var(--fos-text); line-height:1.6; margin-bottom:16px;">
		<?php echo esc_html( $_upg_message ); ?>
	</div>
	<div style="font-size:12.5px; color:var(--fos-text-sub); margin-bottom:20px; line-height:1.5;">
		<?php esc_html_e( 'Review your ContentOS Auto service quota, or switch to BYOK below and click "Retry Agent" on the paused stage to resume with your own key.', 'contentosapp-studio' ); ?>
	</div>
	<div style="display:flex; gap:10px; flex-wrap:wrap; align-items:center;">
		<a href="<?php echo esc_url( $_upg_url ); ?>" target="_blank" rel="noopener noreferrer"
		   class="fos-service-plan-link"
		   style="display:inline-flex; align-items:center; gap:6px; background:#6366F1; color:#fff; font-size:13px; font-weight:600; padding:9px 18px; border-radius:8px; text-decoration:none; border:none; cursor:pointer; transition:opacity 0.15s ease;">
			💎 <?php esc_html_e( 'Manage service plan', 'contentosapp-studio' ); ?>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="opacity:0.8"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
		</a>
		<?php if ( $_can_buy_addon ) : ?>
		<button type="button"
		        class="fos-service-addon-btn js-costudio-open-addon-modal"
		        style="display:inline-flex; align-items:center; gap:6px; background:#fff; color:#6366F1; font-size:13px; font-weight:600; padding:9px 18px; border-radius:8px; border:2px solid #6366F1; cursor:pointer; transition:background 0.15s ease;">
			⚡ <?php esc_html_e( 'Buy extra credits', 'contentosapp-studio' ); ?>
		</button>
		<?php endif; ?>
		<a href="<?php echo esc_url( admin_url( 'admin.php?page=costudio-settings&tab=ai' ) ); ?>"
		   class="fos-service-byok-link"
		   style="display:inline-flex; align-items:center; gap:6px; background:#fff; color:var(--fos-text); font-size:13px; font-weight:500; padding:9px 18px; border-radius:8px; text-decoration:none; border:1px solid var(--fos-border); cursor:pointer; transition:background 0.15s ease;">
			🔑 <?php esc_html_e( 'Switch to BYOK', 'contentosapp-studio' ); ?>
		</a>
		<button type="button" class="fos-btn fos-btn--ghost fos-btn--sm fos-delete-btn"
		        data-id="<?php echo (int) $production_id; ?>"
		        style="margin-left:auto; color:var(--fos-danger); border-color:var(--fos-danger);">
			<?php esc_html_e( 'Discard production', 'contentosapp-studio' ); ?>
		</button>
	</div>
</div>

<?php // ── 3. Pipeline progress (stages completed before limit) ────────────── ?>
<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 progress', '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 limit was reached', 'contentosapp-studio' ); ?>
		</span>
	</div>

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

		$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' => __( 'Paused', 'contentosapp-studio' ), 'bg' => '#EEF2FF', 'fg' => '#6366F1', 'dot' => '#6366F1', '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-upg-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"><?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>
					<?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 Agent', '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 ) : ?>
				<div class="fos-pipeline-row__details" id="<?php echo esc_attr( $output_id ); ?>" style="display:none;">
					<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"><?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>
					<?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>
					</div>
				</div>
			<?php endif; ?>
		</div>
	<?php endforeach; ?>
</div>

<?php // ── 4. 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-upg-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-upg-log-content" class="fos-log-content">
		<div id="fos-detalhe-debug-log-body">
			<?php
			if ( ! empty( $pipeline_log ) ) :
				foreach ( $pipeline_log as $entry ) :
					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' );
					$lvl_class = 'fos-log-level--' . strtolower( $entry['level'] ?? 'info' );
					$agent_lbl = ! empty( $entry['agent'] ) ? sprintf( '#%02d', $entry['agent'] ) : '';
					$msg_lbl   = $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_lbl ) : ?>
						<span class="fos-log-agent"><?php echo esc_html( $agent_lbl ); ?></span>
					<?php endif; ?>
					<span class="fos-log-msg"><?php echo esc_html( $msg_lbl ); ?></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>
