<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Partial affiché par le shortcode [avision_agency_dashboard] (pas de document HTML complet).
 * Accès : manage_options ou rôle avi_agency (voir class-avision-dashboard-route-guard.php).
 *
 * @package Avision
 */

$agency_admin_user_id = function_exists( 'get_current_user_id' ) ? (int) get_current_user_id() : 0;

// S10-D : Score moyen flotte depuis cache S9-A (lecture seule).
$fleet_cache = ( $agency_admin_user_id > 0 && function_exists( 'get_option' ) )
	? get_option( 'avi_fleet_kpis_cache_' . $agency_admin_user_id )
	: '';
$fleet_data  = $fleet_cache ? json_decode( $fleet_cache, true ) : array();
$fleet_data  = is_array( $fleet_data ) ? $fleet_data : array();
$avg_score   = isset( $fleet_data['avg_score'] ) ? (int) $fleet_data['avg_score'] : null;
$cache_age   = null;
if ( isset( $fleet_data['updated_at'] ) && is_string( $fleet_data['updated_at'] ) && $fleet_data['updated_at'] !== '' && function_exists( 'human_time_diff' ) && function_exists( 'current_time' ) ) {
	$ts = strtotime( $fleet_data['updated_at'] . ' UTC' );
	if ( $ts ) {
		$cache_age = human_time_diff( $ts, current_time( 'timestamp' ) );
	}
}

// S10-D : fiches agence (score BDD S9-A) + tri par criticité.
$listings = array();
if ( $agency_admin_user_id > 0 && isset( $GLOBALS['wpdb'] ) && is_object( $GLOBALS['wpdb'] ) ) {
	global $wpdb;
	$t_profiles = $wpdb->prefix . 'avi_saas_profiles';
	$t_agencies = $wpdb->prefix . 'avi_saas_agencies';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t_profiles ) ) === $t_profiles
		&& $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $t_agencies ) ) === $t_agencies ) {
		$listings = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT p.id, p.business_name, p.user_id, p.score, p.guardian_active,
				        COALESCE(p.uuid, '') AS uuid,
				        COALESCE(p.radar_plan, 'offert') AS radar_plan,
				        COALESCE(p.avi_bundle, '') AS avi_bundle
				 FROM `{$t_profiles}` p
				 INNER JOIN `{$t_agencies}` ag ON ag.id = p.agency_id AND ag.admin_user_id = %d
				 WHERE p.user_id IS NOT NULL
				 ORDER BY p.id ASC
				 LIMIT 200",
				$agency_admin_user_id
			),
			ARRAY_A
		);
		if ( ! is_array( $listings ) ) {
			$listings = array();
		}
	}
}

foreach ( $listings as $k => $row ) {
	if ( ! is_array( $row ) ) {
		continue;
	}
	$sc = isset( $row['score'] ) ? (int) $row['score'] : 0;
	if ( $sc < 40 ) {
		$listings[ $k ]['tier'] = 'critical';
	} elseif ( $sc <= 70 ) {
		$listings[ $k ]['tier'] = 'warning';
	} else {
		$listings[ $k ]['tier'] = 'healthy';
	}
}

