<?php

/**
 * Contentosapp Studio Standalone License Page
 *
 * @package Contentosapp_Studio
 * @since   1.0.0
 */

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

$license_service = Costudio_Standalone_License::get_instance();
$current_plan    = $license_service->get_plan();
$has_paid_service_plan = $license_service->is_valid();

// Data for stats
$this_month  = Costudio_Standalone_License::get_monthly_count();
$byok_month  = Costudio_Standalone_License::get_monthly_byok_count();
$total       = Costudio_Production::count_all();
$hours_saved = round($total * 3.7);
$_lic_sites_repo = costudio_sites();
$sites_count     = $_lic_sites_repo ? count($_lic_sites_repo->get_all()) : 0;

$limit_monthly = $license_service->get_api_production_limit();
$limit_sites_label = __( 'Unlimited', 'contentosapp-studio' );
$bar_pct       = min(100, round(($this_month / $limit_monthly) * 100));

// Quota reset date: always the 1st of next month.
$reset_date        = gmdate( 'Y-m-01', strtotime( 'first day of next month' ) );
$reset_date_format = date_i18n( get_option( 'date_format' ), strtotime( $reset_date ) );

// Extra Quotas (addon) — populated by sync_remote_usage() from server's /quota response.
// Card only renders when the ContentOS Auto service reports addon eligibility.
//
// Lazy-init: if the addon transient was never set (first page load after
// upgrading to the addon-aware client), force a single remote sync so the
// page reflects current state instead of the cached defaults. After the first
// sync the transient persists for an hour and this branch is skipped.
if ( false === get_transient( 'costudio_addon_balance' ) && ! empty( get_option( Costudio_Standalone_License::OPT_KEY, '' ) ) ) {
	Costudio_Standalone_License::sync_remote_usage( true );
}
$addon_balance = Costudio_Standalone_License::get_addon_balance();
$addon_visible = ! empty( $addon_balance['enabled'] );

$plan_icon_map = array(
	Costudio_Standalone_License::PLAN_FREE     => 'awards',
	Costudio_Standalone_License::PLAN_STARTER => 'admin-site-alt3',
	'pro'                                      => 'shield-alt',
	'studio'                                   => 'star-filled',
);
$current_plan_icon = $plan_icon_map[ $current_plan ] ?? 'awards';

// Lifetime Free trial accounting (server-synced, see CAP_Quota 'lifetime' bucket).
// For the Free plan the quota is a one-time trial, not a monthly allowance.
$trial_limit     = $limit_monthly; // 3 for Free.
$trial_remaining = $license_service->get_trial_remaining();
$trial_used      = max( 0, $trial_limit - $trial_remaining );
$trial_exhausted = ( $current_plan === Costudio_Standalone_License::PLAN_FREE && $trial_remaining <= 0 );
$trial_pct       = $trial_limit > 0 ? min( 100, (int) round( ( $trial_used / $trial_limit ) * 100 ) ) : 0;

// Contextual BYOK upsell: set by the pipeline when a BYOK provider returns 429.
// Reuses an existing transient — no parallel state. Moderate (Guideline 11).
$byok_rate_limited = get_transient( 'costudio_byok_rate_limited' );
$byok_upsell_show  = is_array( $byok_rate_limited ) && ! empty( $byok_rate_limited['provider'] );

// URLs
$store_url   = 'https://contentosapp.com/#pricing'; // New-purchase / public pricing section (landing page anchor).
$account_url = 'https://contentosapp.com/account'; // Existing customers: licenses + upgrade (proration) + billing.

/*
 * Per-tier value matrix (Fluxo 2). Hardcoded canonical product spec — every
 * differentiated line below is delivered by ContentOS Auto (our managed
 * service, which may be tiered). BYOK (your own API key) is unlimited and
 * identical on every plan, so the "universal" group is never plan-gated.
 */
$costudio_plan_matrix = array(
	'free' => array(
		'quota'    => 3,
		'research' => __( 'Real web research grounding every article', 'contentosapp-studio' ),
		'images'   => __( '1 original cover image, generated for you', 'contentosapp-studio' ),
		'priority' => false,
		'check'    => 'green',
	),
	'starter' => array(
		'quota'    => 5,
		'research' => __( 'Web research that grounds every article (~6 sources)', 'contentosapp-studio' ),
		'images'   => __( '1 original cover image per article', 'contentosapp-studio' ),
		'priority' => false,
		'check'    => 'green',
	),
	'pro' => array(
		'quota'    => 30,
		'research' => __( 'In-depth, fact-checked research (~10 vetted sources)', 'contentosapp-studio' ),
		'images'   => __( '3 high-quality images per article', 'contentosapp-studio' ),
		'priority' => false,
		'check'    => 'primary',
	),
	'studio' => array(
		'quota'    => 100,
		'research' => __( 'Our deepest research, for maximum authority (~16 sources)', 'contentosapp-studio' ),
		'images'   => __( '5 premium, highest-fidelity images per article', 'contentosapp-studio' ),
		'priority' => true,
		'check'    => 'green',
	),
);

