<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
$avi_profile_row = array();
$avi_pid_raw     = isset( $_GET['pid'] ) ? (string) $_GET['pid'] : '';
$avi_pid                 = function_exists( 'sanitize_text_field' ) && function_exists( 'wp_unslash' )
	? sanitize_text_field( wp_unslash( $avi_pid_raw ) )
	: trim( stripslashes( $avi_pid_raw ) );
if ( $avi_pid !== '' && isset( $GLOBALS['wpdb'] ) && is_object( $GLOBALS['wpdb'] ) && method_exists( $GLOBALS['wpdb'], 'get_row' ) ) {
	global $wpdb;
	$profiles_table = $wpdb->prefix . 'avi_saas_profiles';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $profiles_table ) ) !== $profiles_table ) {
		$profiles_table = 'wor1515_avi_saas_profiles';
	}
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $profiles_table ) ) === $profiles_table ) {
		// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- nom de table validé (SHOW TABLES).
		$row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$profiles_table}` WHERE uuid = %s LIMIT 1", $avi_pid ), ARRAY_A );
		if ( is_array( $row ) ) {
			$avi_profile_row = $row;
		}
	}

	if ( empty( $avi_profile_row['id'] ) ) {
		$avi_skip_pid_redirect = function_exists( 'is_user_logged_in' ) && is_user_logged_in()
			&& function_exists( 'current_user_can' ) && current_user_can( 'manage_options' );
		if ( ! $avi_skip_pid_redirect && function_exists( 'wp_safe_redirect' ) && function_exists( 'home_url' ) && ! headers_sent() ) {
			wp_safe_redirect( home_url( '/connexion/' ) );
			exit;
		}
	}

}

$GLOBALS['avi_profile_row'] = $avi_profile_row;

// Sprint 11 — contexte profil pour cartes Stripe (niveau / Gardien / bundle).
$avi_s11_profile        = is_array( $avi_profile_row ) ? $avi_profile_row : array();
$avi_s11_show_stripe    = ! empty( $avi_s11_profile['id'] );
$avi_s11_level          = isset( $avi_s11_profile['current_level'] ) ? (int) $avi_s11_profile['current_level'] : 1;
$avi_s11_guardian_on    = ! empty( $avi_s11_profile['guardian_active'] ) && (int) $avi_s11_profile['guardian_active'] === 1;
$avi_s11_guardian_scan  = isset( $avi_s11_profile['guardian_scan_enabled'] ) ? (int) $avi_s11_profile['guardian_scan_enabled'] : 0;
$avi_s11_bundle         = isset( $avi_s11_profile['avi_bundle'] ) ? (string) $avi_s11_profile['avi_bundle'] : '';
$avi_s11_radar_plan     = isset( $avi_s11_profile['radar_plan'] ) ? strtolower( trim( (string) $avi_s11_profile['radar_plan'] ) ) : 'offert';
if ( $avi_s11_radar_plan === '' ) {
	$avi_s11_radar_plan = 'offert';
}
$avi_s11_portal_url     = function_exists( 'get_option' ) ? trim( (string) get_option( 'avi_stripe_customer_portal_url', '' ) ) : '';
$avi_s11_portal_ok      = ( $avi_s11_portal_url !== '' && $avi_s11_portal_url !== '#' );
$avi_s11_uid            = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0;
$avi_s11_stripe_nonce   = function_exists( 'wp_create_nonce' ) ? wp_create_nonce( 'avision_premium_nonce' ) : '';
$avi_s11_ajax           = function_exists( 'admin_url' ) ? admin_url( 'admin-ajax.php' ) : '';
$avi_s11_saas_profile_row = null;
if ( $avi_s11_uid > 0 && isset( $GLOBALS['wpdb'] ) && is_object( $GLOBALS['wpdb'] ) ) {
	global $wpdb;
	$avi_s11_saas_profile_row = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT avi_bundle, guardian_active, radar_plan FROM `{$wpdb->prefix}avi_saas_profiles` WHERE user_id = %d LIMIT 1",
			$avi_s11_uid
		)
	);
	$avi_s11_bundle          = $avi_s11_saas_profile_row ? (string) $avi_s11_saas_profile_row->avi_bundle : '';
	$avi_s11_guardian_active = $avi_s11_saas_profile_row ? (int) $avi_s11_saas_profile_row->guardian_active : 0;
	$avi_s11_radar_plan      = $avi_s11_saas_profile_row ? strtolower( trim( (string) $avi_s11_saas_profile_row->radar_plan ) ) : 'offert';
}
if ( ! isset( $avi_s11_guardian_active ) ) {
	$avi_s11_guardian_active = $avi_s11_guardian_on ? 1 : 0;
}
if ( $avi_s11_radar_plan === '' ) {
	$avi_s11_radar_plan = 'offert';
}
$avi_s11_radar_hebdo_active    = ( $avi_s11_radar_plan === 'hebdo' || $avi_s11_bundle === 'starter_pro' );
$avi_s11_radar_elite_active    = ( $avi_s11_radar_plan === 'elite' || $avi_s11_bundle === 'elite_pro' );
$avi_s11_starter_bundle_active = ( $avi_s11_bundle === 'starter_pro' );
$avi_s11_elite_bundle_active   = ( $avi_s11_bundle === 'elite_pro' );
$avi_s11_stripe_sync_uid = ! empty( $avi_s11_profile['user_id'] ) ? (int) $avi_s11_profile['user_id'] : $avi_s11_uid;
$avi_s11_sub_latest      = ( $avi_s11_stripe_sync_uid > 0 && function_exists( 'avi_get_latest_active_stripe_subscription_id' ) )
	? avi_get_latest_active_stripe_subscription_id( $avi_s11_stripe_sync_uid ) : '';
$avi_s11_sub_radar_hebdo = '';
$avi_s11_sub_bundle_starter = '';
$avi_s11_sub_guardian    = '';
if ( $avi_s11_stripe_sync_uid > 0 && function_exists( 'avi_get_active_stripe_subscription_id_for_product' ) ) {
	if ( defined( 'AVI_STRIPE_PRODUCT_RADAR_HEBDO' ) ) {
		$avi_s11_sub_radar_hebdo = avi_get_active_stripe_subscription_id_for_product( $avi_s11_stripe_sync_uid, AVI_STRIPE_PRODUCT_RADAR_HEBDO );
	}
	if ( defined( 'AVI_STRIPE_PRODUCT_BUNDLE_STARTER' ) ) {
		$avi_s11_sub_bundle_starter = avi_get_active_stripe_subscription_id_for_product( $avi_s11_stripe_sync_uid, AVI_STRIPE_PRODUCT_BUNDLE_STARTER );
	}
	if ( defined( 'AVI_STRIPE_PRODUCT_GUARDIAN' ) ) {
		$avi_s11_sub_guardian = avi_get_active_stripe_subscription_id_for_product( $avi_s11_stripe_sync_uid, AVI_STRIPE_PRODUCT_GUARDIAN );
	}
}
if ( $avi_s11_sub_radar_hebdo === '' ) {
	$avi_s11_sub_radar_hebdo = $avi_s11_sub_latest;
}
if ( $avi_s11_sub_bundle_starter === '' ) {
	$avi_s11_sub_bundle_starter = $avi_s11_sub_latest;
}
if ( $avi_s11_sub_guardian === '' ) {
	$avi_s11_sub_guardian = $avi_s11_sub_latest;
}
echo render_partial(
	'header',
	array(
		'profile' => $avi_profile_row,
	)
);
?>

<main class="dashboard-container avi-premium-dashboard">
	<!-- AVI Announcements Banner -->
	<div id="avi-banners-wrap" style="display:none;
	     padding:0 0 12px;"></div>
	<style>
	.avi-banner-item {
	    display:flex;align-items:center;gap:12px;
	    background:var(--avi-surface,#0D1E38);
	    border:1px solid rgba(255,255,255,0.07);
	    border-radius:10px;padding:12px 18px;
	    margin-bottom:8px;
	    border-left:4px solid var(--avi-banner-color,var(--avi-accent,#3B82F6));
	}
	.avi-banner-badge {
	    flex-shrink:0;font-size:11px;font-weight:700;
	    padding:3px 10px;border-radius:20px;
	    text-transform:uppercase;letter-spacing:0.5px;color:#fff;
	}
	.avi-banner-msg { flex:1;color:var(--avi-text-muted,#C0D0E8);line-height:1.5; }
	.avi-banner-msg.size-small  { font-size:12px; }
	.avi-banner-msg.size-normal { font-size:14px; }
	.avi-banner-msg.size-large  { font-size:16px; }
	.avi-banner-scroll { display:inline-block;
	    animation:avi-scroll 18s linear infinite; }
	.avi-banner-close {
	    flex-shrink:0;
	    background:none;border:none;cursor:pointer;
	    color:rgba(255,255,255,0.4);font-size:18px;line-height:1;
	    padding:0 0 0 8px;transition:color 0.15s;
	}
	.avi-banner-close:hover { color:#fff; }
	@keyframes avi-scroll {
	    0%   { transform:translateX(60vw);  }
	    100% { transform:translateX(-100%); }
	}
	</style>
	<script>
	(function(){
	    var aviBannerAudience = 'b2c';

	    function aviBoldParse(msg) {
	        return msg.replace(/\*\*(.+?)\*\*/g,
	            '<strong>$1</strong>');
	    }

	    function aviRenderBanners(banners) {
	        var wrap = document.getElementById('avi-banners-wrap');
	        if (!wrap || !banners.length) return;

	        // Lire les IDs dismissés depuis localStorage
	        var storageKey = 'avi_dismissed_banners';
	        var dismissed  = [];
	        try {
	            dismissed = JSON.parse(localStorage.getItem(storageKey) || '[]');
	        } catch(e) { dismissed = []; }

	        // Filtrer les bannières non dismissées
	        var visible = banners.filter(function(b) {
	            return dismissed.indexOf(String(b.id)) === -1;
	        });

	        if (!visible.length) return; // tout dismissé → rester caché

	        var html = '';
	        visible.forEach(function(b) {
	            var color = b.badge_color || '#3B82F6';
	            var msg   = aviBoldParse(b.message || '');
	            var inner = b.scrolling == '1'
	                ? '<span class="avi-banner-scroll">' + msg + '</span>'
	                : msg;
	            html += '<div class="avi-banner-item" '
	                + 'data-banner-id="' + b.id + '" '
	                + 'style="--avi-banner-color:' + color + ';">'
	                + '<span class="avi-banner-badge" '
	                + 'style="background:' + color + ';">'
	                + b.badge_text + '</span>'
	                + '<span class="avi-banner-msg size-'
	                + (b.text_size || 'normal') + '">'
	                + inner + '</span>'
	                + '<button type="button" class="avi-banner-close" '
	                + 'aria-label="Dismiss" '
	                + 'data-bid="' + b.id + '">×</button>'
	                + '</div>';
	        });

	        wrap.innerHTML = html;
	        wrap.style.display = 'block';

	        // Listener fermeture
	        wrap.querySelectorAll('.avi-banner-close').forEach(function(btn) {
	            btn.addEventListener('click', function() {
	                var bid = String(btn.getAttribute('data-bid'));
	                // Mémoriser
	                try {
	                    var d = JSON.parse(localStorage.getItem(storageKey) || '[]');
	                    if (d.indexOf(bid) === -1) d.push(bid);
	                    localStorage.setItem(storageKey, JSON.stringify(d));
	                } catch(e) {}
	                // Masquer l'item
	                var item = wrap.querySelector('[data-banner-id="' + bid + '"]');
	                if (item) item.remove();
	                // Si plus rien → cacher le wrap
	                if (!wrap.querySelector('.avi-banner-item')) {
	                    wrap.style.display = 'none';
	                }
	            });
	        });
	    }

	    fetch('/wp-json/avision/v1/banners?audience=' + aviBannerAudience)
	        .then(function(r){ return r.json(); })
	        .then(function(d){ aviRenderBanners(d.banners || []); })
	        .catch(function(){});
	})();
	</script>
    <div class="dashboard-header">
        <h1>
            🎉 <?php echo $i18n->get('dashboard_title'); ?>
            <span class="company-name"></span>
        </h1>
        <p>Welcome to your Premium Dashboard - Full access unlocked!</p>
    </div>
    
    <div class="alert-box success" style="margin-bottom: 30px;">
        <span class="icon">✓</span>
        <div>
            <strong>Premium Access Active</strong>
            <p>You now have full access to all features including automation tools!</p>
        </div>
    </div>
    
    <div class="score-section">
        <div class="score-circle"></div>
        
        <div class="score-details">
            <div class="score-status good">
                <?php echo $i18n->get('dashboard_status_good'); ?>
            </div>
            
            <div class="kpi-grid">
                <div class="kpi-card">
                    <div class="value">3rd</div>
                    <div class="label" data-i18n="kpi_position"><?php echo $i18n->get('kpi_position'); ?></div>
                </div>
                <div class="kpi-card">
                    <div class="value">1st</div>
                    <div class="label" data-i18n="kpi_leader"><?php echo $i18n->get('kpi_leader'); ?></div>
                </div>
                <div class="kpi-card growth">
                    <div class="value">+45%</div>
                    <div class="label">Quotes Increase</div>
                </div>
                <div class="kpi-card growth">
                    <div class="value">+60%</div>
                    <div class="label">Calls Increase</div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="levels-container">
        <div class="level-card done" data-level="1">
            <div class="level-header">
                <div class="level-number">
                    <div class="level-badge">✓</div>
                    <span class="level-title" data-i18n="level_1_title"><?php echo $i18n->get('level_1_title'); ?></span>
                </div>
                <span class="level-status done"><?php echo $i18n->get('level_1_done'); ?></span>
            </div>
        </div>
        
        <div class="level-card done" data-level="2">
            <div class="level-header">
                <div class="level-number">
                    <div class="level-badge">✓</div>
                    <span class="level-title" data-i18n="level_2_title"><?php echo $i18n->get('level_2_title'); ?></span>
                </div>
                <span class="level-status done">Completed</span>
            </div>
        </div>
        
        <div class="level-card active" data-level="3">
            <div class="level-header">
                <div class="level-number">
                    <div class="level-badge">3</div>
                    <span class="level-title" data-i18n="level_3_title"><?php echo $i18n->get('level_3_title'); ?></span>
                </div>
                <span class="level-status active">Unlocked</span>
            </div>
            <div class="level-content">
                <p class="level-description" data-i18n="level_3_desc"><?php echo $i18n->get('level_3_desc'); ?></p>
                
                <div class="automation-toggles">
                    <div class="toggle-item">
                        <span class="toggle-label" data-i18n="level_3_auto_reviews"><?php echo $i18n->get('level_3_auto_reviews'); ?></span>
                        <div class="toggle-switch active" onclick="this.classList.toggle('active')"></div>
                    </div>
                    <div class="toggle-item">
                        <span class="toggle-label" data-i18n="level_3_auto_posts"><?php echo $i18n->get('level_3_auto_posts'); ?></span>
                        <div class="toggle-switch" onclick="this.classList.toggle('active')"></div>
                    </div>
                </div>
                
                <div class="alert-box info">
                    <span class="icon">💡</span>
                    <div>
                        <strong data-i18n="automation_title"><?php echo $i18n->get('automation_title'); ?></strong>
                        <p data-i18n="automation_desc"><?php echo $i18n->get('automation_desc'); ?></p>
                        <a href="/payment?type=automation" class="btn btn-premium" style="margin-top: 10px;">
                            <?php echo $i18n->get('automation_subscribe'); ?> - <?php echo $i18n->get_price('automation'); ?>
                        </a>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="bonus-section open">
            <div class="bonus-header">
                <h3>
                    <span>🎁</span>
                    <span data-i18n="level_4_title"><?php echo $i18n->get('level_4_title'); ?></span>
                </h3>
                <span class="bonus-toggle-icon">▼</span>
            </div>
            <div class="bonus-content">
                <div class="bonus-inner">
                    <p class="level-description" data-i18n="level_4_desc"><?php echo $i18n->get('level_4_desc'); ?></p>
                    
                    <label style="display: block; margin-bottom: 10px; font-weight: 500;">
                        <?php echo $i18n->get('level_4_email_template'); ?>
                    </label>
                    <textarea id="validation-post-textarea" class="email-template" data-i18n="email_template" placeholder=""></textarea>
                    
                    <div class="bonus-actions">
                        <button class="btn btn-outline" data-action="copy-email">
                            <?php echo $i18n->get('level_4_copy'); ?>
                        </button>
                        <button class="btn btn-primary" data-action="email-sent">
                            <?php echo $i18n->get('level_4_sent'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

	<?php if ( $avi_s11_show_stripe && defined( 'AVI_STRIPE_PRODUCT_RADAR_HEBDO' ) && $avi_s11_uid > 0 && empty( $is_shared_report ) ) : ?>
	<!-- S11 : Plans Stripe (checkout via AJAX, même nonce que avision_stripe_s10b_checkout) -->
	<div class="avi-stripe-plans-section" style="margin:32px 0;padding:24px;border:1px solid #e2e4e8;border-radius:12px;background:#fafbfc;">
		<style>
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-title { font-size:1.25em;font-weight:800;margin:0 0 8px; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-subtitle { color:#555;font-size:.95em;margin:0 0 20px;line-height:1.5; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-grid-2 { display:flex;flex-wrap:wrap;gap:16px; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-card-2 { flex:1;min-width:280px;padding:20px;border:2px solid #7c3aed;border-radius:12px;background:#faf5ff;position:relative; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-card-2.featured { border-color:#6d28d9;background:#f3e8ff; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-badge { display:inline-block;background:#7c3aed;color:#fff;font-size:.72em;font-weight:700;padding:2px 10px;border-radius:20px;margin-bottom:10px;letter-spacing:.04em; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-name { font-size:1.1em;font-weight:800;margin:0 0 4px;color:#1e1b4b; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-price { font-size:1.5em;font-weight:900;color:#7c3aed;margin:8px 0 12px; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-price small { font-size:.55em;font-weight:500;color:#6b7280; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-features { list-style:none;padding:0;margin:0 0 16px;font-size:.9em;color:#374151; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-features li { padding:3px 0; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-btn-bundle { background:#7c3aed;color:#fff !important;border:none;width:100%;padding:12px 16px;border-radius:8px;font-weight:700;font-size:1em;cursor:pointer; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-btn-bundle:hover { background:#6d28d9; }
			.avi-premium-dashboard .avi-stripe-plans-section .avi-btn-bundle-disabled { opacity:.85;cursor:not-allowed;background:#e5e7eb !important;color:#374151 !important;border:1px solid #d1d5db !important;width:100%;padding:12px 16px;border-radius:8px;font-weight:700; }
			@media(max-width:600px){
				.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-grid-2 { flex-direction:column; }
				.avi-premium-dashboard .avi-stripe-plans-section .avi-bundle-card-2 { min-width:unset; }
			}
		</style>

		<?php
		$avi_bundle_title = array(
			'fr' => 'Bundles — Radar &amp; Gardien',
			'en' => 'Bundles — Radar &amp; Guardian',
			'es' => 'Bundles — Radar y Guardián',
		);
		$avi_bundle_sub = array(
			'fr' => '🎯 Combinez le suivi Radar et la veille Gardien dans un seul abonnement — moins cher, activé en 1 clic, sans jongler entre deux paiements. Le Gardien se déclenche automatiquement dès que vous validez les 3 piliers fondateurs (Level 1–3), qui posent les bases solides pour une veille locale efficace.',
			'en' => '🎯 Combine Radar tracking and Guardian monitoring in one subscription — better value, activated in 1 click, with no juggling between two payments. Guardian automatically activates once you complete the 3 foundation pillars (Levels 1–3), which build the solid base for effective local monitoring.',
			'es' => '🎯 Combina el seguimiento Radar y la vigilancia Guardián en una sola suscripción — mejor precio, activado en 1 clic, sin gestionar dos pagos. El Guardián se activa automáticamente al completar los 3 pilares fundadores (Niveles 1–3), que establecen la base sólida para una vigilancia local eficaz.',
		);
		$_lang_b = 'en';
		if ( function_exists( 'get_locale' ) ) {
			$lc = strtolower( substr( (string) get_locale(), 0, 2 ) );
			if ( in_array( $lc, array( 'fr', 'en', 'es' ), true ) ) {
				$_lang_b = $lc;
			}
		}
		?>

		<h2 class="avi-bundle-title"><?php echo wp_kses_post( $avi_bundle_title[ $_lang_b ] ); ?></h2>
		<p class="avi-bundle-subtitle"><?php echo wp_kses_post( $avi_bundle_sub[ $_lang_b ] ); ?></p>

		<div class="avi-bundle-grid-2">

			<!-- Starter Pro -->
			<div class="avi-bundle-card-2">
				<div class="avi-bundle-badge">⚡ Starter</div>
				<div class="avi-bundle-name"><?php esc_html_e( 'Pack Starter Pro', 'avision-dashboard' ); ?></div>
				<div class="avi-bundle-price">$35<small><?php esc_html_e( '/mo', 'avision-dashboard' ); ?></small></div>
				<ul class="avi-bundle-features">
					<li>📡 <?php esc_html_e( 'Growth Radar Weekly — 75 keywords', 'avision-dashboard' ); ?></li>
					<li>🛡️ <?php esc_html_e( 'Guardian — 9 shields (active at Level 4)', 'avision-dashboard' ); ?></li>
				</ul>
				<?php if ( $avi_s11_starter_bundle_active ) : ?>
					<button type="button" class="avi-btn-bundle-disabled" disabled aria-disabled="true"><?php esc_html_e( 'Your Plan ✓', 'avision-dashboard' ); ?></button>
					<?php if ( ! $avi_s11_elite_bundle_active && defined( 'AVI_STRIPE_PRODUCT_BUNDLE_ELITE' ) ) : ?>
					<button type="button" class="btn btn-primary avi-btn-upgrade" style="margin-top:10px;width:100%;"
						data-product="<?php echo esc_attr( AVI_STRIPE_PRODUCT_BUNDLE_ELITE ); ?>"
						data-current-sub="<?php echo esc_attr( $avi_s11_sub_bundle_starter ); ?>"
						data-nonce="<?php echo esc_attr( $avi_s11_stripe_nonce ); ?>"
						onclick="if(typeof aviUpgradeSubscription==='function'){aviUpgradeSubscription(this.getAttribute('data-product')||'',this.getAttribute('data-current-sub')||'',this);}">
						<?php esc_html_e( '⬆️ Upgrade to Elite Pro (prorata)', 'avision-dashboard' ); ?>
					</button>
					<?php endif; ?>
				<?php elseif ( defined( 'AVI_STRIPE_PRODUCT_BUNDLE_STARTER' ) ) : ?>
					<button type="button" class="avi-btn-bundle avi-stripe-checkout-btn" data-avi-product="<?php echo esc_attr( AVI_STRIPE_PRODUCT_BUNDLE_STARTER ); ?>">
						<?php esc_html_e( 'Activate Bundle', 'avision-dashboard' ); ?>
					</button>
				<?php endif; ?>
			</div>

			<!-- Elite Pro -->
			<div class="avi-bundle-card-2 featured">
				<div class="avi-bundle-badge" style="background:#6d28d9;">🚀 Elite — <?php esc_html_e( 'Best Value', 'avision-dashboard' ); ?></div>
				<div class="avi-bundle-name"><?php esc_html_e( 'Pack Elite Pro', 'avision-dashboard' ); ?></div>
				<div class="avi-bundle-price" style="color:#6d28d9;">$39<small><?php esc_html_e( '/mo', 'avision-dashboard' ); ?></small></div>
				<ul class="avi-bundle-features">
					<li>📡 <?php esc_html_e( 'Growth Radar Elite — 100+ keywords daily', 'avision-dashboard' ); ?></li>
					<li>🛡️ <?php esc_html_e( 'Guardian — 9 shields (active at Level 4)', 'avision-dashboard' ); ?></li>
					<li>🔔 <?php esc_html_e( 'Spy alerts + priority monitoring', 'avision-dashboard' ); ?></li>
				</ul>
				<?php if ( $avi_s11_elite_bundle_active ) : ?>
					<button type="button" class="avi-btn-bundle-disabled" disabled aria-disabled="true"><?php esc_html_e( 'Your Plan ✓', 'avision-dashboard' ); ?></button>
				<?php elseif ( defined( 'AVI_STRIPE_PRODUCT_BUNDLE_ELITE' ) ) : ?>
					<button type="button" class="avi-btn-bundle avi-stripe-checkout-btn" style="background:#6d28d9;" data-avi-product="<?php echo esc_attr( AVI_STRIPE_PRODUCT_BUNDLE_ELITE ); ?>">
						<?php esc_html_e( 'Activate Bundle', 'avision-dashboard' ); ?>
					</button>
				<?php endif; ?>
			</div>

		</div><!-- .avi-bundle-grid-2 -->

		<?php
		$avi_s11_guardian_deferred = $avi_s11_guardian_on && $avi_s11_guardian_scan === 0;
		if ( $avi_s11_guardian_deferred ) :
			$done = min( max( $avi_s11_level - 1, 0 ), 3 );
			$pct  = (int) round( ( $done / 3 ) * 100 );
			$lbl  = ( $avi_s11_bundle === 'elite_pro' ) ? __( 'Pack Elite Pro', 'avision-dashboard' ) : __( 'Pack Starter Pro', 'avision-dashboard' );
			?>
		<div class="avi-guardian-pending" style="margin-top:24px;padding:16px;border:1px dashed #999;border-radius:8px;">
			<div class="avi-guardian-pending-title" style="font-weight:700;margin-bottom:8px;">
				🛡️ <?php esc_html_e( 'Guardian Mode — en préparation', 'avision-dashboard' ); ?>
				<span class="avi-bundle-tag" style="margin-left:8px;font-size:.85em;color:#555;"><?php echo esc_html( $lbl ); ?></span>
			</div>
			<p style="font-size:.9em;"><?php esc_html_e( 'Complétez les 3 niveaux fondations pour activer le scan Guardian.', 'avision-dashboard' ); ?></p>
			<div class="avi-pillars" style="display:flex;gap:8px;flex-wrap:wrap;margin:12px 0;">
				<?php foreach ( array( 1, 2, 3 ) as $i ) : ?>
				<div class="avi-pillar <?php echo $done >= $i ? 'done' : ''; ?>" style="padding:8px 10px;border:1px solid #ccc;border-radius:6px;font-size:.85em;">
					<span><?php echo (int) $i; ?></span>
					<small style="display:block;"><?php echo esc_html( sprintf( __( 'Niveau %d', 'avision-dashboard' ), $i ) ); ?></small>
					<?php echo $done >= $i ? '✅' : '○'; ?>
				</div>
				<?php endforeach; ?>
				<div class="avi-pillar-guardian" style="padding:8px 10px;border:1px solid #c5a059;border-radius:6px;font-size:.85em;">🛡️ <small><?php esc_html_e( 'Guardian ON', 'avision-dashboard' ); ?></small></div>
			</div>
			<div class="avi-progress-bar" style="height:8px;background:#eee;border-radius:4px;overflow:hidden;">
				<div class="avi-progress-fill" style="height:100%;width:<?php echo (int) $pct; ?>%;background:#1a7f37;"></div>
			</div>
			<small style="display:block;margin-top:8px;color:#666;">
				<?php
				echo esc_html( (string) $done . '/3 — ' );
				echo $pct < 100
					? esc_html__( 'Guardian scan au niveau 4', 'avision-dashboard' )
					: esc_html__( 'Déverrouillage imminent…', 'avision-dashboard' );
				?>
			</small>
		</div>
		<?php endif; ?>

		<input type="hidden" id="avi-premium-stripe-nonce" value="<?php echo esc_attr( $avi_s11_stripe_nonce ); ?>" />
	</div>
	<script>
	(function() {
		var ajax = <?php echo wp_json_encode( $avi_s11_ajax ); ?>;
		document.addEventListener('DOMContentLoaded', function() {
			document.querySelectorAll('.avi-stripe-checkout-btn').forEach(function(btn) {
				btn.addEventListener('click', function() {
					var product = btn.getAttribute('data-avi-product');
					var nonceEl = document.getElementById('avi-premium-stripe-nonce');
					if (!product || !nonceEl) return;
					btn.disabled = true;
					var fd = new FormData();
					fd.append('action', 'avision_stripe_s10b_checkout');
					fd.append('nonce', nonceEl.value);
					fd.append('avi_product', product);
					fd.append('currency', 'eur');
					fetch(ajax, { method: 'POST', body: fd, credentials: 'same-origin' })
						.then(function(r) { return r.json(); })
						.then(function(data) {
							if (data.success && data.data && data.data.url) {
								window.location.href = data.data.url;
								return;
							}
							if (typeof console !== 'undefined' && console.error) {
								console.error('[AVI-CHECKOUT] Error:', data);
								console.error('[AVI-CHECKOUT] Message:', data && data.data && data.data.message);
							}
							var msg = (data && data.data && data.data.message) ? data.data.message
								: ((data && data.data && data.data.code) ? data.data.code : 'checkout_error');
							alert(msg);
						})
						.catch(function() { alert('network_error'); })
						.finally(function() { btn.disabled = false; });
				});
			});
		});
	})();
	</script>
	<?php endif; ?>

	<style>
	#aviGuSection > summary { font-size:20px; font-weight:700; cursor:pointer; padding:16px 0; padding-left:24px; color:#ffffff !important; list-style:none; display:flex; justify-content:flex-start; align-items:center; }
	#aviGuSection > summary::-webkit-details-marker { display:none; }
	.avi-gu-chevron { display:inline-flex; align-items:center; justify-content:center; flex-shrink:0; transition:transform .25s ease; margin-left:8px; }
	.avi-gu-chevron svg { display:block; width:20px; height:20px; }
	#aviGuSection[open] .avi-gu-chevron { transform:rotate(180deg); }
	.avi-gu-dashboard { max-width:1140px; margin:40px auto; padding:24px !important; background:#fff !important; box-shadow:0 2px 12px rgba(0,0,0,.06) !important; border-radius:12px !important; }
	.avi-gu-search { width:100%; padding:10px 16px; border:1px solid #ddd; border-radius:8px; font-size:15px; margin-bottom:20px; box-sizing:border-box; }
	.avi-gu-cats { display:flex; gap:8px; flex-wrap:wrap; margin-bottom:24px; }
	.avi-gu-cat { padding:6px 14px; border-radius:20px; border:1px solid #ddd; background:#fff; cursor:pointer; font-size:13px; transition:all .2s; }
	.avi-gu-cat.active, .avi-gu-cat:hover { background:#1a1a2e; color:#fff; border-color:#1a1a2e; }
	.avi-gu-cards { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:16px; }
	.avi-gu-card { background:#fff; border-radius:12px; padding:16px; box-shadow:0 2px 8px rgba(0,0,0,.07); border-left:4px solid #ddd; }
	.avi-gu-card[data-impact="high"] { border-left-color:#dc3232; }
	.avi-gu-card[data-impact="medium"] { border-left-color:#f0ad4e; }
	.avi-gu-card[data-impact="low"] { border-left-color:#46b450; }
	.avi-gu-card-title { font-weight:700; font-size:14px; color:#1a1a2e; margin-bottom:6px; white-space:normal; word-break:break-word; overflow:visible; display:block; }
	.avi-gu-card-summary { font-size:13px; color:#555; line-height:1.5; }
	.avi-gu-card-meta { font-size:11px; color:#999; margin-top:8px; display:flex; gap:8px; flex-wrap:wrap; }
	.avi-gu-badge { padding:2px 8px; border-radius:10px; background:#f0f0f0; font-size:11px; }
	.avi-gu-empty { text-align:center; color:#999; padding:40px; }
	@media(max-width:600px){ .avi-gu-cards { grid-template-columns:1fr; } }
	details.avi-gu-card summary { cursor:pointer; list-style:none; }
	details.avi-gu-card summary::-webkit-details-marker { display:none; }
	details.avi-gu-card[open] { border-left-width:6px; }
	.avi-gu-card-header { display:flex; justify-content:space-between; align-items:flex-start; gap:8px; }
	.avi-gu-card-body { padding-top:10px; border-top:1px solid #eee; margin-top:8px; font-size:13px; color:#444; line-height:1.6; }
	.avi-gu-card-toggle { font-size:11px; color:#999; white-space:nowrap; margin-top:2px; }
	</style>
	<details id="aviGuSection">
	<summary>🌐 <?php echo esc_html__('Google Updates — Local SEO News', 'avision-dashboard'); ?> <span class="avi-gu-chevron" aria-hidden="true"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" focusable="false"><path d="M6 9l6 6 6-6" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg></span></summary>
	<div class="avi-gu-dashboard" id="aviGuDashboard">
	  <input type="text" class="avi-gu-search" id="aviGuSearch"
	         placeholder="<?php echo esc_attr__('Search updates...', 'avision-dashboard'); ?>">
	  <div class="avi-gu-cats" id="aviGuCats">
	    <button class="avi-gu-cat active" data-cat="">📋 <?php esc_html_e('All', 'avision-dashboard'); ?></button>
	    <button class="avi-gu-cat" data-keyword="photo">📸 Photos</button>
	    <button class="avi-gu-cat" data-keyword="review">⭐ Reviews</button>
	    <button class="avi-gu-cat" data-keyword="post">📝 Posts</button>
	    <button class="avi-gu-cat" data-keyword="verif">🔐 Verification</button>
	    <button class="avi-gu-cat" data-keyword="gemini overview ask maps">🤖 AI &amp; Maps</button>
	    <button class="avi-gu-cat" data-keyword="suspend">⚠️ Suspension</button>
	  </div>
	  <div class="avi-gu-cards" id="aviGuCards">
	    <div class="avi-gu-empty">⏳ <?php esc_html_e('Loading updates...', 'avision-dashboard'); ?></div>
	  </div>
	</div>
	</details>

	<script>
	(function(){
	  var API = '<?php echo esc_js( home_url('/wp-json') ); ?>/avision/v1/google-updates-proxy';
	  var allUpdates = [];
	  var activeCat = '';
	  var activeKeyword = '';
	  var searchVal = '';

	  function renderCards(items){
	    var el = document.getElementById('aviGuCards');
	    if(!items.length){ el.innerHTML='<div class="avi-gu-empty">No updates found.</div>'; return; }
	    var html = '';
	    items.forEach(function(u){
	      var impact = u.impact || 'low';
	      var titleClean = String(u.title || '').replace(/^Date:\s*\d{4}-\d{2}-\d{2}\.\s*/i, '');
	      var impactLabel = impact === 'high' ? 'High' : (impact === 'medium' ? 'Medium' : 'Low');
	      var dt = String(u.update_date || '');
	      var dtPretty = dt;
	      try {
	        var d = new Date(dt);
	        if (!isNaN(d.getTime())) {
	          dtPretty = d.toLocaleDateString('en-GB', { year:'numeric', month:'short', day:'2-digit' });
	        }
	      } catch(e) {}
	      var dashIdx = titleClean.indexOf(' — ');
	      if (dashIdx === -1) dashIdx = titleClean.indexOf(' - ');
	      var tag = dashIdx > -1 ? titleClean.substring(0, dashIdx).toLowerCase() : 'untagged';
	      html += '<details class="avi-gu-card" data-impact="'+impact+'" data-filter-tag="'+escHtml(tag)+'">';
	      html += '<summary class="avi-gu-card-header">';
	      html += '<div class="avi-gu-card-title">'+escHtml(titleClean)+'</div>';
	      html += '<div>';
	      html += '<div class="avi-gu-card-meta">';
	      html += '<span class="avi-gu-badge">'+(u.source_name && u.source_name.indexOf('Google') > -1 ? '🏛️ ' : '🎓 ')+escHtml(u.source_name||'')+'</span>';
	      html += '<span class="avi-gu-badge">'+escHtml(dtPretty)+'</span>';
	      html += '<span class="avi-gu-badge">'+escHtml(impactLabel)+'</span>';
	      html += '</div>';
	      html += '<div class="avi-gu-card-toggle">Click to expand</div>';
	      html += '</div>';
	      html += '</summary>';
	      html += '<div class="avi-gu-card-body">';
	      html += '<div>'+escHtml(u.summary||'')+'</div>';
	      html += '<div class="avi-gu-card-meta" style="margin-top:10px">';
	      html += '<span class="avi-gu-badge">Date: '+escHtml(dtPretty)+'</span>';
	      html += '</div>';
	      html += '</div>';
	      html += '</details>';
	    });
	    el.innerHTML = html;
	  }

	  function filter(){
	    var items = allUpdates.filter(function(u){
	      var kw = String(activeKeyword || '').toLowerCase().trim();
	      var matchKeyword = true;
	      if (kw) {
	        var parts = kw.split(/\s+/).filter(function(x){ return !!x; });
	        var titleRaw = String(u.title || '');
	        var dashIdx = titleRaw.indexOf(' \u2014 ');
	        if (dashIdx === -1) dashIdx = titleRaw.indexOf(' - ');
	        var tag = dashIdx > -1 ? titleRaw.substring(0, dashIdx).toLowerCase() : '';
	        if (tag) {
	          matchKeyword = parts.some(function(p){ return tag.indexOf(p) > -1; });
	        } else {
	          matchKeyword = parts.some(function(p){
	            return titleRaw.toLowerCase().indexOf(p) > -1;
	          });
	        }
	      }
	      var matchSearch = !searchVal || (u.title+' '+(u.summary||'')).toLowerCase().indexOf(searchVal) > -1;
	      return matchKeyword && matchSearch;
	    });
	    renderCards(items);
	  }

	  function escHtml(s){
	    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
	  }

	  function load(){
	    fetch('<?php echo esc_url( rest_url('avision/v1/google-updates-proxy') ); ?>?status=injected&limit=50&audience=b2c')
	      .then(function(r){ return r.json(); })
	      .then(function(d){ allUpdates = d.updates || []; filter(); })
	      .catch(function(){
	        document.getElementById('aviGuCards').innerHTML =
	          '<div class="avi-gu-empty">Unable to load updates.</div>';
	      });
	  }

	  var searchEl = document.getElementById('aviGuSearch');
	  if (searchEl) {
	    searchEl.addEventListener('input', function(){
	      searchVal = this.value.toLowerCase(); filter();
	    });
	  }
	  document.querySelectorAll('.avi-gu-cat').forEach(function(btn){
	    btn.addEventListener('click', function(){
	      document.querySelectorAll('.avi-gu-cat').forEach(function(b){ b.classList.remove('active'); });
	      this.classList.add('active');
	      activeCat = this.dataset.cat || '';
	      activeKeyword = this.dataset.keyword || '';
	      filter();
	    });
	  });

	  load();
	})();
	</script>

	<div class="avi-email-prefs-footer">
		<button type="button"
			class="avi-unsubscribe-link"
			onclick="if (typeof aviOpenUnsubscribeModal === 'function') { aviOpenUnsubscribeModal('btoc'); }"
			aria-label="<?php echo esc_attr__( 'Manage email preferences', 'avision-dashboard' ); ?>">
			<?php echo esc_html__( 'Manage email preferences', 'avision-dashboard' ); ?>
		</button>
	</div>
	<?php require __DIR__ . '/avi-premium-b2c-modals.php'; ?>
</main>

<script>
document.addEventListener('DOMContentLoaded', function() {
    window.avisionScore = new AvisionScore('.score-circle');
    window.avisionScore.init(75);
});
</script>

<?php echo render_partial('footer'); ?>