if ( ! empty( $listings ) ) {
	usort(
		$listings,
		static function ( $a, $b ) {
			$tier_order = array(
				'critique' => 0,
				'critical' => 0,
				'warning'  => 1,
				'attention'=> 1,
				'healthy'  => 2,
			);
			$ta = $tier_order[ strtolower( (string) ( $a['tier'] ?? 'healthy' ) ) ] ?? 2;
			$tb = $tier_order[ strtolower( (string) ( $b['tier'] ?? 'healthy' ) ) ] ?? 2;
			if ( $ta !== $tb ) {
				return $ta <=> $tb;
			}
			return ( (int) ( $a['score'] ?? 0 ) ) <=> ( (int) ( $b['score'] ?? 0 ) );
		}
	);
}
?>
<section class="avision-agency-dashboard-partial" aria-label="<?php echo esc_attr__( 'Cockpit agence', 'avision-dashboard' ); ?>">
	<header class="avision-agency-dashboard-partial__header">
		<h2 class="avision-agency-dashboard-partial__title"><?php esc_html_e( 'Cockpit agence', 'avision-dashboard' ); ?></h2>
	</header>
	<div class="avision-agency-dashboard-partial__body">
		<!-- 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 = 'b2b';

		    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>
		<p><?php esc_html_e( 'Espace réservé aux administrateurs et au rôle avi_agency. Remplacez ce bloc par votre interface ou surchargez le filtre avision_agency_dashboard_shortcode_html.', 'avision-dashboard' ); ?></p>

		<?php if ( $avg_score !== null ) : ?>
		<div class="avi-fleet-score-bar" style="display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin:12px 0;padding:10px 14px;background:#f6f7f9;border-radius:8px;border:1px solid #e2e4e8;">
			<span class="avi-fleet-score-label" style="font-weight:600;"><?php esc_html_e( 'Score moyen flotte', 'avision-dashboard' ); ?></span>
			<span class="avi-fleet-score-value <?php echo $avg_score >= 70 ? 'avi-score-green' : ( $avg_score >= 40 ? 'avi-score-orange' : 'avi-score-red' ); ?>" style="font-weight:700;font-size:1.1em;">
				<?php echo esc_html( (string) $avg_score . '/100' ); ?>
			</span>
			<?php if ( $cache_age ) : ?>
				<span class="avi-fleet-score-age" style="color:#666;font-size:.9em;">
					<?php
					/* translators: %s human-readable time since cache update */
					echo esc_html( sprintf( __( 'Mis à jour il y a %s', 'avision-dashboard' ), $cache_age ) );
					?>
				</span>
			<?php endif; ?>
		</div>
		<?php endif; ?>

		<style>
			.avi-score-green { color: #1a7f37; }
			.avi-score-orange { color: #b35900; }
			.avi-score-red { color: #c5221f; }
			.avi-filter-btn.avi-filter-has-critical { box-shadow: 0 0 0 2px rgba(197,34,31,.35); }
			.avi-filter-badge { margin-left: 6px; font-size: 0.85em; opacity: 0.9; }
			.avi-listing-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; margin: 16px 0; }
			.avi-listing-card { border: 1px solid #e2e4e8; border-radius: 8px; padding: 12px; background: #fff; }
			.avi-listing-card h4 { margin: 0 0 8px; font-size: 1rem; }
			.avi-price-display-row { margin: 6px 0 12px; font-size: 0.95em; line-height: 1.35; }
			.avi-price-display-row .avi-price-full { color: #888; margin-right: 8px; }
			.avi-price-display-row .avi-price-launch { font-weight: 700; color: #111; }
			.avi-price-display-row .avi-price-launch small { font-weight: 500; color: #555; margin-left: 2px; }
			.avi-price-badge { display: inline-block; margin-left: 8px; font-size: 0.72em; font-weight: 600; color: #b45309; background: #fff7ed; padding: 2px 8px; border-radius: 4px; vertical-align: middle; }
			.avi-wholesale-pricing { margin: 24px 0; padding: 18px; border: 1px solid #e2e4e8; border-radius: 12px; background: #fafbfc; }
			.avi-wholesale-pricing h3 { margin-top: 0; }
			.avi-wholesale-grid { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 12px; }
			.avi-wholesale-card { flex: 1; min-width: 200px; padding: 14px; border: 1px solid #ddd; border-radius: 8px; background: #fff; }
			.avi-ws-price { font-size: 1.25em; font-weight: 700; margin: 8px 0; }
			.avi-btn-ws { margin-top: 8px; }
			.avi-tier-info { font-size: 0.95em; color: #444; }
			.avi-ws-note { font-size: 0.85em; color: #666; margin-top: 14px; }
		</style>

		<?php
		$avi_price_btob_full    = function_exists( 'get_option' ) ? (string) get_option( 'avi_price_display_btob_full', '$159' ) : '$159';
		$avi_price_btob_launch  = function_exists( 'get_option' ) ? (string) get_option( 'avi_price_display_btob_launch', '$99' ) : '$99';
		$avi_ws_fleet_count     = isset( $fleet_data['managed_listings_count'] ) ? max( 0, (int) $fleet_data['managed_listings_count'] ) : count( $listings );
		$avi_ws_tier            = function_exists( 'avi_get_wholesale_tier' ) ? avi_get_wholesale_tier( $avi_ws_fleet_count ) : 1;
		$avi_ws_tier_labels     = array(
			1 => __( '1–10 fiches', 'avision-dashboard' ),
			2 => __( '11–50 fiches', 'avision-dashboard' ),
			3 => __( '51+ fiches', 'avision-dashboard' ),
		);
		$avi_ws_tier_label      = isset( $avi_ws_tier_labels[ $avi_ws_tier ] ) ? $avi_ws_tier_labels[ $avi_ws_tier ] : $avi_ws_tier_labels[1];
		$avi_ws_guardian_prices = array( 1 => '26€', 2 => '24€', 3 => '19€' );
		$avi_ws_hebdo_prices    = array( 1 => '6€', 2 => '5€', 3 => '3€' );
		$avi_ws_elite_prices    = array( 1 => '12€', 2 => '12€', 3 => '10€' );
		$avi_ws_guardian_price  = isset( $avi_ws_guardian_prices[ $avi_ws_tier ] ) ? $avi_ws_guardian_prices[ $avi_ws_tier ] : $avi_ws_guardian_prices[1];
		$avi_ws_hebdo_price     = isset( $avi_ws_hebdo_prices[ $avi_ws_tier ] ) ? $avi_ws_hebdo_prices[ $avi_ws_tier ] : $avi_ws_hebdo_prices[1];
		$avi_ws_elite_price     = isset( $avi_ws_elite_prices[ $avi_ws_tier ] ) ? $avi_ws_elite_prices[ $avi_ws_tier ] : $avi_ws_elite_prices[1];
		?>
		<div class="avi-wholesale-pricing" id="avi-wholesale-pricing">
			<h3><?php esc_html_e( 'Options Premium — Tarifs agence (wholesale)', 'avision-dashboard' ); ?></h3>
			<p style="margin:0 0 12px;font-size:.9em;color:#555;">
				<?php esc_html_e( 'Tarifs indicatifs B2B (palier selon la taille de la flotte). Les montants Stripe réels viennent des Price IDs configurés en base.', 'avision-dashboard' ); ?>
			</p>
			<div class="avi-price-display-row" aria-label="<?php esc_attr_e( 'Prix indicatif agence', 'avision-dashboard' ); ?>">
				<span class="avi-price-full"><s><?php echo esc_html( $avi_price_btob_full ); ?></s></span>
				<span class="avi-price-launch"><?php echo esc_html( $avi_price_btob_launch ); ?><small><?php esc_html_e( '/mois', 'avision-dashboard' ); ?></small></span>
				<span class="avi-price-badge"><?php esc_html_e( 'Prix de lancement', 'avision-dashboard' ); ?></span>
			</div>
			<p class="avi-tier-info">
				<?php esc_html_e( 'Votre palier actuel (estimation)', 'avision-dashboard' ); ?> :
				<strong><?php echo esc_html( $avi_ws_tier_label ); ?></strong>
				<?php esc_html_e( '— tarifs dégressifs appliqués automatiquement à l’activation wholesale.', 'avision-dashboard' ); ?>
			</p>
			<div class="avi-wholesale-grid">
				<div class="avi-wholesale-card">
					<h4><?php esc_html_e( '🛡️ Guardian Mode', 'avision-dashboard' ); ?></h4>
					<p class="avi-ws-price"><?php echo esc_html( $avi_ws_guardian_price ); ?><small><?php esc_html_e( '/fiche/mois', 'avision-dashboard' ); ?></small></p>
					<p style="font-size:.9em;color:#555;"><?php esc_html_e( '12 signaux · veille 24/7', 'avision-dashboard' ); ?></p>
					<?php
					if ( function_exists( 'avi_render_wholesale_checkout_button' ) ) {
						avi_render_wholesale_checkout_button( 'guardian', (int) $avi_ws_tier, __( 'Guardian wholesale', 'avision-dashboard' ), (string) $avi_ws_guardian_price, $agency_admin_user_id );
					}
					?>
				</div>
				<div class="avi-wholesale-card">
					<h4><?php esc_html_e( '📡 Radar Hebdo', 'avision-dashboard' ); ?></h4>
					<p class="avi-ws-price"><?php echo esc_html( $avi_ws_hebdo_price ); ?><small><?php esc_html_e( '/fiche/mois', 'avision-dashboard' ); ?></small></p>
					<p style="font-size:.9em;color:#555;"><?php esc_html_e( '75 mots-clés · scan 7j', 'avision-dashboard' ); ?></p>
					<?php
					if ( function_exists( 'avi_render_wholesale_checkout_button' ) ) {
						avi_render_wholesale_checkout_button( 'hebdo', (int) $avi_ws_tier, __( 'Radar Hebdo wholesale', 'avision-dashboard' ), (string) $avi_ws_hebdo_price, $agency_admin_user_id );
					}
					?>
				</div>
				<div class="avi-wholesale-card">
					<h4><?php esc_html_e( '🚀 Radar Élite', 'avision-dashboard' ); ?></h4>
					<p class="avi-ws-price"><?php echo esc_html( $avi_ws_elite_price ); ?><small><?php esc_html_e( '/fiche/mois', 'avision-dashboard' ); ?></small></p>
					<p style="font-size:.9em;color:#555;"><?php esc_html_e( '100 mots-clés · scan 24h', 'avision-dashboard' ); ?></p>
					<?php
					if ( function_exists( 'avi_render_wholesale_checkout_button' ) ) {
						avi_render_wholesale_checkout_button( 'elite', (int) $avi_ws_tier, __( 'Radar Élite wholesale', 'avision-dashboard' ), (string) $avi_ws_elite_price, $agency_admin_user_id );
					}
					?>
				</div>
			</div>
			<p class="avi-ws-note">
				<?php esc_html_e( '* Les boutons d’achat wholesale seront activés après la création des produits dans Stripe et l’injection des Price IDs en options WordPress. Contactez-nous pour activer dès maintenant.', 'avision-dashboard' ); ?>
			</p>
		</div>

		<?php if ( ! empty( $listings ) ) : ?>
		<div class="avi-agency-managed-listings" style="margin-top:20px;">
			<h3 style="margin-bottom:10px;"><?php esc_html_e( 'Fiches gérées', 'avision-dashboard' ); ?></h3>
			<div class="avi-listing-cards">
				<?php foreach ( $listings as $listing ) : ?>
					<?php
					if ( ! is_array( $listing ) ) {
						continue;
					}
					$name         = isset( $listing['business_name'] ) ? (string) $listing['business_name'] : '';
					$fiche_score  = (int) ( $listing['score'] ?? 0 );
					$score_class  = $fiche_score >= 70 ? 'avi-score-green' : ( $fiche_score >= 40 ? 'avi-score-orange' : 'avi-score-red' );
					$score_label  = $fiche_score > 0 ? ( (string) $fiche_score . '/100' ) : __( 'Score en calcul…', 'avision-dashboard' );
					$g_active     = ! empty( $listing['guardian_active'] ) && (int) $listing['guardian_active'] === 1;
					$client_uuid  = isset( $listing['uuid'] ) ? trim( (string) $listing['uuid'] ) : '';
					$premium_url  = function_exists( 'trailingslashit' ) && function_exists( 'home_url' ) && function_exists( 'add_query_arg' ) && $client_uuid !== ''
						? add_query_arg( 'pid', rawurlencode( $client_uuid ), trailingslashit( home_url( '/premium-dashboard/' ) ) )
						: trailingslashit( home_url( '/premium-dashboard/' ) );
					?>
					<div class="avi-listing-card">
						<h4><?php echo esc_html( $name !== '' ? $name : __( '(Sans nom)', 'avision-dashboard' ) ); ?></h4>
						<div class="avi-listing-score <?php echo esc_attr( $score_class ); ?>" style="font-size:.95em;">
							<span class="avi-score-dot" aria-hidden="true">●</span>
							<span class="avi-score-val"><?php echo esc_html( $score_label ); ?></span>
						</div>
						<?php
						$fiche_radar  = isset( $listing['radar_plan'] ) ? (string) $listing['radar_plan'] : 'offert';
						$fiche_bundle = isset( $listing['avi_bundle'] ) ? (string) $listing['avi_bundle'] : '';
						$fiche_radar_label = array(
							'offert'  => 'Radar : 20 kw (free)',
							'hebdo'   => 'Radar : 75 kw/week',
							'elite'   => 'Radar : 100+ kw/day',
						);
						$fiche_bundle_labels = array(
							'starter_pro' => 'Pack Starter Pro',
							'elite_pro'   => 'Pack Elite Pro',
						);
						?>
						<p style="margin:8px 0 0;font-size:.85em;color:#555;">
							<?php echo $g_active
								? '<span style="color:#16a34a;">● Guardian : active</span>'
								: '<span style="color:#dc2626;">● Guardian : inactive</span>'; ?>
						</p>
						<p style="margin:4px 0 0;font-size:.85em;color:#555;">
							<?php echo esc_html(
								isset( $fiche_radar_label[ $fiche_radar ] )
									? $fiche_radar_label[ $fiche_radar ]
									: 'Radar : offert'
							); ?>
						</p>
						<?php if ( $fiche_bundle !== '' && isset( $fiche_bundle_labels[ $fiche_bundle ] ) ) : ?>
						<p style="margin:4px 0 0;font-size:.85em;color:#6366f1;font-weight:600;">
							<?php echo esc_html( $fiche_bundle_labels[ $fiche_bundle ] ); ?>
						</p>
						<?php endif; ?>
						<a href="<?php echo esc_url( $premium_url ); ?>" class="avi-btn-small" style="display:inline-block;margin-top:8px;font-size:.85em;">
							<?php
							echo $g_active
								? esc_html__( '→ Cockpit client (gérer abonnement / Guardian)', 'avision-dashboard' )
								: esc_html__( '→ Ouvrir le cockpit client (abonnement sur son compte)', 'avision-dashboard' );
							?>
						</a>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php endif; ?>

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

		<?php
		// S9-B — Script + nonce pour le centre d'alertes (READ ONLY).
		if ( function_exists( 'wp_enqueue_script' ) ) {
			$src = defined( 'AVISION_URL' ) ? trailingslashit( AVISION_URL ) . 'assets/js/agency-dashboard.js' : '';
			$ver = defined( 'AVISION_VERSION' ) ? AVISION_VERSION : '1.0';
			if ( function_exists( 'plugin_dir_path' ) && defined( 'AVISION_PLUGIN_FILE' ) ) {
				$p = trailingslashit( plugin_dir_path( AVISION_PLUGIN_FILE ) ) . 'assets/js/agency-dashboard.js';
				if ( is_string( $p ) && $p !== '' && @file_exists( $p ) ) {
					$ver = (string) @filemtime( $p );
				}
			}
			if ( $src !== '' ) {
				wp_enqueue_script( 'avision-agency-dashboard', $src, array(), $ver, true );
				if ( function_exists( 'wp_localize_script' ) && function_exists( 'wp_create_nonce' ) && function_exists( 'admin_url' ) ) {
					wp_localize_script(
						'avision-agency-dashboard',
						'aviAgencyData',
						array(
							'nonce'            => wp_create_nonce( 'avision_agency_nonce' ),
							'ajaxurl'          => admin_url( 'admin-ajax.php' ),
							'alertRefreshMs'   => defined( 'AVI_S10D_ALERTS_REFRESH_INTERVAL_S' ) ? (int) AVI_S10D_ALERTS_REFRESH_INTERVAL_S * 1000 : 300000,
							's10dUiVersion'    => defined( 'AVI_S10D_UI_VERSION' ) ? (string) AVI_S10D_UI_VERSION : '1.0',
						)
					);
				}
			}
		}
		?>

		<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-agency { background:#fff; box-shadow: 0 2px 12px rgba(0,0,0,.06); border-radius: 12px; padding: 24px; margin: 40px auto; max-width: 1140px; }
		#aviGuAgency { background:#fff; border-radius:12px; box-shadow:0 2px 12px rgba(0,0,0,.06); padding:24px; margin:40px auto; max-width:1140px; color:#1a1a2e !important; }
		#aviGuAgency {
			display: block !important;
			max-width: 1140px !important;
			margin: 40px auto !important;
			padding: 24px !important;
			background: #fff !important;
			border-radius: 12px !important;
			box-shadow: 0 2px 12px rgba(0,0,0,.06) !important;
			box-sizing: border-box !important;
			color: #1a1a2e !important;
		}
		.avi-gu-agency .avi-gu-cards {
			display: grid !important;
			grid-template-columns: repeat(auto-fill, minmax(280px,1fr)) !important;
			gap: 16px !important;
		}
		.avi-gu-agency h2 { font-size:22px; font-weight:700; margin-bottom:16px; }
		.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 { background:#f0f0f0; color:#333; padding:2px 8px; border-radius:10px; 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 — Fleet Intelligence', '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-agency" id="aviGuAgency">
		  <input type="text" class="avi-gu-search" id="aviGuSearchAgency"
		         placeholder="<?php echo esc_attr__('Search updates...', 'avision-dashboard'); ?>">
		  <div class="avi-gu-cats" id="aviGuCatsAgency">
		    <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>
		    <button class="avi-gu-cat" data-keyword="fleet">🚀 Fleet Impact</button>
		    <button class="avi-gu-cat" data-keyword="multi location">🏢 Multi-Location</button>
		  </div>
		  <div class="avi-gu-cards" id="aviGuCardsAgency">
		    <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 impactOnlyHigh = false;
		  var searchVal = '';

		  function renderCards(items){
		    var el = document.getElementById('aviGuCardsAgency');
		    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 matchImpact = !impactOnlyHigh || (String(u.impact || 'low') === 'high');
		      var matchSearch = !searchVal || (u.title+' '+(u.summary||'')).toLowerCase().indexOf(searchVal) > -1;
		      return matchKeyword && matchImpact && 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=b2b')
		      .then(function(r){ return r.json(); })
		      .then(function(d){ allUpdates = d.updates || []; filter(); })
		      .catch(function(){
		        document.getElementById('aviGuCardsAgency').innerHTML =
		          '<div class="avi-gu-empty">Unable to load updates.</div>';
		      });
		  }

		  var searchEl = document.getElementById('aviGuSearchAgency');
		  if (searchEl) {
		    searchEl.addEventListener('input', function(){
		      searchVal = this.value.toLowerCase(); filter();
		    });
		  }

		  document.querySelectorAll('#aviGuCatsAgency .avi-gu-cat').forEach(function(btn){
		    btn.addEventListener('click', function(){
		      document.querySelectorAll('#aviGuCatsAgency .avi-gu-cat').forEach(function(b){ b.classList.remove('active'); });
		      this.classList.add('active');
		      activeCat = this.dataset.cat || '';
		      activeKeyword = this.dataset.keyword || '';
		      impactOnlyHigh = (this.dataset.impactFilter === 'high');
		      filter();
		    });
		  });

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

		<!-- S9-B : Centre d'alertes flotte — READ ONLY -->
		<div id="avi-agency-alerts-panel" class="avi-panel avi-panel-alerts">
			<div class="avi-panel-header">
				<span>🔔</span>
				<h3>Centre d'alertes flotte
					<sup style="font-size:10px;color:#888">Lecture seule</sup>
				</h3>
				<div class="avi-alerts-filters">
					<button type="button" class="avi-filter-btn active" data-avi-filter="all" onclick="aviLoadAgencyAlerts({filter:'all'})"><?php esc_html_e( 'Tout', 'avision-dashboard' ); ?></button>
					<button type="button" class="avi-filter-btn" data-avi-filter="critical" onclick="aviLoadAgencyAlerts({filter:'critical'})">🔴 <?php esc_html_e( 'Critiques', 'avision-dashboard' ); ?></button>
					<button type="button" class="avi-filter-btn" data-avi-filter="warning" onclick="aviLoadAgencyAlerts({filter:'warning'})">🟠 <?php esc_html_e( 'Attention', 'avision-dashboard' ); ?></button>
					<select id="avi-agency-alerts-days" aria-label="<?php echo esc_attr__( 'Période', 'avision-dashboard' ); ?>">
						<option value="7">7 jours</option>
						<option value="14">14 jours</option>
						<option value="30">30 jours</option>
					</select>
				</div>
			</div>
			<div id="avi-agency-alerts-container">
				<!-- Chargé par aviLoadAgencyAlerts() -->
			</div>
		</div>

		<?php
		$avi_agency_name_for_chat = __( 'Your Agency', 'avision-dashboard' );
		if ( $agency_admin_user_id > 0 && function_exists( 'get_userdata' ) ) {
			$avi_ag_u = get_userdata( $agency_admin_user_id );
			if ( $avi_ag_u && is_string( $avi_ag_u->display_name ) && trim( $avi_ag_u->display_name ) !== '' ) {
				$avi_agency_name_for_chat = $avi_ag_u->display_name;
			}
		}
		$avi_chat_args = array(
			'variant'                => 'agency',
			'is_b2b_fleet_context'   => true,
			'is_hotel'               => false,
			'show_whisper'           => false,
			'chat_dashboard_type'    => 'b2b_fleet',
			'fleet_agency_user_id'   => (int) $agency_admin_user_id,
			'fleet_agency_name'      => (string) $avi_agency_name_for_chat,
			'fleet_avg_score'        => ( $avg_score !== null ) ? (int) $avg_score : 0,
			'fleet_managed_count'    => (int) count( $listings ),
		);
		if ( function_exists( 'get_template_part' ) ) {
			get_template_part( 'template-parts/components/avi-chat-widget', null, $avi_chat_args );
		}
		?>
	<?php require __DIR__ . '/page-agency-b2b-modals.php'; ?>
	</div>
</section>