// One-paragraph clarifier so the Auto-vs-BYOK value framing is unmistakable.
$costudio_byok_note = __( 'ContentOS Auto is our fully-managed service — no API keys, no setup. Higher tiers research deeper and generate more images for you. Prefer your own keys? BYOK delivers unlimited output on every plan, and lets you pick any model yourself.', 'contentosapp-studio' );

/**
 * Render the grouped feature list (ContentOS Auto + "every plan") for a plan
 * card in the comparison. Kept local to this template.
 *
 * @param string $plan   starter|pro|studio
 * @param array  $matrix The $costudio_plan_matrix.
 */
if ( ! function_exists( 'costudio_render_plan_features' ) ) {
	function costudio_render_plan_features( string $plan, array $matrix ): void {
		$m     = $matrix[ $plan ] ?? $matrix['free'];
		$check = 'fos-lic-feature-check--' . ( $m['check'] ?? 'green' );
		$row   = static function ( string $text, string $check, bool $muted = false ) {
			$cls = 'fos-lic-feature-check ' . ( $muted ? 'fos-lic-feature-check--muted' : $check );
			echo '<li class="fos-lic-plan-feature"><div class="' . esc_attr( $cls ) . '">' . ( $muted ? '·' : '✓' ) . '</div>' . esc_html( $text ) . '</li>';
		};
		// Sales narrative is outcome-driven: we never name the underlying AI model
		// (it is a server-side choice we keep free to change). The value ladder is
		// quota → research depth → images → priority. See pricing-matrix-final.
		?>
		<li class="fos-lic-feat-group"><?php esc_html_e( 'Done for you', 'contentosapp-studio' ); ?></li>
		<?php
		if ( 'free' === $plan ) {
			$row(
				sprintf(
					/* translators: %d: number of one-time premium articles done for you on the Free plan. */
					__( '%d premium articles done for you (one-time)', 'contentosapp-studio' ),
					(int) $m['quota']
				),
				$check
			);
		} else {
			$row(
				sprintf(
					/* translators: %d: number of ready-to-publish articles produced for you each month. */
					__( '%d ready-to-publish articles, every month', 'contentosapp-studio' ),
					(int) $m['quota']
				),
				$check
			);
		}
		// Value ladder: quota -> research depth -> images -> priority.
		$row( (string) $m['research'], $check );
		$row( (string) $m['images'], $check );
		if ( ! empty( $m['priority'] ) ) {
			$row( __( 'Priority processing — your jobs always run first', 'contentosapp-studio' ), $check );
		}

		// Universal value: full trio on Free (sells the zero-risk entry), one
		// compact reminder line on paid tiers to avoid repeating it four times.
		if ( 'free' === $plan ) {
			?>
			<li class="fos-lic-feat-group"><?php esc_html_e( 'Every plan includes', 'contentosapp-studio' ); ?></li>
			<?php
			$row( __( 'Unlimited articles with BYOK (your own key)', 'contentosapp-studio' ), 'fos-lic-feature-check--green' );
			$row( __( 'Unlimited connected sites', 'contentosapp-studio' ), 'fos-lic-feature-check--green' );
			$row( __( 'Fully customizable agents', 'contentosapp-studio' ), 'fos-lic-feature-check--green' );
		} else {
			$row( __( 'Plus unlimited BYOK, unlimited sites and customizable agents', 'contentosapp-studio' ), $check, true );
		}
	}
}

?>

<div class="wrap fos-standalone-wrap">

    <!-- ── PAGE HEADER ─────────────────────────────────────────────────────── -->
    <?php
    $costudio_header_title    = __( 'Contentosapp Studio', 'contentosapp-studio' );
    $costudio_header_subtitle = __( 'Global AI-powered content production pipeline with 7 specialized agents', 'contentosapp-studio' );
    $costudio_logo_mark_path  = COSTUDIO_DIR . 'assets/images/costudio-logo-mark.png';
    $costudio_header_icon_url = COSTUDIO_URL . 'assets/images/costudio-logo-mark.png';
    $costudio_header_classes  = 'fos-license-page-header';
    if ( is_readable( $costudio_logo_mark_path ) && filesize( $costudio_logo_mark_path ) <= 128 * 1024 ) {
        $costudio_header_icon_url = 'data:image/png;base64,' . base64_encode( file_get_contents( $costudio_logo_mark_path ) );
    }
    $costudio_header_right    = '<span id="fos-plan-badge-header" class="cts-badge ' . ( $has_paid_service_plan ? 'cts-badge--success' : 'cts-badge--neutral' ) . '">'
        . esc_html( strtoupper( $current_plan ) ) . '</span>';
    include __DIR__ . '/../partials/partial-page-header.php';
    ?>

    <?php if ( $byok_upsell_show ) : ?>
        <!-- Contextual BYOK rate-limit upsell (set by the pipeline on provider 429). -->
        <div class="fos-lic-byok-note fos-lic-byok-note--upsell">
            <span class="fos-lic-byok-note-icon" aria-hidden="true">⏳</span>
            <span>
                <?php
                printf(
                    /* translators: %s: BYOK provider name (e.g. Gemini, OpenAI). */
                    esc_html__( 'Your own %s key just hit a rate limit. ContentOS Auto runs on our managed infrastructure — no provider limits to manage. Compare plans below.', 'contentosapp-studio' ),
                    esc_html( ucfirst( (string) $byok_rate_limited['provider'] ) )
                );
                ?>
            </span>
        </div>
    <?php endif; ?>

    <?php if ($has_paid_service_plan) : ?>
        <!-- STATE 2 — PAID PLAN ACTIVE -->
        <div id="state-paid">
            <div class="fos-lic-license-hero">
                <div class="fos-lic-license-hero-top">
                    <div class="fos-lic-lh-plan-info">
                        <div class="fos-lic-lh-plan-icon fos-lic-lh-plan-icon--<?php echo esc_attr( $current_plan ); ?>" aria-hidden="true">
                            <span class="dashicons dashicons-<?php echo esc_attr( $current_plan_icon ); ?>"></span>
                        </div>
                        <div>
                            <div class="fos-lic-lh-plan-label"><?php esc_html_e('Current plan', 'contentosapp-studio'); ?></div>
                            <div class="fos-lic-lh-plan-name"><?php echo esc_html( ucfirst( $current_plan ) ); ?></div>
                        </div>
                    </div>
                    <div class="fos-lic-lh-status">
                        <div class="fos-lic-lh-status-dot"></div>
                        <div class="fos-lic-lh-status-text"><?php esc_html_e('License active', 'contentosapp-studio'); ?></div>
                    </div>
                </div>
                <div class="fos-lic-license-stats">
                    <div class="fos-lic-license-stat">
                        <div class="fos-lic-ls-label"><?php esc_html_e('Auto / month', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-ls-value green" id="fos-lic-monthly-usage">
                            <span class="fos-lic-usage-num"><?php echo esc_html( $this_month ); ?></span> / <span class="fos-lic-limit-num"><?php echo esc_html( $limit_monthly ); ?></span>
                            <button type="button" class="fos-lic-sync-btn" id="fos-lic-sync-btn" title="<?php esc_attr_e('Sync with server', 'contentosapp-studio'); ?>">
                                <span class="dashicons dashicons-update"></span>
                            </button>
                        </div>
                        <div class="fos-lic-ls-sub" id="fos-lic-monthly-reset"><?php
                        /* translators: %s: human-formatted date when the quota resets */
                        printf( esc_html__( 'Resets %s', 'contentosapp-studio' ), esc_html( $reset_date_format ) ); ?></div>
                    </div>
                    <div class="fos-lic-license-stat">
                        <div class="fos-lic-ls-label"><?php esc_html_e('BYOK / month', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-ls-value purple">∞ <?php esc_html_e('Unlimited', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-ls-sub"><?php esc_html_e('Your own API key', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-license-stat">
                        <div class="fos-lic-ls-label"><?php esc_html_e('Connected sites', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-ls-value"><?php echo esc_html($sites_count); ?> / <?php echo esc_html($limit_sites_label); ?></div>
                        <div class="fos-lic-ls-sub"><?php esc_html_e('Connected sites', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-license-stat">
                        <div class="fos-lic-ls-label"><?php esc_html_e('Hours saved', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-ls-value green"><?php echo esc_html($hours_saved); ?>h</div>
                        <div class="fos-lic-ls-sub"><?php
                        /* translators: %d: number of articles produced */
                        printf( esc_html__('%d articles × 3.7h', 'contentosapp-studio'), (int) $total ); ?></div>
                    </div>
                </div>
            </div>

            <?php if ( $addon_visible ) : ?>
            <!-- ── EXTRA QUOTAS (addon) — Sprint B.1 ───────────────────────────── -->
            <div class="fos-lic-addon-card" id="fos-addon-card">
                <div class="fos-lic-addon-header">
                    <div class="fos-lic-addon-icon">⚡</div>
                    <div class="fos-lic-addon-title-block">
                        <div class="fos-lic-addon-title"><?php esc_html_e( 'Extra Quotas', 'contentosapp-studio' ); ?></div>
                        <div class="fos-lic-addon-subtitle"><?php esc_html_e( 'Buy additional article credits when you need to publish more than your monthly plan allows.', 'contentosapp-studio' ); ?></div>
                    </div>
                    <button type="button" class="fos-lic-addon-buy-btn" id="fos-addon-buy-btn">
                        <span class="dashicons dashicons-cart"></span>
                        <?php esc_html_e( 'Buy more credits', 'contentosapp-studio' ); ?>
                    </button>
                </div>

                <div class="fos-lic-addon-body">
                    <?php if ( (int) $addon_balance['balance'] > 0 || (int) $addon_balance['total_purchased'] > 0 ) : ?>
                        <div class="fos-lic-addon-stats">
                            <div class="fos-lic-addon-stat">
                                <div class="fos-lic-addon-stat-label"><?php esc_html_e( 'Available balance', 'contentosapp-studio' ); ?></div>
                                <div class="fos-lic-addon-stat-value purple" id="fos-lic-addon-balance"><?php echo (int) $addon_balance['balance']; ?></div>
                                <div class="fos-lic-addon-stat-sub"><?php esc_html_e( 'credits ready to use', 'contentosapp-studio' ); ?></div>
                            </div>
                            <div class="fos-lic-addon-stat">
                                <div class="fos-lic-addon-stat-label"><?php esc_html_e( 'Lifetime purchased', 'contentosapp-studio' ); ?></div>
                                <div class="fos-lic-addon-stat-value"><?php echo (int) $addon_balance['total_purchased']; ?></div>
                                <div class="fos-lic-addon-stat-sub"><?php esc_html_e( 'credits bought to date', 'contentosapp-studio' ); ?></div>
                            </div>
                            <div class="fos-lic-addon-stat">
                                <div class="fos-lic-addon-stat-label"><?php esc_html_e( 'Lifetime consumed', 'contentosapp-studio' ); ?></div>
                                <div class="fos-lic-addon-stat-value"><?php echo (int) $addon_balance['total_consumed']; ?></div>
                                <div class="fos-lic-addon-stat-sub"><?php esc_html_e( 'credits used so far', 'contentosapp-studio' ); ?></div>
                            </div>
                            <?php if ( ! empty( $addon_balance['last_purchase_at'] ) ) : ?>
                                <div class="fos-lic-addon-stat">
                                    <div class="fos-lic-addon-stat-label"><?php esc_html_e( 'Last purchase', 'contentosapp-studio' ); ?></div>
                                    <div class="fos-lic-addon-stat-value small">
                                        <?php
                                        $ts = strtotime( (string) $addon_balance['last_purchase_at'] );
                                        echo esc_html( $ts ? date_i18n( get_option( 'date_format' ), $ts ) : '—' );
                                        ?>
                                    </div>
                                    <div class="fos-lic-addon-stat-sub"><?php esc_html_e( 'most recent transaction', 'contentosapp-studio' ); ?></div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <button type="button" class="fos-lic-addon-history-toggle" id="fos-addon-history-toggle" aria-expanded="false">
                            <span class="dashicons dashicons-arrow-down-alt2"></span>
                            <?php esc_html_e( 'View purchase history', 'contentosapp-studio' ); ?>
                        </button>

                        <div class="fos-lic-addon-history" id="fos-addon-history" hidden>
                            <div class="fos-lic-addon-history-loading"><?php esc_html_e( 'Loading history...', 'contentosapp-studio' ); ?></div>
                        </div>

                    <?php else : ?>
                        <div class="fos-lic-addon-empty">
                            <div class="fos-lic-addon-empty-icon">🛒</div>
                            <div class="fos-lic-addon-empty-text">
                                <strong><?php esc_html_e( 'No extra credits purchased yet.', 'contentosapp-studio' ); ?></strong>
                                <br>
                                <?php esc_html_e( 'Buy a pack when you need to publish more than your monthly plan allows. Credits never expire.', 'contentosapp-studio' ); ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="fos-lic-details-grid">
                <div class="fos-lic-detail-card">
                    <div class="fos-lic-detail-card-title">🔑 <?php esc_html_e('License data', 'contentosapp-studio'); ?></div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Key', 'contentosapp-studio'); ?></span>
                        <?php $display_license_key = (string) get_option( 'costudio_license_commercial_key', get_option( 'costudio_license_key', '' ) ); ?>
                        <span class="fos-lic-detail-val">XXXX-XXXX-XXXX-<?php echo esc_html(substr($display_license_key, -4)); ?></span>
                    </div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Email', 'contentosapp-studio'); ?></span>
                        <?php $display_license_email = (string) get_option( 'costudio_license_email', '' ); ?>
                        <span class="fos-lic-detail-val normal">
                            <?php echo esc_html( $display_license_email ? $display_license_email : __( 'Not available', 'contentosapp-studio' ) ); ?>
                        </span>
                    </div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Plan', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val normal"><?php echo esc_html( ucfirst( $current_plan ) ); ?></span>
                    </div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Status', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-badge-active"><?php esc_html_e('Active', 'contentosapp-studio'); ?></span>
                    </div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Activated on', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val normal"><?php echo esc_html( date_i18n(get_option('date_format'), get_option('costudio_activated_at', time())) ); ?></span>
                    </div>
                </div>
                <div class="fos-lic-detail-card">
                    <div class="fos-lic-detail-card-title">⚡ <?php esc_html_e('What your ContentOS Auto delivers', 'contentosapp-studio'); ?></div>
                    <?php $costudio_cur = $costudio_plan_matrix[ $current_plan ] ?? $costudio_plan_matrix['pro']; ?>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Research', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val green"><?php echo esc_html( $costudio_cur['research'] ); ?></span>
                    </div>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('AI images', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val green"><?php echo esc_html( $costudio_cur['images'] ); ?></span>
                    </div>
                    <?php if ( ! empty( $costudio_cur['priority'] ) ) : ?>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('Priority processing', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val green"><?php esc_html_e('Enabled', 'contentosapp-studio'); ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="fos-lic-detail-row">
                        <span class="fos-lic-detail-key"><?php esc_html_e('BYOK (your own key)', 'contentosapp-studio'); ?></span>
                        <span class="fos-lic-detail-val green"><?php esc_html_e('Unlimited · all features', 'contentosapp-studio'); ?></span>
                    </div>
                </div>
            </div>

            <!-- Auto vs BYOK clarifier -->
            <div class="fos-lic-byok-note">
                <span class="fos-lic-byok-note-icon" aria-hidden="true">💡</span>
                <span><?php echo esc_html( $costudio_byok_note ); ?></span>
            </div>

            <?php if ( $current_plan === 'starter' ) : ?>
                <!-- Starter → Pro service plan offer (moderate, Guideline 11) -->
                <div class="fos-lic-migration-card">
                    <div class="fos-lic-migration-header">
                        <div class="fos-lic-migration-icon">⭐</div>
                        <div>
                            <div class="fos-lic-migration-title"><?php esc_html_e('Ready for more done-for-you articles?', 'contentosapp-studio'); ?></div>
                            <div class="fos-lic-migration-desc">
                                <?php esc_html_e('Pro raises your ContentOS Auto quota to 30/month, with deeper research and 3 AI images per article.', 'contentosapp-studio'); ?>
                            </div>
                        </div>
                    </div>
                    <div class="fos-lic-migration-footer">
                        <div class="fos-lic-migration-promo">
                            🚀 <?php esc_html_e('Pro Plan: $49/month or $490/year', 'contentosapp-studio'); ?>
                        </div>
                        <a href="<?php echo esc_url($account_url); ?>" target="_blank" class="fos-lic-btn-migrate"><?php esc_html_e('Manage service plan →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>
            <?php elseif ( $current_plan === 'pro' ) : ?>
                <!-- Pro → Studio service plan offer -->
                <div class="fos-lic-migration-card">
                    <div class="fos-lic-migration-header">
                        <div class="fos-lic-migration-icon">⭐</div>
                        <div>
                            <div class="fos-lic-migration-title"><?php esc_html_e('Ready to scale your production?', 'contentosapp-studio'); ?></div>
                            <div class="fos-lic-migration-desc">
                                <?php esc_html_e('Higher managed-service quota for ContentOS Auto.', 'contentosapp-studio'); ?>
                            </div>
                        </div>
                    </div>
                    <div class="fos-lic-migration-footer">
                        <div class="fos-lic-migration-promo">
                            🚀 <?php esc_html_e('Studio Plan: $129/month or $1290/year', 'contentosapp-studio'); ?>
                        </div>
                        <a href="<?php echo esc_url($account_url); ?>" target="_blank" class="fos-lic-btn-migrate"><?php esc_html_e('Manage service plan →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>
            <?php endif; ?>

            <div class="fos-lic-account-card">
                <div class="fos-lic-account-card__header">
                    <span aria-hidden="true">⚙️</span>
                    <span class="fos-lic-account-card__title"><?php esc_html_e( 'Account management', 'contentosapp-studio' ); ?></span>
                </div>

                <div class="fos-lic-account-row">
                    <div class="fos-lic-account-row__icon fos-lic-account-row__icon--primary" aria-hidden="true">💳</div>
                    <div class="fos-lic-account-row__body">
                        <div class="fos-lic-account-row__title"><?php esc_html_e( 'Manage license', 'contentosapp-studio' ); ?></div>
                        <div class="fos-lic-account-row__desc"><?php esc_html_e( 'Cancel subscription, update payment method or download invoices.', 'contentosapp-studio' ); ?></div>
                    </div>
                    <button type="button" class="fos-lic-btn-manage" id="fos-manage-subscription-btn">
                        <?php esc_html_e( 'Manage license →', 'contentosapp-studio' ); ?>
                    </button>
                </div>

                <div class="fos-lic-account-row">
                    <div class="fos-lic-account-row__icon fos-lic-account-row__icon--neutral" aria-hidden="true">🔌</div>
                    <div class="fos-lic-account-row__body">
                        <div class="fos-lic-account-row__title"><?php esc_html_e( 'Deactivate on this site', 'contentosapp-studio' ); ?></div>
                        <div class="fos-lic-account-row__desc"><?php esc_html_e( 'Frees up an activation slot for another site. Your data will not be deleted.', 'contentosapp-studio' ); ?></div>
                    </div>
                    <button type="button" class="fos-lic-btn-deactivate" id="fos-license-deactivate-btn">
                        <?php esc_html_e( 'Deactivate', 'contentosapp-studio' ); ?>
                    </button>
                </div>
            </div>
        </div>

    <?php else : ?>
        <!-- STATE 1 — managed service Free plan (lifetime premium trial) -->
        <?php
        // Lazy-init: refresh the lifetime trial counter from the server once.
        // Free has no Bearer key, so sync runs anonymously via site_url. The
        // transient self-expires hourly so we don't re-hit the endpoint per load.
        if ( false === get_transient( 'costudio_remote_usage_count' ) ) {
            Costudio_Standalone_License::sync_remote_usage( true );
            $trial_remaining = $license_service->get_trial_remaining();
            $trial_used      = max( 0, $trial_limit - $trial_remaining );
            $trial_exhausted = ( $trial_remaining <= 0 );
            $trial_pct       = $trial_limit > 0 ? min( 100, (int) round( ( $trial_used / $trial_limit ) * 100 ) ) : 0;
        }
        ?>
        <div id="state-free">
            <!-- Usage mini-hero -->
            <div class="fos-lic-usage-hero">
                <div class="fos-lic-usage-hero-top">
                    <div class="fos-lic-plan-info">
                        <div class="fos-lic-plan-icon fos-lic-plan-icon--free" aria-hidden="true">
                            <span class="dashicons dashicons-awards"></span>
                        </div>
                        <div>
                            <div class="fos-lic-plan-label"><?php esc_html_e('Current plan', 'contentosapp-studio'); ?></div>
                            <div class="fos-lic-plan-name"><?php esc_html_e('Free', 'contentosapp-studio'); ?></div>
                        </div>
                    </div>
                    <div class="fos-lic-status">
                        <div class="fos-lic-status-dot"></div>
                        <div class="fos-lic-status-text"><?php esc_html_e('Free plan', 'contentosapp-studio'); ?></div>
                    </div>
                </div>
                <div class="fos-lic-usage-stats">
                    <div class="fos-lic-usage-stat">
                        <div class="fos-lic-us-label"><?php esc_html_e('Premium trial', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-us-value <?php echo esc_attr( $trial_exhausted ? 'fos-text-danger' : 'green' ); ?>"><?php echo esc_html( $trial_used ); ?> / <?php echo esc_html( $trial_limit ); ?></div>
                        <?php if ( $trial_exhausted ) : ?>
                            <div class="fos-lic-us-sub fos-text-danger" style="font-weight:600"><?php esc_html_e('Trial used', 'contentosapp-studio'); ?></div>
                        <?php else : ?>
                            <div class="fos-lic-us-sub"><?php
                            printf(
								/* translators: %d: remaining one-time premium trial articles via ContentOS Auto. */
								esc_html__('%d premium articles left', 'contentosapp-studio'),
								(int) max( 0, $trial_remaining )
							); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="fos-lic-usage-stat">
                        <div class="fos-lic-us-label"><?php esc_html_e('BYOK / month', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-us-value green"><?php echo esc_html($byok_month); ?> / ∞</div>
                        <div class="fos-lic-us-sub"><?php esc_html_e('Your own key', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-usage-stat">
                        <div class="fos-lic-us-label"><?php esc_html_e('Hours saved', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-us-value green"><?php echo esc_html($hours_saved); ?>h</div>
                        <div class="fos-lic-us-sub"><?php
                        /* translators: %d: number of articles produced */
                        printf( esc_html__('%d articles × 3.7h', 'contentosapp-studio'), (int) $total ); ?></div>
                    </div>
                    <div class="fos-lic-usage-stat">
                        <div class="fos-lic-us-label"><?php esc_html_e('Connected sites', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-us-value"><?php echo esc_html($sites_count); ?> / ∞</div>
                        <div class="fos-lic-us-sub"><?php esc_html_e('Connected sites', 'contentosapp-studio'); ?></div>
                    </div>
                </div>
                <div class="fos-lic-prod-bar-wrap">
                    <div class="fos-lic-prod-bar-label">
                        <?php if ( $trial_exhausted ) : ?>
                            <span class="fos-text-danger" style="font-weight:600"><?php esc_html_e('Premium trial used', 'contentosapp-studio'); ?></span>
                        <?php else : ?>
                            <span><?php
                            /* translators: 1: premium trial articles used, 2: trial total */
                            printf( esc_html__( 'Premium trial — %1$d of %2$d used', 'contentosapp-studio' ), (int) $trial_used, (int) $trial_limit ); ?></span>
                        <?php endif; ?>
                        <a href="<?php echo esc_url($store_url); ?>" target="_blank" style="color:var(--fos-primary);font-weight:600"><?php esc_html_e('Compare plans →', 'contentosapp-studio'); ?></a>
                    </div>
                    <?php
                    $bar_tooltip = $trial_exhausted
                        ? __('Free premium trial used. BYOK stays unlimited with your own provider key.', 'contentosapp-studio')
                        /* translators: %d: percentage of the one-time premium trial consumed */
                        : sprintf(
							/* translators: %d: percentage of monthly ContentOS Auto service quota consumed. */
							__('%d%% of your one-time premium trial used.', 'contentosapp-studio'),
							$trial_pct
						);
                    ?>
                    <div class="fos-lic-prod-bar-track" title="<?php echo esc_attr($bar_tooltip); ?>">
                        <div class="fos-lic-prod-bar-fill <?php echo esc_attr( $trial_exhausted ? 'fos-bg-danger' : '' ); ?>" style="width: <?php echo esc_attr($trial_pct); ?>%;"></div>
                    </div>
                    <div class="fos-lic-prod-bar-reset">
                        <?php esc_html_e( 'One-time trial — no monthly reset. BYOK with your own key is always unlimited.', 'contentosapp-studio' ); ?>
                    </div>
                </div>
            </div>

            <?php if ( $trial_exhausted ) : ?>
                <!-- Trial-exhausted CTA (moderate upsell — Guideline 11) -->
                <div class="fos-lic-migration-card">
                    <div class="fos-lic-migration-header">
                        <div class="fos-lic-migration-icon">🚀</div>
                        <div>
                            <div class="fos-lic-migration-title"><?php esc_html_e('Your free premium trial is used', 'contentosapp-studio'); ?></div>
                            <div class="fos-lic-migration-desc">
                                <?php esc_html_e('Keep creating right now — switch to BYOK (your own key) for unlimited articles, or upgrade for more done-for-you ContentOS Auto productions.', 'contentosapp-studio'); ?>
                            </div>
                        </div>
                    </div>
                    <div class="fos-lic-migration-footer">
                        <div class="fos-lic-migration-promo">
                            💡 <?php esc_html_e('BYOK is free and unlimited on every plan', 'contentosapp-studio'); ?>
                        </div>
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=costudio-settings' ) ); ?>" class="fos-lic-btn-migrate"><?php esc_html_e('Set up BYOK →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>
            <?php endif; ?>

            <!-- Plan comparison -->
            <div class="fos-lic-zone-label"><?php esc_html_e('Choose your plan', 'contentosapp-studio'); ?></div>

            <div class="fos-lic-plan-compare fos-lic-plan-compare--four">
                <!-- Free (current) -->
                <div class="fos-lic-plan-card">
                    <div class="fos-lic-plan-header">
                        <div class="fos-lic-plan-name"><?php esc_html_e('Free', 'contentosapp-studio'); ?></div>
                        <div class="fos-lic-plan-price-free">$0</div>
                        <div class="fos-lic-plan-annual">
                            <span class="fos-lic-plan-annual-price"><?php esc_html_e('No credit card', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-desc"><?php esc_html_e('See the full engine in action — end to end.', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-plan-body">
                        <ul class="fos-lic-plan-features">
                            <?php costudio_render_plan_features( 'free', $costudio_plan_matrix ); ?>
                        </ul>
                    </div>
                    <div class="fos-lic-plan-footer">
                        <button class="fos-lic-btn-plan fos-lic-btn-plan--current" disabled><?php esc_html_e('Current plan', 'contentosapp-studio'); ?></button>
                    </div>
                </div>

                <!-- Starter -->
                <div class="fos-lic-plan-card">
                    <div class="fos-lic-plan-header" style="padding-top:28px">
                        <div class="fos-lic-plan-name">STARTER</div>
                        <div>
                            <span class="fos-lic-plan-price">$9</span>
                            <span class="fos-lic-plan-period"> <?php esc_html_e('/ month', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-annual">
                            <span class="fos-lic-plan-annual-price">$90 / year</span>
                            <span class="fos-lic-plan-annual-save"><?php esc_html_e('2 months free', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-desc"><?php esc_html_e('Build a publishing habit — a predictable monthly flow of live articles.', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-plan-body">
                        <ul class="fos-lic-plan-features">
                            <?php costudio_render_plan_features( 'starter', $costudio_plan_matrix ); ?>
                        </ul>
                    </div>
                    <div class="fos-lic-plan-footer">
                        <a href="<?php echo esc_url($store_url); ?>" target="_blank" class="fos-lic-btn-plan"><?php esc_html_e('Go Starter →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>

                <!-- Pro -->
                <div class="fos-lic-plan-card featured">
                    <div class="fos-lic-plan-badge-top"><?php esc_html_e('Most Popular', 'contentosapp-studio'); ?></div>
                    <div class="fos-lic-plan-header" style="padding-top:28px">
                        <div class="fos-lic-plan-name">PRO</div>
                        <div>
                            <span class="fos-lic-plan-price">$49</span>
                            <span class="fos-lic-plan-period"> <?php esc_html_e('/ month', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-annual">
                            <span class="fos-lic-plan-annual-price">$490 / year</span>
                            <span class="fos-lic-plan-annual-save"><?php esc_html_e('2 months free', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-desc"><?php esc_html_e('For teams serious about content: more volume and deeper research.', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-plan-body">
                        <ul class="fos-lic-plan-features">
                            <?php costudio_render_plan_features( 'pro', $costudio_plan_matrix ); ?>
                        </ul>
                    </div>
                    <div class="fos-lic-plan-footer">
                        <a href="<?php echo esc_url($store_url); ?>" target="_blank" class="fos-lic-btn-plan fos-lic-btn-plan--primary"><?php esc_html_e('Go Pro →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>

                <!-- Studio -->
                <div class="fos-lic-plan-card">
                    <div class="fos-lic-plan-header" style="padding-top:28px">
                        <div class="fos-lic-plan-name">STUDIO</div>
                        <div>
                            <span class="fos-lic-plan-price">$129</span>
                            <span class="fos-lic-plan-period"> <?php esc_html_e('/ month', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-annual">
                            <span class="fos-lic-plan-annual-price">$1290 / year</span>
                            <span class="fos-lic-plan-annual-save"><?php esc_html_e('2 months free', 'contentosapp-studio'); ?></span>
                        </div>
                        <div class="fos-lic-plan-desc"><?php esc_html_e('Agency-grade scale — high volume, the deepest research and priority in the queue.', 'contentosapp-studio'); ?></div>
                    </div>
                    <div class="fos-lic-plan-body">
                        <ul class="fos-lic-plan-features">
                            <?php costudio_render_plan_features( 'studio', $costudio_plan_matrix ); ?>
                        </ul>
                    </div>
                    <div class="fos-lic-plan-footer">
                        <a href="<?php echo esc_url($store_url); ?>" target="_blank" class="fos-lic-btn-plan"><?php esc_html_e('Get Studio →', 'contentosapp-studio'); ?></a>
                    </div>
                </div>
            </div>

            <!-- Auto vs BYOK clarifier -->
            <div class="fos-lic-byok-note">
                <span class="fos-lic-byok-note-icon" aria-hidden="true">💡</span>
                <span><?php echo esc_html( $costudio_byok_note ); ?></span>
            </div>

            <!-- Activation form -->
            <div class="fos-lic-zone-label"><?php esc_html_e('Already have a license? Activate now', 'contentosapp-studio'); ?></div>

            <div class="fos-lic-activation-card">
                <div class="fos-lic-activation-header">
                    <div class="fos-lic-activation-header-icon">🔑</div>
                    <div class="fos-lic-activation-header-title"><?php esc_html_e('Activate license', 'contentosapp-studio'); ?></div>
                </div>
                <form id="fos-license-form" method="post">
                    <div class="fos-lic-activation-body">
                        <div class="fos-lic-field">
                            <label class="fos-lic-field-label"><?php esc_html_e('License key', 'contentosapp-studio'); ?></label>
                            <div class="fos-lic-field-input-wrap">
                                <input type="password" id="fos-license-key-input" name="costudio_pro_license_key" class="fos-lic-field-input" placeholder="XXXX-XXXX-XXXX-XXXX" value="" autocomplete="new-password" required>
                                <button type="button" class="fos-lic-toggle-vis">👁</button>
                            </div>
                        </div>
                        <div class="fos-lic-field">
                            <label class="fos-lic-field-label"><?php esc_html_e('Purchase email', 'contentosapp-studio'); ?></label>
                            <input type="email" name="costudio_license_email" class="fos-lic-field-input email" placeholder="you@example.com" value="" autocomplete="email" required>
                            <span class="fos-lic-field-hint"><?php esc_html_e('Email used when purchasing the license.', 'contentosapp-studio'); ?></span>
                        </div>
                    </div>
                    <div class="fos-lic-activation-footer">
                        <div class="fos-lic-activation-link">
                            <?php esc_html_e('Don\'t have a license?', 'contentosapp-studio'); ?> <a href="<?php echo esc_url($store_url); ?>" target="_blank"><?php esc_html_e('Buy a License →', 'contentosapp-studio'); ?></a>
                        </div>
                        <div class="fos-lic-footer-right">
                            <span id="fos-license-msg" class="fos-lic-inline-msg"></span>
                            <button type="submit" class="fos-lic-btn-activate">🔒 <?php esc_html_e('Activate license', 'contentosapp-studio'); ?></button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <?php
    // Sprint B.3 — Buy Extra Quotas modal partial. Stays hidden until
    // window.costudioAddonModal() is called by the License page's
    // "Buy more credits" button (#fos-addon-buy-btn).
    include __DIR__ . '/partials/modal-buy-addon.php';
    ?>

</div>
