<?php
/**
 * Avision Embed — Endpoint iframe signé HMAC
 * #Sprint44-Plugin
 *
 * Route publique : GET /wp-json/avision/v1/embed
 * Paramètres     : key_id, sig, profile_id, lang, tabs
 * Auth           : HMAC-SHA256 (key_id + profile_id + ts) signé
 *                  avec le secret de la clé embed
 *
 * @package Avision
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Avision_Embed {

	// Tolérance timestamp : 365 jours (plugin WP — URL regénérée à chaque chargement admin)
	const SIG_TTL = 31536000;

	// Onglets autorisés
	const ALLOWED_TABS = array( 'map', 'evolution', 'competitors', 'coverage', 'battle' );

	private static $embed_price_ids = array(
		'nano'              => 'price_1TsGiILhwIe2NLTF8fPXJe8A',
		'mini'              => 'price_1TsGk0LhwIe2NLTF6BdmLbZ6',
		'standard'          => 'price_1TsGlTLhwIe2NLTF3GqdXpP7',
		'pro'               => 'price_1TsGmeLhwIe2NLTFw7jPjaNA',
		'starter_agency'    => 'price_1TsGnjLhwIe2NLTF2oHPQUFh',
		'standard_agency'   => 'price_1TsGp4LhwIe2NLTFJNPnVLub',
		'pro_agency'        => 'price_1TsGq5LhwIe2NLTFisXxKXuQ',
		'enterprise_agency' => 'price_1TsGrMLhwIe2NLTF5ONYVKlp',
	);

	private static $embed_pack_credits = array(
		'nano'              => 10,
		'mini'              => 30,
		'standard'          => 75,
		'pro'               => 200,
		'starter_agency'    => 100,
		'standard_agency'   => 300,
		'pro_agency'        => 750,
		'enterprise_agency' => 2000,
	);

	/* Paliers prix/crédit solo (price_data dynamique) */
	private static $solo_credit_tiers = array(
		array(
			'min'   => 1,
			'max'   => 99,
			'price' => 0.200,
		),
		array(
			'min'   => 100,
			'max'   => 299,
			'price' => 0.167,
		),
		array(
			'min'   => 300,
			'max'   => 749,
			'price' => 0.147,
		),
		array(
			'min'   => 750,
			'max'   => 1999,
			'price' => 0.125,
		),
		array(
			'min'   => 2000,
			'max'   => 9999,
			'price' => 0.098,
		),
	);

	/* Paliers prix/crédit agence (price_data dynamique) */
	private static $agency_credit_tiers = array(
		array(
			'min'   => 1,
			'max'   => 99,
			'price' => 0.140,
		),
		array(
			'min'   => 100,
			'max'   => 299,
			'price' => 0.117,
		),
		array(
			'min'   => 300,
			'max'   => 749,
			'price' => 0.100,
		),
		array(
			'min'   => 750,
			'max'   => 1999,
			'price' => 0.093,
		),
		array(
			'min'   => 2000,
			'max'   => 9999,
			'price' => 0.088,
		),
	);

	/**
	 * Enregistre les hooks WordPress du module embed.
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'rest_api_init', array( __CLASS__, 'register_routes' ) );
		add_action( 'admin_post_avi_le_logout', array( __CLASS__, 'handle_localedge_logout' ) );
		add_action( 'admin_post_nopriv_avi_le_logout', array( __CLASS__, 'handle_localedge_logout' ) );
		add_action( 'avi_guardian_monthly_billing', array( __CLASS__, 'run_guardian_monthly_billing' ) );
		if ( ! wp_next_scheduled( 'avi_guardian_monthly_billing' ) ) {
			wp_schedule_event( strtotime( 'first day of next month midnight' ), 'monthly', 'avi_guardian_monthly_billing' );
		}
		add_action( 'init', array( __CLASS__, 'maybe_migrate_media_display_name' ), 5 );
		add_action( 'init', array( __CLASS__, 'maybe_migrate_media_gbp_status' ), 5 );
		add_action( 'init', array( __CLASS__, 'maybe_migrate_media_gbp_media_name' ), 5 );
	}

	/**
	 * Déconnexion LocalEdge hosted — bypass wp_logout hook thème (redirect forcé vers /).
	 *
	 * @return void
	 */
	public static function handle_localedge_logout() {
		$redirect = home_url( '/localedge-login/' );
		if ( ! is_user_logged_in() ) {
			wp_safe_redirect( $redirect );
			exit;
		}
		check_admin_referer( 'avi_le_logout' );
		$user_id = get_current_user_id();
		wp_destroy_current_session();
		wp_clear_auth_cookie();
		wp_set_current_user( 0 );
		if ( function_exists( 'avi_clear_oauth_redirect_state_on_logout' ) ) {
			avi_clear_oauth_redirect_state_on_logout( $user_id );
		}
		wp_safe_redirect( add_query_arg( 'loggedout', 'true', $redirect ) );
		exit;
	}

	/**
	 * URL de déconnexion LocalEdge (admin-post, sans wp-login.php?action=logout).
	 *
	 * @return string
	 */
	public static function get_localedge_logout_url() {
		return wp_nonce_url(
			admin_url( 'admin-post.php?action=avi_le_logout' ),
			'avi_le_logout'
		);
	}

	/**
	 * Migration one-shot : colonne display_name sur avi_saas_media.
	 *
	 * @return void
	 */
	public static function maybe_migrate_media_display_name() {
		global $wpdb;
		$table = $wpdb->prefix . 'avi_saas_media';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			return;
		}
		$col = $wpdb->get_results(
			"SHOW COLUMNS FROM `{$table}` LIKE 'display_name'"
		);
		if ( empty( $col ) ) {
			$wpdb->query(
				"ALTER TABLE `{$table}`
				ADD COLUMN `display_name` varchar(255) DEFAULT NULL
				AFTER `file_path`"
			);
		}
	}

	/**
	 * Migration one-shot : colonne gbp_status sur avi_saas_media.
	 * #SprintL2-photos-fix
	 *
	 * @return void
	 */
	public static function maybe_migrate_media_gbp_status() {
		global $wpdb;
		$table = $wpdb->prefix . 'avi_saas_media';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			return;
		}
		$col = $wpdb->get_results(
			"SHOW COLUMNS FROM `{$table}` LIKE 'gbp_status'"
		);
		if ( empty( $col ) ) {
			$wpdb->query(
				"ALTER TABLE `{$table}`
				ADD COLUMN `gbp_status` varchar(20) DEFAULT NULL
				AFTER `status`"
			);
		}
	}

	/**
	 * Migration one-shot : colonne gbp_media_name sur avi_saas_media.
	 *
	 * @return void
	 */
	public static function maybe_migrate_media_gbp_media_name() {
		global $wpdb;
		$table = $wpdb->prefix . 'avi_saas_media';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			return;
		}
		$col = $wpdb->get_results(
			"SHOW COLUMNS FROM `{$table}` LIKE 'gbp_media_name'"
		);
		if ( empty( $col ) ) {
			$wpdb->query(
				"ALTER TABLE `{$table}`
				ADD COLUMN `gbp_media_name` varchar(512) DEFAULT NULL
				AFTER `gbp_status`"
			);
		}
	}

	/**
	 * Enregistre les routes REST embed.
	 *
	 * @return void
	 */
	public static function register_routes() {
		global $wpdb;
		$table = $wpdb->prefix . 'avi_embed_keys';
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) === $table ) {
			$cols = $wpdb->get_col( "SHOW COLUMNS FROM `{$table}`" );
			if ( ! is_array( $cols ) ) {
				$cols = array();
			}
			if ( ! in_array( 'logo_url', $cols, true ) ) {
				$wpdb->query(
					"ALTER TABLE `{$table}`
					ADD COLUMN `logo_url` varchar(500) NULL DEFAULT NULL
					AFTER `label`"
				);
			}
			if ( ! in_array( 'white_label_name', $cols, true ) ) {
				$wpdb->query(
					"ALTER TABLE `{$table}`
					ADD COLUMN `white_label_name` varchar(100) NULL DEFAULT NULL
					AFTER `logo_url`"
				);
			}
			$cols = $wpdb->get_col(
				"SELECT COLUMN_NAME
				 FROM INFORMATION_SCHEMA.COLUMNS
				 WHERE TABLE_SCHEMA = DATABASE()
				   AND TABLE_NAME = '{$wpdb->prefix}avi_embed_keys'"
			);
			if ( ! is_array( $cols ) ) {
				$cols = array();
			}
			if ( ! in_array( 'domain', $cols, true ) ) {
				$wpdb->query(
					"ALTER TABLE `{$wpdb->prefix}avi_embed_keys`
					 ADD COLUMN `domain` VARCHAR(255) NULL DEFAULT NULL
					 AFTER `allowed_domains`"
				);
			}
			if ( ! in_array( 'purchase_code', $cols, true ) ) {
				$wpdb->query(
					"ALTER TABLE `{$wpdb->prefix}avi_embed_keys`
					 ADD COLUMN `purchase_code` VARCHAR(100)
					 NULL DEFAULT NULL
					 AFTER `domain`"
				);
			}
		}

		/* ── avi_embed_credits (LocalEdge crédits séparés) ── */
		$table_embed_credits = $wpdb->prefix . 'avi_embed_credits';
		if ( $wpdb->get_var(
			"SELECT COUNT(*) FROM information_schema.TABLES
			 WHERE TABLE_SCHEMA = DATABASE()
			   AND TABLE_NAME = '{$table_embed_credits}'"
		) == 0 ) {
			$wpdb->query(
				"CREATE TABLE `{$table_embed_credits}` (
					`id`            BIGINT UNSIGNED NOT NULL
					                AUTO_INCREMENT,
					`key_id`        VARCHAR(32) NOT NULL,
					`profile_id`    BIGINT UNSIGNED NOT NULL,
					`credits_total` INT NOT NULL DEFAULT 0,
					`credits_used`  INT NOT NULL DEFAULT 0,
					`credits_bonus` INT NOT NULL DEFAULT 0,
					`pack_type`     VARCHAR(20) NULL DEFAULT NULL,
					`purchased_at`  DATETIME NOT NULL
					                DEFAULT CURRENT_TIMESTAMP,
					`expires_at`    DATETIME NULL DEFAULT NULL,
					`updated_at`    DATETIME NOT NULL
					                DEFAULT CURRENT_TIMESTAMP
					                ON UPDATE CURRENT_TIMESTAMP,
					PRIMARY KEY (`id`),
					UNIQUE KEY `uk_key_profile`
						(`key_id`, `profile_id`)
				) ENGINE=InnoDB
				  DEFAULT CHARSET=utf8mb4
				  COLLATE=utf8mb4_unicode_ci"
			);
		}

		register_rest_route(
			'avision/v1',
			'/embed',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'serve_embed' ),
				'permission_callback' => '__return_true',
				'args'                => array(
					'key_id'     => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
					'sig'        => array(
						'required'          => true,
						'sanitize_callback' => 'sanitize_text_field',
					),
					'profile_id' => array(
						'required'          => true,
						'sanitize_callback' => 'absint',
					),
					'ts'         => array(
						'required'          => true,
						'sanitize_callback' => 'absint',
					),
					'lang'       => array(
						'required'          => false,
						'default'           => 'en',
						'sanitize_callback' => 'sanitize_text_field',
					),
					'tabs'       => array(
						'required'          => false,
						'default'           => 'all',
						'sanitize_callback' => 'sanitize_text_field',
					),
					'theme'      => array(
						'required'          => false,
						'default'           => 'light',
						'sanitize_callback' => 'sanitize_text_field',
					),
					'logo_url'   => array(
						'required'          => false,
						'default'           => '',
						'sanitize_callback' => 'esc_url_raw',
					),
				),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/sign',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'sign_embed_url' ),
				'permission_callback' => array( __CLASS__, 'check_embed_auth' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/choose-location',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'choose_gbp_location' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/choose-locations-bulk',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'choose_gbp_locations_bulk' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/switch-profile',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'switch_profile' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/reply-review',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'reply_to_review' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		/* #SprintL2-reviews-ai — génération réponse avis via OpenRouter */
		register_rest_route(
			'avision/v1',
			'/embed/ai-review-reply',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'ai_review_reply' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/update-gbp',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'update_gbp_field' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/sync-profile',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'sync_profile_cache' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/gbp-categories',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'search_gbp_categories' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/create-post',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'create_post' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/avi-generate-post',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'handle_avi_generate_post' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/upload-photo',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'upload_photo' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/publish-photo',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'publish_photo' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/sync-photos',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'sync_photos' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/delete-photo',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'delete_photo' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/delete-photo-gbp',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'delete_photo_gbp' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/update-photo',
			array(
				'methods'             => 'PATCH',
				'callback'            => array( __CLASS__, 'handle_update_photo' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		/* #SprintL2-photos-ux — proxy téléchargement photo GBP (cross-origin) */
		register_rest_route(
			'avision/v1',
			'/embed/proxy-photo',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'proxy_photo_download' ),
				'permission_callback' => '__return_true',
			)
		);

		/* #SprintL2-L2.4-whitelabel — mise à jour logo + nom white-label */
		register_rest_route(
			'avision/v1',
			'/embed/update-key',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'update_embed_key' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		/* #SprintL2-L2.2-kw-crud — keywords embed CRUD */
		register_rest_route(
			'avision/v1',
			'/embed/keywords',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_embed_keywords' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/keywords',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'add_embed_keyword' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/keywords/(?P<id>\d+)',
			array(
				'methods'             => 'DELETE',
				'callback'            => array( __CLASS__, 'delete_embed_keyword' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/keywords/(?P<id>\d+)',
			array(
				'methods'             => 'PUT',
				'callback'            => array( __CLASS__, 'update_embed_keyword' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		/* #SprintL2-L2.3-assign-credits — pool agence → profil client */
		register_rest_route(
			'avision/v1',
			'/embed/assign-credits',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'assign_credits' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		/* #SprintL2-L2.3-bulk-fix — pool agence → plusieurs profils */
		register_rest_route(
			'avision/v1',
			'/embed/assign-credits-bulk',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'assign_credits_bulk' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/keys',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( __CLASS__, 'list_keys' ),
					'permission_callback' => array( __CLASS__, 'check_embed_auth' ),
				),
				array(
					'methods'             => 'POST',
					'callback'            => array( __CLASS__, 'create_key' ),
					'permission_callback' => array( __CLASS__, 'check_embed_auth' ),
				),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/activate',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'activate_embed_license' ),
				'permission_callback' => '__return_true',
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/checkout',
			array(
				'methods'             => 'POST',
				'callback'            => array(
					__CLASS__,
					'create_embed_checkout',
				),
				'permission_callback' => array(
					__CLASS__,
					'verify_embed_request',
				),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/agency-tier-change',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'handle_agency_tier_change' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/reviews-more',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'proxy_reviews_more' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/reviews-cache-save',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'save_reviews_cache' ),
				'permission_callback' => array( __CLASS__, 'verify_embed_request' ),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/keys/(?P<id>\d+)',
			array(
				array(
					'methods'             => 'DELETE',
					'callback'            => array( __CLASS__, 'revoke_key' ),
					'permission_callback' => array( __CLASS__, 'check_embed_auth' ),
				),
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/get-attributes-available',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'get_attributes_available' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/update-attribute',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'update_gbp_attribute' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);

		register_rest_route(
			'avision/v1',
			'/embed/guardian-alerts',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_guardian_alerts' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/guardian-alerts/mark-read',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'mark_guardian_alerts_read' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/guardian-plan',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_guardian_plan' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/guardian-deactivate',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'post_guardian_deactivate' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/guardian-activate',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'post_guardian_activate' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/citations',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_citations' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/citations/save',
			array(
				'methods'             => 'POST',
				'callback'            => array( __CLASS__, 'save_citation' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/citations/score',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_citations_score' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
		register_rest_route(
			'avision/v1',
			'/embed/score-history',
			array(
				'methods'             => 'GET',
				'callback'            => array( __CLASS__, 'get_score_history' ),
				'permission_callback' => function ( $request ) {
					$admin_key = $request->get_header( 'X-AVI-Admin-Key' );
					if ( $admin_key && defined( 'AVISION_ADMIN_API_KEY' ) && hash_equals( AVISION_ADMIN_API_KEY, $admin_key ) ) {
						return true;
					}
					return self::verify_embed_request( $request );
				},
			)
		);
	}

	/**
	 * Permission : admin WP ou clé admin interne.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return bool
	 */
	public static function check_embed_auth( \WP_REST_Request $request ) {
		if ( current_user_can( 'manage_options' ) ) {
			return true;
		}
		$auth = $request->get_header( 'X-AVI-Admin-Key' );
		$key  = defined( 'AVISION_ADMIN_API_KEY' ) ? AVISION_ADMIN_API_KEY : '';
		return ( $key && hash_equals( $key, (string) $auth ) );
	}

	/**
	 * Génère un token REST embed signé (TTL 2 h côté vérification).
	 * #Sprint44-Plugin
	 *
	 * @param string $key_id     Identifiant public de la clé embed.
	 * @param int    $profile_id ID profil.
	 * @return string
	 */
	public static function generate_embed_token(
		string $key_id,
		int $profile_id
	): string {
		$ts      = time();
		$payload = 'embed_rest|' . $key_id . '|' . $profile_id . '|' . $ts;
		$secret  = defined( 'AVISION_ADMIN_API_KEY' )
			? AVISION_ADMIN_API_KEY
			: wp_salt( 'auth' );
		return base64_encode( $ts . ':' . hash_hmac( 'sha256', $payload, $secret ) );
	}

	/**
	 * Vérifie un token REST embed (mode iframe public).
	 * #Sprint44-Plugin
	 *
	 * @param string $token      Token base64.
	 * @param int    $profile_id ID profil attendu.
	 * @return bool
	 */
	public static function verify_embed_token(
		string $token,
		int $profile_id,
		string $key_id = ''
	): bool {
		$decoded = base64_decode( $token );
		if ( ! $decoded ) {
			return false;
		}
		$parts = explode( ':', $decoded, 2 );
		if ( count( $parts ) !== 2 ) {
			return false;
		}
		list( $ts, $sig ) = $parts;
		if ( abs( time() - (int) $ts ) > 7200 ) {
			return false;
		}
		global $wpdb;
		if ( $key_id !== '' ) {
			$key_ok = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT key_id FROM `{$wpdb->prefix}avi_embed_keys`
					 WHERE key_id = %s AND status = 'active' LIMIT 1",
					$key_id
				)
			);
			if ( ! $key_ok ) {
				return false;
			}
		} else {
			$key_id = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT key_id FROM `{$wpdb->prefix}avi_embed_keys`
					 WHERE profile_id = %d AND status = 'active'
					 ORDER BY created_at DESC LIMIT 1",
					$profile_id
				)
			);
			if ( ! $key_id ) {
				$key_id = $wpdb->get_var(
					$wpdb->prepare(
						"SELECT ek.key_id FROM `{$wpdb->prefix}avi_embed_keys` ek
						 INNER JOIN `{$wpdb->prefix}avi_saas_profiles` p ON p.agency_id = ek.agency_id
						 WHERE p.id = %d AND ek.key_type = 'agency' AND ek.status = 'active'
						 ORDER BY ek.created_at DESC LIMIT 1",
						$profile_id
					)
				);
			}
			if ( ! $key_id ) {
				return false;
			}
		}
		$secret   = defined( 'AVISION_ADMIN_API_KEY' )
			? AVISION_ADMIN_API_KEY
			: wp_salt( 'auth' );
		$payload  = 'embed_rest|' . $key_id . '|' . $profile_id . '|' . $ts;
		$expected = hash_hmac( 'sha256', $payload, $secret );
		return hash_equals( $expected, $sig );
	}

	/**
	 * Vérifie la signature HMAC d'une requête embed.
	 *
	 * @param string $key_id     Identifiant public de la clé.
	 * @param int    $profile_id ID profil.
	 * @param int    $ts         Timestamp Unix.
	 * @param string $sig        Signature fournie.
	 * @return bool
	 */
	private static function verify_sig(
		string $key_id,
		int    $profile_id,
		int    $ts,
		string $sig
	): bool {
		if ( abs( time() - $ts ) > self::SIG_TTL ) {
			return false;
		}

		global $wpdb;
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT secret_hash, status, expires_at, allowed_domains, profile_id AS bound_profile,
				        key_type, agency_id
				 FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s LIMIT 1",
				$key_id
			)
		);

		if ( ! $row || $row->status !== 'active' ) {
			return false;
		}

		if ( $row->expires_at && strtotime( $row->expires_at ) < time() ) {
			return false;
		}

		if ( $row->allowed_domains ) {
			$domains = json_decode( $row->allowed_domains, true );
			if ( is_array( $domains ) && ! empty( $domains ) ) {
				$referer = isset( $_SERVER['HTTP_REFERER'] ) ? (string) $_SERVER['HTTP_REFERER'] : '';
				if ( $referer === '' && isset( $_SERVER['HTTP_ORIGIN'] ) ) {
					$referer = (string) $_SERVER['HTTP_ORIGIN'];
				}
				$host    = parse_url( $referer, PHP_URL_HOST );
				$allowed = false;
				foreach ( $domains as $d ) {
					if ( $host && str_ends_with( $host, trim( $d ) ) ) {
						$allowed = true;
						break;
					}
				}
				if ( ! $allowed ) {
					return false;
				}
			}
		}

		$key_type = ! empty( $row->key_type ) ? (string) $row->key_type : 'solo';
		if ( $key_type === 'agency' ) {
			$agency_id = (int) $row->agency_id;
			if ( $agency_id <= 0 || ! self::profile_belongs_to_agency( $profile_id, $agency_id ) ) {
				return false;
			}
		} elseif ( $row->bound_profile && (int) $row->bound_profile !== $profile_id ) {
			return false;
		}

		$payload  = $key_id . '|' . $profile_id . '|' . $ts;
		$expected = hash_hmac( 'sha256', $payload, $row->secret_hash );
		return hash_equals( $expected, $sig );
	}

	/**
	 * Sert la page HTML iframe embed.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return void
	 */
	public static function serve_embed( \WP_REST_Request $request ) {
		$key_id     = $request->get_param( 'key_id' );
		$sig        = $request->get_param( 'sig' );
		$profile_id = (int) $request->get_param( 'profile_id' );
		$ts         = (int) $request->get_param( 'ts' );
		$lang       = $request->get_param( 'lang' );
		// Priorité : langue stockée en DB à l'achat (avi_embed_keys.lang)
		// $key_row peut ne pas être encore chargé ici — on appliquera le override après le SELECT
		// Flag pour override post-SELECT
		$lang_from_url = $lang;
		$theme      = $request->get_param( 'theme' );
		/* Auth : HMAC sig OU WP user localedge_solo */
		$le_wp_auth = false;
		$le_is_wp_auth_request = ( (string) $sig === 'wp_auth' && (int) $ts === 0 );
		if ( $le_is_wp_auth_request || ! self::verify_sig( (string) $key_id, $profile_id, $ts, (string) $sig ) ) {
			/* Fallback : WP user localedge_solo connecté */
			if ( is_user_logged_in() ) {
				$le_current = wp_get_current_user();
				if ( in_array( 'localedge_solo', (array) $le_current->roles, true ) ) {
					$le_embed_key = get_user_meta( $le_current->ID, 'avi_embed_key', true );
					$le_pid       = (int) get_user_meta( $le_current->ID, 'avi_profile_id', true );
					if ( $le_embed_key && $le_pid ) {
						$key_id     = $le_embed_key;
						$profile_id = $le_pid;
						if ( ! $lang ) {
							$lang = get_user_meta( $le_current->ID, 'avi_localedge_lang', true ) ?: 'en';
						}
						$le_wp_auth = true;
					}
				} elseif ( in_array( 'localedge_agency', (array) $le_current->roles, true ) ) {
					$le_embed_key = get_user_meta( $le_current->ID, 'avi_embed_key', true );
					$le_pid       = (int) get_user_meta( $le_current->ID, 'avi_profile_id', true );
					if ( ! $le_pid ) {
						/* Fallback : dériver depuis avi_saas_user_id → profil admin */
						global $wpdb;
						$le_saas_uid = (int) get_user_meta( $le_current->ID, 'avi_saas_user_id', true );
						if ( $le_saas_uid ) {
							$le_pid = (int) $wpdb->get_var( $wpdb->prepare(
								"SELECT id FROM `{$wpdb->prefix}avi_saas_profiles`
								 WHERE user_id = %d LIMIT 1",
								$le_saas_uid
							) );
						}
					}
					if ( $le_embed_key && $le_pid ) {
						$key_id     = $le_embed_key;
						$profile_id = $le_pid;
						if ( ! $lang ) {
							$lang = get_user_meta( $le_current->ID, 'avi_localedge_lang', true ) ?: 'en';
						}
						$le_wp_auth = true;
					}
				}
			}
			if ( ! $le_wp_auth ) {
				self::embed_error( 'invalid_signature', 'Invalid or expired signature.', 403 );
			}
		}

		global $wpdb;
		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT logo_url, white_label_name, key_type, agency_id, profile_id, lang
				 FROM `{$wpdb->prefix}avi_embed_keys` WHERE key_id = %s LIMIT 1",
				$key_id
			)
		);
		$key_type  = ( $key_row && ! empty( $key_row->key_type ) )
			? $key_row->key_type
			: 'solo';
		$agency_id = ( $key_row && ! empty( $key_row->agency_id ) )
			? (int) $key_row->agency_id
			: 0;
		$_avi_admin_ids = array( 1, 338 );
		$_avi_is_admin  = in_array( get_current_user_id(), $_avi_admin_ids, true )
		               || current_user_can( 'manage_options' );
		// Fallback : ?admin_key= dans l URL (usage admin uniquement, jamais expose aux clients)
		if ( ! $_avi_is_admin && defined( 'AVISION_ADMIN_API_KEY' ) && isset( $_GET['admin_key'] ) ) {
			$_avi_is_admin = hash_equals( constant( 'AVISION_ADMIN_API_KEY' ), $_GET['admin_key'] );
		}
		// Override langue : la langue DB prime sur ?lang=xx (anti-contournement geo-pricing)
		// Exception : l admin peut changer la langue librement via ?lang=xx
		if ( $key_row && ! empty( $key_row->lang ) && ! $_avi_is_admin ) {
			$lang = $key_row->lang;
		} elseif ( empty( $lang ) ) {
			$lang = $lang_from_url ?: 'en';
		}
		$embed_logo_url    = ( $key_row && ! empty( $key_row->logo_url ) )
			? esc_url( $key_row->logo_url )
			: '';
		$embed_white_label = ( $key_row && ! empty( $key_row->white_label_name ) )
			? (string) $key_row->white_label_name
			: 'Avision';

		$reviews_next_page_token = '';
		$agency_master_profile_id = ( $key_row && ! empty( $key_row->profile_id ) )
			? (int) $key_row->profile_id
			: $profile_id;

		$agency_profiles = array();
		$agency_credits  = array(
			'available' => 0,
			'total'     => 0,
			'used'      => 0,
		);
		$agency_tier          = 1;
		$agency_max_listings  = 10;
		$agency_used_listings = 0;
		$agency_price_t1      = '$89';
		$agency_price_t2      = '$149';
		$agency_price_t3      = '$249';
		/* Profil admin toujours en tête de flotte pour agence hosted */
		$le_agency_master_row = null;
		if ( $key_type === 'agency' && $agency_master_profile_id > 0 ) {
			$le_agency_master_row = $wpdb->get_row( $wpdb->prepare(
				"SELECT p.id, p.business_name, p.city, p.score, p.google_location_name,
				        p.google_place_id, p.country, p.agency_id
				 FROM `{$wpdb->prefix}avi_saas_profiles` p
				 WHERE p.id = %d LIMIT 1",
				$agency_master_profile_id
			) );
		}
		if ( $key_type === 'agency' && $agency_id > 0 ) {
			$profiles_raw = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT
						p.id,
						p.uuid,
						p.business_name,
						COALESCE(p.city, '') AS city,
						COALESCE(p.country, 'FR') AS country,
						COALESCE(p.score, 0) AS score,
						COALESCE(p.google_primary_category, p.category, '') AS gbp_category,
						COALESCE(p.guardian_active, 0) AS guardian_active,
						COALESCE(p.radar_plan, 'offert') AS radar_plan,
						COALESCE(p.current_level, 1) AS current_level,
						COALESCE(p.average_rating, 0) AS average_rating,
						COALESCE(p.review_count, 0) AS review_count,
						COALESCE(p.google_place_id, '') AS google_place_id,
						COALESCE(p.google_location_name, '') AS google_location_name,
						p.last_radar_scan,
						p.updated_at,
						COALESCE(kw.kw_count, 0) AS kw_count,
						kw.last_kw_scan,
						COALESCE(hm.heatmap_scan_count, 0) AS heatmap_scan_count,
						hm.last_heatmap_scan,
						GREATEST(
							COALESCE(p.updated_at, '1970-01-01'),
							COALESCE(p.last_radar_scan, '1970-01-01'),
							COALESCE(kw.last_kw_scan, '1970-01-01'),
							COALESCE(hm.last_heatmap_scan, '1970-01-01')
						) AS last_activity_at
					 FROM `{$wpdb->prefix}avi_saas_profiles` p
					 LEFT JOIN (
						 SELECT profile_id,
								COUNT(*) AS kw_count,
								MAX(last_scan_at) AS last_kw_scan
						 FROM `{$wpdb->prefix}avi_saas_keywords`
						 GROUP BY profile_id
					 ) kw ON kw.profile_id = p.id
					 LEFT JOIN (
						 SELECT profile_id,
								COUNT(*) AS heatmap_scan_count,
								MAX(created_at) AS last_heatmap_scan
						 FROM `{$wpdb->prefix}avi_heatmap_results`
						 WHERE status IN ('completed', 'partial')
						 GROUP BY profile_id
					 ) hm ON hm.profile_id = p.id
					 WHERE p.agency_id = %d
					   AND p.user_id IS NOT NULL
					 ORDER BY p.score ASC, p.business_name ASC
					 LIMIT 200",
					$agency_id
				)
			);
			if ( $profiles_raw ) {
				/* #SprintL1-L3.4-unanswered-badge — 1 SELECT batch pour tous les caches */
				$profile_ids    = array();
				$unanswered_map = array();
				foreach ( $profiles_raw as $pr ) {
					$profile_ids[] = (int) $pr->id;
				}
				if ( ! empty( $profile_ids ) ) {
					$placeholders = implode( ',', array_fill( 0, count( $profile_ids ), '%d' ) );
					$caches       = $wpdb->get_results(
						$wpdb->prepare(
							"SELECT id, google_data_cache FROM {$wpdb->prefix}avi_saas_profiles WHERE id IN ($placeholders)",
							...array_values( $profile_ids )
						)
					);
					if ( $caches ) {
						foreach ( $caches as $c ) {
							$count = 0;
							if ( ! empty( $c->google_data_cache ) ) {
								$gdc = json_decode( $c->google_data_cache, true );
								if ( is_array( $gdc ) ) {
									$reviews = isset( $gdc['reviews']['reviews'] ) ? $gdc['reviews']['reviews'] : array();
									if ( is_array( $reviews ) ) {
										foreach ( $reviews as $rv ) {
											if ( ! is_array( $rv ) ) {
												continue;
											}
											if ( empty( $rv['reviewReply']['comment'] ) ) {
												$count++;
											}
										}
									}
								}
							}
							$unanswered_map[ (int) $c->id ] = $count;
						}
					}
				}
				foreach ( $profiles_raw as $p ) {
					$agency_profiles[] = array(
						'id'                => (int) $p->id,
						'uuid'              => $p->uuid,
						'business_name'     => $p->business_name,
						'city'              => $p->city,
						'country'           => $p->country,
						'score'             => (int) $p->score,
						'gbp_category'      => $p->gbp_category,
						'guardian_active'   => (int) $p->guardian_active,
						'radar_plan'        => $p->radar_plan,
						'current_level'     => (int) $p->current_level,
						'average_rating'    => (float) $p->average_rating,
						'review_count'       => (int) $p->review_count,
						'google_place_id'    => $p->google_place_id ?? '',
						'google_location_name' => $p->google_location_name ?? '',
						'kw_count'           => (int) $p->kw_count,
						'last_radar_scan'    => $p->last_radar_scan,
						'last_kw_scan'       => $p->last_kw_scan,
						'heatmap_scan_count' => (int) ( $p->heatmap_scan_count ?? 0 ),
						'last_heatmap_scan'  => $p->last_heatmap_scan,
						'last_activity_at'  => $p->last_activity_at,
						'unanswered_count'  => isset( $unanswered_map[ (int) $p->id ] )
							? (int) $unanswered_map[ (int) $p->id ] : 0,
					);
				}
				$client_ids = array_column( $agency_profiles, 'id' );
				if ( ! empty( $client_ids ) ) {
					$placeholders = implode( ',', array_fill( 0, count( $client_ids ), '%d' ) );
					$credit_rows  = $wpdb->get_results(
						$wpdb->prepare(
							"SELECT profile_id,
							        GREATEST( 0, credits_total + COALESCE( credits_bonus, 0 )
							        - credits_used + COALESCE( credits_refunded, 0 ) ) AS available
							 FROM `{$wpdb->prefix}avi_heatmap_credits`
							 WHERE owner_type = 'profile' AND profile_id IN ($placeholders)",
							...array_values( $client_ids )
						)
					);
					$credits_map = array();
					if ( $credit_rows ) {
						foreach ( $credit_rows as $cr_row ) {
							$credits_map[ (int) $cr_row->profile_id ] = (int) $cr_row->available;
						}
					}
					foreach ( $agency_profiles as $ap_idx => $ap_row ) {
						$agency_profiles[ $ap_idx ]['client_credits'] = isset( $credits_map[ (int) $ap_row['id'] ] )
							? $credits_map[ (int) $ap_row['id'] ]
							: 0;
					}
				}
			}
			if ( ! empty( $agency_profiles ) ) {
				$profile_allowed = false;
				foreach ( $agency_profiles as $ap ) {
					if ( (int) $ap['id'] === $profile_id ) {
						$profile_allowed = true;
						break;
					}
				}
				if ( ! $profile_allowed ) {
					self::embed_error( 'profile_not_in_agency', 'Profile not in agency fleet.', 403 );
				}
			}
		}

		if ( $agency_id > 0 ) {
			$agency_tier          = 1;
			$agency_max_listings  = 10;
			$agency_used_listings = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_profiles` WHERE agency_id = %d AND user_id IS NOT NULL",
				$agency_id
			) );
			$le_meta              = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT tier, max_listings FROM `{$wpdb->prefix}avi_localedge_agency_meta` WHERE agency_id = %d LIMIT 1",
					$agency_id
				)
			);
			if ( $le_meta ) {
				$agency_tier         = (int) $le_meta->tier;
				$agency_max_listings = (int) $le_meta->max_listings;
			}
			$le_agency_prices = array(
				'en'    => array( 1 => '$89', 2 => '$149', 3 => '$249' ),
				'fr'    => array( 1 => '45€', 2 => '95€', 3 => '195€' ),
				'de'    => array( 1 => '45€', 2 => '95€', 3 => '195€' ),
				'es'    => array( 1 => '$39', 2 => '$69', 3 => '$109' ),
				'tr'    => array( 1 => '$25', 2 => '$45', 3 => '$75' ),
				'pt'    => array( 1 => '$25', 2 => '$45', 3 => '$75' ),
				'pt-br' => array( 1 => '$25', 2 => '$45', 3 => '$75' ),
			);
			$lang_key_prices   = isset( $le_agency_prices[ $lang ] ) ? $lang : 'en';
			$agency_price_t1 = $le_agency_prices[ $lang_key_prices ][1];
			$agency_price_t2 = $le_agency_prices[ $lang_key_prices ][2];
			$agency_price_t3 = $le_agency_prices[ $lang_key_prices ][3];
			$cr = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT
						credits_total,
						COALESCE(credits_bonus, 0) AS credits_bonus,
						credits_used,
						COALESCE(credits_refunded, 0) AS credits_refunded,
						(credits_total
						 + COALESCE(credits_bonus, 0)
						 - credits_used
						 + COALESCE(credits_refunded, 0)) AS available
					 FROM `{$wpdb->prefix}avi_heatmap_credits`
					 WHERE owner_type = 'agency'
					   AND agency_id = %d
					 LIMIT 1",
					$agency_id
				)
			);
			if ( $cr ) {
				$agency_credits = array(
					'available' => (int) $cr->available,
					'total'     => (int) $cr->credits_total,
					'used'      => (int) $cr->credits_used,
				);
			}
		}

		$solo_credits = array(
			'available' => 0,
			'used'      => 0,
		);
		if ( $key_type === 'solo' && ! empty( $key_id ) ) {
			$sc = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT
						GREATEST(0,
							credits_total
							+ COALESCE(credits_bonus,0)
							- credits_used
						) AS available,
						credits_used
					 FROM `{$wpdb->prefix}avi_embed_credits`
					 WHERE key_id = %s
					 LIMIT 1",
					$key_id
				)
			);
			if ( $sc ) {
				$solo_credits = array(
					'available' => (int) $sc->available,
					'used'      => (int) $sc->credits_used,
				);
			}
		}

		$purchase_success = isset( $_GET['purchase'] )
			&& $_GET['purchase'] === 'success';

		$allowed_langs = array( 'en', 'fr', 'es', 'pt-br', 'tr', 'de' );
		if ( ! in_array( $lang, $allowed_langs, true ) ) {
			$lang = 'en';
		}
		if ( function_exists( 'switch_to_locale' ) ) {
			$_locale_map = array( 'fr' => 'fr_FR', 'es' => 'es_ES', 'de' => 'de_DE', 'pt-br' => 'pt_BR', 'tr' => 'tr_TR' );
			switch_to_locale( isset( $_locale_map[ $lang ] ) ? $_locale_map[ $lang ] : 'en_US' );
		}

		$wpdb->update(
			$wpdb->prefix . 'avi_embed_keys',
			array( 'last_used_at' => current_time( 'mysql', true ) ),
			array( 'key_id' => $key_id ),
			array( '%s' ),
			array( '%s' )
		);

		add_filter( 'avi_embed_mode', '__return_true' );
		add_filter(
			'avi_embed_profile_id',
			function () use ( $profile_id ) {
				return $profile_id;
			}
		);

		if ( ! class_exists( '\Avision\Avision_Radar_Heatmap' ) ) {
			self::embed_error( 'module_unavailable', 'Heatmap module not loaded.', 500 );
		}

		$profile_exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $profile_exists ) {
			self::embed_error( 'profile_not_found', 'Profile not found.', 404 );
		}

		$solo_place_id = '';
		$solo_business = '';
		$solo_city     = '';
		$solo_location_name = '';
		if ( $key_type !== 'agency' ) {
			$solo_profile = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT google_place_id, business_name, city, google_location_name
					 FROM `{$wpdb->prefix}avi_saas_profiles`
					 WHERE id = %d LIMIT 1",
					$profile_id
				)
			);
			if ( $solo_profile ) {
				$solo_place_id = $solo_profile->google_place_id ?? '';
				$solo_location_name = $solo_profile->google_location_name ?? '';
				$solo_business = $solo_profile->business_name ?? '';
				$solo_city     = $solo_profile->city ?? '';
			}
		}

		$score_data    = array();
		$score_profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT score, google_data_cache, last_metrics_snapshot,
				        updated_at, last_radar_scan, google_location_name,
				        google_access_token, pending_google_locations
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( $score_profile ) {
			$gdc = array();
			$lms = array();
			if ( ! empty( $score_profile->google_data_cache ) ) {
				$gdc = json_decode( $score_profile->google_data_cache, true );
				if ( ! is_array( $gdc ) ) {
					$gdc = array();
				}
			}
			if ( ! empty( $score_profile->last_metrics_snapshot ) ) {
				$lms = json_decode( $score_profile->last_metrics_snapshot, true );
				if ( ! is_array( $lms ) ) {
					$lms = array();
				}
			}
			$nap     = isset( $gdc['nap'] ) ? $gdc['nap'] : array();
			$reviews = isset( $gdc['reviews'] ) ? $gdc['reviews'] : array();
			$score_data = array(
				'score'           => (int) $score_profile->score,
				'synced_at'       => isset( $gdc['synced_at'] ) ? $gdc['synced_at'] : $score_profile->updated_at,
				'has_website'     => ! empty( $nap['websiteUri'] ),
				'website_url'     => isset( $nap['websiteUri'] ) ? $nap['websiteUri'] : '',
				'has_phone'       => ! empty( $nap['phoneNumbers'] ),
				'has_hours'       => ! empty( $nap['regularHours'] ),
				'has_description' => ! empty( $nap['profile']['description'] ) || ! empty( $nap['description'] ),
				'has_category'    => ! empty( $nap['categories']['primaryCategory']['displayName'] ),
				'category_name'   => isset( $nap['categories']['primaryCategory']['displayName'] )
					? $nap['categories']['primaryCategory']['displayName'] : '',
				'has_address'     => ! empty( $nap['storefrontAddress']['locality'] ),
				'city'            => isset( $nap['storefrontAddress']['locality'] )
					? $nap['storefrontAddress']['locality'] : '',
				'has_special_hours'  => ! empty( $nap['specialHours'] ),
				'special_hours_value'=> ! empty( $nap['specialHours'] ) ? 'Configured' : '',
				'has_service_area'   => ! empty( $nap['serviceArea'] ),
				'service_area_value' => isset( $nap['serviceArea']['businessType'] )
					? $nap['serviceArea']['businessType'] : ( ! empty( $nap['serviceArea'] ) ? 'Configured' : '' ),
				'average_rating'  => isset( $reviews['averageRating'] )
					? (float) $reviews['averageRating'] : 0,
				'review_count'    => isset( $reviews['totalReviewCount'] )
					? (int) $reviews['totalReviewCount'] : 0,
				'total_photos'    => isset( $lms['total_photos'] ) ? (int) $lms['total_photos'] : 0,
				'position_rank'   => isset( $lms['position_rank'] ) ? (float) $lms['position_rank'] : 0,
				'business_name'   => isset( $nap['title'] ) ? $nap['title'] : '',
				'has_name'        => ! empty( $nap['title'] ),
				'name_value'      => isset( $nap['title'] ) ? $nap['title'] : '',
				/* #SprintL1-L1.4-verified-badge */
			) + self::score_verification_from_nap( is_array( $nap ) ? $nap : array() ) + array(
				/* Valeurs éditables GBP — #SprintL2-L2.8-score-data */
				'phone_value'           => isset( $nap['phoneNumbers']['primaryPhone'] )
					? $nap['phoneNumbers']['primaryPhone'] : '',
				'description_value'     => isset( $nap['profile']['description'] )
					? $nap['profile']['description']
					: ( isset( $nap['description'] ) ? $nap['description'] : '' ),
				'address_lines'         => isset( $nap['storefrontAddress']['addressLines'] )
					? $nap['storefrontAddress']['addressLines'] : array(),
				'address_locality'      => isset( $nap['storefrontAddress']['locality'] )
					? $nap['storefrontAddress']['locality'] : '',
				'address_region'        => isset( $nap['storefrontAddress']['administrativeArea'] )
					? $nap['storefrontAddress']['administrativeArea'] : '',
				'address_postal'        => isset( $nap['storefrontAddress']['postalCode'] )
					? $nap['storefrontAddress']['postalCode'] : '',
				'address_neighborhood'  => isset( $nap['storefrontAddress']['sublocality'] )
					? $nap['storefrontAddress']['sublocality'] : '',
				'address_country'       => isset( $nap['storefrontAddress']['regionCode'] )
					? $nap['storefrontAddress']['regionCode']
					: ( isset( $nap['storefrontAddress']['countryCode'] )
						? $nap['storefrontAddress']['countryCode'] : '' ),
				/* #SprintL2-hours-fix — normaliser openTime/closeTime objets GBP → HH:MM */
				'hours_periods'         => self::normalize_gbp_hours_periods(
					isset( $nap['regularHours']['periods'] ) ? (array) $nap['regularHours']['periods'] : array()
				),
				'primary_category_id'   => isset( $nap['categories']['primaryCategory']['name'] )
					? $nap['categories']['primaryCategory']['name'] : '',
				'primary_category_name' => isset( $nap['categories']['primaryCategory']['displayName'] )
					? $nap['categories']['primaryCategory']['displayName'] : '',
				'additional_categories' => isset( $nap['categories']['additionalCategories'] )
					? $nap['categories']['additionalCategories'] : array(),
				'google_location_name'  => isset( $score_profile->google_location_name )
					? $score_profile->google_location_name : '',
				'gbp_attributes'        => isset( $nap['attributes'] ) && is_array( $nap['attributes'] )
					? $nap['attributes'] : array(),
				'attr_wheelchair_entrance' => self::nap_attr( $nap, 'has_wheelchair_accessible_entrance' ),
				'attr_wheelchair_parking'  => self::nap_attr( $nap, 'has_wheelchair_accessible_parking' ),
				'attr_wheelchair_restroom' => self::nap_attr( $nap, 'has_wheelchair_accessible_restroom' ),
				'attr_wheelchair_seating'  => self::nap_attr( $nap, 'has_wheelchair_accessible_seating' ),
				'attr_free_parking'        => self::nap_attr( $nap, 'has_free_parking_lot' ),
				'attr_paid_parking'        => self::nap_attr( $nap, 'has_paid_parking_lot' ),
				'attr_street_parking'      => self::nap_attr( $nap, 'has_free_street_parking' ),
				'attr_wifi'                => self::nap_attr( $nap, 'has_wifi' ),
				'attr_pet_friendly'        => self::nap_attr( $nap, 'has_pet_friendly' ),
				'attr_good_for_kids'       => self::nap_attr( $nap, 'has_good_for_kids' ),
				'attr_credit_cards'        => self::nap_attr( $nap, 'has_credit_cards' ),
				'attr_outdoor_seating'     => self::nap_attr( $nap, 'has_outdoor_seating' ),
				'attr_count'               => isset( $nap['attributes'] ) && is_array( $nap['attributes'] )
					? count( $nap['attributes'] ) : 0,
				'open_info_status'         => isset( $nap['openInfo']['status'] )
					? $nap['openInfo']['status'] : '',
				'has_open_info'            => ! empty( $nap['openInfo']['status'] ),
				'is_open'                  => isset( $nap['openInfo']['status'] ) && $nap['openInfo']['status'] === 'OPEN',
				'is_closed_temp'           => isset( $nap['openInfo']['status'] ) && $nap['openInfo']['status'] === 'CLOSED_TEMPORARILY',
				'is_closed_perm'           => isset( $nap['openInfo']['status'] ) && $nap['openInfo']['status'] === 'CLOSED_PERMANENTLY',
			);
			/* Posts récents */
			$last_post = $wpdb->get_var( $wpdb->prepare(
				"SELECT MAX(published_at) FROM `{$wpdb->prefix}avi_saas_posts`
				 WHERE profile_id = %d AND status = 'published'",
				$profile_id
			) );
			$posts_count = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_posts`
				 WHERE profile_id = %d AND status = 'published'",
				$profile_id
			) );
			$has_recent_post = false;
			if ( $last_post ) {
				$diff            = ( time() - strtotime( $last_post ) ) / 86400;
				$has_recent_post = $diff <= 7;
			}
			$score_data['posts_count']     = $posts_count;
			$score_data['last_post_at']    = $last_post ?? '';
			$score_data['has_recent_post'] = $has_recent_post;

			/* Photos publiées */
			$photos_published = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE profile_id = %d AND status = 'published'",
				$profile_id
			) );
			$last_photo = $wpdb->get_var( $wpdb->prepare(
				"SELECT MAX(created_at) FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE profile_id = %d AND status = 'published'",
				$profile_id
			) );
			$has_photos                      = $photos_published >= 3;
			$score_data['photos_published']  = $photos_published;
			$score_data['last_photo_at']     = $last_photo ?? '';
			$score_data['has_photos']        = $has_photos;
			$score_data['total_photos']      = $photos_published;

			/* Heatmap stats pour GBP Score */
			$heatmap_row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT
						COUNT(*) as total_scans,
						MAX(scan_date) as last_scan_date,
						DATEDIFF(NOW(), MAX(scan_date)) as days_since_last,
						ROUND(AVG(avg_rank), 1) as avg_rank,
						MAX(grid_size) as max_grid,
						COUNT(DISTINCT keyword) as keywords_count
					 FROM `{$wpdb->prefix}avi_heatmap_results`
					 WHERE profile_id = %d AND status = 'completed'",
					$profile_id
				)
			);

			$hm_total = $heatmap_row ? (int) $heatmap_row->total_scans : 0;
			$hm_last  = $heatmap_row ? $heatmap_row->last_scan_date : null;
			$hm_days  = $heatmap_row ? (int) $heatmap_row->days_since_last : 999;
			$hm_rank  = $heatmap_row ? (float) $heatmap_row->avg_rank : 0;
			$hm_grid  = $heatmap_row ? (int) $heatmap_row->max_grid : 0;
			$hm_kw    = $heatmap_row ? (int) $heatmap_row->keywords_count : 0;
			if ( $hm_total === 0 ) {
				$hm_days = 999;
			}

			// Points activité (max 8)
			$hm_pts_act = 0;
			if ( $hm_total >= 1 ) {
				$hm_pts_act += 2;
			}
			if ( $hm_days <= 7 ) {
				$hm_pts_act += 3;
			} elseif ( $hm_days <= 30 ) {
				$hm_pts_act += 2;
			} elseif ( $hm_total >= 1 ) {
				$hm_pts_act -= 3;
			}

			// Points performance (max 7)
			$hm_pts_perf = 0;
			if ( $hm_rank > 0 ) {
				if ( $hm_rank <= 5 ) {
					$hm_pts_perf = 7;
				} elseif ( $hm_rank <= 10 ) {
					$hm_pts_perf = 5;
				} elseif ( $hm_rank <= 20 ) {
					$hm_pts_perf = 2;
				}
			}

			// Points couverture (max 5)
			$hm_pts_cov = 0;
			if ( $hm_grid >= 13 ) {
				$hm_pts_cov += 3;
			} elseif ( $hm_grid >= 7 ) {
				$hm_pts_cov += 2;
			}
			if ( $hm_kw >= 3 ) {
				$hm_pts_cov += 2;
			}

			$score_data['hm_total_scans']     = $hm_total;
			$score_data['hm_last_scan']       = $hm_last ?? '';
			$score_data['hm_days_since']      = $hm_days;
			$score_data['hm_avg_rank']        = $hm_rank;
			$score_data['hm_max_grid']        = $hm_grid;
			$score_data['hm_keywords_count']  = $hm_kw;
			$score_data['hm_pts_activity']    = $hm_pts_act;
			$score_data['hm_pts_performance'] = $hm_pts_perf;
			$score_data['hm_pts_coverage']    = $hm_pts_cov;
			$score_data['hm_pts_total']       = $hm_pts_act + $hm_pts_perf + $hm_pts_cov;
			$score_data['hm_has_scans']       = $hm_total > 0;
			$score_data['hm_is_fresh']        = $hm_days <= 7;
			$score_data['hm_is_stale']        = $hm_total > 0 && $hm_days > 30;
		}

		/* #SprintL1-L1.3-oauth-cta — détection connexion GBP */
		$has_google_token = false;
		$is_gbp_connected = false;
		if ( $score_profile ) {
			$has_google_token = ! empty( $score_profile->google_access_token );
			$is_gbp_connected = $has_google_token
				&& ! empty( $score_profile->google_location_name );
		}
		/* Agence : master flotte peut avoir un token sans google_location_name (pas une fiche GBP unique). */
		if ( ! $has_google_token && $key_type === 'agency' && $agency_master_profile_id > 0 ) {
			$master_tok = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT google_access_token FROM `{$wpdb->prefix}avi_saas_profiles`
					 WHERE id = %d LIMIT 1",
					$agency_master_profile_id
				)
			);
			if ( ! empty( $master_tok ) ) {
				$has_google_token = true;
			}
		}
		$le_is_hosted = false;
		if ( isset( $wpdb ) ) {
			$le_hosted_val = $wpdb->get_var( $wpdb->prepare(
				"SELECT hosted FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s LIMIT 1",
				(string) $key_id
			) );
			$le_is_hosted = ( (int) $le_hosted_val === 1 );
		}
		if ( $le_is_hosted ) {
			$embed_connect_url = home_url( '/localedge-connect/' )
				. '?hosted=1'
				. '&key=' . rawurlencode( (string) $key_id )
				. '&profile_id=' . (int) $profile_id
				. '&lang=' . rawurlencode( (string) $lang );
		} else {
			$embed_connect_url = 'https://avision.org/connect?key=' . rawurlencode( (string) $key_id )
				. '&profile_id=' . (int) $profile_id
				. '&lang=' . rawurlencode( (string) $lang );
		}

		$reviews_data     = array();
		$unanswered_count = 0;
		if ( $score_profile ) {
			$gdc_reviews = array();
			if ( ! empty( $score_profile->google_data_cache ) ) {
				$gdc_reviews = json_decode( $score_profile->google_data_cache, true );
				if ( ! is_array( $gdc_reviews ) ) {
					$gdc_reviews = array();
				}
			}
			$reviews_raw  = isset( $gdc_reviews['reviews']['reviews'] )
				? $gdc_reviews['reviews']['reviews'] : array();
			$reviews_data = array(
				'average_rating' => isset( $gdc_reviews['reviews']['averageRating'] )
					? (float) $gdc_reviews['reviews']['averageRating'] : 0,
				'total_count'    => isset( $gdc_reviews['reviews']['totalReviewCount'] )
					? (int) $gdc_reviews['reviews']['totalReviewCount'] : 0,
				'reviews'        => array(),
			);
			$reviews_next_page_token = '';
			if ( isset( $gdc_reviews['reviews']['nextPageToken'] ) ) {
				$reviews_next_page_token = (string) $gdc_reviews['reviews']['nextPageToken'];
			}
			if ( is_array( $reviews_raw ) ) {
				foreach ( $reviews_raw as $rv ) {
					if ( ! is_array( $rv ) ) {
						continue;
					}
					$has_reply = ! empty( $rv['reviewReply']['comment'] );
					$reviews_data['reviews'][] = array(
						'review_id'      => isset( $rv['reviewId'] ) ? $rv['reviewId'] : '',
						'reviewer_name'  => isset( $rv['reviewer']['displayName'] )
							? $rv['reviewer']['displayName'] : 'Anonymous',
						'reviewer_photo' => isset( $rv['reviewer']['profilePhotoUrl'] )
							? $rv['reviewer']['profilePhotoUrl'] : '',
						'star_rating'    => isset( $rv['starRating'] )
							? $rv['starRating'] : 'ZERO',
						'comment'        => isset( $rv['comment'] ) ? $rv['comment'] : '',
						'create_time'    => isset( $rv['createTime'] ) ? $rv['createTime'] : '',
						'has_reply'      => $has_reply,
						'reply_comment'  => $has_reply ? $rv['reviewReply']['comment'] : '',
						'reply_time'     => $has_reply
							? ( isset( $rv['reviewReply']['updateTime'] )
								? $rv['reviewReply']['updateTime'] : '' )
							: '',
						'review_name'    => isset( $rv['name'] ) ? $rv['name'] : '',
					);
					if ( ! $has_reply ) {
						$unanswered_count++;
					}
				}
			}
		}

		$posts_data = array();
		$posts_raw  = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, post_type, content, status,
				        scheduled_at, published_at, created_at
				 FROM `{$wpdb->prefix}avi_saas_posts`
				 WHERE profile_id = %d
				   AND post_type IN ('update','offer','event')
				 ORDER BY created_at DESC
				 LIMIT 50",
				$profile_id
			)
		);
		if ( $posts_raw ) {
			foreach ( $posts_raw as $p ) {
				$posts_data[] = array(
					'id'           => (int) $p->id,
					'post_type'    => $p->post_type,
					'content'      => $p->content,
					'status'       => $p->status,
					'scheduled_at' => $p->scheduled_at,
					'published_at' => $p->published_at,
					'created_at'   => $p->created_at,
				);
			}
		}

		$photos_data = array();
		$photos_raw  = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, file_path, display_name, media_type, category,
				        status, gbp_status, scheduled_at, published_at, created_at
				 FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE profile_id = %d
				 ORDER BY created_at DESC
				 LIMIT 100",
				$profile_id
			)
		);
		if ( $photos_raw ) {
			foreach ( $photos_raw as $ph ) {
				$photos_data[] = array(
					'id'           => (int) $ph->id,
					'file_path'    => $ph->file_path,
					'display_name' => $ph->display_name,
					'media_type'   => $ph->media_type,
					'category'     => $ph->category,
					'status'       => $ph->status,
					'gbp_status'   => $ph->gbp_status,
					'scheduled_at' => $ph->scheduled_at,
					'published_at' => $ph->published_at,
					'created_at'   => $ph->created_at,
				);
			}
		}

		$token_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_refresh_token,
				        google_location_name
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( $token_row && ! empty( $token_row->google_access_token ) ) {
			set_transient(
				'avi_embed_reply_token_' . $profile_id,
				array(
					'token'    => $token_row->google_access_token,
					'refresh'  => $token_row->google_refresh_token,
					'location' => $token_row->google_location_name,
				),
				3600
			);
		}

		// #Sprint44-Plugin — Token REST embed injecté dans data-heatmap
		$embed_token  = self::generate_embed_token( (string) $key_id, $profile_id );
		$heatmap_html = \Avision\Avision_Radar_Heatmap::render_embed( $profile_id, $embed_token, (string) $key_id, (string) $lang );

		/* #SprintL2-L2.4-banner-whitelabel — logo dans bannière heatmap, pas de bandeau séparé */
		$logo_html = '';

		$plugin_url  = defined( 'AVISION_URL' ) ? str_replace( 'http://', 'https://', AVISION_URL ) : '';
		$leaflet_css = $plugin_url . 'assets/css/vendor/leaflet.css';
		$leaflet_js  = $plugin_url . 'assets/js/vendor/leaflet.js';

		$html = '<!DOCTYPE html>'
			. '<html lang="' . esc_attr( $lang ) . '">'
			. '<head>'
			. '<meta charset="UTF-8">'
			. '<meta name="viewport" content="width=device-width,initial-scale=1">'
			. '<meta name="robots" content="noindex,nofollow">'
			. '<title>Heatmap</title>'
			. '<link rel="stylesheet" href="' . esc_url( $leaflet_css ) . '">'
			. '<link rel="stylesheet" href="' . esc_url( $plugin_url . 'assets/css/avi-radar-heatmap.css' ) . '">'
			. '<link rel="stylesheet" href="' . esc_url( $plugin_url . 'assets/css/avi-embed.css' ) . '">'
			. '<link rel="preconnect" href="https://fonts.googleapis.com">'
			. '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>'
			. '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap">'
			. '<style>'
			. ':root {'
			. '  --bg-app:#f1f5f9;'
			. '  --bg-card:#ffffff;'
			. '  --border-color:#e2e8f0;'
			. '  --text-main:#0f172a;'
			. '  --text-muted:#64748b;'
			. '  --avi-navy:#0f172a;'
			. '  --avi-navy-light:#1e293b;'
			. '  --primary-blue:#2563eb;'
			. '  --premium-gold:#d97706;'
			. '  --premium-bg:#fffbeb;'
			. '  --success-soft:#059669;'
			. '  --danger-soft:#dc2626;'
			. '  --border:var(--border-color);'
			. '  --primary:var(--primary-blue);'
			. '  --accent:var(--premium-gold);'
			. '  --success:var(--success-soft);'
			. '  --success-bg:#dcfce7;'
			. '  --danger:var(--danger-soft);'
			. '  --warning:var(--premium-gold);'
			. '  --warning-bg:var(--premium-bg);'
			. '  --bonus-purple:#9333ea;'
			. '  --bonus-bg:#f5f3ff;'
			. '  --bonus-text:#5b21b6;'
			. '  --avi-green:#10b981;'
			. '  --avi-orange:#f59e0b;'
			. '  --avi-red:#ef4444;'
			. '}'
			. 'html,body{font-family:"Inter",system-ui,sans-serif;}'
			. 'html body #avision-dashboard-root .avi-heatmap-modal{'
			. 'padding:0!important;'
			. 'align-items:stretch!important;'
			. 'justify-content:stretch!important;'
			. '}'
			. 'html body #avision-dashboard-root .avi-heatmap-modal-card{'
			. 'max-width:100%!important;'
			. 'width:100%!important;'
			. 'height:100vh!important;'
			. 'max-height:100vh!important;'
			. 'border-radius:0!important;'
			. 'margin:0!important;'
			. '}'
			. 'html body #avision-dashboard-root .avi-heatmap-modal-layout{'
			. 'display:grid!important;'
			. 'grid-template-columns:340px minmax(0,1fr)!important;'
			. 'flex-direction:row!important;'
			. 'height:100%!important;'
			. 'min-height:0!important;'
			. '}'
			. 'html body #avision-dashboard-root .avi-heatmap-modal-info{'
			. 'width:340px!important;'
			. 'max-width:340px!important;'
			. 'min-width:340px!important;'
			. 'grid-column:1!important;'
			. '}'
			. 'html body #avision-dashboard-root .avi-heatmap-modal-map{'
			. 'grid-column:2!important;'
			. 'width:100%!important;'
			. 'height:100%!important;'
			. 'min-height:0!important;'
			. '}'
			. '#avision-dashboard-root .avi-hm-pedago-overlay {'
			. '  position:fixed!important;'
			. '  inset:0!important;'
			. '  z-index:200000!important;'
			. '  display:flex;'
			. '}'
			. 'html,body{margin:0 !important;padding:0 !important;overflow:hidden !important;height:100% !important;}'
			. '#aviEmbedClientName,.avi-hm-profile-badge,[data-avi-profile-badge],.avi-heatmap-closed-profile{'
			. 'max-width:min(500px,60vw);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;'
			. 'border-radius:20px;padding:6px 16px;font-size:13px;}'
			. '.avi-agency-master-item{border-bottom:2px solid #ede9fe;margin-bottom:4px;}'
			. 'html body #avision-dashboard-root{display:flex !important;flex-direction:column !important;height:100vh !important;overflow:hidden !important;}'
			. 'html body #avision-dashboard-root .avi-embed-wrap{flex:1 !important;overflow:hidden !important;display:flex !important;flex-direction:column !important;min-height:0 !important;position:relative !important;}'
			. 'html body #avision-dashboard-root .avi-radar-heatmap-module{flex:1 !important;display:flex !important;flex-direction:column !important;margin:0 !important;padding:0 !important;min-height:0 !important;overflow:hidden !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-closed{margin:0 !important;border-radius:0 !important;flex-shrink:0 !important;}'
			. '/* #SprintL2-hamburger-nav — bannière une ligne */'
			. 'html body #avision-dashboard-root .avi-heatmap-closed{'
			. 'flex-wrap:nowrap !important;overflow:hidden !important;min-height:56px !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-closed-main{'
			. 'flex-shrink:0 !important;min-width:0 !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-closed-profile{'
			. 'flex:1 !important;min-width:0 !important;overflow:hidden !important;'
			. 'text-overflow:ellipsis !important;white-space:nowrap !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-closed-meta{'
			. 'flex-shrink:0 !important;white-space:nowrap !important;}'
			. '.avi-heatmap-closed-meta a{pointer-events:auto !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-drawer[hidden]{display:flex !important;flex-direction:column !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-drawer{flex:1 !important;overflow:hidden !important;display:flex !important;flex-direction:column !important;min-height:0 !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-drawer-grid{display:grid !important;grid-template-columns:minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) !important;grid-template-rows:1fr !important;flex:1 !important;overflow:hidden !important;min-height:0 !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-panel{overflow-y:auto !important;min-height:0 !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-grid-preview{max-height:380px !important;overflow:hidden !important;}'
			. '.avi-embed-nav-wrap{position:relative !important;display:flex;align-items:stretch;'
			. 'background:#0f172a;border-bottom:1px solid rgba(255,255,255,0.12);flex-shrink:0;}'
			. 'nav.avi-embed-nav,.avi-embed-nav{flex:1;min-width:0;overflow-x:auto;overflow-y:hidden;'
			. 'scrollbar-width:thin;display:flex;flex-wrap:nowrap;gap:2px;'
			. 'padding:0 8px;align-items:stretch;}'
			. 'nav.avi-embed-nav::-webkit-scrollbar,.avi-embed-nav::-webkit-scrollbar{height:3px;}'
			. 'nav.avi-embed-nav::-webkit-scrollbar-track,.avi-embed-nav::-webkit-scrollbar-track{'
			. 'background:rgba(255,255,255,.05);}'
			. 'nav.avi-embed-nav::-webkit-scrollbar-thumb,.avi-embed-nav::-webkit-scrollbar-thumb{'
			. 'background:rgba(109,40,217,.6);border-radius:3px;}'
			. 'nav.avi-embed-nav::-webkit-scrollbar-thumb:hover,.avi-embed-nav::-webkit-scrollbar-thumb:hover{'
			. 'background:rgba(109,40,217,.9);}'
			. 'nav.avi-embed-nav::after,.avi-embed-nav::after{content:"";position:sticky;right:0;'
			. 'flex-shrink:0;width:24px;align-self:stretch;'
			. 'background:linear-gradient(to right,transparent,#0f172a);pointer-events:none;}'
			. '.avi-embed-lang-wrap{flex-shrink:0;display:flex;align-items:center;padding:0 8px;'
			. 'border-left:1px solid rgba(255,255,255,.1);background:#0f172a;'
			. 'position:sticky;right:0;z-index:10;}'
			. 'nav.avi-embed-nav button,.avi-embed-nav-btn{background:none;border:none;border-bottom:2px solid transparent;'
			. 'color:rgba(255,255,255,0.6);cursor:pointer;font-family:Inter,system-ui,sans-serif;font-size:13px;'
			. 'font-weight:500;padding:10px 14px;transition:color .15s,border-color .15s;white-space:nowrap;'
			. 'border-radius:0;flex-shrink:0;}'
			. 'nav.avi-embed-nav button:hover,.avi-embed-nav-btn:hover{color:rgba(255,255,255,0.9);}'
			. 'nav.avi-embed-nav button[aria-selected="true"],.avi-embed-nav-btn[aria-selected="true"]{'
			. 'color:#fff;border-bottom-color:#a78bfa;}'
			. 'nav.avi-embed-nav .avi-nav-label{margin-left:4px;}'
			. '.avi-embed-hamburger{display:none;background:none;border:none;color:#fff;'
			. 'font-size:22px;padding:8px 12px;cursor:pointer;flex-shrink:0;}'
			. '.avi-embed-mobile-menu{position:absolute;top:100%;left:0;right:0;background:#1e293b;'
			. 'z-index:10000;display:none;flex-direction:column;padding:8px 0;'
			. 'box-shadow:0 8px 24px rgba(0,0,0,.3);border-top:1px solid rgba(255,255,255,.1);}'
			. '.avi-embed-mobile-menu.is-open{display:flex;}'
			. '.avi-embed-mobile-menu-btn{display:flex;align-items:center;gap:10px;'
			. 'padding:12px 20px;color:#cbd5e1;background:none;border:none;font-size:14px;'
			. 'cursor:pointer;text-align:left;width:100%;transition:background .15s;}'
			. '.avi-embed-mobile-menu-btn:hover,.avi-embed-mobile-menu-btn[aria-selected="true"]{'
			. 'background:rgba(109,40,217,.3);color:#fff;}'
			. '.avi-embed-mobile-menu-btn[aria-selected="true"]{border-left:3px solid #6d28d9;}'
			. '@media(max-width:768px){'
			. 'nav.avi-embed-nav,.avi-embed-nav{display:none !important;}'
			. 'nav.avi-embed-nav::-webkit-scrollbar,.avi-embed-nav::-webkit-scrollbar{display:none;}'
			. 'nav.avi-embed-nav,.avi-embed-nav{scrollbar-width:none;}'
			. '.avi-embed-hamburger{display:flex !important;align-items:center;justify-content:center;}'
			. '.avi-embed-nav-btn{font-size:11px;padding:8px 10px;white-space:nowrap;flex-shrink:0;}'
			. '}'
			. '@media(max-width:480px){'
			. '.avi-embed-nav-btn{font-size:10px;padding:6px 8px;}'
			. '.avi-embed-nav-btn .avi-nav-label{display:none;}'
			. '.avi-embed-nav-btn .avi-nav-icon{display:inline;}'
			. '}'
			. 'nav.avi-embed-nav *{pointer-events:auto !important;}'
			. '/* #SprintL1-L2.7-control-center */'
			. '.avi-embed-home-active .avi-heatmap-panel--preview .avi-heatmap-panel-head{display:none !important;}'
			. '.avi-embed-home-active .avi-heatmap-panel--preview .avi-heatmap-design-switch{display:none !important;}'
			. '.avi-embed-home-active .avi-heatmap-panel--preview .avi-heatmap-grid-preview{display:none !important;}'
			. '.avi-embed-home-active .avi-heatmap-metrics{border-top:1px solid #e2e8f0;margin-top:8px;padding-top:8px;}'
			. '.avi-embed-home-active .avi-heatmap-panel--preview{display:flex !important;flex-direction:column;}'
			. '.avi-embed-home-active .avi-embed-home-dashboard{order:0;display:block !important;}'
			. '.avi-embed-home-active .avi-heatmap-metrics{order:1;}'
			. '.avi-embed-home-active .avi-hm-open-map-btn{order:2;margin-top:auto;}'
			. '.avi-embed-home-dashboard{display:none;padding:0;}'
			. '.avi-ehd-widgets{display:flex;flex-direction:column;gap:6px;margin-top:12px;margin-bottom:8px;}'
			. '.avi-ehd-widget{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;cursor:pointer;transition:box-shadow .15s,border-color .15s;display:flex;flex-direction:row;align-items:center;gap:10px;}'
			. '.avi-ehd-widget:hover{box-shadow:0 2px 6px rgba(0,0,0,.08);border-color:#c7d2fe;}'
			. '.avi-ehd-widget-icon{font-size:18px;line-height:1;flex-shrink:0;}'
			. '.avi-ehd-widget-body{display:flex;flex-direction:column;gap:1px;min-width:0;}'
			. '.avi-ehd-widget-label{font-size:9px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.04em;}'
			. '.avi-ehd-widget-value{font-size:18px;font-weight:700;color:#1e293b;line-height:1;}'
			. '.avi-ehd-widget--score .avi-ehd-widget-value{color:#6d28d9;}'
			. '.avi-ehd-widget--reviews .avi-ehd-widget-value{color:#dc2626;}'
			. '.avi-ehd-widget--reviews[data-count="0"] .avi-ehd-widget-value{color:#059669;}'
			. '.avi-ehd-widget--scan .avi-ehd-widget-value{font-size:12px;font-weight:600;color:#374151;}'
			. '.avi-ehd-widget-label-row{display:flex;align-items:center;gap:4px;}'
			. '.avi-ehd-info-btn{background:none;border:none;cursor:pointer;font-size:13px;'
			. 'padding:2px 4px;line-height:1;vertical-align:middle;}'
			. '.avi-ehd-info-btn:hover{opacity:.7;}'
			. '.avi-add-kw-btn{display:block;width:100%;margin-bottom:8px;padding:7px 12px;'
			. 'background:#6d28d9;color:#fff;border:none;border-radius:8px;'
			. 'font-size:12px;font-weight:600;cursor:pointer;}'
			. '.avi-add-kw-btn:hover{background:#5b21b6;}'
			. '.avi-edu-banner{background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);'
			. 'border-radius:12px;padding:16px 18px;margin-bottom:10px;'
			. 'color:#fff;position:relative;overflow:hidden;font-family:inherit;}'
			. '.avi-edu-banner::before{content:"";position:absolute;'
			. 'top:-20px;right:-20px;width:100px;height:100px;'
			. 'background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-edu-banner-title{font-size:13px;font-weight:700;'
			. 'margin-bottom:4px;display:flex;align-items:center;gap:6px;}'
			. '.avi-edu-banner-body{font-size:11px;opacity:.9;line-height:1.5;margin-bottom:10px;}'
			. '.avi-edu-banner-close{position:absolute;top:10px;right:12px;'
			. 'background:rgba(255,255,255,.2);border:none;border-radius:50%;'
			. 'width:22px;height:22px;cursor:pointer;color:#fff;font-size:12px;'
			. 'display:flex;align-items:center;justify-content:center;line-height:1;}'
			. '.avi-edu-banner-close:hover{background:rgba(255,255,255,.35);}'
			. '.avi-edu-banner-btn{display:inline-flex;align-items:center;gap:5px;'
			. 'background:rgba(255,255,255,.2);border:1px solid rgba(255,255,255,.3);'
			. 'border-radius:6px;padding:5px 12px;font-size:11px;font-weight:600;'
			. 'color:#fff;cursor:pointer;transition:background .15s;font-family:inherit;}'
			. '.avi-edu-banner-btn:hover{background:rgba(255,255,255,.3);}'
			. '.avi-edu-tips-btn{position:fixed;bottom:80px;right:16px;'
			. 'background:#6d28d9;color:#fff;border:none;border-radius:50%;'
			. 'width:44px;height:44px;font-size:20px;cursor:pointer;'
			. 'box-shadow:0 4px 12px rgba(109,40,217,.4);z-index:9999;'
			. 'display:flex;align-items:center;justify-content:center;font-family:inherit;}'
			. '.avi-edu-modal-backdrop{position:fixed;inset:0;z-index:100050;'
			. 'background:rgba(0,0,0,.5);display:flex;align-items:center;'
			. 'justify-content:center;padding:20px;}'
			. '.avi-edu-modal{background:#fff;border-radius:16px;max-width:480px;'
			. 'width:100%;max-height:85vh;overflow-y:auto;padding:28px 24px;font-family:inherit;}'
			. '.avi-edu-modal-title{font-size:18px;font-weight:800;color:#1e293b;'
			. 'margin-bottom:16px;text-align:center;}'
			. '.avi-edu-step{background:#f8fafc;border-radius:10px;padding:14px;'
			. 'margin-bottom:10px;border-left:3px solid #6d28d9;}'
			. '.avi-edu-step-title{font-weight:700;color:#6d28d9;margin-bottom:6px;font-size:13px;}'
			. '.avi-edu-step-body{font-size:12px;color:#475569;line-height:1.6;}'
			. '.avi-edu-step--danger{background:#fef2f2!important;border-left:3px solid #dc2626!important;}'
			. '.avi-edu-step--danger .avi-edu-step-title{color:#dc2626!important;}'
			. '.avi-edu-step--danger .avi-edu-step-body{color:#991b1b!important;}'
			. '.avi-ehd-guardian-widget{display:flex;align-items:flex-start;gap:10px;background:linear-gradient(135deg,#f0fdf4 0%,#dcfce7 100%);border:1.5px solid #86efac;border-radius:12px;padding:14px 16px;margin-top:14px;}'
			. '.avi-ehd-guardian-left{display:flex;align-items:flex-start;gap:10px;width:100%;}'
			. '.avi-ehd-guardian-icon{font-size:22px;line-height:1;flex-shrink:0;margin-top:2px;}'
			. '.avi-ehd-guardian-body{flex:1;min-width:0;}'
			. '.avi-ehd-guardian-title{font-size:13px;font-weight:700;color:#15803d;display:flex;align-items:center;gap:6px;margin-bottom:4px;}'
			. '.avi-ehd-guardian-info-btn{background:none;border:none;cursor:pointer;font-size:13px;padding:0;line-height:1;opacity:.7;}'
			. '.avi-ehd-guardian-info-btn:hover{opacity:1;}'
			. '.avi-ehd-guardian-status{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:#16a34a;margin-bottom:3px;}'
			. '.avi-ehd-guardian-dot{width:8px;height:8px;border-radius:50%;background:#22c55e;box-shadow:0 0 0 3px rgba(34,197,94,.25);animation:avi-pulse-g 2s infinite;flex-shrink:0;}'
			. '@keyframes avi-pulse-g{0%,100%{box-shadow:0 0 0 3px rgba(34,197,94,.25);}50%{box-shadow:0 0 0 6px rgba(34,197,94,.1);}}'
			. '.avi-ehd-guardian-sub{font-size:11px;color:#166534;font-weight:500;}'
			. '.avi-guardian-badge{display:inline-flex;align-items:center;gap:4px;background:linear-gradient(135deg,#f8fafc 0%,#f1f5f9 100%);border:1px solid #e2e8f0;border-radius:20px;padding:3px 10px 3px 8px;font-size:11px;font-weight:600;color:#64748b;margin-left:auto;cursor:pointer;vertical-align:middle;box-shadow:0 1px 2px rgba(0,0,0,.06);}'
			. '.avi-guardian-badge-dot{width:7px;height:7px;border-radius:50%;background:#22c55e;box-shadow:0 0 0 2px rgba(34,197,94,.3);animation:avi-pulse-g 2s infinite;flex-shrink:0;}'
			. '@keyframes avi-pulse-green{0%,100%{box-shadow:0 0 0 0 rgba(34,197,94,0.5);}50%{box-shadow:0 0 0 5px rgba(34,197,94,0);}}'
			. '@keyframes avi-pulse-orange{0%,100%{box-shadow:0 0 0 0 rgba(249,115,22,0.5);}50%{box-shadow:0 0 0 5px rgba(249,115,22,0);}}'
			. '.avi-guardian-pricing-box{margin:12px 0;padding:12px 14px;border-radius:8px;font-size:13px;}'
			. '.avi-guardian-trial{background:#f0fdf4;border:1px solid #86efac;}'
			. '.avi-guardian-active{background:#fff7ed;border:1px solid #fdba74;}'
			. '.avi-guardian-pricing-title{font-weight:700;margin-bottom:4px;}'
			. '.avi-guardian-pricing-body{font-size:15px;font-weight:600;color:#16a34a;margin-bottom:4px;}'
			. '.avi-guardian-pricing-detail{color:#6b7280;font-size:12px;margin-bottom:8px;}'
			. '.avi-guardian-deactivate-btn{background:none;border:1px solid #ef4444;color:#ef4444;border-radius:6px;padding:6px 12px;font-size:12px;cursor:pointer;margin-top:4px;}'
			. '.avi-guardian-deactivate-btn:hover{background:#fef2f2;}'
			. '.avi-guardian-pricing-warning{background:#fff7ed;border-left:3px solid #f97316;padding:8px 10px;border-radius:4px;font-size:12px;color:#92400e;margin-bottom:8px;line-height:1.5;}'
			. '.avi-guardian-deactivate-warn{font-size:11px;color:#9ca3af;margin-top:6px;font-style:italic;line-height:1.4;}'
			. '.avi-guardian-low-credits{background:#fef2f2;border:1px solid #fca5a5;}'
			. '.avi-guardian-paid-active{background:#f0fdf4;border:1px solid #86efac;}'
			. '.avi-guardian-buy-btn{background:#16a34a;border:none;color:#fff;border-radius:6px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer;margin-top:8px;width:100%;}'
			. '.avi-guardian-buy-btn:hover{background:#15803d;}'
			. '.avi-guardian-credits-count{font-size:13px;color:#374151;margin-top:6px;}'
			. '.avi-guardian-next-billing{font-size:12px;color:#6b7280;margin-top:4px;}'
			. '.avi-guardian-disabled{background:#f3f4f6;border:1px solid #d1d5db;}'
			. '.avi-guardian-activate-btn{background:#7c3aed;border:none;color:#fff;border-radius:6px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer;margin-top:8px;width:100%;}'
			. '.avi-guardian-activate-btn:hover{background:#6d28d9;}'
			. '.avi-score-btn-guardian-trial{box-shadow:0 0 0 2px #22c55e;animation:avi-pulse-green 2s infinite;}'
			. '.avi-score-btn-guardian-active{box-shadow:0 0 0 2px #f97316;animation:avi-pulse-orange 2s infinite;}'
			. '.avi-score-btn-guardian-off{box-shadow:0 0 0 2px #9ca3af;opacity:.7;}'
			. '.avi-guardian-field-dot{display:inline-block;width:7px;height:7px;border-radius:50%;margin:0 4px;vertical-align:middle;position:relative;top:-1px;}'
			. '.avi-guardian-field-dot.avi-score-btn-guardian-trial{background:#22c55e;box-shadow:none;animation:avi-pulse-green 2s infinite;}'
			. '.avi-guardian-field-dot.avi-score-btn-guardian-active{background:#f97316;box-shadow:none;animation:avi-pulse-orange 2s infinite;}'
			. '.avi-guardian-field-dot.avi-score-btn-guardian-off{background:#9ca3af;box-shadow:none;animation:none;opacity:.6;}'
			. '.avi-guardian-field-warn{font-size:11px;margin-right:4px;vertical-align:middle;position:relative;top:-1px;animation:avi-pulse-warn 1.5s infinite;}'
			. '@keyframes avi-pulse-warn{0%,100%{opacity:1;}50%{opacity:.4;}}'
			. '.avi-guardian-badge-info{background:none;border:none;cursor:pointer;font-size:11px;padding:0;line-height:1;margin-left:2px;opacity:.7;}'
			. '.avi-edu-modal-close{display:block;width:100%;margin-top:16px;'
			. 'padding:10px;background:#6d28d9;color:#fff;border:none;'
			. 'border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;}'
			. '.avi-ehd-nap{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;margin-bottom:4px;}'
			. '.avi-ehd-nap-label{font-size:9px;font-weight:600;color:#94a3b8;text-transform:uppercase;letter-spacing:.04em;margin-bottom:6px;display:inline-flex;align-items:center;gap:4px;}'
			. '.avi-ehd-nap-items{display:flex;flex-wrap:wrap;gap:4px;}'
			. '.avi-ehd-nap-item{display:flex;align-items:center;gap:3px;font-size:10px;border-radius:4px;padding:2px 6px;white-space:nowrap;}'
			. '.avi-ehd-nap-item--ok{background:#f0fdf4;color:#166534;border:1px solid #bbf7d0;}'
			. '.avi-ehd-nap-item--missing{background:#fef2f2;color:#dc2626;border:1px solid #fecaca;cursor:pointer;}'
			. '.avi-ehd-nap-item--missing:hover{background:#fee2e2;}'
			. '.avi-ehd-nap-dot{width:6px;height:6px;border-radius:50%;flex-shrink:0;}'
			. '.avi-ehd-nap-dot--ok{background:#22c55e;}'
			. '.avi-ehd-nap-dot--missing{background:#ef4444;}'
			. '/* #SprintL2-L2.2-home-kw */'
			. '.avi-ehd-keywords{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:10px;padding:10px 14px;margin-top:8px;}'
			. '.avi-ehd-kw-list{display:flex;flex-direction:column;gap:4px;margin-top:6px;}'
			. '.avi-ehd-kw-item{display:flex;align-items:center;'
			. 'justify-content:space-between;gap:8px;font-size:12px;}'
			. '.avi-ehd-kw-name{color:#374151;flex:1;min-width:0;'
			. 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}'
			. '.avi-ehd-kw-rank{font-size:11px;font-weight:700;'
			. 'border-radius:4px;padding:1px 6px;flex-shrink:0;}'
			. '.avi-ehd-kw-rank--top3{background:#f0fdf4;color:#166534;}'
			. '.avi-ehd-kw-rank--top10{background:#eff6ff;color:#1d4ed8;}'
			. '.avi-ehd-kw-rank--top20{background:#fefce8;color:#a16207;}'
			. '.avi-ehd-kw-rank--out{background:#f8fafc;color:#94a3b8;}'
			. '.avi-ehd-kw-more{font-size:11px;color:#6d28d9;cursor:pointer;'
			. 'margin-top:4px;text-align:right;}'
			. '.avi-ehd-kw-more:hover{text-decoration:underline;}'
			. '.avi-ehd-title{font-size:.95rem;font-weight:900;color:#0f172a;text-transform:none;letter-spacing:normal;line-height:1;display:flex;align-items:center;gap:6px;margin:0;padding:0;}'
			. '.avi-hm-step-badge{display:inline-flex;align-items:center;justify-content:center;'
			. 'width:20px;height:20px;min-width:20px;border-radius:50%;'
			. 'background:#f59e0b;color:#0a1628;font-size:10px;font-weight:700;flex-shrink:0;}'
			. '/* #SprintL2-L2.8-score-ui */'
			. '.avi-score-edit-modal-backdrop{position:fixed;inset:0;z-index:100010;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;padding:16px;}'
			. '.avi-score-edit-modal{background:#fff;border-radius:14px;width:100%;max-width:480px;max-height:90vh;overflow-y:auto;box-shadow:0 8px 40px rgba(0,0,0,.18);display:flex;flex-direction:column;}'
			. '.avi-score-edit-modal-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid #e2e8f0;flex-shrink:0;}'
			. '.avi-score-edit-modal-title{font-size:15px;font-weight:700;color:#1e293b;display:flex;align-items:center;gap:8px;}'
			. '.avi-score-edit-modal-close{background:none;border:none;font-size:20px;cursor:pointer;color:#94a3b8;padding:4px 8px;border-radius:6px;line-height:1;}'
			. '.avi-score-edit-modal-close:hover{background:#f1f5f9;color:#475569;}'
			. '.avi-score-edit-modal-body{padding:20px;flex:1;}'
			. '.avi-score-edit-modal-footer{padding:12px 20px;border-top:1px solid #e2e8f0;display:flex;gap:8px;justify-content:flex-end;flex-shrink:0;}'
			. '.avi-score-edit-field{margin-bottom:14px;}'
			. '.avi-score-edit-label{font-size:12px;font-weight:600;color:#475569;margin-bottom:6px;display:block;}'
			. '.avi-score-edit-input{width:100%;padding:9px 12px;border:1px solid #e2e8f0;border-radius:8px;font-size:13px;color:#1e293b;box-sizing:border-box;transition:border-color .15s;}'
			. '.avi-score-edit-input:focus{outline:none;border-color:#6d28d9;box-shadow:0 0 0 3px rgba(109,40,217,.08);}'
			. 'textarea.avi-score-edit-input{min-height:100px;resize:vertical;}'
			. '.avi-score-edit-btn-save{background:#6d28d9;color:#fff;border:none;border-radius:8px;padding:9px 20px;font-size:13px;font-weight:600;cursor:pointer;transition:background .15s;}'
			. '.avi-score-edit-btn-save:hover{background:#5b21b6;}'
			. '.avi-score-edit-btn-save:disabled{background:#c4b5fd;cursor:not-allowed;}'
			. '.avi-score-edit-btn-cancel{background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;border-radius:8px;padding:9px 16px;font-size:13px;cursor:pointer;}'
			. '.avi-score-edit-btn-cancel:hover{background:#e2e8f0;}'
			. '.avi-score-edit-error{color:#dc2626;font-size:12px;margin-top:8px;display:none;}'
			. '.avi-score-edit-success{color:#059669;font-size:12px;margin-top:8px;display:none;}'
			. '.avi-score-edit-lodging-warn{background:#fef3c7;border:1px solid #fcd34d;border-radius:8px;padding:10px 12px;font-size:12px;color:#92400e;margin-bottom:12px;display:flex;gap:8px;align-items:flex-start;}'
			. '.avi-score-criterion-edit-btn{margin-left:auto;background:none;border:1px solid #e2e8f0;border-radius:6px;padding:3px 10px;font-size:11px;color:#6d28d9;cursor:pointer;white-space:nowrap;transition:background .15s,border-color .15s;flex-shrink:0;}'
			. '.avi-score-criterion-edit-btn:hover{background:#f5f3ff;border-color:#c4b5fd;}'
			. '.avi-score-criterion-edit-btn--fix{border-color:#fecaca;color:#dc2626;}'
			. '.avi-score-criterion-edit-btn--fix:hover{background:#fef2f2;}'
			. '.avi-score-hours-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:6px;align-items:center;font-size:12px;}'
			. '.avi-score-hours-day{font-weight:600;color:#374151;}'
			. '.avi-score-hours-input{padding:5px 8px;border:1px solid #e2e8f0;border-radius:6px;font-size:12px;width:100%;box-sizing:border-box;}'
			. '.avi-score-cat-search{position:relative;}'
			. '.avi-score-cat-results{position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid #e2e8f0;border-radius:8px;max-height:180px;overflow-y:auto;z-index:100020;box-shadow:0 4px 12px rgba(0,0,0,.1);display:none;}'
			. '.avi-score-cat-result-item{padding:8px 12px;font-size:12px;cursor:pointer;color:#374151;}'
			. '.avi-score-cat-result-item:hover{background:#f5f3ff;color:#6d28d9;}'
			. '.avi-score-cat-selected{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px;}'
			. '.avi-score-cat-tag{background:#ede9fe;color:#5b21b6;border-radius:4px;padding:3px 8px;font-size:11px;display:flex;align-items:center;gap:4px;}'
			. '.avi-score-cat-tag-remove{cursor:pointer;font-size:14px;line-height:1;color:#7c3aed;}'
			. '.avi-embed-lang-sel{position:relative;display:flex;align-items:center;}'
			. '.avi-embed-lang-btn{background:transparent;border:none;border-radius:6px;color:rgba(255,255,255,0.7);cursor:pointer;font-size:12px;font-weight:500;padding:4px 8px;display:flex;align-items:center;gap:4px;transition:all .15s;pointer-events:auto !important;position:relative;z-index:100;}'
			. '.avi-embed-lang-btn:hover{background:rgba(255,255,255,0.1);color:#fff;}'
			. '.avi-embed-lang-dropdown{position:fixed;background:#1e293b;border:1px solid rgba(255,255,255,0.15);border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.4);min-width:140px;overflow:hidden;z-index:2147483647;display:none;}'
			. '.avi-embed-lang-option{align-items:center;background:none;border:none;color:rgba(255,255,255,0.8);cursor:pointer;display:flex;font-size:13px;gap:10px;padding:10px 14px;transition:background .15s;width:100%;text-align:left;}'
			. '.avi-embed-lang-option:hover{background:rgba(255,255,255,0.08);}'
			. '.avi-embed-lang-option.active{color:#fff;background:rgba(167,139,250,0.15);}'
			. '.avi-embed-upsell{position:fixed;bottom:0;left:0;right:0;'
			. 'background:#1e1b4b;z-index:99998;font-family:Inter,system-ui,sans-serif;'
			. 'transition:height .25s ease;overflow:hidden;}'
			. '.avi-embed-upsell-slim{display:flex;align-items:center;'
			. 'justify-content:space-between;padding:0 16px;height:36px;cursor:pointer;}'
			. '.avi-embed-upsell-slim-text{color:rgba(255,255,255,0.8);font-size:12px;}'
			. '.avi-embed-upsell-slim-btn{background:rgba(167,139,250,0.2);border:none;'
			. 'border-radius:4px;color:#a78bfa;cursor:pointer;font-size:11px;'
			. 'font-weight:600;padding:3px 10px;}'
			. '.avi-embed-upsell-content{display:none;border-top:1px solid rgba(167,139,250,0.3);}'
			. '.avi-embed-upsell.expanded .avi-embed-upsell-content{display:flex;}'
			. '.avi-embed-upsell-block{flex:1;display:flex;align-items:center;'
			. 'justify-content:space-between;padding:8px 16px;gap:12px;}'
			. '.avi-embed-upsell-block+.avi-embed-upsell-block{'
			. 'border-left:1px solid rgba(167,139,250,0.2);}'
			. '.avi-embed-upsell-msg{color:rgba(255,255,255,0.9);font-size:12px;'
			. 'line-height:1.4;flex:1;}'
			. '.avi-embed-upsell-msg strong{color:#fff;font-weight:600;}'
			. '.avi-embed-upsell-badge{background:rgba(167,139,250,0.15);'
			. 'border:1px solid rgba(167,139,250,0.4);border-radius:4px;color:#a78bfa;'
			. 'font-size:10px;font-weight:700;padding:2px 6px;white-space:nowrap;'
			. 'margin-left:6px;}'
			. '.avi-embed-upsell-btn{background:linear-gradient(135deg,#7c3aed,#6d28d9);'
			. 'border:none;border-radius:6px;color:#fff;cursor:pointer;font-size:11px;'
			. 'font-weight:700;padding:7px 12px;white-space:nowrap;transition:opacity .15s;'
			. 'flex-shrink:0;text-decoration:none;display:inline-flex;align-items:center;gap:4px;}'
			. '.avi-embed-upsell-btn:hover{opacity:0.85;}'
			. '.avi-embed-upsell-dismiss{background:none;border:none;'
			. 'color:rgba(255,255,255,0.3);cursor:pointer;font-size:16px;'
			. 'padding:4px 6px;flex-shrink:0;line-height:1;}'
			. 'html body #avision-dashboard-root{padding-bottom:0 !important;}'
			. 'html body #avision-dashboard-root .avi-radar-heatmap-module{padding-bottom:36px !important;}'
			. '.avi-kw-panel{position:absolute;inset:0;padding:16px;overflow-y:auto;background:#f8fafc;z-index:10;}'
			. '.avi-kw-header{background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);'
			. 'border-radius:12px;padding:16px 18px;margin:16px 16px 12px;'
			. 'color:#fff;position:relative;overflow:hidden;font-family:inherit;}'
			. '.avi-kw-header::before{content:"";position:absolute;'
			. 'top:-20px;right:-20px;width:100px;height:100px;'
			. 'background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-kw-header-title{font-size:13px;font-weight:700;margin-bottom:4px;'
			. 'display:flex;align-items:center;gap:6px;color:#fff;}'
			. '.avi-kw-header-sub{font-size:11px;opacity:.9;line-height:1.5;color:#fff;}'
			. '.avi-kw-toolbar{display:flex;align-items:center;gap:10px;margin-bottom:16px;flex-wrap:wrap;}'
			. '.avi-kw-search{border:1px solid #e2e8f0;border-radius:6px;font-size:13px;padding:7px 12px;flex:1;min-width:160px;outline:none;}'
			. '.avi-kw-search:focus{border-color:#7c3aed;}'
			. '.avi-kw-add-btn{background:#7c3aed;border:none;border-radius:6px;color:#fff;cursor:pointer;font-size:13px;font-weight:600;padding:8px 16px;white-space:nowrap;display:flex;align-items:center;gap:6px;}'
			. '.avi-kw-add-btn:hover{background:#6d28d9;}'
			. '.avi-kw-filters{display:flex;gap:6px;margin-bottom:12px;overflow-x:auto;scrollbar-width:none;flex-wrap:nowrap !important;}'
			. '.avi-kw-filters::-webkit-scrollbar{display:none;}'
			. '.avi-kw-filter-btn{background:#fff;border:1px solid #e2e8f0;border-radius:20px;color:#64748b;cursor:pointer;font-size:11px;font-weight:500;padding:4px 12px;transition:all .15s;}'
			. '.avi-kw-filter-btn.active{background:#7c3aed;border-color:#7c3aed;color:#fff;}'
			. '.avi-kw-table{width:100%;table-layout:fixed;border-collapse:collapse;font-size:13px;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.08);}'
			. '.avi-kw-table th{background:linear-gradient(135deg,#ede9fe 0%,#e0e7ff 100%);color:#5b21b6;font-size:11px;font-weight:600;padding:10px 12px;text-align:left;border-bottom:1px solid #c4b5fd;cursor:pointer;user-select:none;white-space:nowrap;letter-spacing:.02em;}'
			. '.avi-kw-table th:hover{background:linear-gradient(135deg,#ddd6fe 0%,#c7d2fe 100%);color:#4c1d95;}'
			. '.avi-kw-table td{padding:10px 12px;border-bottom:1px solid #f1f5f9;vertical-align:middle;color:#1e293b;}'
			. '.avi-kw-table tr:last-child td{border-bottom:none;}'
			. '.avi-kw-table tr:hover td{background:#fafafa;}'
			. '.avi-kw-badge{border-radius:4px;font-size:10px;font-weight:700;padding:2px 7px;}'
			. '.avi-kw-badge-scanned{background:#dcfce7;color:#16a34a;}'
			. '.avi-kw-badge-pending{background:#f1f5f9;color:#64748b;}'
			. '.avi-kw-badge-danger{background:#fef2f2;color:#dc2626;}'
			. '.avi-kw-rank{font-weight:700;color:#7c3aed;}'
			. '.avi-kw-rank-none{color:#94a3b8;}'
			. '.avi-kw-action-btn{background:none;border:1px solid #e2e8f0;border-radius:5px;cursor:pointer;font-size:11px;padding:4px 8px;color:#475569;transition:all .15s;}'
			. '.avi-kw-action-btn:hover{background:#f1f5f9;}'
			. '.avi-kw-action-btn.delete:hover{border-color:#fca5a5;color:#dc2626;}'
			. '.avi-kw-empty{text-align:center;padding:48px 16px;color:#94a3b8;}'
			. '.avi-kw-add-form{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:16px;margin-bottom:16px;display:none;}'
			. '.avi-kw-add-form.open{display:block;}'
			. '.avi-kw-add-input{border:1px solid #e2e8f0;border-radius:6px;font-size:13px;padding:8px 12px;width:100%;margin-bottom:8px;box-sizing:border-box;outline:none;}'
			. '.avi-kw-add-input:focus{border-color:#7c3aed;}'
			. '.avi-kw-add-actions{display:flex;gap:8px;justify-content:flex-end;}'
			. '.avi-kw-cancel-btn{background:#f1f5f9;border:none;border-radius:6px;color:#475569;cursor:pointer;font-size:12px;padding:7px 14px;}'
			. '.avi-kw-grid-badge{border-radius:4px;font-size:10px;font-weight:700;padding:2px 6px;color:#fff;white-space:nowrap;}'
			. '.avi-kw-grid-3x3{background:#16a34a;}'
			. '.avi-kw-grid-5x5{background:#0284c7;}'
			. '.avi-kw-grid-7x7{background:#7c3aed;}'
			. '.avi-kw-grid-9x9{background:#ea580c;}'
			. '.avi-kw-grid-11x11{background:#dc2626;}'
			. '.avi-kw-grid-13x13{background:#374151;}'
			. '.avi-kw-grid-15x15{background:#92400e;}'
			. '.avi-kw-grid-21x21{background:#0f172a;}'
			. '.avi-kw-grid-none{background:#e2e8f0;color:#94a3b8;}'
			. '.avi-kw-group-header{background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;cursor:pointer;display:flex;align-items:center;gap:8px;padding:8px 12px;margin-bottom:4px;font-size:12px;font-weight:600;color:#475569;user-select:none;}'
			. '.avi-kw-group-header:hover{background:#f1f5f9;}'
			. '.avi-kw-group-arrow{transition:transform .2s;display:inline-block;}'
			. '.avi-kw-group-arrow.open{transform:rotate(90deg);}'
			. '.avi-kw-group-body{margin-bottom:8px;}'
			. '.avi-kw-group-body.collapsed{display:none;}'
			. '.avi-kw-table th{text-align:center !important;}'
			. '.avi-kw-table td{text-align:center !important;vertical-align:middle !important;}'
			. '.avi-kw-table th:first-child{text-align:left !important;}'
			. '.avi-kw-table td:first-child{text-align:left !important;}'
			. '.avi-kw-table th:last-child{text-align:center !important;}'
			. '.avi-kw-table td:last-child{text-align:center !important;}'
			. '.avi-kw-table colgroup col:nth-child(1){width:28%;}'
			. '.avi-kw-table colgroup col:nth-child(2){width:8%;}'
			. '.avi-kw-table colgroup col:nth-child(3){width:7%;}'
			. '.avi-kw-table colgroup col:nth-child(4){width:8%;}'
			. '.avi-kw-table colgroup col:nth-child(5){width:10%;}'
			. '.avi-kw-table colgroup col:nth-child(6){width:14%;}'
			. '.avi-kw-table colgroup col:nth-child(7){width:9%;}'
			. '.avi-kw-table colgroup col:nth-child(8){width:16%;}'
			. '.avi-kw-child-row td:first-child{padding-left:12px !important;text-align:left !important;}'
			. '.avi-kw-child-row td{border-bottom:1px solid #f1f5f9 !important;}'
			. '.avi-agency-trigger{align-items:center;background:rgba(255,255,255,0.1);'
			. 'border:1px solid rgba(255,255,255,0.2);border-radius:6px;color:#fff;'
			. 'cursor:pointer;display:flex;font-size:12px;font-weight:600;'
			. 'gap:6px;padding:5px 10px;white-space:nowrap;flex-shrink:0;}'
			. '.avi-agency-trigger:hover{background:rgba(255,255,255,0.18);}'
			. '.avi-agency-panel{position:fixed;top:0;left:0;width:min(420px,92vw);height:100vh;'
			. 'background:#fff;border-right:1px solid #e2e8f0;'
			. 'box-shadow:4px 0 24px rgba(0,0,0,.15);z-index:2147483646;'
			. 'display:flex;flex-direction:column;transform:translateX(-100%);'
			. 'transition:transform .25s ease;}'
			. '.avi-agency-panel.open{transform:translateX(0);}'
			. '.avi-agency-overlay{position:fixed;inset:0;background:rgba(0,0,0,.3);'
			. 'z-index:2147483645;display:none;}'
			. '.avi-agency-overlay.open{display:block;}'
			. '.avi-agency-header{align-items:center;background:#0f172a;'
			. 'display:flex;justify-content:space-between;padding:16px;flex-shrink:0;}'
			. '.avi-agency-header h3{color:#fff;font-size:14px;font-weight:600;margin:0;}'
			. '.avi-agency-close{background:none;border:none;color:rgba(255,255,255,0.6);'
			. 'cursor:pointer;font-size:20px;line-height:1;padding:2px 6px;}'
			. '.avi-agency-search{border:none;border-bottom:1px solid #e2e8f0;'
			. 'font-size:13px;padding:12px 16px;outline:none;width:100%;box-sizing:border-box;'
			. 'flex-shrink:0;}'
			. '.avi-agency-list{flex:1;overflow-y:auto;padding:8px 0;}'
			. '.avi-agency-credits-bar{background:#0f172a;color:#fff;padding:10px 16px;'
			. 'font-size:12px;display:flex;align-items:center;justify-content:space-between;'
			. 'flex-shrink:0;border-bottom:1px solid rgba(255,255,255,0.1);}'
			. '.avi-agency-credits-val{color:#a78bfa;font-weight:700;font-size:14px;}'
			. '.avi-agency-credits-add{background:#7c3aed;border:none;border-radius:4px;'
			. 'color:#fff;cursor:pointer;font-size:10px;font-weight:700;padding:3px 8px;}'
			. '.avi-agency-sort{border:1px solid #e2e8f0;border-radius:6px;'
			. 'color:#64748b;font-size:11px;padding:4px 8px;background:#fff;'
			. 'outline:none;cursor:pointer;margin-left:8px;}'
			. '.avi-agency-item{align-items:flex-start;border:none;background:none;'
			. 'cursor:pointer;display:flex;gap:10px;padding:12px 16px;'
			. 'text-align:left;width:100%;transition:background .15s;'
			. 'border-bottom:1px solid #f1f5f9;}'
			. '.avi-agency-item:hover{background:#f8fafc;}'
			. '.avi-agency-item.active{background:#f5f3ff;border-left:3px solid #6d28d9;}'
			. '.avi-agency-item.active.avi-agency-urgency-high,.avi-agency-item.active.avi-agency-urgency-med{'
			. 'background:#f5f3ff !important;border-left:3px solid #6d28d9 !important;}'
			. '.avi-agency-item-avatar{align-items:center;border-radius:8px;'
			. 'color:#fff;display:flex;flex-shrink:0;'
			. 'font-size:12px;font-weight:700;height:40px;justify-content:center;width:40px;}'
			. '.avi-agency-item-info{flex:1;min-width:0;}'
			. '.avi-agency-item-name{color:#1e293b;font-size:13px;font-weight:600;'
			. 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-bottom:2px;}'
			. '.avi-agency-item-lines{display:flex;flex-direction:column;gap:0;min-width:0;}'
			. '.avi-agency-item-line{display:flex;align-items:center;gap:6px;flex-wrap:nowrap;'
			. 'overflow:hidden;font-size:11px;color:#64748b;margin-top:2px;}'
			. '.avi-agency-item-line span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}'
			. '.avi-ag-badge{border-radius:3px;font-size:10px;font-weight:600;'
			. 'padding:1px 5px;white-space:nowrap;}'
			. '/* #SprintL1-L3.4-unanswered-badge */'
			. '.avi-ag-unanswered-badge{display:inline-flex;align-items:center;'
			. 'gap:3px;background:#fef2f2;color:#dc2626;border:1px solid #fecaca;'
			. 'border-radius:4px;padding:1px 6px;font-size:11px;font-weight:600;}'
			. '.avi-ag-score-red{background:#fef2f2;color:#dc2626;}'
			. '.avi-ag-score-orange{background:#fff7ed;color:#ea580c;}'
			. '.avi-ag-score-yellow{background:#fefce8;color:#ca8a04;}'
			. '.avi-ag-score-green{background:#f0fdf4;color:#16a34a;}'
			. '.avi-ag-score-gold{background:#fef9c3;color:#b45309;}'
			. '.avi-ag-guardian-on{background:#dcfce7;color:#16a34a;}'
			. '.avi-ag-guardian-off{background:#f1f5f9;color:#94a3b8;}'
			. '.avi-ag-activity{color:#94a3b8;font-size:10px;}'
			. '.avi-agency-urgency-high{border-left:3px solid #dc2626 !important;}'
			. '.avi-agency-urgency-med{border-left:3px solid #ea580c !important;}'
			. '.avi-agency-footer{border-top:1px solid #e2e8f0;padding:12px 16px;flex-shrink:0;}'
			. '.avi-agency-count{color:#94a3b8;font-size:11px;text-align:center;}'
			. '.avi-submenu-wrap{position:relative;display:inline-flex;align-items:stretch;}'
			. '.avi-submenu-arrow{background:none;border:none;border-left:1px solid rgba(255,255,255,0.15);color:rgba(255,255,255,0.6);cursor:pointer;font-size:10px;padding:0 6px;}'
			. '.avi-submenu-arrow:hover{color:#fff;}'
			. '.avi-submenu-drop{position:fixed;background:#1e293b;border:1px solid rgba(255,255,255,0.15);border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.4);min-width:180px;z-index:2147483647;display:none;}'
			. '.avi-submenu-drop.open{display:block;}'
			. '.avi-submenu-opt{background:none;border:none;color:rgba(255,255,255,0.85);cursor:pointer;display:block;font-size:13px;padding:10px 16px;text-align:left;width:100%;transition:background .15s;}'
			. '.avi-submenu-opt:hover{background:rgba(255,255,255,0.08);}'
			. '.avi-submenu-opt.active{color:#a78bfa;}'
			. '.avi-submenu-drop .avi-submenu-opt{'
			. 'color:#0f172a!important;'
			. 'background:#fff!important;'
			. '}'
			. '.avi-submenu-drop .avi-submenu-opt:hover{'
			. 'background:#f1f5f9!important;'
			. 'color:#7c3aed!important;'
			. '}'
			. ( $key_type === 'agency'
				? '.avi-agency-item-wrap{display:flex;align-items:center;gap:4px;'
				. 'width:100%;overflow:hidden;margin-bottom:4px;}'
				. '.avi-agency-item-wrap .avi-agency-item{flex:1;min-width:0;}'
				. '.avi-ag-assign-btn{font-size:10px;padding:2px 8px;border-radius:4px;'
				. 'border:1px solid #c4b5fd;background:#f5f3ff;color:#6d28d9;cursor:pointer;'
				. 'white-space:nowrap;transition:background .15s;flex-shrink:0;}'
				. '.avi-ag-assign-btn:hover{background:#ede9fe;}'
				. '.avi-ag-credits-badge{display:inline-flex;align-items:center;gap:3px;'
				. 'background:#f5f3ff;color:#6d28d9;border:1px solid #ddd6fe;'
				. 'border-radius:4px;padding:1px 6px;font-size:11px;font-weight:600;}'
				. '.avi-bulk-bar{display:flex;align-items:center;gap:8px;'
				. 'padding:8px 12px;background:#f5f3ff;'
				. 'border-bottom:1px solid #ddd6fe;flex-wrap:wrap;font-size:12px;}'
				. '.avi-bulk-select-all{display:flex;align-items:center;gap:4px;'
				. 'color:#6d28d9;font-weight:600;cursor:pointer;}'
				. '.avi-bulk-count{color:#64748b;flex:1;font-size:11px;}'
				. '.avi-bulk-qty-wrap{display:flex;align-items:center;gap:4px;}'
				. '.avi-bulk-qty-input{width:60px;padding:4px 6px;'
				. 'border:1px solid #ddd6fe;border-radius:6px;'
				. 'font-size:12px;text-align:center;}'
				. '.avi-bulk-assign-btn{background:#6d28d9;color:#fff;border:none;'
				. 'border-radius:6px;padding:6px 12px;font-size:11px;'
				. 'font-weight:600;cursor:pointer;white-space:nowrap;}'
				. '.avi-bulk-assign-btn:disabled{opacity:.5;cursor:not-allowed;}'
				. '.avi-bulk-assign-btn:hover:not(:disabled){background:#5b21b6;}'
				. '.avi-client-checkbox{cursor:pointer;accent-color:#6d28d9;'
				. 'width:14px;height:14px;flex-shrink:0;}'
				. '.avi-onboarding-overlay{position:fixed;inset:0;z-index:100040;'
				. 'background:rgba(15,23,42,.92);display:flex;align-items:center;'
				. 'justify-content:center;padding:20px;}'
				. '.avi-onboarding-modal{background:#fff;border-radius:20px;'
				. 'max-width:440px;width:100%;padding:40px 32px;text-align:center;'
				. 'box-shadow:0 20px 60px rgba(0,0,0,.3);}'
				. '.avi-onboarding-logo{font-size:48px;margin-bottom:16px;}'
				. '.avi-onboarding-title{font-size:22px;font-weight:800;'
				. 'color:#1e293b;margin-bottom:8px;}'
				. '.avi-onboarding-subtitle{font-size:14px;color:#64748b;'
				. 'margin-bottom:32px;line-height:1.6;}'
				. '.avi-onboarding-connect-btn{display:inline-flex;align-items:center;'
				. 'gap:10px;background:linear-gradient(135deg,#4285f4,#34a853);'
				. 'color:#fff;border:none;border-radius:12px;padding:14px 28px;'
				. 'font-size:15px;font-weight:700;cursor:pointer;'
				. 'text-decoration:none;transition:opacity .15s;margin-bottom:16px;'
				. 'width:100%;justify-content:center;}'
				. '.avi-onboarding-connect-btn:hover{opacity:.9;}'
				. '.avi-onboarding-skip{font-size:12px;color:#94a3b8;'
				. 'cursor:pointer;text-decoration:underline;display:block;}'
				. '.avi-onboarding-steps{display:flex;gap:16px;margin-bottom:28px;'
				. 'text-align:left;}'
				. '.avi-onboarding-step{flex:1;background:#f8fafc;border-radius:10px;'
				. 'padding:12px;font-size:12px;color:#475569;}'
				. '.avi-onboarding-step-icon{font-size:20px;margin-bottom:6px;}'
				. '.avi-onboarding-step-title{font-weight:700;color:#1e293b;'
				. 'margin-bottom:4px;font-size:12px;}'
				. '.avi-ag-line3-right{flex-shrink:0;white-space:nowrap;'
				. 'color:#64748b;font-size:11px;}'
				. '.avi-ag-cat-trunc{flex:1;overflow:hidden;text-overflow:ellipsis;'
				. 'white-space:nowrap;min-width:0;}'
				. '.avi-assign-modal-backdrop{position:fixed;inset:0;z-index:2147483656;'
				. 'background:rgba(0,0,0,.4);display:none;align-items:center;justify-content:center;}'
				. '.avi-assign-modal{background:#fff;border-radius:14px;width:320px;'
				. 'box-shadow:0 8px 30px rgba(0,0,0,.15);}'
				. '.avi-assign-modal-header{display:flex;justify-content:space-between;'
				. 'align-items:center;padding:14px 18px;border-bottom:1px solid #e2e8f0;'
				. 'font-weight:700;font-size:14px;}'
				. '.avi-assign-modal-body{padding:18px;}'
				. '.avi-assign-client-name{font-weight:600;color:#1e293b;margin-bottom:4px;}'
				. '.avi-assign-client-credits{font-size:12px;color:#6d28d9;margin-bottom:8px;}'
				. '.avi-assign-pool{font-size:12px;color:#64748b;margin-bottom:16px;}'
				. '.avi-assign-qty-wrap{display:flex;align-items:center;gap:8px;margin-bottom:4px;}'
				. '.avi-assign-qty-hint{font-size:10px;color:#94a3b8;'
				. 'text-align:center;margin-top:4px;margin-bottom:12px;}'
				. '.avi-assign-qty-btn{width:32px;height:32px;border-radius:6px;border:1px solid #e2e8f0;'
				. 'background:#f8fafc;font-size:18px;cursor:pointer;display:flex;'
				. 'align-items:center;justify-content:center;}'
				. '.avi-assign-qty-btn:hover{background:#e2e8f0;}'
				. '#aviAssignQty{flex:1;text-align:center;padding:6px;border:1px solid #e2e8f0;'
				. 'border-radius:6px;font-size:16px;font-weight:700;}'
				. '.avi-assign-confirm-btn{width:100%;padding:10px;background:#6d28d9;color:#fff;'
				. 'border:none;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;}'
				. '.avi-assign-confirm-btn:hover{background:#5b21b6;}'
				. '.avi-assign-confirm-btn:disabled{opacity:.6;cursor:not-allowed;}'
				. '.avi-assign-msg{font-size:12px;margin-top:8px;text-align:center;}'
				. '#aviAssignClose{background:none;border:none;font-size:20px;color:#94a3b8;cursor:pointer;}'
				: '' )
			. '.avi-score-panel{position:absolute;inset:0;background:#f8fafc;'
			. 'z-index:10;display:none;overflow-y:auto;padding:24px;padding-bottom:60px !important;}'
			. '.avi-score-inner{max-width:900px;margin:0 auto;}'
			. '.avi-score-topbar{background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);border-radius:12px;padding:18px 22px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between;gap:16px;position:relative;overflow:hidden;color:#fff;}'
			. '.avi-score-topbar::before{content:"";position:absolute;top:-20px;right:-20px;width:120px;height:120px;background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-score-topbar-left{flex:1;min-width:0;}'
			. '.avi-score-topbar-title{font-size:.95rem;font-weight:900;color:#fff;display:flex;align-items:center;gap:6px;margin-bottom:4px;}'
			. '.avi-score-topbar-biz{font-size:13px;color:rgba(255,255,255,.85);font-weight:500;margin-bottom:2px;}'
			. '.avi-score-topbar-sub{font-size:11px;color:rgba(255,255,255,.7);line-height:1.4;}'
			. '.avi-score-topbar-right{flex-shrink:0;}'
			. '.avi-score-close{background:none;border:none;color:#94a3b8;'
			. 'cursor:pointer;font-size:22px;padding:4px;}'
			. '.avi-score-gauge-wrap{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:12px;padding:24px;margin-bottom:16px;text-align:center;}'
			. '.avi-score-gauge-svg{display:block;margin:0 auto 12px;}'
			. '.avi-score-gauge-val{font-size:48px;font-weight:800;line-height:1;}'
			. '.avi-score-gauge-label{color:#64748b;font-size:13px;margin-top:4px;}'
			. '.avi-score-gauge-sync{color:#94a3b8;font-size:11px;margin-top:8px;}'
			. '.avi-score-criteria{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:12px;padding:20px;margin-bottom:16px;}'
			. '.avi-score-criteria h3{font-size:13px;font-weight:600;color:#475569;'
			. 'margin-bottom:12px;text-transform:uppercase;letter-spacing:.5px;}'
			. '.avi-score-nap-row{padding:10px 0;border-bottom:1px solid #f1f5f9;}'
			. '.avi-score-nap-row:last-child{border-bottom:none;}'
			. '.avi-score-nap-top{display:flex;align-items:center;gap:8px;}'
			. '.avi-score-nap-icon{font-size:16px;flex-shrink:0;width:22px;text-align:center;}'
			. '.avi-score-nap-label{flex:1;font-size:13px;font-weight:600;color:#1e293b;}'
			. '.avi-score-nap-pts{font-size:11px;font-weight:700;color:#6d28d9;white-space:nowrap;}'
			. '.avi-score-nap-status{font-size:11px;padding:2px 7px;border-radius:4px;font-weight:600;white-space:nowrap;}'
			. '.avi-score-nap-val{font-size:11px;color:#64748b;margin-top:3px;padding-left:30px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}'
			. '.avi-score-gbp-link{display:inline-flex;align-items:center;gap:4px;border:1.5px solid #6d28d9;color:#6d28d9;background:transparent;border-radius:8px;font-size:12px;font-weight:700;padding:7px 14px;text-decoration:none;white-space:nowrap;transition:background .15s;}'
			. '.avi-score-gbp-link:hover{background:#ede9fe;}'
			. '.avi-sync-btn{background:#f0fdf4;border:1.5px solid #86efac;border-radius:8px;color:#15803d;cursor:pointer;font-size:12px;font-weight:700;padding:7px 14px;white-space:nowrap;width:100%;transition:background .15s;}'
			. '.avi-sync-btn:hover{background:#dcfce7;}'
			. '.avi-sync-btn:disabled{opacity:.6;cursor:not-allowed;}'
			. '.avi-sync-btn--syncing{background:#f0f9ff;border-color:#bae6fd;color:#0369a1;}'
			. '.avi-sync-btn-wrap{display:flex;justify-content:center;'
			. 'margin:8px 0 4px;}'
			. '.avi-score-gauge-card{display:grid;grid-template-columns:1fr repeat(3,auto) auto;gap:0;background:#fff;border-radius:14px;border:1px solid #e2e8f0;margin-bottom:16px;overflow:hidden;}'
			. '.avi-score-gc-gauge{display:flex;flex-direction:column;align-items:center;padding:20px 24px;border-right:1px solid #f1f5f9;background:#fff;min-width:200px;}'
			. '.avi-score-gauge-progress{width:100%;height:4px;background:#e2e8f0;border-radius:2px;margin:6px 0 4px;overflow:hidden;}'
			. '.avi-score-gauge-progress-bar{height:100%;border-radius:2px;transition:width .6s ease;}'
			. '.avi-score-gc-kpi{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:20px 24px;border-right:1px solid #f1f5f9;min-width:110px;transition:filter .15s;}'
			. '.avi-score-gc-kpi:hover{filter:brightness(.97);}'
			. '.avi-score-gc-kpi-row{display:flex;align-items:center;gap:6px;margin-bottom:6px;}'
			. '.avi-score-gc-kpi-val{font-size:28px;font-weight:800;line-height:1;}'
			. '.avi-score-gc-kpi-icon{font-size:20px;line-height:1;}'
			. '.avi-score-gc-kpi-label{font-size:11px;color:#94a3b8;text-align:center;white-space:nowrap;}'
			. '.avi-score-gc-actions{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:20px 16px;background:#f8fafc;min-width:140px;}'
			. '/* #SprintL1-L1.4-badge-fix — badge vérification moderne */'
			. '.avi-verified-badge{display:inline-flex;align-items:center;gap:5px;'
			. 'font-size:11px;font-weight:600;border-radius:20px;padding:4px 10px;'
			. 'letter-spacing:.01em;}'
			. '/* #SprintL1-L1.4-badge-position */'
			. '.avi-ehd-widget--score{position:relative;}'
			. '.avi-ehd-widget--score .avi-verified-badge{'
			. 'position:absolute;top:8px;right:8px;font-size:10px;padding:2px 8px;}'
			. '.avi-verify-cta{background:#fef2f2;border:1px solid #fecaca;'
			. 'border-radius:8px;padding:10px 14px;margin:12px 20px 0;}'
			. '.avi-verify-cta--pending{background:#fefce8;border-color:#fde68a;}'
			. '.avi-verify-cta-text{font-size:12px;color:#374151;margin:0 0 8px;}'
			. '.avi-verify-cta-btn{display:inline-flex;align-items:center;'
			. 'background:#dc2626;color:#fff;border-radius:6px;padding:6px 14px;'
			. 'font-size:12px;font-weight:600;text-decoration:none;'
			. 'transition:background .15s;}'
			. '.avi-verify-cta-btn:hover{background:#b91c1c;}'
			. '.avi-score-criteria-wrap{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;}'
			. '.avi-score-col{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px;}'
			. '.avi-score-col-title{font-size:12px;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:.5px;margin-bottom:12px;}'
			. '.avi-attrs-group{margin-bottom:12px;}'
			. '.avi-attrs-group-title{font-size:11px;font-weight:600;color:#6d28d9;text-transform:uppercase;letter-spacing:.3px;margin-bottom:6px;padding-bottom:4px;border-bottom:1px solid #ede9fe;}'
			. '.avi-score-attr-row{display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid #f8fafc;}'
			. '.avi-score-attr-row:last-child{border-bottom:none;}'
			. '.avi-score-attr-row--empty{opacity:.5;}'
			. '.avi-attrs-load-error{color:#94a3b8;font-size:12px;padding:12px;text-align:center;}'
			. '.avi-attrs-load-hint{font-size:11px;color:#6d28d9;font-weight:600;}'
			. '.avi-score-attr-label{flex:1;font-size:12px;color:#1e293b;}'
			. '.avi-attr-na{font-size:10px;color:#94a3b8;white-space:nowrap;}'
			. '.avi-attr-toggle{position:relative;display:inline-block;width:36px;height:20px;flex-shrink:0;}'
			. '.avi-attr-toggle input{opacity:0;width:0;height:0;}'
			. '.avi-attr-slider{position:absolute;cursor:pointer;inset:0;background:#e2e8f0;border-radius:20px;transition:.2s;}'
			. '.avi-attr-slider:before{content:"";position:absolute;width:14px;height:14px;left:3px;bottom:3px;background:#fff;border-radius:50%;transition:.2s;}'
			. '.avi-attr-cb:checked+.avi-attr-slider{background:#6d28d9;}'
			. '.avi-attr-cb:checked+.avi-attr-slider:before{transform:translateX(16px);}'
			. '.avi-attr-cb:disabled+.avi-attr-slider{cursor:not-allowed;opacity:.6;}'
			. '.avi-attr-enum-wrap{display:flex;flex-direction:column;gap:4px;width:100%;}'
			. '.avi-attr-enum-options{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px;}'
			. '.avi-attr-enum-opt{display:flex;align-items:center;gap:4px;font-size:12px;color:#1e293b;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;padding:3px 8px;cursor:pointer;}'
			. '.avi-attr-enum-opt input{accent-color:#6d28d9;}'
			. '.avi-attr-enum-sel{border:1px solid #e2e8f0;border-radius:6px;font-size:12px;padding:6px 10px;color:#1e293b;width:100%;background:#fff;}'
			. '.avi-attr-url-wrap{width:100%;}'
			. '.avi-attr-url-row{display:flex;gap:6px;align-items:center;margin-top:4px;}'
			. '.avi-attr-url-input{flex:1;border:1px solid #e2e8f0;border-radius:6px;font-size:12px;padding:5px 8px;color:#1e293b;}'
			. '.avi-attr-url-input:focus{border-color:#6d28d9;outline:none;}'
			. '.avi-attr-url-gbp{font-size:11px;color:#6d28d9;text-decoration:none;white-space:nowrap;border:1px solid #c4b5fd;border-radius:6px;padding:4px 8px;}'
			. '.avi-attr-url-gbp:hover{background:#ede9fe;}'
			. '.avi-attrs-group-hint{font-size:11px;color:#94a3b8;margin-bottom:8px;line-height:1.4;padding:6px 8px;background:#f8fafc;border-radius:6px;border-left:3px solid #c4b5fd;}'
			. '.avi-attrs-section-title{font-size:11px;font-weight:700;color:#6d28d9;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;}'
			. '.avi-attrs-sep{border-top:1px solid #e2e8f0;margin:12px 0;}'
			. '.avi-attrs-group-toggle{cursor:pointer;user-select:none;display:flex;justify-content:space-between;align-items:center;}'
			. '.avi-attrs-group-toggle:hover{color:#4c1d95;}'
			. '.avi-attrs-chevron{font-size:16px;font-weight:700;color:#94a3b8;transition:transform .15s;}'
			. '.avi-attrs-group-body{overflow:hidden;}'
			. '.avi-score-nap-fresh{font-size:10px;margin-top:3px;padding-left:30px;line-height:1.4;}'
			. '.avi-score-nap-fresh--ok{color:#16a34a;}'
			. '.avi-score-nap-fresh--warn{color:#ea580c;font-weight:600;}'
			. '.avi-score-nap-row--guardian{border-left:3px solid #ef4444 !important;padding-left:8px !important;background:#fff8f8 !important;border-radius:6px;}'
			. '.avi-score-nap-row--warn{border-left:3px solid #f59e0b !important;padding-left:8px !important;background:#fffbeb !important;border-radius:6px;}'
			. '.avi-score-warn{background:#fef3c7;color:#92400e;border-radius:4px;padding:1px 6px;font-size:11px;font-weight:600;}'
			. '.avi-score-nap-guardian-diff{margin-top:5px;padding:6px 10px;background:#fef2f2;border:1px solid #fecaca;border-radius:6px;font-size:11px;}'
			. '.avi-score-nap-guardian-old{color:#64748b;margin-bottom:2px;}'
			. '.avi-score-nap-guardian-new{color:#dc2626;font-weight:700;}'
			. '.avi-score-nap-guardian-date{color:#94a3b8;font-size:10px;margin-top:3px;}'
			. '.avi-score-nap-guardian-fix-now{margin-top:8px;width:100%;padding:7px 12px;background:#dc2626;color:#fff;border:none;border-radius:6px;font-size:12px;font-weight:700;cursor:pointer;text-align:left;display:block;}'
			. '.avi-score-nap-guardian-fix-now:hover{background:#b91c1c;}'
			. '.avi-score-nap-guardian-label{font-size:12px;font-weight:700;color:#dc2626;margin-bottom:4px;display:flex;align-items:center;gap:4px;}'
			. '.avi-score-nap-upsell{padding-left:30px;margin-top:3px;}'
			. '.avi-score-upsell-btn{font-size:10px;color:#6d28d9;text-decoration:none;font-weight:600;border:none;background:transparent;padding:0;cursor:pointer;}'
			. '.avi-score-upsell-btn:hover{text-decoration:underline;}'
			. '.avi-score-freshness-note{font-size:11px;color:#64748b;background:#f8fafc;border-left:3px solid #c4b5fd;border-radius:4px;padding:6px 10px;margin-bottom:12px;line-height:1.4;}'
			. '.avi-score-delta{font-size:12px;font-weight:700;padding:3px 10px;border-radius:20px;margin-top:4px;display:inline-block;}'
			. '.avi-score-delta--neg{background:#fee2e2;color:#dc2626;}'
			. '.avi-score-delta--pos{background:#dcfce7;color:#16a34a;}'
			. '.avi-score-delta-home{font-size:10px;font-weight:700;padding:2px 6px;border-radius:10px;margin-left:6px;vertical-align:middle;}'
			. '.avi-score-nap-pts--neg{color:#dc2626 !important;}'
			. '.avi-score-hm-sep{display:flex;align-items:center;justify-content:space-between;padding:12px 0 8px;border-top:2px solid #ede9fe;margin-top:8px;}'
			. '.avi-score-hm-title{font-size:12px;font-weight:700;color:#6d28d9;text-transform:uppercase;letter-spacing:.5px;}'
			. '.avi-score-hm-row{background:#faf9ff;border-radius:6px;padding:4px 6px;margin-bottom:4px;}'
			. '.avi-sh-wrap{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:18px 20px;margin-top:16px;}'
			. '.avi-sh-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:8px;}'
			. '.avi-sh-title{font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:#6d28d9;display:flex;align-items:center;gap:6px;}'
			. '.avi-sh-controls{display:flex;gap:6px;flex-wrap:wrap;align-items:center;}'
			. '.avi-sh-period-btn{font-size:11px;padding:3px 10px;border-radius:5px;border:1px solid #e2e8f0;background:#f8fafc;color:#64748b;cursor:pointer;font-weight:500;}'
			. '.avi-sh-period-btn--active{background:#6d28d9;color:#fff;border-color:#6d28d9;}'
			. '.avi-sh-curve-btn{font-size:11px;padding:3px 10px;border-radius:5px;border:1px solid #e2e8f0;background:#f8fafc;color:#64748b;cursor:pointer;}'
			. '.avi-sh-curve-btn--active{border-color:#6d28d9;color:#6d28d9;font-weight:600;}'
			. '.avi-sh-kw-select{font-size:11px;padding:3px 8px;border:1px solid #e2e8f0;border-radius:5px;color:#475569;background:#f8fafc;cursor:pointer;}'
			. '.avi-sh-svg-wrap{width:100%;overflow:hidden;position:relative;}'
			. '.avi-sh-svg-wrap svg{width:100%;height:180px;}'
			. '.avi-sh-legend{display:flex;gap:16px;margin-top:10px;flex-wrap:wrap;}'
			. '.avi-sh-legend-item{display:flex;align-items:center;gap:5px;font-size:11px;color:#64748b;}'
			. '.avi-sh-legend-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0;}'
			. '.avi-sh-stat{display:flex;gap:16px;margin-top:10px;flex-wrap:wrap;}'
			. '.avi-sh-stat-item{font-size:11px;color:#64748b;}'
			. '.avi-sh-stat-item strong{color:#1e293b;font-size:13px;}'
			. '.avi-sh-empty{text-align:center;padding:40px 0;color:#94a3b8;font-size:13px;}'
			. '.avi-sh-info-btn{background:none;border:none;cursor:pointer;font-size:13px;padding:0 4px;}'
			. '.avi-sh-tooltip{position:absolute;background:#1e293b;color:#fff;font-size:11px;padding:8px 12px;border-radius:8px;pointer-events:none;opacity:0;transition:opacity .15s;z-index:999;min-width:140px;box-shadow:0 4px 12px rgba(0,0,0,.2);}'
			. '.avi-sh-tooltip-date{font-weight:700;margin-bottom:4px;color:#e2e8f0;font-size:10px;}'
			. '.avi-sh-tooltip-row{display:flex;align-items:center;gap:6px;margin-top:2px;}'
			. '.avi-sh-tooltip-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0;}'
			. '.avi-score-tabs{display:flex;gap:4px;margin-bottom:16px;background:#f1f5f9;border-radius:10px;padding:4px;}'
			. '.avi-score-tab-btn{flex:1;padding:8px 12px;border:none;background:none;border-radius:7px;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;transition:all .2s;font-family:inherit;}'
			. '.avi-score-tab-btn--active{background:#fff;color:#6d28d9;box-shadow:0 1px 4px rgba(0,0,0,.08);}'
			. '.avi-score-tab-panel{display:none;}'
			. '.avi-score-tab-panel--active{display:block;}'
			. '.avi-score-cards-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px;}'
			. '.avi-score-card{background:#fff;border:1px solid #e2e8f0;border-radius:12px;overflow:hidden;}'
			. '.avi-score-card-header{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;cursor:pointer;user-select:none;border-bottom:1px solid #f1f5f9;}'
			. '.avi-score-card-header-left{display:flex;align-items:center;gap:8px;}'
			. '.avi-score-card-title{font-size:13px;font-weight:700;color:#1e293b;}'
			. '.avi-score-card-count{font-size:11px;color:#94a3b8;margin-left:4px;}'
			. '.avi-score-card-chevron{font-size:12px;color:#94a3b8;transition:transform .2s;}'
			. '.avi-score-card--collapsed .avi-score-card-chevron{transform:rotate(-90deg);}'
			. '.avi-score-card-info-btn{background:none;border:none;cursor:pointer;font-size:12px;padding:0 4px;}'
			. '.avi-score-card-body{padding:0 0 8px 0;}'
			. '.avi-score-card--collapsed .avi-score-card-body{display:none;}'
			. '.avi-score-card-body .avi-score-nap-row{border-radius:0;border-left:none;border-right:none;border-top:none;margin-bottom:0;padding:10px 16px;}'
			. '.avi-score-card-body .avi-score-hm-sep{margin:0;padding:10px 16px 6px;border-top:1px solid #f1f5f9;}'
			. '.avi-score-card-body .avi-score-hm-row{border-radius:0;margin-bottom:0;padding:10px 16px;}'
			. '.avi-score-card-more-btn{width:100%;padding:8px 16px;background:none;border:none;border-top:1px solid #f1f5f9;color:#6d28d9;font-size:12px;font-weight:600;cursor:pointer;text-align:center;font-family:inherit;}'
			. '.avi-score-card-more-btn:hover{background:#faf5ff;}'
			. '[data-score-tab-panel="attributes"] .avi-score-col{'
			. 'width:100%;max-width:100%;border:1px solid #e2e8f0;'
			. 'border-radius:12px;padding:20px;background:#fff;'
			. '}'
			. '[data-score-tab-panel="attributes"] .avi-attrs-group{'
			. 'break-inside:avoid;'
			. '}'
			. '.avi-score-card-status{display:flex;gap:4px;align-items:center;}'
			. '.avi-score-card-dot{width:8px;height:8px;border-radius:50%;}'
			. '.avi-sh-fullscreen-btn{font-size:11px;padding:3px 10px;border-radius:5px;border:1px solid #e2e8f0;background:#f8fafc;color:#64748b;cursor:pointer;}'
			. '.avi-sh-fullscreen-btn:hover{background:#e2e8f0;}'
			. '.avi-sh-wrap--fullscreen{position:fixed;inset:0;z-index:2147483646;background:#fff;padding:56px 24px 16px;overflow:hidden;margin:0;border-radius:0;display:flex;flex-direction:column;gap:6px;}'
			. '.avi-sh-wrap--fullscreen .avi-sh-header{flex-shrink:0;min-height:36px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;padding-right:80px;}'
			. '.avi-sh-wrap--fullscreen .avi-sh-svg-wrap{flex:1;min-height:0;height:calc(100vh - 240px) !important;max-height:calc(100vh - 240px);overflow:hidden;}'
			. '.avi-sh-wrap--fullscreen .avi-sh-svg-wrap svg{width:100% !important;height:100% !important;display:block;}'
			. '.avi-sh-wrap--fullscreen .avi-sh-stat{flex-shrink:0;min-height:24px;}'
			. '.avi-sh-wrap--fullscreen .avi-sh-legend{flex-shrink:0;min-height:20px;}'
			. '@media(max-width:640px){'
			. '.avi-score-cards-grid{grid-template-columns:1fr;}'
			. '.avi-score-tabs{gap:2px;}'
			. '.avi-score-tab-btn{font-size:11px;padding:6px 8px;}'
			. '}'
			. '.avi-score-b2-tabs{display:none;}'
			. '@media(max-width:640px){'
			. '.avi-score-criteria-wrap{grid-template-columns:1fr;}'
			. '.avi-score-gauge-card{grid-template-columns:1fr 1fr;grid-template-rows:auto auto auto;}'
			. '.avi-score-gc-gauge{grid-column:1/-1;border-right:none;border-bottom:1px solid #f1f5f9;}'
			. '.avi-score-gc-kpi{border-right:none;border-bottom:1px solid #f1f5f9;}'
			. '.avi-score-gc-actions{grid-column:1/-1;flex-direction:row;}'
			. '.avi-score-b2-tabs{display:flex;gap:0;margin-bottom:12px;border-radius:8px;overflow:hidden;border:1px solid #e2e8f0;}'
			. '.avi-score-b2-tab{flex:1;padding:8px;background:#f8fafc;border:none;font-size:12px;font-weight:600;color:#64748b;cursor:pointer;}'
			. '.avi-score-b2-tab.active{background:#6d28d9;color:#fff;}'
			. '.avi-score-col--hidden{display:none !important;}'
			. '}'
			. '.avi-verified-badge--verified{background:#f0fdf4;color:#15803d;'
			. 'border:1px solid #86efac;}'
			. '.avi-verified-badge--verified::before{content:"\\2713";'
			. 'color:#16a34a;font-weight:700;}'
			. '.avi-verified-badge--pending{background:#fefce8;color:#a16207;'
			. 'border:1px solid #fde047;}'
			. '.avi-verified-badge--pending::before{content:"\\29D6";color:#ca8a04;}'
			. '.avi-verified-badge--unverified{background:#f8fafc;color:#64748b;'
			. 'border:1px solid #e2e8f0;}'
			. '.avi-verified-badge--unverified::before{content:"\\26A0";color:#f59e0b;}'
			. '.avi-score-ok{background:#dcfce7;color:#16a34a;}'
			. '.avi-score-ko{background:#fef2f2;color:#dc2626;}'
			. '.avi-score-stats{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:12px;padding:20px;margin-bottom:16px;}'
			. '.avi-score-stats h3{font-size:13px;font-weight:600;color:#475569;'
			. 'margin-bottom:12px;text-transform:uppercase;letter-spacing:.5px;}'
			. '.avi-score-stats-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;min-width:0;}'
			. '.avi-score-stat-item{background:#f8fafc;border-radius:8px;'
			. 'padding:16px;text-align:center;}'
			. '.avi-score-stat-val{font-size:24px;font-weight:700;color:#1e293b;}'
			. '.avi-score-stat-label{font-size:10px;color:#94a3b8;margin-top:2px;}'
			. '.avi-score-export{display:flex;gap:8px;margin-top:8px;}'
			. '.avi-score-export-btn{background:#0f172a;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;font-size:12px;font-weight:600;'
			. 'padding:8px 16px;flex:1;transition:opacity .15s;}'
			. '.avi-score-export-btn:hover{opacity:0.85;}'
			. '.avi-score-export-btn.csv{background:#16a34a;}'
			. '.avi-reviews-panel{position:absolute;inset:0;background:#f8fafc;'
			. 'z-index:10;display:none;overflow-y:auto;padding:24px;padding-bottom:60px;}'
			. '.avi-reviews-inner{max-width:960px;margin:0 auto;}'
			. '.avi-reviews-header{display:flex;align-items:center;gap:16px;'
			. 'background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);border-radius:12px;'
			. 'padding:20px 24px;margin-bottom:16px;position:relative;overflow:hidden;}'
			. '.avi-reviews-header::before{content:"";position:absolute;top:-20px;right:-20px;'
			. 'width:100px;height:100px;background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-reviews-avg{font-size:48px;font-weight:800;color:#fff;line-height:1;}'
			. '.avi-reviews-avg-sub{color:rgba(255,255,255,.8);font-size:13px;margin-top:4px;}'
			. '.avi-reviews-stars{color:#fbbf24;font-size:20px;letter-spacing:2px;}'
			. '.avi-review-card{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:10px;padding:16px;margin-bottom:12px;}'
			. '.avi-review-card-header{display:flex;align-items:center;gap:10px;'
			. 'margin-bottom:10px;}'
			. '.avi-review-avatar{width:36px;height:36px;border-radius:50%;'
			. 'object-fit:cover;flex-shrink:0;background:#e2e8f0;}'
			. '.avi-review-avatar-initials{width:36px;height:36px;border-radius:50%;'
			. 'background:#7c3aed;color:#fff;display:flex;align-items:center;'
			. 'justify-content:center;font-size:13px;font-weight:700;flex-shrink:0;}'
			. '.avi-review-name{font-size:13px;font-weight:600;color:#1e293b;}'
			. '.avi-review-date{color:#94a3b8;font-size:11px;}'
			. '.avi-review-stars{color:#f59e0b;font-size:14px;}'
			. '.avi-review-text{color:#374151;font-size:13px;line-height:1.6;'
			. 'margin-bottom:10px;}'
			. '.avi-review-read-more{color:#7c3aed;font-size:12px;cursor:pointer;'
			. 'background:none;border:none;padding:0;text-decoration:underline;}'
			. '.avi-review-reply{background:#f5f3ff;border-left:3px solid #7c3aed;'
			. 'border-radius:0 6px 6px 0;padding:10px 12px;margin-top:8px;'
			. 'font-size:12px;color:#374151;}'
			. '.avi-review-reply-label{color:#7c3aed;font-size:11px;font-weight:600;'
			. 'margin-bottom:4px;}'
			. '.avi-review-reply-form{margin-top:10px;}'
			. '.avi-review-reply-textarea{border:1px solid #e2e8f0;border-radius:6px;'
			. 'font-size:12px;padding:8px;width:100%;min-height:80px;'
			. 'box-sizing:border-box;resize:vertical;outline:none;font-family:inherit;}'
			. '.avi-review-reply-textarea:focus{border-color:#7c3aed;}'
			. '.avi-review-reply-actions{display:flex;gap:8px;margin-top:6px;'
			. 'justify-content:flex-end;}'
			. '.avi-review-reply-cancel{background:#f1f5f9;border:none;border-radius:5px;'
			. 'color:#64748b;cursor:pointer;font-size:12px;padding:6px 12px;}'
			. '.avi-review-reply-submit{background:#7c3aed;border:none;border-radius:5px;'
			. 'color:#fff;cursor:pointer;font-size:12px;font-weight:600;padding:6px 14px;}'
			. '.avi-review-reply-btn{background:none;border:1px solid #7c3aed;'
			. 'border-radius:5px;color:#7c3aed;cursor:pointer;font-size:11px;'
			. 'font-weight:600;padding:5px 10px;margin-top:8px;}'
			. '.avi-review-reply-btn:hover{background:#f5f3ff;}'
			. '.avi-reviews-upsell{background:linear-gradient(135deg,#1e1b4b,#312e81);'
			. 'border-radius:10px;padding:12px 16px;margin-top:12px;opacity:.92;}'
			. '.avi-reviews-export{display:flex;gap:8px;margin-top:16px;}'
			. '.avi-reviews-export-btn{border:none;border-radius:6px;color:#fff;'
			. 'cursor:pointer;font-size:12px;font-weight:600;padding:8px 16px;flex:1;}'
			. '.avi-reviews-export-btn.csv{background:#16a34a;}'
			. '.avi-reviews-export-btn.pdf{background:#0f172a;}'
			. '.avi-review-badge{background:#dc2626;border-radius:10px;color:#fff;'
			. 'font-size:10px;font-weight:700;padding:1px 6px;margin-left:4px;'
			. 'vertical-align:middle;}'
			. '.avi-rv-toolbar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;'
			. 'margin-bottom:16px;}'
			. '.avi-rv-filter-btn{background:#fff;border:1px solid #e2e8f0;border-radius:20px;'
			. 'color:#64748b;cursor:pointer;font-size:11px;font-weight:500;padding:5px 12px;'
			. 'transition:all .15s;}'
			. '.avi-rv-filter-btn.active{background:#7c3aed;border-color:#7c3aed;color:#fff;}'
			. '.avi-rv-sort-sel{border:1px solid #e2e8f0;border-radius:20px;color:#64748b;'
			. 'font-size:11px;padding:5px 10px;background:#fff;outline:none;cursor:pointer;}'
			. '.avi-rv-per-page{border:1px solid #e2e8f0;border-radius:20px;color:#64748b;'
			. 'font-size:11px;padding:5px 10px;background:#fff;outline:none;cursor:pointer;'
			. 'margin-left:auto;}'
			. '.avi-rv-pagination{display:flex;align-items:center;gap:12px;'
			. 'justify-content:center;margin-top:16px;}'
			. '.avi-rv-page-btn{background:#fff;border:1px solid #e2e8f0;border-radius:6px;'
			. 'color:#475569;cursor:pointer;font-size:12px;padding:6px 14px;'
			. 'transition:all .15s;}'
			. '.avi-rv-page-btn:disabled{opacity:0.4;cursor:default;}'
			. '.avi-rv-page-btn:hover:not(:disabled){background:#f1f5f9;}'
			. '.avi-rv-page-info{color:#64748b;font-size:12px;}'
			. '.avi-rv-load-more{background:#0f172a;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;font-size:12px;font-weight:600;'
			. 'padding:10px 24px;width:100%;margin-top:8px;transition:opacity .15s;}'
			. '.avi-rv-load-more:hover{opacity:0.85;}'
			. '.avi-rv-count{color:#94a3b8;font-size:12px;margin-bottom:8px;}'
			. '.avi-rv-filter-bar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;align-items:center;}'
			. '.avi-rv-filter-sel{background:#fff;border:1px solid #e2e8f0;border-radius:8px;'
			. 'color:#475569;cursor:pointer;font-size:12px;font-weight:500;padding:6px 10px;appearance:auto;}'
			. '.avi-rv-filter-sel:focus{border-color:#6d28d9;outline:none;}'
			. '.avi-rv-table{width:100%;border-collapse:collapse;background:#fff;'
			. 'border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;font-size:13px;}'
			. '.avi-rv-table th{background:linear-gradient(135deg,#ede9fe 0%,#e0e7ff 100%);'
			. 'color:#5b21b6;font-size:11px;font-weight:600;padding:10px 12px;text-align:left;'
			. 'border-bottom:1px solid #c4b5fd;white-space:nowrap;}'
			. '.avi-rv-table th:not(:first-child){cursor:help;}'
			. '.avi-rv-flag-btn{background:#fff8f0;border:1px solid #fed7aa;border-radius:6px;'
			. 'color:#ea580c;cursor:pointer;font-size:11px;font-weight:600;padding:4px 8px;'
			. 'text-decoration:none;display:inline-flex;align-items:center;white-space:nowrap;margin-left:4px;}'
			. '.avi-rv-flag-btn:hover{background:#ffedd5;border-color:#fb923c;}'
			. '.avi-rv-table td{padding:10px 12px;border-bottom:1px solid #f1f5f9;'
			. 'vertical-align:middle;}'
			. '.avi-rv-table tr:last-child td{border-bottom:none;}'
			. '.avi-rv-table tr:hover td{background:#fafafa;}'
			. '.avi-rv-row-expanded td{background:#f5f3ff !important;}'
			. '.avi-rv-expand-row td{background:#f9f7ff;padding:12px 16px;'
			. 'border-bottom:1px solid #ede9fe;}'
			. '.avi-rv-avatar-sm{width:32px;height:32px;border-radius:50%;'
			. 'object-fit:cover;flex-shrink:0;}'
			. '.avi-rv-avatar-sm-initials{width:32px;height:32px;border-radius:50%;'
			. 'background:#7c3aed;color:#fff;display:flex;align-items:center;'
			. 'justify-content:center;font-size:11px;font-weight:700;}'
			. '.avi-rv-stars-sm{color:#f59e0b;font-size:12px;letter-spacing:1px;}'
			. '.avi-rv-snippet{color:#374151;max-width:320px;overflow:hidden;'
			. 'text-overflow:ellipsis;white-space:nowrap;}'
			. '.avi-rv-badge-replied{background:#dcfce7;color:#16a34a;'
			. 'border-radius:4px;font-size:10px;font-weight:700;padding:2px 6px;}'
			. '.avi-rv-badge-pending{background:#fef2f2;color:#dc2626;'
			. 'border-radius:4px;font-size:10px;font-weight:700;padding:2px 6px;}'
			. '.avi-rv-action-btn{background:none;border:1px solid #e2e8f0;'
			. 'border-radius:4px;color:#475569;cursor:pointer;font-size:11px;'
			. 'padding:4px 8px;margin-right:4px;transition:all .15s;}'
			. '.avi-rv-action-btn:hover{background:#f1f5f9;}'
			. '.avi-rv-action-btn.reply{border-color:#7c3aed;color:#7c3aed;}'
			. '.avi-rv-action-btn.reply:hover{background:#f5f3ff;}'
			. '.avi-rv-expand-content{color:#374151;font-size:13px;line-height:1.6;'
			. 'margin-bottom:10px;}'
			. '.avi-rv-expand-reply{background:#fff;border-left:3px solid #7c3aed;'
			. 'border-radius:0 6px 6px 0;padding:10px 12px;'
			. 'font-size:12px;color:#374151;margin-bottom:8px;}'
			. '.avi-rv-expand-reply-label{color:#7c3aed;font-size:11px;'
			. 'font-weight:600;margin-bottom:0;}'
			. '.avi-rv-expand-reply-head{display:flex;align-items:center;'
			. 'justify-content:space-between;gap:8px;margin-bottom:6px;flex-wrap:wrap;}'
			. '.avi-rv-reply-form{margin-top:8px;}'
			. '.avi-rv-reply-ta-wrap{position:relative;width:100%;}'
			. '.avi-rv-reply-ta{resize:none;width:100%;min-height:180px;height:180px;'
			. 'padding:10px 12px;border:1px solid #e2e8f0;border-radius:8px 8px 0 0;'
			. 'font-size:13px;line-height:1.8;color:#1e293b;font-family:inherit;'
			. 'box-sizing:border-box;white-space:pre-wrap;word-wrap:break-word;'
			. 'overflow-y:auto;}'
			. '.avi-rv-reply-ta:focus{outline:none;border-color:#6d28d9;'
			. 'box-shadow:0 0 0 3px rgba(109,40,217,.08);}'
			. '.avi-rv-reply-resize{display:flex;align-items:center;justify-content:center;'
			. 'width:100%;height:20px;background:#f8fafc;border:1px solid #e2e8f0;'
			. 'border-top:none;border-radius:0 0 8px 8px;cursor:ns-resize;'
			. 'color:#94a3b8;font-size:10px;user-select:none;}'
			. '.avi-rv-reply-resize:hover{background:#f1f5f9;color:#6d28d9;}'
			. '.avi-rv-reply-acts{display:flex;gap:8px;margin-top:6px;justify-content:flex-end;}'
			. '.avi-rv-reply-cancel{background:#f1f5f9;border:none;border-radius:5px;'
			. 'color:#64748b;cursor:pointer;font-size:12px;padding:6px 12px;}'
			. '.avi-rv-reply-submit{background:#7c3aed;border:none;border-radius:5px;'
			. 'color:#fff;cursor:pointer;font-size:12px;font-weight:600;padding:6px 14px;}'
			. '/* #SprintL2-reviews-ai */'
			. '.avi-rv-reply-acts-top{display:flex;gap:8px;margin-bottom:6px;align-items:center;flex-wrap:wrap;}'
			. '.avi-review-ai-btn{display:inline-flex;align-items:center;gap:6px;'
			. 'background:linear-gradient(135deg,#6d28d9,#4f46e5);color:#fff;'
			. 'border:none;border-radius:8px;padding:7px 14px;font-size:12px;'
			. 'font-weight:600;cursor:pointer;transition:opacity .15s;}'
			. '.avi-review-ai-btn:hover{opacity:.9;}'
			. '.avi-review-ai-btn:disabled{opacity:.6;cursor:not-allowed;}'
			. '.avi-review-edit-btn{display:inline-flex;align-items:center;gap:6px;'
			. 'background:#f8fafc;color:#374151;border:1px solid #e2e8f0;'
			. 'border-radius:8px;padding:7px 14px;font-size:12px;font-weight:600;'
			. 'cursor:pointer;transition:background .15s;}'
			. '.avi-review-edit-btn:hover{background:#f1f5f9;border-color:#94a3b8;}'
			. '.avi-rv-expand-reply-btns{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}'
			. '.avi-toast{position:fixed;bottom:80px;left:50%;'
			. 'transform:translateX(-50%);background:#166534;color:#fff;'
			. 'padding:10px 20px;border-radius:8px;font-size:13px;'
			. 'font-weight:600;z-index:100020;box-shadow:0 4px 12px rgba(0,0,0,.2);'
			. 'transition:opacity .4s;}'
			. '.avi-toast--hide{opacity:0;}'
			. '.avi-toast--error{background:#dc2626;}'
			. '.avi-review-ai-regen{background:none;border:none;color:#6d28d9;'
			. 'font-size:11px;cursor:pointer;padding:2px 6px;text-decoration:underline;}'
			. '.avi-rv-load-more-info{color:#94a3b8;font-size:11px;text-align:center;'
			. 'margin-top:8px;}'
			. '.avi-posts-panel{position:absolute;inset:0;background:#f8fafc;'
			. 'z-index:10;display:none;overflow-y:auto;padding:24px;padding-bottom:60px;}'
			. '.avi-posts-header{background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);'
			. 'border-radius:12px;padding:16px 18px;margin:16px 16px 12px;'
			. 'color:#fff;position:relative;overflow:hidden;font-family:inherit;}'
			. '.avi-posts-header::before{content:"";position:absolute;'
			. 'top:-20px;right:-20px;width:100px;height:100px;'
			. 'background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-header-info-btn{background:none;border:none;cursor:pointer;font-size:14px;'
			. 'padding:0 0 0 4px;line-height:1;vertical-align:middle;opacity:.85;}'
			. '.avi-header-info-btn:hover{opacity:1;}'
			. '.avi-posts-inner{max-width:900px;margin:0 auto;}'
			. '.avi-posts-topbar{display:flex;align-items:center;gap:12px;'
			. 'margin-bottom:16px;flex-wrap:wrap;}'
			. '.avi-posts-new-btn{background:#7c3aed;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;font-size:13px;font-weight:600;'
			. 'padding:9px 18px;display:flex;align-items:center;gap:6px;}'
			. '.avi-posts-new-btn:hover{background:#6d28d9;}'
			. '.avi-posts-filter-btn{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:20px;color:#64748b;cursor:pointer;'
			. 'font-size:11px;font-weight:500;padding:5px 12px;transition:all .15s;}'
			. '.avi-posts-filter-btn.active{background:#7c3aed;border-color:#7c3aed;color:#fff;}'
			. '.avi-posts-table{width:100%;border-collapse:collapse;background:#fff;'
			. 'border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;font-size:13px;}'
			. '.avi-posts-table th{background:#f8fafc;color:#475569;font-size:11px;'
			. 'font-weight:600;padding:10px 12px;text-align:left;'
			. 'border-bottom:1px solid #e2e8f0;white-space:nowrap;}'
			. '.avi-posts-table td{padding:10px 12px;border-bottom:1px solid #f1f5f9;'
			. 'vertical-align:middle;}'
			. '.avi-posts-table tr:last-child td{border-bottom:none;}'
			. '.avi-posts-table tr:hover td{background:#fafafa;}'
			. '.avi-post-type-badge{border-radius:4px;font-size:10px;font-weight:700;'
			. 'padding:2px 7px;white-space:nowrap;}'
			. '.avi-post-type-update{background:#dbeafe;color:#1d4ed8;}'
			. '.avi-post-type-offer{background:#dcfce7;color:#15803d;}'
			. '.avi-post-type-event{background:#fef3c7;color:#b45309;}'
			. '.avi-post-status-badge{border-radius:4px;font-size:10px;font-weight:700;'
			. 'padding:2px 7px;white-space:nowrap;}'
			. '.avi-post-status-published{background:#dcfce7;color:#15803d;}'
			. '.avi-post-status-scheduled{background:#e0f2fe;color:#0369a1;}'
			. '.avi-post-status-pending{background:#fef3c7;color:#b45309;}'
			. '.avi-post-status-failed{background:#fef2f2;color:#dc2626;}'
			. '.avi-post-status-draft{background:#f1f5f9;color:#64748b;}'
			. '.avi-posts-snippet{color:#374151;max-width:280px;overflow:hidden;'
			. 'text-overflow:ellipsis;white-space:nowrap;}'
			. '.avi-posts-action-btn{background:none;border:1px solid #e2e8f0;'
			. 'border-radius:4px;color:#475569;cursor:pointer;font-size:11px;'
			. 'padding:4px 8px;transition:all .15s;}'
			. '.avi-posts-action-btn:hover{background:#f1f5f9;}'
			. '.avi-posts-empty{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:10px;padding:48px;text-align:center;color:#94a3b8;}'
			. '.avi-posts-upsell{background:linear-gradient(135deg,#1e1b4b,#312e81);'
			. 'border-radius:10px;padding:12px 16px;margin-top:12px;opacity:.92;}'
			. '.avi-posts-export{display:flex;gap:8px;margin-top:16px;}'
			. '.avi-posts-export-btn{border:none;border-radius:6px;color:#fff;'
			. 'cursor:pointer;font-size:12px;font-weight:600;padding:8px 16px;flex:1;}'
			. '.avi-posts-export-btn.csv{background:#16a34a;}'
			. '.avi-posts-export-btn.pdf{background:#0f172a;}'
			. '.avi-posts-count{color:#94a3b8;font-size:12px;margin-bottom:8px;}'
			. '.avi-posts-create-overlay{position:fixed;inset:0;background:rgba(0,0,0,.3);'
			. 'z-index:2147483640;display:none;}'
			. '.avi-posts-create-overlay.open{display:block;}'
			. '.avi-posts-create-panel{position:fixed;top:0;right:0;width:420px;'
			. 'height:100vh;background:#fff;border-left:1px solid #e2e8f0;'
			. 'box-shadow:-4px 0 24px rgba(0,0,0,.15);z-index:2147483641;'
			. 'display:flex;flex-direction:column;'
			. 'transform:translateX(100%);transition:transform .25s ease;}'
			. '.avi-posts-create-panel.open{transform:translateX(0);}'
			. '.avi-posts-create-header{background:#0f172a;color:#fff;'
			. 'display:flex;align-items:center;justify-content:space-between;'
			. 'padding:16px 20px;flex-shrink:0;}'
			. '.avi-posts-create-header h3{font-size:15px;font-weight:600;margin:0;}'
			. '.avi-posts-create-close{background:none;border:none;color:rgba(255,255,255,.6);'
			. 'cursor:pointer;font-size:22px;line-height:1;padding:2px 6px;}'
			. '.avi-posts-create-body{flex:1;overflow-y:auto;padding:20px;}'
			. '.avi-posts-create-footer{border-top:1px solid #e2e8f0;padding:16px 20px;'
			. 'flex-shrink:0;display:flex;gap:10px;}'
			. '.avi-posts-field{margin-bottom:16px;}'
			. '.avi-posts-field label{display:block;font-size:12px;font-weight:600;'
			. 'color:#374151;margin-bottom:6px;}'
			. '.avi-posts-field select,.avi-posts-field textarea,'
			. '.avi-posts-field input[type="datetime-local"]{'
			. 'border:1px solid #e2e8f0;border-radius:6px;font-size:13px;'
			. 'padding:8px 12px;width:100%;box-sizing:border-box;'
			. 'outline:none;font-family:inherit;background:#fff;}'
			. '.avi-posts-field select:focus,.avi-posts-field textarea:focus,'
			. '.avi-posts-field input:focus{border-color:#7c3aed;}'
			. '.avi-posts-field textarea{min-height:120px;resize:vertical;}'
			. '.avi-posts-char-count{color:#94a3b8;font-size:11px;text-align:right;'
			. 'margin-top:4px;}'
			. '.avi-posts-char-count.warn{color:#ea580c;}'
			. '.avi-posts-char-count.over{color:#dc2626;}'
			. '.avi-posts-schedule-type{display:flex;gap:10px;margin-bottom:16px;}'
			. '.avi-posts-schedule-opt{flex:1;border:2px solid #e2e8f0;border-radius:8px;'
			. 'cursor:pointer;padding:12px;text-align:center;transition:all .15s;'
			. 'background:#fff;}'
			. '.avi-posts-schedule-opt.selected{border-color:#7c3aed;background:#f5f3ff;}'
			. '.avi-posts-schedule-opt-title{font-size:13px;font-weight:600;color:#1e293b;}'
			. '.avi-posts-schedule-opt-sub{font-size:11px;color:#64748b;margin-top:2px;}'
			. '.avi-posts-schedule-opt-sub.credit{color:#7c3aed;font-weight:600;}'
			. '.avi-posts-event-fields{display:none;}'
			. '.avi-posts-event-fields.show{display:block;}'
			. '.avi-posts-submit-btn{background:#7c3aed;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;flex:1;font-size:13px;font-weight:600;'
			. 'padding:10px;transition:opacity .15s;}'
			. '.avi-posts-submit-btn:hover{opacity:0.85;}'
			. '.avi-posts-submit-btn:disabled{opacity:0.5;cursor:default;}'
			. '.avi-posts-cancel-btn{background:#f1f5f9;border:none;border-radius:6px;'
			. 'color:#475569;cursor:pointer;font-size:13px;padding:10px 20px;}'
			. '.avi-posts-credit-info{background:#f5f3ff;border:1px solid #ede9fe;'
			. 'border-radius:6px;padding:10px 14px;font-size:12px;color:#7c3aed;'
			. 'margin-bottom:12px;display:none;}'
			. '.avi-posts-credit-info.show{display:block;}'
			. '.avi-posts-photo-zone{border:2px dashed #e2e8f0;border-radius:8px;'
			. 'padding:16px;text-align:center;cursor:pointer;transition:all .15s;'
			. 'margin-bottom:8px;background:#fafafa;}'
			. '.avi-posts-photo-zone:hover{border-color:#7c3aed;background:#f5f3ff;}'
			. '.avi-posts-photo-zone.has-photo{border-color:#7c3aed;border-style:solid;}'
			. '.avi-posts-photo-preview{max-width:100%;max-height:120px;'
			. 'border-radius:6px;margin-top:8px;object-fit:cover;}'
			. '.avi-posts-photo-btns{display:flex;gap:8px;margin-top:8px;}'
			. '.avi-posts-photo-btn{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:5px;color:#475569;cursor:pointer;font-size:11px;'
			. 'font-weight:500;padding:5px 10px;flex:1;transition:all .15s;}'
			. '.avi-posts-photo-btn:hover{border-color:#7c3aed;color:#7c3aed;}'
			. '.avi-posts-photo-btn.from-gallery{border-color:#a78bfa;color:#7c3aed;'
			. 'background:#f5f3ff;}'
			. '.avi-posts-photo-info{color:#94a3b8;font-size:11px;margin-top:4px;}'
			. '.avi-hub-logo-upload{display:flex;align-items:center;gap:10px;margin:8px 0;}'
			. '.avi-hub-logo-upload-btn{background:#f1f5f9;border:1px solid #e2e8f0;'
			. 'border-radius:6px;color:#475569;cursor:pointer;font-size:12px;padding:7px 14px;}'
			. '.avi-hub-logo-upload-btn:hover{border-color:#7c3aed;color:#7c3aed;}'
			. '.avi-hub-logo-preview{height:40px;border-radius:4px;object-fit:contain;'
			. 'border:1px solid #e2e8f0;padding:2px;display:none;}'
			. '.avi-hub-tier-block{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:20px;margin-bottom:16px;}'
			. '.avi-hub-tier-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;}'
			. '.avi-hub-tier-badge{background:#f5f3ff;color:#7c3aed;border:1px solid #ddd6fe;border-radius:20px;padding:4px 14px;font-size:12px;font-weight:700;letter-spacing:.3px;}'
			. '.avi-hub-tier-info{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px 14px;margin-bottom:14px;font-size:12px;color:#475569;line-height:1.6;}'
			. '.avi-hub-tier-info strong{color:#1e293b;}'
			. '.avi-hub-gauge-wrap{margin-bottom:14px;}'
			. '.avi-hub-gauge-label{font-size:12px;color:#64748b;margin-bottom:6px;}'
			. '.avi-hub-gauge-label strong{color:#1e293b;font-weight:700;}'
			. '.avi-hub-gauge-bar{background:#f1f5f9;border-radius:99px;height:8px;overflow:hidden;}'
			. '.avi-hub-gauge-fill{height:100%;border-radius:99px;transition:width .4s ease;}'
			. '.avi-hub-tier-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;}'
			. '.avi-hub-tier-btn{border:none;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600;padding:8px 16px;transition:opacity .2s;}'
			. '.avi-hub-tier-up{background:#7c3aed;color:#fff;}'
			. '.avi-hub-tier-up:hover{opacity:.88;}'
			. '.avi-hub-tier-down{background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;}'
			. '.avi-hub-tier-down:hover{border-color:#7c3aed;color:#7c3aed;}'
			. '.avi-hub-tier-success{position:fixed;bottom:24px;right:24px;background:#059669;color:#fff;border-radius:8px;padding:12px 20px;font-size:13px;font-weight:600;z-index:99999;box-shadow:0 4px 12px rgba(0,0,0,.15);}'
			. '.avi-photos-panel{position:absolute;inset:0;background:#f8fafc;'
			. 'z-index:10;display:none;overflow-y:auto;padding:24px;padding-bottom:60px;}'

			. '.avi-citations-panel{position:absolute;inset:0;background:#f8fafc;z-index:10;display:none;overflow-y:auto;padding:24px;padding-bottom:80px;}'
			. '.avi-cit-topbar{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;background:#fff;border-bottom:1px solid #e2e8f0;position:sticky;top:0;z-index:2;}'
			. '.avi-cit-topbar-title{font-size:15px;font-weight:700;color:#1e293b;margin:0;}'
			. '.avi-cit-close{background:none;border:none;font-size:20px;cursor:pointer;color:#64748b;padding:4px 8px;border-radius:6px;line-height:1;}'
			. '.avi-cit-close:hover{background:#e2e8f0;}'
			. '.avi-cit-body{padding:16px 20px;}'
			. '.avi-cit-info-banner{background:#eff6ff;border:1px solid #bfdbfe;border-radius:10px;padding:12px 14px;margin-bottom:16px;font-size:12px;color:#1e40af;line-height:1.5;display:flex;gap:10px;align-items:flex-start;}'
			. '.avi-cit-info-banner-text{flex:1;}'
			. '.avi-cit-info-close{background:none;border:none;color:#93c5fd;cursor:pointer;font-size:16px;padding:0;line-height:1;flex-shrink:0;}'
			. '.avi-cit-progress{background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:12px 16px;margin-bottom:16px;display:flex;align-items:center;gap:12px;}'
			. '.avi-cit-progress-label{font-size:13px;font-weight:600;color:#1e293b;white-space:nowrap;min-width:80px;}'
			. '.avi-cit-progress-bar-wrap{flex:1;height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden;}'
			. '.avi-cit-progress-bar{height:100%;background:#22c55e;border-radius:3px;transition:width .4s;}'
			. '.avi-cit-section-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:#94a3b8;margin:16px 0 8px;}'
			. '.avi-cit-item{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:10px 14px;margin-bottom:6px;display:flex;align-items:center;gap:10px;transition:border-color .15s;}'
			. '.avi-cit-item:hover{border-color:#cbd5e1;}'
			. '.avi-cit-item--done{border-color:#22c55e;background:#f0fdf4;}'
			. '.avi-cit-item--already{border-color:#3b82f6;background:#eff6ff;}'
			. '.avi-cit-badge{font-size:14px;flex-shrink:0;}'
			. '.avi-cit-name{flex:1;font-size:13px;font-weight:500;color:#1e293b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}'
			. '.avi-cit-name a{color:#3b82f6;text-decoration:none;}'
			. '.avi-cit-name a:hover{text-decoration:underline;}'
			. '.avi-cit-actions{display:flex;gap:6px;flex-shrink:0;align-items:center;}'
			. '.avi-cit-btn{font-size:11px;padding:4px 10px;border-radius:5px;border:1px solid #e2e8f0;background:#f8fafc;color:#475569;cursor:pointer;white-space:nowrap;transition:all .15s;font-weight:500;}'
			. '.avi-cit-btn:hover{background:#e2e8f0;}'
			. '.avi-cit-btn--done{background:#22c55e;color:#fff;border-color:#22c55e;}'
			. '.avi-cit-btn--already{background:#3b82f6;color:#fff;border-color:#3b82f6;}'
			. '.avi-cit-btn--remove{background:none;border:none;color:#cbd5e1;cursor:pointer;font-size:14px;padding:2px 4px;line-height:1;}'
			. '.avi-cit-btn--remove:hover{color:#ef4444;}'
			. '.avi-cit-url-row{display:flex;gap:6px;align-items:center;margin-top:6px;padding-top:6px;border-top:1px solid #e2e8f0;}'
			. '.avi-cit-url-input{flex:1;font-size:11px;padding:5px 8px;border:1px solid #e2e8f0;border-radius:5px;outline:none;color:#475569;}'
			. '.avi-cit-url-input:focus{border-color:#3b82f6;}'
			. '.avi-cit-url-save{font-size:11px;padding:5px 10px;background:#3b82f6;color:#fff;border:none;border-radius:5px;cursor:pointer;white-space:nowrap;}'
			. '.avi-cit-tooltip{font-size:10px;color:#94a3b8;margin-top:4px;font-style:italic;}'
			. '.avi-cit-done-section-hdr{display:flex;align-items:center;justify-content:space-between;cursor:pointer;margin:16px 0 8px;}'
			. '.avi-cit-done-label{font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:#22c55e;}'
			. '.avi-cit-done-toggle{font-size:11px;color:#94a3b8;background:none;border:none;cursor:pointer;}'
			. '.avi-cit-add-row{display:flex;gap:8px;align-items:center;margin-top:12px;padding:10px 14px;background:#fff;border:1px dashed #cbd5e1;border-radius:8px;}'
			. '.avi-cit-add-input{flex:1;font-size:12px;padding:6px 10px;border:1px solid #e2e8f0;border-radius:6px;outline:none;}'
			. '.avi-cit-add-input:focus{border-color:#3b82f6;}'
			. '.avi-cit-add-btn{font-size:12px;padding:6px 14px;background:#7c3aed;color:#fff;border:none;border-radius:6px;cursor:pointer;white-space:nowrap;font-weight:500;}'
			. '.avi-cit-add-btn:hover{background:#6d28d9;}'
			. '.avi-photos-inner{max-width:960px;margin:0 auto;}'
			. '.avi-photos-header{background:linear-gradient(135deg,#6d28d9 0%,#4f46e5 100%);'
			. 'border-radius:12px;padding:16px 18px;margin:0 0 16px;color:#fff;'
			. 'position:relative;overflow:hidden;font-family:inherit;}'
			. '.avi-photos-header::before{content:"";position:absolute;'
			. 'top:-20px;right:-20px;width:100px;height:100px;'
			. 'background:rgba(255,255,255,.08);border-radius:50%;}'
			. '.avi-photos-topbar{display:flex;align-items:center;gap:10px;'
			. 'margin-bottom:16px;flex-wrap:wrap;}'
			. '.avi-photos-upload-btn{background:#7c3aed;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;font-size:13px;font-weight:600;'
			. 'padding:9px 18px;display:flex;align-items:center;gap:6px;}'
			. '.avi-photos-upload-btn:hover{background:#6d28d9;}'
			. '.avi-photos-sync-btn{background:#0f172a;border:none;border-radius:6px;'
			. 'color:#fff;cursor:pointer;font-size:12px;font-weight:500;'
			. 'padding:9px 14px;}'
			. '.avi-photos-sync-btn:hover{opacity:0.85;}'
			. '.avi-photos-filter-btn{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:20px;color:#64748b;cursor:pointer;'
			. 'font-size:11px;font-weight:500;padding:5px 12px;transition:all .15s;}'
			. '.avi-photos-filter-btn.active{background:#7c3aed;border-color:#7c3aed;color:#fff;}'
			. '.avi-photos-cols-sel{border:1px solid #e2e8f0;border-radius:20px;'
			. 'color:#64748b;font-size:11px;padding:5px 10px;background:#fff;'
			. 'outline:none;cursor:pointer;margin-left:auto;}'
			. '.avi-photos-grid{display:grid;gap:12px;margin-bottom:16px;}'
			. '.avi-photos-grid.cols-1{grid-template-columns:1fr;}'
			. '.avi-photos-grid.cols-2{grid-template-columns:repeat(2,1fr);}'
			. '.avi-photos-grid.cols-3{grid-template-columns:repeat(3,1fr);}'
			. '.avi-photos-grid.cols-4{grid-template-columns:repeat(4,1fr);}'
			. '.avi-photos-grid.cols-5{grid-template-columns:repeat(5,1fr);}'
			. '.avi-photos-grid.cols-6{grid-template-columns:repeat(6,1fr);}'
			. '.avi-photo-card{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:8px;overflow:hidden;position:relative;}'
			. '.avi-photo-img-wrap{position:relative;overflow:hidden;}'
			. '.avi-photo-img{width:100%;aspect-ratio:4/3;object-fit:cover;'
			. 'display:block;background:#f1f5f9;}'
			. '.avi-photo-img-placeholder{width:100%;aspect-ratio:4/3;'
			. 'background:linear-gradient(135deg,#f1f5f9,#e2e8f0);'
			. 'display:flex;align-items:center;justify-content:center;'
			. 'color:#94a3b8;font-size:32px;}'
			. '.avi-photo-info{padding:8px 10px;}'
			. '.avi-photo-status{font-size:10px;font-weight:700;padding:2px 6px;'
			. 'border-radius:4px;display:inline-block;margin-bottom:4px;}'
			. '.avi-photo-status-published{background:#dcfce7;color:#15803d;}'
			. '.avi-photo-status-in_stock{background:#dbeafe;color:#1d4ed8;}'
			. '.avi-photo-status-scheduled{background:#e0f2fe;color:#0369a1;}'
			. '.avi-photo-date{color:#94a3b8;font-size:10px;}'
			. '.avi-photo-actions{position:absolute;inset:0;background:rgba(0,0,0,.5);'
			. 'display:flex;align-items:center;justify-content:center;'
			. 'gap:8px;opacity:0;transition:opacity .2s;pointer-events:none;}'
			. '.avi-photo-img-wrap:hover .avi-photo-actions{opacity:1;pointer-events:auto;}'
			. '.avi-photo-action-btn{background:#fff;border:none;border-radius:6px;'
			. 'color:#1e293b;cursor:pointer;font-size:11px;font-weight:600;'
			. 'padding:6px 10px;transition:background .15s;}'
			. '.avi-photo-action-btn:hover{background:#f1f5f9;}'
			. '.avi-photo-action-btn.publish{background:#7c3aed;color:#fff;}'
			. '.avi-photo-action-btn.publish:hover{background:#6d28d9;}'
			. '.avi-photo-card-btn--danger-gbp{background:#fff0f0;border:1px solid #fca5a5;border-radius:6px;color:#dc2626;cursor:pointer;font-size:11px;font-weight:600;padding:5px 10px;}'
			. '.avi-photo-card-btn--danger-gbp:hover:not(:disabled){background:#fee2e2;}'
			. '.avi-photo-bulk-cb{position:absolute;top:8px;left:8px;width:16px;height:16px;cursor:pointer;z-index:10;accent-color:#6d28d9;}'
			. '.avi-photos-bulk-bar{display:none;align-items:center;gap:10px;background:#1e1b4b;border-radius:10px;padding:10px 16px;margin-bottom:12px;flex-wrap:wrap;}'
			. '.avi-bulk-count{color:#fff;font-size:12px;font-weight:700;flex-shrink:0;}'
			. '.avi-bulk-btn{border:none;border-radius:6px;cursor:pointer;font-size:11px;font-weight:600;padding:6px 12px;background:#6d28d9;color:#fff;}'
			. '.avi-bulk-btn--danger{background:#dc2626;}'
			. '.avi-bulk-btn--ghost{background:rgba(255,255,255,.15);color:#fff;}'
			. '.avi-bulk-btn:hover{opacity:.85;}'
			. '.avi-bulk-gbp-note{color:rgba(255,255,255,.7);font-size:10px;flex:1;min-width:200px;}'
			. '.avi-photos-empty{background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:10px;padding:48px;text-align:center;color:#94a3b8;}'
			. '.avi-photos-upsell{background:linear-gradient(135deg,#1e1b4b,#312e81);'
			. 'border-radius:10px;padding:12px 16px;margin-top:12px;opacity:.92;}'
			. '.avi-photos-export{display:flex;gap:8px;margin-top:8px;}'
			. '.avi-photos-export-btn{border:none;border-radius:6px;color:#fff;'
			. 'cursor:pointer;font-size:12px;font-weight:600;padding:8px 16px;flex:1;}'
			. '.avi-photos-export-btn.csv{background:#16a34a;}'
			. '.avi-photos-export-btn.pdf{background:#0f172a;}'
			. '.avi-photos-count{color:#94a3b8;font-size:12px;margin-bottom:12px;}'
			. '.avi-photos-upload-drop{border:2px dashed #e2e8f0;border-radius:10px;'
			. 'padding:32px;text-align:center;margin-bottom:16px;'
			. 'background:#fff;cursor:pointer;transition:all .15s;display:none;}'
			. '.avi-photos-upload-drop.open{display:block;}'
			. '.avi-photos-upload-drop:hover{border-color:#7c3aed;background:#f5f3ff;}'
			. '.avi-photos-upload-drop.dragover{border-color:#7c3aed;background:#f5f3ff;}'
			. '.avi-photo-video{width:100%;aspect-ratio:4/3;object-fit:cover;'
			. 'display:block;background:#0f172a;}'
			. '.avi-photo-video-badge{position:absolute;top:8px;left:8px;'
			. 'background:rgba(0,0,0,.7);border-radius:4px;color:#fff;'
			. 'font-size:10px;font-weight:700;padding:2px 6px;}'
			. '/* #SprintL2-photos-fix — badge statut GBP */'
			. '.avi-photo-gbp-badge{position:absolute;top:8px;right:8px;'
			. 'border-radius:4px;font-size:10px;font-weight:700;padding:2px 7px;'
			. 'display:flex;align-items:center;gap:3px;box-shadow:0 1px 3px rgba(0,0,0,.2);}'
			. '.avi-photo-gbp-badge--pub{background:#dcfce7;color:#15803d;}'
			. '.avi-photo-gbp-badge--unpub{background:#f1f5f9;color:#64748b;}'
			. '/* #SprintL2-photos-filter-download — bouton téléchargement (overlay actions) */'
			. '.avi-photo-download-btn{display:inline-flex;align-items:center;justify-content:center;'
			. 'text-decoration:none;}'
			. '/* #SprintL2-photos-ux — barre outils 2 lignes */'
			. '.avi-photos-toolbar{display:flex;flex-direction:column;gap:8px;margin-bottom:16px;}'
			. '.avi-photos-toolbar-row1{display:flex;align-items:center;gap:8px;}'
			. '.avi-photos-toolbar-row2{display:flex;align-items:center;gap:6px;flex-wrap:wrap;}'
			. '.avi-photos-toolbar-sep{width:1px;height:20px;background:#e2e8f0;margin:0 4px;}'
			. '.avi-photos-cols-select{margin-left:auto;}'
			. '/* #SprintL2-photos-ux — redesign card */'
			. '.avi-photo-card-img{position:relative;aspect-ratio:4/3;overflow:hidden;}'
			. '.avi-photo-card-img img{width:100%;height:100%;object-fit:cover;}'
			. '.avi-photo-card-body{padding:10px 12px;display:flex;flex-direction:column;gap:6px;}'
			. '.avi-photo-card-name{font-size:12px;font-weight:600;color:#1e293b;'
			. 'display:flex;align-items:center;gap:6px;min-width:0;}'
			. '.avi-photo-card-name .avi-photo-name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1;}'
			. '.avi-photo-card-meta{display:flex;align-items:center;gap:6px;font-size:11px;color:#64748b;}'
			. '.avi-photo-card-actions{display:flex;gap:6px;margin-top:4px;}'
			. '.avi-photo-card-btn{flex:1;padding:6px;border-radius:6px;border:1px solid #e2e8f0;'
			. 'background:#f8fafc;font-size:11px;cursor:pointer;text-align:center;'
			. 'color:#475569;transition:background .15s;}'
			. '.avi-photo-card-btn:hover{background:#e2e8f0;}'
			. '.avi-photo-card-btn--danger{border-color:#fecaca;color:#dc2626;background:#fff;}'
			. '.avi-photo-card-btn--danger:hover{background:#fef2f2;}'
			. '.avi-photo-meta{padding:8px 10px;border-top:1px solid #f1f5f9;}'
			. '.avi-photo-meta-row{display:flex;align-items:center;gap:6px;margin-bottom:4px;}'
			. '.avi-photo-cat-badge{background:#dbeafe;color:#1d4ed8;border-radius:4px;'
			. 'font-size:9px;font-weight:700;padding:1px 5px;white-space:nowrap;}'
			. '.avi-photo-name{color:#374151;font-size:11px;font-weight:500;'
			. 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:140px;'
			. 'cursor:pointer;border-bottom:1px dashed #d1d5db;}'
			. '.avi-photo-name:hover{color:#7c3aed;border-bottom-color:#7c3aed;}'
			. '.avi-photo-date-pub{color:#94a3b8;font-size:10px;}'
			. '.avi-photo-edit-form{padding:8px 10px;border-top:1px solid #f1f5f9;'
			. 'display:none;background:#f9fafb;}'
			. '.avi-photo-edit-form.open{display:block;}'
			. '.avi-photo-edit-input{border:1px solid #e2e8f0;border-radius:5px;'
			. 'font-size:11px;padding:5px 8px;width:100%;box-sizing:border-box;'
			. 'outline:none;margin-bottom:6px;}'
			. '.avi-photo-edit-input:focus{border-color:#7c3aed;}'
			. '.avi-photo-edit-sel{border:1px solid #e2e8f0;border-radius:5px;'
			. 'font-size:11px;padding:5px 8px;width:100%;box-sizing:border-box;'
			. 'outline:none;background:#fff;margin-bottom:6px;}'
			. '.avi-photo-edit-acts{display:flex;gap:6px;}'
			. '.avi-photo-edit-save{background:#7c3aed;border:none;border-radius:4px;'
			. 'color:#fff;cursor:pointer;font-size:11px;font-weight:600;padding:5px 10px;flex:1;}'
			. '.avi-photo-edit-cancel{background:#f1f5f9;border:none;border-radius:4px;'
			. 'color:#64748b;cursor:pointer;font-size:11px;padding:5px 8px;}'
			. '.avi-photo-cat-more-btn{background:none;border:none;color:#7c3aed;'
			. 'cursor:pointer;font-size:10px;padding:0;text-decoration:underline;}'
			. '.avi-photo-copy-btn{background:none;border:none;color:#94a3b8;'
			. 'cursor:pointer;font-size:10px;padding:2px 4px;}'
			. '.avi-photo-copy-btn:hover{color:#7c3aed;}'
			. '/* #SprintL2-responsive-layout */'
			. '@media(max-width:900px){'
			. 'html body #avision-dashboard-root .avi-heatmap-drawer-grid{'
			. 'grid-template-columns:1fr !important;grid-template-rows:auto !important;'
			. 'overflow-y:auto !important;overflow-x:hidden !important;}'
			. 'html body #avision-dashboard-root .avi-heatmap-panel{'
			. 'min-width:0 !important;width:100% !important;}'
			. '}'
			. '@media(max-width:600px){'
			. 'html body #avision-dashboard-root .avi-heatmap-closed-meta span:last-child{'
			. 'display:none !important;}'
			. '.avi-ehd-widgets{display:grid !important;grid-template-columns:repeat(2,1fr) !important;}'
			. '.avi-ehd-nap-items{flex-wrap:wrap !important;}'
			. '}'
			. ( ! empty( $embed_logo_url )
				? '.avi-heatmap-icon{display:none !important;}'
				. '.avi-heatmap-closed-main::before{content:"";display:block;width:48px;height:48px;'
				. 'background:url("' . esc_url( $embed_logo_url ) . '") center/contain no-repeat;'
				. 'border-radius:8px;flex-shrink:0;}'
				: '' )
			. '.avi-heatmap-modal-advice-placeholder{display:none!important;}'
			. '.btn-upgrade{background:linear-gradient(135deg,#7c3aed,#6d28d9);color:#fff;border:none;padding:0.5rem 1.2rem;border-radius:8px;font-weight:700;font-size:0.9rem;cursor:pointer;transition:transform .15s,box-shadow .15s;box-shadow:0 2px 8px rgba(124,58,237,.25);}'
			. '.btn-upgrade:hover{transform:scale(1.04);box-shadow:0 4px 14px rgba(124,58,237,.35);}'
			. '.btn-upgrade:disabled{opacity:.55;cursor:not-allowed;filter:grayscale(.15);transform:none;}'
			. '</style>'
			. '</head>'
			. '<body class="avi-embed-body theme-' . esc_attr( $theme ) . '">'
			. '<div class="avi-embed-loading" id="aviEmbedLoader">'
			. '<div class="avi-embed-spinner"></div>'
			. '</div>'
			. '<div id="avision-dashboard-root" data-lang="' . esc_attr( $lang ) . '"'
			. ' data-language="' . esc_attr( $lang ) . '"'
			. ' style="width:100%;height:100%;overflow:hidden;">'
			. '<div class="avi-embed-wrap">'
			. $heatmap_html
			. '</div>'
			. '</div>'
			. '<script src="' . esc_url( $leaflet_js ) . '"></script>'
			. '<script>'
			. 'window.aviEmbedToken=' . wp_json_encode( $embed_token ) . ';'
			. 'window.aviEmbedNonce=' . wp_json_encode( wp_create_nonce( 'wp_rest' ) ) . ';'
			. 'window.aviEmbedRestUrl=' . wp_json_encode( rest_url( 'avision/v1/' ) ) . ';'
			. 'window.aviEmbedProfileId=' . (int) $profile_id . ';'
			. 'window.aviEmbedLogoUrl=' . wp_json_encode( $embed_logo_url ) . ';'
			. 'window.aviEmbedWhiteLabel=' . wp_json_encode( $embed_white_label ) . ';'
			. 'window.aviEmbedKeyType=' . wp_json_encode( $key_type ) . ';'
			. 'window.aviEmbedAgencyId=' . (int) $agency_id . ';'
			. 'window.aviEmbedAgencyMasterId=' . (int) $agency_master_profile_id . ';'
			. 'window.aviEmbedAgencyProfiles=' . wp_json_encode( $agency_profiles ) . ';'
			. 'window.aviEmbedAgencyCredits=' . wp_json_encode( $agency_credits ) . ';'
			. 'window.aviEmbedAgencyTier=' . (int) $agency_tier . ';'
			. 'window.aviEmbedAgencyMaxListings=' . (int) $agency_max_listings . ';'
			. 'window.aviEmbedAgencyUsedListings=' . (int) $agency_used_listings . ';'
			. 'window.aviEmbedAgencyPrices={"t1":' . wp_json_encode( $agency_price_t1 ) . ',"t2":' . wp_json_encode( $agency_price_t2 ) . ',"t3":' . wp_json_encode( $agency_price_t3 ) . '};'
			. 'window.aviEmbedSoloCredits=' . wp_json_encode( $solo_credits ) . ';'
			. 'window.aviEmbedPurchaseSuccess='
			. ( $purchase_success ? 'true' : 'false' ) . ';'
			. 'window.aviEmbedKeyId=' . wp_json_encode( (string) $key_id ) . ';'
			. 'window.aviEmbedSwitchUrl=' . wp_json_encode( rest_url( 'avision/v1/embed/switch-profile' ) ) . ';'
			. 'window.aviEmbedTheme=' . wp_json_encode( (string) $theme ) . ';'
			. 'window.aviEmbedSoloPlaceId=' . wp_json_encode( $solo_place_id ) . ';'
			. 'window.aviEmbedSoloLocationName=' . wp_json_encode( $solo_location_name ) . ';'
			. 'window.aviEmbedSoloBusinessName=' . wp_json_encode( $solo_business ) . ';'
			. 'window.aviEmbedSoloCity=' . wp_json_encode( $solo_city ) . ';'
			. 'window.aviEmbedScoreData=' . wp_json_encode( $score_data ) . ';'
			. 'window.aviEmbedReviewsData=' . wp_json_encode( $reviews_data ) . ';'
			. 'window._aviReviewsNextPageToken=' . wp_json_encode( $reviews_next_page_token ) . ';'
			. 'window._aviReviewsLoadMoreCooldown=false;'
			. 'window.aviEmbedCitationsData=' . wp_json_encode(
				array(
					'citations' => array(),
					'score'     => 0,
					'done'      => 0,
				)
			) . ';'
			. 'window.aviEmbedPostsData=' . wp_json_encode( $posts_data ) . ';'
			. 'window.aviEmbedPhotosData=' . wp_json_encode( $photos_data ) . ';'
			. 'window.aviEmbedUnansweredCount=' . (int) $unanswered_count . ';'
			. 'window.aviEmbedGbpConnected=' . ( $is_gbp_connected ? 'true' : 'false' ) . ';'
			. 'window.aviEmbedIsAdmin=' . ( $_avi_is_admin ? 'true' : 'false' ) . ';'
			. 'window.aviEmbedHasGoogleToken=' . ( $has_google_token ? 'true' : 'false' ) . ';'
			. 'window.aviEmbedConnectUrl=' . wp_json_encode( $embed_connect_url ) . ';'
			. 'window.aviEmbedIsHosted=' . ( ( $le_wp_auth || $le_is_hosted || $request->get_param( 'hosted' ) === '1' ) ? 'true' : 'false' ) . ';'
			. 'window.aviEmbedLogoutUrl=' . wp_json_encode(
				self::get_localedge_logout_url()
			) . ';'
			. 'window.aviEmbedPendingLocations=' . wp_json_encode(
				( $score_profile && ! empty( $score_profile->pending_google_locations ) )
					? json_decode( $score_profile->pending_google_locations, true )
					: null
			) . ';'
			. '</script>'
			. '<script src="' . esc_url( $plugin_url . 'assets/js/avi-radar-heatmap.js' ) . '"></script>'
			. '<script>'
			. '(function(){'
			. 'var _leCC={3:2,5:4,7:8,9:13,11:18,13:25,15:33,21:60};'
			. 'window._leCC=_leCC;'
			. 'function _leGridLabel(s,w){return s+"x"+s+" - "+(_leCC[s]||s*s)+" "+w;}'
			. 'window._leGridLabel=_leGridLabel;'
			. 'var _lePatching=false;'
			. 'function _leGetCost(size,kwCount){'
			. '  return (_leCC[size]||size*size)*(kwCount||1);'
			. '}'
			. 'function _lePatch(){'
			. '  if(_lePatching)return;'
			. '  _lePatching=true;'
			. '  try{'
			. '    var root=document.querySelector('
			. '      \'.avi-radar-heatmap-module\''
			. '    );'
			. '    if(!root){_lePatching=false;return;}'
			. '    var gs=root.querySelector('
			. '      \'[data-avi-heatmap-grid-size]\''
			. '    );'
			. '    var size=gs?parseInt(gs.value,10):7;'
			. '    var kwSel=root.querySelectorAll('
			. '      \'[data-heatmap-keyword].is-selected\''
			. '    );'
			. '    var kwCount=kwSel.length||1;'
			. '    var cost=_leGetCost(size,kwCount);'
			. '    var costEl=root.querySelector('
			. '      \'[data-avi-heatmap-cost]\''
			. '    );'
			. '    if(costEl&&costEl.textContent!==String(cost)){'
			. '      costEl.textContent=String(cost);'
			. '    }'
			. '    var balEl=root.querySelector('
			. '      \'[data-avi-heatmap-balance]\''
			. '    );'
			. '    var bal=balEl?parseInt(balEl.textContent||0,10):0;'
			. '    var after=Math.max(0,bal-cost);'
			. '    var gsSel=root.querySelector('
			. '      \'[data-avi-heatmap-grid-size]\''
			. '    );'
			. '    if(gsSel){'
			. '      Array.from(gsSel.options).forEach('
			. '        function(opt){'
			. '          var m=opt.text.match(/^(\\d+)x\\d+/);'
			. '          if(!m)return;'
			. '          var gs=parseInt(m[1],10);'
			. '          var c=_leCC[gs]||gs*gs;'
			. '          var cwMatch=opt.text.match(/^\\d+x\\d+\\s*-\\s*\\d+\\s*(.+)$/i);'
			. '          var cw=cwMatch?cwMatch[1].trim():"credits";'
			. '          var newTxt=gs+"x"+gs+" - "+c+" "+cw;'
			. '          if(opt.text!==newTxt){'
			. '            opt.text=newTxt;'
			. '          }'
			. '        }'
			. '      );'
			. '    }'
			. '    var baEl=root.querySelector('
			. '      \'[data-avi-heatmap-balance-after]\''
			. '    );'
			. '    if(baEl&&baEl.textContent!==String(after)){'
			. '      baEl.textContent=String(after);'
			. '    }'
			. '  }catch(e){}'
			. '  _lePatching=false;'
			. '}'
			. 'var _leObs=new MutationObserver(function(muts){'
			. '  var structural=muts.some(function(m){'
			. '    return m.type===\'childList\';'
			. '  });'
			. '  if(structural&&!_lePatching){'
			. '    setTimeout(_lePatch,100);'
			. '  }'
			. '});'
			. 'function _leInit(){'
			. '  var root=document.querySelector('
			. '    \'.avi-radar-heatmap-module\''
			. '  );'
			. '  if(!root){setTimeout(_leInit,300);return;}'
			. '  var gs=root.querySelector('
			. '    \'[data-avi-heatmap-grid-size]\''
			. '  );'
			. '  if(gs){'
			. '    gs.addEventListener(\'change\',function(){'
			. '      setTimeout(_lePatch,150);'
			. '    });'
			. '  }'
			. '  _leObs.observe(root,{'
			. '    childList:true,subtree:true'
			. '  });'
			. '  setInterval(function(){'
			. '    if(!_lePatching)_lePatch();'
			. '  },2000);'
			. '  setTimeout(_lePatch,800);'
			. '}'
			. 'if(document.readyState===\'loading\'){'
			. '  document.addEventListener('
			. '    \'DOMContentLoaded\',_leInit'
			. '  );'
			. '}else{'
			. '  setTimeout(_leInit,100);'
			. '}'
			. '})();'
			. '</script>'
			. '<script>'
			. 'document.addEventListener("DOMContentLoaded",function(){'
			. 'function _applyWlBanner(){'
			. 'var _wlName=window.aviEmbedWhiteLabel||"";'
			. 'var _wlLogo=window.aviEmbedLogoUrl||"";'
			. 'if(_wlLogo){'
			. 'var _st=document.getElementById("aviWlBannerStyle");'
			. 'if(!_st){_st=document.createElement("style");_st.id="aviWlBannerStyle";document.head.appendChild(_st);}'
			. '_st.textContent=".avi-heatmap-icon{display:none!important}"'
			. '+".avi-heatmap-closed-main::before{content:\\"\\";display:block;width:48px;height:48px;"'
			. '+"background:url("+JSON.stringify(_wlLogo)+") center/contain no-repeat;border-radius:8px;flex-shrink:0;}";'
			. '}'
			. 'document.querySelectorAll(".avi-heatmap-eyebrow").forEach(function(el){'
			. 'el.textContent=(_wlName&&_wlName!=="Avision")?_wlName.toUpperCase():"LOCALEDGE";'
			. '});'
			. 'document.querySelectorAll(".avi-heatmap-title").forEach(function(el){'
			. 'el.textContent="Local SEO Dominance";'
			. '});'
			. '}'
			. '_applyWlBanner();'
			. 'var l=document.getElementById("aviEmbedLoader");'
			. 'if(l)setTimeout(function(){l.style.display="none"},800);'
			. 'var t=document.querySelector("[data-avi-heatmap-toggle]");'
			. 'if(t)setTimeout(function(){t.click();},400);'
			. 'if(t)setTimeout(function(){'
			. 'var g=document.querySelector(".avi-heatmap-drawer-grid");'
			. 'if(g){'
			. 'g.style.setProperty("display","grid","important");'
			. 'g.style.setProperty("grid-template-columns","minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)","important");'
			. 'g.style.setProperty("grid-template-rows","1fr","important");'
			. '}'
			. '},500);'
			. 'var _embedNavTabs=["home","keywords","map","evolution","competitors","posts","photos","avis","score","citations","help"];'
			. 'var _embedNavI18n={'
			. 'en:{home:"🏠 Home",keywords:"🔑 Keywords",map:"🗺️ Map",evolution:"📈 Evolution",competitors:"🎯 Competitors",posts:"📝 GBP Posts",photos:"📸 GBP Photos",avis:"⭐ Google Reviews",score:"📊 GBP Score",citations:"\\uD83D\\uDCCB Citations",help:"❓ Help",agency_hub:"🏢 Agency Hub",profile_solo:"\\uD83D\\uDC64 My Profile"},'
			. 'fr:{home:"🏠 Accueil",keywords:"🔑 Mots-clés",map:"🗺️ Carte",evolution:"📈 Évolution",competitors:"🎯 Concurrents",posts:"📝 Posts GBP",photos:"📸 Photos GBP",avis:"⭐ Avis Google",score:"📊 Score GBP",citations:"\\uD83D\\uDCCB Citations",help:"❓ Aide",agency_hub:"🏢 Espace Agence",profile_solo:"\\uD83D\\uDC64 Mon Profil"},'
			. 'es:{home:"🏠 Inicio",keywords:"🔑 Palabras clave",map:"🗺️ Mapa",evolution:"📈 Evolución",competitors:"🎯 Competidores",posts:"📝 Posts GBP",photos:"📸 Fotos GBP",avis:"⭐ Reseñas Google",score:"📊 Score GBP",citations:"\\uD83D\\uDCCB Citas",help:"❓ Ayuda",agency_hub:"🏢 Panel Agencia",profile_solo:"\\uD83D\\uDC64 Mi Perfil"},'
			. '"pt-br":{home:"🏠 Início",keywords:"🔑 Palavras-chave",map:"🗺️ Mapa",evolution:"📈 Evolução",competitors:"🎯 Concorrentes",posts:"📝 Posts GBP",photos:"📸 Fotos GBP",avis:"⭐ Avaliações Google",score:"📊 Score GBP",citations:"\\uD83D\\uDCCB Cita\\u00e7\\u00f5es",help:"❓ Ajuda",agency_hub:"🏢 Painel Agência",profile_solo:"\\uD83D\\uDC64 Meu Perfil"},'
			. 'tr:{home:"🏠 Ana Sayfa",keywords:"🔑 Anahtar Kelimeler",map:"🗺️ Harita",evolution:"📈 Gelişim",competitors:"🎯 Rakipler",posts:"📝 GBP Gönderileri",photos:"📸 GBP Fotoğrafları",avis:"⭐ Google Yorumları",score:"📊 GBP Skoru",citations:"\\uD83D\\uDCCB Al\\u0131nt\\u0131lar",help:"❓ Yardım",agency_hub:"🏢 Ajans Paneli",profile_solo:"\\uD83D\\uDC64 Profilim"},'
			. 'de:{home:"🏠 Startseite",keywords:"🔑 Keywords",map:"🗺️ Karte",evolution:"📈 Entwicklung",competitors:"🎯 Mitbewerber",posts:"📝 GBP Beiträge",photos:"📸 GBP Fotos",avis:"⭐ Google Bewertungen",score:"📊 GBP Score",citations:"\\uD83D\\uDCCB Eintr\\u00e4ge",help:"❓ Hilfe",agency_hub:"🏢 Agentur-Hub",profile_solo:"\\uD83D\\uDC64 Mein Profil"}'
			. '};'
			. 'var _embedI18n={'
			. 'en:{close:"Close",cancel:"Cancel",save:"Save",delete:"Delete",'
			. 'search_kw:"Search keywords...",add_kw:"+ Add keyword",add_keyword:"+ Add keyword",'
			. 'confirm_delete_scan:"Delete this scheduled scan?",'
			. 'kw_my_keywords:"My Keywords",kw_panel_title:"My Keywords",kw_panel_sub:"Track the search terms that matter for your local visibility. Each keyword can be scanned on the heatmap to show your Google Maps ranking across your neighborhood.",more:"more",'
			. 'import_kw:"📥 Import",export_kw:"📤 Export",'
			. 'export_csv:"📊 Export CSV",export_pdf:"📄 Export PDF",'
			. 'import_label:"Paste keywords — one per line or comma-separated:",'
			. 'import_btn:"Import",scan_kw:"Scan this keyword",'
			. 'no_kw:"No keywords yet — add your first keyword above",'
			. 'scanned:"✅ Scanned",pending:"⬜ Pending",threat:"⚠️ Threat",'
			. 'actions:"Actions",'
			. 'col_keyword:"Keyword",col_rank:"Rank",col_best:"Best rank",'
			. 'col_grid:"Grid",col_status:"Status",col_scan:"Last scan",'
			. 'col_threat:"Threat",publish_now:"Publish now",schedule_post:"Schedule post",schedule_post_credits:"Schedule post (2 credits)",publishing:"Publishing...",scheduling:"Scheduling...",new_post:"New GBP Post",edit_post:"Edit post",posts_panel_title:"GBP Posts",posts_panel_sub:"Create and manage your Google Business Profile posts. Regular posts improve your visibility and keep your customers informed about offers, news and events.",posts_info_title:"GBP Posts — How it works",posts_info_s1_title:"📝 Create content",posts_info_s1_body:"Write posts (offer, news, event) directly from LocalEdge. AVI can write them for you in one click.",posts_info_s2_title:"📅 Schedule",posts_info_s2_body:"Plan your publications in advance to maintain a regular presence on Google.",posts_info_s3_title:"📈 Boost your visibility",posts_info_s3_body:"Google favors active profiles. A minimum of 1 post per week is recommended to appear in the Local Pack.",upgrade_posts_title:"✨ Automate your GBP Posts",upgrade_posts_sub:"Avision Pro publishes posts automatically · Autopilot mode available",new_post_btn:"+ New post",write_content:"Content (max 1500 characters)",write_content_ph:"Write your post content...",scheduled_date:"Scheduled date & time",no_content:"No content",post_type_label:"Post type",post_type_update:"📢 Update — News & announcements",post_type_offer:"🏷️ Offer — Promotions & deals",post_type_event:"📅 Event — Events & activities",post_type_update_short:"📢 Update",post_type_offer_short:"🏷️ Offer",post_type_event_short:"📅 Event",credits_info:"💳 This will use 2 credits from your balance.",credits_2:"2 credits",publication:"Publication",publish_now_title:"⚡ Publish now",schedule_title:"🕐 Schedule",free:"Free",photo_optional:"Photo (optional)",upload_device:"📁 Upload from device",choose_photos:"🖼️ Choose from Photos",gallery_soon:"Coming soon — set up your photo gallery first",gallery_first_alert:"Set up your GBP Photos gallery first (Photos tab) to use this feature.",image_too_large:"Image too large — max 5MB",err_no_content:"Please enter post content.",err_content_long:"Content exceeds 1500 characters.",err_no_schedule:"Please select a scheduled date.",err_create_post:"Error creating post",err_network:"Network error",err_generic:"Error",no_posts:"No posts yet",no_posts_sub:"Create your first GBP post to engage your customers",posts_count_suffix:" post(s)",event_title:"Event title",event_title_ph:"e.g. Summer Sale",start_date:"Start date",end_date:"End date",filter_all:"All",post_status_published:"✅ Published",post_status_scheduled:"🕐 Scheduled",post_status_pending:"⏳ Pending",post_status_failed:"❌ Failed",post_status_draft:"📝 Draft",view_btn:"👁 View",th_type:"Type",th_content:"Content",th_status:"Status",th_scheduled:"Scheduled",th_published:"Published",th_actions:"Actions",sync_gbp:"🔄 Sync from GBP",syncing:"Syncing...",publish_photo:"⚡ Publish",schedule_photo:"🕐 Schedule",delete_photo_title:"Delete from library",delete_confirm:"Delete this media from library?",rename_hint:"Click to rename",change_category:"Click to change category",no_category:"No category",upload_photo:"+ Upload photo",select_photo_picker:"📎 Select a photo to add to your post",schedule_date_prompt:"Schedule date and time (YYYY-MM-DDTHH:MM):",saving:"Saving...",select_btn:"✓ Select",copy_url:"Copy URL",video_badge:"🎬 Video",'
			. 'sync_failed:"Sync failed",photos_sync_success:"\u2705 Photos synced from Google",delete_gbp_title:"Delete from GBP",delete_gbp_confirm:"Delete this photo from your Google Business Profile? This cannot be undone.",delete_gbp_success:"Photo deleted from GBP",delete_gbp_error:"Failed to delete from GBP",bulk_download:"Download selected",bulk_delete:"Delete from library",bulk_delete_confirm:"Delete {n} photo(s) from library?",bulk_delete_success:"{n} photo(s) deleted from library",bulk_gbp_note:"\u26a0\ufe0f Google does not allow bulk deletion of photos \u2014 please delete them one by one.",selected:"selected",select_category:"— Select category (Google official) —",rename_ph:"Keyword-rich filename (e.g. plombier-paris-intervention.jpg)",show_less_cats:"▲ Show less",show_all_cats:"▼ Show all GBP categories",photos_panel_title:"GBP Photos",photos_panel_sub:"Manage your Google Business Profile photos: upload, organize, publish and optimize for local SEO.",photos_info_title:"GBP Photos — How it works",photos_info_s1_title:"📚 Library vs Published vs Not Published",photos_info_s1_body:"Library = all your photos stored in LocalEdge. Published = visible on your Google profile. Not Published = uploaded but not yet pushed to Google.",photos_info_s2_title:"🗂️ Categories",photos_info_s2_body:"Organize your photos by category (exterior, interior, team, products…). A well-organized profile inspires more trust with customers.",photos_info_s3_title:"✏️ Rename for SEO",photos_info_s3_body:"The display name of your photo matters for SEO. Use descriptive names with your keywords (e.g. \'italian-restaurant-paris-terrace\'). Click the pencil icon to rename any photo.",photos_info_s4_title:"⬇️ Download & 🗑️ Delete",photos_info_s4_body:"Use \u0027\u2b07\ufe0f Download\u0027 to save a photo to your device. Use \u0027\ud83d\uddd1\ufe0f Delete from library\u0027 to remove it from LocalEdge only. Use \u0027\ud83c\udf10 Delete from GBP\u0027 to remove it permanently from your Google profile (cannot be undone).",upgrade_photos_title:"✨ Never run out of fresh photos",upgrade_photos_sub:"Avision Pro automatically schedules and publishes your photos to keep your profile always fresh · Autopilot mode",photos_filter_library:"📚 Library",photos_filter_gbp_pub:"✅ Published on GBP",photos_filter_gbp_unpub:"📚 Not published",photo_category_label:"Photo category",filter_all_cats:"All categories",download_label:"Download",upload_drag:"Drag & drop photos here",upload_drag_sub:"Photos JPG/PNG (max 5MB) · Videos MP4 (max 75MB, 30s)",reply_btn:"💬 Reply",cancel_reply:"Cancel",publish_reply:"Publish reply",publishing_reply:"Publishing...",reply_published:"Reply published on Google!",write_reply_ph:"Write your reply...",avi_writes_review:"✨ AVI writes",avi_rewrite_reply:"✨ Rewrite with AVI",edit_reply:"\\u270F\\uFE0F Edit reply",generating_reply:"✨ Generating...",regenerate_reply:"↺ Regenerate",ai_reply_error:"AVI couldn\u0027t generate a reply. Try again.",your_reply:"💬 Your reply · ",no_reviews:"No reviews found",no_reviews_filter:"No reviews match this filter",reviews_0:"0 reviews",reviews_showing:"Showing ",reviews_of:" of ",reviews_suffix:" reviews",load_more:"🔄 Load more reviews from Google",load_more_info:"✅ All ",load_more_info_end:" reviews loaded from your GBP cache · Sync new reviews via Avision Pro for real-time updates",load_more_loading:"Loading reviews...",filter_all_stars:"All ⭐",without_reply:"💬 Without reply",sort_recent:"Most recent",sort_oldest:"Oldest first",sort_lowest:"Lowest rating first",sort_unanswered:"Without reply first",per_page:" per page",previous:"← Previous",next:"Next →",page_of:"Page ",gbp_reviews_title:"Google Business Profile reviews",gbp_reviews_sub:"Respond directly to build trust with your customers",reviews_info_title:"Google Reviews — How it works",reviews_info_s1_title:"⭐ Why reviews matter",reviews_info_s1_body:"Google reviews directly impact your local ranking and your conversion rate. A business with recent responses ranks higher in the Local Pack.",reviews_info_s2_title:"✉️ Reply to build trust",reviews_info_s2_body:"Responding to every review — positive or negative — shows professionalism. AVI can generate a personalized reply in one click.",reviews_info_s3_title:"📅 Stay consistent",reviews_info_s3_body:"Filter by New, This Week, This Month or This Year to prioritize your responses and never miss a review.",tip_th_reviewer:"Customer name and profile photo",tip_th_stars:"Rating given by the reviewer (1–5 stars)",tip_th_date:"Date the review was posted",tip_th_review:"Full review content left by the customer",tip_th_replied:"Whether you have replied to this review",tip_th_actions:"Reply, edit or regenerate a response with AVI",filter_new:"New",filter_week:"This week",filter_month:"This month",filter_year:"This year",filter_all_years:"All years",filter_all_months:"All months",filter_all_weeks:"All weeks",filter_all_replies:"All replies",filter_with_reply:"\u2705 With reply",flag_review_tip:"Report this review to Google (spam, fake, inappropriate)",th_report:"Report",tip_th_report:"Flag this review to Google (spam, fake, inappropriate)",upgrade_ai_title:"🤖 Respond faster with AI",upgrade_ai_sub:"Avision Pro generates personalized replies in seconds · Autopilot mode available",upgrade_link:"Upgrade to Avision Pro →",th_reviewer:"Reviewer",th_stars:"Stars",th_date:"Date",th_review:"Review",th_replied:"Replied",gbp_score_title:"📊 GBP Score",profile_completeness:"Profile completeness",profile_stats:"Profile stats",last_sync:"🕐 Last sync: ",crit_name:"Business name",pts_0:"Info",crit_website:"Website",crit_phone:"Phone number",crit_hours:"Opening hours",crit_description:"Business description",crit_category:"Primary category",crit_address:"Address",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ Done",missing:"❌ Missing",reviews_label:"reviews",photos_label:"Photos",avg_rank:"Avg rank",score_urgent:"Needs urgent attention",score_improve:"Room for improvement",score_getting:"Getting there",score_good:"Good profile",score_excellent:"Excellent profile",unknown:"Unknown",upsell_slim:"✨ Upgrade to Avision Pro — Guardian · RAG · Multi-profile",learn_more:"▲ Learn more",learn_close:"▼ Close",upsell_local:"🏠 Local Business",upsell_agency:"🏢 Agency",no_client:"No client found",search_client_ph:"🔍 Search client...",clients_title:"👥 Clients",'
			. 'clients_trigger:"👥 Clients ▾",loading:"⏳ Loading...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Sync from Google",sync_info_title:"Sync from Google",sync_info_score_body:"Refreshes your GBP Score and profile data directly from Google. Use it if your score, reviews or attributes don\\u2019t reflect recent changes you made on Google Business Profile.",sync_info_home_body:"Refreshes all your dashboard statistics — rank data, reviews and scan history. Use it if your stats seem outdated or if you\\u2019ve recently made changes to your Google Business Profile.",sync_info_footer:"Data updates automatically every 24h. This button forces an immediate refresh.",help_title:"Help & FAQ",help_subtitle:"Find answers to common questions about your Google Business Profile",help_s1_title:"🔴 Top 5 — Common Problems",help_s2_title:"🟣 Optimize My Profile",help_s3_title:"🔵 Google\'s Updates",help_faq1_q:"🚫 My listing is suspended",help_faq1_a:"Google suspends profiles for keyword-stuffed names, address mismatches, or too many rapid edits. Fix the issue first, then file a reinstatement request with proof (utility bill, lease, business license). Never create a duplicate listing while under review.",help_faq2_q:"🔍 My listing doesn\'t appear on Google Maps",help_faq2_a:"Check that your profile is fully verified and published. Unverified listings won\'t appear in Search or Maps. New profiles can take 2 to 4 weeks to appear consistently. Check your NAP consistency across your website and other directories.",help_faq3_q:"✅ How to verify my listing (video)",help_faq3_a:"Video verification is the default method in 2026. Record a single continuous take showing your signage, interior, and a live action in your GBP dashboard. Make sure your business name, address and website match before attempting.",help_faq4_q:"✏️ Unauthorized edits were made to my listing",help_faq4_a:"Anyone can suggest edits and Google may accept them automatically. Check your details regularly and revert incorrect changes via your GBP dashboard. Guardian mode in LocalEdge monitors your key fields 24/7 and alerts you instantly.",help_faq5_q:"⭐ I can\'t reply to reviews",help_faq5_a:"This usually indicates a profile restriction rather than a full suspension. Check your GBP dashboard for any notifications. Make sure you are logged into the correct Google account that owns the profile.",help_faq6_q:"📸 Which photos should I post and how many?",help_faq6_a:"Post at least 10 photos: exterior, interior, team, products or services. Add new photos every month — Google rewards active profiles. Avoid stock photos or AI-generated images. Real photos of your actual business build trust and improve your ranking.",help_faq7_q:"🏷️ How do I choose the right primary category?",help_faq7_a:"Your primary category is the single biggest ranking lever on Google Maps. Choose the most specific category that matches your core service. A plumber should select Plumber, not Home Services. You can add secondary categories for additional services.",help_faq8_q:"📝 How do I write a good business description?",help_faq8_a:"Write 250 to 750 characters describing what you do, who you serve, and what makes you different. Include your main keywords naturally. Avoid promotional language, URLs, or phone numbers. Update it every 6 months to stay fresh.",help_faq9_q:"🗓️ How often should I post?",help_faq9_a:"Post at least once a week to maintain freshness signals. Use AVI in the Posts tab to generate and schedule content in seconds. What\'s New posts expire after 7 days, Events persist until the end date, and Offers drive direct engagement.",help_faq10_q:"⭐ How do I get more customer reviews?",help_faq10_a:"Ask every satisfied customer immediately after the service. Send a direct review link via email or SMS. Add a QR code to your receipts or cards. Never offer incentives or tell customers what to write — Google penalizes this in 2026.",help_faq11_q:"📍 Should I show my address or a service area?",help_faq11_a:"If customers visit your premises, show your address. If you travel to customers, hide your address and add service areas instead. Showing a home address when you visit customers can confuse users and risk a suspension.",help_faq12_q:"🔄 I have a duplicate listing — what should I do?",help_faq12_a:"Duplicate listings split your reviews and confuse Google. Search for your business on Google Maps and report any duplicate via the Suggest an edit option. Google will merge or remove the extra listing. Never try to manage two profiles for the same business.",help_faq13_q:"🤖 Q&A removed — replaced by Ask Maps (Gemini)",help_faq13_a:"Google discontinued the Q&A feature and replaced it with Ask Maps, powered by Gemini AI. Gemini now answers user questions by pulling from your profile fields, reviews, photos and website. Fill every GBP field and add FAQ content to your website with FAQ schema markup.",help_faq14_q:"🛡️ New review rules in 2026",help_faq14_a:"Google updated its review policy in early 2026. AI-generated reviews are now prohibited. You can still ask for reviews but must not tell customers what to write. A neutral ask like \'share your honest experience\' is safe. Fake or incentivized reviews risk profile suspension.",help_faq15_q:"⚡ Rapid edits can trigger a suspension",help_faq15_a:"Making many changes at once — name, address, category, hours — is a common suspension trigger in 2026. Space out your edits over several days. Guardian mode in LocalEdge tracks field changes and warns you before you reach a risky threshold.",syncing_btn:"⏳ Syncing...",sync_success:"✅ Profile synced!",sync_error:"Sync failed. Try again.",add_credits:"+ Add pool credits",assign_credits:"+ Credits",assign_min_hint:"Min. 10 cr \u00b7 Multiples of 10",select_all:"Select all",bulk_cr_each:"cr each",bulk_assigning:"Assigning...",bulk_assigned:"\u2705 clients credited",onboarding_title:"Connect your Google Business Profile",onboarding_subtitle:"Link your GBP to unlock all LocalEdge features: score, reviews, photos, posts and more.",onboarding_connect:"\uD83D\uDD17 Connect Google Business",'
			. 'picker_title:"Choose your Google Business Profile",picker_subtitle:"Select the listing you want to manage with LocalEdge.",picker_btn:"Select this listing",picker_loading:"Connecting...",picker_error:"Error connecting this listing. Please try again.",picker_select_all:"Select all",picker_import:"Import selected listings",'
			. 'onboarding_skip:"I\u0027ll do this later",onboarding_step1_title:"1. Sign in",onboarding_step1_desc:"Connect your Google account",onboarding_step2_title:"2. Select profile",onboarding_step2_desc:"Choose your business listing",onboarding_step3_title:"3. Ready!",onboarding_step3_desc:"All features unlocked",edu_banner_title:"🎯 Welcome to your Local SEO Command Center",edu_banner_body:"Your GBP is connected. Now let\u0027s make it work — monitor your score, grow your visibility and outrank competitors.",edu_banner_close:"Got it \u2713",edu_help_btn:"💡",edu_modal_title:"How LocalEdge works",edu_step1_title:"Step 1 — Complete Your Profile",edu_step1_body:"Your GBP is connected \u2705 This is your starting point. Head to the GBP Score tab to instantly see which fields are incomplete. Phone, hours, description, photos, categories — every missing field costs you positions on Google Maps. A 100% complete profile gets up to 2x more clicks.",edu_step2_title:"Step 2 — Scan \u0026 Analyze Your Local Visibility",edu_step2_body:"In the Heatmap tab, select 1 to 5 keywords that describe your business (e.g. \u0027plumber London\u0027). Launch your first scan — each grid point shows your real Google Maps position in that area. Don\u0027t worry: every page has \u2139\uFE0F buttons to guide you at every step.",edu_step3_title:"Step 3 — Optimize, Engage \u0026 Grow",edu_step3_body:"Now that you know where you stand, take action. GBP Score: fix priority fields to climb rankings. Posts \u0026 Photos: \u2728 AVI writes and schedules your content in seconds. Reviews: reply within 24h with \u2728 AVI — Google rewards businesses that engage with their customers.",edu_learn_more:"How it works \u2192",tt_score:"Your GBP Score measures how complete and optimized your profile is. A score above 70 significantly improves your visibility in Google\u0027s Local Pack. Find it in the GBP Score tab \u2192",tt_unanswered:"Responding to reviews within 24h boosts your Google trust score. Unanswered reviews hurt your ranking. Go to Google Reviews tab to reply \u2192",tt_next_scan:"Regular scans track your local visibility evolution over time. Each scan maps your Google Maps position across your neighborhood grid. Launch a scan in column 3 \u2192",tt_nap:"Your profile completeness directly impacts your local ranking. Each missing field costs you points. Fix them in the GBP Score tab \u2192",tt_control_center:"Your GBP snapshot: score, unanswered reviews, next scheduled scan, and profile completeness \u2014 all in one place to help you prioritize what to fix first.",clients_count_suffix:" client(s)",pool_credits:"💳 Pool credits: ",available_word:" available · ",used_word:" used",never:"Never",today:"Today",yesterday:"Yesterday",sort_priority:"🚨 Priority (low score first)",sort_best_score:"⭐ Best score first",sort_activity:"🕐 Last activity",sort_name:"A→Z Name",sort_kw:"🔑 Most keywords",scan_badge:" scan(s)",kw_badge:" kw",logo_too_large:"Logo too large — max 2MB",upload_logo:"📁 Upload logo from device",or_sep:"— or —",agency_hub_title:"Agency Hub",col_suffix:" col",cols_suffix:" cols",err_rename:"Network error on rename",err_file_too_large:"File too large",tip_col_keyword:"The tracked search term",tip_col_rank:"Current average rank across all heatmap grid points",tip_col_best:"Best rank ever recorded",tip_col_grid:"Grid size used for last scan",tip_col_status:"Pending = never scanned · Scanned = has data",tip_col_scan:"Date + scan type (solo or multi)",tip_col_threat:"⚠️ Competitor dominates Top 3 on 50%+ of grid points",filter_danger:"⚠️ Danger",filter_solo_scan:"🔍 Solo scan",filter_multi_scan:"📊 Multi scan",filter_az:"A→Z",filter_all_grids:"All grids",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" keywords)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Not scanned yet",export_col_city:"City",export_col_scan_type:"Scan type",export_yes:"Yes",export_no:"No",export_danger_yes:"⚠️ Yes",kw_report_title:"Keywords Report",kw_report_generated:"Generated:",kw_report_keywords_suffix:" keywords",import_kw_tip:"Import multiple keywords (one per line or CSV)",add_kw_ph:"Enter keyword (e.g. Plumber London)",import_kw_ph:"Plumber London\\nElectrician Manchester\\nRoofer Birmingham",post_char_of:" / 1500",post_add_photo:"📷 Add a photo",post_photo_formats:"JPG, PNG — max 5MB",export_col_created:"Created",posts_page_title:"GBP Posts",posts_report_title:"GBP Posts Report",photo_status_in_stock:"📚 In library",photos_count_suffix:" photo(s)",no_photos:"No photos yet",no_photos_sub:"Upload photos to build your GBP library",photo_alt_default:"GBP Photo",photo_sched_vid:"5 cr",photo_sched_img:"3 cr",err_rename_failed:"Rename failed",export_col_file:"File",export_col_category:"Category",photos_page_title:"GBP Photos",photos_report_title:"GBP Photos Report",photos_library_count_suffix:" photos in library",cat_cover:"🖼️ Cover",cat_profile:"👤 Profile",cat_logo:"🎨 Logo",cat_interior:"🏠 Interior",cat_exterior:"🏢 Exterior",cat_product:"📦 Product",cat_at_work:"💼 At Work",cat_food_drink:"🍽️ Food & Drink",cat_menu:"📋 Menu",cat_common_area:"🛋️ Common Area",cat_rooms:"🛏️ Rooms",cat_teams:"👥 Teams",cat_additional:"➕ Additional",rv_replied_yes:"✅ Yes",rv_replied_no:"❌ No",export_col_reply:"Reply",export_col_has_reply:"Has Reply",reviews_page_title:"Reviews Report",reviews_report_title:"Google Reviews Report",reviews_pdf_avg:"⭐ Average: ",reviews_pdf_reviews_suffix:" reviews",export_col_criterion:"Criterion",export_col_points:"Points",score_export_done:"Done",score_export_missing:"Missing",score_export_score:"Score",score_export_rating:"Rating",score_export_photos:"Photos",score_report_title:"GBP Score Report",score_pdf_stats:"Stats",score_pdf_rating:"⭐ Rating: ",score_pdf_photos:"📸 Photos: ",rel_d_ago:"d ago",rel_w_ago:"w ago",rel_mo_ago:"mo ago",rel_y_ago:"y ago",hub_subtitle:"Manage your agency settings, credits and white-label.",hub_credit_pool:"💳 Credit Pool",hub_tier_label:"Current Plan",hub_tier_t1:"Tier 1 — up to 10 listings",hub_tier_t2:"Tier 2 — up to 50 listings",hub_tier_t3:"Tier 3 — unlimited listings",hub_listings_gauge:"Active listings",hub_tier_upgrade:"Upgrade plan",hub_tier_downgrade:"Downgrade plan",hub_upgrade_processing:"Redirecting to payment...",hub_downgrade_confirm:"Confirm downgrade to this plan?",hub_downgrade_blocked:"Downgrade blocked: too many active listings.",hub_downgrade_success:"Plan updated successfully.",hub_info_upgrade:"Upgrade: you only pay the difference between plans (prorata).",hub_info_downgrade:"Downgrade: free, no refund. Blocked if active listings exceed the new plan limit.",hub_available:"Available",hub_used:"Used",hub_buy_credits:"+ Buy credits (wholesale)",hub_whitelabel:"🎨 White-label",hub_whitelabel_desc:"Logo URL and brand name displayed in the embed and PDF exports.",hub_logo_ph:"https://yourlogo.com/logo.png",hub_brand_ph:"Your Agency Name",hub_save_settings:"Save settings",saved:"Saved \u2713",hub_save_alert:"White-label settings — coming Sprint 45",hub_import_clients:"📥 Import clients",hub_import_csv_desc:"CSV format: business_name, city, category, country",hub_import_csv_btn:"Import CSV",hub_import_alert:"CSV import — coming Sprint 45",hub_pro_title:"🚀 Avision Pro Agency",hub_pro_sub:"Helicopter view · Bulk actions · Advanced reporting · Full Guardian",hub_pro_cta:"Upgrade to Avision Pro Agency →",profile_title:"My Profile",profile_subtitle:"Manage your credits and account.",profile_credits_available:"Credits available",profile_credits_used:"Used",profile_buy:"+ Buy credits",profile_pack_nano:"Nano — 10 credits",profile_pack_mini:"Mini — 30 credits",profile_pack_standard:"Standard — 75 credits",profile_pack_pro:"Pro — 200 credits",profile_pack_agency:"Agency — 600 credits",profile_price_nano:"$2",profile_price_mini:"$5",profile_price_standard:"$11",profile_price_pro:"$25",profile_price_agency:"$59",profile_save_economy:" — save ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Full dashboard · Guardian \\u00b7 Advanced SEO",profile_upsell_cta:"Upgrade to Avision Pro \\u2192",credits_modal_title:"💳 Your LocalEdge Credits",credits_modal_solo_p1:"Your LocalEdge credits never expire — buy when you need them, use them at your own pace.",credits_modal_usage_title:"Where to spend your credits:",credits_modal_heatmap:"🗺️ Heatmap scan — from 2 cr (3×3) to 60 cr (21×21)",credits_modal_post:"📝 GBP Post via AVI — 3 cr",credits_modal_photo:"📷 GBP Photo sync — 2 cr",credits_modal_guardian:"🔔 Guardian (profile monitoring) — free, included",credits_modal_savings_title:"The more you buy, the less you pay per credit.",credits_modal_savings_sub:"The Pro pack at $25 costs 38% less per credit than the Nano pack.",credits_modal_agency_title:"💳 Your Agency Credit Pool",credits_modal_agency_p1:"Your credit pool is shared across all your client profiles. Buy wholesale, distribute as needed.",credits_modal_agency_wholesale:"Wholesale pricing — your agency credits cost up to 47% less than standard rates. Your resale margin is yours to set.",credits_modal_agency_noexpiry:"No expiration — your credits remain available indefinitely.",purchase_success_title:"✓ Payment received!",purchase_success_sub:"Your credits will be available within a few seconds.",purchase_success_close:"Got it",slider_title:"Or choose your own amount",slider_credits:"credits",slider_price_per:"per credit",slider_vs_nano:"vs Nano",slider_buy_btn:"Buy",slider_min_label:"10 cr",slider_max_label_solo:"1,000 cr",slider_max_label_agency:"5,000 cr",client_balance:"Client balance",cr_need:"Need",cr_available:"Available",cr_missing:"Missing",days_ago:"d ago",attr_other:"Other",anonymous_reviewer:"Anonymous",error_generic:"An error occurred.",vs_standard:"vs standard",badge_discount_17:"-17%",badge_discount_27:"-27%",badge_discount_38:"-38%",badge_discount_16:"-16%",badge_discount_30:"-30%",badge_discount_40:"-40%",badge_discount_47:"-47%",ag_pack_starter:"Starter Agency — 100 credits",ag_pack_standard:"Standard Agency — 300 credits",ag_pack_pro:"Pro Agency — 750 credits",ag_pack_enterprise:"Enterprise Agency — 2000 credits",ag_price_starter:"$14",ag_price_standard:"$35",ag_price_pro:"$75",ag_price_enterprise:"$175",logo_preview_alt:"Logo preview",hub_uploaded_file:"(uploaded file)",ag_no_scan:"🗺️ No scan",gbp_open_title:"Open GBP listing: ",gbp_search_title:"Search on Google Maps: ",gbp_score:"GBP Score",unanswered:"Unanswered",unanswered_sub:"reviews to reply",credits_left:"Credits",next_scan:"Next Scan",no_scan:"No scan",nap_status:"Profile completeness",nap_name:"Name",nap_address:"Address",nap_phone:"Phone",nap_website:"Website",nap_hours:"Hours",nap_desc:"Description",fix_it:"Fix it \\u2192",edit:"Edit",fix:"Fix",edit_name:"Edit Business Name",name_warn:"Changing your business name may trigger a Google review. Use your exact real-world name.",edit_website:"Edit Website",edit_phone:"Edit Phone",edit_hours:"Edit Opening Hours",edit_description:"Edit Description",edit_categories:"Edit Categories",edit_address:"Edit Address",edit_success:"Updated successfully on Google!",edit_error:"Error updating. Please try again.",lodging_posts_warn:"GBP Posts are not available for lodging businesses (hotels, B&Bs, etc.). Google reserves this space for booking platforms.",hours_closed:"Closed",hours_open:"Open",cat_search_placeholder:"Search Google categories...",cat_primary:"Primary category",cat_additional:"Additional categories (max 9)",cat_lodging_warn:"Changing your primary category may affect your profile features.",addr_neighborhood:"Neighborhood / District",addr_street:"Street address",addr_city:"City",addr_region:"State / Region",addr_postal:"Postal code",addr_country:"Country code (e.g. FR)",verified:"Verified",pending_verification:"Pending verification",not_verified:"Not verified",verify_cta_text:"Your business is not verified on Google. Verified listings get more trust and visibility.",verify_cta_btn:"Verify my business \\u2192",verify_pending_text:"Verification in progress. Google may take up to 7 days to complete the process.",score_panel_sub:"Your Google Business Profile optimization score. Each completed field improves your visibility in local search results.",score_info_title:"GBP Score \u2014 How it works",score_info_s1_title:"\uD83C\uDFAF How the score is calculated",score_info_s1_body:"Base 30 pts + Website (+5) + Hours (+3) + Description 200+ chars (+2) + Additional category (+1) + Attributes \u22653 (+1). Maximum: 42 pts.",score_info_s2_title:"\uD83D\uDCC8 Why it matters",score_info_s2_body:"A complete and optimized profile ranks higher in Google\u0027s Local Pack. Each missing field costs you visibility in local searches.",score_info_s3_title:"\u270F\uFE0F How to improve",score_info_s3_body:"Click Edit or Fix on each criterion to update directly from LocalEdge \u2014 no need to open your Google Business Profile.",gbp_attributes_title:"GBP Attributes",attr_na:"N/A for this category",attr_url_gbp_hint:"Edit on Google Business Profile",attrs_filled:"Configured",crit_posts:"Recent posts",crit_photos:"Published photos",photos_published_label:"published",photos_min:"min. 3 recommended",post_stale:"Last post > 7 days \u2014 publish to keep your points",post_fresh:"Fresh \u2014 published within 7 days",post_upsell:"Schedule a post to keep your score",photo_stale:"Last photo > 7 days \u2014 publish to keep your points",photo_fresh:"Fresh \u2014 photo published within 7 days",photo_upsell:"Publish a photo to maintain your score",crit_reviews_reply:"Latest review replied",replied:"Replied",not_replied:"Not replied",no_reviews_yet:"No reviews yet",freshness_note:"Your score fluctuates with your activity: posts, photos, review replies, profile completeness and heatmap scans all impact your ranking. Stay active to maximize your points.",view:"View",reply:"Reply",attr_saved:"Attribute updated",attr_error:"Failed to update attribute",attrs_load_error:"Unable to load attributes",attrs_load_hint:"Click \uD83D\uDD04 Sync from Google to reload",hm_section_title:"🗺️ Heatmap Visibility",hm_info_title:"Heatmap — Why it changes everything",hm_info_s1_title:"📍 Know your exact position",hm_info_s1_body:"Each scan maps your Google Maps ranking across every point of your neighborhood grid. You see exactly where you dominate and where competitors beat you — street by street.",hm_info_s2_title:"🏆 Analyze your competitors",hm_info_s2_body:"The heatmap reveals which competitors occupy the top 3 positions on each grid point. Identify who to outrank, on which zones, and adjust your local SEO strategy accordingly.",hm_info_s3_title:"📐 Grid size = territory control",hm_info_s3_body:"A 7x7 grid covers your immediate neighborhood. A 13x13 grid maps your entire city. The larger your grid, the more territory you control and the more data you have to make strategic decisions.",hm_info_s4_title:"🔄 Regular scans = ranking gains",hm_info_s4_body:"Scan the same keyword weekly to track your progression. Each scan uses credits but gives you actionable data: are you gaining or losing positions? React before competitors take your spots.",hm_activity_label:"Scan activity",hm_performance_label:"Local performance",hm_coverage_label:"Territory coverage",hm_scan_now:"Launch a scan",hm_stale_warn:"No scan in 30+ days — your data is outdated",hm_no_scan:"No scan yet — start mapping your territory",control_center:"Control Center",guardian_badge:"\ud83d\udd14 Alerts",guardian_modal_title:"Guardian Lite \u2014 Profile Alerts",guardian_no_alerts:"No alerts detected",guardian_plan_free:"Free plan \u2014 no monitoring",guardian_plan_lite:"Lite \u2014 1x\/month scan",guardian_plan_standard:"Standard \u2014 weekly scan",guardian_plan_daily:"Daily scan active",guardian_field_title:"Business name changed",guardian_field_phone:"Phone number changed",guardian_field_categories:"Category changed",guardian_field_hours:"Opening hours changed",guardian_field_website:"Website changed",guardian_field_openInfo:"Open\/closed status changed",guardian_why_title:"Why monitor your profile?",guardian_why_1:"Anyone can suggest edits to your GBP \u2014 including competitors",guardian_why_2:"Local Guides have significant power and can mark your business as closed",guardian_why_3:"Undetected changes cause ranking drops and lost visibility",guardian_fix_btn:"Fix in GBP Score \u2192",guardian_mark_read:"Mark all as read",guardian_detected:"Detected:",guardian_old:"Before:",guardian_new:"After:",guardian_verify:"verify immediately",guardian_fix_now:"Fix now",guardian_field_address:"Address",guardian_field_description:"Description",guardian_field_specialHours:"Special Hours",guardian_field_serviceArea:"Service Area",crit_special_hours:"Special hours",crit_service_area:"Service area",special_hours_edit_info:"Special hours must be managed directly on Google Business Profile.",service_area_edit_info:"Service area must be managed directly on Google Business Profile.",guardian_changed:"changed",guardian_fix_gbp:"Fix on GBP \u2192",crit_open_status:"Business status",open_info_warn:"Modifying this status will update your Google Business Profile immediately.",open_status_open:"Open \u2014 Normal business hours",open_status_temp:"Temporarily closed \u2014 will reopen",open_status_perm:"Permanently closed \u2014 verify urgently",open_status_open_no_hours:"Open \u2014 No main hours displayed",open_status_unknown:"Status unknown",cit_title:"Citations",cit_listed:"listed",cit_done:"Done",cit_mark_done:"\u2713 Done",cit_already:"Already listed",cit_mark_already:"\u2713 Already listed",cit_trust:"We trust you \u2014 we don\u0027t verify this automatically",cit_url_placeholder:"Your listing URL (optional)",cit_section_universal:"\ud83c\udf0d Universal",cit_section_local:"\ud83c\udff3\ufe0f Local",cit_section_niche:"\ud83c\udfaf Niche",cit_todo:"\ud83d\udccb To do",cit_completed:"Completed",cit_collapse:"\u25b2 Collapse",cit_expand:"\u25bc Expand",cit_undo:"\u21a9 Undo",cit_remove:"Remove",cit_add_name:"Directory name",cit_add_url:"https://...",cit_add_btn:"+ Add",cit_banner_msg:"We automatically selected directories based on your Google Business category \"{cat}\". Some suggestions may not be a perfect fit \u2014 feel free to remove them or add your own.",cit_your_category:"your category",cit_panel_sub:"Track your business listings across directories to boost your local SEO visibility.",cit_info_title:"Citations & Local SEO",cit_info_s1_title:"\ud83d\udccd What is a citation?",cit_info_s1_body:"A citation is any online mention of your business name, address and phone number (NAP). Search engines use citations to verify your business is legitimate and improve your local rankings.",cit_info_s2_title:"\u26a0\ufe0f NAP consistency is critical",cit_info_s2_body:"Your business name, address and phone number must be exactly identical across all directories \u2014 same abbreviations, same punctuation, same format. Even small differences confuse search engines and hurt your rankings.",cit_info_s3_title:"\ud83c\udfaf Why these directories?",cit_info_s3_body:"We automatically selected directories based on your Google Business category and location. Some niche suggestions may not fit perfectly \u2014 feel free to remove them or add your own.",cit_info_s4_title:"\u2705 Already listed?",cit_info_s4_body:"If your business is already listed on a directory, click \u2018Already listed\u2019 and optionally add the URL to your listing. We trust you \u2014 we don\u0027t verify this automatically, but we may add verification in the future.",cit_score_section:"\ud83d\udccb Citations",cit_score_label:"Directory listings",cit_score_detail:"directories listed",cit_stale_warn:"Add a new directory to maintain your score",sh_title:"Score & Rank History",sh_daily:"Daily",sh_score:"GBP Score",sh_rank:"Avg Rank",sh_drop:"Sharp drop",sh_all_kw:"All keywords",sh_no_data:"No data yet. Run a heatmap scan to start tracking.",sh_start:"Start",sh_now:"Now",sh_best_rank:"Best rank",sh_info_title:"Understanding your Score & Rank History",sh_info_s1_title:"\\ud83d\\udcc8 GBP Score (purple)",sh_info_s1_body:"Your Google Business Profile optimization score from 0 to 100. It rises as you complete your profile, add photos, get reviews, and fix Guardian alerts.",sh_info_s2_title:"\\ud83d\\udccd Avg Rank (amber)",sh_info_s2_body:"Your average position in Google Maps results across all heatmap grid points. Lower is better \\u2014 rank #1 means you appear first for that search area.",sh_info_s3_title:"\\u26a0\\ufe0f Why does my rank fluctuate?",sh_info_s3_body:"GBP rank varies based on the searcher\\u0027s location, the keyword used, time of day, and Google algorithm updates. This is normal \\u2014 track the trend, not individual points.",sh_info_s4_title:"\\ud83d\\udd34 Red dots",sh_info_s4_body:"A red dot signals a sharp drop: -10 pts or more on score, or +5 positions lost on rank. These are moments to investigate \\u2014 check Guardian alerts for that date.",tab_profile:"Profile",tab_attributes:"Attributes",tab_history:"History",card_nap:"NAP & Info",card_online:"Online Presence",card_activity:"Activity",card_visibility:"Visibility",sh_fullscreen:"Full screen",sh_exit_fs:"Exit",card_nap_info_title:"NAP & Local SEO",card_nap_s1_title:"📍 What is NAP?",card_nap_s1_body:"NAP stands for Name, Address and Phone number. Search engines use your NAP to verify your business exists and is legitimate. Inconsistent NAP across the web hurts your local rankings.",card_nap_s2_title:"🎯 Why it matters",card_nap_s2_body:"Google cross-references your GBP with other directories. If your name or address differs even slightly, it creates doubt and lowers your local pack ranking.",card_nap_s3_title:"✅ What to do",card_nap_s3_body:"Keep your name, address, phone and category strictly identical on Google Business Profile and all directories. Use the Citations tab to track your listings.",card_nap_s4_title:"⚠️ Risk of re-verification or suspension",card_nap_s4_body:"Avoid modifying your category, description or key information too quickly. Google\u0027s algorithms need time to integrate changes. Too many rapid modifications can trigger a re-verification process or even a suspension of your listing.",card_online_info_title:"Online Presence",card_online_s1_title:"🌐 Website",card_online_s1_body:"A verified website linked to your GBP adds trust and +5 pts to your score. Make sure it loads correctly and matches your business information.",card_online_s2_title:"🕒 Opening hours",card_online_s2_body:"Accurate opening hours help customers find you and trust your business. Missing hours costs -3 pts and reduces your chances of appearing in \\u0027Open now\\u0027 searches.",card_online_s3_title:"📝 Description",card_online_s3_body:"A well-written description helps Google understand what your business does. Include your main services and location naturally. Missing description costs -2 pts.",card_activity_info_title:"Activity & Engagement",card_activity_s1_title:"📸 Google Posts",card_activity_s1_body:"Publishing posts regularly signals to Google that your business is active. A post within the last 7 days gives you +5 pts. Posts older than 7 days are marked stale.",card_activity_s2_title:"🖼️ Photos",card_activity_s2_body:"Businesses with photos get 42% more direction requests and 35% more website clicks. Fresh photos published within 7 days earn the maximum +5 pts.",card_activity_s3_title:"⭐ Review replies",card_activity_s3_body:"Responding to reviews shows customers and Google that you care. Reply to your latest review to earn +3 pts and build customer trust.",card_visibility_info_title:"Local Visibility",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"The heatmap shows where you rank on Google Maps across your service area. Run regular scans to track your position and spot opportunities to improve.",card_visibility_s2_title:"📋 Citations",card_visibility_s2_body:"Citations are mentions of your business on directories. More consistent citations = more trust from Google. Add at least one new directory per month to maintain your score.",card_visibility_s3_title:"📈 Tracking your progress",card_visibility_s3_body:"Use the History tab to see how your score and local rank evolve over time. A rising score combined with a falling rank number means your local SEO is working.",card_see_more:"See more",card_see_less:"See less",attrs_info_title:"GBP Attributes — What you need to know",attrs_info_s1_title:"🔧 What are GBP Attributes?",attrs_info_s1_body:"Attributes are additional details about your business that help customers make decisions — accessibility options, payment methods, parking, services available, and more. They appear directly on your Google Business Profile.",attrs_info_s2_title:"📍 Why they matter for Local SEO",attrs_info_s2_body:"Complete attributes signal to Google that your profile is detailed and trustworthy. They also help your business appear in specific filtered searches — for example, customers searching for \u0027wheelchair accessible\u0027 or \u0027free parking\u0027 businesses.",attrs_info_s3_title:"⚠️ Important — Some attributes cannot be edited here",attrs_info_s3_body:"Google controls which attributes are available based on your business category. Some attributes can only be modified directly on Google Business Profile. If an attribute does not respond to changes made here, please update it directly at business.google.com.",attr_url_hint:"Add these URLs to boost your visibility on Google. For appointment links, go to Google Business Profile \u2192 Edit Profile \u2192 Booking.",guardian_home_title:"Guardian",guardian_home_status:"Active",guardian_checking:"Checking...",guardian_disconnected:"Disconnected",guardian_home_subtitle:"Monitoring your profile 24\/7",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 Your GBP Sentinel",guardian_info_s1_title:"\ud83d\udd0d What Guardian monitors",guardian_info_s1_body:"Guardian watches 10 key fields of your Google Business Profile: business name, address, phone, website, main category, opening hours, description, open\/closed status, cover photos and attributes.",guardian_info_s2_title:"\u26a0\ufe0f Why it matters",guardian_info_s2_body:"Anyone \u2014 including competitors or Google itself \u2014 can suggest changes to your profile. Undetected modifications can cause ranking drops overnight. Guardian alerts you immediately so you can react.",guardian_info_s3_title:"\u2705 What Guardian does NOT do",guardian_info_s3_body:"Guardian does not improve your ranking. Continue optimising your GBP, publishing posts, responding to reviews and improving your score. Guardian protects the visibility you have already earned \u2014 it does not create new visibility.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 Included in your plan",guardian_info_s4_body:"Guardian Lite monitors 10 key GBP fields 24/7 and alerts you the moment a suspicious change is detected. Monitoring is always included in your plan \u2014 credits are only used when AVI auto-fixes a detected change (3 credits/month included \u00b7 2 credits per change fixed).",guardian_info_cta:"Got it \u2713",guardian_trial_ended:"Trial ended \u2014 credits active",guardian_trial_active:"Free Trial Active",guardian_trial_days_left:"days left in free trial",guardian_pricing_detail:"After trial: 3 credits/month + 2 credits per change detected",guardian_pricing_detail_active:"3 credits/month \u00b7 2 credits per change detected",guardian_disabled_title:"Deactivated",guardian_disabled_warn:"Your profile is no longer monitored. Competitors can modify your GBP without you knowing.",guardian_activate:"Activate Guardian \u2192",guardian_credits_active:"Credits Active",guardian_deactivate:"Deactivate Guardian",guardian_post_trial_status:"\u26a0\ufe0f Trial ended",guardian_post_trial_warning:"\u26a0\ufe0f Your profile is now exposed. Competitors and Local Guides can modify your GBP at any time \u2014 undetected changes cause ranking drops, wrong hours, and lost calls.",guardian_deactivate_warn:"If you deactivate, changes to your profile will go completely undetected. You won\u2019t be notified if a competitor marks you as closed.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Monitored by Guardian \u2014 free trial active",guardian_tooltip_active:"\u26A0\uFE0F Trial ended \u2014 Guardian active on credits. Click \u2139\uFE0F on home to manage.",guardian_low_credits_title:"Low Credits \u2014 Guardian at risk",guardian_low_credits_warn:"You have fewer than 10 credits. Guardian may stop monitoring soon.",guardian_credits_remaining:"Credits remaining:",guardian_buy_credits:"Buy credits \u2192",guardian_trial_expired_title:"Free Trial Ended",guardian_trial_expired_warn:"Your 15-day free trial has ended. Activate Guardian to keep monitoring your profile.",guardian_trial_expired_badge:"\u23f1\ufe0f Trial ended \u2014 activate to continue",guardian_paid_active_title:"Guardian Active",guardian_next_billing:"Next billing:",guardian_tooltip_off:"Guardian deactivated \u2014 this field is no longer monitored"},'
			. 'fr:{close:"Fermer",cancel:"Annuler",save:"Enregistrer",delete:"Supprimer",'
			. 'search_kw:"Rechercher un mot-clé...",add_kw:"+ Ajouter un mot-clé",add_keyword:"+ Ajouter un mot-clé",'
			. 'confirm_delete_scan:"Supprimer ce scan planifié ?",'
			. 'kw_my_keywords:"Mes mots-cl\u00e9s",kw_panel_title:"Mes mots-cl\u00e9s",kw_panel_sub:"Suivez les termes de recherche qui comptent pour votre visibilit\u00e9 locale. Chaque mot-cl\u00e9 peut \u00eatre scann\u00e9 sur la heatmap pour afficher votre position sur Google Maps dans votre zone.",more:"de plus",'
			. 'import_kw:"📥 Importer",export_kw:"📤 Exporter",'
			. 'export_csv:"📊 Exporter CSV",export_pdf:"📄 Exporter PDF",'
			. 'import_label:"Collez vos mots-clés — un par ligne ou séparés par virgule :",'
			. 'import_btn:"Importer",scan_kw:"Scanner ce mot-clé",'
			. 'no_kw:"Aucun mot-clé — ajoutez votre premier mot-clé ci-dessus",'
			. 'scanned:"✅ Scanné",pending:"⬜ En attente",threat:"⚠️ Menace",'
			. 'actions:"Actions",'
			. 'col_keyword:"Mot-clé",col_rank:"Position",col_best:"Meilleure position",'
			. 'col_grid:"Grille",col_status:"Statut",col_scan:"Dernier scan",'
			. 'col_threat:"Menace",publish_now:"Publier maintenant",schedule_post:"Programmer le post",schedule_post_credits:"Programmer (2 crédits)",publishing:"Publication...",scheduling:"Programmation...",new_post:"Nouveau post GBP",edit_post:"Modifier le post",posts_panel_title:"Publications GBP",posts_panel_sub:"Cr\u00e9ez et g\u00e9rez vos publications Google Business Profile. Des publications r\u00e9guli\u00e8res am\u00e9liorent votre visibilit\u00e9 et informent vos clients de vos offres, actualit\u00e9s et \u00e9v\u00e9nements.",posts_info_title:"Publications GBP — Comment \u00e7a marche",posts_info_s1_title:"📝 Cr\u00e9ez du contenu",posts_info_s1_body:"R\u00e9digez des posts (offre, actualit\u00e9, \u00e9v\u00e9nement) directement depuis LocalEdge. AVI peut r\u00e9diger pour vous en un clic.",posts_info_s2_title:"📅 Planifiez",posts_info_s2_body:"Programmez vos publications \u00e0 l\'avance pour maintenir une pr\u00e9sence r\u00e9guli\u00e8re sur Google.",posts_info_s3_title:"📈 Boostez votre visibilit\u00e9",posts_info_s3_body:"Google favorise les fiches actives. 1 post par semaine minimum est recommand\u00e9 pour appara\u00eetre dans le Pack Local.",upgrade_posts_title:"✨ Automatisez vos Publications GBP",upgrade_posts_sub:"Avision Pro publie automatiquement · Mode autopilote disponible",new_post_btn:"+ Nouveau post",write_content:"Contenu (max 1500 caractères)",write_content_ph:"Rédigez le contenu de votre post...",scheduled_date:"Date et heure programmées",no_content:"Aucun contenu",post_type_label:"Type de post",post_type_update:"📢 Actualité — Nouvelles & annonces",post_type_offer:"🏷️ Offre — Promotions & deals",post_type_event:"📅 Événement — Activités & événements",post_type_update_short:"📢 Actualité",post_type_offer_short:"🏷️ Offre",post_type_event_short:"📅 Événement",credits_info:"💳 Cela utilisera 2 crédits de votre solde.",credits_2:"2 crédits",publication:"Publication",publish_now_title:"⚡ Publier maintenant",schedule_title:"🕐 Programmer",free:"Gratuit",photo_optional:"Photo (optionnel)",upload_device:"📁 Importer depuis l\\u0027appareil",choose_photos:"🖼️ Choisir dans Photos",gallery_soon:"Bientôt — configurez d\\u0027abord votre galerie photos",gallery_first_alert:"Configurez d\\u0027abord votre galerie GBP Photos (onglet Photos) pour utiliser cette fonction.",image_too_large:"Image trop volumineuse — max 5 Mo",err_no_content:"Veuillez saisir le contenu du post.",err_content_long:"Le contenu dépasse 1500 caractères.",err_no_schedule:"Veuillez sélectionner une date programmée.",err_create_post:"Erreur lors de la création du post",err_network:"Erreur réseau",err_generic:"Erreur",no_posts:"Aucun post pour l\\u0027instant",no_posts_sub:"Créez votre premier post GBP pour engager vos clients",posts_count_suffix:" post(s)",event_title:"Titre de l\\u0027événement",event_title_ph:"ex. Soldes d\\u0027été",start_date:"Date de début",end_date:"Date de fin",filter_all:"Tous",post_status_published:"✅ Publié",post_status_scheduled:"🕐 Programmé",post_status_pending:"⏳ En attente",post_status_failed:"❌ Échoué",post_status_draft:"📝 Brouillon",view_btn:"👁 Voir",th_type:"Type",th_content:"Contenu",th_status:"Statut",th_scheduled:"Programmé",th_published:"Publié",th_actions:"Actions",sync_gbp:"🔄 Sync depuis GBP",syncing:"Synchronisation...",publish_photo:"⚡ Publier",schedule_photo:"🕐 Programmer",delete_photo_title:"Supprimer de la bibliothèque",delete_confirm:"Supprimer ce média de la bibliothèque ?",rename_hint:"Cliquer pour renommer",change_category:"Cliquer pour changer la catégorie",no_category:"Sans catégorie",'
			. 'upload_photo:"+ Importer une photo",select_photo_picker:"📎 Sélectionnez une photo pour votre post",schedule_date_prompt:"Date et heure (AAAA-MM-JJTHH:MM) :",saving:"Enregistrement...",select_btn:"✓ Sélectionner",copy_url:"Copier l\\u0027URL",video_badge:"🎬 Vidéo",sync_failed:"Échec de la synchronisation",photos_sync_success:"\u2705 Photos synchronisées depuis Google",delete_gbp_title:"Supprimer de GBP",delete_gbp_confirm:"Supprimer cette photo de votre fiche Google ? Cette action est irréversible.",delete_gbp_success:"Photo supprimée de GBP",delete_gbp_error:"Échec de la suppression GBP",bulk_download:"Télécharger la sélection",bulk_delete:"Supprimer de la library",bulk_delete_confirm:"Supprimer {n} photo(s) de la library ?",bulk_delete_success:"{n} photo(s) supprimée(s) de la library",bulk_gbp_note:"\u26a0\ufe0f Google ne permet pas la suppression en masse de photos \u2014 veuillez les supprimer une par une.",selected:"sélectionnée(s)",select_category:"— Choisir une catégorie (officielle Google) —",rename_ph:"Nom de fichier optimisé (ex. plombier-paris-intervention.jpg)",show_less_cats:"▲ Afficher moins",show_all_cats:"▼ Toutes les catégories GBP",photos_panel_title:"Photos GBP",photos_panel_sub:"G\u00e9rez vos photos Google Business Profile : importez, organisez, publiez et optimisez pour le SEO local.",photos_info_title:"Photos GBP — Comment \u00e7a marche",photos_info_s1_title:"📚 Library / Published / Not Published",photos_info_s1_body:"Library = toutes vos photos stock\u00e9es dans LocalEdge. Published = visibles sur votre fiche Google. Not Published = import\u00e9es mais pas encore envoy\u00e9es sur Google.",photos_info_s2_title:"🗂️ Cat\u00e9gories",photos_info_s2_body:"Organisez vos photos par cat\u00e9gorie (ext\u00e9rieur, int\u00e9rieur, \u00e9quipe, produits…). Un profil bien organis\u00e9 inspire davantage confiance aux clients.",photos_info_s3_title:"✏️ Renommer pour le SEO",photos_info_s3_body:"Le nom affich\u00e9 de votre photo compte pour le SEO. Utilisez des noms descriptifs avec vos mots-cl\u00e9s (ex : \'restaurant-italien-paris-terrasse\'). Cliquez sur l\'ic\u00f4ne crayon pour renommer.",photos_info_s4_title:"⬇️ T\u00e9l\u00e9charger & 🗑️ Supprimer",photos_info_s4_body:"Utilisez \u0027\u2b07\ufe0f Télécharger\u0027 pour sauvegarder une photo. \u0027\ud83d\uddd1\ufe0f Supprimer de la library\u0027 la retire de LocalEdge uniquement. \u0027\ud83c\udf10 Supprimer de GBP\u0027 la supprime définitivement de votre fiche Google (irréversible).",upgrade_photos_title:"✨ Gardez toujours des photos fraîches",upgrade_photos_sub:"Avision Pro planifie et publie vos photos automatiquement pour garder votre fiche toujours vivante · Mode autopilote",photos_filter_library:"📚 Bibliothèque",photos_filter_gbp_pub:"✅ Publié sur GBP",photos_filter_gbp_unpub:"📚 Non publié",photo_category_label:"Catégorie photo",filter_all_cats:"Toutes catégories",download_label:"Télécharger",upload_drag:"Glissez-déposez vos photos ici",upload_drag_sub:"Photos JPG/PNG (max 5 Mo) · Vidéos MP4 (max 75 Mo, 30s)",reply_btn:"💬 Répondre",cancel_reply:"Annuler",publish_reply:"Publier la réponse",publishing_reply:"Publication...",reply_published:"R\\u00e9ponse publi\\u00e9e sur Google !",write_reply_ph:"Rédigez votre réponse...",avi_writes_review:"✨ AVI rédige",avi_rewrite_reply:"✨ Réécrire avec AVI",edit_reply:"\\u270F\\uFE0F Modifier",generating_reply:"✨ Génération...",regenerate_reply:"↺ Régénérer",ai_reply_error:"AVI n\u2019a pas pu générer une réponse.",your_reply:"💬 Votre réponse · ",no_reviews:"Aucun avis trouvé",no_reviews_filter:"Aucun avis ne correspond à ce filtre",reviews_0:"0 avis",reviews_showing:"Affichage ",reviews_of:" sur ",reviews_suffix:" avis",load_more:"🔄 Charger plus d\\u0027avis depuis Google",load_more_info:"✅ Les ",load_more_info_end:" avis sont chargés depuis votre cache GBP · Synchronisez via Avision Pro pour des mises à jour en temps réel",load_more_loading:"Chargement des avis...",filter_all_stars:"Tous ⭐",without_reply:"💬 Sans réponse",sort_recent:"Plus récents",sort_oldest:"Plus anciens",sort_lowest:"Note la plus basse",sort_unanswered:"Sans réponse d\\u0027abord",per_page:" par page",previous:"← Précédent",next:"Suivant →",page_of:"Page ",gbp_reviews_title:"Avis Google Business Profile",gbp_reviews_sub:"Répondez directement pour renforcer la confiance de vos clients",reviews_info_title:"Avis Google — Comment ça marche",reviews_info_s1_title:"⭐ Pourquoi les avis comptent",reviews_info_s1_body:"Les avis Google impactent directement votre classement local et votre taux de conversion. Une fiche avec des réponses récentes se classe mieux dans le Pack Local.",reviews_info_s2_title:"✉️ Répondre pour inspirer confiance",reviews_info_s2_body:"Répondre à chaque avis — positif ou négatif — montre votre professionnalisme. AVI peut générer une réponse personnalisée en un clic.",reviews_info_s3_title:"📅 Restez régulier",reviews_info_s3_body:"Filtrez par Nouveaux, Cette semaine, Ce mois ou Cette année pour prioriser vos réponses et ne manquer aucun avis.",tip_th_reviewer:"Nom et photo du client",tip_th_stars:"Note donnée par le client (1 à 5 étoiles)",tip_th_date:"Date de publication de l\u0027avis",tip_th_review:"Contenu complet de l\u0027avis laissé par le client",tip_th_replied:"Indique si vous avez répondu à cet avis",tip_th_actions:"Répondre, modifier ou régénérer une réponse avec AVI",filter_new:"Nouveaux",filter_week:"Cette semaine",filter_month:"Ce mois",filter_year:"Cette année",filter_all_years:"Toutes les années",filter_all_months:"Tous les mois",filter_all_weeks:"Toutes les semaines",filter_all_replies:"Tous les avis",filter_with_reply:"\u2705 Avec réponse",flag_review_tip:"Signaler cet avis à Google (spam, faux avis, inapproprié)",th_report:"Signaler",tip_th_report:"Signaler cet avis à Google (spam, faux avis, inapproprié)",upgrade_ai_title:"🤖 Répondez plus vite avec l\\u0027IA",upgrade_ai_sub:"Avision Pro génère des réponses personnalisées en quelques secondes · Mode autopilote disponible",upgrade_link:"Passer à Avision Pro →",th_reviewer:"Auteur",th_stars:"Étoiles",th_date:"Date",th_review:"Avis",th_replied:"Répondu",gbp_score_title:"📊 Score GBP",profile_completeness:"Complétude du profil",profile_stats:"Statistiques du profil",last_sync:"🕐 Dernière sync : ",crit_name:"Nom de l\u2019entreprise",pts_0:"Info",crit_website:"Site web",crit_phone:"Numéro de téléphone",crit_hours:"Horaires d\\u0027ouverture",crit_description:"Description de l\\u0027activité",crit_category:"Catégorie principale",crit_address:"Adresse",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ OK",missing:"❌ Manquant",reviews_label:"avis",photos_label:"Photos",avg_rank:"Position moy.",score_urgent:"Attention urgente requise",'
			. 'score_improve:"Marge de progression",score_getting:"En bonne voie",score_good:"Bon profil",score_excellent:"Excellent profil",unknown:"Inconnu",upsell_slim:"✨ Passez à Avision Pro — Guardian · RAG · Multi-profil",learn_more:"▲ En savoir plus",learn_close:"▼ Fermer",upsell_local:"🏠 Commerce local",upsell_agency:"🏢 Agence",no_client:"Aucun client trouvé",search_client_ph:"🔍 Rechercher un client...",clients_title:"👥 Clients",clients_trigger:"👥 Clients ▾",loading:"⏳ Chargement...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Synchroniser depuis Google",sync_info_title:"Synchroniser depuis Google",sync_info_score_body:"Met à jour votre Score GBP et les données de votre fiche directement depuis Google. Utilisez ce bouton si votre score, vos avis ou vos attributs ne reflètent pas les modifications récentes effectuées sur Google Business Profile.",sync_info_home_body:"Met à jour toutes les statistiques de votre tableau de bord — données de classement, avis et historique des scans. Utilisez ce bouton si vos statistiques semblent obsolètes ou si vous venez de modifier votre fiche Google Business Profile.",sync_info_footer:"Les données se mettent à jour automatiquement toutes les 24h. Ce bouton force une actualisation immédiate.",help_title:"Aide & FAQ",help_subtitle:"Trouvez des réponses aux questions fréquentes sur votre fiche Google Business Profile",help_s1_title:"🔴 Top 5 — Problèmes fréquents",help_s2_title:"🟣 Optimiser ma fiche",help_s3_title:"🔵 Mises à jour Google",help_faq1_q:"🚫 Ma fiche est suspendue",help_faq1_a:"Google suspend les fiches pour des noms contenant des mots-clés, des incohérences d\'adresse ou trop de modifications rapides. Corrigez le problème d\'abord, puis déposez une demande de réintégration avec des preuves (facture, bail, licence). Ne créez jamais de doublon pendant la procédure.",help_faq2_q:"🔍 Ma fiche n\'apparaît pas sur Google Maps",help_faq2_a:"Vérifiez que votre fiche est entièrement validée et publiée. Les fiches non vérifiées n\'apparaissent pas. Les nouvelles fiches peuvent prendre 2 à 4 semaines pour s\'afficher. Vérifiez aussi la cohérence de vos coordonnées NAP sur votre site et les autres annuaires.",help_faq3_q:"✅ Comment vérifier ma fiche (vidéo)",help_faq3_a:"La vérification par vidéo est la méthode par défaut en 2026. Filmez en continu votre enseigne, l\'intérieur et une action en direct dans votre tableau de bord GBP. Assurez-vous que le nom, l\'adresse et le site web correspondent avant de commencer.",help_faq4_q:"✏️ Des modifications non autorisées ont été faites",help_faq4_a:"N\'importe qui peut suggérer des modifications et Google peut les accepter automatiquement. Vérifiez vos informations régulièrement et annulez les changements incorrects via votre tableau de bord GBP. Le mode Guardian de LocalEdge surveille vos champs clés 24h/24.",help_faq5_q:"⭐ Je ne peux pas répondre aux avis",help_faq5_a:"Cela indique généralement une restriction de profil plutôt qu\'une suspension complète. Vérifiez les notifications dans votre tableau de bord GBP. Assurez-vous d\'être connecté au bon compte Google propriétaire de la fiche.",help_faq6_q:"📸 Quelles photos publier et combien ?",help_faq6_a:"Publiez au minimum 10 photos : façade, intérieur, équipe, produits ou services. Ajoutez de nouvelles photos chaque mois — Google récompense les fiches actives. Évitez les photos stock ou générées par IA. Des photos authentiques renforcent la confiance et améliorent votre classement.",help_faq7_q:"🏷️ Comment choisir la bonne catégorie principale ?",help_faq7_a:"La catégorie principale est le levier de classement le plus puissant sur Google Maps. Choisissez la catégorie la plus précise correspondant à votre activité principale. Un plombier doit choisir Plombier, pas Services à domicile. Vous pouvez ajouter des catégories secondaires pour vos autres services.",help_faq8_q:"📝 Comment rédiger une bonne description ?",help_faq8_a:"Rédigez 250 à 750 caractères décrivant ce que vous faites, qui vous servez et ce qui vous distingue. Intégrez vos mots-clés principaux naturellement. Évitez le langage promotionnel, les URL ou les numéros de téléphone. Mettez à jour tous les 6 mois.",help_faq9_q:"🗓️ À quelle fréquence publier des posts ?",help_faq9_a:"Publiez au moins une fois par semaine pour maintenir des signaux de fraîcheur. Utilisez AVI dans l\'onglet Posts pour générer et programmer du contenu en quelques secondes. Les posts Nouveautés expirent après 7 jours, les Événements persistent jusqu\'à la date de fin.",help_faq10_q:"⭐ Comment obtenir plus d\'avis clients ?",help_faq10_a:"Demandez à chaque client satisfait immédiatement après la prestation. Envoyez un lien d\'avis direct par email ou SMS. Ajoutez un QR code sur vos reçus ou cartes. N\'offrez jamais d\'incitation ni ne dictez ce qu\'ils doivent écrire — Google le sanctionne en 2026.",help_faq11_q:"📍 Adresse visible ou zone de service ?",help_faq11_a:"Si vos clients viennent chez vous, affichez votre adresse. Si vous vous déplacez chez eux, masquez votre adresse et ajoutez des zones de service. Afficher une adresse personnelle quand vous vous déplacez peut semer la confusion et risquer une suspension.",help_faq12_q:"🔄 J\'ai une fiche en double — que faire ?",help_faq12_a:"Les fiches dupliquées divisent vos avis et perturbent Google. Recherchez votre entreprise sur Google Maps et signalez le doublon via Suggérer une modification. Google fusionnera ou supprimera la fiche en trop. Ne gérez jamais deux fiches pour la même entreprise.",help_faq13_q:"🤖 Q&A supprimé — remplacé par Ask Maps (Gemini)",help_faq13_a:"Google a supprimé la fonctionnalité Q&A et l\'a remplacée par Ask Maps, propulsé par Gemini AI. Gemini répond aux questions des utilisateurs en s\'appuyant sur vos champs de profil, avis, photos et site web. Remplissez tous les champs GBP et ajoutez une FAQ sur votre site avec le balisage schema.",help_faq14_q:"🛡️ Nouvelles règles avis 2026",help_faq14_a:"Google a mis à jour sa politique d\'avis début 2026. Les avis générés par IA sont désormais interdits. Vous pouvez toujours demander des avis mais ne devez pas dicter ce qu\'ils écrivent. Une demande neutre comme partagez votre expérience honnête est sans risque.",help_faq15_q:"⚡ Les modifications rapides peuvent déclencher une suspension",help_faq15_a:"Effectuer de nombreux changements d\'un coup — nom, adresse, catégorie, horaires — est un déclencheur fréquent de suspension en 2026. Espacez vos modifications sur plusieurs jours. Le mode Guardian de LocalEdge suit les changements de champs et vous avertit avant d\'atteindre un seuil risqué.",syncing_btn:"⏳ Synchronisation...",sync_success:"✅ Profil synchronisé !",sync_error:"Échec. Réessayez.",add_credits:"+ Cr\\u00e9dits pool",assign_credits:"+ Cr\\u00e9dits",assign_min_hint:"Min. 10 cr \\u00b7 Par tranches de 10",select_all:"Tout s\\u00e9lectionner",bulk_cr_each:"cr chacun",bulk_assigning:"Attribution...",bulk_assigned:"\\u2705 clients cr\\u00e9dit\\u00e9s",onboarding_title:"Connectez votre fiche Google Business",'
			. 'picker_title:"Choisissez votre fiche Google Business",picker_subtitle:"S\u00e9lectionnez la fiche que vous souhaitez g\u00e9rer avec LocalEdge.",picker_btn:"S\u00e9lectionner cette fiche",picker_loading:"Connexion en cours...",picker_error:"Erreur lors de la connexion. Veuillez r\u00e9essayer.",picker_select_all:"Tout s\u00e9lectionner",picker_import:"Importer les fiches s\u00e9lectionn\u00e9es",'
			. 'onboarding_title:"Connectez votre fiche Google Business",onboarding_subtitle:"Liez votre GBP pour d\\u00e9bloquer toutes les fonctionnalit\\u00e9s : score, avis, photos, posts et plus.",onboarding_connect:"\\uD83D\\uDD17 Connecter Google Business",onboarding_skip:"Je ferai \\u00e7a plus tard",onboarding_step1_title:"1. Connexion",onboarding_step1_desc:"Connectez votre compte Google",onboarding_step2_title:"2. S\\u00e9lection",onboarding_step2_desc:"Choisissez votre fiche",onboarding_step3_title:"3. Pr\\u00eat\\u00a0!",onboarding_step3_desc:"Toutes les fonctions activ\\u00e9es",edu_banner_title:"🎯 Bienvenue dans votre Centre de Commande SEO Local",edu_banner_body:"Votre GBP est connect\\u00e9. Optimisez votre score, d\\u00e9veloppez votre visibilit\\u00e9 et surclassez vos concurrents.",edu_banner_close:"Compris \\u2713",edu_help_btn:"💡",edu_modal_title:"Comment fonctionne LocalEdge",edu_step1_title:"\\u00c9tape 1 — Compl\\u00e9tez votre fiche",edu_step1_body:"Votre fiche GBP est connect\\u00e9e \\u2705 C\\u0027est votre point de d\\u00e9part. Rendez-vous dans l\\u0027onglet GBP Score pour voir en un coup d\\u0027oeil quels champs sont incomplets. T\\u00e9l\\u00e9phone, horaires, description, photos, cat\\u00e9gories — chaque champ manquant vous co\\u00fbte des positions sur Google Maps. Une fiche 100% compl\\u00e8te g\\u00e9n\\u00e8re jusqu\\u0027\\u00e0 2x plus de clics.",edu_step2_title:"\\u00c9tape 2 — Scannez et analysez votre visibilit\\u00e9 locale",edu_step2_body:"Dans l\\u0027onglet Heatmap, s\\u00e9lectionnez 1 \\u00e0 5 mots-cl\\u00e9s qui d\\u00e9crivent votre activit\\u00e9 (ex. \\u0027plombier Paris\\u0027). Lancez votre premier scan — chaque point de la grille vous montre votre position r\\u00e9elle sur Google Maps dans ce quartier. Pas d\\u0027inqui\\u00e9tude : chaque page contient des boutons \\u2139\\uFE0F pour vous guider \\u00e0 chaque \\u00e9tape.",edu_step3_title:"\\u00c9tape 3 — Optimisez, engagez et progressez",edu_step3_body:"Maintenant que vous voyez o\\u00f9 vous en \\u00eates, passez \\u00e0 l\\u0027action. GBP Score : corrigez les champs prioritaires pour grimper dans les r\\u00e9sultats. Posts \\u0026 Photos : \\u2728 AVI r\\u00e9dige et programme votre contenu en quelques secondes. Avis : r\\u00e9pondez sous 24h avec \\u2728 AVI — Google r\\u00e9compense les entreprises qui s\\u0027engagent avec leurs clients.",edu_learn_more:"Comment \\u00e7a marche \\u2192",tt_score:"Votre Score GBP mesure la compl\\u00e9tude et l\\u2019optimisation de votre fiche. Un score sup\\u00e9rieur \\u00e0 70 am\\u00e9liore significativement votre visibilit\\u00e9 dans le Pack Local Google. Trouvez-le dans l\\u2019onglet GBP Score \\u2192",tt_unanswered:"R\\u00e9pondre aux avis dans les 24h am\\u00e9liore votre score de confiance Google. Les avis sans r\\u00e9ponse nuisent \\u00e0 votre classement. Allez dans l\\u2019onglet Google Reviews pour r\\u00e9pondre \\u2192",tt_next_scan:"Les scans r\\u00e9guliers permettent de suivre l\\u2019\\u00e9volution de votre visibilit\\u00e9 locale. Chaque scan cartographie votre position sur Google Maps. Lancez un scan dans la colonne 3 \\u2192",tt_nap:"La compl\\u00e9tude de votre profil impacte directement votre classement local. Chaque champ manquant vous co\\u00fbte des points. Corrigez-les dans l\\u2019onglet GBP Score \\u2192",tt_control_center:"Votre tableau de bord GBP : score, avis sans r\\u00e9ponse, prochain scan planifi\\u00e9 et compl\\u00e9tude du profil \\u2014 tout en un pour prioriser ce qui compte.",clients_count_suffix:" client(s)",pool_credits:"💳 Crédits pool : ",available_word:" disponibles · ",used_word:" utilisés",never:"Jamais",today:"Aujourd\\u0027hui",yesterday:"Hier",sort_priority:"🚨 Priorité (score bas d\\u0027abord)",sort_best_score:"⭐ Meilleur score d\\u0027abord",sort_activity:"🕐 Dernière activité",sort_name:"A→Z Nom",sort_kw:"🔑 Plus de mots-clés",scan_badge:" scan(s)",kw_badge:" mots-clés",logo_too_large:"Logo trop volumineux — max 2 Mo",upload_logo:"📁 Importer un logo",or_sep:"— ou —",agency_hub_title:"Hub Agence",col_suffix:" col",cols_suffix:" cols",err_rename:"Erreur réseau lors du renommage",err_file_too_large:"Fichier trop volumineux",tip_col_keyword:"Terme de recherche suivi",tip_col_rank:"Position moyenne actuelle sur tous les points de la grille heatmap",tip_col_best:"Meilleure position jamais enregistrée",tip_col_grid:"Taille de grille du dernier scan",tip_col_status:"En attente = jamais scanné · Scanné = données disponibles",tip_col_scan:"Date + type de scan (solo ou multi)",tip_col_threat:"⚠️ Un concurrent domine le Top 3 sur 50 %+ des points de grille",filter_danger:"⚠️ Danger",filter_solo_scan:"🔍 Scan solo",filter_multi_scan:"📊 Scan multi",filter_az:"A→Z",filter_all_grids:"Toutes les grilles",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" mots-clés)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Pas encore scanné",export_col_city:"Ville",export_col_scan_type:"Type de scan",export_yes:"Oui",export_no:"Non",export_danger_yes:"⚠️ Oui",kw_report_title:"Rapport mots-clés",kw_report_generated:"Généré :",kw_report_keywords_suffix:" mots-clés",import_kw_tip:"Importer plusieurs mots-clés (un par ligne ou CSV)",add_kw_ph:"Saisir un mot-clé (ex. Plombier Paris)",import_kw_ph:"Plombier Paris\\nÉlectricien Lyon\\nCouvreur Marseille",post_char_of:" / 1500",post_add_photo:"📷 Ajouter une photo",post_photo_formats:"JPG, PNG — max 5 Mo",export_col_created:"Créé",posts_page_title:"Posts GBP",posts_report_title:"Rapport Posts GBP",photo_status_in_stock:"📚 En bibliothèque",photos_count_suffix:" photo(s)",no_photos:"Aucune photo",no_photos_sub:"Importez des photos pour constituer votre bibliothèque GBP",photo_alt_default:"Photo GBP",photo_sched_vid:"5 cr",photo_sched_img:"3 cr",err_rename_failed:"Échec du renommage",export_col_file:"Fichier",export_col_category:"Catégorie",photos_page_title:"Photos GBP",photos_report_title:"Rapport Photos GBP",photos_library_count_suffix:" photos en bibliothèque",cat_cover:"🖼️ Couverture",cat_profile:"👤 Profil",cat_logo:"🎨 Logo",cat_interior:"🏠 Intérieur",cat_exterior:"🏢 Extérieur",cat_product:"📦 Produit",cat_at_work:"💼 Au travail",cat_food_drink:"🍽️ Nourriture & boissons",cat_menu:"📋 Menu",cat_common_area:"🛋️ Espace commun",cat_rooms:"🛏️ Chambres",cat_teams:"👥 Équipes",cat_additional:"➕ Supplémentaire",rv_replied_yes:"✅ Oui",rv_replied_no:"❌ Non",export_col_reply:"Réponse",export_col_has_reply:"Répondu",reviews_page_title:"Rapport Avis",reviews_report_title:"Rapport Avis Google",reviews_pdf_avg:"⭐ Moyenne : ",reviews_pdf_reviews_suffix:" avis",export_col_criterion:"Critère",export_col_points:"Points",score_export_done:"Fait",score_export_missing:"Manquant",score_export_score:"Score",score_export_rating:"Note",score_export_photos:"Photos",score_report_title:"Rapport Score GBP",score_pdf_stats:"Statistiques",score_pdf_rating:"⭐ Note : ",score_pdf_photos:"📸 Photos : ",rel_d_ago:"j",rel_w_ago:"sem",rel_mo_ago:"mois",rel_y_ago:"an",hub_subtitle:"Gérez les paramètres agence, crédits et white-label.",hub_credit_pool:"💳 Pool de crédits",hub_tier_label:"Forfait actuel",hub_tier_t1:"Tier 1 — jusqu\u0027\u00e0 10 fiches",hub_tier_t2:"Tier 2 — jusqu\u0027\u00e0 50 fiches",hub_tier_t3:"Tier 3 — fiches illimit\u00e9es",hub_listings_gauge:"Fiches actives",hub_tier_upgrade:"Passer au forfait sup\u00e9rieur",hub_tier_downgrade:"R\u00e9duire le forfait",hub_upgrade_processing:"Redirection vers le paiement...",hub_downgrade_confirm:"Confirmer le passage \u00e0 ce forfait ?",hub_downgrade_blocked:"R\u00e9duction impossible : trop de fiches actives.",hub_downgrade_success:"Forfait mis \u00e0 jour avec succ\u00e8s.",hub_info_upgrade:"Upgrade : vous payez uniquement la diff\u00e9rence entre les forfaits (prorata).",hub_info_downgrade:"Downgrade : gratuit, sans remboursement. Bloqu\u00e9 si vos fiches actives d\u00e9passent la limite du nouveau forfait.",hub_available:"Disponibles",hub_used:"Utilisés",hub_buy_credits:"+ Acheter des crédits (gros)",hub_whitelabel:"🎨 White-label",hub_whitelabel_desc:"URL du logo et nom de marque affichés dans l\u0027embed et les exports PDF.",hub_logo_ph:"https://votrelogo.com/logo.png",hub_brand_ph:"Nom de votre agence",hub_save_settings:"Enregistrer",saved:"Enregistr\u00e9 \u2713",hub_save_alert:"Paramètres white-label — Sprint 45",hub_import_clients:"📥 Importer des clients",hub_import_csv_desc:"Format CSV : business_name, city, category, country",hub_import_csv_btn:"Importer CSV",hub_import_alert:"Import CSV — Sprint 45",hub_pro_title:"🚀 Avision Pro Agence",hub_pro_sub:"Vue hélicoptère · Actions groupées · Reporting avancé · Guardian complet",hub_pro_cta:"Passer à Avision Pro Agence →",profile_title:"Mon Profil",profile_subtitle:"Gérez vos crédits et votre compte.",profile_credits_available:"Crédits disponibles",profile_credits_used:"Utilisés",profile_buy:"+ Acheter des crédits",profile_pack_nano:"Nano — 10 crédits",profile_pack_mini:"Mini — 30 crédits",profile_pack_standard:"Standard — 75 crédits",profile_pack_pro:"Pro — 200 crédits",profile_pack_agency:"Agence — 600 crédits",profile_price_nano:"2 $",profile_price_mini:"5 $",profile_price_standard:"11 $",profile_price_pro:"25 $",profile_price_agency:"59 $",profile_save_economy:" — économisez ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Dashboard complet · Guardian \\u00b7 SEO avancé",profile_upsell_cta:"Passer à Avision Pro \\u2192",credits_modal_title:"💳 Vos crédits LocalEdge",credits_modal_solo_p1:"Vos crédits LocalEdge sont permanents — ils n\u0027expirent jamais. Achetez quand vous en avez besoin, utilisez-les à votre rythme.",credits_modal_usage_title:"Où dépenser vos crédits :",credits_modal_heatmap:"🗺️ Scan heatmap — de 2 cr (3×3) à 60 cr (21×21)",credits_modal_post:"📝 Publication GBP Post via AVI — 3 cr",credits_modal_photo:"📷 Synchronisation photo GBP — 2 cr",credits_modal_guardian:"🔔 Guardian (surveillance fiche) — gratuit, inclus",credits_modal_savings_title:"Plus vous achetez, moins vous payez par crédit.",credits_modal_savings_sub:"Le pack Pro à $25 coûte 38% moins cher par crédit que le pack Nano.",credits_modal_agency_title:"💳 Votre pool de crédits agence",credits_modal_agency_p1:"Votre pool est partagé entre toutes vos fiches clients. Achetez en gros, distribuez selon vos besoins.",credits_modal_agency_wholesale:"Tarif wholesale — vos crédits agence coûtent jusqu\u0027à 47% moins cher que le tarif standard. Votre marge est libre.",credits_modal_agency_noexpiry:"Pas d\u0027expiration — vos crédits restent disponibles indéfiniment.",purchase_success_title:"\u2713 Paiement re\u00e7u\u00a0!",purchase_success_sub:"Vos cr\u00e9dits seront disponibles dans quelques secondes.",purchase_success_close:"Compris",slider_title:"Ou choisissez votre montant",slider_credits:"cr\u00e9dits",slider_price_per:"par cr\u00e9dit",slider_vs_nano:"vs Nano",slider_buy_btn:"Acheter",slider_min_label:"10 cr",slider_max_label_solo:"1\u00a0000 cr",slider_max_label_agency:"5\u00a0000 cr",client_balance:"Solde client",cr_need:"Requis",cr_available:"Disponible",cr_missing:"Manquant",days_ago:"j",attr_other:"Autre",anonymous_reviewer:"Anonyme",error_generic:"Une erreur est survenue.",vs_standard:"vs standard",badge_discount_17:"-17\u00a0%",badge_discount_27:"-27\u00a0%",badge_discount_38:"-38\u00a0%",badge_discount_16:"-16\u00a0%",badge_discount_30:"-30\u00a0%",badge_discount_40:"-40\u00a0%",badge_discount_47:"-47\u00a0%",ag_pack_starter:"Starter Agence — 100 crédits",ag_pack_standard:"Standard Agence — 300 crédits",ag_pack_pro:"Pro Agence — 750 crédits",ag_pack_enterprise:"Entreprise Agence — 2000 crédits",ag_price_starter:"14$",ag_price_standard:"35$",ag_price_pro:"75$",ag_price_enterprise:"175$",logo_preview_alt:"Aperçu du logo",hub_uploaded_file:"(fichier importé)",ag_no_scan:"🗺️ Aucun scan",gbp_open_title:"Ouvrir la fiche GBP : ",gbp_search_title:"Rechercher sur Google Maps : ",gbp_score:"Score GBP",unanswered:"Sans r\u00e9ponse",unanswered_sub:"avis \u00e0 r\u00e9pondre",credits_left:"Cr\u00e9dits",next_scan:"Prochain scan",no_scan:"Aucun scan",nap_status:"Compl\u00e9tude profil",nap_name:"Nom",nap_address:"Adresse",nap_phone:"T\u00e9l\u00e9phone",nap_website:"Site web",nap_hours:"Horaires",nap_desc:"Description",fix_it:"Compl\u00e9ter \\u2192",edit:"Modifier",fix:"Corriger",edit_name:"Modifier le nom",name_warn:"Modifier le nom peut d\u00e9clencher une v\u00e9rification Google. Utilisez votre vrai nom commercial.",edit_website:"Modifier le site web",edit_phone:"Modifier le t\u00e9l\u00e9phone",edit_hours:"Modifier les horaires",edit_description:"Modifier la description",edit_categories:"Modifier les cat\u00e9gories",edit_address:"Modifier l\u2019adresse",edit_success:"Mis \u00e0 jour avec succ\u00e8s sur Google !",edit_error:"Erreur lors de la mise \u00e0 jour. Veuillez r\u00e9essayer.",lodging_posts_warn:"Les posts GBP ne sont pas disponibles pour les h\u00f4tels et h\u00e9bergements. Google r\u00e9serve cet espace aux plateformes de r\u00e9servation.",hours_closed:"Ferm\u00e9",hours_open:"Ouvert",cat_search_placeholder:"Rechercher des cat\u00e9gories Google...",cat_primary:"Cat\u00e9gorie principale",cat_additional:"Cat\u00e9gories suppl\u00e9mentaires (max 9)",cat_lodging_warn:"Modifier votre cat\u00e9gorie principale peut affecter les fonctionnalit\u00e9s de votre profil.",addr_neighborhood:"Quartier / Arrondissement",addr_street:"Adresse",addr_city:"Ville",addr_region:"\u00c9tat / R\u00e9gion",addr_postal:"Code postal",addr_country:"Code pays (ex. FR)",verified:"Vérifié",pending_verification:"Vérification en attente",not_verified:"Non vérifié",verify_cta_text:"Votre fiche n\u2019est pas v\u00e9rifi\u00e9e sur Google. Les fiches v\u00e9rifi\u00e9es b\u00e9n\u00e9ficient de plus de visibilit\u00e9.",verify_cta_btn:"V\u00e9rifier ma fiche \u2192",verify_pending_text:"V\u00e9rification en cours. Google peut prendre jusqu\u2019\u00e0 7 jours.",score_panel_sub:"Votre score d\u0027optimisation Google Business Profile. Chaque champ compl\u00e9t\u00e9 am\u00e9liore votre visibilit\u00e9 dans les r\u00e9sultats de recherche locale.",score_info_title:"Score GBP \u2014 Comment \u00e7a marche",score_info_s1_title:"\uD83C\uDFAF Comment le score est calcul\u00e9",score_info_s1_body:"Base 30 pts + Site web (+5) + Horaires (+3) + Description 200+ car. (+2) + Cat\u00e9gorie additionnelle (+1) + Attributs \u22653 (+1). Maximum : 42 pts.",score_info_s2_title:"\uD83D\uDCC8 Pourquoi c\u0027est important",score_info_s2_body:"Un profil complet et optimis\u00e9 se classe mieux dans le Pack Local Google. Chaque champ manquant vous co\u00fbte de la visibilit\u00e9 en recherche locale.",score_info_s3_title:"\u270F\uFE0F Comment am\u00e9liorer",score_info_s3_body:"Cliquez sur Modifier ou Corriger sur chaque crit\u00e8re pour mettre \u00e0 jour directement depuis LocalEdge \u2014 sans ouvrir votre fiche Google.",gbp_attributes_title:"Attributs GBP",attr_na:"N/A pour cette cat\u00e9gorie",attr_url_gbp_hint:"Modifier sur Google Business Profile",attrs_filled:"Renseign\u00e9s",crit_posts:"Publications r\u00e9centes",crit_photos:"Photos publi\u00e9es",photos_published_label:"publi\u00e9es",photos_min:"min. 3 recommand\u00e9es",post_stale:"Dernier post > 7 jours \u2014 publiez pour garder vos points",post_fresh:"Frais \u2014 publi\u00e9 dans les 7 derniers jours",post_upsell:"Planifiez un post pour maintenir votre score",photo_stale:"Derni\u00e8re photo > 7 jours \u2014 publiez pour garder vos points",photo_fresh:"Fra\u00eeche \u2014 photo publi\u00e9e dans les 7 derniers jours",photo_upsell:"Publiez une photo pour maintenir votre score",crit_reviews_reply:"Dernier avis r\u00e9pondu",replied:"R\u00e9pondu",not_replied:"Non r\u00e9pondu",no_reviews_yet:"Aucun avis encore",freshness_note:"Votre score fluctue selon votre activit\\u00e9 : publications, photos, r\\u00e9ponses aux avis, compl\\u00e9tude du profil et scans heatmap impactent votre classement. Restez actif pour maximiser vos points.",view:"Voir",reply:"R\u00e9pondre",attr_saved:"Attribut mis \u00e0 jour",attr_error:"\u00c9chec de la mise \u00e0 jour",attrs_load_error:"Impossible de charger les attributs",attrs_load_hint:"Cliquez sur \uD83D\uDD04 Sync from Google pour recharger",hm_section_title:"🗺️ Visibilité Heatmap",hm_info_title:"Heatmap — Pourquoi ça change tout",hm_info_s1_title:"📍 Connaissez votre position exacte",hm_info_s1_body:"Chaque scan cartographie votre position sur Google Maps sur chaque point de votre grille de quartier. Vous voyez exactement où vous dominez et où les concurrents vous devancent — rue par rue.",hm_info_s2_title:"🏆 Analysez vos concurrents",hm_info_s2_body:"La heatmap révèle quels concurrents occupent le top 3 sur chaque point de la grille. Identifiez qui dépasser, sur quelles zones, et adaptez votre stratégie SEO local en conséquence.",hm_info_s3_title:"📐 Taille de grille = contrôle du territoire",hm_info_s3_body:"Une grille 7x7 couvre votre quartier immédiat. Une grille 13x13 cartographie toute votre ville. Plus votre grille est grande, plus vous contrôlez de territoire et plus vous avez de données pour décider.",hm_info_s4_title:"🔄 Scans réguliers = gains de positions",hm_info_s4_body:"Scannez le même mot-clé chaque semaine pour suivre votre progression. Chaque scan utilise des crédits mais vous donne des données actionnables : gagnez-vous ou perdez-vous des positions ? Réagissez avant que vos concurrents ne prennent vos places.",hm_activity_label:"Activité scans",hm_performance_label:"Performance locale",hm_coverage_label:"Couverture territoire",hm_scan_now:"Lancer un scan",hm_stale_warn:"Aucun scan depuis 30+ jours — vos données sont obsolètes",hm_no_scan:"Aucun scan encore — commencez à cartographier votre territoire",control_center:"Centre de contr\u00f4le",guardian_badge:"\ud83d\udd14 Alertes",guardian_modal_title:"Guardian Lite \u2014 Alertes profil",guardian_no_alerts:"Aucune alerte d\u00e9tect\u00e9e",guardian_plan_free:"Plan gratuit \u2014 pas de surveillance",guardian_plan_lite:"Lite \u2014 scan 1x\/mois",guardian_plan_standard:"Standard \u2014 scan hebdomadaire",guardian_plan_daily:"Scan quotidien actif",guardian_field_title:"Nom de l\u2019entreprise modifi\u00e9",guardian_field_phone:"Num\u00e9ro de t\u00e9l\u00e9phone modifi\u00e9",guardian_field_categories:"Cat\u00e9gorie modifi\u00e9e",guardian_field_hours:"Horaires modifi\u00e9s",guardian_field_website:"Site web modifi\u00e9",guardian_field_openInfo:"Statut ouvert\/ferm\u00e9 modifi\u00e9",guardian_why_title:"Pourquoi surveiller votre fiche ?",guardian_why_1:"N\u2019importe qui peut sugg\u00e9rer des modifications sur votre GBP \u2014 y compris vos concurrents",guardian_why_2:"Les Local Guides ont un pouvoir important et peuvent marquer votre \u00e9tablissement comme ferm\u00e9",guardian_why_3:"Des modifications non d\u00e9tect\u00e9es entra\u00eenent une chute de classement et une perte de visibilit\u00e9",guardian_fix_btn:"Corriger dans GBP Score \u2192",guardian_mark_read:"Tout marquer comme lu",guardian_detected:"D\u00e9tect\u00e9 le :",guardian_old:"Avant :",guardian_new:"Apr\u00e8s :",guardian_verify:"v\u00e9rifier imm\u00e9diatement",guardian_fix_now:"Corriger maintenant",guardian_field_address:"Adresse",guardian_field_description:"Description",guardian_field_specialHours:"Horaires sp\u00e9ciaux",guardian_field_serviceArea:"Zone de service",crit_special_hours:"Horaires sp\u00e9ciaux",crit_service_area:"Zone de service",special_hours_edit_info:"Les horaires sp\u00e9ciaux doivent \u00eatre g\u00e9r\u00e9s directement sur Google Business Profile.",service_area_edit_info:"La zone de service doit \u00eatre g\u00e9r\u00e9e directement sur Google Business Profile.",guardian_changed:"modifi\u00e9",guardian_fix_gbp:"Corriger sur GBP \u2192",crit_open_status:"Statut de l\u2019\u00e9tablissement",open_info_warn:"La modification de ce statut mettra \u00e0 jour votre fiche Google Business Profile imm\u00e9diatement.",open_status_open:"Ouvert \u2014 Horaires normaux",open_status_temp:"Ferm\u00e9 temporairement \u2014 r\u00e9ouverture pr\u00e9vue",open_status_perm:"Ferm\u00e9 d\u00e9finitivement \u2014 \u00e0 v\u00e9rifier d\u2019urgence",open_status_open_no_hours:"Ouvert \u2014 Sans horaires principaux",open_status_unknown:"Statut inconnu",cit_title:"Citations",cit_listed:"ajout\u00e9es",cit_done:"Ajout\u00e9",cit_mark_done:"\u2713 Ajout\u00e9",cit_already:"D\u00e9j\u00e0 list\u00e9",cit_mark_already:"\u2713 D\u00e9j\u00e0 list\u00e9",cit_trust:"Nous vous faisons confiance \u2014 nous ne v\u00e9rifions pas automatiquement",cit_url_placeholder:"URL de votre fiche (optionnel)",cit_section_universal:"\ud83c\udf0d Universels",cit_section_local:"\ud83c\udff3\ufe0f France",cit_section_niche:"\ud83c\udfaf Votre secteur",cit_todo:"\ud83d\udccb \u00c0 faire",cit_completed:"Compl\u00e9t\u00e9s",cit_collapse:"\u25b2 R\u00e9duire",cit_expand:"\u25bc D\u00e9velopper",cit_undo:"\u21a9 Annuler",cit_remove:"Supprimer",cit_add_name:"Nom de l\u0027annuaire",cit_add_url:"https://...",cit_add_btn:"+ Ajouter",cit_banner_msg:"Nous avons s\u00e9lectionn\u00e9 automatiquement des annuaires bas\u00e9s sur votre cat\u00e9gorie Google Business \"{cat}\". Certaines suggestions peuvent ne pas correspondre parfaitement \u2014 n\u0027h\u00e9sitez pas \u00e0 les supprimer ou \u00e0 en ajouter.",cit_your_category:"votre cat\u00e9gorie",cit_panel_sub:"Suivez vos inscriptions dans les annuaires pour am\u00e9liorer votre visibilit\u00e9 SEO local.",cit_info_title:"Citations & SEO Local",cit_info_s1_title:"\ud83d\udccd Qu\u0027est-ce qu\u0027une citation ?",cit_info_s1_body:"Une citation est toute mention en ligne de votre nom d\u0027entreprise, adresse et num\u00e9ro de t\u00e9l\u00e9phone (NAP). Les moteurs de recherche utilisent les citations pour v\u00e9rifier la l\u00e9gitimit\u00e9 de votre entreprise et am\u00e9liorer votre classement local.",cit_info_s2_title:"\u26a0\ufe0f La coh\u00e9rence NAP est critique",cit_info_s2_body:"Votre nom, adresse et t\u00e9l\u00e9phone doivent \u00eatre exactement identiques dans tous les annuaires \u2014 m\u00eames abr\u00e9viations, m\u00eame ponctuation, m\u00eame format. La moindre diff\u00e9rence d\u00e9route les moteurs de recherche et nuit \u00e0 votre classement.",cit_info_s3_title:"\ud83c\udfaf Pourquoi ces annuaires ?",cit_info_s3_body:"Nous avons s\u00e9lectionn\u00e9 automatiquement des annuaires selon votre cat\u00e9gorie Google Business et votre localisation. Certaines suggestions de niche peuvent ne pas correspondre \u2014 supprimez-les ou ajoutez les v\u00f4tres.",cit_info_s4_title:"\u2705 D\u00e9j\u00e0 list\u00e9 ?",cit_info_s4_body:"Si votre entreprise est d\u00e9j\u00e0 dans un annuaire, cliquez sur \u2018D\u00e9j\u00e0 list\u00e9\u2019 et ajoutez optionnellement l\u0027URL. Nous vous faisons confiance \u2014 nous ne v\u00e9rifions pas automatiquement, mais nous pourrons le faire \u00e0 l\u0027avenir.",cit_score_section:"\ud83d\udccb Citations",cit_score_label:"Annuaires",cit_score_detail:"annuaires renseign\u00e9s",cit_stale_warn:"Ajoutez un annuaire pour maintenir votre score",sh_title:"Historique Score & Rang",sh_daily:"Journalier",sh_score:"Score GBP",sh_rank:"Rang moyen",sh_drop:"Chute",sh_all_kw:"Tous les mots-cl\\u00e9s",sh_no_data:"Pas encore de donn\\u00e9es. Lancez un scan heatmap pour commencer le suivi.",sh_start:"D\\u00e9but",sh_now:"Maintenant",sh_best_rank:"Meilleur rang",sh_info_title:"Comprendre l\\u0027historique Score & Rang",sh_info_s1_title:"\\ud83d\\udcc8 Score GBP (violet)",sh_info_s1_body:"Votre score d\\u0027optimisation Google Business Profile de 0 \\u00e0 100. Il monte quand vous compl\\u00e9tez votre fiche, ajoutez des photos, obtenez des avis et corrigez les alertes Guardian.",sh_info_s2_title:"\\ud83d\\udccd Rang moyen (ambre)",sh_info_s2_body:"Votre position moyenne dans les r\\u00e9sultats Google Maps sur tous les points de la grille heatmap. Plus bas = mieux \\u2014 rang #1 signifie que vous apparaissez en premier.",sh_info_s3_title:"\\u26a0\\ufe0f Pourquoi mon rang fluctue-t-il ?",sh_info_s3_body:"Le rang GBP varie selon la position g\\u00e9ographique du chercheur, le mot-cl\\u00e9 utilis\\u00e9, l\\u0027heure de la journ\\u00e9e et les mises \\u00e0 jour de l\\u0027algorithme Google. C\\u0027est normal \\u2014 suivez la tendance, pas les points individuels.",sh_info_s4_title:"\\ud83d\\udd34 Points rouges",sh_info_s4_body:"Un point rouge signale une chute importante : -10 pts ou plus sur le score, ou +5 positions perdues sur le rang. Ce sont des moments \\u00e0 investiguer \\u2014 v\\u00e9rifiez les alertes Guardian pour cette date.",tab_profile:"Profil",tab_attributes:"Attributs",tab_history:"Historique",card_nap:"NAP & Infos",card_online:"Présence en ligne",card_activity:"Activité",card_visibility:"Visibilité",sh_fullscreen:"Plein écran",sh_exit_fs:"Quitter",card_nap_info_title:"NAP & SEO Local",card_nap_s1_title:"📍 Qu\\u0027est-ce que le NAP ?",card_nap_s1_body:"NAP signifie Nom, Adresse et Téléphone. Les moteurs de recherche utilisent votre NAP pour vérifier l\\u0027existence et la légitimité de votre entreprise. Un NAP incohérent nuit à votre référencement local.",card_nap_s2_title:"🎯 Pourquoi c\\u0027est important",card_nap_s2_body:"Google compare votre GBP avec d\\u0027autres annuaires. Si votre nom ou adresse diffère, cela crée un doute et réduit votre positionnement local.",card_nap_s3_title:"✅ Que faire",card_nap_s3_body:"Gardez votre nom, adresse, t\u00e9l\u00e9phone et cat\u00e9gorie strictement identiques sur Google Business Profile et tous les annuaires. Utilisez l\u0027onglet Citations pour suivre vos inscriptions.",card_nap_s4_title:"\u26a0\ufe0f Risque de re-v\u00e9rification ou suspension",card_nap_s4_body:"Évitez de modifier votre cat\u00e9gorie, description ou informations cl\u00e9s trop rapidement. Les algorithmes de Google ont besoin de temps pour int\u00e9grer les changements. Trop de modifications rapides peuvent d\u00e9clencher une proc\u00e9dure de re-v\u00e9rification voire une suspension de votre fiche.",card_online_info_title:"Présence en ligne",card_online_s1_title:"🌐 Site web",card_online_s1_body:"Un site web vérifié lié à votre GBP renforce la confiance et ajoute +5 pts à votre score. Assurez-vous qu\\u0027il se charge correctement.",card_online_s2_title:"🕒 Horaires d\\u0027ouverture",card_online_s2_body:"Des horaires exacts aident les clients à vous trouver. L\\u0027absence d\\u0027horaires coûte -3 pts et réduit vos chances d\\u0027apparaître dans les recherches « Ouvert maintenant ».",card_online_s3_title:"📝 Description",card_online_s3_body:"Une bonne description aide Google à comprendre ce que fait votre entreprise. Incluez naturellement vos services principaux et votre localisation. L\\u0027absence coûte -2 pts.",card_activity_info_title:"Activité & Engagement",card_activity_s1_title:"📸 Posts Google",card_activity_s1_body:"Publier des posts régulièrement indique à Google que votre entreprise est active. Un post dans les 7 derniers jours vous donne +5 pts.",card_activity_s2_title:"🖼️ Photos",card_activity_s2_body:"Les entreprises avec photos reçoivent 42% de demandes d\\u0027itinéraire en plus. Des photos fraîches publiées dans les 7 jours rapportent le maximum de pts.",card_activity_s3_title:"⭐ Réponses aux avis",card_activity_s3_body:"Répondre aux avis montre à Google et aux clients que vous êtes actif. Répondez à votre dernier avis pour gagner +3 pts.",card_visibility_info_title:"Visibilité Locale",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"La heatmap montre où vous vous classez sur Google Maps dans votre zone. Faites des scans réguliers pour suivre votre position.",card_visibility_s2_title:"📋 Citations",card_visibility_s2_body:"Les citations sont des mentions de votre entreprise dans les annuaires. Plus de citations cohérentes = plus de confiance de Google.",card_visibility_s3_title:"📈 Suivre votre progression",card_visibility_s3_body:"Utilisez l\\u0027onglet Historique pour voir l\\u0027évolution de votre score et rang local. Un score croissant avec un rang qui baisse signifie que votre SEO local fonctionne.",card_see_more:"Voir plus",card_see_less:"Voir moins",attrs_info_title:"Attributs GBP — Ce que vous devez savoir",attrs_info_s1_title:"🔧 Que sont les attributs GBP ?",attrs_info_s1_body:"Les attributs sont des informations compl\u00e9mentaires sur votre \u00e9tablissement qui aident les clients \u00e0 prendre des d\u00e9cisions — accessibilit\u00e9, modes de paiement, parking, services disponibles, etc. Ils apparaissent directement sur votre fiche Google Business Profile.",attrs_info_s2_title:"📍 Pourquoi c\u0027est important pour le SEO local",attrs_info_s2_body:"Des attributs complets indiquent \u00e0 Google que votre fiche est d\u00e9taill\u00e9e et fiable. Ils aident aussi votre \u00e9tablissement \u00e0 appara\u00eetre dans des recherches filtr\u00e9es — par exemple les clients qui cherchent un \u00e9tablissement \u00ab accessible en fauteuil roulant \u00bb ou avec \u00ab parking gratuit \u00bb.",attrs_info_s3_title:"⚠️ Important — Certains attributs ne peuvent pas \u00eatre modifi\u00e9s ici",attrs_info_s3_body:"Google contr\u00f4le les attributs disponibles selon la cat\u00e9gorie de votre \u00e9tablissement. Certains attributs ne peuvent \u00eatre modifi\u00e9s que directement sur Google Business Profile. Si un attribut ne r\u00e9pond pas aux modifications effectu\u00e9es ici, mettez-le \u00e0 jour directement sur business.google.com.",attr_url_hint:"Ajoutez ces URLs pour am\u00e9liorer votre visibilit\u00e9 sur Google. Pour les liens de r\u00e9servation, allez sur Google Business Profile \u2192 Modifier le profil \u2192 R\u00e9servation.",guardian_home_title:"Guardian",guardian_home_status:"Actif",guardian_checking:"V\u00e9rification...",guardian_disconnected:"D\u00e9connect\u00e9",guardian_home_subtitle:"Surveille votre fiche 24h\/24",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 Votre sentinelle GBP",guardian_info_s1_title:"\ud83d\udd0d Ce que Guardian surveille",guardian_info_s1_body:"Guardian surveille 10 champs cl\u00e9s de votre fiche Google Business Profile\u00a0: nom, adresse, t\u00e9l\u00e9phone, site web, cat\u00e9gorie principale, horaires, description, statut ouvert\/ferm\u00e9, photos de couverture et attributs.",guardian_info_s2_title:"\u26a0\ufe0f Pourquoi c\u0027est crucial",guardian_info_s2_body:"N\u0027importe qui \u2014 y compris des concurrents ou Google lui-m\u00eame \u2014 peut proposer des modifications \u00e0 votre fiche. Des changements non d\u00e9tect\u00e9s peuvent faire chuter votre positionnement du jour au lendemain. Guardian vous alerte imm\u00e9diatement pour que vous puissiez r\u00e9agir.",guardian_info_s3_title:"\u2705 Ce que Guardian ne fait PAS",guardian_info_s3_body:"Guardian n\u0027am\u00e9liore pas votre positionnement. Continuez \u00e0 optimiser votre GBP, publier des posts, r\u00e9pondre aux avis et am\u00e9liorer votre score. Guardian prot\u00e8ge la visibilit\u00e9 que vous avez d\u00e9j\u00e0 acquise \u2014 il ne cr\u00e9e pas de nouvelle visibilit\u00e9.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 Inclus dans votre forfait",guardian_info_s4_body:"Guardian Lite surveille 10 champs GBP cl\u00e9s 24h/24 et vous alerte d\u00e8s qu\u2019un changement suspect est d\u00e9tect\u00e9. La surveillance est toujours incluse dans votre forfait \u2014 les cr\u00e9dits ne sont utilis\u00e9s que lorsque AVI corrige automatiquement un changement (3 cr\u00e9dits/mois inclus \u00b7 2 cr\u00e9dits par correction).",guardian_info_cta:"Compris \u2713",guardian_trial_ended:"Essai termin\u00e9 \u2014 cr\u00e9dits actifs",guardian_trial_active:"Essai gratuit actif",guardian_trial_days_left:"jours restants dans l\u2019essai gratuit",guardian_pricing_detail:"Apr\u00e8s l\u2019essai\u00a0: 3 cr\u00e9dits/mois + 2 cr\u00e9dits par modification d\u00e9tect\u00e9e",guardian_pricing_detail_active:"3 cr\u00e9dits/mois \u00b7 2 cr\u00e9dits par modification d\u00e9tect\u00e9e",guardian_disabled_title:"D\u00e9sactiv\u00e9",guardian_disabled_warn:"Votre fiche n\u2019est plus surveill\u00e9e. Les concurrents peuvent modifier votre GBP sans que vous le sachiez.",guardian_activate:"Activer Guardian \u2192",guardian_credits_active:"Cr\u00e9dits actifs",guardian_deactivate:"D\u00e9sactiver Guardian",guardian_post_trial_status:"\u26a0\ufe0f Essai termin\u00e9",guardian_post_trial_warning:"\u26a0\ufe0f Votre fiche est maintenant expos\u00e9e. Concurrents et Local Guides peuvent modifier votre GBP \u00e0 tout moment \u2014 des modifications non d\u00e9tect\u00e9es entra\u00eenent des baisses de classement, des horaires erron\u00e9s et des appels perdus.",guardian_deactivate_warn:"Si vous d\u00e9sactivez, les modifications de votre fiche passeront enti\u00e8rement inaper\u00e7ues. Vous ne serez pas alert\u00e9 si un concurrent vous marque comme ferm\u00e9.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Surveill\u00e9 par Guardian \u2014 essai gratuit actif",guardian_tooltip_active:"\u26A0\uFE0F Essai termin\u00e9 \u2014 cr\u00e9dits actifs. Cliquez \u2139\uFE0F sur l\u2019accueil pour g\u00e9rer.",guardian_low_credits_title:"Cr\u00e9dits faibles \u2014 Guardian en danger",guardian_low_credits_warn:"Vous avez moins de 10 cr\u00e9dits. Guardian pourrait cesser de surveiller bient\u00f4t.",guardian_credits_remaining:"Cr\u00e9dits restants\u00a0:",guardian_buy_credits:"Acheter des cr\u00e9dits \u2192",guardian_trial_expired_title:"Essai gratuit termin\u00e9",guardian_trial_expired_warn:"Votre essai gratuit de 15 jours est termin\u00e9. Activez Guardian pour continuer \u00e0 surveiller votre fiche.",guardian_trial_expired_badge:"\u23f1\ufe0f Essai termin\u00e9 \u2014 activez pour continuer",guardian_paid_active_title:"Guardian Actif",guardian_next_billing:"Prochain d\u00e9bit\u00a0:",guardian_tooltip_off:"Guardian d\u00e9sactiv\u00e9 \u2014 ce champ n\u2019est plus surveill\u00e9"},'
			. 'es:{close:"Cerrar",cancel:"Cancelar",save:"Guardar",delete:"Eliminar",'
			. 'search_kw:"Buscar palabra clave...",add_kw:"+ Añadir palabra clave",add_keyword:"+ Añadir palabra clave",'
			. 'confirm_delete_scan:"¿Eliminar este escaneo programado?",'
			. 'kw_my_keywords:"Mis palabras clave",kw_panel_title:"Mis palabras clave",kw_panel_sub:"Rastrea los t\u00e9rminos de b\u00fasqueda que importan para tu visibilidad local. Cada palabra clave puede escanearse en el mapa de calor para mostrar tu posici\u00f3n en Google Maps en tu zona.",more:"m\u00e1s",'
			. 'import_kw:"📥 Importar",export_kw:"📤 Exportar",'
			. 'export_csv:"📊 Exportar CSV",export_pdf:"📄 Exportar PDF",'
			. 'import_label:"Pegue sus palabras clave — una por línea o separadas por coma:",'
			. 'import_btn:"Importar",scan_kw:"Escanear esta palabra clave",'
			. 'no_kw:"Sin palabras clave — añada su primera palabra clave arriba",'
			. 'scanned:"✅ Escaneado",pending:"⬜ Pendiente",threat:"⚠️ Amenaza",'
			. 'actions:"Acciones",'
			. 'col_keyword:"Palabra clave",col_rank:"Posición",col_best:"Mejor posición",'
			. 'col_grid:"Cuadrícula",col_status:"Estado",col_scan:"Último escaneo",'
			. 'col_threat:"Amenaza",publish_now:"Publicar ahora",schedule_post:"Programar publicación",schedule_post_credits:"Programar (2 créditos)",publishing:"Publicando...",scheduling:"Programando...",new_post:"Nueva publicación GBP",edit_post:"Editar publicación",posts_panel_title:"Publicaciones GBP",posts_panel_sub:"Crea y gestiona tus publicaciones de Google Business Profile. Las publicaciones regulares mejoran tu visibilidad e informan a tus clientes sobre ofertas, noticias y eventos.",posts_info_title:"Publicaciones GBP — C\u00f3mo funciona",posts_info_s1_title:"📝 Crea contenido",posts_info_s1_body:"Redacta publicaciones (oferta, noticia, evento) directamente desde LocalEdge. AVI puede redactarlas por ti en un clic.",posts_info_s2_title:"📅 Programa",posts_info_s2_body:"Planifica tus publicaciones con antelaci\u00f3n para mantener una presencia regular en Google.",posts_info_s3_title:"📈 Aumenta tu visibilidad",posts_info_s3_body:"Google favorece los perfiles activos. Se recomienda un m\u00ednimo de 1 publicaci\u00f3n por semana para aparecer en el Pack Local.",upgrade_posts_title:"✨ Automatiza tus Publicaciones GBP",upgrade_posts_sub:"Avision Pro publica autom\u00e1ticamente · Modo autopiloto disponible",new_post_btn:"+ Nueva publicación",write_content:"Contenido (máx. 1500 caracteres)",write_content_ph:"Escriba el contenido de su publicación...",scheduled_date:"Fecha y hora programadas",no_content:"Sin contenido",post_type_label:"Tipo de publicación",post_type_update:"📢 Actualización — Noticias y anuncios",post_type_offer:"🏷️ Oferta — Promociones",post_type_event:"📅 Evento — Actividades",post_type_update_short:"📢 Actualización",post_type_offer_short:"🏷️ Oferta",post_type_event_short:"📅 Evento",credits_info:"💳 Esto usará 2 créditos de su saldo.",credits_2:"2 créditos",publication:"Publicación",publish_now_title:"⚡ Publicar ahora",schedule_title:"🕐 Programar",free:"Gratis",photo_optional:"Foto (opcional)",upload_device:"📁 Subir desde dispositivo",choose_photos:"🖼️ Elegir de Fotos",gallery_soon:"Próximamente — configure su galería primero",gallery_first_alert:"Configure primero su galería GBP Photos (pestaña Fotos).",image_too_large:"Imagen demasiado grande — máx. 5 MB",err_no_content:"Introduzca el contenido de la publicación.",err_content_long:"El contenido supera 1500 caracteres.",err_no_schedule:"Seleccione una fecha programada.",err_create_post:"Error al crear la publicación",err_network:"Error de red",err_generic:"Error",no_posts:"Sin publicaciones aún",no_posts_sub:"Cree su primera publicación GBP para atraer clientes",posts_count_suffix:" publicación(es)",event_title:"Título del evento",event_title_ph:"ej. Rebajas de verano",start_date:"Fecha de inicio",end_date:"Fecha de fin",filter_all:"Todos",post_status_published:"✅ Publicado",post_status_scheduled:"🕐 Programado",post_status_pending:"⏳ Pendiente",post_status_failed:"❌ Fallido",post_status_draft:"📝 Borrador",view_btn:"👁 Ver",th_type:"Tipo",th_content:"Contenido",th_status:"Estado",th_scheduled:"Programado",th_published:"Publicado",th_actions:"Acciones",sync_gbp:"🔄 Sincronizar desde GBP",syncing:"Sincronizando...",publish_photo:"⚡ Publicar",schedule_photo:"🕐 Programar",delete_photo_title:"Eliminar de la biblioteca",delete_confirm:"¿Eliminar este medio de la biblioteca?",rename_hint:"Clic para renombrar",change_category:"Clic para cambiar categoría",no_category:"Sin categoría",upload_photo:"+ Subir foto",'
			. 'select_photo_picker:"📎 Seleccione una foto para su publicación",schedule_date_prompt:"Fecha y hora (AAAA-MM-DDTHH:MM):",saving:"Guardando...",select_btn:"✓ Seleccionar",copy_url:"Copiar URL",video_badge:"🎬 Vídeo",sync_failed:"Error de sincronización",photos_sync_success:"\u2705 Fotos sincronizadas desde Google",delete_gbp_title:"Eliminar de GBP",delete_gbp_confirm:"¿Eliminar esta foto de tu perfil de Google? Esta acción no se puede deshacer.",delete_gbp_success:"Foto eliminada de GBP",delete_gbp_error:"Error al eliminar de GBP",bulk_download:"Descargar selección",bulk_delete:"Eliminar de la library",bulk_delete_confirm:"¿Eliminar {n} foto(s) de la library?",bulk_delete_success:"{n} foto(s) eliminada(s) de la library",bulk_gbp_note:"\u26a0\ufe0f Google no permite la eliminación masiva de fotos \u2014 elimínalas una por una.",selected:"seleccionada(s)",select_category:"— Seleccionar categoría (oficial Google) —",rename_ph:"Nombre optimizado (ej. fontanero-madrid-servicio.jpg)",show_less_cats:"▲ Mostrar menos",show_all_cats:"▼ Todas las categorías GBP",photos_panel_title:"Fotos GBP",photos_panel_sub:"Gestiona tus fotos de Google Business Profile: sube, organiza, publica y optimiza para el SEO local.",photos_info_title:"Fotos GBP — C\u00f3mo funciona",photos_info_s1_title:"📚 Library / Published / Not Published",photos_info_s1_body:"Library = todas tus fotos almacenadas en LocalEdge. Published = visibles en tu perfil de Google. Not Published = subidas pero a\u00fan no enviadas a Google.",photos_info_s2_title:"🗂️ Categor\u00edas",photos_info_s2_body:"Organiza tus fotos por categor\u00eda (exterior, interior, equipo, productos…). Un perfil bien organizado genera m\u00e1s confianza en los clientes.",photos_info_s3_title:"✏️ Renombrar para SEO",photos_info_s3_body:"El nombre de tu foto importa para el SEO. Usa nombres descriptivos con tus palabras clave (ej: \'restaurante-italiano-paris-terraza\'). Haz clic en el icono de l\u00e1piz para renombrar.",photos_info_s4_title:"⬇️ Descargar & 🗑️ Eliminar",photos_info_s4_body:"Use \u0027\u2b07\ufe0f Descargar\u0027 para guardar una foto. \u0027\ud83d\uddd1\ufe0f Eliminar de la library\u0027 la quita solo de LocalEdge. \u0027\ud83c\udf10 Eliminar de GBP\u0027 la elimina permanentemente de tu perfil de Google (irreversible).",upgrade_photos_title:"✨ Mant\u00e9n siempre fotos actualizadas",upgrade_photos_sub:"Avision Pro programa y publica tus fotos autom\u00e1ticamente para mantener tu perfil siempre activo · Modo autopiloto",photos_filter_library:"📚 Biblioteca",photos_filter_gbp_pub:"✅ Publicado en GBP",photos_filter_gbp_unpub:"📚 No publicado",photo_category_label:"Categoría de foto",filter_all_cats:"Todas las categorías",download_label:"Descargar",upload_drag:"Arrastre y suelte fotos aquí",upload_drag_sub:"Fotos JPG/PNG (máx. 5 MB) · Vídeos MP4 (máx. 75 MB, 30s)",reply_btn:"💬 Responder",cancel_reply:"Cancelar",publish_reply:"Publicar respuesta",publishing_reply:"Publicando...",reply_published:"\\u00a1Respuesta publicada en Google!",write_reply_ph:"Escriba su respuesta...",avi_writes_review:"✨ AVI escribe",avi_rewrite_reply:"✨ Reescribir con AVI",edit_reply:"\\u270F\\uFE0F Editar",generating_reply:"✨ Generando...",regenerate_reply:"↺ Regenerar",ai_reply_error:"AVI no pudo generar una respuesta.",your_reply:"💬 Su respuesta · ",no_reviews:"No se encontraron reseñas",no_reviews_filter:"Ninguna reseña coincide con este filtro",reviews_0:"0 reseñas",reviews_showing:"Mostrando ",reviews_of:" de ",reviews_suffix:" reseñas",load_more:"🔄 Cargar más reseñas de Google",load_more_info:"✅ Las ",load_more_info_end:" reseñas cargadas desde su caché GBP · Sincronice con Avision Pro",load_more_loading:"Cargando rese\u00f1as...",filter_all_stars:"Todos ⭐",without_reply:"💬 Sin respuesta",sort_recent:"Más recientes",sort_oldest:"Más antiguas",sort_lowest:"Peor valoración",sort_unanswered:"Sin respuesta primero",per_page:" por página",previous:"← Anterior",next:"Siguiente →",page_of:"Página ",gbp_reviews_title:"Reseñas de Google Business Profile",gbp_reviews_sub:"Responda directamente para generar confianza",reviews_info_title:"Reseñas Google — Cómo funciona",reviews_info_s1_title:"⭐ Por qué importan las reseñas",reviews_info_s1_body:"Las reseñas de Google impactan directamente en tu ranking local y tu tasa de conversión. Un negocio con respuestas recientes aparece mejor en el Pack Local.",reviews_info_s2_title:"✉️ Responde para generar confianza",reviews_info_s2_body:"Responder a cada reseña — positiva o negativa — demuestra profesionalismo. AVI puede generar una respuesta personalizada en un clic.",reviews_info_s3_title:"📅 Mantén la constancia",reviews_info_s3_body:"Filtra por Nuevas, Esta semana, Este mes o Este año para priorizar tus respuestas y no perderte ninguna reseña.",tip_th_reviewer:"Nombre y foto del cliente",tip_th_stars:"Valoración del cliente (1-5 estrellas)",tip_th_date:"Fecha de publicación de la reseña",tip_th_review:"Contenido completo de la reseña",tip_th_replied:"Si has respondido a esta reseña",tip_th_actions:"Responder, editar o regenerar una respuesta con AVI",filter_new:"Nuevas",filter_week:"Esta semana",filter_month:"Este mes",filter_year:"Este año",filter_all_years:"Todos los años",filter_all_months:"Todos los meses",filter_all_weeks:"Todas las semanas",filter_all_replies:"Todas las reseñas",filter_with_reply:"\u2705 Con respuesta",flag_review_tip:"Reportar esta reseña a Google (spam, falsa, inapropiada)",th_report:"Reportar",tip_th_report:"Reportar esta reseña a Google (spam, falsa, inapropiada)",upgrade_ai_title:"🤖 Responda más rápido con IA",upgrade_ai_sub:"Avision Pro genera respuestas personalizadas en segundos · Modo autopiloto disponible",upgrade_link:"Actualizar a Avision Pro →",th_reviewer:"Autor",th_stars:"Estrellas",th_date:"Fecha",th_review:"Reseña",th_replied:"Respondido",gbp_score_title:"📊 Puntuación GBP",profile_completeness:"Completitud del perfil",profile_stats:"Estadísticas del perfil",last_sync:"🕐 Última sync: ",crit_name:"Nombre del negocio",pts_0:"Info",crit_website:"Sitio web",crit_phone:"Teléfono",crit_hours:"Horario",crit_description:"Descripción del negocio",crit_category:"Categoría principal",crit_address:"Dirección",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ Hecho",missing:"❌ Falta",reviews_label:"reseñas",photos_label:"Fotos",avg_rank:"Posición media",score_urgent:"Requiere atención urgente",score_improve:"Margen de mejora",score_getting:"En camino",score_good:"Buen perfil",score_excellent:"Perfil excelente",'
			. 'unknown:"Desconocido",upsell_slim:"✨ Actualice a Avision Pro — Guardian · RAG · Multi-perfil",learn_more:"▲ Saber más",learn_close:"▼ Cerrar",upsell_local:"🏠 Negocio local",upsell_agency:"🏢 Agencia",no_client:"Ningún cliente encontrado",search_client_ph:"🔍 Buscar cliente...",clients_title:"👥 Clientes",clients_trigger:"👥 Clientes ▾",loading:"⏳ Cargando...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Sincronizar desde Google",sync_info_title:"Sincronizar desde Google",sync_info_score_body:"Actualiza tu Puntuación GBP y los datos de tu perfil directamente desde Google. Úsalo si tu puntuación, reseñas o atributos no reflejan los cambios recientes realizados en Google Business Profile.",sync_info_home_body:"Actualiza todas las estadísticas de tu panel — datos de posición, reseñas e historial de escaneos. Úsalo si tus estadísticas parecen desactualizadas o si has realizado cambios recientes en tu Google Business Profile.",sync_info_footer:"Los datos se actualizan automáticamente cada 24h. Este botón fuerza una actualización inmediata.",help_title:"Ayuda & FAQ",help_subtitle:"Encuentra respuestas a las preguntas frecuentes sobre tu Google Business Profile",help_s1_title:"🔴 Top 5 — Problemas frecuentes",help_s2_title:"🟣 Optimizar mi ficha",help_s3_title:"🔵 Actualizaciones de Google",help_faq1_q:"🚫 Mi ficha está suspendida",help_faq1_a:"Google suspende fichas por nombres con palabras clave, inconsistencias de dirección o demasiadas ediciones rápidas. Corrige el problema primero, luego presenta una solicitud de reintegración con pruebas (factura, contrato, licencia). Nunca crees una ficha duplicada durante el proceso.",help_faq2_q:"🔍 Mi ficha no aparece en Google Maps",help_faq2_a:"Comprueba que tu perfil esté completamente verificado y publicado. Las fichas no verificadas no aparecen. Los perfiles nuevos pueden tardar 2 a 4 semanas en mostrarse. Verifica también la coherencia de tu NAP en tu sitio web y otros directorios.",help_faq3_q:"✅ Cómo verificar mi ficha (vídeo)",help_faq3_a:"La verificación por vídeo es el método predeterminado en 2026. Graba un vídeo continuo mostrando tu rótulo, interior y una acción en vivo en tu panel de GBP. Asegúrate de que el nombre, la dirección y el sitio web coincidan antes de intentarlo.",help_faq4_q:"✏️ Se realizaron ediciones no autorizadas en mi ficha",help_faq4_a:"Cualquiera puede sugerir ediciones y Google puede aceptarlas automáticamente. Revisa tu información regularmente y revierte los cambios incorrectos desde tu panel de GBP. El modo Guardian de LocalEdge monitorea tus campos clave las 24 horas.",help_faq5_q:"⭐ No puedo responder a las reseñas",help_faq5_a:"Esto generalmente indica una restricción de perfil más que una suspensión completa. Revisa las notificaciones en tu panel de GBP. Asegúrate de haber iniciado sesión con la cuenta de Google correcta propietaria del perfil.",help_faq6_q:"📸 ¿Qué fotos publicar y cuántas?",help_faq6_a:"Publica al menos 10 fotos: fachada, interior, equipo, productos o servicios. Añade fotos nuevas cada mes — Google premia los perfiles activos. Evita fotos de banco o generadas por IA. Las fotos reales de tu negocio generan confianza y mejoran tu posicionamiento.",help_faq7_q:"🏷️ ¿Cómo elegir la categoría principal correcta?",help_faq7_a:"La categoría principal es la palanca de posicionamiento más importante en Google Maps. Elige la categoría más específica que corresponda a tu servicio principal. Un fontanero debe elegir Fontanero, no Servicios del hogar. Puedes añadir categorías secundarias para otros servicios.",help_faq8_q:"📝 ¿Cómo redactar una buena descripción?",help_faq8_a:"Escribe entre 250 y 750 caracteres describiendo qué haces, a quién sirves y qué te diferencia. Incluye tus palabras clave principales de forma natural. Evita lenguaje promocional, URLs o números de teléfono. Actualízala cada 6 meses.",help_faq9_q:"🗓️ ¿Con qué frecuencia publicar posts?",help_faq9_a:"Publica al menos una vez por semana para mantener señales de frescura. Usa AVI en la pestaña Posts para generar y programar contenido en segundos. Las publicaciones de Novedades caducan a los 7 días, los Eventos persisten hasta la fecha de fin.",help_faq10_q:"⭐ ¿Cómo conseguir más reseñas de clientes?",help_faq10_a:"Pide a cada cliente satisfecho inmediatamente después del servicio. Envía un enlace de reseña directo por email o SMS. Añade un código QR en tus recibos o tarjetas. Nunca ofrezcas incentivos ni indiques qué deben escribir — Google lo penaliza en 2026.",help_faq11_q:"📍 ¿Dirección visible o área de servicio?",help_faq11_a:"Si los clientes vienen a tus instalaciones, muestra tu dirección. Si visitas a los clientes, oculta tu dirección y añade áreas de servicio. Mostrar una dirección personal cuando visitas clientes puede generar confusión y arriesgar una suspensión.",help_faq12_q:"🔄 Tengo una ficha duplicada — ¿qué hago?",help_faq12_a:"Las fichas duplicadas dividen tus reseñas y confunden a Google. Busca tu negocio en Google Maps y reporta el duplicado mediante Sugerir una edición. Google fusionará o eliminará la ficha extra. Nunca gestiones dos fichas para el mismo negocio.",help_faq13_q:"🤖 Q&A eliminado — reemplazado por Ask Maps (Gemini)",help_faq13_a:"Google eliminó la función Q&A y la reemplazó con Ask Maps, impulsado por Gemini AI. Gemini responde preguntas de usuarios basándose en tus campos de perfil, reseñas, fotos y sitio web. Completa todos los campos de GBP y añade contenido FAQ en tu web con marcado schema.",help_faq14_q:"🛡️ Nuevas reglas de reseñas en 2026",help_faq14_a:"Google actualizó su política de reseñas a principios de 2026. Las reseñas generadas por IA están ahora prohibidas. Puedes seguir pidiendo reseñas pero no debes dictar qué escribir. Una solicitud neutral como comparte tu experiencia honesta es segura.",help_faq15_q:"⚡ Las ediciones rápidas pueden provocar una suspensión",help_faq15_a:"Realizar muchos cambios a la vez — nombre, dirección, categoría, horarios — es un desencadenante frecuente de suspensión en 2026. Espacía tus ediciones durante varios días. El modo Guardian de LocalEdge rastrea los cambios y te avisa antes de alcanzar un umbral de riesgo.",syncing_btn:"⏳ Sincronizando...",sync_success:"✅ ¡Perfil sincronizado!",sync_error:"Error. Inténtelo de nuevo.",add_credits:"+ Cr\\u00e9ditos pool",assign_credits:"+ Cr\\u00e9ditos",assign_min_hint:"M\\u00EDn. 10 cr \\u00b7 M\\u00FAltiplos de 10",select_all:"Seleccionar todo",bulk_cr_each:"cr c/u",bulk_assigning:"Asignando...",bulk_assigned:"\\u2705 clientes acreditados",'
			. 'picker_title:"Elige tu ficha Google Business",picker_subtitle:"Selecciona la ficha que deseas gestionar con LocalEdge.",picker_btn:"Seleccionar esta ficha",picker_loading:"Conectando...",picker_error:"Error al conectar. Int\u00e9ntalo de nuevo.",picker_select_all:"Seleccionar todo",picker_import:"Importar fichas seleccionadas",'
			. 'onboarding_title:"Conecta tu ficha Google Business",onboarding_subtitle:"Vincule su GBP para desbloquear todas las funciones: puntuaci\\u00f3n, rese\\u00f1as, fotos, publicaciones y m\\u00e1s.",onboarding_connect:"\\uD83D\\uDD17 Conectar Google Business",onboarding_skip:"Lo har\\u00e9 m\\u00e1s tarde",onboarding_step1_title:"1. Iniciar sesi\\u00f3n",onboarding_step1_desc:"Conecte su cuenta de Google",onboarding_step2_title:"2. Seleccionar",onboarding_step2_desc:"Elija su ficha de negocio",onboarding_step3_title:"3. \\u00a1Listo!",onboarding_step3_desc:"Todas las funciones activadas",edu_banner_title:"🎯 Bienvenido a su Centro de Control SEO Local",edu_banner_body:"Su GBP est\\u00e1 conectado. Optimice su puntuaci\\u00f3n, aumente su visibilidad y supere a sus competidores.",edu_banner_close:"Entendido \\u2713",edu_help_btn:"💡",edu_modal_title:"C\\u00f3mo funciona LocalEdge",edu_step1_title:"Paso 1 — Complete su perfil",edu_step1_body:"Tu ficha GBP est\\u00e1 conectada \\u2705 Este es tu punto de partida. Ve a la pesta\\u00f1a GBP Score para ver de un vistazo qu\\u00e9 campos est\\u00e1n incompletos. Tel\\u00e9fono, horarios, descripci\\u00f3n, fotos, categor\\u00edas — cada campo que falta te cuesta posiciones en Google Maps. Un perfil 100% completo genera hasta 2x m\\u00e1s clics.",edu_step2_title:"Paso 2 — Escanee y analice su visibilidad local",edu_step2_body:"En la pesta\\u00f1a Heatmap, selecciona 1 a 5 palabras clave que describan tu negocio (ej. \\u0027fontanero Madrid\\u0027). Lanza tu primer escaneo — cada punto de la cuadr\\u00edcula muestra tu posici\\u00f3n real en Google Maps en esa zona. No te preocupes: cada p\\u00e1gina tiene botones \\u2139\\uFE0F para guiarte en cada paso.",edu_step3_title:"Paso 3 — Optimice, interac\\u00fate y crezca",edu_step3_body:"Ahora que sabes d\\u00f3nde est\\u00e1s, act\\u00faa. GBP Score: corrige los campos prioritarios para subir en los resultados. Posts y Fotos: \\u2728 AVI redacta y programa tu contenido en segundos. Rese\\u00f1as: responde en menos de 24h con \\u2728 AVI — Google premia a las empresas que interact\\u00faan con sus clientes.",edu_learn_more:"C\\u00f3mo funciona \\u2192",tt_score:"Su puntuaci\\u00f3n GBP mide la completitud y optimizaci\\u00f3n de su perfil. Una puntuaci\\u00f3n superior a 70 mejora significativamente su visibilidad en el Paquete Local de Google. Encu\\u00e9ntrelo en la pesta\\u00f1a GBP Score \\u2192",tt_unanswered:"Responder a las rese\\u00f1as en 24h mejora su puntuaci\\u00f3n de confianza en Google. Vaya a la pesta\\u00f1a Google Reviews para responder \\u2192",tt_next_scan:"Los escaneos regulares rastrean la evoluci\\u00f3n de su visibilidad local. Lance un escaneo en la columna 3 \\u2192",tt_nap:"La completitud de su perfil impacta directamente en su clasificaci\\u00f3n local. Corr\\u00edjalos en la pesta\\u00f1a GBP Score \\u2192",tt_control_center:"Tu resumen de GBP: puntuaci\\u00f3n, rese\\u00f1as sin respuesta, pr\\u00f3ximo escaneo y completitud del perfil \\u2014 todo en un lugar para priorizar lo m\\u00e1s importante.",clients_count_suffix:" cliente(s)",pool_credits:"💳 Créditos pool: ",available_word:" disponibles · ",used_word:" usados",never:"Nunca",today:"Hoy",yesterday:"Ayer",sort_priority:"🚨 Prioridad (score bajo primero)",sort_best_score:"⭐ Mejor score primero",sort_activity:"🕐 Última actividad",sort_name:"A→Z Nombre",sort_kw:"🔑 Más palabras clave",scan_badge:" scan(s)",kw_badge:" palabras clave",logo_too_large:"Logo demasiado grande — máx. 2 MB",upload_logo:"📁 Subir logo",or_sep:"— o —",agency_hub_title:"Hub Agencia",col_suffix:" col",cols_suffix:" cols",err_rename:"Error de red al renombrar",err_file_too_large:"Archivo demasiado grande",tip_col_keyword:"Término de búsqueda rastreado",tip_col_rank:"Posición media actual en todos los puntos del mapa de calor",tip_col_best:"Mejor posición registrada",tip_col_grid:"Tamaño de cuadrícula del último escaneo",tip_col_status:"Pendiente = nunca escaneado · Escaneado = con datos",tip_col_scan:"Fecha + tipo de escaneo (solo o multi)",tip_col_threat:"⚠️ Un competidor domina el Top 3 en más del 50 % de los puntos",filter_danger:"⚠️ Peligro",filter_solo_scan:"🔍 Escaneo solo",filter_multi_scan:"📊 Escaneo multi",filter_az:"A→Z",filter_all_grids:"Todas las cuadrículas",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" palabras clave)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Sin escanear aún",export_col_city:"Ciudad",export_col_scan_type:"Tipo de escaneo",export_yes:"Sí",export_no:"No",export_danger_yes:"⚠️ Sí",kw_report_title:"Informe de palabras clave",kw_report_generated:"Generado:",kw_report_keywords_suffix:" palabras clave",import_kw_tip:"Importar varias palabras clave (una por línea o CSV)",add_kw_ph:"Introduzca palabra clave (ej. Fontanero Madrid)",import_kw_ph:"Fontanero Madrid\\nElectricista Barcelona\\nCerrajero Valencia",post_char_of:" / 1500",post_add_photo:"📷 Añadir una foto",post_photo_formats:"JPG, PNG — máx. 5 MB",export_col_created:"Creado",posts_page_title:"Posts GBP",posts_report_title:"Informe Posts GBP",photo_status_in_stock:"📚 En biblioteca",photos_count_suffix:" foto(s)",no_photos:"Sin fotos aún",no_photos_sub:"Suba fotos para crear su biblioteca GBP",photo_alt_default:"Foto GBP",photo_sched_vid:"5 cr",photo_sched_img:"3 cr",err_rename_failed:"Error al renombrar",export_col_file:"Archivo",export_col_category:"Categoría",photos_page_title:"Fotos GBP",photos_report_title:"Informe Fotos GBP",photos_library_count_suffix:" fotos en biblioteca",cat_cover:"🖼️ Portada",cat_profile:"👤 Perfil",cat_logo:"🎨 Logo",cat_interior:"🏠 Interior",cat_exterior:"🏢 Exterior",cat_product:"📦 Producto",cat_at_work:"💼 En el trabajo",cat_food_drink:"🍽️ Comida y bebida",cat_menu:"📋 Menú",cat_common_area:"🛋️ Zona común",cat_rooms:"🛏️ Habitaciones",cat_teams:"👥 Equipos",cat_additional:"➕ Adicional",rv_replied_yes:"✅ Sí",rv_replied_no:"❌ No",export_col_reply:"Respuesta",export_col_has_reply:"Respondido",reviews_page_title:"Informe Reseñas",reviews_report_title:"Informe Reseñas Google",reviews_pdf_avg:"⭐ Media: ",reviews_pdf_reviews_suffix:" reseñas",export_col_criterion:"Criterio",export_col_points:"Puntos",score_export_done:"Hecho",score_export_missing:"Falta",score_export_score:"Puntuación",score_export_rating:"Valoración",score_export_photos:"Fotos",score_report_title:"Informe Score GBP",score_pdf_stats:"Estadísticas",score_pdf_rating:"⭐ Valoración: ",score_pdf_photos:"📸 Fotos: ",rel_d_ago:"d",rel_w_ago:"sem",rel_mo_ago:"mes",rel_y_ago:"a",hub_subtitle:"Gestione ajustes de agencia, créditos y white-label.",hub_credit_pool:"💳 Pool de créditos",hub_tier_label:"Plan actual",hub_tier_t1:"Tier 1 — hasta 10 fichas",hub_tier_t2:"Tier 2 — hasta 50 fichas",hub_tier_t3:"Tier 3 — fichas ilimitadas",hub_listings_gauge:"Fichas activas",hub_tier_upgrade:"Mejorar plan",hub_tier_downgrade:"Reducir plan",hub_upgrade_processing:"Redirigiendo al pago...",hub_downgrade_confirm:"\u00bfConfirmar cambio a este plan?",hub_downgrade_blocked:"Reducci\u00f3n bloqueada: demasiadas fichas activas.",hub_downgrade_success:"Plan actualizado correctamente.",hub_info_upgrade:"Upgrade: solo paga la diferencia entre planes (prorrata).",hub_info_downgrade:"Downgrade: gratuito, sin reembolso. Bloqueado si las fichas activas superan el l\u00edmite del nuevo plan.",hub_available:"Disponibles",hub_used:"Usados",hub_buy_credits:"+ Comprar créditos (mayorista)",hub_whitelabel:"🎨 White-label",hub_whitelabel_desc:"URL del logo y nombre de marca en el embed y exportaciones PDF.",hub_logo_ph:"https://sulogo.com/logo.png",hub_brand_ph:"Nombre de su agencia",hub_save_settings:"Guardar",saved:"Guardado \u2713",hub_save_alert:"Ajustes white-label — Sprint 45",hub_import_clients:"📥 Importar clientes",hub_import_csv_desc:"Formato CSV: business_name, city, category, country",hub_import_csv_btn:"Importar CSV",hub_import_alert:"Importación CSV — Sprint 45",hub_pro_title:"🚀 Avision Pro Agencia",hub_pro_sub:"Vista helicóptero · Acciones masivas · Informes avanzados · Guardian completo",hub_pro_cta:"Actualizar a Avision Pro Agencia →",profile_title:"Mi Perfil",profile_subtitle:"Gestione sus créditos y cuenta.",profile_credits_available:"Créditos disponibles",profile_credits_used:"Usados",profile_buy:"+ Comprar créditos",profile_pack_nano:"Nano — 10 créditos",profile_pack_mini:"Mini — 30 créditos",profile_pack_standard:"Standard — 75 créditos",profile_pack_pro:"Pro — 200 créditos",profile_pack_agency:"Agencia — 600 créditos",profile_price_nano:"$2",profile_price_mini:"$5",profile_price_standard:"$11",profile_price_pro:"$25",profile_price_agency:"$59",profile_save_economy:" — ahorre ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Dashboard completo · Guardian \\u00b7 SEO avanzado",profile_upsell_cta:"Actualizar a Avision Pro \\u2192",credits_modal_title:"💳 Sus créditos LocalEdge",credits_modal_solo_p1:"Sus créditos LocalEdge son permanentes — nunca caducan. Compre cuando los necesite, úselos a su ritmo.",credits_modal_usage_title:"Dónde gastar sus créditos:",credits_modal_heatmap:"🗺️ Escaneo heatmap — de 2 cr (3×3) a 60 cr (21×21)",credits_modal_post:"📝 Publicación GBP Post via AVI — 3 cr",credits_modal_photo:"📷 Sincronización foto GBP — 2 cr",credits_modal_guardian:"🔔 Guardian (monitoreo de ficha) — gratis, incluido",credits_modal_savings_title:"Cuanto más compra, menos paga por crédito.",credits_modal_savings_sub:"El pack Pro a $25 cuesta un 38% menos por crédito que el pack Nano.",credits_modal_agency_title:"💳 Su pool de créditos de agencia",credits_modal_agency_p1:"Su pool se comparte entre todos sus perfiles de clientes. Compre al por mayor, distribuya según sus necesidades.",credits_modal_agency_wholesale:"Precio mayorista — sus créditos de agencia cuestan hasta un 47% menos que las tarifas estándar. Su margen es libre.",credits_modal_agency_noexpiry:"Sin caducidad — sus créditos permanecen disponibles indefinidamente.",purchase_success_title:"\u2713 \u00a1Pago recibido!",purchase_success_sub:"Sus cr\u00e9ditos estar\u00e1n disponibles en unos segundos.",purchase_success_close:"Entendido",slider_title:"O elija su propio importe",slider_credits:"cr\u00e9ditos",slider_price_per:"por cr\u00e9dito",slider_vs_nano:"vs Nano",slider_buy_btn:"Comprar",slider_min_label:"10 cr",slider_max_label_solo:"1.000 cr",slider_max_label_agency:"5.000 cr",client_balance:"Saldo del cliente",cr_need:"Necesario",cr_available:"Disponible",cr_missing:"Faltante",days_ago:"d",attr_other:"Otro",anonymous_reviewer:"An\u00f3nimo",error_generic:"Se produjo un error.",vs_standard:"vs est\u00e1ndar",badge_discount_17:"-17%",badge_discount_27:"-27%",badge_discount_38:"-38%",badge_discount_16:"-16%",badge_discount_30:"-30%",badge_discount_40:"-40%",badge_discount_47:"-47%",ag_pack_starter:"Starter Agencia — 100 créditos",ag_pack_standard:"Standard Agencia — 300 créditos",ag_pack_pro:"Pro Agencia — 750 créditos",ag_pack_enterprise:"Enterprise Agencia — 2000 créditos",ag_price_starter:"$14",ag_price_standard:"$35",ag_price_pro:"$75",ag_price_enterprise:"$175",logo_preview_alt:"Vista previa del logo",hub_uploaded_file:"(archivo subido)",ag_no_scan:"🗺️ Sin escaneo",gbp_open_title:"Abrir ficha GBP: ",gbp_search_title:"Buscar en Google Maps: ",gbp_score:"Score GBP",unanswered:"Sin respuesta",unanswered_sub:"rese\u00f1as por responder",credits_left:"Cr\u00e9ditos",next_scan:"Pr\u00f3ximo scan",no_scan:"Sin scan",nap_status:"Completitud perfil",nap_name:"Nombre",nap_address:"Direcci\u00f3n",nap_phone:"Tel\u00e9fono",nap_website:"Web",nap_hours:"Horario",nap_desc:"Descripci\u00f3n",fix_it:"Completar \\u2192",edit:"Editar",fix:"Corregir",edit_name:"Editar nombre",name_warn:"Cambiar el nombre puede activar una revisi\u00f3n de Google. Use su nombre comercial real.",edit_website:"Editar sitio web",edit_phone:"Editar tel\u00e9fono",edit_hours:"Editar horarios",edit_description:"Editar descripci\u00f3n",edit_categories:"Editar categor\u00edas",edit_address:"Editar direcci\u00f3n",edit_success:"\u00a1Actualizado con \u00e9xito en Google!",edit_error:"Error al actualizar. Int\u00e9ntelo de nuevo.",lodging_posts_warn:"Las publicaciones GBP no est\u00e1n disponibles para alojamientos. Google reserva este espacio para plataformas de reservas.",hours_closed:"Cerrado",hours_open:"Abierto",cat_search_placeholder:"Buscar categor\u00edas de Google...",cat_primary:"Categor\u00eda principal",cat_additional:"Categor\u00edas adicionales (m\u00e1x 9)",cat_lodging_warn:"Cambiar su categor\u00eda principal puede afectar las funciones de su perfil.",addr_neighborhood:"Barrio / Distrito",addr_street:"Direcci\u00f3n",addr_city:"Ciudad",addr_region:"Estado / Regi\u00f3n",addr_postal:"C\u00f3digo postal",addr_country:"C\u00f3digo de pa\u00eds (ej. FR)",verified:"Verificado",pending_verification:"Verificación pendiente",not_verified:"No verificado",verify_cta_text:"Su ficha no est\u00e1 verificada en Google. Las fichas verificadas generan m\u00e1s confianza.",verify_cta_btn:"Verificar mi ficha \u2192",verify_pending_text:"Verificaci\u00f3n en curso. Google puede tardar hasta 7 d\u00edas.",score_panel_sub:"Tu puntuaci\u00f3n de optimizaci\u00f3n de Google Business Profile. Cada campo completado mejora tu visibilidad en los resultados de b\u00fasqueda local.",score_info_title:"Puntuaci\u00f3n GBP \u2014 C\u00f3mo funciona",score_info_s1_title:"\uD83C\uDFAF C\u00f3mo se calcula la puntuaci\u00f3n",score_info_s1_body:"Base 30 pts + Sitio web (+5) + Horario (+3) + Descripci\u00f3n 200+ car. (+2) + Categor\u00eda adicional (+1) + Atributos \u22653 (+1). M\u00e1ximo: 42 pts.",score_info_s2_title:"\uD83D\uDCC8 Por qu\u00e9 importa",score_info_s2_body:"Un perfil completo y optimizado aparece mejor en el Pack Local de Google. Cada campo faltante te cuesta visibilidad en b\u00fasquedas locales.",score_info_s3_title:"\u270F\uFE0F C\u00f3mo mejorar",score_info_s3_body:"Haz clic en Editar o Corregir en cada criterio para actualizar directamente desde LocalEdge \u2014 sin abrir tu perfil de Google.",gbp_attributes_title:"Atributos GBP",attr_na:"N/A para esta categor\u00eda",attr_url_gbp_hint:"Editar en Google Business Profile",attrs_filled:"Configurados",crit_posts:"Publicaciones recientes",crit_photos:"Fotos publicadas",photos_published_label:"publicadas",photos_min:"m\u00edn. 3 recomendadas",post_stale:"\u00daltima publicaci\u00f3n > 7 d\u00edas \u2014 publica para mantener tus puntos",post_fresh:"Fresco \u2014 publicado en los \u00faltimos 7 d\u00edas",post_upsell:"Programa una publicaci\u00f3n para mantener tu puntuaci\u00f3n",photo_stale:"\u00daltima foto > 7 d\u00edas \u2014 publica para mantener tus puntos",photo_fresh:"Fresca \u2014 foto publicada en los \u00faltimos 7 d\u00edas",photo_upsell:"Publica una foto para mantener tu puntuaci\u00f3n",crit_reviews_reply:"\u00daltima rese\u00f1a respondida",replied:"Respondida",not_replied:"Sin respuesta",no_reviews_yet:"A\u00fan no hay rese\u00f1as",freshness_note:"Tu puntuaci\\u00f3n var\\u00eda seg\\u00fan tu actividad: publicaciones, fotos, respuestas a rese\\u00f1as, completitud del perfil y scans del mapa de calor impactan tu ranking. Mantente activo para maximizar tus puntos.",view:"Ver",reply:"Responder",attr_saved:"Atributo actualizado",attr_error:"Error al actualizar atributo",attrs_load_error:"No se pudieron cargar los atributos",attrs_load_hint:"Haga clic en \uD83D\uDD04 Sync from Google para recargar",hm_section_title:"🗺️ Visibilidad Heatmap",hm_info_title:"Heatmap — Por qué lo cambia todo",hm_info_s1_title:"📍 Conoce tu posición exacta",hm_info_s1_body:"Cada scan mapea tu posición en Google Maps en cada punto de tu cuadrícula de barrio. Ves exactamente dónde dominas y dónde los competidores te superan — calle por calle.",hm_info_s2_title:"🏆 Analiza tus competidores",hm_info_s2_body:"El mapa de calor revela qué competidores ocupan el top 3 en cada punto de la cuadrícula. Identifica a quién superar, en qué zonas, y ajusta tu estrategia de SEO local.",hm_info_s3_title:"📐 Tamaño de cuadrícula = control del territorio",hm_info_s3_body:"Una cuadrícula 7x7 cubre tu barrio inmediato. Una 13x13 mapea toda tu ciudad. Cuanto mayor sea tu cuadrícula, más territorio controlas y más datos tienes para tomar decisiones estratégicas.",hm_info_s4_title:"🔄 Scans regulares = ganancias de posición",hm_info_s4_body:"Escanea la misma palabra clave semanalmente para rastrear tu progresión. Cada scan usa créditos pero te da datos accionables: ¿estás ganando o perdiendo posiciones? Reacciona antes de que los competidores tomen tus lugares.",hm_activity_label:"Actividad scans",hm_performance_label:"Rendimiento local",hm_coverage_label:"Cobertura territorio",hm_scan_now:"Lanzar un scan",hm_stale_warn:"Sin scan en 30+ días — tus datos están desactualizados",hm_no_scan:"Sin scan aún — empieza a mapear tu territorio",control_center:"Centro de control",guardian_badge:"\ud83d\udd14 Alertas",guardian_modal_title:"Guardian Lite \u2014 Alertas de perfil",guardian_no_alerts:"No se detectaron alertas",guardian_plan_free:"Plan gratuito \u2014 sin monitorizaci\u00f3n",guardian_plan_lite:"Lite \u2014 escaneo 1x\/mes",guardian_plan_standard:"Est\u00e1ndar \u2014 escaneo semanal",guardian_plan_daily:"Escaneo diario activo",guardian_field_title:"Nombre del negocio modificado",guardian_field_phone:"N\u00famero de tel\u00e9fono modificado",guardian_field_categories:"Categor\u00eda modificada",guardian_field_hours:"Horarios modificados",guardian_field_website:"Sitio web modificado",guardian_field_openInfo:"Estado abierto\/cerrado modificado",guardian_why_title:"\u00bfPor qu\u00e9 vigilar tu perfil?",guardian_why_1:"Cualquiera puede sugerir cambios en tu GBP \u2014 incluidos los competidores",guardian_why_2:"Los Local Guides tienen mucho poder y pueden marcar tu negocio como cerrado",guardian_why_3:"Los cambios no detectados provocan ca\u00eddas en el ranking y p\u00e9rdida de visibilidad",guardian_fix_btn:"Corregir en GBP Score \u2192",guardian_mark_read:"Marcar todo como le\u00eddo",guardian_detected:"Detectado:",guardian_old:"Antes:",guardian_new:"Despu\u00e9s:",guardian_verify:"verificar inmediatamente",guardian_fix_now:"Corregir ahora",guardian_field_address:"Direcci\u00f3n",guardian_field_description:"Descripci\u00f3n",guardian_field_specialHours:"Horarios especiales",guardian_field_serviceArea:"\u00c1rea de servicio",crit_special_hours:"Horarios especiales",crit_service_area:"\u00c1rea de servicio",special_hours_edit_info:"Los horarios especiales deben gestionarse directamente en Google Business Profile.",service_area_edit_info:"El \u00e1rea de servicio debe gestionarse directamente en Google Business Profile.",guardian_changed:"modificado",guardian_fix_gbp:"Corregir en GBP \u2192",crit_open_status:"Estado del negocio",open_info_warn:"Modificar este estado actualizar\u00e1 su ficha de Google Business Profile de inmediato.",open_status_open:"Abierto \u2014 Horario normal",open_status_temp:"Cerrado temporalmente \u2014 reapertura prevista",open_status_perm:"Cerrado permanentemente \u2014 verificar urgentemente",open_status_open_no_hours:"Abierto \u2014 Sin horario principal",open_status_unknown:"Estado desconocido",cit_title:"Citas",cit_listed:"a\u00f1adidas",cit_done:"A\u00f1adido",cit_mark_done:"\u2713 A\u00f1adir",cit_already:"Ya listado",cit_mark_already:"\u2713 Ya listado",cit_trust:"Confiamos en usted \u2014 no verificamos esto autom\u00e1ticamente",cit_url_placeholder:"URL de tu ficha (opcional)",cit_section_universal:"\ud83c\udf0d Universal",cit_section_local:"\ud83c\udff3\ufe0f Espa\u00f1a",cit_section_niche:"\ud83c\udfaf Tu sector",cit_todo:"\ud83d\udccb Por hacer",cit_completed:"Completados",cit_collapse:"\u25b2 Contraer",cit_expand:"\u25bc Expandir",cit_undo:"\u21a9 Deshacer",cit_remove:"Eliminar",cit_add_name:"Nombre del directorio",cit_add_url:"https://...",cit_add_btn:"+ A\u00f1adir",cit_banner_msg:"Seleccionamos autom\u00e1ticamente directorios basados en su categor\u00eda de Google Business \"{cat}\". Algunas sugerencias pueden no ser perfectas \u2014 si\u00e9ntase libre de eliminarlas o agregar las suyas.",cit_your_category:"su categor\u00eda",cit_panel_sub:"Realiza un seguimiento de tus fichas en directorios para mejorar tu visibilidad SEO local.",cit_info_title:"Citas & SEO Local",cit_info_s1_title:"\ud83d\udccd \u00bfQu\u00e9 es una cita?",cit_info_s1_body:"Una cita es cualquier menci\u00f3n en l\u00ednea de tu nombre, direcci\u00f3n y tel\u00e9fono (NAP). Los motores de b\u00fasqueda las usan para verificar tu negocio y mejorar tu posicionamiento local.",cit_info_s2_title:"\u26a0\ufe0f La coherencia NAP es cr\u00edtica",cit_info_s2_body:"Tu nombre, direcci\u00f3n y tel\u00e9fono deben ser exactamente id\u00e9nticos en todos los directorios \u2014 mismas abreviaturas, misma puntuaci\u00f3n, mismo formato. Cualquier diferencia confunde a los motores de b\u00fasqueda.",cit_info_s3_title:"\ud83c\udfaf \u00bfPor qu\u00e9 estos directorios?",cit_info_s3_body:"Seleccionamos autom\u00e1ticamente directorios seg\u00fan tu categor\u00eda de Google Business y ubicaci\u00f3n. Algunas sugerencias de nicho pueden no encajar \u2014 elim\u00ednalas o a\u00f1ade las tuyas.",cit_info_s4_title:"\u2705 \u00bfYa est\u00e1s listado?",cit_info_s4_body:"Si tu negocio ya aparece en un directorio, haz clic en \u2018Ya listado\u2019 y a\u00f1ade opcionalmente la URL. Confiamos en ti \u2014 no verificamos esto autom\u00e1ticamente, pero podr\u00edamos hacerlo en el futuro.",cit_score_section:"\ud83d\udccb Citas",cit_score_label:"Directorios",cit_score_detail:"directorios listados",cit_stale_warn:"A\u00f1ada un directorio para mantener su puntuaci\u00f3n",sh_title:"Historial Score & Rango",sh_daily:"Diario",sh_score:"Score GBP",sh_rank:"Rango medio",sh_drop:"Ca\u00edda",sh_all_kw:"Todas las palabras clave",sh_no_data:"Sin datos a\u00fan. Ejecuta un escaneo heatmap para empezar el seguimiento.",sh_start:"Inicio",sh_now:"Ahora",sh_best_rank:"Mejor rango",sh_info_title:"Entendiendo tu Historial Score & Rango",sh_info_s1_title:"\\ud83d\\udcc8 Score GBP (morado)",sh_info_s1_body:"Tu puntuaci\\u00f3n de optimizaci\\u00f3n de Google Business Profile de 0 a 100. Sube al completar tu ficha, a\\u00f1adir fotos, obtener rese\\u00f1as y corregir alertas Guardian.",sh_info_s2_title:"\\ud83d\\udccd Rango medio (\\u00e1mbar)",sh_info_s2_body:"Tu posici\\u00f3n media en los resultados de Google Maps en todos los puntos de la cuadr\\u00edcula heatmap. M\\u00e1s bajo es mejor \\u2014 rango #1 significa que apareces primero.",sh_info_s3_title:"\\u26a0\\ufe0f \\u00bfPor qu\\u00e9 fluct\\u00faa mi rango?",sh_info_s3_body:"El rango GBP var\\u00eda seg\\u00fan la ubicaci\\u00f3n del buscador, la palabra clave, la hora del d\\u00eda y las actualizaciones del algoritmo de Google. Es normal \\u2014 sigue la tendencia, no los puntos individuales.",sh_info_s4_title:"\\ud83d\\udd34 Puntos rojos",sh_info_s4_body:"Un punto rojo indica una ca\\u00edda brusca: -10 pts o m\\u00e1s en el score, o +5 posiciones perdidas en el rango. Son momentos para investigar \\u2014 revisa las alertas Guardian para esa fecha.",tab_profile:"Perfil",tab_attributes:"Atributos",tab_history:"Historial",card_nap:"NAP e Info",card_online:"Presencia online",card_activity:"Actividad",card_visibility:"Visibilidad",sh_fullscreen:"Pantalla completa",sh_exit_fs:"Salir",card_nap_info_title:"NAP & SEO Local",card_nap_s1_title:"📍 ¿Qué es el NAP?",card_nap_s1_body:"NAP significa Nombre, Dirección y Teléfono. Los motores de búsqueda usan tu NAP para verificar tu negocio. Un NAP incoherente perjudica tu posicionamiento local.",card_nap_s2_title:"🎯 Por qué importa",card_nap_s2_body:"Google compara tu GBP con otros directorios. Si tu nombre o dirección difiere, genera dudas y reduce tu posición local.",card_nap_s3_title:"✅ Qué hacer",card_nap_s3_body:"Mantenga su nombre, direcci\u00f3n, tel\u00e9fono y categor\u00eda estrictamente id\u00e9nticos en Google Business Profile y todos los directorios. Utilice la pesta\u00f1a Citas para rastrear sus listados.",card_nap_s4_title:"\u26a0\ufe0f Riesgo de reverificaci\u00f3n o suspensi\u00f3n",card_nap_s4_body:"Evite modificar su categor\u00eda, descripci\u00f3n o informaci\u00f3n clave demasiado r\u00e1pido. Los algoritmos de Google necesitan tiempo para integrar los cambios. Demasiadas modificaciones r\u00e1pidas pueden desencadenar un proceso de reverificaci\u00f3n o incluso la suspensi\u00f3n de su ficha.",card_online_info_title:"Presencia online",card_online_s1_title:"🌐 Sitio web",card_online_s1_body:"Un sitio web vinculado a tu GBP añade confianza y +5 pts. Asegúrate de que carga correctamente.",card_online_s2_title:"🕒 Horarios",card_online_s2_body:"Los horarios precisos ayudan a los clientes a encontrarte. Sin horarios pierdes -3 pts y apareces menos en búsquedas \\u0027Abierto ahora\\u0027.",card_online_s3_title:"📝 Descripción",card_online_s3_body:"Una buena descripción ayuda a Google a entender tu negocio. Sin descripción pierdes -2 pts.",card_activity_info_title:"Actividad & Compromiso",card_activity_s1_title:"📸 Posts de Google",card_activity_s1_body:"Publicar posts regularmente indica a Google que tu negocio está activo. Un post en los últimos 7 días te da +5 pts.",card_activity_s2_title:"🖼️ Fotos",card_activity_s2_body:"Los negocios con fotos reciben 42% más solicitudes de ruta. Fotos frescas en los últimos 7 días dan los máximos puntos.",card_activity_s3_title:"⭐ Respuestas a reseñas",card_activity_s3_body:"Responder reseñas muestra a Google y clientes que estás activo. Responde tu última reseña para ganar +3 pts.",card_visibility_info_title:"Visibilidad Local",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"El heatmap muestra dónde apareces en Google Maps en tu zona. Haz escaneos regulares para seguir tu posición.",card_visibility_s2_title:"📋 Citas",card_visibility_s2_body:"Las citas son menciones de tu negocio en directorios. Más citas coherentes = más confianza de Google.",card_visibility_s3_title:"📈 Seguimiento",card_visibility_s3_body:"Usa la pestaña Historial para ver cómo evolucionan tu puntuación y posición local.",card_see_more:"Ver m\u00e1s",card_see_less:"Ver menos",attrs_info_title:"Atributos GBP — Lo que necesitas saber",attrs_info_s1_title:"🔧 \u00bfQu\u00e9 son los atributos GBP?",attrs_info_s1_body:"Los atributos son detalles adicionales sobre tu negocio que ayudan a los clientes a tomar decisiones — opciones de accesibilidad, m\u00e9todos de pago, aparcamiento, servicios disponibles, etc. Aparecen directamente en tu perfil de Google Business.",attrs_info_s2_title:"📍 Por qu\u00e9 importan para el SEO local",attrs_info_s2_body:"Los atributos completos indican a Google que tu perfil es detallado y de confianza. Tambi\u00e9n ayudan a que tu negocio aparezca en b\u00fasquedas filtradas espec\u00edficas, como clientes que buscan negocios \u0027accesibles en silla de ruedas\u0027 o con \u0027aparcamiento gratuito\u0027.",attrs_info_s3_title:"⚠️ Importante — Algunos atributos no se pueden editar aqu\u00ed",attrs_info_s3_body:"Google controla qu\u00e9 atributos est\u00e1n disponibles seg\u00fan la categor\u00eda de tu negocio. Algunos atributos solo se pueden modificar directamente en Google Business Profile. Si un atributo no responde a los cambios realizados aqu\u00ed, act\u00falalo directamente en business.google.com.",attr_url_hint:"A\u00f1ade estas URLs para mejorar tu visibilidad en Google. Para los enlaces de cita, ve a Google Business Profile \u2192 Editar perfil \u2192 Reservas.",guardian_home_title:"Guardian",guardian_home_status:"Activo",guardian_checking:"Verificando...",guardian_disconnected:"Desconectado",guardian_home_subtitle:"Supervisando su ficha 24\/7",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 Su centinela GBP",guardian_info_s1_title:"\ud83d\udd0d Qu\u00e9 supervisa Guardian",guardian_info_s1_body:"Guardian vigila 10 campos clave: nombre, direcci\u00f3n, tel\u00e9fono, sitio web, categor\u00eda principal, horarios, descripci\u00f3n, estado abierto\/cerrado, fotos de portada y atributos.",guardian_info_s2_title:"\u26a0\ufe0f Por qu\u00e9 es crucial",guardian_info_s2_body:"Cualquiera puede sugerir cambios en su ficha. Los cambios no detectados pueden hundir su posicionamiento. Guardian le alerta de inmediato.",guardian_info_s3_title:"\u2705 Lo que Guardian NO hace",guardian_info_s3_body:"Guardian no mejora su posicionamiento. Contin\u00fae optimizando su GBP. Guardian protege la visibilidad que ya ha conseguido.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 Incluido en su plan",guardian_info_s4_body:"Guardian Lite supervisa 10 campos GBP clave las 24h y le avisa en cuanto detecta un cambio sospechoso. La vigilancia siempre est\u00e1 incluida en su plan \u2014 los cr\u00e9ditos solo se usan cuando AVI corrige autom\u00e1ticamente un cambio (3 cr\u00e9ditos/mes incluidos \u00b7 2 cr\u00e9ditos por correcci\u00f3n).",guardian_info_cta:"Entendido \u2713",guardian_trial_ended:"Prueba terminada \u2014 cr\u00e9ditos activos",guardian_trial_active:"Prueba gratuita activa",guardian_trial_days_left:"d\u00edas restantes en la prueba",guardian_pricing_detail:"Despu\u00e9s de la prueba: 3 cr\u00e9ditos/mes + 2 cr\u00e9ditos por cambio detectado",guardian_pricing_detail_active:"3 cr\u00e9ditos/mes \u00b7 2 cr\u00e9ditos por cambio detectado",guardian_disabled_title:"Desactivado",guardian_disabled_warn:"Su ficha ya no est\u00e1 supervisada. Los competidores pueden modificar su GBP sin que usted lo sepa.",guardian_activate:"Activar Guardian \u2192",guardian_credits_active:"Cr\u00e9ditos activos",guardian_deactivate:"Desactivar Guardian",guardian_post_trial_status:"\u26a0\ufe0f Prueba terminada",guardian_post_trial_warning:"\u26a0\ufe0f Su ficha est\u00e1 ahora expuesta. Competidores y Gu\u00edas Locales pueden modificar su GBP en cualquier momento \u2014 los cambios no detectados causan ca\u00eddas de posicionamiento, horarios incorrectos y llamadas perdidas.",guardian_deactivate_warn:"Si desactiva, los cambios en su ficha pasar\u00e1n completamente desapercibidos. No ser\u00e1 alertado si un competidor lo marca como cerrado.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Supervisado por Guardian \u2014 prueba gratuita activa",guardian_tooltip_active:"\u26A0\uFE0F Prueba terminada \u2014 cr\u00e9ditos activos. Haga clic en \u2139\uFE0F en inicio para gestionar.",guardian_low_credits_title:"Cr\u00e9ditos bajos \u2014 Guardian en riesgo",guardian_low_credits_warn:"Tiene menos de 10 cr\u00e9ditos. Guardian podr\u00eda dejar de supervisar pronto.",guardian_credits_remaining:"Cr\u00e9ditos restantes:",guardian_buy_credits:"Comprar cr\u00e9ditos \u2192",guardian_trial_expired_title:"Prueba gratuita finalizada",guardian_trial_expired_warn:"Su prueba gratuita de 15 d\u00edas ha finalizado. Active Guardian para seguir supervisando su ficha.",guardian_trial_expired_badge:"\u23f1\ufe0f Prueba finalizada \u2014 active para continuar",guardian_paid_active_title:"Guardian Activo",guardian_next_billing:"Pr\u00f3xima facturaci\u00f3n:",guardian_tooltip_off:"Guardian desactivado \u2014 este campo ya no est\u00e1 supervisado"},'
			. '"pt-br":{close:"Fechar",cancel:"Cancelar",save:"Salvar",delete:"Excluir",'
			. 'search_kw:"Buscar palavra-chave...",add_kw:"+ Adicionar palavra-chave",add_keyword:"+ Adicionar palavra-chave",'
			. 'confirm_delete_scan:"Excluir este scan agendado?",'
			. 'kw_my_keywords:"Minhas palavras-chave",kw_panel_title:"Minhas palavras-chave",kw_panel_sub:"Acompanhe os termos de busca importantes para sua visibilidade local. Cada palavra-chave pode ser escaneada no mapa de calor para mostrar sua posi\u00e7\u00e3o no Google Maps na sua \u00e1rea.",more:"mais",'
			. 'import_kw:"📥 Importar",export_kw:"📤 Exportar",'
			. 'export_csv:"📊 Exportar CSV",export_pdf:"📄 Exportar PDF",'
			. 'import_label:"Cole suas palavras-chave — uma por linha ou separadas por vírgula:",'
			. 'import_btn:"Importar",scan_kw:"Escanear esta palavra-chave",'
			. 'no_kw:"Sem palavras-chave — adicione sua primeira palavra-chave acima",'
			. 'scanned:"✅ Escaneado",pending:"⬜ Pendente",threat:"⚠️ Ameaça",'
			. 'actions:"Ações",'
			. 'col_keyword:"Palavra-chave",col_rank:"Posição",col_best:"Melhor posição",'
			. 'col_grid:"Grade",col_status:"Status",col_scan:"Último scan",'
			. 'col_threat:"Ameaça",publish_now:"Publicar agora",schedule_post:"Agendar publicação",schedule_post_credits:"Agendar (2 créditos)",publishing:"Publicando...",scheduling:"Agendando...",new_post:"Nova publicação GBP",edit_post:"Editar publicação",posts_panel_title:"Publicações GBP",posts_panel_sub:"Crie e gerencie suas publicações do Google Business Profile. Publicações regulares melhoram sua visibilidade e mantêm seus clientes informados sobre ofertas, novidades e eventos.",posts_info_title:"Publicações GBP — Como funciona",posts_info_s1_title:"📝 Crie conteúdo",posts_info_s1_body:"Escreva publicações (oferta, novidade, evento) diretamente do LocalEdge. AVI pode escrever para você em um clique.",posts_info_s2_title:"📅 Agende",posts_info_s2_body:"Planeje suas publicações com antecedência para manter uma presença regular no Google.",posts_info_s3_title:"📈 Aumente sua visibilidade",posts_info_s3_body:"O Google favorece perfis ativos. Recomenda-se no mínimo 1 publicação por semana para aparecer no Pacote Local.",upgrade_posts_title:"✨ Automatize suas Publicações GBP",upgrade_posts_sub:"Avision Pro publica automaticamente · Modo autopiloto disponível",new_post_btn:"+ Nova publicação",write_content:"Conteúdo (máx. 1500 caracteres)",write_content_ph:"Escreva o conteúdo da publicação...",scheduled_date:"Data e hora agendadas",no_content:"Sem conteúdo",post_type_label:"Tipo de publicação",post_type_update:"📢 Atualização — Notícias e anúncios",post_type_offer:"🏷️ Oferta — Promoções",post_type_event:"📅 Evento — Atividades",post_type_update_short:"📢 Atualização",post_type_offer_short:"🏷️ Oferta",post_type_event_short:"📅 Evento",credits_info:"💳 Isso usará 2 créditos do seu saldo.",credits_2:"2 créditos",publication:"Publicação",publish_now_title:"⚡ Publicar agora",schedule_title:"🕐 Agendar",free:"Grátis",photo_optional:"Foto (opcional)",upload_device:"📁 Enviar do dispositivo",choose_photos:"🖼️ Escolher em Fotos",gallery_soon:"Em breve — configure sua galeria primeiro",gallery_first_alert:"Configure primeiro sua galeria GBP Photos (aba Fotos).",image_too_large:"Imagem muito grande — máx. 5 MB",err_no_content:"Digite o conteúdo da publicação.",err_content_long:"Conteúdo excede 1500 caracteres.",err_no_schedule:"Selecione uma data agendada.",err_create_post:"Erro ao criar publicação",err_network:"Erro de rede",err_generic:"Erro",no_posts:"Nenhuma publicação ainda",no_posts_sub:"Crie sua primeira publicação GBP para engajar clientes",posts_count_suffix:" publicação(ões)",event_title:"Título do evento",event_title_ph:"ex. Promoção de verão",start_date:"Data de início",end_date:"Data de término",filter_all:"Todos",post_status_published:"✅ Publicado",post_status_scheduled:"🕐 Agendado",post_status_pending:"⏳ Pendente",post_status_failed:"❌ Falhou",post_status_draft:"📝 Rascunho",view_btn:"👁 Ver",th_type:"Tipo",th_content:"Conteúdo",th_status:"Status",th_scheduled:"Agendado",th_published:"Publicado",th_actions:"Ações",sync_gbp:"🔄 Sincronizar do GBP",syncing:"Sincronizando...",publish_photo:"⚡ Publicar",schedule_photo:"🕐 Agendar",delete_photo_title:"Excluir da biblioteca",delete_confirm:"Excluir esta mídia da biblioteca?",rename_hint:"Clique para renomear",change_category:"Clique para alterar categoria",no_category:"Sem categoria",upload_photo:"+ Enviar foto",select_photo_picker:"📎 Selecione uma foto para sua publicação",schedule_date_prompt:"Data e hora (AAAA-MM-DDTHH:MM):",'
			. 'saving:"Salvando...",select_btn:"✓ Selecionar",copy_url:"Copiar URL",video_badge:"🎬 Vídeo",sync_failed:"Falha na sincronização",photos_sync_success:"\u2705 Fotos sincronizadas do Google",delete_gbp_title:"Excluir do GBP",delete_gbp_confirm:"Excluir esta foto do seu perfil do Google? Esta ação não pode ser desfeita.",delete_gbp_success:"Foto excluída do GBP",delete_gbp_error:"Falha ao excluir do GBP",bulk_download:"Baixar seleção",bulk_delete:"Excluir da library",bulk_delete_confirm:"Excluir {n} foto(s) da library?",bulk_delete_success:"{n} foto(s) excluída(s) da library",bulk_gbp_note:"\u26a0\ufe0f O Google não permite exclusão em massa de fotos \u2014 exclua uma por uma.",selected:"selecionada(s)",select_category:"— Selecionar categoria (oficial Google) —",rename_ph:"Nome otimizado (ex. encanador-sp-servico.jpg)",show_less_cats:"▲ Mostrar menos",show_all_cats:"▼ Todas as categorias GBP",photos_panel_title:"Fotos GBP",photos_panel_sub:"Gerencie suas fotos do Google Business Profile: envie, organize, publique e otimize para o SEO local.",photos_info_title:"Fotos GBP — Como funciona",photos_info_s1_title:"📚 Library / Published / Not Published",photos_info_s1_body:"Library = todas as suas fotos armazenadas no LocalEdge. Published = visíveis no seu perfil do Google. Not Published = enviadas mas ainda não publicadas no Google.",photos_info_s2_title:"🗂️ Categorias",photos_info_s2_body:"Organize suas fotos por categoria (exterior, interior, equipe, produtos…). Um perfil bem organizado inspira mais confiança nos clientes.",photos_info_s3_title:"✏️ Renomear para SEO",photos_info_s3_body:"O nome da foto importa para o SEO. Use nomes descritivos com suas palavras-chave (ex: \'restaurante-italiano-paris-terraco\'). Clique no ícone de lápis para renomear.",photos_info_s4_title:"⬇️ Baixar & 🗑️ Excluir",photos_info_s4_body:"Use \u0027\u2b07\ufe0f Baixar\u0027 para salvar uma foto. \u0027\ud83d\uddd1\ufe0f Excluir da library\u0027 remove apenas do LocalEdge. \u0027\ud83c\udf10 Excluir do GBP\u0027 remove permanentemente do seu perfil do Google (irreversível).",upgrade_photos_title:"✨ Mantenha sempre fotos atualizadas",upgrade_photos_sub:"Avision Pro agenda e publica suas fotos automaticamente para manter seu perfil sempre ativo · Modo autopiloto",photos_filter_library:"📚 Biblioteca",photos_filter_gbp_pub:"✅ Publicado no GBP",photos_filter_gbp_unpub:"📚 Não publicado",photo_category_label:"Categoria da foto",filter_all_cats:"Todas as categorias",download_label:"Baixar",upload_drag:"Arraste e solte fotos aqui",upload_drag_sub:"Fotos JPG/PNG (máx. 5 MB) · Vídeos MP4 (máx. 75 MB, 30s)",reply_btn:"💬 Responder",cancel_reply:"Cancelar",publish_reply:"Publicar resposta",publishing_reply:"Publicando...",reply_published:"Resposta publicada no Google!",write_reply_ph:"Escreva sua resposta...",avi_writes_review:"✨ AVI escreve",avi_rewrite_reply:"✨ Reescrever com AVI",edit_reply:"\\u270F\\uFE0F Editar",generating_reply:"✨ Gerando...",regenerate_reply:"↺ Regenerar",ai_reply_error:"AVI não conseguiu gerar uma resposta.",your_reply:"💬 Sua resposta · ",no_reviews:"Nenhuma avaliação encontrada",no_reviews_filter:"Nenhuma avaliação corresponde a este filtro",reviews_0:"0 avaliações",reviews_showing:"Exibindo ",reviews_of:" de ",reviews_suffix:" avaliações",load_more:"🔄 Carregar mais avaliações do Google",load_more_info:"✅ Todas as ",load_more_info_end:" avaliações carregadas do cache GBP · Sincronize via Avision Pro",load_more_loading:"Carregando avalia\u00e7\u00f5es...",filter_all_stars:"Todos ⭐",without_reply:"💬 Sem resposta",sort_recent:"Mais recentes",sort_oldest:"Mais antigas",sort_lowest:"Pior avaliação",sort_unanswered:"Sem resposta primeiro",per_page:" por página",previous:"← Anterior",next:"Próximo →",page_of:"Página ",gbp_reviews_title:"Avaliações do Google Business Profile",gbp_reviews_sub:"Responda diretamente para construir confiança",reviews_info_title:"Avaliações Google — Como funciona",reviews_info_s1_title:"⭐ Por que as avaliações importam",reviews_info_s1_body:"As avaliações do Google impactam diretamente seu ranking local e sua taxa de conversão. Um negócio com respostas recentes aparece melhor no Pacote Local.",reviews_info_s2_title:"✉️ Responda para gerar confiança",reviews_info_s2_body:"Responder a cada avaliação — positiva ou negativa — demonstra profissionalismo. AVI pode gerar uma resposta personalizada em um clique.",reviews_info_s3_title:"📅 Mantenha a consistência",reviews_info_s3_body:"Filtre por Novas, Esta semana, Este mês ou Este ano para priorizar suas respostas e não perder nenhuma avaliação.",tip_th_reviewer:"Nome e foto do cliente",tip_th_stars:"Avaliação do cliente (1–5 estrelas)",tip_th_date:"Data de publicação da avaliação",tip_th_review:"Conteúdo completo da avaliação do cliente",tip_th_replied:"Se você respondeu a esta avaliação",tip_th_actions:"Responder, editar ou regenerar uma resposta com AVI",filter_new:"Novas",filter_week:"Esta semana",filter_month:"Este mês",filter_year:"Este ano",filter_all_years:"Todos os anos",filter_all_months:"Todos os meses",filter_all_weeks:"Todas as semanas",filter_all_replies:"Todas as avaliações",filter_with_reply:"\u2705 Com resposta",flag_review_tip:"Reportar esta avaliação ao Google (spam, falsa, inapropriada)",th_report:"Reportar",tip_th_report:"Reportar esta avaliação ao Google (spam, falsa, inapropriada)",upgrade_ai_title:"🤖 Responda mais rápido com IA",upgrade_ai_sub:"Avision Pro gera respostas personalizadas em segundos · Modo autopiloto disponível",upgrade_link:"Atualizar para Avision Pro →",th_reviewer:"Autor",th_stars:"Estrelas",th_date:"Data",th_review:"Avaliação",th_replied:"Respondido",gbp_score_title:"📊 Pontuação GBP",profile_completeness:"Completude do perfil",profile_stats:"Estatísticas do perfil",last_sync:"🕐 Última sync: ",crit_name:"Nome da empresa",pts_0:"Info",crit_website:"Site",crit_phone:"Telefone",crit_hours:"Horário",crit_description:"Descrição do negócio",crit_category:"Categoria principal",crit_address:"Endereço",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ Feito",missing:"❌ Ausente",reviews_label:"avaliações",photos_label:"Fotos",avg_rank:"Posição média",score_urgent:"Requer atenção urgente",score_improve:"Margem de melhoria",score_getting:"No caminho certo",score_good:"Bom perfil",score_excellent:"Perfil excelente",unknown:"Desconhecido",upsell_slim:"✨ Atualize para Avision Pro — Guardian · RAG · Multi-perfil",learn_more:"▲ Saiba mais",'
			. 'learn_close:"▼ Fechar",upsell_local:"🏠 Negócio local",upsell_agency:"🏢 Agência",no_client:"Nenhum cliente encontrado",search_client_ph:"🔍 Buscar cliente...",clients_title:"👥 Clientes",clients_trigger:"👥 Clientes ▾",loading:"⏳ Carregando...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Sincronizar do Google",sync_info_title:"Sincronizar do Google",sync_info_score_body:"Atualiza sua Pontuação GBP e os dados do perfil diretamente do Google. Use se sua pontuação, avaliações ou atributos não refletirem as alterações recentes feitas no Google Business Profile.",sync_info_home_body:"Atualiza todas as estatísticas do seu painel — dados de classificação, avaliações e histórico de varreduras. Use se suas estatísticas parecerem desatualizadas ou se você fez alterações recentes no seu Google Business Profile.",sync_info_footer:"Os dados são atualizados automaticamente a cada 24h. Este botão força uma atualização imediata.",help_title:"Ajuda & FAQ",help_subtitle:"Encontre respostas para perguntas frequentes sobre seu Google Business Profile",help_s1_title:"🔴 Top 5 — Problemas frequentes",help_s2_title:"🟣 Otimizar meu perfil",help_s3_title:"🔵 Atualizações do Google",help_faq1_q:"🚫 Meu perfil está suspenso",help_faq1_a:"O Google suspende perfis por nomes com palavras-chave, inconsistências de endereço ou muitas edições rápidas. Corrija o problema primeiro, depois envie uma solicitação de reintegração com provas (conta de luz, contrato, licença). Nunca crie um perfil duplicado durante o processo.",help_faq2_q:"🔍 Meu perfil não aparece no Google Maps",help_faq2_a:"Verifique se seu perfil está totalmente verificado e publicado. Perfis não verificados não aparecem. Novos perfis podem levar 2 a 4 semanas para aparecer consistentemente. Verifique também a consistência do seu NAP no site e em outros diretórios.",help_faq3_q:"✅ Como verificar meu perfil (vídeo)",help_faq3_a:"A verificação por vídeo é o método padrão em 2026. Grave um vídeo contínuo mostrando sua fachada, interior e uma ação ao vivo no painel do GBP. Certifique-se de que nome, endereço e site correspondam antes de tentar.",help_faq4_q:"✏️ Edições não autorizadas foram feitas no meu perfil",help_faq4_a:"Qualquer pessoa pode sugerir edições e o Google pode aceitá-las automaticamente. Verifique suas informações regularmente e reverta alterações incorretas pelo painel do GBP. O modo Guardian do LocalEdge monitora seus campos principais 24 horas por dia.",help_faq5_q:"⭐ Não consigo responder às avaliações",help_faq5_a:"Isso geralmente indica uma restrição de perfil, não uma suspensão completa. Verifique as notificações no painel do GBP. Certifique-se de estar conectado à conta Google correta que possui o perfil.",help_faq6_q:"📸 Quais fotos publicar e quantas?",help_faq6_a:"Publique pelo menos 10 fotos: fachada, interior, equipe, produtos ou serviços. Adicione novas fotos todo mês — o Google recompensa perfis ativos. Evite fotos de banco ou geradas por IA. Fotos reais do seu negócio geram confiança e melhoram seu posicionamento.",help_faq7_q:"🏷️ Como escolher a categoria principal correta?",help_faq7_a:"A categoria principal é a maior alavanca de posicionamento no Google Maps. Escolha a categoria mais específica que corresponda ao seu serviço principal. Um encanador deve escolher Encanador, não Serviços domésticos. Você pode adicionar categorias secundárias para outros serviços.",help_faq8_q:"📝 Como escrever uma boa descrição?",help_faq8_a:"Escreva de 250 a 750 caracteres descrevendo o que você faz, quem você atende e o que o diferencia. Inclua suas palavras-chave principais de forma natural. Evite linguagem promocional, URLs ou números de telefone. Atualize a cada 6 meses.",help_faq9_q:"🗓️ Com que frequência publicar posts?",help_faq9_a:"Publique pelo menos uma vez por semana para manter sinais de atualização. Use o AVI na aba Posts para gerar e agendar conteúdo em segundos. Posts de Novidades expiram após 7 dias, Eventos persistem até a data de término.",help_faq10_q:"⭐ Como conseguir mais avaliações de clientes?",help_faq10_a:"Peça a cada cliente satisfeito imediatamente após o serviço. Envie um link direto de avaliação por email ou SMS. Adicione um QR code nos seus recibos ou cartões. Nunca ofereça incentivos nem diga o que devem escrever — o Google penaliza isso em 2026.",help_faq11_q:"📍 Endereço visível ou área de atendimento?",help_faq11_a:"Se clientes visitam seu estabelecimento, mostre seu endereço. Se você visita clientes, oculte o endereço e adicione áreas de atendimento. Mostrar endereço residencial quando você visita clientes pode gerar confusão e risco de suspensão.",help_faq12_q:"🔄 Tenho um perfil duplicado — o que fazer?",help_faq12_a:"Perfis duplicados dividem suas avaliações e confundem o Google. Pesquise seu negócio no Google Maps e denuncie o duplicado via Sugerir uma edição. O Google mesclará ou removerá o perfil extra. Nunca gerencie dois perfis para o mesmo negócio.",help_faq13_q:"🤖 Q&A removido — substituído pelo Ask Maps (Gemini)",help_faq13_a:"O Google removeu o recurso Q&A e o substituiu pelo Ask Maps, com tecnologia Gemini AI. O Gemini responde perguntas de usuários com base nos campos do seu perfil, avaliações, fotos e site. Preencha todos os campos do GBP e adicione conteúdo FAQ no seu site com marcação schema.",help_faq14_q:"🛡️ Novas regras de avaliações em 2026",help_faq14_a:"O Google atualizou sua política de avaliações no início de 2026. Avaliações geradas por IA agora são proibidas. Você ainda pode pedir avaliações, mas não deve ditar o que escrever. Um pedido neutro como compartilhe sua experiência honesta é seguro.",help_faq15_q:"⚡ Edições rápidas podem causar suspensão",help_faq15_a:"Fazer muitas alterações de uma vez — nome, endereço, categoria, horários — é um gatilho frequente de suspensão em 2026. Espaçe suas edições ao longo de vários dias. O modo Guardian do LocalEdge rastreia alterações e avisa antes de atingir um limite de risco.",syncing_btn:"⏳ Sincronizando...",sync_success:"✅ Perfil sincronizado!",sync_error:"Falha. Tente novamente.",add_credits:"+ Cr\\u00e9ditos pool",assign_credits:"+ Cr\\u00e9ditos",assign_min_hint:"M\\u00EDn. 10 cr \\u00b7 M\\u00FAltiplos de 10",select_all:"Selecionar tudo",bulk_cr_each:"cr cada",bulk_assigning:"Atribuindo...",bulk_assigned:"\\u2705 clientes creditados",'
			. 'picker_title:"Escolha seu perfil Google Business",picker_subtitle:"Selecione o perfil que deseja gerenciar com LocalEdge.",picker_btn:"Selecionar este perfil",picker_loading:"Conectando...",picker_error:"Erro ao conectar. Tente novamente.",picker_select_all:"Selecionar tudo",picker_import:"Importar fichas selecionadas",'
			. 'onboarding_title:"Conecte sua ficha Google Business",onboarding_subtitle:"Vincule seu GBP para desbloquear todos os recursos: pontua\\u00e7\\u00e3o, avalia\\u00e7\\u00f5es, fotos, posts e mais.",onboarding_connect:"\\uD83D\\uDD17 Conectar Google Business",onboarding_skip:"Farei isso mais tarde",onboarding_step1_title:"1. Entrar",onboarding_step1_desc:"Conecte sua conta Google",onboarding_step2_title:"2. Selecionar",onboarding_step2_desc:"Escolha seu perfil",onboarding_step3_title:"3. Pronto!",onboarding_step3_desc:"Todos os recursos ativados",edu_banner_title:"🎯 Bem-vindo ao seu Centro de Controle SEO Local",edu_banner_body:"Seu GBP est\\u00e1 conectado. Otimize sua pontua\\u00e7\\u00e3o e supere seus concorrentes.",edu_banner_close:"Entendi \\u2713",edu_help_btn:"💡",edu_modal_title:"Como o LocalEdge funciona",edu_step1_title:"Passo 1 — Complete seu perfil",edu_step1_body:"Seu perfil GBP est\\u00e1 conectado \\u2705 Este \\u00e9 o seu ponto de partida. Acesse a aba GBP Score para ver rapidamente quais campos est\\u00e3o incompletos. Telefone, hor\\u00e1rios, descri\\u00e7\\u00e3o, fotos, categorias — cada campo ausente custa posi\\u00e7\\u00f5es no Google Maps. Um perfil 100% completo gera at\\u00e9 2x mais cliques.",edu_step2_title:"Passo 2 — Escaneie e analise",edu_step2_body:"Na aba Heatmap, selecione 1 a 5 palavras-chave que descrevam seu neg\\u00f3cio (ex. \\u0027encanador S\\u00e3o Paulo\\u0027). Lance seu primeiro scan — cada ponto da grade mostra sua posi\\u00e7\\u00e3o real no Google Maps naquela \\u00e1rea. N\\u00e3o se preocupe: cada p\\u00e1gina tem bot\\u00f5es \\u2139\\uFE0F para orient\\u00e1-lo em cada etapa.",edu_step3_title:"Passo 3 — Otimize e cres\\u00e7a",edu_step3_body:"Agora que voc\\u00ea sabe onde est\\u00e1, tome a\\u00e7\\u00e3o. GBP Score: corrija os campos priorit\\u00e1rios para subir nos resultados. Posts e Fotos: \\u2728 AVI redige e agenda seu conte\\u00fado em segundos. Avalia\\u00e7\\u00f5es: responda em at\\u00e9 24h com \\u2728 AVI — o Google recompensa empresas que interagem com seus clientes.",edu_learn_more:"Como funciona \\u2192",tt_score:"Sua pontua\\u00e7\\u00e3o GBP mede a completude e otimiza\\u00e7\\u00e3o do seu perfil. Uma pontua\\u00e7\\u00e3o acima de 70 melhora significativamente sua visibilidade no Pacote Local do Google. Encontre-o na aba GBP Score \\u2192",tt_unanswered:"Responder avalia\\u00e7\\u00f5es em 24h melhora sua pontua\\u00e7\\u00e3o de confian\\u00e7a no Google. Acesse a aba Google Reviews para responder \\u2192",tt_next_scan:"Scans regulares acompanham a evolu\\u00e7\\u00e3o da sua visibilidade local. Lance um scan na coluna 3 \\u2192",tt_nap:"A completude do seu perfil impacta diretamente seu ranking local. Corrija-os na aba GBP Score \\u2192",tt_control_center:"Seu resumo do GBP: pontua\\u00e7\\u00e3o, avalia\\u00e7\\u00f5es sem resposta, pr\\u00f3ximo scan agendado e completude do perfil \\u2014 tudo em um lugar para priorizar o que corrigir.",clients_count_suffix:" cliente(s)",pool_credits:"💳 Créditos pool: ",available_word:" disponíveis · ",used_word:" usados",never:"Nunca",today:"Hoje",yesterday:"Ontem",sort_priority:"🚨 Prioridade (score baixo primeiro)",sort_best_score:"⭐ Melhor score primeiro",sort_activity:"🕐 Última atividade",sort_name:"A→Z Nome",sort_kw:"🔑 Mais palavras-chave",scan_badge:" scan(s)",kw_badge:" palavras-chave",logo_too_large:"Logo muito grande — máx. 2 MB",upload_logo:"📁 Enviar logo",or_sep:"— ou —",agency_hub_title:"Hub Agência",col_suffix:" col",cols_suffix:" cols",err_rename:"Erro de rede ao renomear",err_file_too_large:"Arquivo muito grande",tip_col_keyword:"Termo de pesquisa rastreado",tip_col_rank:"Posição média atual em todos os pontos do mapa de calor",tip_col_best:"Melhor posição já registrada",tip_col_grid:"Tamanho da grade do último scan",tip_col_status:"Pendente = nunca escaneado · Escaneado = com dados",tip_col_scan:"Data + tipo de scan (solo ou multi)",tip_col_threat:"⚠️ Concorrente domina o Top 3 em mais de 50 % dos pontos",filter_danger:"⚠️ Perigo",filter_solo_scan:"🔍 Scan solo",filter_multi_scan:"📊 Scan multi",filter_az:"A→Z",filter_all_grids:"Todas as grades",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" palavras-chave)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Ainda não escaneado",export_col_city:"Cidade",export_col_scan_type:"Tipo de scan",export_yes:"Sim",export_no:"Não",export_danger_yes:"⚠️ Sim",kw_report_title:"Relatório de palavras-chave",kw_report_generated:"Gerado:",kw_report_keywords_suffix:" palavras-chave",import_kw_tip:"Importar várias palavras-chave (uma por linha ou CSV)",add_kw_ph:"Digite palavra-chave (ex. Encanador São Paulo)",import_kw_ph:"Encanador São Paulo\\nEletricista Rio\\nTelhado Curitiba",post_char_of:" / 1500",post_add_photo:"📷 Adicionar foto",post_photo_formats:"JPG, PNG — máx. 5 MB",export_col_created:"Criado",posts_page_title:"Posts GBP",posts_report_title:"Relatório Posts GBP",photo_status_in_stock:"📚 Na biblioteca",photos_count_suffix:" foto(s)",no_photos:"Nenhuma foto ainda",no_photos_sub:"Envie fotos para criar sua biblioteca GBP",photo_alt_default:"Foto GBP",photo_sched_vid:"5 cr",photo_sched_img:"3 cr",err_rename_failed:"Falha ao renomear",export_col_file:"Arquivo",export_col_category:"Categoria",photos_page_title:"Fotos GBP",photos_report_title:"Relatório Fotos GBP",photos_library_count_suffix:" fotos na biblioteca",cat_cover:"🖼️ Capa",cat_profile:"👤 Perfil",cat_logo:"🎨 Logo",cat_interior:"🏠 Interior",cat_exterior:"🏢 Exterior",cat_product:"📦 Produto",cat_at_work:"💼 No trabalho",cat_food_drink:"🍽️ Comida e bebida",cat_menu:"📋 Cardápio",cat_common_area:"🛋️ Área comum",cat_rooms:"🛏️ Quartos",cat_teams:"👥 Equipes",cat_additional:"➕ Adicional",rv_replied_yes:"✅ Sim",rv_replied_no:"❌ Não",export_col_reply:"Resposta",export_col_has_reply:"Respondido",reviews_page_title:"Relatório Avaliações",reviews_report_title:"Relatório Avaliações Google",reviews_pdf_avg:"⭐ Média: ",reviews_pdf_reviews_suffix:" avaliações",export_col_criterion:"Critério",export_col_points:"Pontos",score_export_done:"Feito",score_export_missing:"Faltando",score_export_score:"Score",score_export_rating:"Nota",score_export_photos:"Fotos",score_report_title:"Relatório Score GBP",score_pdf_stats:"Estatísticas",score_pdf_rating:"⭐ Nota: ",score_pdf_photos:"📸 Fotos: ",rel_d_ago:"d",rel_w_ago:"sem",rel_mo_ago:"mês",rel_y_ago:"a",hub_subtitle:"Gerencie configurações da agência, créditos e white-label.",hub_credit_pool:"💳 Pool de créditos",hub_tier_label:"Plano atual",hub_tier_t1:"Tier 1 — at\u00e9 10 fichas",hub_tier_t2:"Tier 2 — at\u00e9 50 fichas",hub_tier_t3:"Tier 3 — fichas ilimitadas",hub_listings_gauge:"Fichas ativas",hub_tier_upgrade:"Melhorar plano",hub_tier_downgrade:"Reduzir plano",hub_upgrade_processing:"Redirecionando para pagamento...",hub_downgrade_confirm:"Confirmar mudan\u00e7a para este plano?",hub_downgrade_blocked:"Redu\u00e7\u00e3o bloqueada: muitas fichas ativas.",hub_downgrade_success:"Plano atualizado com sucesso.",hub_info_upgrade:"Upgrade: voc\u00ea paga apenas a diferen\u00e7a entre os planos (prorata).",hub_info_downgrade:"Downgrade: gratuito, sem reembolso. Bloqueado se as fichas ativas excederem o limite do novo plano.",hub_available:"Disponíveis",hub_used:"Usados",hub_buy_credits:"+ Comprar créditos (atacado)",hub_whitelabel:"🎨 White-label",hub_whitelabel_desc:"URL do logo e nome da marca exibidos no embed e PDFs.",hub_logo_ph:"https://seulogo.com/logo.png",hub_brand_ph:"Nome da sua agência",hub_save_settings:"Salvar",saved:"Salvo \u2713",hub_save_alert:"Configurações white-label — Sprint 45",hub_import_clients:"📥 Importar clientes",hub_import_csv_desc:"Formato CSV: business_name, city, category, country",hub_import_csv_btn:"Importar CSV",hub_import_alert:"Importação CSV — Sprint 45",hub_pro_title:"🚀 Avision Pro Agência",hub_pro_sub:"Visão helicóptero · Ações em massa · Relatórios avançados · Guardian completo",hub_pro_cta:"Upgrade para Avision Pro Agência →",profile_title:"Meu Perfil",profile_subtitle:"Gerencie seus créditos e conta.",profile_credits_available:"Créditos disponíveis",profile_credits_used:"Usados",profile_buy:"+ Comprar créditos",profile_pack_nano:"Nano — 10 créditos",profile_pack_mini:"Mini — 30 créditos",profile_pack_standard:"Standard — 75 créditos",profile_pack_pro:"Pro — 200 créditos",profile_pack_agency:"Agência — 600 créditos",profile_price_nano:"$2",profile_price_mini:"$5",profile_price_standard:"$11",profile_price_pro:"$25",profile_price_agency:"$59",profile_save_economy:" — economize ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Dashboard completo · Guardian \\u00b7 SEO avançado",profile_upsell_cta:"Upgrade para Avision Pro \\u2192",credits_modal_title:"💳 Seus créditos LocalEdge",credits_modal_solo_p1:"Seus créditos LocalEdge são permanentes — nunca expiram. Compre quando precisar, use no seu ritmo.",credits_modal_usage_title:"Onde gastar seus créditos:",credits_modal_heatmap:"🗺️ Scan heatmap — de 2 cr (3×3) a 60 cr (21×21)",credits_modal_post:"📝 Publicação GBP Post via AVI — 3 cr",credits_modal_photo:"📷 Sincronização de foto GBP — 2 cr",credits_modal_guardian:"🔔 Guardian (monitoramento de perfil) — gratuito, incluído",credits_modal_savings_title:"Quanto mais você compra, menos paga por crédito.",credits_modal_savings_sub:"O pacote Pro por $25 custa 38% menos por crédito que o pacote Nano.",credits_modal_agency_title:"💳 Seu pool de créditos de agência",credits_modal_agency_p1:"Seu pool é compartilhado entre todos os perfis de clientes. Compre no atacado, distribua conforme necessário.",credits_modal_agency_wholesale:"Preço no atacado — seus créditos de agência custam até 47% menos que as tarifas padrão. Sua margem é livre.",credits_modal_agency_noexpiry:"Sem expiração — seus créditos ficam disponíveis indefinidamente.",purchase_success_title:"\u2713 Pagamento recebido!",purchase_success_sub:"Seus cr\u00e9ditos estar\u00e3o dispon\u00edveis em alguns segundos.",purchase_success_close:"Entendido",slider_title:"Ou escolha seu pr\u00f3prio valor",slider_credits:"cr\u00e9ditos",slider_price_per:"por cr\u00e9dito",slider_vs_nano:"vs Nano",slider_buy_btn:"Comprar",slider_min_label:"10 cr",slider_max_label_solo:"1.000 cr",slider_max_label_agency:"5.000 cr",client_balance:"Saldo do cliente",cr_need:"Necess\u00e1rio",cr_available:"Dispon\u00edvel",cr_missing:"Faltando",days_ago:"d",attr_other:"Outro",anonymous_reviewer:"An\u00f4nimo",error_generic:"Ocorreu um erro.",vs_standard:"vs padr\u00e3o",badge_discount_17:"-17%",badge_discount_27:"-27%",badge_discount_38:"-38%",badge_discount_16:"-16%",badge_discount_30:"-30%",badge_discount_40:"-40%",badge_discount_47:"-47%",ag_pack_starter:"Starter Agência — 100 créditos",ag_pack_standard:"Standard Agência — 300 créditos",ag_pack_pro:"Pro Agência — 750 créditos",ag_pack_enterprise:"Enterprise Agência — 2000 créditos",ag_price_starter:"$14",ag_price_standard:"$35",ag_price_pro:"$75",ag_price_enterprise:"$175",logo_preview_alt:"Prévia do logo",hub_uploaded_file:"(arquivo enviado)",ag_no_scan:"🗺️ Sem scan",gbp_open_title:"Abrir ficha GBP: ",gbp_search_title:"Pesquisar no Google Maps: ",gbp_score:"Score GBP",unanswered:"Sem resposta",unanswered_sub:"avalia\u00e7\u00f5es para responder",credits_left:"Cr\u00e9ditos",next_scan:"Pr\u00f3ximo scan",no_scan:"Sem scan",nap_status:"Completude perfil",nap_name:"Nome",nap_address:"Endere\u00e7o",nap_phone:"Telefone",nap_website:"Site",nap_hours:"Hor\u00e1rio",nap_desc:"Descri\u00e7\u00e3o",fix_it:"Completar \\u2192",edit:"Editar",fix:"Corrigir",edit_name:"Editar nome",name_warn:"Alterar o nome pode acionar uma revis\u00e3o do Google. Use seu nome comercial real.",edit_website:"Editar site",edit_phone:"Editar telefone",edit_hours:"Editar hor\u00e1rio",edit_description:"Editar descri\u00e7\u00e3o",edit_categories:"Editar categorias",edit_address:"Editar endere\u00e7o",edit_success:"Atualizado com sucesso no Google!",edit_error:"Erro ao atualizar. Tente novamente.",lodging_posts_warn:"As publica\u00e7\u00f5es GBP n\u00e3o est\u00e3o dispon\u00edveis para hospedagens.",hours_closed:"Fechado",hours_open:"Aberto",cat_search_placeholder:"Pesquisar categorias do Google...",cat_primary:"Categoria principal",cat_additional:"Categorias adicionais (m\u00e1x 9)",cat_lodging_warn:"Alterar sua categoria principal pode afetar os recursos do seu perfil.",addr_neighborhood:"Bairro / Distrito",addr_street:"Endere\u00e7o",addr_city:"Cidade",addr_region:"Estado / Regi\u00e3o",addr_postal:"CEP",addr_country:"C\u00f3digo do pa\u00eds (ex. BR)",verified:"Verificado",pending_verification:"Verificação pendente",not_verified:"Não verificado",verify_cta_text:"Seu perfil n\u00e3o est\u00e1 verificado no Google. Perfis verificados t\u00eam mais visibilidade.",verify_cta_btn:"Verificar meu perfil \u2192",verify_pending_text:"Verifica\u00e7\u00e3o em andamento. O Google pode levar at\u00e9 7 dias.",score_panel_sub:"Sua pontua\u00e7\u00e3o de otimiza\u00e7\u00e3o do Google Business Profile. Cada campo preenchido melhora sua visibilidade nos resultados de pesquisa local.",score_info_title:"Score GBP \u2014 Como funciona",score_info_s1_title:"\uD83C\uDFAF Como a pontua\u00e7\u00e3o \u00e9 calculada",score_info_s1_body:"Base 30 pts + Site (+5) + Hor\u00e1rio (+3) + Descri\u00e7\u00e3o 200+ car. (+2) + Categoria adicional (+1) + Atributos \u22653 (+1). M\u00e1ximo: 42 pts.",score_info_s2_title:"\uD83D\uDCC8 Por que isso importa",score_info_s2_body:"Um perfil completo e otimizado aparece melhor no Pacote Local do Google. Cada campo faltante custa visibilidade em pesquisas locais.",score_info_s3_title:"\u270F\uFE0F Como melhorar",score_info_s3_body:"Clique em Editar ou Corrigir em cada crit\u00e9rio para atualizar diretamente do LocalEdge \u2014 sem abrir seu perfil do Google.",gbp_attributes_title:"Atributos GBP",attr_na:"N/A para esta categoria",attr_url_gbp_hint:"Editar no Google Business Profile",attrs_filled:"Configurados",crit_posts:"Publica\u00e7\u00f5es recentes",crit_photos:"Fotos publicadas",photos_published_label:"publicadas",photos_min:"m\u00edn. 3 recomendadas",post_stale:"\u00daltima publica\u00e7\u00e3o > 7 dias \u2014 publique para manter seus pontos",post_fresh:"Fresco \u2014 publicado nos \u00faltimos 7 dias",post_upsell:"Agende uma publica\u00e7\u00e3o para manter sua pontua\u00e7\u00e3o",photo_stale:"\u00daltima foto > 7 dias \u2014 publique para manter seus pontos",photo_fresh:"Fresca \u2014 foto publicada nos \u00faltimos 7 dias",photo_upsell:"Publique uma foto para manter sua pontua\u00e7\u00e3o",crit_reviews_reply:"\u00daltima avalia\u00e7\u00e3o respondida",replied:"Respondida",not_replied:"Sem resposta",no_reviews_yet:"Nenhuma avalia\u00e7\u00e3o ainda",freshness_note:"Sua pontua\\u00e7\\u00e3o varia com sua atividade: publica\\u00e7\\u00f5es, fotos, respostas a avalia\\u00e7\\u00f5es, completude do perfil e scans do mapa de calor impactam seu ranking. Fique ativo para maximizar seus pontos.",view:"Ver",reply:"Responder",attr_saved:"Atributo atualizado",attr_error:"Falha ao atualizar atributo",attrs_load_error:"N\u00e3o foi poss\u00edvel carregar os atributos",attrs_load_hint:"Clique em \uD83D\uDD04 Sync from Google para recarregar",hm_section_title:"🗺️ Visibilidade Heatmap",hm_info_title:"Heatmap — Por que muda tudo",hm_info_s1_title:"📍 Conheça sua posição exata",hm_info_s1_body:"Cada scan mapeia sua posição no Google Maps em cada ponto da grade do bairro. Você vê exatamente onde domina e onde os concorrentes te superam — rua por rua.",hm_info_s2_title:"🏆 Analise seus concorrentes",hm_info_s2_body:"O mapa de calor revela quais concorrentes ocupam o top 3 em cada ponto da grade. Identifique quem superar, em quais zonas, e ajuste sua estratégia de SEO local.",hm_info_s3_title:"📐 Tamanho da grade = controle do território",hm_info_s3_body:"Uma grade 7x7 cobre seu bairro imediato. Uma 13x13 mapeia toda sua cidade. Quanto maior a grade, mais território você controla e mais dados tem para decisões estratégicas.",hm_info_s4_title:"🔄 Scans regulares = ganhos de posição",hm_info_s4_body:"Escaneie a mesma palavra-chave semanalmente para rastrear sua progressão. Cada scan usa créditos mas fornece dados acionáveis: você está ganhando ou perdendo posições? Reaja antes que concorrentes tomem seus lugares.",hm_activity_label:"Atividade scans",hm_performance_label:"Performance local",hm_coverage_label:"Cobertura território",hm_scan_now:"Lançar um scan",hm_stale_warn:"Nenhum scan há 30+ dias — seus dados estão desatualizados",hm_no_scan:"Nenhum scan ainda — comece a mapear seu território",control_center:"Central de controle",guardian_badge:"\ud83d\udd14 Alertas",guardian_modal_title:"Guardian Lite \u2014 Alertas do perfil",guardian_no_alerts:"Nenhum alerta detectado",guardian_plan_free:"Plano gratuito \u2014 sem monitoramento",guardian_plan_lite:"Lite \u2014 varredura 1x\/m\u00eas",guardian_plan_standard:"Standard \u2014 varredura semanal",guardian_plan_daily:"Varredura di\u00e1ria ativa",guardian_field_title:"Nome da empresa alterado",guardian_field_phone:"N\u00famero de telefone alterado",guardian_field_categories:"Categoria alterada",guardian_field_hours:"Hor\u00e1rios alterados",guardian_field_website:"Site alterado",guardian_field_openInfo:"Status aberto\/fechado alterado",guardian_why_title:"Por que monitorar seu perfil?",guardian_why_1:"Qualquer pessoa pode sugerir edi\u00e7\u00f5es no seu GBP \u2014 incluindo concorrentes",guardian_why_2:"Os Local Guides t\u00eam muito poder e podem marcar seu neg\u00f3cio como fechado",guardian_why_3:"Altera\u00e7\u00f5es n\u00e3o detectadas causam queda no ranking e perda de visibilidade",guardian_fix_btn:"Corrigir no GBP Score \u2192",guardian_mark_read:"Marcar tudo como lido",guardian_detected:"Detectado em:",guardian_old:"Antes:",guardian_new:"Depois:",guardian_verify:"verificar imediatamente",guardian_fix_now:"Corrigir agora",guardian_field_address:"Endere\u00e7o",guardian_field_description:"Descri\u00e7\u00e3o",guardian_field_specialHours:"Hor\u00e1rios especiais",guardian_field_serviceArea:"\u00c1rea de atendimento",crit_special_hours:"Hor\u00e1rios especiais",crit_service_area:"\u00c1rea de atendimento",special_hours_edit_info:"Os hor\u00e1rios especiais devem ser gerenciados diretamente no Google Business Profile.",service_area_edit_info:"A \u00e1rea de atendimento deve ser gerenciada diretamente no Google Business Profile.",guardian_changed:"alterado",guardian_fix_gbp:"Corrigir no GBP \u2192",crit_open_status:"Status do neg\u00f3cio",open_info_warn:"Modificar este status atualizar\u00e1 seu perfil do Google Business imediatamente.",open_status_open:"Aberto \u2014 Hor\u00e1rio normal",open_status_temp:"Fechado temporariamente \u2014 reabertura prevista",open_status_perm:"Fechado permanentemente \u2014 verificar urgentemente",open_status_open_no_hours:"Aberto \u2014 Sem hor\u00e1rio principal",open_status_unknown:"Status desconhecido",cit_title:"Cita\u00e7\u00f5es",cit_listed:"adicionadas",cit_done:"Adicionado",cit_mark_done:"\u2713 Adicionar",cit_already:"J\u00e1 listado",cit_mark_already:"\u2713 J\u00e1 listado",cit_trust:"Confiamos em voc\u00ea \u2014 n\u00e3o verificamos isso automaticamente",cit_url_placeholder:"URL da sua ficha (opcional)",cit_section_universal:"\ud83c\udf0d Universal",cit_section_local:"\ud83c\udff3\ufe0f Brasil",cit_section_niche:"\ud83c\udfaf Seu setor",cit_todo:"\ud83d\udccb A fazer",cit_completed:"Conclu\u00eddos",cit_collapse:"\u25b2 Recolher",cit_expand:"\u25bc Expandir",cit_undo:"\u21a9 Desfazer",cit_remove:"Remover",cit_add_name:"Nome do diret\u00f3rio",cit_add_url:"https://...",cit_add_btn:"+ Adicionar",cit_banner_msg:"Selecionamos automaticamente diret\u00f3rios com base na sua categoria do Google Business \"{cat}\". Algumas sugest\u00f5es podem n\u00e3o ser perfeitas \u2014 sinta-se \u00e0 vontade para remov\u00ea-las ou adicionar as suas.",cit_your_category:"sua categoria",cit_panel_sub:"Acompanhe suas listagens em diret\u00f3rios para melhorar sua visibilidade de SEO local.",cit_info_title:"Cita\u00e7\u00f5es & SEO Local",cit_info_s1_title:"\ud83d\udccd O que \u00e9 uma cita\u00e7\u00e3o?",cit_info_s1_body:"Uma cita\u00e7\u00e3o \u00e9 qualquer men\u00e7\u00e3o online do nome, endere\u00e7o e telefone (NAP) do seu neg\u00f3cio. Os motores de busca usam cita\u00e7\u00f5es para verificar a legitimidade do seu neg\u00f3cio e melhorar seu posicionamento local.",cit_info_s2_title:"\u26a0\ufe0f A consist\u00eancia do NAP \u00e9 cr\u00edtica",cit_info_s2_body:"Seu nome, endere\u00e7o e telefone devem ser exatamente id\u00eanticos em todos os diret\u00f3rios \u2014 mesmas abrevia\u00e7\u00f5es, mesma pontua\u00e7\u00e3o, mesmo formato. At\u00e9 pequenas diferen\u00e7as confundem os motores de busca.",cit_info_s3_title:"\ud83c\udfaf Por que esses diret\u00f3rios?",cit_info_s3_body:"Selecionamos automaticamente diret\u00f3rios com base na sua categoria do Google Business e localiza\u00e7\u00e3o. Algumas sugest\u00f5es de nicho podem n\u00e3o ser perfeitas \u2014 remova-as ou adicione as suas.",cit_info_s4_title:"\u2705 J\u00e1 est\u00e1 listado?",cit_info_s4_body:"Se seu neg\u00f3cio j\u00e1 est\u00e1 em um diret\u00f3rio, clique em \u2018J\u00e1 listado\u2019 e adicione opcionalmente a URL. Confiamos em voc\u00ea \u2014 n\u00e3o verificamos isso automaticamente, mas podemos fazer isso no futuro.",cit_score_section:"\ud83d\udccb Cita\u00e7\u00f5es",cit_score_label:"Diret\u00f3rios",cit_score_detail:"diret\u00f3rios listados",cit_stale_warn:"Adicione um diret\u00f3rio para manter sua pontua\u00e7\u00e3o",sh_title:"Hist\\u00f3rico Score & Posi\\u00e7\\u00e3o",sh_daily:"Di\\u00e1rio",sh_score:"Score GBP",sh_rank:"Posi\\u00e7\\u00e3o m\\u00e9dia",sh_drop:"Queda",sh_all_kw:"Todas as palavras-chave",sh_no_data:"Sem dados ainda. Execute um scan heatmap para come\\u00e7ar o rastreamento.",sh_start:"In\\u00edcio",sh_now:"Agora",sh_best_rank:"Melhor posi\\u00e7\\u00e3o",sh_info_title:"Entendendo seu Hist\\u00f3rico de Score & Posi\\u00e7\\u00e3o",sh_info_s1_title:"\\ud83d\\udcc8 Score GBP (roxo)",sh_info_s1_body:"Sua pontua\\u00e7\\u00e3o de otimiza\\u00e7\\u00e3o do Google Business Profile de 0 a 100. Sobe ao completar seu perfil, adicionar fotos, obter avalia\\u00e7\\u00f5es e corrigir alertas Guardian.",sh_info_s2_title:"\\ud83d\\udccd Posi\\u00e7\\u00e3o m\\u00e9dia (\\u00e2mbar)",sh_info_s2_body:"Sua posi\\u00e7\\u00e3o m\\u00e9dia nos resultados do Google Maps em todos os pontos da grade heatmap. Menor \\u00e9 melhor \\u2014 posi\\u00e7\\u00e3o #1 significa que voc\\u00ea aparece primeiro.",sh_info_s3_title:"\\u26a0\\ufe0f Por que minha posi\\u00e7\\u00e3o flutua?",sh_info_s3_body:"A posi\\u00e7\\u00e3o GBP varia de acordo com a localiza\\u00e7\\u00e3o do pesquisador, a palavra-chave usada, a hora do dia e as atualiza\\u00e7\\u00f5es do algoritmo do Google. \\u00c9 normal \\u2014 acompanhe a tend\\u00eancia, n\\u00e3o os pontos individuais.",sh_info_s4_title:"\\ud83d\\udd34 Pontos vermelhos",sh_info_s4_body:"Um ponto vermelho sinaliza uma queda acentuada: -10 pts ou mais no score, ou +5 posi\\u00e7\\u00f5es perdidas no ranking. S\\u00e3o momentos para investigar \\u2014 verifique os alertas Guardian para essa data.",tab_profile:"Perfil",tab_attributes:"Atributos",tab_history:"Histórico",card_nap:"NAP & Info",card_online:"Presença online",card_activity:"Atividade",card_visibility:"Visibilidade",sh_fullscreen:"Tela cheia",sh_exit_fs:"Sair",card_nap_info_title:"NAP & SEO Local",card_nap_s1_title:"📍 O que é NAP?",card_nap_s1_body:"NAP significa Nome, Endereço e Telefone. Os motores de busca usam o NAP para verificar seu negócio. NAP incoerente prejudica seu posicionamento local.",card_nap_s2_title:"🎯 Por que importa",card_nap_s2_body:"O Google compara seu GBP com outros diretórios. Se seu nome ou endereço difere, gera dúvidas e reduz sua posição local.",card_nap_s3_title:"✅ O que fazer",card_nap_s3_body:"Mantenha seu nome, endere\u00e7o, telefone e categoria estritamente id\u00eanticos no Google Business Profile e em todos os diret\u00f3rios. Use a aba Cita\u00e7\u00f5es para acompanhar seus cadastros.",card_nap_s4_title:"\u26a0\ufe0f Risco de reverifica\u00e7\u00e3o ou suspens\u00e3o",card_nap_s4_body:"Evite modificar sua categoria, descri\u00e7\u00e3o ou informa\u00e7\u00f5es-chave rapidamente demais. Os algoritmos do Google precisam de tempo para integrar as mudan\u00e7as. Muitas modifica\u00e7\u00f5es r\u00e1pidas podem desencadear um processo de reverifica\u00e7\u00e3o ou at\u00e9 a suspens\u00e3o do seu perfil.",card_online_info_title:"Presença online",card_online_s1_title:"🌐 Site",card_online_s1_body:"Um site vinculado ao seu GBP adiciona confiança e +5 pts. Verifique se carrega corretamente.",card_online_s2_title:"🕒 Horários",card_online_s2_body:"Horários precisos ajudam clientes a encontrar você. Sem horários você perde -3 pts.",card_online_s3_title:"📝 Descrição",card_online_s3_body:"Uma boa descrição ajuda o Google a entender seu negócio. Sem descrição você perde -2 pts.",card_activity_info_title:"Atividade & Engajamento",card_activity_s1_title:"📸 Posts do Google",card_activity_s1_body:"Publicar posts regularmente indica ao Google que seu negócio está ativo. Um post nos últimos 7 dias dá +5 pts.",card_activity_s2_title:"🖼️ Fotos",card_activity_s2_body:"Negócios com fotos recebem 42% mais pedidos de rota. Fotos novas nos últimos 7 dias dão o máximo de pts.",card_activity_s3_title:"⭐ Respostas a avaliações",card_activity_s3_body:"Responder avaliações mostra ao Google e clientes que você está ativo. Responda sua última avaliação para ganhar +3 pts.",card_visibility_info_title:"Visibilidade Local",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"O heatmap mostra onde você aparece no Google Maps na sua área. Faça scans regulares para acompanhar sua posição.",card_visibility_s2_title:"📋 Citações",card_visibility_s2_body:"Citações são menções do seu negócio em diretórios. Mais citações coerentes = mais confiança do Google.",card_visibility_s3_title:"📈 Acompanhamento",card_visibility_s3_body:"Use a aba Histórico para ver como evoluem sua pontuação e posição local.",card_see_more:"Ver mais",card_see_less:"Ver menos",attrs_info_title:"Atributos GBP — O que voc\u00ea precisa saber",attrs_info_s1_title:"🔧 O que s\u00e3o os atributos GBP?",attrs_info_s1_body:"Os atributos s\u00e3o detalhes adicionais sobre seu neg\u00f3cio que ajudam os clientes a tomar decis\u00f5es — op\u00e7\u00f5es de acessibilidade, m\u00e9todos de pagamento, estacionamento, servi\u00e7os dispon\u00edveis, etc. Eles aparecem diretamente no seu Perfil do Google Business.",attrs_info_s2_title:"📍 Por que s\u00e3o importantes para o SEO local",attrs_info_s2_body:"Atributos completos indicam ao Google que seu perfil \u00e9 detalhado e confi\u00e1vel. Eles tamb\u00e9m ajudam seu neg\u00f3cio a aparecer em pesquisas filtradas espec\u00edficas, como clientes que buscam neg\u00f3cios \u0027acess\u00edveis para cadeirantes\u0027 ou com \u0027estacionamento gratuito\u0027.",attrs_info_s3_title:"⚠️ Importante — Alguns atributos n\u00e3o podem ser editados aqui",attrs_info_s3_body:"O Google controla quais atributos est\u00e3o dispon\u00edveis com base na categoria do seu neg\u00f3cio. Alguns atributos s\u00f3 podem ser modificados diretamente no Google Business Profile. Se um atributo n\u00e3o responder \u00e0s altera\u00e7\u00f5es feitas aqui, atualize-o diretamente em business.google.com.",attr_url_hint:"Adicione estas URLs para melhorar sua visibilidade no Google. Para links de agendamento, acesse Google Business Profile \u2192 Editar perfil \u2192 Reservas.",guardian_home_title:"Guardian",guardian_home_status:"Ativo",guardian_checking:"Verificando...",guardian_disconnected:"Desconectado",guardian_home_subtitle:"Monitorando seu perfil 24\/7",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 Sua sentinela GBP",guardian_info_s1_title:"\ud83d\udd0d O que o Guardian monitora",guardian_info_s1_body:"O Guardian monitora 10 campos-chave: nome, endere\u00e7o, telefone, site, categoria principal, hor\u00e1rios, descri\u00e7\u00e3o, status aberto\/fechado, fotos de capa e atributos.",guardian_info_s2_title:"\u26a0\ufe0f Por que \u00e9 crucial",guardian_info_s2_body:"Qualquer pessoa pode sugerir altera\u00e7\u00f5es no seu perfil. Mudan\u00e7as n\u00e3o detectadas podem fazer seu posicionamento cair. O Guardian alerta voc\u00ea imediatamente.",guardian_info_s3_title:"\u2705 O que o Guardian N\u00c3O faz",guardian_info_s3_body:"O Guardian n\u00e3o melhora seu posicionamento. Continue otimizando seu GBP. O Guardian protege a visibilidade que voc\u00ea j\u00e1 conquistou.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 Inclu\u00eddo no seu plano",guardian_info_s4_body:"Guardian Lite monitora 10 campos GBP essenciais 24h por dia e notifica voc\u00ea assim que detecta uma altera\u00e7\u00e3o suspeita. O monitoramento est\u00e1 sempre inclu\u00eddo no seu plano \u2014 os cr\u00e9ditos s\u00f3 s\u00e3o usados quando AVI corrige automaticamente uma altera\u00e7\u00e3o (3 cr\u00e9ditos/m\u00eas inclu\u00eddos \u00b7 2 cr\u00e9ditos por corre\u00e7\u00e3o).",guardian_info_cta:"Entendido \u2713",guardian_trial_ended:"Per\u00edodo de teste encerrado \u2014 cr\u00e9ditos ativos",guardian_trial_active:"Teste gratuito ativo",guardian_trial_days_left:"dias restantes no teste gratuito",guardian_pricing_detail:"Ap\u00f3s o teste: 3 cr\u00e9ditos/m\u00eas + 2 cr\u00e9ditos por altera\u00e7\u00e3o detectada",guardian_pricing_detail_active:"3 cr\u00e9ditos/m\u00eas \u00b7 2 cr\u00e9ditos por altera\u00e7\u00e3o detectada",guardian_disabled_title:"Desativado",guardian_disabled_warn:"Seu perfil n\u00e3o est\u00e1 mais monitorado. Concorrentes podem modificar seu GBP sem que voc\u00ea saiba.",guardian_activate:"Ativar Guardian \u2192",guardian_credits_active:"Cr\u00e9ditos ativos",guardian_deactivate:"Desativar Guardian",guardian_post_trial_status:"\u26a0\ufe0f Teste encerrado",guardian_post_trial_warning:"\u26a0\ufe0f Seu perfil est\u00e1 agora exposto. Concorrentes e Guias Locais podem modificar seu GBP a qualquer momento \u2014 altera\u00e7\u00f5es n\u00e3o detectadas causam queda no ranking, hor\u00e1rios errados e chamadas perdidas.",guardian_deactivate_warn:"Se desativar, as altera\u00e7\u00f5es no seu perfil passar\u00e3o completamente despercebidas. Voc\u00ea n\u00e3o ser\u00e1 alertado se um concorrente marcar seu neg\u00f3cio como fechado.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Monitorado pelo Guardian \u2014 teste gratuito ativo",guardian_tooltip_active:"\u26A0\uFE0F Teste encerrado \u2014 cr\u00e9ditos ativos. Clique em \u2139\uFE0F na p\u00e1gina inicial para gerenciar.",guardian_low_credits_title:"Cr\u00e9ditos baixos \u2014 Guardian em risco",guardian_low_credits_warn:"Voc\u00ea tem menos de 10 cr\u00e9ditos. O Guardian pode parar de monitorar em breve.",guardian_credits_remaining:"Cr\u00e9ditos restantes:",guardian_buy_credits:"Comprar cr\u00e9ditos \u2192",guardian_trial_expired_title:"Teste gratuito encerrado",guardian_trial_expired_warn:"Seu teste gratuito de 15 dias encerrou. Ative o Guardian para continuar monitorando seu perfil.",guardian_trial_expired_badge:"\u23f1\ufe0f Teste encerrado \u2014 ative para continuar",guardian_paid_active_title:"Guardian Ativo",guardian_next_billing:"Pr\u00f3xima cobran\u00e7a:",guardian_tooltip_off:"Guardian desativado \u2014 este campo n\u00e3o est\u00e1 mais monitorado"},'
			. 'tr:{close:"Kapat",cancel:"İptal",save:"Kaydet",delete:"Sil",'
			. 'search_kw:"Anahtar kelime ara...",add_kw:"+ Anahtar kelime ekle",add_keyword:"+ Anahtar kelime ekle",'
			. 'confirm_delete_scan:"Bu planlanmış taramayı sil?",'
			. 'kw_my_keywords:"Anahtar kelimelerim",kw_panel_title:"Anahtar Kelimelerim",kw_panel_sub:"Yerel g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz i\u00e7in \u00f6nemli arama terimlerini takip edin. Her anahtar kelime, mahallenizde Google Haritalar s\u0131ralaman\u0131z\u0131 g\u00f6stermek i\u00e7in \u0131s\u0131 haritas\u0131nda taranabilir.",more:"daha fazla",'
			. 'import_kw:"📥 İçe aktar",export_kw:"📤 Dışa aktar",'
			. 'export_csv:"📊 CSV dışa aktar",export_pdf:"📄 PDF dışa aktar",'
			. 'import_label:"Anahtar kelimelerinizi yapıştırın — her satıra bir tane veya virgülle:",'
			. 'import_btn:"İçe aktar",scan_kw:"Bu kelimeyi tara",'
			. 'no_kw:"Henüz anahtar kelime yok — yukarıdan ilk kelimenizi ekleyin",'
			. 'scanned:"✅ Tarandı",pending:"⬜ Beklemede",threat:"⚠️ Tehdit",'
			. 'actions:"İşlemler",'
			. 'col_keyword:"Anahtar kelime",col_rank:"Sıra",col_best:"En iyi sıra",'
			. 'col_grid:"Izgara",col_status:"Durum",col_scan:"Son tarama",'
			. 'col_threat:"Tehdit",publish_now:"Şimdi yayınla",schedule_post:"Gönderiyi planla",schedule_post_credits:"Planla (2 kredi)",publishing:"Yayınlanıyor...",scheduling:"Planlanıyor...",new_post:"Yeni GBP Gönderisi",edit_post:"Gönderiyi düzenle",posts_panel_title:"GBP Gönderileri",posts_panel_sub:"Google Business Profile g\u00f6nderilerinizi olu\u015fturun ve y\u00f6netin. D\u00fczenli g\u00f6nderiler g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz\u00fc art\u0131r\u0131r ve m\u00fc\u015fterilerinizi teklifler, haberler ve etkinlikler hakk\u0131nda bilgilendirir.",posts_info_title:"GBP G\u00f6nderileri — Nas\u0131l \u00e7al\u0131\u015f\u0131r",posts_info_s1_title:"📝 \u0130\u00e7erik olu\u015fturun",posts_info_s1_body:"LocalEdge\'den do\u011frudan g\u00f6nderi (teklif, haber, etkinlik) yaz\u0131n. AVI tek t\u0131kla sizin i\u00e7in yazabilir.",posts_info_s2_title:"📅 Planlay\u0131n",posts_info_s2_body:"Google\'da d\u00fczenli bir varl\u0131k s\u00fcrd\u00fcrmek i\u00e7in yay\u0131nlar\u0131n\u0131z\u0131 \u00f6nceden planlay\u0131n.",posts_info_s3_title:"📈 G\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz\u00fc art\u0131r\u0131n",posts_info_s3_body:"Google aktif profilleri tercih eder. Yerel Pakette g\u00f6r\u00fcnmek i\u00e7in haftada minimum 1 g\u00f6nderi \u00f6nerilir.",upgrade_posts_title:"✨ GBP G\u00f6nderilerinizi Otomatikle\u015ftirin",upgrade_posts_sub:"Avision Pro otomatik olarak yay\u0131nlar · Otopilot modu mevcut",new_post_btn:"+ Yeni gönderi",write_content:"İçerik (maks. 1500 karakter)",write_content_ph:"Gönderi içeriğinizi yazın...",scheduled_date:"Planlanan tarih ve saat",no_content:"İçerik yok",post_type_label:"Gönderi türü",post_type_update:"📢 Güncelleme — Haberler ve duyurular",post_type_offer:"🏷️ Teklif — Promosyonlar",post_type_event:"📅 Etkinlik — Aktiviteler",post_type_update_short:"📢 Güncelleme",post_type_offer_short:"🏷️ Teklif",post_type_event_short:"📅 Etkinlik",credits_info:"💳 Bakiyenizden 2 kredi kullanılacak.",credits_2:"2 kredi",publication:"Yayın",publish_now_title:"⚡ Şimdi yayınla",schedule_title:"🕐 Planla",free:"Ücretsiz",photo_optional:"Fotoğraf (isteğe bağlı)",upload_device:"📁 Cihazdan yükle",choose_photos:"🖼️ Fotoğraflardan seç",gallery_soon:"Yakında — önce galerinizi kurun",gallery_first_alert:"Bu özellik için önce GBP Fotoğraflar galerinizi kurun (Fotoğraflar sekmesi).",image_too_large:"Görsel çok büyük — maks. 5 MB",err_no_content:"Lütfen gönderi içeriği girin.",err_content_long:"İçerik 1500 karakteri aşıyor.",err_no_schedule:"Lütfen planlanan bir tarih seçin.",err_create_post:"Gönderi oluşturma hatası",err_network:"Ağ hatası",err_generic:"Hata",no_posts:"Henüz gönderi yok",no_posts_sub:"Müşterilerinizle etkileşim için ilk GBP gönderinizi oluşturun",posts_count_suffix:" gönderi",event_title:"Etkinlik başlığı",event_title_ph:"ör. Yaz indirimi",start_date:"Başlangıç tarihi",end_date:"Bitiş tarihi",filter_all:"Tümü",post_status_published:"✅ Yayınlandı",post_status_scheduled:"🕐 Planlandı",post_status_pending:"⏳ Beklemede",post_status_failed:"❌ Başarısız",post_status_draft:"📝 Taslak",view_btn:"👁 Görüntüle",th_type:"Tür",th_content:"İçerik",th_status:"Durum",th_scheduled:"Planlandı",th_published:"Yayınlandı",th_actions:"İşlemler",sync_gbp:"🔄 GBP\\u0027den senkronize et",syncing:"Senkronize ediliyor...",publish_photo:"⚡ Yayınla",schedule_photo:"🕐 Planla",delete_photo_title:"Kütüphaneden sil",delete_confirm:"Bu medyayı kütüphaneden silmek istiyor musunuz?",rename_hint:"Yeniden adlandırmak için tıklayın",change_category:"Kategoriyi değiştirmek için tıklayın",no_category:"Kategori yok",upload_photo:"+ Fotoğraf yükle",select_photo_picker:"📎 Gönderinize eklemek için fotoğraf seçin",'
			. 'schedule_date_prompt:"Tarih ve saat (YYYY-MM-DDTHH:MM):",saving:"Kaydediliyor...",select_btn:"✓ Seç",copy_url:"URL\\u0027yi kopyala",video_badge:"🎬 Video",sync_failed:"Senkronizasyon başarısız",photos_sync_success:"\u2705 Fotoğraflar Google\u0027dan senkronize edildi",delete_gbp_title:"GBP\u0027den Sil",delete_gbp_confirm:"Bu fotoğrafı Google profilinizden silmek istiyor musunuz? Bu işlem geri alınamaz.",delete_gbp_success:"Fotoğraf GBP\u0027den silindi",delete_gbp_error:"GBP\u0027den silme başarısız",bulk_download:"Seçilenleri indir",bulk_delete:"Library\u0027den sil",bulk_delete_confirm:"{n} fotoğraf library\u0027den silinsin mi?",bulk_delete_success:"{n} fotoğraf library\u0027den silindi",bulk_gbp_note:"\u26a0\ufe0f Google toplu fotoğraf silmeye izin vermiyor \u2014 lütfen tek tek silin.",selected:"seçili",select_category:"— Kategori seçin (resmi Google) —",rename_ph:"Anahtar kelime içeren dosya adı (ör. tesisatci-istanbul-servis.jpg)",show_less_cats:"▲ Daha az göster",show_all_cats:"▼ Tüm GBP kategorileri",photos_panel_title:"GBP Fotoğrafları",photos_panel_sub:"Google Business Profile fotoğraflarınızı y\u00f6netin: y\u00fckleyin, d\u00fczenleyin, yayınlayın ve yerel SEO i\u00e7in optimize edin.",photos_info_title:"GBP Fotoğrafları — Nasıl \u00e7al\u0131\u015fır",photos_info_s1_title:"📚 Library / Published / Not Published",photos_info_s1_body:"Library = LocalEdge\'de saklanan t\u00fcm fotoğraflarınız. Published = Google profilinizde g\u00f6r\u00fcnen fotoğraflar. Not Published = y\u00fcklenen ancak hen\u00fcz Google\'a g\u00f6nderilmemiş fotoğraflar.",photos_info_s2_title:"🗂️ Kategoriler",photos_info_s2_body:"Fotoğraflarınızı kategorilere g\u00f6re d\u00fczenleyin (dış mekan, iç mekan, ekip, \u00fcr\u00fcnler…). İyi organize edilmiş bir profil m\u00fcşterilerde daha fazla g\u00fcven uyandırır.",photos_info_s3_title:"✏️ SEO i\u00e7in Yeniden Adlandırın",photos_info_s3_body:"Fotoğraf adı SEO i\u00e7in \u00f6nemlidir. Anahtar kelimelerinizle a\u00e7ıklayıcı isimler kullanın (örn: \'italyan-restoran-paris-teras\'). Yeniden adlandırmak i\u00e7in kalem simgesine tıklayın.",photos_info_s4_title:"⬇️ İndir & 🗑️ Sil",photos_info_s4_body:"\u0027\u2b07\ufe0f İndir\u0027 ile fotoğraf kaydedin. \u0027\ud83d\uddd1\ufe0f Library\u0027den sil\u0027 yalnızca LocalEdge\u0027den kaldırır. \u0027\ud83c\udf10 GBP\u0027den sil\u0027 Google profilinizden kalıcı olarak siler (geri alınamaz).",upgrade_photos_title:"✨ Profilinizi hep taze tutun",upgrade_photos_sub:"Avision Pro fotoğraflarınızı otomatik olarak planlar ve yayınlar · Otopilot modu",photos_filter_library:"📚 Kütüphane",photos_filter_gbp_pub:"✅ GBP\\u2019de yayınlandı",photos_filter_gbp_unpub:"📚 Yayınlanmadı",photo_category_label:"Fotoğraf kategorisi",filter_all_cats:"Tüm kategoriler",download_label:"İndir",upload_drag:"Fotoğrafları buraya sürükleyip bırakın",upload_drag_sub:"Fotoğraflar JPG/PNG (maks. 5 MB) · Videolar MP4 (maks. 75 MB, 30s)",reply_btn:"💬 Yanıtla",cancel_reply:"İptal",publish_reply:"Yanıtı yayınla",publishing_reply:"Yayınlanıyor...",reply_published:"Yan\\u0131t Google\\u2019da yay\\u0131nland\\u0131!",write_reply_ph:"Yanıtınızı yazın...",avi_writes_review:"✨ AVI yazar",avi_rewrite_reply:"✨ AVI ile yeniden yaz",edit_reply:"\\u270F\\uFE0F D\\u00fczenle",generating_reply:"✨ Olu\u015fturuluyor...",regenerate_reply:"↺ Yeniden olu\u015ftur",ai_reply_error:"AVI bir yan\u0131t olu\u015fturamad\u0131.",your_reply:"💬 Yanıtınız · ",no_reviews:"Yorum bulunamadı",no_reviews_filter:"Bu filtreye uyan yorum yok",reviews_0:"0 yorum",reviews_showing:"Gösterilen ",reviews_of:" / ",reviews_suffix:" yorum",load_more:"🔄 Google\\u0027dan daha fazla yorum yükle",load_more_info:"✅ Tüm ",load_more_info_end:" yorum GBP önbelleğinizden yüklendi · Avision Pro ile senkronize edin",load_more_loading:"Yorumlar y\u00fckleniyor...",filter_all_stars:"Tümü ⭐",without_reply:"💬 Yanıtsız",sort_recent:"En yeni",sort_oldest:"En eski",sort_lowest:"En düşük puan",sort_unanswered:"Önce yanıtsızlar",per_page:" / sayfa",previous:"← Önceki",next:"Sonraki →",page_of:"Sayfa ",gbp_reviews_title:"Google Business Profile yorumları",gbp_reviews_sub:"Güven oluşturmak için doğrudan yanıt verin",reviews_info_title:"Google Yorumları — Nasıl çalışır",reviews_info_s1_title:"⭐ Yorumlar neden önemli",reviews_info_s1_body:"Google yorumları yerel sıralamanızı ve dönüşüm oranınızı doğrudan etkiler. Son yanıtları olan bir işletme Yerel Pakette daha üst sıralarda yer alır.",reviews_info_s2_title:"✉️ Güven için yanıt verin",reviews_info_s2_body:"Her yoruma yanıt vermek — olumlu veya olumsuz — profesyonelliğinizi gösterir. AVI tek tıkla kişiselleştirilmiş yanıt üretebilir.",reviews_info_s3_title:"📅 Tutarlı kalın",reviews_info_s3_body:"Yanıtlarınızı önceliklendirmek ve hiçbir yorumu kaçırmamak için Yeni, Bu hafta, Bu ay veya Bu yıl filtrelerini kullanın.",tip_th_reviewer:"Müşteri adı ve profil fotoğrafı",tip_th_stars:"Yorumcunun verdiği puan (1-5 yıldız)",tip_th_date:"Yorumun yayınlanma tarihi",tip_th_review:"Müşterinin bıraktığı yorum içeriği",tip_th_replied:"Bu yoruma yanıt verip vermediğiniz",tip_th_actions:"AVI ile yanıt verin, düzenleyin veya yeniden oluşturun",filter_new:"Yeni",filter_week:"Bu hafta",filter_month:"Bu ay",filter_year:"Bu yıl",filter_all_years:"Tüm yıllar",filter_all_months:"Tüm aylar",filter_all_weeks:"Tüm haftalar",filter_all_replies:"Tüm yorumlar",filter_with_reply:"\u2705 Yanıtlı",flag_review_tip:"Bu yorumu Google\u0027a bildirin (spam, sahte, uygunsuz)",th_report:"Bildir",tip_th_report:"Bu yorumu Google\u0027a bildirin (spam, sahte, uygunsuz)",upgrade_ai_title:"🤖 Yapay zeka ile daha hızlı yanıtlayın",upgrade_ai_sub:"Avision Pro saniyeler içinde kişiselleştirilmiş yanıtlar üretir · Otopilot modu mevcut",upgrade_link:"Avision Pro\\u0027ya geç →",th_reviewer:"Yazar",th_stars:"Yıldız",th_date:"Tarih",th_review:"Yorum",th_replied:"Yanıtlandı",gbp_score_title:"📊 GBP Skoru",profile_completeness:"Profil tamlığı",profile_stats:"Profil istatistikleri",last_sync:"🕐 Son senkronizasyon: ",crit_name:"\u0130\u015fletme ad\u0131",pts_0:"Bilgi",crit_website:"Web sitesi",crit_phone:"Telefon",crit_hours:"Çalışma saatleri",crit_description:"İşletme açıklaması",crit_category:"Ana kategori",crit_address:"Adres",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ Tamam",missing:"❌ Eksik",reviews_label:"yorum",photos_label:"Fotoğraflar",avg_rank:"Ort. sıra",score_urgent:"Acil dikkat gerekli",score_improve:"Geliştirme alanı",score_getting:"İyi yolda",score_good:"İyi profil",score_excellent:"Mükemmel profil",unknown:"Bilinmiyor",upsell_slim:"✨ Avision Pro\\u0027ya geçin — Guardian · RAG · Çoklu profil",learn_more:"▲ Daha fazla bilgi",learn_close:"▼ Kapat",'
			. 'upsell_local:"🏠 Yerel işletme",upsell_agency:"🏢 Ajans",no_client:"Müşteri bulunamadı",search_client_ph:"🔍 Müşteri ara...",clients_title:"👥 Müşteriler",clients_trigger:"👥 Müşteriler ▾",loading:"⏳ Yükleniyor...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Google\\u2019dan senkronize et",sync_info_title:"Google\\u2019dan Senkronize Et",sync_info_score_body:"GBP Puanınızı ve profil verilerinizi doğrudan Google\\u2019dan günceller. Puanınız, yorumlarınız veya özellikleriniz Google Business Profile\\u2019da yaptığınız son değişiklikleri yansıtmıyorsa kullanın.",sync_info_home_body:"Tüm gösterge paneli istatistiklerinizi günceller — sıralama verileri, yorumlar ve tarama geçmişi. İstatistikleriniz güncel görünmüyorsa veya Google Business Profile\\u2019ınızda son zamanlarda değişiklik yaptıysanız kullanın.",sync_info_footer:"Veriler her 24 saatte bir otomatik olarak güncellenir. Bu düğme anlık bir yenileme başlatır.",help_title:"Yardım & SSS",help_subtitle:"Google Business Profile hakkında sık sorulan sorulara yanıt bulun",help_s1_title:"🔴 Top 5 — Sık Karşılaşılan Sorunlar",help_s2_title:"🟣 Profilimi Optimize Et",help_s3_title:"🔵 Google Güncellemeleri",help_faq1_q:"🚫 Profilim askıya alındı",help_faq1_a:"Google, anahtar kelime içeren isimler, adres tutarsızlıkları veya çok fazla hızlı düzenleme nedeniyle profilleri askıya alır. Önce sorunu düzeltin, ardından kanıtlarla (fatura, kira sözleşmesi, lisans) yeniden etkinleştirme talebi gönderin. İnceleme sürecinde asla kopya profil oluşturmayın.",help_faq2_q:"🔍 Profilim Google Maps\'te görünmüyor",help_faq2_a:"Profilinizin tamamen doğrulandığından ve yayınlandığından emin olun. Doğrulanmamış profiller görünmez. Yeni profiller tutarlı şekilde görünmek için 2 ila 4 hafta alabilir. Ayrıca web siteniz ve diğer dizinlerdeki NAP tutarlılığını kontrol edin.",help_faq3_q:"✅ Profilimi nasıl doğrularım (video)",help_faq3_a:"Video doğrulama 2026\'da varsayılan yöntemdir. Tabelanızı, iç mekanı ve GBP panelinizde canlı bir işlemi gösteren kesintisiz bir video çekin. Denemeden önce ad, adres ve web sitesinin eşleştiğinden emin olun.",help_faq4_q:"✏️ Profilimde yetkisiz düzenlemeler yapıldı",help_faq4_a:"Herkes düzenleme önerebilir ve Google bunları otomatik olarak kabul edebilir. Bilgilerinizi düzenli olarak kontrol edin ve yanlış değişiklikleri GBP panelinizden geri alın. LocalEdge\'in Guardian modu temel alanlarınızı 7/24 izler.",help_faq5_q:"⭐ Yorumlara yanıt veremiyorum",help_faq5_a:"Bu genellikle tam askıya alma değil, profil kısıtlamasına işaret eder. GBP panelinizde bildirimleri kontrol edin. Profili sahip olan doğru Google hesabıyla oturum açtığınızdan emin olun.",help_faq6_q:"📸 Hangi fotoğrafları ve kaç tane yayınlamalıyım?",help_faq6_a:"En az 10 fotoğraf yayınlayın: dış cephe, iç mekan, ekip, ürünler veya hizmetler. Her ay yeni fotoğraf ekleyin — Google aktif profilleri ödüllendirir. Stok veya yapay zeka üretimi fotoğraflardan kaçının. Gerçek fotoğraflar güven oluşturur ve sıralamanızı iyileştirir.",help_faq7_q:"🏷️ Doğru birincil kategoriyi nasıl seçerim?",help_faq7_a:"Birincil kategori, Google Maps\'teki en güçlü sıralama kaldıracıdır. Temel hizmetinize en uygun ve en spesifik kategoriyi seçin. Bir tesisatçı Tesisat Hizmetleri\'ni değil Tesisatçı\'yı seçmelidir. Diğer hizmetler için ikincil kategoriler ekleyebilirsiniz.",help_faq8_q:"📝 İyi bir işletme açıklaması nasıl yazılır?",help_faq8_a:"Ne yaptığınızı, kime hizmet ettiğinizi ve sizi farklı kılan şeyi anlatan 250 ila 750 karakter yazın. Ana anahtar kelimelerinizi doğal biçimde ekleyin. Tanıtım dili, URL veya telefon numaralarından kaçının. Her 6 ayda bir güncelleyin.",help_faq9_q:"🗓️ Ne sıklıkla gönderi paylaşmalıyım?",help_faq9_a:"Tazelik sinyallerini korumak için haftada en az bir kez paylaşın. Saniyeler içinde içerik oluşturmak ve zamanlamak için Posts sekmesindeki AVI\'yi kullanın. Yenilik gönderileri 7 gün sonra sona erer, Etkinlikler bitiş tarihine kadar kalır.",help_faq10_q:"⭐ Daha fazla müşteri yorumu nasıl alırım?",help_faq10_a:"Hizmetten hemen sonra her memnun müşteriden yorum isteyin. Email veya SMS ile doğrudan yorum bağlantısı gönderin. Fişlerinize veya kartlarınıza QR kod ekleyin. Asla teşvik sunmayın veya ne yazmaları gerektiğini söylemeyin — Google bunu 2026\'da cezalandırıyor.",help_faq11_q:"📍 Adres mi göstereyim yoksa hizmet alanı mı?",help_faq11_a:"Müşteriler işyerinize geliyorsa adresinizi gösterin. Müşterilere gidiyorsanız adresinizi gizleyin ve hizmet alanları ekleyin. Müşterilere gittiğinizde ev adresinizi göstermek kafa karışıklığı yaratabilir ve askıya alınma riskine yol açabilir.",help_faq12_q:"🔄 Kopya bir profilim var — ne yapmalıyım?",help_faq12_a:"Kopya profiller yorumlarınızı böler ve Google\'ı yanıltır. Google Maps\'te işletmenizi arayın ve Düzenleme öner seçeneğiyle kopyayı bildirin. Google fazla profili birleştirir veya kaldırır. Aynı işletme için asla iki profil yönetmeyin.",help_faq13_q:"🤖 Q&A kaldırıldı — Ask Maps (Gemini) ile değiştirildi",help_faq13_a:"Google, Q&A özelliğini kaldırdı ve Gemini AI destekli Ask Maps ile değiştirdi. Gemini, profil alanlarınızı, yorumlarınızı, fotoğraflarınızı ve web sitenizi kullanarak kullanıcı sorularını yanıtlar. Tüm GBP alanlarını doldurun ve web sitenize schema işaretlemesiyle FAQ içeriği ekleyin.",help_faq14_q:"🛡️ 2026 yeni yorum kuralları",help_faq14_a:"Google, yorum politikasını 2026 başında güncelledi. Yapay zeka tarafından oluşturulan yorumlar artık yasaktır. Yorum istemeye devam edebilirsiniz ancak ne yazacaklarını dikte edemezsiniz. Dürüst deneyiminizi paylaşın gibi tarafsız bir istek güvenlidir.",help_faq15_q:"⚡ Hızlı düzenlemeler askıya almayı tetikleyebilir",help_faq15_a:"Ad, adres, kategori, saatler gibi aynı anda birçok değişiklik yapmak 2026\'da yaygın bir askıya alma tetikleyicisidir. Düzenlemelerinizi birkaç güne yayın. LocalEdge\'in Guardian modu alan değişikliklerini takip eder ve riskli bir eşiğe ulaşmadan önce sizi uyarır.",syncing_btn:"⏳ Senkronize ediliyor...",sync_success:"✅ Profil senkronize edildi!",sync_error:"Hata. Tekrar deneyin.",add_credits:"+ Havuz kredisi",assign_credits:"+ Kredi",assign_min_hint:"Min. 10 kr \\u00b7 10\\u2019ar 10\\u2019ar",select_all:"T\\u00fcm\\u00fcn\\u00fc se\\u00e7",bulk_cr_each:"kr her biri",bulk_assigning:"Atan\\u0131yor...",bulk_assigned:"\\u2705 m\\u00fc\\u015fteri kredilendirildi",'
			. 'picker_title:"Google Business Profilinizi Se\\u00e7in",picker_subtitle:"LocalEdge ile y\\u00f6netmek istedi\\u011finiz profili se\\u00e7in.",picker_btn:"Bu profili se\\u00e7",picker_loading:"Ba\\u011flan\\u0131yor...",picker_error:"Ba\\u011flant\\u0131 hatas\\u0131. L\\u00fctfen tekrar deneyin.",picker_select_all:"T\\u00fcm\\u00fcn\\u00fc se\\u00e7",picker_import:"Se\\u00e7ili listeleri i\\u00e7e aktar",'
			. 'onboarding_title:"Google Business Profilinizi Ba\\u011flay\\u0131n",onboarding_subtitle:"T\\u00fcm \\u00f6zellikleri a\\u00e7mak i\\u00e7in GBP\\u2019nizi ba\\u011Flay\\u0131n.",onboarding_connect:"\\uD83D\\uDD17 Google Business\\u2019\\u0131 ba\\u011Fla",onboarding_skip:"Bunu daha sonra yapaca\\u011F\\u0131m",onboarding_step1_title:"1. Giri\\u015f",onboarding_step1_desc:"Google hesab\\u0131n\\u0131z\\u0131 ba\\u011Flay\\u0131n",onboarding_step2_title:"2. Se\\u00e7im",onboarding_step2_desc:"\\u0130\\u015Fletme profilinizi se\\u00e7in",onboarding_step3_title:"3. Haz\\u0131r!",onboarding_step3_desc:"T\\u00fcm \\u00f6zellikler aktif",edu_banner_title:"🎯 Yerel SEO Kontrol Merkezinize Ho\\u015f Geldiniz",edu_banner_body:"GBP\\u2019niz ba\\u011Fl\\u0131. Skorunuzu optimize edin ve rakiplerinizi ge\\u00e7in.",edu_banner_close:"Anla\\u015f\\u0131ld\\u0131 \\u2713",edu_help_btn:"💡",edu_modal_title:"LocalEdge nas\\u0131l \\u00e7al\\u0131\\u015f\\u0131r",edu_step1_title:"Ad\\u0131m 1 — Profilinizi tamamlay\\u0131n",edu_step1_body:"GBP profiliniz ba\\u011fland\\u0131 \\u2705 Buras\\u0131 ba\\u015flang\\u0131\\u00e7 noktan\\u0131z. Hangi alanlar\\u0131n eksik oldu\\u011funu bir bak\\u0131\\u015fta g\\u00f6rmek i\\u00e7in GBP Score sekmesine gidin. Telefon, \\u00e7al\\u0131\\u015fma saatleri, a\\u00e7\\u0131klama, foto\\u011fraflar, kategoriler — her eksik alan Google Maps\\u0027teki s\\u0131ralaman\\u0131za mal olur. %100 eksiksiz bir profil 2 kata kadar daha fazla t\\u0131klama getirir.",edu_step2_title:"Ad\\u0131m 2 — Tara ve analiz et",edu_step2_body:"Heatmap sekmesinde i\\u015fletmenizi tan\\u0131mlayan 1 ila 5 anahtar kelime se\\u00e7in (\\u00f6rn. \\u0027tesisat\\u00e7\\u0131 \\u0130stanbul\\u0027). \\u0130lk taran\\u0131z\\u0131 ba\\u015flat\\u0131n — \\u0131zgradaki her nokta o b\\u00f6lgedeki ger\\u00e7ek Google Maps s\\u0131ralaman\\u0131z\\u0131 g\\u00f6sterir. Endi\\u015flenmeyin: her sayfada sizi ad\\u0131m ad\\u0131m y\\u00f6nlendiren \\u2139\\uFE0F d\\u00fc\\u011fmeleri bulunur.",edu_step3_title:"Ad\\u0131m 3 — Optimize edin ve b\\u00fcy\\u00fcyin",edu_step3_body:"Nerede durdu\\u011funuzu art\\u0131k biliyorsunuz, harekete ge\\u00e7in. GBP Score: s\\u0131ralamada y\\u00fckselmek i\\u00e7in \\u00f6ncelikli alanlar\\u0131 d\\u00fczeltin. G\\u00f6nderiler ve Foto\\u011fraflar: \\u2728 AVI i\\u00e7eri\\u011finizi saniyeler i\\u00e7inde yazar ve zamanlar. Yorumlar: \\u2728 AVI ile 24 saat i\\u00e7inde yan\\u0131t verin — Google m\\u00fc\\u015fterileriyle etkile\\u015fime giren i\\u015fletmeleri \\u00f6d\\u00fcllendirir.",edu_learn_more:"Nas\\u0131l \\u00e7al\\u0131\\u015f\\u0131r \\u2192",tt_score:"GBP Skorunuz profilinizin ne kadar eksiksiz ve optimize edildi\\u011fini \\u00f6l\\u00e7er. 70\\u2019in \\u00fczerinde bir skor Google Yerel Paketi\\u2019ndeki g\\u00f6r\\u00fcn\\u00fcrl\\u00fc\\u011f\\u00fcn\\u00fcz\\u00fc \\u00f6nemli \\u00f6l\\u00e7\\u00fcde art\\u0131r\\u0131r. GBP Score sekmesinde bulun \\u2192",tt_unanswered:"Yorumlara 24 saat i\\u00e7inde yan\\u0131t vermek Google g\\u00fcven skorunuzu art\\u0131r\\u0131r. Google Reviews sekmesine gidin \\u2192",tt_next_scan:"D\\u00fczenli taramalar yerel g\\u00f6r\\u00fcn\\u00fcrl\\u00fc\\u011f\\u00fcn\\u00fcz\\u00fcn evrimini takip eder. S\\u00fctun 3\\u2019te tarama ba\\u015flat\\u0131n \\u2192",tt_nap:"Profil tamaml\\u0131\\u011f\\u0131n\\u0131z yerel s\\u0131ralaman\\u0131z\\u0131 do\\u011frudan etkiler. GBP Score sekmesinde d\\u00fczeltiniz \\u2192",tt_control_center:"GBP \\u00f6zetiniz: puan, yan\\u0131ts\\u0131z yorumlar, planlanan tarama ve profil eksiksizli\\u011fi \\u2014 \\u00f6ncelikli d\\u00fczeltmeleri belirlemek i\\u00e7in tek bir yerde.",clients_count_suffix:" müşteri",pool_credits:"💳 Havuz kredileri: ",available_word:" kullanılabilir · ",used_word:" kullanıldı",never:"Hiç",today:"Bugün",yesterday:"Dün",sort_priority:"🚨 Öncelik (düşük skor önce)",sort_best_score:"⭐ En iyi skor önce",sort_activity:"🕐 Son aktivite",sort_name:"A→Z İsim",sort_kw:"🔑 En çok anahtar kelime",scan_badge:" scan(s)",kw_badge:" anahtar kelime",logo_too_large:"Logo çok büyük — maks. 2 MB",upload_logo:"📁 Logo yükle",or_sep:"— veya —",agency_hub_title:"Ajans Merkezi",col_suffix:" col",cols_suffix:" cols",err_rename:"Yeniden adlandırma sırasında ağ hatası",err_file_too_large:"Dosya çok büyük",tip_col_keyword:"İzlenen arama terimi",tip_col_rank:"Isı haritası tüm noktalardaki güncel ortalama sıra",tip_col_best:"Kaydedilen en iyi sıra",tip_col_grid:"Son taramada kullanılan ızgara boyutu",tip_col_status:"Beklemede = hiç taranmadı · Tarandı = veri var",tip_col_scan:"Tarih + tarama türü (solo veya multi)",tip_col_threat:"⚠️ Rakip ızgara noktalarının %50+ üzerinde Top 3\u0027e hakim",filter_danger:"⚠️ Tehlike",filter_solo_scan:"🔍 Solo tarama",filter_multi_scan:"📊 Multi tarama",filter_az:"A→Z",filter_all_grids:"Tüm ızgaralar",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" anahtar kelime)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Henüz taranmadı",export_col_city:"Şehir",export_col_scan_type:"Tarama türü",export_yes:"Evet",export_no:"Hayır",export_danger_yes:"⚠️ Evet",kw_report_title:"Anahtar Kelime Raporu",kw_report_generated:"Oluşturuldu:",kw_report_keywords_suffix:" anahtar kelime",import_kw_tip:"Birden fazla anahtar kelime içe aktar (satır başına veya CSV)",add_kw_ph:"Anahtar kelime girin (ör. Tesisatçı İstanbul)",import_kw_ph:"Tesisatçı İstanbul\\nElektrikçi Ankara\\nÇatıcı İzmir",post_char_of:" / 1500",post_add_photo:"📷 Fotoğraf ekle",post_photo_formats:"JPG, PNG — maks. 5 MB",export_col_created:"Oluşturuldu",posts_page_title:"GBP Gönderileri",posts_report_title:"GBP Gönderi Raporu",photo_status_in_stock:"📚 Kütüphanede",photos_count_suffix:" fotoğraf",no_photos:"Henüz fotoğraf yok",no_photos_sub:"GBP kütüphanenizi oluşturmak için fotoğraf yükleyin",photo_alt_default:"GBP Fotoğrafı",photo_sched_vid:"5 kr",photo_sched_img:"3 kr",err_rename_failed:"Yeniden adlandırma başarısız",export_col_file:"Dosya",export_col_category:"Kategori",photos_page_title:"GBP Fotoğrafları",photos_report_title:"GBP Fotoğraf Raporu",photos_library_count_suffix:" fotoğraf kütüphanede",cat_cover:"🖼️ Kapak",cat_profile:"👤 Profil",cat_logo:"🎨 Logo",cat_interior:"🏠 İç mekan",cat_exterior:"🏢 Dış mekan",cat_product:"📦 Ürün",cat_at_work:"💼 İş başında",cat_food_drink:"🍽️ Yiyecek ve içecek",cat_menu:"📋 Menü",cat_common_area:"🛋️ Ortak alan",cat_rooms:"🛏️ Odalar",cat_teams:"👥 Ekipler",cat_additional:"➕ Ek",rv_replied_yes:"✅ Evet",rv_replied_no:"❌ Hayır",export_col_reply:"Yanıt",export_col_has_reply:"Yanıtlandı",reviews_page_title:"Yorum Raporu",reviews_report_title:"Google Yorum Raporu",reviews_pdf_avg:"⭐ Ortalama: ",reviews_pdf_reviews_suffix:" yorum",export_col_criterion:"Kriter",export_col_points:"Puan",score_export_done:"Tamam",score_export_missing:"Eksik",score_export_score:"Skor",score_export_rating:"Puan",score_export_photos:"Fotoğraflar",score_report_title:"GBP Skor Raporu",score_pdf_stats:"İstatistikler",score_pdf_rating:"⭐ Puan: ",score_pdf_photos:"📸 Fotoğraflar: ",rel_d_ago:"g",rel_w_ago:"hf",rel_mo_ago:"ay",rel_y_ago:"y",hub_subtitle:"Ajans ayarları, krediler ve white-label yönetimi.",hub_credit_pool:"💳 Kredi havuzu",hub_tier_label:"Mevcut Plan",hub_tier_t1:"Tier 1 — 10 listeye kadar",hub_tier_t2:"Tier 2 — 50 listeye kadar",hub_tier_t3:"Tier 3 — s\u0131n\u0131rs\u0131z liste",hub_listings_gauge:"Aktif listeler",hub_tier_upgrade:"Plan\u0131 y\u00fckselt",hub_tier_downgrade:"Plan\u0131 d\u00fc\u015f\u00fcr",hub_upgrade_processing:"\u00d6demeye y\u00f6nlendiriliyor...",hub_downgrade_confirm:"Bu plana ge\u00e7i\u015fi onayla?",hub_downgrade_blocked:"D\u00fc\u015f\u00fcrme engellendi: \u00e7ok fazla aktif liste.",hub_downgrade_success:"Plan ba\u015far\u0131yla g\u00fcncellendi.",hub_info_upgrade:"Upgrade: yaln\u0131zca planlar aras\u0131ndaki fark\u0131 \u00f6dersiniz (prorata).",hub_info_downgrade:"Downgrade: \u00fccretsiz, geri \u00f6deme yok. Aktif listeler yeni plan s\u0131n\u0131r\u0131n\u0131 a\u015farsa engellenir.",hub_available:"Kullanılabilir",hub_used:"Kullanıldı",hub_buy_credits:"+ Kredi satın al (toptan)",hub_whitelabel:"🎨 White-label",hub_whitelabel_desc:"Embed ve PDF dışa aktarmalarda gösterilen logo URL ve marka adı.",hub_logo_ph:"https://logonuz.com/logo.png",hub_brand_ph:"Ajans adınız",hub_save_settings:"Kaydet",saved:"Kaydedildi \u2713",hub_save_alert:"White-label ayarları — Sprint 45",hub_import_clients:"📥 Müşteri içe aktar",hub_import_csv_desc:"CSV formatı: business_name, city, category, country",hub_import_csv_btn:"CSV içe aktar",hub_import_alert:"CSV içe aktarma — Sprint 45",hub_pro_title:"🚀 Avision Pro Ajans",hub_pro_sub:"Helikopter görünümü · Toplu işlemler · Gelişmiş raporlama · Tam Guardian",hub_pro_cta:"Avision Pro Ajans\u0027a yükselt →",profile_title:"Profilim",profile_subtitle:"Kredilerinizi ve hesabınızı yönetin.",profile_credits_available:"Mevcut krediler",profile_credits_used:"Kullanılan",profile_buy:"+ Kredi satın al",profile_pack_nano:"Nano — 10 kredi",profile_pack_mini:"Mini — 30 kredi",profile_pack_standard:"Standard — 75 kredi",profile_pack_pro:"Pro — 200 kredi",profile_pack_agency:"Ajans — 600 kredi",profile_price_nano:"$2",profile_price_mini:"$5",profile_price_standard:"$11",profile_price_pro:"$25",profile_price_agency:"$59",profile_save_economy:" — tasarruf ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Tam dashboard · Guardian \\u00b7 Gelişmiş SEO",profile_upsell_cta:"Avision Pro\\u0027ya yükselt \\u2192",credits_modal_title:"💳 LocalEdge Kredileriniz",credits_modal_solo_p1:"LocalEdge kredileriniz kalıcıdır — asla sona ermez. İhtiyaç duyduğunuzda satın alın, kendi hızınızda kullanın.",credits_modal_usage_title:"Kredilerinizi nerede harcayabilirsiniz:",credits_modal_heatmap:"🗺️ Heatmap taraması — 2 kr (3×3)\u0027den 60 kr (21×21)\u0027e",credits_modal_post:"📝 AVI aracılığıyla GBP Gönderisi — 3 kr",credits_modal_photo:"📷 GBP fotoğraf senkronizasyonu — 2 kr",credits_modal_guardian:"🔔 Guardian (profil izleme) — ücretsiz, dahil",credits_modal_savings_title:"Ne kadar çok satın alırsanız, kredi başına o kadar az ödersiniz.",credits_modal_savings_sub:"$25\u0027lik Pro paketi, Nano paketine göre kredi başına %38 daha ucuzdur.",credits_modal_agency_title:"💳 Ajans Kredi Havuzunuz",credits_modal_agency_p1:"Havuzunuz tüm müşteri profilleri arasında paylaşılır. Toplu satın alın, ihtiyaca göre dağıtın.",credits_modal_agency_wholesale:"Toptan fiyat — ajans kredileriniz standart fiyatlara göre %47\u0027ye kadar daha ucuzdur. Marjınız size aittir.",credits_modal_agency_noexpiry:"Son kullanma tarihi yok — kredileriniz süresiz olarak kullanılabilir.",purchase_success_title:"\u2713 \u00d6deme al\u0131nd\u0131!",purchase_success_sub:"Kredileriniz birka\u00e7 saniye i\u00e7inde kullan\u0131labilir olacak.",purchase_success_close:"Anla\u015f\u0131ld\u0131",slider_title:"Veya kendi tutar\u0131n\u0131z\u0131 se\u00e7in",slider_credits:"kredi",slider_price_per:"kredi ba\u015f\u0131na",slider_vs_nano:"Nano\u0027ya g\u00f6re",slider_buy_btn:"Sat\u0131n Al",slider_min_label:"10 kr",slider_max_label_solo:"1.000 kr",slider_max_label_agency:"5.000 kr",client_balance:"M\u00fc\u015fteri bakiyesi",cr_need:"Gerekli",cr_available:"Mevcut",cr_missing:"Eksik",days_ago:"g",attr_other:"Di\u011fer",anonymous_reviewer:"Anonim",error_generic:"Bir hata olu\u015ftu.",vs_standard:"standarda g\u00f6re",badge_discount_17:"-%17",badge_discount_27:"-%27",badge_discount_38:"-%38",badge_discount_16:"-%16",badge_discount_30:"-%30",badge_discount_40:"-%40",badge_discount_47:"-%47",ag_pack_starter:"Başlangıç Ajans — 100 kredi",ag_pack_standard:"Standart Ajans — 300 kredi",ag_pack_pro:"Pro Ajans — 750 kredi",ag_pack_enterprise:"Kurumsal Ajans — 2000 kredi",ag_price_starter:"$14",ag_price_standard:"$35",ag_price_pro:"$75",ag_price_enterprise:"$175",logo_preview_alt:"Logo önizleme",hub_uploaded_file:"(yüklenen dosya)",ag_no_scan:"🗺️ Scan yok",gbp_open_title:"GBP kaydını aç: ",gbp_search_title:"Google Maps\u0027te ara: ",gbp_score:"GBP Skoru",unanswered:"Yan\u0131ts\u0131z",unanswered_sub:"yan\u0131tlanacak yorum",credits_left:"Krediler",next_scan:"Sonraki tarama",no_scan:"Tarama yok",nap_status:"Profil tamaml\u0131\u011f\u0131",nap_name:"Ad",nap_address:"Adres",nap_phone:"Telefon",nap_website:"Web sitesi",nap_hours:"Saatler",nap_desc:"A\u00e7\u0131klama",fix_it:"Tamamla \\u2192",edit:"D\u00fczenle",fix:"D\u00fczelt",edit_name:"Ad\u0131 d\u00fczenle",name_warn:"Ad\u0131 de\u011fi\u015ftirmek Google incelemesini tetikleyebilir.",edit_website:"Web sitesini d\u00fczenle",edit_phone:"Telefonu d\u00fczenle",edit_hours:"\u00c7al\u0131\u015fma saatlerini d\u00fczenle",edit_description:"A\u00e7\u0131klamay\u0131 d\u00fczenle",edit_categories:"Kategorileri d\u00fczenle",edit_address:"Adresi d\u00fczenle",edit_success:"Google\u2019da ba\u015far\u0131yla g\u00fcncellendi!",edit_error:"G\u00fcncelleme hatas\u0131. L\u00fctfen tekrar deneyin.",lodging_posts_warn:"GBP g\u00f6nderileri konaklama i\u015fletmeleri i\u00e7in mevcut de\u011fildir.",hours_closed:"Kapal\u0131",hours_open:"A\u00e7\u0131k",cat_search_placeholder:"Google kategorilerinde ara...",cat_primary:"Birincil kategori",cat_additional:"Ek kategoriler (maks 9)",cat_lodging_warn:"Birincil kategorinizi de\u011fi\u015ftirmek profil \u00f6zelliklerinizi etkileyebilir.",addr_neighborhood:"Mahalle / Semt",addr_street:"Sokak adresi",addr_city:"\u015eehir",addr_region:"Eyalet / B\u00f6lge",addr_postal:"Posta kodu",addr_country:"\u00dclke kodu (ör. TR)",verified:"Do\u011fruland\u0131",pending_verification:"Do\u011frulama beklemede",not_verified:"Do\u011frulanmad\u0131",verify_cta_text:"İşletmeniz Google\u2019da do\u011frulanmam\u0131\u015f. Do\u011frulanm\u0131\u015f profiller daha fazla g\u00f6r\u00fcn\u00fcrl\u00fck sa\u011flar.",verify_cta_btn:"İşletmemi do\u011frula \u2192",verify_pending_text:"Do\u011frulama devam ediyor. Google 7 g\u00fcne kadar s\u00fcrebilir.",score_panel_sub:"Google Business Profile optimizasyon puan\u0131n\u0131z. Her tamamlanan alan, yerel arama sonu\u00e7lar\u0131ndaki g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz\u00fc art\u0131r\u0131r.",score_info_title:"GBP Puan\u0131 \u2014 Nas\u0131l \u00e7al\u0131\u015f\u0131r",score_info_s1_title:"\uD83C\uDFAF Puan nas\u0131l hesaplan\u0131r",score_info_s1_body:"Baz 30 pts + Web sitesi (+5) + Saatler (+3) + 200+ kar. a\u00e7\u0131klama (+2) + Ek kategori (+1) + \u00d6zellikler \u22653 (+1). Maksimum: 42 pts.",score_info_s2_title:"\uD83D\uDCC8 Neden \u00f6nemli",score_info_s2_body:"Eksiksiz ve optimize edilmi\u015f bir profil, Google\u0027un Yerel Paketi\u0027nde daha \u00fcst s\u0131ralarda yer al\u0131r. Her eksik alan yerel aramalarda g\u00f6r\u00fcn\u00fcrl\u00fck kaybettirir.",score_info_s3_title:"\u270F\uFE0F Nas\u0131l iyile\u015ftirilir",score_info_s3_body:"Google profilinizi a\u00e7madan LocalEdge\u0027den do\u011frudan g\u00fcncellemek i\u00e7in her kriterde D\u00fczenle veya D\u00fczelt\u0027e t\u0131klay\u0131n.",gbp_attributes_title:"GBP \u00d6zellikleri",attr_na:"Bu kategori i\u00e7in N/A",attr_url_gbp_hint:"Google Business Profile\u0027da d\u00fczenle",attrs_filled:"Yap\u0131land\u0131r\u0131lm\u0131\u015f",crit_posts:"Son g\u00f6nderiler",crit_photos:"Yay\u0131nlanan foto\u011fraflar",photos_published_label:"yay\u0131nland\u0131",photos_min:"min. 3 \u00f6nerilir",post_stale:"Son g\u00f6nderi > 7 g\u00fcn \u2014 puan\u0131n\u0131z\u0131 korumak i\u00e7in yay\u0131nlay\u0131n",post_fresh:"Taze \u2014 son 7 g\u00fcnde yay\u0131nland\u0131",post_upsell:"Puan\u0131n\u0131z\u0131 korumak i\u00e7in g\u00f6nderi planlay\u0131n",photo_stale:"Son foto\u011fraf > 7 g\u00fcn \u2014 puan\u0131n\u0131z\u0131 korumak i\u00e7in yay\u0131nlay\u0131n",photo_fresh:"Taze \u2014 son 7 g\u00fcnde yay\u0131nlanan foto\u011fraf",photo_upsell:"Puan\u0131n\u0131z\u0131 korumak i\u00e7in foto\u011fraf yay\u0131nlay\u0131n",crit_reviews_reply:"Son yorum yan\u0131tland\u0131",replied:"Yan\u0131tland\u0131",not_replied:"Yan\u0131ts\u0131z",no_reviews_yet:"Hen\u00fcz yorum yok",freshness_note:"Puan\\u0131n\\u0131z aktivitenize g\\u00f6re de\\u011fi\\u015fir: g\\u00f6nderiler, foto\\u011fraflar, yorum yan\\u0131tlar\\u0131, profil eksiksizli\\u011fi ve \\u0131s\\u0131 haritas\\u0131 taramalar\\u0131 s\\u0131ralaman\\u0131z\\u0131 etkiler. Puan\\u0131n\\u0131z\\u0131 maksimize etmek i\\u00e7in aktif kal\\u0131n.",view:"G\u00f6r\u00fcnt\u00fcle",reply:"Yan\u0131tla",attr_saved:"\u00d6zellik g\u00fcncellendi",attr_error:"\u00d6zellik g\u00fcncellenemedi",attrs_load_error:"\u00d6zellikler y\u00fcklenemedi",attrs_load_hint:"Yeniden y\u00fcklemek i\u00e7in \uD83D\uDD04 Sync from Google\u0027a t\u0131klay\u0131n",hm_section_title:"🗺️ Isı Haritası Görünürlüğü",hm_info_title:"Isı Haritası — Neden her şeyi değiştirir",hm_info_s1_title:"📍 Tam konumunuzu bilin",hm_info_s1_body:"Her tarama, mahalle ızgaranızdaki her noktada Google Haritalar sıralamanızı haritalandırır. Nerede hüküm sürdüğünüzü ve rakiplerin sizi nerede geçtiğini sokak sokak görürsünüz.",hm_info_s2_title:"🏆 Rakiplerinizi analiz edin",hm_info_s2_body:"Isı haritası, her ızgara noktasında ilk 3\u0027te hangi rakiplerin yer aldığını ortaya koyar. Hangi bölgelerde kimi geçeceğinizi belirleyin ve yerel SEO stratejinizi buna göre ayarlayın.",hm_info_s3_title:"📐 Izgara boyutu = bölge kontrolü",hm_info_s3_body:"7x7 ızgara yakın mahallenizi kapsar. 13x13 ızgara tüm şehrinizi haritalandırır. Izgaranız ne kadar büyük olursa, o kadar fazla bölgeyi kontrol eder ve stratejik kararlar için o kadar fazla veriye sahip olursunuz.",hm_info_s4_title:"🔄 Düzenli taramalar = sıralama kazanımları",hm_info_s4_body:"İlerlemenizi takip etmek için aynı anahtar kelimeyi haftalık tarayın. Her tarama kredi kullanır ancak işlem yapılabilir veriler sağlar: konum kazanıyor musunuz yoksa kaybediyor musunuz? Rakipler yerlerinizi almadan önce harekete geçin.",hm_activity_label:"Tarama aktivitesi",hm_performance_label:"Yerel performans",hm_coverage_label:"Bölge kapsamı",hm_scan_now:"Tarama başlat",hm_stale_warn:"30+ gündür tarama yok — verileriniz güncel değil",hm_no_scan:"Henüz tarama yok — bölgenizi haritalandırmaya başlayın",control_center:"Kontrol merkezi",guardian_badge:"\ud83d\udd14 Uyar\u0131lar",guardian_modal_title:"Guardian Lite \u2014 Profil Uyar\u0131lar\u0131",guardian_no_alerts:"Hi\u00e7bir uyar\u0131 tespit edilmedi",guardian_plan_free:"\u00dccretsiz plan \u2014 izleme yok",guardian_plan_lite:"Lite \u2014 ayda 1 tarama",guardian_plan_standard:"Standart \u2014 haftal\u0131k tarama",guardian_plan_daily:"G\u00fcnl\u00fck tarama aktif",guardian_field_title:"\u0130\u015fletme ad\u0131 de\u011fi\u015ftirildi",guardian_field_phone:"Telefon numaras\u0131 de\u011fi\u015ftirildi",guardian_field_categories:"Kategori de\u011fi\u015ftirildi",guardian_field_hours:"\u00c7al\u0131\u015fma saatleri de\u011fi\u015ftirildi",guardian_field_website:"Web sitesi de\u011fi\u015ftirildi",guardian_field_openInfo:"A\u00e7\u0131k\/kapal\u0131 durumu de\u011fi\u015ftirildi",guardian_why_title:"Profilinizi neden izlemelisiniz?",guardian_why_1:"Rakipler dahil herkes GBP\u2019nize de\u011fi\u015fiklik \u00f6nerebilir",guardian_why_2:"Local Guide\u2019lar i\u015fletmenizi kapal\u0131 olarak i\u015faretleyebilir",guardian_why_3:"Fark edilmeyen de\u011fi\u015fiklikler s\u0131ralamada d\u00fc\u015f\u00fc\u015fe ve g\u00f6r\u00fcn\u00fcrl\u00fck kayb\u0131na yol a\u00e7ar",guardian_fix_btn:"GBP Score\u2019da d\u00fczelt \u2192",guardian_mark_read:"T\u00fcm\u00fcn\u00fc okundu i\u015faretle",guardian_detected:"Tespit:",guardian_old:"\u00d6nce:",guardian_new:"Sonra:",guardian_verify:"hemen do\u011frulay\u0131n",guardian_fix_now:"Hemen d\u00fczelt",guardian_field_address:"Adres",guardian_field_description:"A\u00e7\u0131klama",guardian_field_specialHours:"\u00d6zel saatler",guardian_field_serviceArea:"Hizmet alan\u0131",crit_special_hours:"\u00d6zel saatler",crit_service_area:"Hizmet alan\u0131",special_hours_edit_info:"\u00d6zel saatler do\u011frudan Google Business Profile \u00fczerinden y\u00f6netilmelidir.",service_area_edit_info:"Hizmet alan\u0131 do\u011frudan Google Business Profile \u00fczerinden y\u00f6netilmelidir.",guardian_changed:"de\u011fi\u015fti",guardian_fix_gbp:"GBP\u2019de d\u00fczeltin \u2192",crit_open_status:"\u0130\u015fletme durumu",open_info_warn:"Bu durumu de\u011fi\u015ftirmek Google Business Profilinizi hemen g\u00fcncelleyecektir.",open_status_open:"A\u00e7\u0131k \u2014 Normal \u00e7al\u0131\u015fma saatleri",open_status_temp:"Ge\u00e7ici olarak kapal\u0131 \u2014 yeniden a\u00e7\u0131lacak",open_status_perm:"Kal\u0131c\u0131 olarak kapat\u0131ld\u0131 \u2014 acil kontrol edin",open_status_open_no_hours:"A\u00e7\u0131k \u2014 Ana saat yok",open_status_unknown:"Durum bilinmiyor",cit_title:"Al\u0131nt\u0131lar",cit_listed:"eklendi",cit_done:"Eklendi",cit_mark_done:"\u2713 Ekle",cit_already:"Zaten listelendi",cit_mark_already:"\u2713 Zaten listelendi",cit_trust:"Size g\u00fcveniyoruz \u2014 bunu otomatik olarak do\u011frulamay\u0131z",cit_url_placeholder:"Listeleme URL\u0027niz (iste\u011fe ba\u011fl\u0131)",cit_section_universal:"\ud83c\udf0d Evrensel",cit_section_local:"\ud83c\udff3\ufe0f T\u00fcrkiye",cit_section_niche:"\ud83c\udfaf Sekt\u00f6r\u00fcn\u00fcz",cit_todo:"\ud83d\udccb Yap\u0131lacaklar",cit_completed:"Tamamlananlar",cit_collapse:"\u25b2 Daralt",cit_expand:"\u25bc Geni\u015flet",cit_undo:"\u21a9 Geri al",cit_remove:"Kald\u0131r",cit_add_name:"Dizin ad\u0131",cit_add_url:"https://...",cit_add_btn:"+ Ekle",cit_banner_msg:"Google Business kategorinize g\u00f6re otomatik olarak dizinler se\u00e7tik \"{cat}\". Baz\u0131 \u00f6neriler tam uygun olmayabilir \u2014 bunlar\u0131 kald\u0131rabilir veya kendi dizinlerinizi ekleyebilirsiniz.",cit_your_category:"kategoriniz",cit_panel_sub:"Yerel SEO g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz\u00fc art\u0131rmak i\u00e7in dizin listelerinizi takip edin.",cit_info_title:"Al\u0131nt\u0131lar & Yerel SEO",cit_info_s1_title:"\ud83d\udccd Al\u0131nt\u0131 nedir?",cit_info_s1_body:"Al\u0131nt\u0131, i\u015fletmenizin ad\u0131, adresi ve telefon numaras\u0131n\u0131n (NAP) \u00e7evrimi\u00e7i herhangi bir yerde ge\u00e7mesidiir. Arama motorlar\u0131, i\u015fletmenizi do\u011frulamak ve yerel s\u0131ralamalar\u0131n\u0131z\u0131 iyile\u015ftirmek i\u00e7in al\u0131nt\u0131lar\u0131 kullan\u0131r.",cit_info_s2_title:"\u26a0\ufe0f NAP tutarl\u0131l\u0131\u011f\u0131 kritiktir",cit_info_s2_body:"Ad\u0131n\u0131z, adresiniz ve telefon numaran\u0131z t\u00fcm dizinlerde tam olarak ayn\u0131 olmal\u0131d\u0131r \u2014 ayn\u0131 k\u0131saltmalar, ayn\u0131 noktalama, ayn\u0131 format. K\u00fc\u00e7\u00fck farklar bile arama motorlar\u0131n\u0131 \u015fa\u015f\u0131rt\u0131r.",cit_info_s3_title:"\ud83c\udfaf Neden bu dizinler?",cit_info_s3_body:"Google Business kategorinize ve konumunuza g\u00f6re otomatik olarak dizinler se\u00e7tik. Baz\u0131 ni\u015f \u00f6neriler uygun olmayabilir \u2014 bunlar\u0131 kald\u0131rabilir veya kendinizinkini ekleyebilirsiniz.",cit_info_s4_title:"\u2705 Zaten listelendi mi?",cit_info_s4_body:"\u0130\u015fletmeniz zaten bir dizinde yer al\u0131yorsa \u2018Zaten listelendi\u2019ye t\u0131klay\u0131n ve iste\u011fe ba\u011fl\u0131 olarak URL ekleyin. Size g\u00fcveniyoruz \u2014 bunu otomatik olarak do\u011frulamay\u0131z, ancak gelecekte yapabiliriz.",cit_score_section:"\ud83d\udccb Al\u0131nt\u0131lar",cit_score_label:"Dizinler",cit_score_detail:"dizin listelendi",cit_stale_warn:"Puan\u0131n\u0131z\u0131 korumak i\u00e7in bir dizin ekleyin",sh_title:"Skor & S\u0131ralama Ge\\u00e7mi\\u015fi",sh_daily:"G\\u00fcnl\\u00fck",sh_score:"GBP Skoru",sh_rank:"Ort. S\\u0131ralama",sh_drop:"D\\u00fc\\u015f\\u00fc\\u015f",sh_all_kw:"T\\u00fcm anahtar kelimeler",sh_no_data:"Hen\\u00fcz veri yok. Takibi ba\\u015flatmak i\\u00e7in bir heatmap taramas\\u0131 \\u00e7al\\u0131\\u015ft\\u0131r\\u0131n.",sh_start:"Ba\\u015flang\\u0131\\u00e7",sh_now:"\\u015eimdi",sh_best_rank:"En iyi s\\u0131ralama",sh_info_title:"Skor & S\\u0131ralama Ge\\u00e7mi\\u015finizi Anlamak",sh_info_s1_title:"\\ud83d\\udcc8 GBP Skoru (mor)",sh_info_s1_body:"0 ile 100 aras\\u0131nda Google Business Profile optimizasyon skorunuz. Profilinizi tamamlad\\u0131k\\u00e7a, foto\\u011fraf ekledik\\u00e7e, yorum ald\\u0131k\\u00e7a ve Guardian uyar\\u0131lar\\u0131n\\u0131 d\\u00fczeltik\\u00e7e y\\u00fckselir.",sh_info_s2_title:"\\ud83d\\udccd Ortalama S\\u0131ralama (amber)",sh_info_s2_body:"T\\u00fcm heatmap \\u0131zgara noktalar\\u0131nda Google Maps sonu\\u00e7lar\\u0131ndaki ortalama konumunuz. D\\u00fc\\u015f\\u00fck = daha iyi \\u2014 #1 s\\u0131ralama, o arama alan\\u0131nda ilk s\\u0131rada g\\u00f6r\\u00fcnd\\u00fc\\u011f\\u00fcn\\u00fcz anlam\\u0131na gelir.",sh_info_s3_title:"\\u26a0\\ufe0f S\\u0131ralamam neden dalgalan\\u0131yor?",sh_info_s3_body:"GBP s\\u0131ralamas\\u0131 aray\\u0131c\\u0131n\\u0131n co\\u011frafi konumuna, kullan\\u0131lan anahtar kelimeye, g\\u00fcn\\u00fcn saatine ve Google algoritma g\\u00fcncellemelerine g\\u00f6re de\\u011fi\\u015fir. Bu normaldir \\u2014 bireysel noktalar\\u0131 de\\u011fil trendi takip edin.",sh_info_s4_title:"\\ud83d\\udd34 K\\u0131rm\\u0131z\\u0131 noktalar",sh_info_s4_body:"K\\u0131rm\\u0131z\\u0131 nokta keskin bir d\\u00fc\\u015f\\u00fc\\u015f\\u00fc i\\u015faret eder: skorda -10 puan veya daha fazla, ya da s\\u0131ralamada +5 pozisyon kayb\\u0131. Bunlar ara\\u015ft\\u0131r\\u0131lmas\\u0131 gereken anlard\\u0131r \\u2014 o tarih i\\u00e7in Guardian uyar\\u0131lar\\u0131n\\u0131 kontrol edin.",tab_profile:"Profil",tab_attributes:"Nitelikler",tab_history:"Geçmiş",card_nap:"NAP & Bilgi",card_online:"Çevrimiçi Varlık",card_activity:"Aktivite",card_visibility:"Görünürlük",sh_fullscreen:"Tam ekran",sh_exit_fs:"Çık",card_nap_info_title:"NAP & Yerel SEO",card_nap_s1_title:"📍 NAP nedir?",card_nap_s1_body:"NAP; Ad, Adres ve Telefon anlamına gelir. Arama motorları işletmenizi doğrulamak için NAP\\u0027ı kullanır. Tutarsız NAP yerel sıralamanızı olumsuz etkiler.",card_nap_s2_title:"🎯 Neden önemli",card_nap_s2_body:"Google GBP\\u0027nizi diğer dizinlerle karşılaştırır. Ad veya adres farklılıkları güvensizlik yaratır.",card_nap_s3_title:"✅ Ne yapmalı",card_nap_s3_body:"Ad\u0131n\u0131z\u0131, adresinizi, telefon numaran\u0131z\u0131 ve kategorinizi Google Business Profile ve t\u00fcm dizinlerde kesinlikle ayn\u0131 tutun. Listelerinizi takip etmek i\u00e7in Al\u0131nt\u0131lar sekmesini kullan\u0131n.",card_nap_s4_title:"\u26a0\ufe0f Yeniden do\u011frulama veya ask\u0131ya alma riski",card_nap_s4_body:"Kategorinizi, a\u00e7\u0131klaman\u0131z\u0131 veya temel bilgilerinizi \u00e7ok h\u0131zl\u0131 de\u011fi\u015ftirmekten ka\u00e7\u0131n\u0131n. Google\u0027\u0131n algoritmalari\u0131n\u0131 de\u011fi\u015fiklikleri entegre etmesi zaman al\u0131r. \u00c7ok fazla h\u0131zl\u0131 de\u011fi\u015fiklik, yeniden do\u011frulama s\u00fcreci hatta fiche\u0027inizin ask\u0131ya al\u0131nmas\u0131n\u0131 tetikleyebilir.",card_online_info_title:"Çevrimiçi Varlık",card_online_s1_title:"🌐 Web sitesi",card_online_s1_body:"GBP\\u0027nize bağlı bir web sitesi güven ekler ve +5 puan verir.",card_online_s2_title:"🕒 Çalışma saatleri",card_online_s2_body:"Doğru çalışma saatleri müşterilerin sizi bulmasına yardımcı olur. Eksik saatler -3 puana mal olur.",card_online_s3_title:"📝 Açıklama",card_online_s3_body:"İyi bir açıklama Google\\u0027ın işletmenizi anlamasına yardımcı olur. Eksik açıklama -2 puana mal olur.",card_activity_info_title:"Aktivite & Etkileşim",card_activity_s1_title:"📸 Google Gönderileri",card_activity_s1_body:"Düzenli gönderi Google\\u0027a aktif olduğunuzu gösterir. Son 7 günde bir gönderi +5 puan verir.",card_activity_s2_title:"🖼️ Fotoğraflar",card_activity_s2_body:"Fotoğraflı işletmeler 42% daha fazla rota isteği alır. Son 7 günde yeni fotoğraflar maksimum puan verir.",card_activity_s3_title:"⭐ Yorum yanıtları",card_activity_s3_body:"Yorumlara yanıt vermek Google ve müşterilere aktif olduğunuzu gösterir. Son yorumu yanıtlayın ve +3 puan kazanın.",card_visibility_info_title:"Yerel Görünürlük",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"Heatmap, bölgenizdeki Google Haritalar sıralamanızı gösterir. Konumunuzu takip etmek için düzenli taramalar yapın.",card_visibility_s2_title:"📋 Alıntılar",card_visibility_s2_body:"Alıntılar dizinlerdeki işletme bildirimlerinizdir. Daha tutarlı alıntılar = Google\\u0027dan daha fazla güven.",card_visibility_s3_title:"📈 İlerleme takibi",card_visibility_s3_body:"Skorunuzun ve yerel sıralamanızın nasıl geliştiğini görmek için Geçmiş sekmesini kullanın.",card_see_more:"Daha fazla",card_see_less:"Daha az",attrs_info_title:"GBP Nitelikleri — Bilmeniz gerekenler",attrs_info_s1_title:"🔧 GBP Nitelikleri nedir?",attrs_info_s1_body:"Nitelikler, m\u00fc\u015fterilerin karar vermesine yard\u0131mc\u0131 olan ek i\u015fletme bilgileridir — eri\u015filebilirlik se\u00e7enekleri, \u00f6deme y\u00f6ntemleri, otopark, mevcut hizmetler vb. Do\u011frudan Google Business Profile\u0027\u0131n\u0131zda g\u00f6r\u00fcn\u00fcrler.",attrs_info_s2_title:"📍 Yerel SEO i\u00e7in neden \u00f6nemlidir",attrs_info_s2_body:"Eksiksiz nitelikler, Google\u0027a profilinizin ayr\u0131nt\u0131l\u0131 ve g\u00fcvenilir oldu\u011funu g\u00f6sterir. Ayr\u0131ca i\u015fletmenizin belirli filtrelenmi\u015f aramalarda g\u00f6r\u00fcnmesine yard\u0131mc\u0131 olur.",attrs_info_s3_title:"⚠️ \u00d6nemli — Baz\u0131 nitelikler burada d\u00fczenlenemez",attrs_info_s3_body:"Google, i\u015fletme kategorinize g\u00f6re hangi niteliklerin mevcut oldu\u011funu kontrol eder. Baz\u0131 nitelikler yaln\u0131zca do\u011frudan Google Business Profile \u00fczerinden de\u011fi\u015ftirilebilir. Burada yap\u0131lan de\u011fi\u015fiklikler uygulanmazsa l\u00fctfen business.google.com adresinden g\u00fcncelleyin.",attr_url_hint:"Google\u2019daki g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fcn\u00fcz\u00fc art\u0131rmak i\u00e7in bu URL\u2019leri ekleyin. Randevu ba\u011flant\u0131lar\u0131 i\u00e7in Google Business Profile \u2192 Profili d\u00fczenle \u2192 Rezervasyon b\u00f6l\u00fcm\u00fcne gidin.",guardian_home_title:"Guardian",guardian_home_status:"Aktif",guardian_checking:"Kontrol ediliyor...",guardian_disconnected:"Ba\u011flant\u0131 kesildi",guardian_home_subtitle:"Profilinizi 24\/7 izliyor",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 GBP N\u00f6bet\u00e7iniz",guardian_info_s1_title:"\ud83d\udd0d Guardian neyi izler",guardian_info_s1_body:"Guardian 10 alan\u0131 izler: ad, adres, telefon, web sitesi, ana kategori, \u00e7al\u0131\u015fma saatleri, a\u00e7\u0131klama, a\u00e7\u0131k\/kapal\u0131 durumu, kapa\u011f foto\u011fraflar\u0131 ve \u00f6zellikler.",guardian_info_s2_title:"\u26a0\ufe0f Neden kritik",guardian_info_s2_body:"Herkes profilinizde de\u011fi\u015fiklik \u00f6nerebilir. Fark edilmeyen de\u011fi\u015fiklikler s\u0131ralaman\u0131z\u0131 d\u00fc\u015f\u00fcrebilir. Guardian sizi an\u0131nda uyar\u0131r.",guardian_info_s3_title:"\u2705 Guardian\u2019\u0131n yapmad\u0131klar\u0131",guardian_info_s3_body:"Guardian s\u0131ralaman\u0131z\u0131 iyile\u015ftirmez. GBP\u2019nizi optimize etmeye devam edin. Guardian kazand\u0131\u011f\u0131n\u0131z g\u00f6r\u00fcn\u00fcrl\u00fc\u011f\u00fc korur.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 Plan\u0131n\u0131za dahil",guardian_info_s4_body:"Guardian Lite, 10 temel GBP alan\u0131n\u0131 7/24 izler ve \u015f\u00fcpheli bir de\u011fi\u015fiklik tespit etti\u011finde sizi an\u0131nda bilgilendirir. \u0130zleme her zaman plan\u0131n\u0131za dahildir \u2014 krediler yaln\u0131zca AVI bir de\u011fi\u015fikli\u011fi otomatik olarak d\u00fczeltirken kullan\u0131l\u0131r (ayda 3 kredi dahil \u00b7 d\u00fczeltme ba\u015f\u0131na 2 kredi).",guardian_info_cta:"Anla\u015f\u0131ld\u0131 \u2713",guardian_trial_ended:"Deneme sona erdi \u2014 krediler aktif",guardian_trial_active:"Ücretsiz deneme aktif",guardian_trial_days_left:"deneme s\u00fcresinde kalan g\u00fcn",guardian_pricing_detail:"Denemeden sonra: ayda 3 kredi + tespit edilen her de\u011fi\u015fiklik i\u00e7in 2 kredi",guardian_pricing_detail_active:"Ayda 3 kredi \u00b7 tespit edilen her de\u011fi\u015fiklik i\u00e7in 2 kredi",guardian_disabled_title:"Devre d\u0131\u015f\u0131",guardian_disabled_warn:"Profiliniz art\u0131k izlenmiyor. Rakipler GBP\u2019nizi habersizce de\u011fi\u015ftirebilir.",guardian_activate:"Guardian\u2019\u0131 etkinle\u015ftir \u2192",guardian_credits_active:"Krediler aktif",guardian_deactivate:"Guardian\u2019\u0131 devre d\u0131\u015f\u0131 b\u0131rak",guardian_post_trial_status:"\u26a0\ufe0f Deneme sona erdi",guardian_post_trial_warning:"\u26a0\ufe0f Profiliniz art\u0131k a\u00e7\u0131k. Rakipler ve Yerel K\u0131lavuzlar GBP\u2019nizi istedikleri zaman de\u011fi\u015ftirebilir \u2014 tespit edilemeyen de\u011fi\u015fiklikler s\u0131ralama d\u00fc\u015f\u00fc\u015f\u00fcne, yanl\u0131\u015f saatlere ve kay\u0131p aramalara yol a\u00e7ar.",guardian_deactivate_warn:"Devre d\u0131\u015f\u0131 b\u0131rak\u0131rsan\u0131z, profilinizdeki de\u011fi\u015fiklikler tamamen fark edilmeyecek. Bir rakip sizi kapal\u0131 olarak i\u015faretlerse bildirim almayacaks\u0131n\u0131z.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Guardian taraf\u0131ndan izleniyor \u2014 \u00fccretsiz deneme aktif",guardian_tooltip_active:"\u26A0\uFE0F Deneme sona erdi \u2014 krediler aktif. Y\u00f6netmek i\u00e7in ana sayfada \u2139\uFE0F\u2019e t\u0131klay\u0131n.",guardian_low_credits_title:"D\u00fc\u015f\u00fck Kredi \u2014 Guardian tehlikede",guardian_low_credits_warn:"10\u2019dan az krediniz var. Guardian yak\u0131nda izlemeyi durdurabilir.",guardian_credits_remaining:"Kalan kredi:",guardian_buy_credits:"Kredi sat\u0131n al \u2192",guardian_trial_expired_title:"\u00dccretsiz deneme sona erdi",guardian_trial_expired_warn:"15 g\u00fcnl\u00fck \u00fccretsiz denemeniz sona erdi. Profilinizi izlemeye devam etmek i\u00e7in Guardian\u2019\u0131 etkinle\u015ftirin.",guardian_trial_expired_badge:"\u23f1\ufe0f Deneme sona erdi \u2014 devam etmek i\u00e7in etkinle\u015ftirin",guardian_paid_active_title:"Guardian Etkin",guardian_next_billing:"Sonraki faturaland\u0131rma:",guardian_tooltip_off:"Guardian devre d\u0131\u015f\u0131 \u2014 bu alan art\u0131k izlenmiyor"},'
			. 'de:{close:"Schließen",cancel:"Abbrechen",save:"Speichern",delete:"Löschen",'
			. 'search_kw:"Keyword suchen...",add_kw:"+ Keyword hinzufügen",add_keyword:"+ Keyword hinzufügen",'
			. 'confirm_delete_scan:"Diesen geplanten Scan löschen?",'
			. 'kw_my_keywords:"Meine Keywords",kw_panel_title:"Meine Keywords",kw_panel_sub:"Verfolgen Sie die Suchbegriffe, die f\u00fcr Ihre lokale Sichtbarkeit wichtig sind. Jedes Keyword kann auf der Heatmap gescannt werden, um Ihre Google Maps-Position in Ihrer Umgebung anzuzeigen.",more:"weitere",'
			. 'import_kw:"📥 Importieren",export_kw:"📤 Exportieren",'
			. 'export_csv:"📊 CSV exportieren",export_pdf:"📄 PDF exportieren",'
			. 'import_label:"Keywords einfügen — eines pro Zeile oder kommagetrennt:",'
			. 'import_btn:"Importieren",scan_kw:"Dieses Keyword scannen",'
			. 'no_kw:"Noch keine Keywords — fügen Sie oben Ihr erstes Keyword hinzu",'
			. 'scanned:"✅ Gescannt",pending:"⬜ Ausstehend",threat:"⚠️ Bedrohung",'
			. 'actions:"Aktionen",'
			. 'col_keyword:"Keyword",col_rank:"Position",col_best:"Beste Position",'
			. 'col_grid:"Raster",col_status:"Status",col_scan:"Letzter Scan",'
			. 'col_threat:"Bedrohung",publish_now:"Jetzt veröffentlichen",schedule_post:"Beitrag planen",schedule_post_credits:"Planen (2 Credits)",publishing:"Wird veröffentlicht...",scheduling:"Wird geplant...",new_post:"Neuer GBP-Beitrag",edit_post:"Beitrag bearbeiten",posts_panel_title:"GBP Beiträge",posts_panel_sub:"Erstellen und verwalten Sie Ihre Google Business Profile Beiträge. Regelm\u00e4\u00dfige Beitr\u00e4ge verbessern Ihre Sichtbarkeit und halten Ihre Kunden \u00fcber Angebote, Neuigkeiten und Veranstaltungen informiert.",posts_info_title:"GBP Beitr\u00e4ge — So funktioniert es",posts_info_s1_title:"📝 Inhalte erstellen",posts_info_s1_body:"Schreiben Sie Beitr\u00e4ge (Angebot, News, Event) direkt aus LocalEdge. AVI kann mit einem Klick f\u00fcr Sie schreiben.",posts_info_s2_title:"📅 Planen",posts_info_s2_body:"Planen Sie Ihre Ver\u00f6ffentlichungen im Voraus, um eine regelm\u00e4\u00dfige Pr\u00e4senz auf Google aufrechtzuerhalten.",posts_info_s3_title:"📈 Sichtbarkeit steigern",posts_info_s3_body:"Google bevorzugt aktive Profile. Mindestens 1 Beitrag pro Woche wird empfohlen, um im Local Pack zu erscheinen.",upgrade_posts_title:"✨ GBP Beitr\u00e4ge automatisieren",upgrade_posts_sub:"Avision Pro ver\u00f6ffentlicht automatisch · Autopilot verf\u00fcgbar",new_post_btn:"+ Neuer Beitrag",write_content:"Inhalt (max. 1500 Zeichen)",write_content_ph:"Schreiben Sie Ihren Beitrag...",scheduled_date:"Geplantes Datum & Uhrzeit",no_content:"Kein Inhalt",post_type_label:"Beitragstyp",post_type_update:"📢 Update — Neuigkeiten & Ankündigungen",post_type_offer:"🏷️ Angebot — Aktionen",post_type_event:"📅 Event — Veranstaltungen",post_type_update_short:"📢 Update",post_type_offer_short:"🏷️ Angebot",post_type_event_short:"📅 Event",credits_info:"💳 Dies verbraucht 2 Credits aus Ihrem Guthaben.",credits_2:"2 Credits",publication:"Veröffentlichung",publish_now_title:"⚡ Jetzt veröffentlichen",schedule_title:"🕐 Planen",free:"Kostenlos",photo_optional:"Foto (optional)",upload_device:"📁 Vom Gerät hochladen",choose_photos:"🖼️ Aus Fotos wählen",gallery_soon:"Demnächst — richten Sie zuerst Ihre Galerie ein",gallery_first_alert:"Richten Sie zuerst Ihre GBP-Fotos-Galerie ein (Tab Fotos).",image_too_large:"Bild zu groß — max. 5 MB",err_no_content:"Bitte Beitragsinhalt eingeben.",err_content_long:"Inhalt überschreitet 1500 Zeichen.",err_no_schedule:"Bitte ein geplantes Datum wählen.",err_create_post:"Fehler beim Erstellen",err_network:"Netzwerkfehler",err_generic:"Fehler",no_posts:"Noch keine Beiträge",no_posts_sub:"Erstellen Sie Ihren ersten GBP-Beitrag für mehr Kundenbindung",posts_count_suffix:" Beitrag/Beiträge",event_title:"Event-Titel",event_title_ph:"z.B. Sommerschlussverkauf",start_date:"Startdatum",end_date:"Enddatum",filter_all:"Alle",post_status_published:"✅ Veröffentlicht",post_status_scheduled:"🕐 Geplant",post_status_pending:"⏳ Ausstehend",post_status_failed:"❌ Fehlgeschlagen",post_status_draft:"📝 Entwurf",view_btn:"👁 Ansehen",th_type:"Typ",th_content:"Inhalt",th_status:"Status",th_scheduled:"Geplant",th_published:"Veröffentlicht",th_actions:"Aktionen",sync_gbp:"🔄 Von GBP synchronisieren",syncing:"Synchronisiere...",publish_photo:"⚡ Veröffentlichen",schedule_photo:"🕐 Planen",delete_photo_title:"Aus Bibliothek löschen",delete_confirm:"Dieses Medium aus der Bibliothek löschen?",rename_hint:"Klicken zum Umbenennen",change_category:"Klicken zum Kategorie ändern",no_category:"Keine Kategorie",upload_photo:"+ Foto hochladen",select_photo_picker:"📎 Foto für Ihren Beitrag auswählen",'
			. 'schedule_date_prompt:"Datum und Uhrzeit (JJJJ-MM-TTHH:MM):",saving:"Speichern...",select_btn:"✓ Auswählen",copy_url:"URL kopieren",video_badge:"🎬 Video",sync_failed:"Synchronisierung fehlgeschlagen",photos_sync_success:"\u2705 Fotos von Google synchronisiert",delete_gbp_title:"Von GBP löschen",delete_gbp_confirm:"Dieses Foto von Ihrem Google-Profil löschen? Diese Aktion kann nicht rückgängig gemacht werden.",delete_gbp_success:"Foto von GBP gelöscht",delete_gbp_error:"Fehler beim Löschen von GBP",bulk_download:"Auswahl herunterladen",bulk_delete:"Aus Library löschen",bulk_delete_confirm:"{n} Foto(s) aus Library löschen?",bulk_delete_success:"{n} Foto(s) aus Library gelöscht",bulk_gbp_note:"\u26a0\ufe0f Google erlaubt keine Massenlöschung von Fotos \u2014 bitte einzeln löschen.",selected:"ausgewählt",select_category:"— Kategorie wählen (offiziell Google) —",rename_ph:"Keyword-Dateiname (z.B. klempner-berlin-service.jpg)",show_less_cats:"▲ Weniger anzeigen",show_all_cats:"▼ Alle GBP-Kategorien",photos_panel_title:"GBP Fotos",photos_panel_sub:"Verwalten Sie Ihre Google Business Profile Fotos: hochladen, organisieren, ver\u00f6ffentlichen und f\u00fcr lokales SEO optimieren.",photos_info_title:"GBP Fotos — So funktioniert es",photos_info_s1_title:"📚 Library / Published / Not Published",photos_info_s1_body:"Library = alle in LocalEdge gespeicherten Fotos. Published = auf Ihrem Google-Profil sichtbar. Not Published = hochgeladen, aber noch nicht an Google gesendet.",photos_info_s2_title:"🗂️ Kategorien",photos_info_s2_body:"Organisieren Sie Ihre Fotos nach Kategorien (Au\u00dfen, Innen, Team, Produkte…). Ein gut organisiertes Profil weckt mehr Vertrauen bei Kunden.",photos_info_s3_title:"✏️ Umbenennen f\u00fcr SEO",photos_info_s3_body:"Der Anzeigename Ihres Fotos ist wichtig f\u00fcr SEO. Verwenden Sie beschreibende Namen mit Ihren Keywords (z.B. \'italienisches-restaurant-paris-terrasse\'). Klicken Sie auf das Bleistift-Symbol zum Umbenennen.",photos_info_s4_title:"⬇️ Herunterladen & 🗑️ L\u00f6schen",photos_info_s4_body:"\u0027\u2b07\ufe0f Herunterladen\u0027 zum Speichern. \u0027\ud83d\uddd1\ufe0f Aus Library löschen\u0027 entfernt nur aus LocalEdge. \u0027\ud83c\udf10 Von GBP löschen\u0027 löscht dauerhaft von Ihrem Google-Profil (nicht rückgängig zu machen).",upgrade_photos_title:"✨ Immer frische Fotos auf Ihrem Profil",upgrade_photos_sub:"Avision Pro plant und ver\u00f6ffentlicht Ihre Fotos automatisch, damit Ihr Profil immer aktuell bleibt · Autopilot",photos_filter_library:"📚 Bibliothek",photos_filter_gbp_pub:"✅ Auf GBP veröffentlicht",photos_filter_gbp_unpub:"📚 Nicht veröffentlicht",photo_category_label:"Fotokategorie",filter_all_cats:"Alle Kategorien",download_label:"Herunterladen",upload_drag:"Fotos hierher ziehen",upload_drag_sub:"Fotos JPG/PNG (max. 5 MB) · Videos MP4 (max. 75 MB, 30s)",reply_btn:"💬 Antworten",cancel_reply:"Abbrechen",publish_reply:"Antwort veröffentlichen",publishing_reply:"Wird veröffentlicht...",reply_published:"Antwort auf Google ver\\u00f6ffentlicht!",write_reply_ph:"Schreiben Sie Ihre Antwort...",avi_writes_review:"✨ AVI schreibt",avi_rewrite_reply:"✨ Mit AVI umschreiben",edit_reply:"\\u270F\\uFE0F Bearbeiten",generating_reply:"✨ Wird generiert...",regenerate_reply:"↺ Neu generieren",ai_reply_error:"AVI konnte keine Antwort generieren.",your_reply:"💬 Ihre Antwort · ",no_reviews:"Keine Bewertungen gefunden",no_reviews_filter:"Keine Bewertungen passen zu diesem Filter",reviews_0:"0 Bewertungen",reviews_showing:"Anzeige ",reviews_of:" von ",reviews_suffix:" Bewertungen",load_more:"🔄 Mehr Bewertungen von Google laden",load_more_info:"✅ Alle ",load_more_info_end:" Bewertungen aus GBP-Cache geladen · Mit Avision Pro synchronisieren",load_more_loading:"Bewertungen werden geladen...",filter_all_stars:"Alle ⭐",without_reply:"💬 Ohne Antwort",sort_recent:"Neueste",sort_oldest:"Älteste",sort_lowest:"Niedrigste Bewertung",sort_unanswered:"Ohne Antwort zuerst",per_page:" pro Seite",previous:"← Zurück",next:"Weiter →",page_of:"Seite ",gbp_reviews_title:"Google Business Profile Bewertungen",gbp_reviews_sub:"Direkt antworten, um Vertrauen aufzubauen",reviews_info_title:"Google Bewertungen — So funktioniert es",reviews_info_s1_title:"⭐ Warum Bewertungen wichtig sind",reviews_info_s1_body:"Google-Bewertungen beeinflussen direkt Ihr lokales Ranking und Ihre Conversion-Rate. Ein Unternehmen mit aktuellen Antworten erscheint besser im Local Pack.",reviews_info_s2_title:"✉️ Antworten für Vertrauen",reviews_info_s2_body:"Auf jede Bewertung zu antworten — positiv oder negativ — zeigt Professionalität. AVI kann mit einem Klick eine personalisierte Antwort generieren.",reviews_info_s3_title:"📅 Bleiben Sie konsistent",reviews_info_s3_body:"Filtern Sie nach Neu, Diese Woche, Diesen Monat oder Dieses Jahr, um Ihre Antworten zu priorisieren und keine Bewertung zu verpassen.",tip_th_reviewer:"Name und Profilfoto des Kunden",tip_th_stars:"Bewertung des Rezensenten (1–5 Sterne)",tip_th_date:"Datum der Veröffentlichung der Bewertung",tip_th_review:"Vollständiger Bewertungsinhalt des Kunden",tip_th_replied:"Ob Sie auf diese Bewertung geantwortet haben",tip_th_actions:"Mit AVI antworten, bearbeiten oder neu generieren",filter_new:"Neu",filter_week:"Diese Woche",filter_month:"Diesen Monat",filter_year:"Dieses Jahr",filter_all_years:"Alle Jahre",filter_all_months:"Alle Monate",filter_all_weeks:"Alle Wochen",filter_all_replies:"Alle Bewertungen",filter_with_reply:"\u2705 Mit Antwort",flag_review_tip:"Diese Bewertung bei Google melden (Spam, gefälscht, unangemessen)",th_report:"Melden",tip_th_report:"Diese Bewertung bei Google melden (Spam, gefälscht, unangemessen)",upgrade_ai_title:"🤖 Schneller antworten mit KI",upgrade_ai_sub:"Avision Pro erstellt personalisierte Antworten in Sekunden · Autopilot verfügbar",upgrade_link:"Upgrade auf Avision Pro →",th_reviewer:"Autor",th_stars:"Sterne",th_date:"Datum",th_review:"Bewertung",th_replied:"Beantwortet",gbp_score_title:"📊 GBP Score",profile_completeness:"Profilvollständigkeit",profile_stats:"Profilstatistiken",last_sync:"🕐 Letzte Sync: ",crit_name:"Unternehmensname",pts_0:"Info",crit_website:"Website",crit_phone:"Telefonnummer",crit_hours:"Öffnungszeiten",crit_description:"Unternehmensbeschreibung",crit_category:"Hauptkategorie",crit_address:"Adresse",pts_5:"+5 pts",pts_4:"+4 pts",pts_3:"+3 pts",pts_2:"+2 pts",pts_1:"+1 pt",done:"✅ Erledigt",missing:"❌ Fehlt",reviews_label:"Bewertungen",photos_label:"Fotos",avg_rank:"Ø Rang",score_urgent:"Dringende Aufmerksamkeit nötig",score_improve:"Verbesserungspotenzial",score_getting:"Auf dem richtigen Weg",score_good:"Gutes Profil",score_excellent:"Exzellentes Profil",unknown:"Unbekannt",'
			. 'upsell_slim:"✨ Upgrade auf Avision Pro — Guardian · RAG · Multi-Profil",learn_more:"▲ Mehr erfahren",learn_close:"▼ Schließen",upsell_local:"🏠 Lokales Geschäft",upsell_agency:"🏢 Agentur",no_client:"Kein Kunde gefunden",search_client_ph:"🔍 Kunde suchen...",clients_title:"👥 Kunden",clients_trigger:"👥 Kunden ▾",loading:"⏳ Laden...",gbp_badge:"📍 GBP ↗",sync_btn:"🔄 Von Google synchronisieren",sync_info_title:"Von Google synchronisieren",sync_info_score_body:"Aktualisiert Ihren GBP-Score und Profildaten direkt von Google. Verwenden Sie diese Funktion, wenn Score, Bewertungen oder Attribute Ihre letzten Änderungen in Google Business Profile nicht widerspiegeln.",sync_info_home_body:"Aktualisiert alle Dashboard-Statistiken — Rankingdaten, Bewertungen und Scan-Verlauf. Verwenden Sie diese Funktion, wenn Ihre Statistiken veraltet erscheinen oder Sie kürzlich Änderungen in Ihrem Google Business Profile vorgenommen haben.",sync_info_footer:"Daten werden automatisch alle 24 Stunden aktualisiert. Diese Schaltfläche erzwingt eine sofortige Aktualisierung.",help_title:"Hilfe & FAQ",help_subtitle:"Finden Sie Antworten auf häufige Fragen zu Ihrem Google Business Profile",help_s1_title:"🔴 Top 5 — Häufige Probleme",help_s2_title:"🟣 Mein Profil optimieren",help_s3_title:"🔵 Google-Updates",help_faq1_q:"🚫 Mein Profil ist gesperrt",help_faq1_a:"Google sperrt Profile wegen keyword-gefüllter Namen, Adressinkonsistenzen oder zu vielen schnellen Änderungen. Beheben Sie das Problem zuerst, dann stellen Sie einen Wiederherstellungsantrag mit Nachweisen (Rechnung, Mietvertrag, Gewerbeschein). Erstellen Sie während des Verfahrens niemals ein Duplikat.",help_faq2_q:"🔍 Mein Profil erscheint nicht auf Google Maps",help_faq2_a:"Prüfen Sie, ob Ihr Profil vollständig verifiziert und veröffentlicht ist. Unverifizierte Profile erscheinen nicht. Neue Profile können 2 bis 4 Wochen brauchen, um konsistent angezeigt zu werden. Prüfen Sie auch die NAP-Konsistenz auf Ihrer Website und in anderen Verzeichnissen.",help_faq3_q:"✅ Wie verifiziere ich mein Profil (Video)",help_faq3_a:"Die Video-Verifizierung ist 2026 die Standardmethode. Nehmen Sie ein kontinuierliches Video auf, das Ihr Schild, den Innenraum und eine Live-Aktion in Ihrem GBP-Dashboard zeigt. Stellen Sie sicher, dass Name, Adresse und Website übereinstimmen, bevor Sie beginnen.",help_faq4_q:"✏️ Unbefugte Änderungen wurden an meinem Profil vorgenommen",help_faq4_a:"Jeder kann Änderungen vorschlagen und Google kann diese automatisch akzeptieren. Überprüfen Sie Ihre Angaben regelmäßig und machen Sie falsche Änderungen über Ihr GBP-Dashboard rückgängig. Der Guardian-Modus von LocalEdge überwacht Ihre Schlüsselfelder rund um die Uhr.",help_faq5_q:"⭐ Ich kann nicht auf Bewertungen antworten",help_faq5_a:"Dies deutet meist auf eine Profilbeschränkung hin, nicht auf eine vollständige Sperrung. Prüfen Sie Benachrichtigungen in Ihrem GBP-Dashboard. Stellen Sie sicher, dass Sie mit dem richtigen Google-Konto angemeldet sind, das das Profil besitzt.",help_faq6_q:"📸 Welche Fotos und wie viele sollte ich posten?",help_faq6_a:"Veröffentlichen Sie mindestens 10 Fotos: Außenansicht, Innenraum, Team, Produkte oder Dienstleistungen. Fügen Sie jeden Monat neue Fotos hinzu — Google belohnt aktive Profile. Vermeiden Sie Stockfotos oder KI-generierte Bilder. Echte Fotos Ihres Unternehmens schaffen Vertrauen und verbessern Ihr Ranking.",help_faq7_q:"🏷️ Wie wähle ich die richtige Hauptkategorie?",help_faq7_a:"Die Hauptkategorie ist der stärkste Ranking-Hebel auf Google Maps. Wählen Sie die spezifischste Kategorie, die Ihrem Kerngeschäft entspricht. Ein Klempner sollte Klempner wählen, nicht Haushaltsdienstleistungen. Sie können sekundäre Kategorien für weitere Leistungen hinzufügen.",help_faq8_q:"📝 Wie schreibe ich eine gute Unternehmensbeschreibung?",help_faq8_a:"Schreiben Sie 250 bis 750 Zeichen, in denen Sie beschreiben, was Sie tun, wem Sie dienen und was Sie auszeichnet. Integrieren Sie Ihre Hauptschlüsselwörter auf natürliche Weise. Vermeiden Sie Werbesprache, URLs oder Telefonnummern. Aktualisieren Sie die Beschreibung alle 6 Monate.",help_faq9_q:"🗓️ Wie oft sollte ich Beiträge veröffentlichen?",help_faq9_a:"Veröffentlichen Sie mindestens einmal pro Woche, um Frischesignale zu erhalten. Nutzen Sie AVI im Tab Posts, um Inhalte in Sekunden zu erstellen und zu planen. Neuigkeiten-Beiträge laufen nach 7 Tagen ab, Veranstaltungen bleiben bis zum Enddatum aktiv.",help_faq10_q:"⭐ Wie bekomme ich mehr Kundenbewertungen?",help_faq10_a:"Bitten Sie jeden zufriedenen Kunden direkt nach der Leistung um eine Bewertung. Senden Sie einen direkten Bewertungslink per E-Mail oder SMS. Fügen Sie einen QR-Code auf Ihren Belegen oder Karten hinzu. Bieten Sie niemals Anreize an oder schreiben Sie vor, was geschrieben werden soll — Google ahndet dies 2026.",help_faq11_q:"📍 Adresse anzeigen oder Servicegebiet?",help_faq11_a:"Wenn Kunden zu Ihnen kommen, zeigen Sie Ihre Adresse an. Wenn Sie zu Kunden fahren, blenden Sie die Adresse aus und fügen Sie Servicegebiete hinzu. Eine Privatadresse anzuzeigen, wenn Sie Kunden besuchen, kann zu Verwirrung führen und eine Sperrung riskieren.",help_faq12_q:"🔄 Ich habe ein doppeltes Profil — was soll ich tun?",help_faq12_a:"Doppelte Profile teilen Ihre Bewertungen und verwirren Google. Suchen Sie Ihr Unternehmen auf Google Maps und melden Sie das Duplikat über Änderung vorschlagen. Google wird das zusätzliche Profil zusammenführen oder entfernen. Verwalten Sie niemals zwei Profile für dasselbe Unternehmen.",help_faq13_q:"🤖 Q&A entfernt — ersetzt durch Ask Maps (Gemini)",help_faq13_a:"Google hat die Q&A-Funktion entfernt und durch Ask Maps mit Gemini AI ersetzt. Gemini beantwortet Nutzerfragen anhand Ihrer Profilfelder, Bewertungen, Fotos und Website. Füllen Sie alle GBP-Felder aus und fügen Sie FAQ-Inhalte mit Schema-Markup auf Ihrer Website hinzu.",help_faq14_q:"🛡️ Neue Bewertungsregeln 2026",help_faq14_a:"Google hat seine Bewertungsrichtlinien Anfang 2026 aktualisiert. KI-generierte Bewertungen sind jetzt verboten. Sie können weiterhin um Bewertungen bitten, dürfen aber nicht vorgeben, was geschrieben werden soll. Eine neutrale Bitte wie teilen Sie Ihre ehrliche Erfahrung ist sicher.",help_faq15_q:"⚡ Schnelle Änderungen können eine Sperrung auslösen",help_faq15_a:"Viele Änderungen auf einmal — Name, Adresse, Kategorie, Öffnungszeiten — sind 2026 ein häufiger Sperrungsauslöser. Verteilen Sie Ihre Änderungen auf mehrere Tage. Der Guardian-Modus von LocalEdge verfolgt Feldänderungen und warnt Sie, bevor Sie eine Risikoschwelle erreichen.",syncing_btn:"⏳ Synchronisieren...",sync_success:"✅ Profil synchronisiert!",sync_error:"Fehler. Erneut versuchen.",add_credits:"+ Pool-Credits",assign_credits:"+ Credits",assign_min_hint:"Min. 10 Cr \u00b7 Vielfache von 10",select_all:"Alle ausw\u00e4hlen",bulk_cr_each:"Cr je",bulk_assigning:"Wird zugewiesen...",bulk_assigned:"\u2705 Kunden gutgeschrieben",'
			. 'picker_title:"W\u00e4hlen Sie Ihr Google Business Profil",picker_subtitle:"W\u00e4hlen Sie das Profil, das Sie mit LocalEdge verwalten m\u00f6chten.",picker_btn:"Dieses Profil ausw\u00e4hlen",picker_loading:"Verbinde...",picker_error:"Verbindungsfehler. Bitte erneut versuchen.",picker_select_all:"Alle ausw\u00e4hlen",picker_import:"Ausgew\u00e4hlte Eintr\u00e4ge importieren",'
			. 'onboarding_title:"Verbinden Sie Ihr Google Business Profil",onboarding_subtitle:"Verbinden Sie Ihr GBP, um alle Funktionen freizuschalten: Score, Bewertungen, Fotos, Posts und mehr.",onboarding_connect:"\uD83D\uDD17 Google Business verbinden",onboarding_skip:"Sp\u00e4ter erledigen",onboarding_step1_title:"1. Anmelden",onboarding_step1_desc:"Google-Konto verbinden",onboarding_step2_title:"2. Ausw\u00e4hlen",onboarding_step2_desc:"Ihr Unternehmensprofil w\u00e4hlen",onboarding_step3_title:"3. Fertig!",onboarding_step3_desc:"Alle Funktionen freigeschaltet",edu_banner_title:"🎯 Willkommen in Ihrem lokalen SEO-Kontrollzentrum",edu_banner_body:"Ihr GBP ist verbunden. Optimieren Sie Ihren Score und \u00fcbertreffen Sie Ihre Mitbewerber.",edu_banner_close:"Verstanden \u2713",edu_help_btn:"💡",edu_modal_title:"So funktioniert LocalEdge",edu_step1_title:"Schritt 1 — Vervollst\u00e4ndigen Sie Ihr Profil",edu_step1_body:"Ihr GBP-Profil ist verbunden \u2705 Das ist Ihr Ausgangspunkt. Gehen Sie zum Tab GBP Score, um auf einen Blick zu sehen, welche Felder unvollst\u00e4ndig sind. Telefon, \u00d6ffnungszeiten, Beschreibung, Fotos, Kategorien — jedes fehlende Feld kostet Sie Positionen auf Google Maps. Ein 100% vollst\u00e4ndiges Profil erzielt bis zu 2x mehr Klicks.",edu_step2_title:"Schritt 2 — Scannen und analysieren",edu_step2_body:"W\u00e4hlen Sie im Heatmap-Tab 1 bis 5 Schl\u00fcsselw\u00f6rter, die Ihr Unternehmen beschreiben (z.B. \u0027Klempner Berlin\u0027). Starten Sie Ihren ersten Scan — jeder Rasterpunkt zeigt Ihre echte Google Maps-Position in diesem Bereich. Keine Sorge: Jede Seite enth\u00e4lt \u2139\uFE0F-Schaltfl\u00e4chen, die Sie Schritt f\u00fcr Schritt begleiten.",edu_step3_title:"Schritt 3 — Optimieren und wachsen",edu_step3_body:"Jetzt wissen Sie, wo Sie stehen — handeln Sie. GBP Score: Beheben Sie vorrangige Felder, um in den Ergebnissen aufzusteigen. Beitr\u00e4ge & Fotos: \u2728 AVI schreibt und plant Ihre Inhalte in Sekunden. Bewertungen: Antworten Sie innerhalb von 24h mit \u2728 AVI — Google belohnt Unternehmen, die mit ihren Kunden interagieren.",edu_learn_more:"So funktioniert es \u2192",tt_score:"Ihr GBP-Score misst die Vollst\u00e4ndigkeit und Optimierung Ihres Profils. Ein Score \u00fcber 70 verbessert Ihre Sichtbarkeit im Google Local Pack erheblich. Im GBP Score Tab finden \u2192",tt_unanswered:"Das Beantworten von Bewertungen innerhalb von 24h verbessert Ihren Google-Vertrauensscore. Gehen Sie zum Google Reviews Tab \u2192",tt_next_scan:"Regelm\u00e4\u00dfige Scans verfolgen die Entwicklung Ihrer lokalen Sichtbarkeit. Starten Sie einen Scan in Spalte 3 \u2192",tt_nap:"Die Vollst\u00e4ndigkeit Ihres Profils wirkt sich direkt auf Ihr lokales Ranking aus. Korrigieren Sie diese im GBP Score Tab \u2192",tt_control_center:"Ihre GBP-\u00dcbersicht: Score, unbeantwortete Bewertungen, n\u00e4chster geplanter Scan und Profilvollst\u00e4ndigkeit \u2014 alles an einem Ort zur Priorisierung.",clients_count_suffix:" Kunde(n)",pool_credits:"💳 Pool-Credits: ",available_word:" verfügbar · ",used_word:" genutzt",never:"Nie",today:"Heute",yesterday:"Gestern",sort_priority:"🚨 Priorität (niedriger Score zuerst)",sort_best_score:"⭐ Bester Score zuerst",sort_activity:"🕐 Letzte Aktivität",sort_name:"A→Z Name",sort_kw:"🔑 Meiste Keywords",scan_badge:" scan(s)",kw_badge:" Keywords",logo_too_large:"Logo zu groß — max. 2 MB",upload_logo:"📁 Logo hochladen",or_sep:"— oder —",agency_hub_title:"Agentur-Hub",col_suffix:" col",cols_suffix:" cols",err_rename:"Netzwerkfehler beim Umbenennen",err_file_too_large:"Datei zu groß",tip_col_keyword:"Verfolgter Suchbegriff",tip_col_rank:"Aktueller Durchschnittsrang über alle Heatmap-Punkte",tip_col_best:"Bester je erfasster Rang",tip_col_grid:"Rastergröße des letzten Scans",tip_col_status:"Ausstehend = nie gescannt · Gescannt = mit Daten",tip_col_scan:"Datum + Scan-Typ (solo oder multi)",tip_col_threat:"⚠️ Wettbewerber dominiert Top 3 auf über 50 % der Rasterpunkte",filter_danger:"⚠️ Gefahr",filter_solo_scan:"🔍 Solo-Scan",filter_multi_scan:"📊 Multi-Scan",filter_az:"A→Z",filter_all_grids:"Alle Raster",kw_solo_label:"🔍 Solo",kw_multi_label:"📊 Multi",kw_group_multi_prefix:"📊 Multi (",kw_group_keywords_suffix:" Keywords)",kw_group_solo:"🔍 Solo",kw_not_scanned_yet:"⬜ Noch nicht gescannt",export_col_city:"Stadt",export_col_scan_type:"Scan-Typ",export_yes:"Ja",export_no:"Nein",export_danger_yes:"⚠️ Ja",kw_report_title:"Keyword-Bericht",kw_report_generated:"Erstellt:",kw_report_keywords_suffix:" Keywords",import_kw_tip:"Mehrere Keywords importieren (eine pro Zeile oder CSV)",add_kw_ph:"Keyword eingeben (z.B. Klempner Berlin)",import_kw_ph:"Klempner Berlin\\nElektriker München\\nDachdecker Hamburg",post_char_of:" / 1500",post_add_photo:"📷 Foto hinzufügen",post_photo_formats:"JPG, PNG — max. 5 MB",export_col_created:"Erstellt",posts_page_title:"GBP Beiträge",posts_report_title:"GBP Beiträge Bericht",photo_status_in_stock:"📚 In Bibliothek",photos_count_suffix:" Foto(s)",no_photos:"Noch keine Fotos",no_photos_sub:"Laden Sie Fotos hoch, um Ihre GBP-Bibliothek aufzubauen",photo_alt_default:"GBP Foto",photo_sched_vid:"5 Cr",photo_sched_img:"3 Cr",err_rename_failed:"Umbenennen fehlgeschlagen",export_col_file:"Datei",export_col_category:"Kategorie",photos_page_title:"GBP Fotos",photos_report_title:"GBP Fotos Bericht",photos_library_count_suffix:" Fotos in Bibliothek",cat_cover:"🖼️ Titelbild",cat_profile:"👤 Profil",cat_logo:"🎨 Logo",cat_interior:"🏠 Innen",cat_exterior:"🏢 Außen",cat_product:"📦 Produkt",cat_at_work:"💼 Bei der Arbeit",cat_food_drink:"🍽️ Essen & Trinken",cat_menu:"📋 Speisekarte",cat_common_area:"🛋️ Gemeinschaftsbereich",cat_rooms:"🛏️ Zimmer",cat_teams:"👥 Teams",cat_additional:"➕ Zusätzlich",rv_replied_yes:"✅ Ja",rv_replied_no:"❌ Nein",export_col_reply:"Antwort",export_col_has_reply:"Beantwortet",reviews_page_title:"Bewertungsbericht",reviews_report_title:"Google Bewertungsbericht",reviews_pdf_avg:"⭐ Durchschnitt: ",reviews_pdf_reviews_suffix:" Bewertungen",export_col_criterion:"Kriterium",export_col_points:"Punkte",score_export_done:"Erledigt",score_export_missing:"Fehlt",score_export_score:"Score",score_export_rating:"Bewertung",score_export_photos:"Fotos",score_report_title:"GBP Score Bericht",score_pdf_stats:"Statistiken",score_pdf_rating:"⭐ Bewertung: ",score_pdf_photos:"📸 Fotos: ",rel_d_ago:"T",rel_w_ago:"Wo",rel_mo_ago:"Mon",rel_y_ago:"J",hub_subtitle:"Agentur-Einstellungen, Credits und White-Label verwalten.",hub_credit_pool:"💳 Credit-Pool",hub_tier_label:"Aktueller Plan",hub_tier_t1:"Tier 1 — bis zu 10 Eintr\u00e4ge",hub_tier_t2:"Tier 2 — bis zu 50 Eintr\u00e4ge",hub_tier_t3:"Tier 3 — unbegrenzte Eintr\u00e4ge",hub_listings_gauge:"Aktive Eintr\u00e4ge",hub_tier_upgrade:"Plan upgraden",hub_tier_downgrade:"Plan downgraden",hub_upgrade_processing:"Weiterleitung zur Zahlung...",hub_downgrade_confirm:"Downgrade auf diesen Plan best\u00e4tigen?",hub_downgrade_blocked:"Downgrade blockiert: zu viele aktive Eintr\u00e4ge.",hub_downgrade_success:"Plan erfolgreich aktualisiert.",hub_info_upgrade:"Upgrade: Sie zahlen nur den Unterschied zwischen den Pl\u00e4nen (anteilig).",hub_info_downgrade:"Downgrade: kostenlos, keine R\u00fcckerstattung. Blockiert wenn aktive Eintr\u00e4ge das neue Limit \u00fcberschreiten.",hub_available:"Verfügbar",hub_used:"Genutzt",hub_buy_credits:"+ Credits kaufen (Großhandel)",hub_whitelabel:"🎨 White-Label",hub_whitelabel_desc:"Logo-URL und Markenname im Embed und PDF-Exporten.",hub_logo_ph:"https://ihrlogo.com/logo.png",hub_brand_ph:"Ihr Agenturname",hub_save_settings:"Speichern",saved:"Gespeichert \u2713",hub_save_alert:"White-Label-Einstellungen — Sprint 45",hub_import_clients:"📥 Kunden importieren",hub_import_csv_desc:"CSV-Format: business_name, city, category, country",hub_import_csv_btn:"CSV importieren",hub_import_alert:"CSV-Import — Sprint 45",hub_pro_title:"🚀 Avision Pro Agentur",hub_pro_sub:"Helikopter-Ansicht · Massenaktionen · Erweiterte Berichte · Voller Guardian",hub_pro_cta:"Upgrade auf Avision Pro Agentur →",profile_title:"Mein Profil",profile_subtitle:"Verwalten Sie Ihre Credits und Ihr Konto.",profile_credits_available:"Verfügbare Credits",profile_credits_used:"Verbraucht",profile_buy:"+ Credits kaufen",profile_pack_nano:"Nano — 10 Credits",profile_pack_mini:"Mini — 30 Credits",profile_pack_standard:"Standard — 75 Credits",profile_pack_pro:"Pro — 200 Credits",profile_pack_agency:"Agentur — 600 Credits",profile_price_nano:"$2",profile_price_mini:"$5",profile_price_standard:"$11",profile_price_pro:"$25",profile_price_agency:"$59",profile_save_economy:" — sparen ",profile_upsell_title:"\\uD83D\\uDE80 Avision Pro",profile_upsell_sub:"Volles Dashboard · Guardian \\u00b7 Erweitertes SEO",profile_upsell_cta:"Upgrade auf Avision Pro \\u2192",credits_modal_title:"💳 Ihre LocalEdge-Credits",credits_modal_solo_p1:"Ihre LocalEdge-Credits verfallen nie — kaufen Sie bei Bedarf und nutzen Sie sie in Ihrem eigenen Tempo.",credits_modal_usage_title:"Wo Sie Ihre Credits ausgeben können:",credits_modal_heatmap:"🗺️ Heatmap-Scan — von 2 Cr (3×3) bis 60 Cr (21×21)",credits_modal_post:"📝 GBP-Post via AVI — 3 Cr",credits_modal_photo:"📷 GBP-Foto-Sync — 2 Cr",credits_modal_guardian:"🔔 Guardian (Profil-Überwachung) — kostenlos, inklusive",credits_modal_savings_title:"Je mehr Sie kaufen, desto weniger zahlen Sie pro Credit.",credits_modal_savings_sub:"Das Pro-Paket für $25 kostet 38% weniger pro Credit als das Nano-Paket.",credits_modal_agency_title:"💳 Ihr Agentur-Credit-Pool",credits_modal_agency_p1:"Ihr Pool wird auf alle Kundenprofile aufgeteilt. Kaufen Sie im Großhandel, verteilen Sie nach Bedarf.",credits_modal_agency_wholesale:"Großhandelspreis — Ihre Agentur-Credits kosten bis zu 47% weniger als Standardpreise. Ihre Marge gehört Ihnen.",credits_modal_agency_noexpiry:"Kein Ablaufdatum — Ihre Credits bleiben unbegrenzt verfügbar.",purchase_success_title:"\u2713 Zahlung eingegangen!",purchase_success_sub:"Ihre Credits sind in wenigen Sekunden verf\u00fcgbar.",purchase_success_close:"Verstanden",slider_title:"Oder w\u00e4hlen Sie Ihren Betrag",slider_credits:"Credits",slider_price_per:"pro Credit",slider_vs_nano:"vs Nano",slider_buy_btn:"Kaufen",slider_min_label:"10 Cr",slider_max_label_solo:"1.000 Cr",slider_max_label_agency:"5.000 Cr",client_balance:"Kundenguthaben",cr_need:"Ben\u00f6tigt",cr_available:"Verf\u00fcgbar",cr_missing:"Fehlend",days_ago:"T",attr_other:"Sonstige",anonymous_reviewer:"Anonym",error_generic:"Ein Fehler ist aufgetreten.",vs_standard:"vs Standard",badge_discount_17:"-17\u00a0%",badge_discount_27:"-27\u00a0%",badge_discount_38:"-38\u00a0%",badge_discount_16:"-16\u00a0%",badge_discount_30:"-30\u00a0%",badge_discount_40:"-40\u00a0%",badge_discount_47:"-47\u00a0%",ag_pack_starter:"Starter Agentur — 100 Credits",ag_pack_standard:"Standard Agentur — 300 Credits",ag_pack_pro:"Pro Agentur — 750 Credits",ag_pack_enterprise:"Enterprise Agentur — 2000 Credits",ag_price_starter:"14$",ag_price_standard:"35$",ag_price_pro:"75$",ag_price_enterprise:"175$",logo_preview_alt:"Logo-Vorschau",hub_uploaded_file:"(hochgeladene Datei)",ag_no_scan:"🗺️ Kein Scan",gbp_open_title:"GBP-Eintrag öffnen: ",gbp_search_title:"Auf Google Maps suchen: ",gbp_score:"GBP Score",unanswered:"Unbeantwortet",unanswered_sub:"Bewertungen beantworten",credits_left:"Guthaben",next_scan:"N\u00e4chster Scan",no_scan:"Kein Scan",nap_status:"Profilvollst\u00e4ndigkeit",nap_name:"Name",nap_address:"Adresse",nap_phone:"Telefon",nap_website:"Webseite",nap_hours:"Zeiten",nap_desc:"Beschreibung",fix_it:"Erg\u00e4nzen \\u2192",edit:"Bearbeiten",fix:"Korrigieren",edit_name:"Name bearbeiten",name_warn:"Eine \u00c4nderung des Namens kann eine Google-Pr\u00fcfung ausl\u00f6sen.",edit_website:"Website bearbeiten",edit_phone:"Telefon bearbeiten",edit_hours:"\u00d6ffnungszeiten bearbeiten",edit_description:"Beschreibung bearbeiten",edit_categories:"Kategorien bearbeiten",edit_address:"Adresse bearbeiten",edit_success:"Erfolgreich auf Google aktualisiert!",edit_error:"Fehler beim Aktualisieren. Bitte erneut versuchen.",lodging_posts_warn:"GBP-Beitr\u00e4ge sind f\u00fcr Beherbergungsbetriebe nicht verf\u00fcgbar.",hours_closed:"Geschlossen",hours_open:"Ge\u00f6ffnet",cat_search_placeholder:"Google-Kategorien suchen...",cat_primary:"Prim\u00e4re Kategorie",cat_additional:"Zus\u00e4tzliche Kategorien (max. 9)",cat_lodging_warn:"Das \u00c4ndern Ihrer Prim\u00e4rkategorie kann die Profilfunktionen beeinflussen.",addr_neighborhood:"Stadtviertel / Bezirk",addr_street:"Stra\u00dfe",addr_city:"Stadt",addr_region:"Bundesland / Region",addr_postal:"Postleitzahl",addr_country:"L\u00e4ndercode (z.B. DE)",verified:"Verifiziert",pending_verification:"Verifizierung ausstehend",not_verified:"Nicht verifiziert",verify_cta_text:"Ihr Profil ist auf Google nicht verifiziert. Verifizierte Profile erhalten mehr Vertrauen.",verify_cta_btn:"Mein Profil verifizieren \u2192",verify_pending_text:"Verifizierung l\u00e4uft. Google kann bis zu 7 Tage ben\u00f6tigen.",score_panel_sub:"Ihr Google Business Profile Optimierungsscore. Jedes ausgef\u00fcllte Feld verbessert Ihre Sichtbarkeit in lokalen Suchergebnissen.",score_info_title:"GBP Score \u2014 So funktioniert es",score_info_s1_title:"\uD83C\uDFAF Wie der Score berechnet wird",score_info_s1_body:"Basis 30 Pts + Website (+5) + \u00d6ffnungszeiten (+3) + Beschreibung 200+ Zeichen (+2) + Zusatzkategorie (+1) + Attribute \u22653 (+1). Maximum: 42 Pts.",score_info_s2_title:"\uD83D\uDCC8 Warum es wichtig ist",score_info_s2_body:"Ein vollst\u00e4ndiges und optimiertes Profil rankt besser im Google Local Pack. Jedes fehlende Feld kostet Sichtbarkeit in lokalen Suchen.",score_info_s3_title:"\u270F\uFE0F Wie man es verbessert",score_info_s3_body:"Klicken Sie bei jedem Kriterium auf Bearbeiten oder Korrigieren, um direkt \u00fcber LocalEdge zu aktualisieren \u2014 ohne Ihr Google-Profil zu \u00f6ffnen.",gbp_attributes_title:"GBP Attribute",attr_na:"N/A f\u00fcr diese Kategorie",attr_url_gbp_hint:"Auf Google Business Profile bearbeiten",attrs_filled:"Konfiguriert",crit_posts:"Aktuelle Beitr\u00e4ge",crit_photos:"Ver\u00f6ffentlichte Fotos",photos_published_label:"ver\u00f6ffentlicht",photos_min:"mind. 3 empfohlen",post_stale:"Letzter Beitrag > 7 Tage \u2014 ver\u00f6ffentlichen Sie, um Ihre Punkte zu behalten",post_fresh:"Frisch \u2014 innerhalb der letzten 7 Tage ver\u00f6ffentlicht",post_upsell:"Planen Sie einen Beitrag, um Ihren Score zu halten",photo_stale:"Letztes Foto > 7 Tage \u2014 ver\u00f6ffentlichen Sie, um Ihre Punkte zu behalten",photo_fresh:"Frisch \u2014 Foto innerhalb der letzten 7 Tage ver\u00f6ffentlicht",photo_upsell:"Ver\u00f6ffentlichen Sie ein Foto, um Ihren Score zu halten",crit_reviews_reply:"Letzte Bewertung beantwortet",replied:"Beantwortet",not_replied:"Nicht beantwortet",no_reviews_yet:"Noch keine Bewertungen",freshness_note:"Ihr Score schwankt je nach Aktivit\\u00e4t: Beitr\\u00e4ge, Fotos, Bewertungsantworten, Profilkomplettheit und Heatmap-Scans beeinflussen Ihr Ranking. Bleiben Sie aktiv, um Ihre Punkte zu maximieren.",view:"Ansehen",reply:"Antworten",attr_saved:"Attribut aktualisiert",attr_error:"Attribut konnte nicht aktualisiert werden",attrs_load_error:"Attribute konnten nicht geladen werden",attrs_load_hint:"Klicken Sie auf \uD83D\uDD04 Sync from Google zum Neuladen",hm_section_title:"🗺️ Heatmap-Sichtbarkeit",hm_info_title:"Heatmap — Warum es alles verändert",hm_info_s1_title:"📍 Kennen Sie Ihre genaue Position",hm_info_s1_body:"Jeder Scan kartiert Ihre Google Maps-Position an jedem Punkt Ihres Nachbarschaftsrasters. Sie sehen genau, wo Sie dominieren und wo Wettbewerber Sie übertreffen — Straße für Straße.",hm_info_s2_title:"🏆 Analysieren Sie Ihre Wettbewerber",hm_info_s2_body:"Die Heatmap zeigt, welche Wettbewerber die Top-3-Positionen an jedem Rasterpunkt besetzen. Identifizieren Sie, wen Sie überholen müssen, in welchen Zonen, und passen Sie Ihre lokale SEO-Strategie an.",hm_info_s3_title:"📐 Rastergröße = Gebietskontrolle",hm_info_s3_body:"Ein 7x7-Raster deckt Ihre unmittelbare Nachbarschaft ab. Ein 13x13-Raster kartiert Ihre gesamte Stadt. Je größer Ihr Raster, desto mehr Gebiet kontrollieren Sie und desto mehr Daten haben Sie für strategische Entscheidungen.",hm_info_s4_title:"🔄 Regelmäßige Scans = Ranking-Gewinne",hm_info_s4_body:"Scannen Sie wöchentlich dasselbe Keyword, um Ihre Entwicklung zu verfolgen. Jeder Scan verbraucht Credits, liefert aber umsetzbare Daten: Gewinnen oder verlieren Sie Positionen? Reagieren Sie, bevor Wettbewerber Ihre Plätze einnehmen.",hm_activity_label:"Scan-Aktivität",hm_performance_label:"Lokale Performance",hm_coverage_label:"Gebietsabdeckung",hm_scan_now:"Scan starten",hm_stale_warn:"Seit 30+ Tagen kein Scan — Ihre Daten sind veraltet",hm_no_scan:"Noch kein Scan — beginnen Sie, Ihr Gebiet zu kartieren",control_center:"Steuerzentrale",guardian_badge:"\ud83d\udd14 Warnungen",guardian_modal_title:"Guardian Lite \u2014 Profil-Warnungen",guardian_no_alerts:"Keine Warnungen erkannt",guardian_plan_free:"Kostenloser Plan \u2014 keine \u00dcberwachung",guardian_plan_lite:"Lite \u2014 1x\/Monat Scan",guardian_plan_standard:"Standard \u2014 w\u00f6chentlicher Scan",guardian_plan_daily:"T\u00e4glicher Scan aktiv",guardian_field_title:"Unternehmensname ge\u00e4ndert",guardian_field_phone:"Telefonnummer ge\u00e4ndert",guardian_field_categories:"Kategorie ge\u00e4ndert",guardian_field_hours:"\u00d6ffnungszeiten ge\u00e4ndert",guardian_field_website:"Website ge\u00e4ndert",guardian_field_openInfo:"Offen\/geschlossen-Status ge\u00e4ndert",guardian_why_title:"Warum Ihr Profil \u00fcberwachen?",guardian_why_1:"Jeder kann \u00c4nderungen an Ihrem GBP vorschlagen \u2014 auch Wettbewerber",guardian_why_2:"Local Guides haben viel Macht und k\u00f6nnen Ihr Unternehmen als geschlossen markieren",guardian_why_3:"Unentdeckte \u00c4nderungen f\u00fchren zu Ranking-Einbr\u00fcchen und Sichtbarkeitsverlust",guardian_fix_btn:"In GBP Score beheben \u2192",guardian_mark_read:"Alle als gelesen markieren",guardian_detected:"Erkannt:",guardian_old:"Vorher:",guardian_new:"Nachher:",guardian_verify:"sofort \u00fcberpr\u00fcfen",guardian_fix_now:"Jetzt beheben",guardian_field_address:"Adresse",guardian_field_description:"Beschreibung",guardian_field_specialHours:"Sonderzeiten",guardian_field_serviceArea:"Servicegebiet",crit_special_hours:"Sonderzeiten",crit_service_area:"Servicegebiet",special_hours_edit_info:"Sonderzeiten m\u00fcssen direkt \u00fcber Google Business Profile verwaltet werden.",service_area_edit_info:"Das Servicegebiet muss direkt \u00fcber Google Business Profile verwaltet werden.",guardian_changed:"\u00e4nderung",guardian_fix_gbp:"In GBP korrigieren \u2192",crit_open_status:"Gesch\u00e4ftsstatus",open_info_warn:"Das \u00c4ndern dieses Status aktualisiert Ihr Google Business Profil sofort.",open_status_open:"Ge\u00f6ffnet \u2014 Normale \u00d6ffnungszeiten",open_status_temp:"Vor\u00fcbergehend geschlossen \u2014 WiederEr\u00f6ffnung geplant",open_status_perm:"Dauerhaft geschlossen \u2014 dringend pr\u00fcfen",open_status_open_no_hours:"Ge\u00f6ffnet \u2014 Keine Hauptzeiten",open_status_unknown:"Status unbekannt",cit_title:"Eintr\u00e4ge",cit_listed:"hinzugef\u00fcgt",cit_done:"Hinzugef\u00fcgt",cit_mark_done:"\u2713 Hinzuf\u00fcgen",cit_already:"Bereits gelistet",cit_mark_already:"\u2713 Bereits gelistet",cit_trust:"Wir vertrauen Ihnen \u2014 wir \u00fcberpr\u00fcfen dies nicht automatisch",cit_url_placeholder:"URL Ihres Eintrags (optional)",cit_section_universal:"\ud83c\udf0d Universal",cit_section_local:"\ud83c\udff3\ufe0f Deutschland",cit_section_niche:"\ud83c\udfaf Ihre Branche",cit_todo:"\ud83d\udccb Zu erledigen",cit_completed:"Abgeschlossen",cit_collapse:"\u25b2 Einklappen",cit_expand:"\u25bc Ausklappen",cit_undo:"\u21a9 R\u00fcckg\u00e4ngig",cit_remove:"Entfernen",cit_add_name:"Verzeichnisname",cit_add_url:"https://...",cit_add_btn:"+ Hinzuf\u00fcgen",cit_banner_msg:"Wir haben automatisch Verzeichnisse basierend auf Ihrer Google Business Kategorie \"{cat}\" ausgew\u00e4hlt. Einige Vorschl\u00e4ge passen m\u00f6glicherweise nicht perfekt \u2014 l\u00f6schen Sie sie oder f\u00fcgen Sie Ihre eigenen hinzu.",cit_your_category:"Ihre Kategorie",cit_panel_sub:"Verfolgen Sie Ihre Eintr\u00e4ge in Verzeichnissen, um Ihre lokale SEO-Sichtbarkeit zu verbessern.",cit_info_title:"Eintr\u00e4ge & Lokales SEO",cit_info_s1_title:"\ud83d\udccd Was ist ein Eintrag?",cit_info_s1_body:"Ein Eintrag ist jede Online-Erw\u00e4hnung Ihres Unternehmensnamens, Ihrer Adresse und Telefonnummer (NAP). Suchmaschinen nutzen Eintr\u00e4ge, um Ihr Unternehmen zu verifizieren und Ihr lokales Ranking zu verbessern.",cit_info_s2_title:"\u26a0\ufe0f NAP-Konsistenz ist entscheidend",cit_info_s2_body:"Name, Adresse und Telefonnummer m\u00fcssen in allen Verzeichnissen exakt identisch sein \u2014 gleiche Abk\u00fcrzungen, gleiche Interpunktion, gleiches Format. Schon kleine Unterschiede verwirren Suchmaschinen.",cit_info_s3_title:"\ud83c\udfaf Warum diese Verzeichnisse?",cit_info_s3_body:"Wir haben automatisch Verzeichnisse basierend auf Ihrer Google Business Kategorie und Ihrem Standort ausgew\u00e4hlt. Einige Nischen-Vorschl\u00e4ge passen m\u00f6glicherweise nicht \u2014 l\u00f6schen Sie sie oder f\u00fcgen Sie Ihre eigenen hinzu.",cit_info_s4_title:"\u2705 Bereits eingetragen?",cit_info_s4_body:"Wenn Ihr Unternehmen bereits in einem Verzeichnis aufgef\u00fchrt ist, klicken Sie auf \u2018Bereits gelistet\u2019 und f\u00fcgen Sie optional die URL hinzu. Wir vertrauen Ihnen \u2014 wir \u00fcberpr\u00fcfen dies nicht automatisch, k\u00f6nnten es aber in Zukunft tun.",cit_score_section:"\ud83d\udccb Eintr\u00e4ge",cit_score_label:"Verzeichnisse",cit_score_detail:"Verzeichnisse eingetragen",cit_stale_warn:"F\u00fcgen Sie ein Verzeichnis hinzu, um Ihre Punktzahl zu erhalten",sh_title:"Score & Rang-Verlauf",sh_daily:"T\\u00e4glich",sh_score:"GBP Score",sh_rank:"Durchschn. Rang",sh_drop:"Einbruch",sh_all_kw:"Alle Keywords",sh_no_data:"Noch keine Daten. F\\u00fchren Sie einen Heatmap-Scan durch, um das Tracking zu starten.",sh_start:"Start",sh_now:"Jetzt",sh_best_rank:"Bester Rang",sh_info_title:"Ihren Score & Rang-Verlauf verstehen",sh_info_s1_title:"\\ud83d\\udcc8 GBP Score (lila)",sh_info_s1_body:"Ihr Google Business Profile Optimierungsscore von 0 bis 100. Er steigt, wenn Sie Ihr Profil vervollst\\u00e4ndigen, Fotos hinzuf\\u00fcgen, Bewertungen erhalten und Guardian-Warnungen beheben.",sh_info_s2_title:"\\ud83d\\udccd Durchschn. Rang (amber)",sh_info_s2_body:"Ihre durchschnittliche Position in den Google Maps-Ergebnissen \\u00fcber alle Heatmap-Rasterpunkte. Niedriger ist besser \\u2014 Rang #1 bedeutet, Sie erscheinen zuerst.",sh_info_s3_title:"\\u26a0\\ufe0f Warum schwankt mein Rang?",sh_info_s3_body:"Der GBP-Rang variiert je nach geografischer Position des Suchenden, verwendetem Keyword, Tageszeit und Google-Algorithmus-Updates. Das ist normal \\u2014 verfolgen Sie den Trend, nicht einzelne Punkte.",sh_info_s4_title:"\\ud83d\\udd34 Rote Punkte",sh_info_s4_body:"Ein roter Punkt signalisiert einen starken Einbruch: -10 Punkte oder mehr beim Score, oder +5 verlorene Positionen beim Rang. Das sind Momente zum Untersuchen \\u2014 pr\\u00fcfen Sie die Guardian-Warnungen f\\u00fcr dieses Datum.",tab_profile:"Profil",tab_attributes:"Attribute",tab_history:"Verlauf",card_nap:"NAP & Info",card_online:"Online-Präsenz",card_activity:"Aktivität",card_visibility:"Sichtbarkeit",sh_fullscreen:"Vollbild",sh_exit_fs:"Beenden",card_nap_info_title:"NAP & Lokales SEO",card_nap_s1_title:"📍 Was ist NAP?",card_nap_s1_body:"NAP steht für Name, Adresse und Telefonnummer. Suchmaschinen nutzen NAP zur Verifikation. Inkonsistentes NAP schadet Ihrem lokalen Ranking.",card_nap_s2_title:"🎯 Warum es wichtig ist",card_nap_s2_body:"Google vergleicht Ihr GBP mit anderen Verzeichnissen. Unterschiede beim Namen oder der Adresse wecken Zweifel.",card_nap_s3_title:"✅ Was tun",card_nap_s3_body:"Halten Sie Ihren Namen, Ihre Adresse, Telefonnummer und Kategorie auf Google Business Profile und allen Verzeichnissen streng identisch. Verwenden Sie den Tab Zitierungen, um Ihre Eintr\u00e4ge zu verfolgen.",card_nap_s4_title:"\u26a0\ufe0f Risiko einer erneuten Verifizierung oder Sperrung",card_nap_s4_body:"Vermeiden Sie es, Ihre Kategorie, Beschreibung oder wichtige Informationen zu schnell zu \u00e4ndern. Die Algorithmen von Google ben\u00f6tigen Zeit, um \u00c4nderungen zu integrieren. Zu viele schnelle \u00c4nderungen k\u00f6nnen ein erneutes Verifizierungsverfahren oder sogar eine Sperrung Ihres Eintrags ausl\u00f6sen.",card_online_info_title:"Online-Präsenz",card_online_s1_title:"🌐 Website",card_online_s1_body:"Eine verlinkte Website erhöht das Vertrauen und gibt +5 Punkte. Stellen Sie sicher, dass sie korrekt lädt.",card_online_s2_title:"🕒 Öffnungszeiten",card_online_s2_body:"Genaue Öffnungszeiten helfen Kunden, Sie zu finden. Fehlende Zeiten kosten -3 Punkte.",card_online_s3_title:"📝 Beschreibung",card_online_s3_body:"Eine gute Beschreibung hilft Google, Ihr Geschäft zu verstehen. Fehlende Beschreibung kostet -2 Punkte.",card_activity_info_title:"Aktivität & Engagement",card_activity_s1_title:"📸 Google Beiträge",card_activity_s1_body:"Regelmäßige Beiträge signalisieren Google, dass Ihr Unternehmen aktiv ist. Ein Beitrag in den letzten 7 Tagen gibt +5 Punkte.",card_activity_s2_title:"🖼️ Fotos",card_activity_s2_body:"Unternehmen mit Fotos erhalten 42% mehr Routenanfragen. Neue Fotos der letzten 7 Tage geben die maximale Punktzahl.",card_activity_s3_title:"⭐ Bewertungsantworten",card_activity_s3_body:"Das Antworten auf Bewertungen zeigt Google und Kunden, dass Sie aktiv sind. Antworten Sie auf Ihre letzte Bewertung für +3 Punkte.",card_visibility_info_title:"Lokale Sichtbarkeit",card_visibility_s1_title:"🗺️ Heatmap",card_visibility_s1_body:"Die Heatmap zeigt Ihr Google Maps-Ranking in Ihrem Gebiet. Führen Sie regelmäßige Scans durch.",card_visibility_s2_title:"📋 Einträge",card_visibility_s2_body:"Einträge sind Erwähnungen Ihres Unternehmens in Verzeichnissen. Mehr konsistente Einträge = mehr Vertrauen von Google.",card_visibility_s3_title:"📈 Fortschrittsverfolgung",card_visibility_s3_body:"Nutzen Sie die Verlauf-Registerkarte, um die Entwicklung Ihres Scores und lokalen Rankings zu sehen.",card_see_more:"Mehr anzeigen",card_see_less:"Weniger anzeigen",attrs_info_title:"GBP-Attribute — Was Sie wissen m\u00fcssen",attrs_info_s1_title:"🔧 Was sind GBP-Attribute?",attrs_info_s1_body:"Attribute sind zus\u00e4tzliche Details \u00fcber Ihr Unternehmen, die Kunden bei Entscheidungen helfen — Barrierefreiheit, Zahlungsmethoden, Parkm\u00f6glichkeiten, verf\u00fcgbare Dienstleistungen usw. Sie erscheinen direkt auf Ihrem Google Business Profil.",attrs_info_s2_title:"📍 Warum sie f\u00fcr lokales SEO wichtig sind",attrs_info_s2_body:"Vollst\u00e4ndige Attribute signalisieren Google, dass Ihr Profil detailliert und vertrauensw\u00fcrdig ist. Sie helfen auch dabei, bei spezifischen gefilterten Suchen zu erscheinen.",attrs_info_s3_title:"⚠️ Wichtig — Einige Attribute k\u00f6nnen hier nicht bearbeitet werden",attrs_info_s3_body:"Google kontrolliert, welche Attribute basierend auf Ihrer Unternehmenskategorie verf\u00fcgbar sind. Einige Attribute k\u00f6nnen nur direkt \u00fcber Google Business Profile ge\u00e4ndert werden. Falls \u00c4nderungen hier nicht wirksam werden, aktualisieren Sie diese bitte direkt auf business.google.com.",attr_url_hint:"F\u00fcgen Sie diese URLs hinzu, um Ihre Sichtbarkeit bei Google zu verbessern. F\u00fcr Terminlinks gehen Sie zu Google Business Profile \u2192 Profil bearbeiten \u2192 Buchung.",guardian_home_title:"Guardian",guardian_home_status:"Aktiv",guardian_checking:"Wird gepr\u00fcft...",guardian_disconnected:"Getrennt",guardian_home_subtitle:"\u00dcberwacht Ihr Profil 24\/7",guardian_info_title:"\ud83d\udee1\ufe0f Guardian \u2014 Ihr GBP-W\u00e4chter",guardian_info_s1_title:"\ud83d\udd0d Was Guardian \u00fcberwacht",guardian_info_s1_body:"Guardian \u00fcberwacht 10 Schl\u00fcsselfelder Ihres Google Business Profils: Name, Adresse, Telefon, Website, Hauptkategorie, \u00d6ffnungszeiten, Beschreibung, Offen\/Geschlossen-Status, Titelfotos und Attribute.",guardian_info_s2_title:"\u26a0\ufe0f Warum das entscheidend ist",guardian_info_s2_body:"Jeder \u2014 auch Mitbewerber oder Google selbst \u2014 kann \u00c4nderungen an Ihrem Profil vorschlagen. Unbemerkte \u00c4nderungen k\u00f6nnen Ihr Ranking \u00fcber Nacht einbrechen lassen. Guardian benachrichtigt Sie sofort.",guardian_info_s3_title:"\u2705 Was Guardian NICHT tut",guardian_info_s3_body:"Guardian verbessert Ihr Ranking nicht. Optimieren Sie weiterhin Ihr GBP, ver\u00f6ffentlichen Sie Posts und antworten Sie auf Bewertungen. Guardian sch\u00fctzt die Sichtbarkeit, die Sie bereits erworben haben.",guardian_info_s4_title:"\ud83d\udee1\ufe0f Guardian Lite \u2014 In Ihrem Plan enthalten",guardian_info_s4_body:"Guardian Lite \u00fcberwacht 10 wichtige GBP-Felder rund um die Uhr und benachrichtigt Sie sofort bei einem verd\u00e4chtigen \u00c4nderung. Die \u00dcberwachung ist immer in Ihrem Plan enthalten \u2014 Credits werden nur verwendet, wenn AVI eine \u00c4nderung automatisch behebt (3 Credits/Monat inklusive \u00b7 2 Credits pro Korrektur).",guardian_info_cta:"Verstanden \u2713",guardian_trial_ended:"Testphase beendet \u2014 Credits aktiv",guardian_trial_active:"Kostenlose Testphase aktiv",guardian_trial_days_left:"verbleibende Tage in der Testphase",guardian_pricing_detail:"Nach der Testphase: 3 Credits/Monat + 2 Credits pro erkannter \u00c4nderung",guardian_pricing_detail_active:"3 Credits/Monat \u00b7 2 Credits pro erkannter \u00c4nderung",guardian_disabled_title:"Deaktiviert",guardian_disabled_warn:"Ihr Profil wird nicht mehr \u00fcberwacht. Mitbewerber k\u00f6nnen Ihr GBP unbemerkt \u00e4ndern.",guardian_activate:"Guardian aktivieren \u2192",guardian_credits_active:"Credits aktiv",guardian_deactivate:"Guardian deaktivieren",guardian_post_trial_status:"\u26a0\ufe0f Testphase beendet",guardian_post_trial_warning:"\u26a0\ufe0f Ihr Profil ist jetzt ungesch\u00fctzt. Mitbewerber und Local Guides k\u00f6nnen Ihr GBP jederzeit \u00e4ndern \u2014 unentdeckte \u00c4nderungen f\u00fchren zu Ranking-Einbu\u00dfen, falschen \u00d6ffnungszeiten und verlorenen Anrufen.",guardian_deactivate_warn:"Wenn Sie deaktivieren, bleiben \u00c4nderungen an Ihrem Profil vollst\u00e4ndig unbemerkt. Sie werden nicht benachrichtigt, wenn ein Mitbewerber Sie als geschlossen markiert.",guardian_tooltip_trial:"\uD83D\uDEE1\uFE0F Von Guardian \u00fcberwacht \u2014 kostenlose Testphase aktiv",guardian_tooltip_active:"\u26A0\uFE0F Testphase beendet \u2014 Credits aktiv. Klicken Sie auf \u2139\uFE0F auf der Startseite zum Verwalten.",guardian_low_credits_title:"Wenig Credits \u2014 Guardian gef\u00e4hrdet",guardian_low_credits_warn:"Sie haben weniger als 10 Credits. Guardian k\u00f6nnte bald aufh\u00f6ren zu \u00fcberwachen.",guardian_credits_remaining:"Verbleibende Credits:",guardian_buy_credits:"Credits kaufen \u2192",guardian_trial_expired_title:"Kostenlose Testphase beendet",guardian_trial_expired_warn:"Ihre 15-t\u00e4gige kostenlose Testphase ist abgelaufen. Aktivieren Sie Guardian, um Ihr Profil weiter zu \u00fcberwachen.",guardian_trial_expired_badge:"\u23f1\ufe0f Testphase beendet \u2014 zum Fortfahren aktivieren",guardian_paid_active_title:"Guardian Aktiv",guardian_next_billing:"N\u00e4chste Abrechnung:",guardian_tooltip_off:"Guardian deaktiviert \u2014 dieses Feld wird nicht mehr \u00fcberwacht"},'
			. '};'
			. 'var _embedLang=(document.getElementById("avision-dashboard-root")&&document.getElementById("avision-dashboard-root").getAttribute("data-lang"))||"en";'
			. 'if(!_embedNavI18n[_embedLang])_embedLang="en";'
			. 'window.aviEmbedLang=_embedLang||"en";'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _embedNavLabels=_embedNavI18n[_embedLang];'
			. 'var _bootFreqLabels={"once":{"en":"One-time scan","fr":"Scan unique","es":"Escaneo único","de":"Einmaliger Scan","pt-br":"Scan único","tr":"Tek tarama"},"daily":{"en":"Daily","fr":"Quotidien","es":"Diario","de":"Täglich","pt-br":"Diário","tr":"Günlük"},"every3days":{"en":"Every 3 days","fr":"Tous les 3 jours","es":"Cada 3 días","de":"Alle 3 Tage","pt-br":"A cada 3 dias","tr":"Her 3 günde"},"weekly":{"en":"Weekly","fr":"Hebdomadaire","es":"Semanal","de":"Wöchentlich","pt-br":"Semanal","tr":"Haftalık"},"every2weeks":{"en":"Every 2 weeks","fr":"Toutes les 2 semaines","es":"Cada 2 semanas","de":"Alle 2 Wochen","pt-br":"A cada 2 semanas","tr":"Her 2 haftada"},"monthly":{"en":"Monthly","fr":"Mensuel","es":"Mensual","de":"Monatlich","pt-br":"Mensal","tr":"Aylık"}};'
			. 'var _bootCreditWord={"en":"credits","fr":"crédits","es":"créditos","de":"Credits","pt-br":"créditos","tr":"kredi"};'
			. 'try{'
			. '  var _bootFreqSel=document.querySelector("[data-avi-hm-frequency]");'
			. '  if(_bootFreqSel){Array.from(_bootFreqSel.options).forEach(function(o){var _fl=_bootFreqLabels[o.value];if(_fl)o.textContent=(_fl[_embedLang]||_fl["en"]);});}'
			. '  var _bootGridSel=document.querySelector("[data-avi-heatmap-grid-size]");'
			. '  var _bootCw=_bootCreditWord[_embedLang]||_bootCreditWord["en"];'
			. '  if(_bootGridSel){Array.from(_bootGridSel.options).forEach(function(o){var _s=parseInt(o.value,10);if(_s)o.textContent=window._leGridLabel(_s,_bootCw);});}'
			. '}catch(e){}'
			. 'var _embedCurrentTab="home";'
			. '/* Registre panneaux embed — déclarations centralisées (anti-régression scope) */'
			. 'var _homePanel=null;'
			. 'var _previewPanel=null;'
			. 'var _scoreEditModal=null;'
			. 'var _kwPanel=null;'
			. 'var _scorePanel=null;'
			. 'var _reviewsPanel=null;'
			. 'var _postsPanel=null;'
			. 'var _postsFilter="all";'
			. 'var _photosPanel=null;'
			. 'var _citationsPanel=null;'
			. 'var _helpPanel=null;'
			. 'var _photosFilter="all";'
			. 'var _photosFilterCat="all";'
			. 'var _photosCols=3;'
			. 'var _agHubPanel=null;'
			. 'var _profilePanel=null;'
			. 'var _agPanel=null;'
			. 'var _agOverlay=null;'
			. 'var _agTrigger=null;'
			. 'var _agActiveProfileId=window.aviEmbedProfileId;'
			. 'var _subWrap=null;'
			. 'var _subDrop=null;'
			. 'var _gbpBadge=null;'
			. 'var _agActiveName=null;'
			. 'var _upsellBar=null;'
			. 'var _langSel=null;'
			. 'var _langWrap=null;'
			. 'var _langDropdown=null;'
			. 'var _langDropdownOpen=false;'
			. 'var _mobileMenu=null;'
			. 'var _hamburger=null;'
			. 'var _nav=document.createElement("nav");'
			. '_nav.className="avi-embed-nav";'
			. '_nav.setAttribute("role","tablist");'
			. 'var _navBtns={};'
			. 'function _setNavBtnLabel(btn,label){'
			. 'var iconEl=btn.querySelector(".avi-nav-icon");'
			. 'var labelEl=btn.querySelector(".avi-nav-label");'
			. 'if(!iconEl||!labelEl){btn.textContent=label;return;}'
			. 'var sp=label.indexOf(" ");'
			. 'if(sp>0){iconEl.textContent=label.substring(0,sp);labelEl.textContent=label.substring(sp+1);}'
			. 'else{iconEl.textContent=label;labelEl.textContent="";}'
			. '}'
			. '_embedNavTabs.forEach(function(tab){'
			. 'var btn=document.createElement("button");'
			. 'btn.type="button";'
			. 'btn.className="avi-embed-nav-btn";'
			. 'btn.setAttribute("data-embed-tab",tab);'
			. 'btn.setAttribute("role","tab");'
			. 'btn.setAttribute("aria-selected",tab==="home"?"true":"false");'
			. 'var _navIcon=document.createElement("span");'
			. '_navIcon.className="avi-nav-icon";'
			. 'var _navLabel=document.createElement("span");'
			. '_navLabel.className="avi-nav-label";'
			. 'btn.appendChild(_navIcon);'
			. 'btn.appendChild(_navLabel);'
			. '_setNavBtnLabel(btn,_embedNavLabels[tab]);'
			. '_nav.appendChild(btn);'
			. '_navBtns[tab]=btn;'
			. 'if(tab==="score"){'
			. 'var _gBadge=document.createElement("span");'
			. '_gBadge.id="avi-guardian-nav-badge";'
			. '_gBadge.style.cssText="display:none;background:#ef4444;color:#fff;border-radius:50%;font-size:9px;font-weight:700;min-width:16px;height:16px;line-height:16px;text-align:center;padding:0 3px;margin-left:4px;vertical-align:middle;flex-shrink:0;";'
			. 'btn.appendChild(_gBadge);'
			. '_gBadge.addEventListener("click",function(e){'
			. 'e.stopPropagation();e.stopImmediatePropagation();e.preventDefault();'
			. 'var _sBtn=document.querySelector("[data-embed-tab=\u0022score\u0022]");'
			. 'if(_sBtn)_sBtn.click();'
			. '});'
			. '}'
			. '});'
			. 'if(window.aviEmbedProfileId&&window.aviEmbedToken){'
			. '(function(){'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-plan?profile_id="+window.aviEmbedProfileId,{'
			. 'headers:{"X-Embed-Token":window.aviEmbedToken||""}'
			. '})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(p){'
			. 'if(p){'
			. 'window._aviGuardianPlan=p;'
			. '_aviGuardianInjectScore();'
			. 'if(document.getElementById("aviEmbedScorePanel")&&document.getElementById("aviEmbedScorePanel").style.display!=="none"){_scoreRender();}'
			. '}'
			. '}).catch(function(){});'
			. 'document.addEventListener("avi-home-rendered",function(){_aviGuardianInjectScore();});'
			. 'document.addEventListener("avi-score-rendered",function(){if(window._aviGuardianPlan)_scoreRender();});'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-alerts?profile_id="+window.aviEmbedProfileId,{'
			. 'headers:{"X-Embed-Token":window.aviEmbedToken||""}'
			. '})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){'
			. 'if(!d)return;'
			. 'window._aviGuardianAlerts=d.alerts||[];'
			. 'window._aviGuardianUnread=d.unread_count||0;'
			. 'var _gb=document.getElementById("avi-guardian-nav-badge");'
			. 'if(_gb&&d.unread_count>0){'
			. '_gb.textContent=d.unread_count>9?"9+":String(d.unread_count);'
			. '_gb.style.display="inline-block";'
			. '}'
			. 'if(typeof _renderHomeDashboard==="function"&&_embedCurrentTab==="home")_renderHomeDashboard();'
			. 'if(typeof _scoreRender==="function"&&_embedCurrentTab==="score")_scoreRender();'
			. '})'
			. '.catch(function(){});'
			. '})();'
			. '}'
			. '_mobileMenu=document.createElement("div");'
			. '_mobileMenu.className="avi-embed-mobile-menu";'
			. '_mobileMenu.id="aviEmbedMobileMenu";'
			. '_embedNavTabs.forEach(function(tab){'
			. 'var mb=document.createElement("button");'
			. 'mb.type="button";'
			. 'mb.className="avi-embed-mobile-menu-btn";'
			. 'mb.setAttribute("data-embed-tab",tab);'
			. 'mb.setAttribute("aria-selected",tab==="home"?"true":"false");'
			. 'mb.textContent=_embedNavLabels[tab];'
			. '_mobileMenu.appendChild(mb);'
			. '});'
			. 'if(window.aviEmbedKeyType==="agency"){'
			. 'var _mobClientsBtn=document.createElement("button");'
			. '_mobClientsBtn.type="button";'
			. '_mobClientsBtn.className="avi-embed-mobile-menu-btn";'
			. '_mobClientsBtn.textContent=(_t.clients_title||"\\uD83D\\uDC65 Clients");'
			. '_mobClientsBtn.addEventListener("click",function(){'
			. 'if(_mobileMenu)_mobileMenu.classList.remove("is-open");'
			. 'if(_hamburger)_hamburger.textContent="\\u2630";'
			. 'var clientsTrigger=document.querySelector("[data-avi-ag-trigger]");'
			. 'if(clientsTrigger)clientsTrigger.click();'
			. '});'
			. '_mobileMenu.insertBefore(_mobClientsBtn,_mobileMenu.firstChild);'
			. 'var _mobHubBtn=document.createElement("button");'
			. '_mobHubBtn.type="button";'
			. '_mobHubBtn.className="avi-embed-mobile-menu-btn";'
			. '_mobHubBtn.innerHTML="\\uD83C\\uDFE2 "+(_t.agency_hub_title||"Agency Hub");'
			. '_mobHubBtn.addEventListener("click",function(){'
			. 'if(_mobileMenu)_mobileMenu.classList.remove("is-open");'
			. 'if(_hamburger)_hamburger.textContent="\\u2630";'
			. 'if(typeof window._agOpenCreditsHub==="function"){'
			. 'window._agOpenCreditsHub();'
			. '}else{_switchEmbedTab("agency_hub");}'
			. '});'
			. '_mobileMenu.insertBefore(_mobHubBtn,_mobileMenu.firstChild);'
			. '}'
			. 'function _isLodging(){'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var cid=sd.primary_category_id||"";'
			. 'var lodgingIds=["gcid:hotel","gcid:motel","gcid:resort_hotel","gcid:bed_and_breakfast","gcid:hostel","gcid:inn","gcid:lodging"];'
			. 'for(var i=0;i<lodgingIds.length;i++){'
			. 'if(cid.indexOf(lodgingIds[i])!==-1)return true;'
			. '}'
			. 'return false;'
			. '}'
			. 'function _applyLodgingPostsTab(){'
			. 'if(!_navBtns||!_navBtns.posts)return;'
			. 'if(_isLodging()){'
			. '_navBtns.posts.style.display="none";'
			. 'if(_mobileMenu){'
			. 'var _mpBtn=_mobileMenu.querySelector("[data-embed-tab=\\"posts\\"]");'
			. 'if(_mpBtn)_mpBtn.style.display="none";'
			. '}'
			. 'if(_embedCurrentTab==="posts")_switchEmbedTab("home");'
			. '}else{'
			. '_navBtns.posts.style.display="";'
			. 'if(_mobileMenu){'
			. 'var _mpBtn2=_mobileMenu.querySelector("[data-embed-tab=\\"posts\\"]");'
			. 'if(_mpBtn2)_mpBtn2.style.display="";'
			. '}'
			. '}'
			. '}'
			. '_applyLodgingPostsTab();'
			. 'var _embedLangs=[{code:"en",flag:"",label:"English"},{code:"fr",flag:"",label:"Français"},{code:"es",flag:"",label:"Español"},{code:"pt-br",flag:"",label:"Português (BR)"},{code:"tr",flag:"",label:"Türkçe"},{code:"de",flag:"",label:"Deutsch"}];'
			. 'var _embedLangDisplay=function(l){return(l.flag?l.flag+" ":"")+l.label;};'
			. '_langSel=document.createElement("div");'
			. '_langSel.className="avi-embed-lang-sel";'
			. 'var _langTrigger=document.createElement("button");'
			. '_langTrigger.type="button";'
			. '_langTrigger.className="avi-embed-lang-btn";'
			. 'var _currentLangData=_embedLangs.find(function(l){return l.code===_embedLang;})||_embedLangs[0];'
			. '_langTrigger.textContent=_embedLangDisplay(_currentLangData)+" ▾";'
			. '_langSel.appendChild(_langTrigger);'
			. '_langDropdown=document.createElement("div");'
			. '_langDropdown.className="avi-embed-lang-dropdown";'
			. '_embedLangs.forEach(function(l){'
			. 'var opt=document.createElement("button");'
			. 'opt.type="button";'
			. 'opt.className="avi-embed-lang-option"+(l.code===_embedLang?" active":"");'
			. 'opt.setAttribute("data-embed-lang",l.code);'
			. 'opt.textContent=_embedLangDisplay(l);'
			. '_langDropdown.appendChild(opt);'
			. '});'
			. 'document.body.appendChild(_langDropdown);'
			. '_langWrap=document.createElement("div");'
			. '_langWrap.className="avi-embed-lang-wrap";'
			. '_langWrap.appendChild(_langSel);'
			. '_langDropdownOpen=false;'
			. '_langTrigger.addEventListener("click",function(e){'
			. 'e.preventDefault();'
			. 'e.stopPropagation();'
			. '_langDropdownOpen=!_langDropdownOpen;'
			. 'if(_langDropdownOpen){'
			. 'var rect=_langTrigger.getBoundingClientRect();'
			. '_langDropdown.style.top=(rect.bottom+4)+"px";'
			. '_langDropdown.style.right=(window.innerWidth-rect.right)+"px";'
			. '_langDropdown.style.left="auto";'
			. '_langDropdown.style.display="block";'
			. '}else{'
			. '_langDropdown.style.display="none";'
			. '}'
			. '});'
			. 'document.addEventListener("click",function(e){'
			. 'if(!_langSel.contains(e.target)&&!_langDropdown.contains(e.target)){'
			. '_langDropdownOpen=false;'
			. '_langDropdown.style.display="none";'
			. '}'
			. '});'
			. '_langDropdown.addEventListener("click",function(e){'
			. 'var opt=e.target.closest("[data-embed-lang]");'
			. 'if(!opt)return;'
			. 'var lang=opt.getAttribute("data-embed-lang");'
			. '_setEmbedLang(lang);'
			. '_langDropdownOpen=false;'
			. '_langDropdown.style.display="none";'
			. '});'
			. 'var _module=document.querySelector(".avi-radar-heatmap-module");'
			. 'var _closed=document.querySelector(".avi-heatmap-closed");'
			. 'var _drawer=document.querySelector(".avi-heatmap-drawer");'
			. 'var _modal=document.querySelector(".avi-heatmap-modal");'
			. '_previewPanel=document.querySelector(".avi-heatmap-panel--preview");'
			. '_homePanel=document.createElement("div");'
			. '_homePanel.id="aviEmbedHomeDashboard";'
			. '_homePanel.className="avi-embed-home-dashboard";'
			. 'if(_previewPanel){'
			. 'var _openMapBtn=_previewPanel.querySelector(".avi-hm-open-map-btn");'
			. 'if(_openMapBtn){'
			. '_previewPanel.insertBefore(_homePanel,_openMapBtn);'
			. '}else{'
			. '_previewPanel.appendChild(_homePanel);'
			. '}'
			. '}'
			. '_scoreEditModal=document.createElement("div");'
			. '_scoreEditModal.id="aviScoreEditModal";'
			. '_scoreEditModal.className="avi-score-edit-modal-backdrop";'
			. '_scoreEditModal.style.display="none";'
			. 'document.body.appendChild(_scoreEditModal);'
			. 'function _aviGuardianInjectScore(){'
			. 'if(!window.aviEmbedGbpConnected&&window.aviEmbedAgencyId>0){'
			. 'var _gDot=document.querySelector(".avi-guardian-dot");'
			. 'if(_gDot){_gDot.style.background="#9ca3af";_gDot.style.animation="none";_gDot.style.boxShadow="none";}'
			. 'var _gBadge=document.querySelector("[data-guardian-info]");'
			. 'if(_gBadge){'
			. '_gBadge.style.opacity="0.45";'
			. '_gBadge.style.pointerEvents="none";'
			. 'var _gInfoBtn=_gBadge.querySelector(".avi-guardian-badge-info,[data-action=\\"guardian-info\\"],button.avi-guardian-info-btn,.avi-guardian-info");'
			. 'if(_gInfoBtn){_gInfoBtn.style.pointerEvents="auto";_gInfoBtn.style.opacity="1";_gInfoBtn.style.cursor="pointer";}'
			. 'var _gTxt=_gBadge.querySelector(".avi-guardian-badge-status");'
			. 'if(_gTxt)_gTxt.textContent=(_t&&_t.guardian_disconnected)||"Disconnected";'
			. '}'
			. 'document.querySelectorAll(".avi-score-btn-guardian-trial,.avi-score-btn-guardian-active").forEach(function(el){'
			. 'el.classList.remove("avi-score-btn-guardian-trial","avi-score-btn-guardian-active");'
			. 'el.classList.add("avi-score-btn-guardian-off");'
			. '});'
			. 'return;'
			. '}'
			. 'var existing=document.getElementById("avi-guardian-score-banner");'
			. 'if(existing)existing.parentNode.removeChild(existing);'
			. 'var _gp=window._aviGuardianPlan||null;'
			. 'var _dot=document.querySelector(".avi-guardian-dot");'
			. 'var _statusEl=document.querySelector(".avi-guardian-badge-status");'
			. 'if(!_dot)return;'
			. 'var _tGI=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _gIsOff=_gp&&_gp.plan==="free";'
			. 'var _gIsTrialExp=_gp&&!_gp.is_trial&&!_gp.is_paid&&_gp.plan!=="free";'
			. 'if(_gIsOff){'
			. '_dot.style.background="#9ca3af";'
			. '_dot.style.animation="none";'
			. 'if(_statusEl){_statusEl.textContent=_tGI.guardian_disabled_title||"Deactivated";_statusEl.style.color="#9ca3af";}'
			. '}else if(_gIsTrialExp){'
			. '_dot.style.background="#f97316";'
			. '_dot.style.animation="avi-pulse-orange 2s infinite";'
			. 'if(_statusEl){_statusEl.textContent=_tGI.guardian_trial_expired_badge||"\u23f1\ufe0f Trial ended";_statusEl.style.color="#f97316";}'
			. '}else if(!_gp||_gp.is_trial){'
			. '_dot.style.background="#22c55e";'
			. '_dot.style.animation="avi-pulse-green 2s infinite";'
			. 'if(_statusEl){_statusEl.textContent=_tGI.guardian_home_status||"Active";_statusEl.style.color="#22c55e";}'
			. '}else{'
			. '_dot.style.background="#22c55e";'
			. '_dot.style.animation="avi-pulse-green 2s infinite";'
			. 'if(_statusEl){_statusEl.textContent=_tGI.guardian_home_status||"Active";_statusEl.style.color="#22c55e";}'
			. '}'
			. '}'
			. 'function _aviGuardianMarkReadAuto(){'
			. 'if(!window._aviGuardianUnread||window._aviGuardianUnread===0)return;'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-alerts/mark-read",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId})'
			. '}).then(function(){'
			. 'window._aviGuardianUnread=0;'
			. 'var _gb=document.getElementById("avi-guardian-nav-badge");'
			. 'if(_gb)_gb.style.display="none";'
			. '}).catch(function(){});'
			. '}'
			. '_scoreEditModal.addEventListener("click",function(e){'
			. 'if(e.target===_scoreEditModal)_closeScoreEditModal();'
			. '});'
			. 'if(window.aviEmbedIsHosted&&window.aviEmbedLogoutUrl){'
			. 'var _logoutBtn=document.createElement("a");'
			. '_logoutBtn.href=window.aviEmbedLogoutUrl;'
			. '_logoutBtn.className="avi-embed-logout-btn";'
			. '_logoutBtn.title="Logout";'
			. '_logoutBtn.innerHTML="\uD83D\uDD13";'
			. '_logoutBtn.style.cssText="display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:6px;background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2);color:#fff;text-decoration:none;font-size:13px;margin-left:6px;flex-shrink:0;transition:background .15s;cursor:pointer;";'
			. '_logoutBtn.addEventListener("mouseover",function(){_logoutBtn.style.background="rgba(255,255,255,0.18)";});'
			. '_logoutBtn.addEventListener("mouseout",function(){_logoutBtn.style.background="rgba(255,255,255,0.1)";});'
			. '}'
			. 'if(_module&&_closed&&_nav){'
			. 'var _navWrap=document.createElement("div");'
			. '_navWrap.className="avi-embed-nav-wrap";'
			. '_navWrap.appendChild(_nav);'
			. 'if(_langWrap&&(!window.aviEmbedGbpConnected||window.aviEmbedIsAdmin))_navWrap.appendChild(_langWrap);'
			. 'if(window.aviEmbedIsHosted&&typeof _logoutBtn!=="undefined")_navWrap.appendChild(_logoutBtn);'
			. '_hamburger=document.createElement("button");'
			. '_hamburger.type="button";'
			. '_hamburger.className="avi-embed-hamburger";'
			. '_hamburger.id="aviEmbedHamburger";'
			. '_hamburger.textContent="\\u2630";'
			. '_navWrap.appendChild(_hamburger);'
			. 'if(_mobileMenu)_navWrap.appendChild(_mobileMenu);'
			. '_closed.parentNode.insertBefore(_navWrap,_closed.nextSibling);'
			. '}'
			. 'if(_closed){'
			. 'var _bg=window.getComputedStyle(_closed).backgroundColor;'
			. '_nav.style.background=_bg;'
			. 'if(_langWrap)_langWrap.style.background=_bg;'
			. 'var _nw=document.querySelector(".avi-embed-nav-wrap");'
			. 'if(_nw)_nw.style.background=_bg;'
			. '}'
			. 'if(_closed)_closed.style.pointerEvents="none";'
			. '/* === PANNEAU KEYWORDS === */'
			. '_kwPanel=document.createElement("div");'
			. '_kwPanel.id="aviEmbedKwPanel";'
			. '_kwPanel.className="avi-kw-panel";'
			. '_kwPanel.style.display="none";'
			. '/* #SprintL2-L2.2-kw-crud — chargement REST */'
			. 'var _kwData=[];'
			. 'var _kwLoaded=false;'
			. 'function _kwLoad(){'
			. '  if(_kwLoaded){'
			. '    _kwRender();'
			. '    if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. '    return;'
			. '  }'
			. '  fetch(window.location.origin+"/wp-json/avision/v1/embed/keywords"'
			. '    +"?key_id="+encodeURIComponent(window.aviEmbedKeyId||"")'
			. '    +"&profile_id="+(window.aviEmbedProfileId||""),'
			. '    {headers:{"X-Embed-Token":window.aviEmbedToken||""}})'
			. '  .then(function(r){return r.json();})'
			. '  .then(function(d){'
			. '    if(d.success){'
			. '      _kwData=(d.keywords||[]).map(function(k){'
			. '        return {'
			. '          id:k.id,'
			. '          keyword:k.keyword,'
			. '          target_city:k.target_city||"",'
			. '          current_rank:k.current_rank!==null&&k.current_rank!==undefined?parseInt(k.current_rank,10):null,'
			. '          previous_rank:k.previous_rank!==null&&k.previous_rank!==undefined?parseInt(k.previous_rank,10):null,'
			. '          best_rank:k.best_rank!==null&&k.best_rank!==undefined?parseInt(k.best_rank,10):null,'
			. '          scan_status:k.scan_status||"pending",'
			. '          last_scan_at:k.last_scan_at||null,'
			. '          grid_size:null,'
			. '          scan_type:null,'
			. '          scan_group_id:null,'
			. '          danger:false,'
			. '          is_strategic:k.is_strategic?1:0'
			. '        };'
			. '      });'
			. '      _kwLoaded=true;'
			. '    }'
			. '    _kwRender();'
			. '    if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. '  })'
			. '  .catch(function(){'
			. '    _kwRender();'
			. '    if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. '  });'
			. '}'
			. 'var _kwFilter="all";'
			. 'var _kwGridFilter="all";'
			. 'var _kwSort={col:"keyword",asc:true};'
			. 'var _kwSearch="";'
			. 'function _kwMakeColgroup(){'
			. '  var cg=document.createElement("colgroup");'
			. '  var widths=["28%","8%","7%","8%","10%","14%","9%","16%"];'
			. '  widths.forEach(function(w){'
			. '    var col=document.createElement("col");'
			. '    col.style.width=w;cg.appendChild(col);'
			. '  });'
			. '  return cg;'
			. '}'
			. 'function _renderKwRow(k,isChild){'
			. '  var tr=document.createElement("tr");'
			. '  if(isChild)tr.className="avi-kw-child-row";'
			. '  var td1=document.createElement("td");'
			. '  td1.innerHTML="<strong>"+k.keyword+"</strong>"'
			. '    +(k.target_city?"<br><span style=\\"color:#94a3b8;font-size:11px;\\">"+k.target_city+"</span>":"");'
			. '  var td2=document.createElement("td");'
			. '  td2.innerHTML=k.current_rank?"<span class=\\"avi-kw-rank\\">#"+k.current_rank+"</span>":"<span class=\\"avi-kw-rank-none\\">—</span>";'
			. '  var td3=document.createElement("td");'
			. '  td3.innerHTML=k.best_rank?"#"+k.best_rank:"<span class=\\"avi-kw-rank-none\\">—</span>";'
			. '  var td4=document.createElement("td");'
			. '  if(k.grid_size){'
			. '    var gc=k.grid_size.replace(/x/,"x");'
			. '    td4.innerHTML="<span class=\\"avi-kw-grid-badge avi-kw-grid-"+gc+"\\">"+k.grid_size+"</span>";'
			. '  }else{td4.innerHTML="<span class=\\"avi-kw-grid-badge avi-kw-grid-none\\">—</span>";}'
			. '  var td5=document.createElement("td");'
			. '  var sc=k.scan_status==="scanned"?"scanned":"pending";'
			. '  td5.innerHTML="<span class=\\"avi-kw-badge avi-kw-badge-"+sc+"\\">"+(sc==="scanned"?_t.scanned:_t.pending)+"</span>";'
			. '  var td6=document.createElement("td");'
			. '  var scanInfo=k.last_scan_at||_t.never;'
			. '  var scanTypeLabel="";'
			. '  if(k.scan_type==="solo")scanTypeLabel="<br><span style=\\"font-size:10px;color:#7c3aed;\\">"+_t.kw_solo_label+"</span>";'
			. '  else if(k.scan_type==="multi")scanTypeLabel="<br><span style=\\"font-size:10px;color:#0284c7;\\">"+_t.kw_multi_label+"</span>";'
			. '  td6.innerHTML=scanInfo+scanTypeLabel;'
			. '  var td7=document.createElement("td");'
			. '  td7.innerHTML=k.danger?"<span class=\\"avi-kw-badge avi-kw-badge-danger\\">"+_t.threat+"</span>":"<span style=\\"color:#94a3b8;\\">—</span>";'
			. '  var td8=document.createElement("td");'
			. '  td8.style.cssText="display:flex;gap:4px;align-items:center;";'
			. '  var scanBtn=document.createElement("button");'
			. '  scanBtn.type="button";scanBtn.className="avi-kw-action-btn";'
			. '  scanBtn.textContent="🔍";scanBtn.title=_t.scan_kw;'
			. '  scanBtn.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '  var delBtn=document.createElement("button");'
			. '  delBtn.type="button";delBtn.className="avi-kw-action-btn delete";'
			. '  delBtn.textContent="🗑️";delBtn.title=_t.delete;'
			. '  delBtn.addEventListener("click",function(){'
			. '    fetch(window.location.origin+"/wp-json/avision/v1/embed/keywords/"+k.id,{'
			. '      method:"DELETE",'
			. '      headers:{'
			. '        "Content-Type":"application/json",'
			. '        "X-Embed-Token":window.aviEmbedToken||""'
			. '      },'
			. '      body:JSON.stringify({'
			. '        key_id:window.aviEmbedKeyId,'
			. '        profile_id:window.aviEmbedProfileId'
			. '      })'
			. '    })'
			. '    .then(function(r){return r.json().then(function(d){return {ok:r.ok,d:d};});})'
			. '    .then(function(res){'
			. '      if(res.ok&&res.d.success){'
			. '        _kwData=_kwData.filter(function(x){return x.id!==k.id;});'
			. '        _kwRenderTable();'
			. '      }'
			. '    });'
			. '  });'
			. '  td8.appendChild(scanBtn);td8.appendChild(delBtn);'
			. '  tr.appendChild(td1);tr.appendChild(td2);tr.appendChild(td3);'
			. '  tr.appendChild(td4);tr.appendChild(td5);tr.appendChild(td6);'
			. '  tr.appendChild(td7);tr.appendChild(td8);'
			. '  return tr;'
			. '}'
			. 'function _renderGroup(groupId,items,container){'
			. '  var firstItem=items[0];'
			. '  var isMulti=items.length>1;'
			. '  var groupDate=firstItem.last_scan_at||"";'
			. '  var groupGrid=firstItem.grid_size||"";'
			. '  var gridClass=groupGrid?"avi-kw-grid-"+groupGrid.replace("x","x"):"avi-kw-grid-none";'
			. '  var gh=document.createElement("div");'
			. '  gh.className="avi-kw-group-header";'
			. '  gh.setAttribute("data-group",groupId);'
			. '  var arrow=document.createElement("span");'
			. '  arrow.className="avi-kw-group-arrow open";'
			. '  arrow.textContent="▶";'
			. '  var gLabel=document.createElement("span");'
			. '  gLabel.innerHTML=groupDate+" · "'
			. '    +"<span class=\\"avi-kw-grid-badge "+gridClass+"\\">"+(groupGrid||"—")+"</span>"'
			. '    +" · "+(isMulti?_t.kw_group_multi_prefix+items.length+_t.kw_group_keywords_suffix:_t.kw_group_solo);'
			. '  gh.appendChild(arrow);gh.appendChild(gLabel);'
			. '  var gb=document.createElement("div");'
			. '  gb.className="avi-kw-group-body";'
			. '  gb.setAttribute("data-group-body",groupId);'
			. '  var gtbl=document.createElement("table");'
			. '  gtbl.className="avi-kw-table";gtbl.style.marginBottom="0";'
			. '  gtbl.appendChild(_kwMakeColgroup());'
			. '  var gtbody=document.createElement("tbody");'
			. '  items.forEach(function(k){gtbody.appendChild(_renderKwRow(k,true));});'
			. '  gtbl.appendChild(gtbody);gb.appendChild(gtbl);'
			. '  gh.addEventListener("click",function(){'
			. '    var isOpen=gb.classList.contains("collapsed");'
			. '    gb.classList.toggle("collapsed",!isOpen);'
			. '    arrow.classList.toggle("open",isOpen);'
			. '  });'
			. '  container.appendChild(gh);container.appendChild(gb);'
			. '}'
			. 'function _kwRenderTable(){'
			. '  var zone=document.getElementById("aviKwTableZone");'
			. '  if(!zone)return;'
			. '  zone.innerHTML="";'
			. '  /* Filtres */'
			. '  var fz=document.createElement("div");fz.className="avi-kw-filters";'
			. '  var filters=['
			. '    ["all",_t.filter_all],'
			. '    ["scanned",_t.scanned],'
			. '    ["pending",_t.pending],'
			. '    ["danger",_t.filter_danger],'
			. '    ["solo",_t.filter_solo_scan],'
			. '    ["multi",_t.filter_multi_scan],'
			. '    ["az",_t.filter_az]'
			. '  ];'
			. '  filters.forEach(function(f){'
			. '    var fb=document.createElement("button");'
			. '    fb.type="button";fb.className="avi-kw-filter-btn"+(f[0]===_kwFilter?" active":"");'
			. '    fb.textContent=f[1];'
			. '    fb.addEventListener("click",function(){_kwFilter=f[0];_kwRenderTable();});'
			. '    fz.appendChild(fb);'
			. '  });'
			. '  var gf=document.createElement("select");'
			. '  gf.style.cssText="border:1px solid #e2e8f0;border-radius:20px;'
			. 'color:#64748b;font-size:11px;font-weight:500;padding:4px 10px;'
			. 'background:#fff;cursor:pointer;outline:none;margin-left:4px;";'
			. '  var gfOpts=[["all",_t.filter_all_grids],["3x3","3×3"],["5x5","5×5"],'
			. '["7x7","7×7"],["9x9","9×9"],["11x11","11×11"],["13x13","13×13"],'
			. '["15x15","15×15"],["21x21","21×21"]];'
			. '  gfOpts.forEach(function(o){'
			. '    var opt=document.createElement("option");'
			. '    opt.value=o[0];opt.textContent=o[1];'
			. '    if(o[0]===_kwGridFilter)opt.selected=true;'
			. '    gf.appendChild(opt);'
			. '  });'
			. '  gf.addEventListener("change",function(){'
			. '    _kwGridFilter=this.value;_kwRenderTable();'
			. '  });'
			. '  fz.appendChild(gf);'
			. '  zone.appendChild(fz);'
			. '  /* Filtrage + tri */'
			. '  var rows=_kwData.filter(function(k){'
			. '    if(_kwSearch&&k.keyword.toLowerCase().indexOf(_kwSearch.toLowerCase())<0)return false;'
			. '    if(_kwGridFilter!=="all"&&k.grid_size!==_kwGridFilter)return false;'
			. '    if(_kwFilter==="scanned")return k.scan_status==="scanned";'
			. '    if(_kwFilter==="pending")return k.scan_status==="pending";'
			. '    if(_kwFilter==="danger")return k.danger;'
			. '    if(_kwFilter==="solo")return k.scan_type==="solo";'
			. '    if(_kwFilter==="multi")return k.scan_type==="multi";'
			. '    return true;'
			. '  });'
			. '  if(_kwFilter==="az"){'
			. '    rows.sort(function(a,b){return a.keyword.localeCompare(b.keyword);});'
			. '  }else{'
			. '    rows.sort(function(a,b){'
			. '      var va=a[_kwSort.col],vb=b[_kwSort.col];'
			. '      if(va===null||va===undefined)va=_kwSort.asc?Infinity:-Infinity;'
			. '      if(vb===null||vb===undefined)vb=_kwSort.asc?Infinity:-Infinity;'
			. '      return _kwSort.asc?(va>vb?1:-1):(va<vb?1:-1);'
			. '    });'
			. '  }'
			. '  var _groups={};'
			. '  var _noGroup=[];'
			. '  rows.forEach(function(k){'
			. '    if(k.scan_group_id){'
			. '      if(!_groups[k.scan_group_id])_groups[k.scan_group_id]=[];'
			. '      _groups[k.scan_group_id].push(k);'
			. '    }else{'
			. '      _noGroup.push(k);'
			. '    }'
			. '  });'
			. '  var tableZone=document.createElement("div");'
			. '  if(rows.length===0){'
			. '    var empty=document.createElement("div");'
			. '    empty.className="avi-kw-empty";'
			. '    empty.innerHTML="<div style=\\"font-size:32px;margin-bottom:8px;\\">🔑</div><div>"+_t.no_kw+"</div>";'
			. '    tableZone.appendChild(empty);'
			. '  }else{'
			. '    var hcols=['
			. '      ["keyword",_t.col_keyword,_t.tip_col_keyword],'
			. '      ["current_rank",_t.col_rank,_t.tip_col_rank],'
			. '      ["best_rank",_t.col_best,_t.tip_col_best],'
			. '      ["grid_size",_t.col_grid,_t.tip_col_grid],'
			. '      ["scan_status",_t.col_status,_t.tip_col_status],'
			. '      ["last_scan_at",_t.col_scan,_t.tip_col_scan],'
			. '      ["danger",_t.col_threat,_t.tip_col_threat]'
			. '    ];'
			. '    var tbl=document.createElement("table");tbl.className="avi-kw-table";'
			. '    tbl.appendChild(_kwMakeColgroup());'
			. '    var thead=document.createElement("thead");'
			. '    var hr=document.createElement("tr");'
			. '    hcols.forEach(function(h){'
			. '      var th=document.createElement("th");'
			. '      th.innerHTML=h[1]+(_kwSort.col===h[0]?(_kwSort.asc?" ↑":" ↓"):"")'
			. '        +(h[2]?"<span title=\\""+h[2]+"\\" style=\\"margin-left:4px;color:#94a3b8;cursor:help;font-size:10px;\\">ℹ</span>":"");'
			. '      th.title=h[2]||"";'
			. '      th.addEventListener("click",function(){'
			. '        if(_kwSort.col===h[0])_kwSort.asc=!_kwSort.asc;'
			. '        else{_kwSort.col=h[0];_kwSort.asc=true;}'
			. '        _kwRenderTable();'
			. '      });'
			. '      hr.appendChild(th);'
			. '    });'
			. '    var tha=document.createElement("th");tha.textContent=_t.actions;hr.appendChild(tha);'
			. '    thead.appendChild(hr);tbl.appendChild(thead);'
			. '    tableZone.appendChild(tbl);'
			. '    Object.keys(_groups).forEach(function(gid){'
			. '      _renderGroup(gid,_groups[gid],tableZone);'
			. '    });'
			. '    _noGroup.forEach(function(k){'
			. '      var gh2=document.createElement("div");'
			. '      gh2.className="avi-kw-group-header";'
			. '      gh2.style.cursor="default";'
			. '      var label2="";'
			. '      if(k.scan_status==="scanned"&&k.last_scan_at){'
			. '        var gc2=k.grid_size?k.grid_size.replace(/x/,"x"):"";'
			. '        var gridBadge2=k.grid_size'
			. '          ?"<span class=\\"avi-kw-grid-badge avi-kw-grid-"+gc2+"\\">"+k.grid_size+"</span>"'
			. '          :"";'
			. '        label2=k.last_scan_at+" · "+gridBadge2+" · "+_t.kw_solo_label;'
			. '      }else{'
			. '        label2="<span style=\\"color:#94a3b8;\\">"+_t.kw_not_scanned_yet+"</span>";'
			. '      }'
			. '      gh2.innerHTML="<span style=\\"width:16px;display:inline-block;\\"></span>"+label2;'
			. '      var gb2=document.createElement("div");'
			. '      gb2.className="avi-kw-group-body";'
			. '      var gtbl2=document.createElement("table");'
			. '      gtbl2.className="avi-kw-table";'
			. '      gtbl2.appendChild(_kwMakeColgroup());'
			. '      var gtbody2=document.createElement("tbody");'
			. '      gtbody2.appendChild(_renderKwRow(k,true));'
			. '      gtbl2.appendChild(gtbody2);'
			. '      gb2.appendChild(gtbl2);'
			. '      tableZone.appendChild(gh2);'
			. '      tableZone.appendChild(gb2);'
			. '    });'
			. '  }'
			. '  zone.appendChild(tableZone);'
			. '}'
			. 'function _kwRender(){'
			. '  _kwRenderTable();'
			. '}'
			. 'var kwClose=document.createElement("button");'
			. 'kwClose.type="button";'
			. 'kwClose.style.cssText="position:absolute;top:12px;right:16px;background:none;border:none;font-size:20px;color:#94a3b8;cursor:pointer;line-height:1;padding:4px;z-index:20;";'
			. 'kwClose.textContent="×";'
			. 'kwClose.title=_t.close;'
			. 'kwClose.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_kwPanel.appendChild(kwClose);'
			. 'var _kwHeader=document.createElement("div");'
			. '_kwHeader.className="avi-kw-header";'
			. '_kwHeader.innerHTML='
			. '\'<div class="avi-kw-header-title">\\uD83D\\uDD11 \'+(_t.kw_panel_title||"")+\'</div>\''
			. '+\'<div class="avi-kw-header-sub">\'+(_t.kw_panel_sub||"")+\'</div>\';'
			. '_kwPanel.insertBefore(_kwHeader,_kwPanel.firstChild);'
			. 'var tb=document.createElement("div");tb.className="avi-kw-toolbar";'
			. 'var si=document.createElement("input");'
			. 'si.type="text";si.className="avi-kw-search";'
			. 'si.placeholder=_t.search_kw;'
			. 'si.value=_kwSearch;'
			. 'si.addEventListener("input",function(){_kwSearch=this.value;_kwRenderTable();});'
			. 'var ab=document.createElement("button");'
			. 'ab.type="button";ab.className="avi-kw-add-btn";'
			. 'ab.textContent=_t.add_kw;'
			. 'ab.addEventListener("click",function(){'
			. '  var f=document.getElementById("aviKwAddForm");'
			. '  if(f)f.classList.toggle("open");'
			. '});'
			. 'var ib=document.createElement("button");'
			. 'ib.type="button";'
			. 'ib.className="avi-kw-add-btn";'
			. 'ib.style.background="#0f172a";'
			. 'ib.textContent=_t.import_kw;'
			. 'ib.title=_t.import_kw_tip;'
			. 'ib.addEventListener("click",function(){'
			. '  var f=document.getElementById("aviKwImportForm");'
			. '  if(f)f.classList.toggle("open");'
			. '});'
			. 'var expWrap=document.createElement("div");'
			. 'expWrap.style.cssText="position:relative;display:inline-block;";'
			. 'var expBtn=document.createElement("button");'
			. 'expBtn.type="button";expBtn.className="avi-kw-add-btn";'
			. 'expBtn.style.background="#0f172a";'
			. 'expBtn.textContent=_t.export_kw;'
			. 'var expDropOpen=false;'
			. 'var expDrop=document.createElement("div");'
			. 'expDrop.style.cssText="position:fixed;background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:8px;box-shadow:0 4px 16px rgba(0,0,0,.15);'
			. 'min-width:140px;z-index:2147483647;display:none;";'
			. 'var csvOpt=document.createElement("button");'
			. 'csvOpt.type="button";'
			. 'csvOpt.style.cssText="background:none;border:none;color:#1e293b;cursor:pointer;'
			. 'display:block;font-size:13px;padding:10px 16px;text-align:left;width:100%;";'
			. 'csvOpt.textContent=_t.export_csv;'
			. 'var pdfOpt=document.createElement("button");'
			. 'pdfOpt.type="button";'
			. 'pdfOpt.style.cssText=csvOpt.style.cssText;'
			. 'pdfOpt.textContent=_t.export_pdf;'
			. 'expDrop.appendChild(csvOpt);expDrop.appendChild(pdfOpt);'
			. 'document.body.appendChild(expDrop);'
			. 'expBtn.addEventListener("click",function(e){'
			. '  e.stopPropagation();'
			. '  expDropOpen=!expDropOpen;'
			. '  if(expDropOpen){'
			. '    var r=expBtn.getBoundingClientRect();'
			. '    expDrop.style.top=(r.bottom+4)+"px";'
			. '    expDrop.style.left=r.left+"px";'
			. '    expDrop.style.display="block";'
			. '  }else{expDrop.style.display="none";}'
			. '});'
			. 'document.addEventListener("click",function(e){'
			. '  if(!expDrop.contains(e.target)&&e.target!==expBtn){'
			. '    expDropOpen=false;expDrop.style.display="none";'
			. '  }'
			. '});'
			. 'csvOpt.addEventListener("click",function(){'
			. '  expDrop.style.display="none";expDropOpen=false;'
			. '  var cols=[_t.col_keyword,_t.export_col_city,_t.col_rank,_t.col_best,_t.col_grid,_t.col_status,_t.col_scan,_t.export_col_scan_type,_t.col_threat];'
			. '  var rows2=[cols.join(",")];'
			. '  _kwData.forEach(function(k){'
			. '    rows2.push(['
			. '      "\\""+k.keyword+"\\"","\\""+(k.target_city||"")+"\\"",'
			. '      k.current_rank||"",k.best_rank||"",k.grid_size||"",'
			. '      k.scan_status,k.last_scan_at||_t.never,k.scan_type||"",'
			. '      k.danger?_t.export_yes:_t.export_no'
			. '    ].join(","));'
			. '  });'
			. '  var blob=new Blob([rows2.join("\\n")],{type:"text/csv;charset=utf-8;"});'
			. '  var url=URL.createObjectURL(blob);'
			. '  var a=document.createElement("a");'
			. '  a.href=url;a.download="keywords-export.csv";'
			. '  document.body.appendChild(a);a.click();'
			. '  document.body.removeChild(a);URL.revokeObjectURL(url);'
			. '});'
			. 'pdfOpt.addEventListener("click",function(){'
			. '  expDrop.style.display="none";expDropOpen=false;'
			. '  var logoHtml=window.aviEmbedLogoUrl'
			. '    ?("<img src=\\""+window.aviEmbedLogoUrl+"\\" style=\\"height:40px;margin-bottom:8px;\\">")'
			. '    :"";'
			. '  var brand=window.aviEmbedWhiteLabel||"Avision";'
			. '  var tableRows=_kwData.map(function(k){'
			. '    return "<tr><td>"+k.keyword+"</td><td>"+(k.target_city||"—")+"</td>"'
			. '      +"<td>"+(k.current_rank?"#"+k.current_rank:"—")+"</td>"'
			. '      +"<td>"+(k.best_rank?"#"+k.best_rank:"—")+"</td>"'
			. '      +"<td>"+(k.grid_size||"—")+"</td>"'
			. '      +"<td>"+k.scan_status+"</td>"'
			. '      +"<td>"+(k.last_scan_at||_t.never)+"</td>"'
			. '      +"<td>"+(k.scan_type||"—")+"</td>"'
			. '      +"<td>"+(k.danger?_t.export_danger_yes:_t.export_no)+"</td></tr>";'
			. '  }).join("");'
			. '  var win=window.open("","_blank");'
			. '  win.document.write("<html><head><title>"+brand+" — "+_t.kw_report_title+"</title>"'
			. '    +"<style>body{font-family:Inter,sans-serif;padding:32px;color:#1e293b;}"'
			. '    +"h1{font-size:20px;margin-bottom:4px;}p{color:#64748b;font-size:13px;}"'
			. '    +"table{width:100%;border-collapse:collapse;margin-top:16px;font-size:12px;}"'
			. '    +"th{background:#f1f5f9;padding:8px;text-align:left;border-bottom:2px solid #e2e8f0;}"'
			. '    +"td{padding:7px 8px;border-bottom:1px solid #f1f5f9;}"'
			. '    +"tr:nth-child(even)td{background:#fafafa;}"'
			. '    +"@media print{body{padding:0;}}"'
			. '    +"</style></head><body>"'
			. '    +logoHtml'
			. '    +"<h1>"+brand+" — "+_t.kw_report_title+"</h1>"'
			. '    +"<p>"+_t.kw_report_generated+" "+new Date().toLocaleDateString()+" · "+_kwData.length+_t.kw_report_keywords_suffix+"</p>"'
			. '    +"<table><thead><tr>"'
			. '    +"<th>"+_t.col_keyword+"</th><th>"+_t.export_col_city+"</th><th>"+_t.col_rank+"</th><th>"+_t.col_best+"</th>"'
			. '    +"<th>"+_t.col_grid+"</th><th>"+_t.col_status+"</th><th>"+_t.col_scan+"</th><th>"+_t.export_col_scan_type+"</th><th>"+_t.col_threat+"</th>"'
			. '    +"</tr></thead><tbody>"+tableRows+"</tbody></table>"'
			. '    +"</body></html>");'
			. '  win.document.close();'
			. '  win.focus();'
			. '  setTimeout(function(){win.print();},500);'
			. '});'
			. 'expWrap.appendChild(expBtn);'
			. 'tb.appendChild(si);tb.appendChild(ab);tb.appendChild(ib);tb.appendChild(expWrap);'
			. '_kwPanel.appendChild(tb);'
			. 'var af=document.createElement("div");'
			. 'af.className="avi-kw-add-form";af.id="aviKwAddForm";'
			. 'var ai=document.createElement("input");'
			. 'ai.type="text";ai.className="avi-kw-add-input";'
			. 'ai.placeholder=_t.add_kw_ph;'
			. 'var act=document.createElement("div");act.className="avi-kw-add-actions";'
			. 'var cb=document.createElement("button");'
			. 'cb.type="button";cb.className="avi-kw-cancel-btn";cb.textContent=_t.cancel;'
			. 'cb.addEventListener("click",function(){af.classList.remove("open");ai.value="";});'
			. 'var sb=document.createElement("button");'
			. 'sb.type="button";sb.className="avi-kw-add-btn";sb.textContent=_t.save;'
			. 'sb.addEventListener("click",function(){'
			. '  var kw=ai.value.trim();'
			. '  if(!kw)return;'
			. '  fetch(window.location.origin+"/wp-json/avision/v1/embed/keywords",{'
			. '    method:"POST",'
			. '    headers:{'
			. '      "Content-Type":"application/json",'
			. '      "X-Embed-Token":window.aviEmbedToken||""'
			. '    },'
			. '    body:JSON.stringify({'
			. '      key_id:window.aviEmbedKeyId,'
			. '      profile_id:window.aviEmbedProfileId,'
			. '      keyword:kw,'
			. '      target_city:""'
			. '    })'
			. '  })'
			. '  .then(function(r){return r.json().then(function(d){return {ok:r.ok,d:d};});})'
			. '  .then(function(res){'
			. '    if(res.ok&&res.d.success){'
			. '      _kwData.push({'
			. '        id:res.d.id,'
			. '        keyword:res.d.keyword,'
			. '        target_city:res.d.target_city||"",'
			. '        current_rank:null,'
			. '        previous_rank:null,'
			. '        best_rank:null,'
			. '        scan_status:"pending",'
			. '        last_scan_at:null,'
			. '        grid_size:null,'
			. '        scan_type:null,'
			. '        scan_group_id:null,'
			. '        is_strategic:0,'
			. '        danger:false'
			. '      });'
			. '      ai.value="";af.classList.remove("open");'
			. '      _kwRenderTable();'
			. '    }else{'
			. '      alert((res.d&&res.d.message)||_t.err_generic||"Error");'
			. '    }'
			. '  })'
			. '  .catch(function(){alert(_t.err_network||"Error");});'
			. '});'
			. 'act.appendChild(cb);act.appendChild(sb);'
			. 'af.appendChild(ai);af.appendChild(act);'
			. '_kwPanel.appendChild(af);'
			. 'var impF=document.createElement("div");'
			. 'impF.className="avi-kw-add-form";impF.id="aviKwImportForm";'
			. 'var impLabel=document.createElement("p");'
			. 'impLabel.style.cssText="font-size:12px;color:#64748b;margin:0 0 8px;";'
			. 'impLabel.textContent=_t.import_label;'
			. 'var impTa=document.createElement("textarea");'
			. 'impTa.style.cssText="border:1px solid #e2e8f0;border-radius:6px;font-size:12px;padding:8px;width:100%;min-height:80px;box-sizing:border-box;resize:vertical;outline:none;font-family:inherit;";'
			. 'impTa.placeholder=_t.import_kw_ph;'
			. 'var impAct=document.createElement("div");impAct.className="avi-kw-add-actions";'
			. 'var impCb=document.createElement("button");'
			. 'impCb.type="button";impCb.className="avi-kw-cancel-btn";impCb.textContent=_t.cancel;'
			. 'impCb.addEventListener("click",function(){impF.classList.remove("open");impTa.value="";});'
			. 'var impSb=document.createElement("button");'
			. 'impSb.type="button";impSb.className="avi-kw-add-btn";impSb.textContent=_t.import_btn;'
			. 'impSb.addEventListener("click",function(){'
			. '  var lines=impTa.value.split(/[\\n,]+/)'
			. '    .map(function(s){return s.trim();})'
			. '    .filter(Boolean);'
			. '  if(!lines.length)return;'
			. '  var existing=_kwData.map(function(x){'
			. '    return x.keyword.toLowerCase();'
			. '  });'
			. '  var toAdd=lines.filter(function(kw){'
			. '    return existing.indexOf(kw.toLowerCase())===-1;'
			. '  });'
			. '  if(!toAdd.length){'
			. '    impTa.value="";impF.classList.remove("open");return;'
			. '  }'
			. '  var idx=0;'
			. '  function _nextImport(){'
			. '    if(idx>=toAdd.length){'
			. '      impTa.value="";impF.classList.remove("open");'
			. '      _kwRenderTable();return;'
			. '    }'
			. '    var kw=toAdd[idx++];'
			. '    fetch(window.location.origin'
			. '      +"/wp-json/avision/v1/embed/keywords",{'
			. '      method:"POST",'
			. '      headers:{'
			. '        "Content-Type":"application/json",'
			. '        "X-Embed-Token":window.aviEmbedToken||""'
			. '      },'
			. '      body:JSON.stringify({'
			. '        key_id:window.aviEmbedKeyId,'
			. '        profile_id:window.aviEmbedProfileId,'
			. '        keyword:kw,'
			. '        target_city:""'
			. '      })'
			. '    }).then(function(r){return r.json();})'
			. '    .then(function(d){'
			. '      if(d&&d.success&&d.id){'
			. '        _kwData.push({'
			. '          id:d.id,keyword:d.keyword,'
			. '          target_city:d.target_city||"",'
			. '          current_rank:null,previous_rank:null,'
			. '          best_rank:null,scan_status:"pending",'
			. '          last_scan_at:null,is_strategic:0,'
			. '          danger:false'
			. '        });'
			. '      }'
			. '      _nextImport();'
			. '    })'
			. '    .catch(function(){_nextImport();});'
			. '  }'
			. '  _nextImport();'
			. '});'
			. 'impAct.appendChild(impCb);impAct.appendChild(impSb);'
			. 'impF.appendChild(impLabel);impF.appendChild(impTa);impF.appendChild(impAct);'
			. '_kwPanel.appendChild(impF);'
			. 'var _kwTableZone=document.createElement("div");'
			. '_kwTableZone.id="aviKwTableZone";'
			. '_kwPanel.appendChild(_kwTableZone);'
			. '_kwRender();'
			. 'var _kwWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_kwWrap.appendChild(_kwPanel);'
			. 'function _scoreColor(s){'
			. 'if(s<=30)return{color:"#dc2626",label:_t.score_urgent};'
			. 'if(s<=50)return{color:"#ea580c",label:_t.score_improve};'
			. 'if(s<=70)return{color:"#ca8a04",label:_t.score_getting};'
			. 'if(s<=85)return{color:"#16a34a",label:_t.score_good};'
			. 'return{color:"#7c3aed",label:_t.score_excellent};'
			. '}'
			. 'function _scoreRelDate(dt){'
			. 'if(!dt)return _t.unknown;'
			. 'var d=new Date(dt),now=new Date();'
			. 'var diff=Math.floor((now-d)/86400000);'
			. 'if(diff===0)return _t.today;if(diff===1)return _t.yesterday;'
			. 'if(diff<7)return diff+_t.rel_d_ago;'
			. 'if(diff<30)return Math.floor(diff/7)+_t.rel_w_ago;'
			. 'return Math.floor(diff/30)+_t.rel_mo_ago;'
			. '}'
			. 'function _scoreGaugeSvg(score,color){'
			. 'var pct=Math.min(Math.max(score,0),100)/100;'
			. 'var cx=100,cy=100,r=75;'
			. 'var bgPath="M "+(cx-r)+" "+cy+" A "+r+" "+r+" 0 0 1 "+(cx+r)+" "+cy;'
			. '/* Jauge : part de gauche (180°) vers droite (0°) */'
			. 'var startAngle=Math.PI;'
			. 'var endAngle=Math.PI*(1-pct);'
			. 'var x1=cx+r*Math.cos(startAngle);'
			. 'var y1=cy-r*Math.sin(startAngle);'
			. 'var x2=cx+r*Math.cos(endAngle);'
			. 'var y2=cy-r*Math.sin(endAngle);'
			. 'var largeArc=0;'
			. 'var colorPath="M "+x1.toFixed(2)+" "+y1.toFixed(2)'
			. '+" A "+r+" "+r+" 0 "+largeArc+" 1 "'
			. '+x2.toFixed(2)+" "+y2.toFixed(2);'
			. 'return \'<svg class="avi-score-gauge-svg"\''
			. '+\' width="200" height="110" viewBox="0 0 200 110">\''
			. '+\'<path d="\'+bgPath+\'"\''
			. '+\' fill="none" stroke="#e2e8f0"\''
			. '+\' stroke-width="14" stroke-linecap="round"/>\''
			. '+(pct>0'
			. '?(\'<path d="\'+colorPath+\'"\''
			. '+\' fill="none" stroke="\'+color+\'"\''
			. '+\' stroke-width="14" stroke-linecap="round"/>\')'
			. ':"")'
			. '+\'</svg>\';'
			. '}'
			. 'var _additionalCats=[];'
			. 'function _closeScoreEditModal(){'
			. 'if(_scoreEditModal){'
			. '_scoreEditModal.style.display="none";'
			. '_scoreEditModal.innerHTML="";'
			. '}'
			. '}'
			. 'function _refreshAdditionalCatsUI(){'
			. 'var wrap=document.getElementById("aviScoreCatAdditional");'
			. 'if(!wrap)return;'
			. 'wrap.innerHTML="";'
			. '_additionalCats.forEach(function(cat,idx){'
			. 'var tag=document.createElement("span");'
			. 'tag.className="avi-score-cat-tag";'
			. 'tag.innerHTML=cat.displayName'
			. '+"<span class=\\"avi-score-cat-tag-remove\\" data-idx=\\""+idx+"\\">\u00d7</span>";'
			. 'tag.querySelector(".avi-score-cat-tag-remove").addEventListener("click",function(){'
			. '_additionalCats.splice(idx,1);'
			. '_refreshAdditionalCatsUI();'
			. '});'
			. 'wrap.appendChild(tag);'
			. '});'
			. '}'
			. 'function _renderAdditionalCats(cats){'
			. '_additionalCats=cats.map(function(c){'
			. 'return {name:c.name||"",displayName:c.displayName||c.name||""};'
			. '});'
			. '_refreshAdditionalCatsUI();'
			. '}'
			. 'function _addAdditionalCat(cat){'
			. 'if(_additionalCats.length>=9)return;'
			. 'var exists=_additionalCats.some(function(c){return c.name===cat.name;});'
			. 'if(!exists){_additionalCats.push(cat);_refreshAdditionalCatsUI();}'
			. '}'
			. '_scorePanel=document.createElement("div");'
			. '_scorePanel.className="avi-score-panel";'
			. '_scorePanel.id="aviEmbedScorePanel";'
			. 'function _scoreRender(){'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var score=sd.score||0;'
			. 'if(window._aviGuardianAlerts){'
			. 'var _gPenaltyMap={title:0,phoneNumbers:4,categories:1,regularHours:3,websiteUri:5,openInfo:0,storefrontAddress:1,description:2,specialHours:1,serviceArea:1};'
			. 'var _gPenalty=0;'
			. 'window._aviGuardianAlerts.forEach(function(a){'
			. 'if(parseInt(a.is_read)===0&&_gPenaltyMap.hasOwnProperty(a.alert_type)){'
			. '_gPenalty+=_gPenaltyMap[a.alert_type];'
			. '}'
			. '});'
			. 'score=Math.max(0,score-_gPenalty);'
			. 'if(window._aviCitStale)score=Math.max(0,score-2);'
			. '}'
			. 'var tier=_scoreColor(score);'
			. 'var syncLabel=_scoreRelDate(sd.synced_at);'
			. 'var criteria=['
			. '{key:"has_name",label:_t.crit_name,pts:_t.pts_0,icon:"\\uD83C\\uDFE2",field:"name",group:"nap"},'
			. '{key:"has_address",label:_t.crit_address,pts:_t.pts_1,icon:"📍",field:"address",group:"nap"},'
			. '{key:"has_phone",label:_t.crit_phone,pts:_t.pts_4,icon:"📞",field:"phone",group:"nap"},'
			. '{key:"has_category",label:_t.crit_category,pts:_t.pts_1,icon:"📂",field:"categories",group:"nap"},'
			. '{key:"has_description",label:_t.crit_description,pts:_t.pts_2,icon:"📝",field:"description",group:"nap"},'
			. '{key:"is_open",label:(_t.crit_open_status||"Business status"),pts:_t.pts_0,icon:"\ud83d\udfe2",field:"openInfo",group:"nap"},'
			. '{key:"has_special_hours",label:(_t.crit_special_hours||"Special hours"),pts:(_t.pts_1||"+1 pt"),icon:"\ud83d\udcc5",field:"specialHours",group:"nap"},'
			. '{key:"has_service_area",label:(_t.crit_service_area||"Service area"),pts:(_t.pts_1||"+1 pt"),icon:"\ud83d\uddfa\ufe0f",field:"serviceArea",group:"nap"},'
			. '{key:"has_website",label:_t.crit_website,pts:_t.pts_5,icon:"🌐",field:"website",group:"online"},'
			. '{key:"has_hours",label:_t.crit_hours,pts:_t.pts_3,icon:"🕐",field:"hours",group:"online"}'
			. '];'
			. '_scorePanel.innerHTML="";'
			. 'var sc=document.createElement("button");'
			. 'sc.type="button";sc.className="avi-score-close";sc.textContent="×";'
			. 'sc.style.cssText="position:absolute;top:12px;right:16px;'
			. 'background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;";'
			. 'sc.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_scorePanel.appendChild(sc);'
			. 'var inner=document.createElement("div");'
			. 'inner.className="avi-score-inner";'
			. 'var _verif=sd.verification_state||"unverified";'
			. 'var _verifLbl=_verif==="verified"?(_t.verified||"")'
			. ':_verif==="pending"?(_t.pending_verification||"")'
			. ':(_t.not_verified||"");'
			. 'var _placeId=window.aviEmbedSoloPlaceId||"";'
			. 'var _gbpUrl=_placeId'
			. '? "https://www.google.com/maps/place/?q=place_id:"+_placeId'
			. ': "https://www.google.com/maps/search/"'
			. '+encodeURIComponent((sd.business_name||"")+" "+(sd.city||""));'
			. 'var _scoreTopBar=document.createElement("div");'
			. '_scoreTopBar.className="avi-score-topbar";'
			. '_scoreTopBar.innerHTML='
			. '\'<div class="avi-score-topbar-left">\''
			. '+\'<div class="avi-score-topbar-title">\''
			. '+"\\u2B50 "+(_t.gbp_score_title||"")'
			. '+\' <button type="button" class="avi-header-info-btn" id="aviScoreInfoBtn">\\u2139\\uFE0F</button>\''
			. '+\'</div>\''
			. '+(sd.business_name?\'<div class="avi-score-topbar-biz">\'+sd.business_name+\'</div>\':"")'
			. '+\'<div class="avi-score-topbar-sub">\'+(_t.score_panel_sub||"")+\'</div>\''
			. '+\'</div>\''
			. '+\'<div class="avi-score-topbar-right">\''
			. '+\'<span class="avi-verified-badge avi-verified-badge--\'+_verif+\'">\'+_verifLbl+\'</span>\''
			. '+\'</div>\';'
			. 'inner.appendChild(_scoreTopBar);'
			. 'var _scInfoBtn=_scoreTopBar.querySelector("#aviScoreInfoBtn");'
			. 'if(_scInfoBtn){'
			. '_scInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.score_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.score_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.score_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.score_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.score_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.score_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.score_info_s3_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviScoreInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviScoreInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. '/* #SprintL1-L1.4-badge-position — CTA vérification si non vérifié */'
			. 'if(_verif!=="verified"){'
			. 'var _locId=(window.aviEmbedScoreData&&window.aviEmbedScoreData.google_location_name||"")'
			. '.replace("locations/","");'
			. 'var _verifyUrl=_locId'
			. '?"https://business.google.com/dashboard/l/"+_locId'
			. ':"https://business.google.com/";'
			. 'var _verifyCta=document.createElement("div");'
			. 'if(_verif==="pending"){'
			. '_verifyCta.className="avi-verify-cta avi-verify-cta--pending";'
			. '_verifyCta.innerHTML=\'<p class="avi-verify-cta-text">\''
			. '+(_t.verify_pending_text||"")'
			. '+\'</p>\';'
			. '}else{'
			. '_verifyCta.className="avi-verify-cta";'
			. '_verifyCta.innerHTML=\'<p class="avi-verify-cta-text">\''
			. '+(_t.verify_cta_text||"")'
			. '+\'</p><a href="\'+_verifyUrl+\'" target="_blank" rel="noopener noreferrer" \''
			. '+\'class="avi-verify-cta-btn">\''
			. '+(_t.verify_cta_btn||"")'
			. '+\'</a>\';'
			. '}'
			. 'inner.appendChild(_verifyCta);'
			. '}'
			. 'var gw=document.createElement("div");'
			. 'gw.className="avi-score-gauge-card";'
			. 'var _rankBg="#f0fdf4";'
			. 'var _rankColor="#15803d";'
			. 'if(sd.position_rank>20){_rankBg="#fff1f2";_rankColor="#dc2626";}'
			. 'else if(sd.position_rank>10){_rankBg="#fff7ed";_rankColor="#c2410c";}'
			. 'gw.innerHTML="<div class=\\"avi-score-gc-gauge\\">"'
			. '+_scoreGaugeSvg(score,tier.color)'
			. '+"<div class=\\"avi-score-gauge-val\\" style=\\"color:"+tier.color+"\\">"+score+"</div>"'
			. '+"<div class=\\"avi-score-gauge-label\\">"+tier.label+"</div>"'
			. '+"<div class=\\"avi-score-gauge-progress\\"><div class=\\"avi-score-gauge-progress-bar\\" style=\\"width:"+score+"%;background:"+tier.color+"\\"></div></div>"'
			. '+"<div class=\\"avi-score-gauge-sync\\">"+_t.last_sync+syncLabel+"</div>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi\\" style=\\"background:#fefce8;\\">"'
			. '+"<div class=\\"avi-score-gc-kpi-row\\">"'
			. '+"<span class=\\"avi-score-gc-kpi-val\\" style=\\"color:#854d0e;\\">"+(sd.average_rating?parseFloat(sd.average_rating).toFixed(1):"—")+"</span>"'
			. '+"<span class=\\"avi-score-gc-kpi-icon\\">\\u2B50</span>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi-label\\">"+(sd.review_count||0)+" "+(_t.reviews_label||"reviews")+"</div>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi\\" style=\\"background:#eff6ff;\\">"'
			. '+"<div class=\\"avi-score-gc-kpi-row\\">"'
			. '+"<span class=\\"avi-score-gc-kpi-val\\" style=\\"color:#1d4ed8;\\">"+(sd.total_photos||"—")+"</span>"'
			. '+"<span class=\\"avi-score-gc-kpi-icon\\">\\uD83D\\uDCF8</span>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi-label\\">"+(_t.photos_label||"Photos")+"</div>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi\\" style=\\"background:"+_rankBg+";\\">"'
			. '+"<div class=\\"avi-score-gc-kpi-row\\">"'
			. '+"<span class=\\"avi-score-gc-kpi-val\\" style=\\"color:"+_rankColor+";\\">"+(sd.position_rank||"—")+"</span>"'
			. '+"<span class=\\"avi-score-gc-kpi-icon\\">#</span>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-kpi-label\\">"+(_t.avg_rank||"Avg rank")+"</div>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-score-gc-actions\\">"'
			. '+"<a href=\\""+_gbpUrl+"\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\" class=\\"avi-score-gbp-link\\">"'
			. '+(_t.gbp_badge||"GBP \\u2197")+"</a>"'
			. '+"<button type=\\"button\\" class=\\"avi-sync-btn\\" id=\\"aviScoreSyncBtn\\" data-context=\\"score\\">"'
			. '+(_t.sync_btn||"\\uD83D\\uDD04 Sync from Google")'
			. '+"<span class=\\"avi-sync-info-btn\\" data-context=\\"score\\" aria-label=\\"info\\" style=\\"display:inline-flex;align-items:center;margin-left:6px;font-size:14px;cursor:pointer;line-height:1;\\">&#x2139;&#xFE0F;</span>"'
			. '+"</button>"'
			. '+"</div>";'
			. 'inner.appendChild(gw);'
			. 'var cr=document.createElement("div");'
			. 'cr.className="avi-score-criteria-wrap";'
			. 'var crLeft=document.createElement("div");'
			. 'crLeft.className="avi-score-col";'
			. 'crLeft.innerHTML=\'<div class="avi-score-col-title">\'+(_t.profile_completeness||"")+\'</div>\';'
			. 'var freshnessNote=document.createElement("div");'
			. 'freshnessNote.className="avi-score-freshness-note";'
			. 'freshnessNote.innerHTML="\\uD83D\\uDCA1 "+(_t.freshness_note||"Your score fluctuates with your activity: posts, photos, review replies, profile completeness and heatmap scans all impact your ranking. Stay active to maximize your points.");'
			. 'crLeft.insertBefore(freshnessNote, crLeft.firstChild.nextSibling);'
			. 'crLeft.style.display="none";'
			. 'var _cardBodyNAP=document.createElement("div");'
			. '_cardBodyNAP.className="avi-score-card-body";'
			. '_cardBodyNAP.id="aviCardBodyNAP";'
			. 'var _cardBodyOnline=document.createElement("div");'
			. '_cardBodyOnline.className="avi-score-card-body";'
			. '_cardBodyOnline.id="aviCardBodyOnline";'
			. 'var _cardBodyActivity=document.createElement("div");'
			. '_cardBodyActivity.className="avi-score-card-body";'
			. '_cardBodyActivity.id="aviCardBodyActivity";'
			. 'var _cardBodyVisibility=document.createElement("div");'
			. '_cardBodyVisibility.className="avi-score-card-body";'
			. '_cardBodyVisibility.id="aviCardBodyVisibility";'
			. 'function _applyCardLimit(cardBodyId){'
			. 'var body=document.getElementById(cardBodyId);'
			. 'if(!body){'
			. 'if(cardBodyId==="aviCardBodyNAP")body=_cardBodyNAP;'
			. 'else if(cardBodyId==="aviCardBodyOnline")body=_cardBodyOnline;'
			. 'else if(cardBodyId==="aviCardBodyActivity")body=_cardBodyActivity;'
			. 'else if(cardBodyId==="aviCardBodyVisibility")body=_cardBodyVisibility;'
			. '}'
			. 'if(!body)return;'
			. 'var rows=body.querySelectorAll(".avi-score-nap-row,.avi-score-hm-row");'
			. 'if(rows.length<=3)return;'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'for(var ri=3;ri<rows.length;ri++){rows[ri].style.display="none";rows[ri].setAttribute("data-card-hidden","1");}'
			. 'var _moreBtn=document.createElement("button");'
			. '_moreBtn.type="button";'
			. '_moreBtn.className="avi-score-card-more-btn";'
			. '_moreBtn.setAttribute("data-card-expanded","0");'
			. '_moreBtn.textContent="\\u25bc "+(_tL.card_see_more||"")+" ("+(rows.length-3)+")";'
			. '_moreBtn.addEventListener("click",function(){'
			. 'var expanded=_moreBtn.getAttribute("data-card-expanded")==="1";'
			. 'var hiddenRows=body.querySelectorAll("[data-card-hidden]");'
			. 'hiddenRows.forEach(function(r){r.style.display=expanded?"none":"";});'
			. '_moreBtn.setAttribute("data-card-expanded",expanded?"0":"1");'
			. '_moreBtn.textContent=expanded?"\\u25bc "+(_tL.card_see_more||"")+" ("+(rows.length-3)+")":"\\u25b2 "+(_tL.card_see_less||"");'
			. '});'
			. 'body.appendChild(_moreBtn);'
			. '}'
			. 'var criterionValues={'
			. 'name:sd.name_value||"",'
			. 'website:sd.website_url||"",'
			. 'phone:sd.phone_value||"",'
			. 'hours:sd.has_hours?("\\u2713 "+(sd.hours_periods||[]).length+" days"):"",'
			. 'description:sd.description_value?sd.description_value.substring(0,60)+"...":"",'
			. 'categories:sd.primary_category_name||"",'
			. 'address:[sd.address_lines?sd.address_lines[0]:"",sd.address_locality].filter(Boolean).join(", "),'
			. 'specialHours:sd.special_hours_value||"",'
			. 'serviceArea:sd.service_area_value||""'
			. '};'
			. 'var postOk=!!sd.has_recent_post;'
			. 'var postCount=sd.posts_count||0;'
			. 'var postDays=sd.last_post_at?Math.round((Date.now()-new Date(sd.last_post_at))/(1000*86400)):-1;'
			. 'var postStale=postCount>0&&postDays>7;'
			. 'var photoOk=!!sd.has_photos;'
			. 'var photoCount=sd.photos_published||0;'
			. 'var photoDays=sd.last_photo_at?Math.round((Date.now()-new Date(sd.last_photo_at))/(1000*86400)):-1;'
			. 'var photoStale=photoCount>0&&photoDays>7;'
			. 'var rvData=window.aviEmbedReviewsData||{};'
			. 'var rvList=rvData.reviews||[];'
			. 'var lastRv=rvList.length>0?rvList[0]:null;'
			. 'var rvReplied=lastRv?!!lastRv.has_reply:false;'
			. 'var rvOk=lastRv&&rvReplied;'
			. 'var _scoreDelta=0;'
			. 'if(!sd.has_recent_post||postStale)_scoreDelta-=5;'
			. 'if(!sd.has_photos||photoStale)_scoreDelta-=5;'
			. 'if(!rvOk)_scoreDelta-=3;'
			. 'if(!sd.has_website)_scoreDelta-=5;'
			. 'if(!sd.has_phone)_scoreDelta-=4;'
			. 'if(!sd.has_hours)_scoreDelta-=3;'
			. 'if(!sd.has_description)_scoreDelta-=2;'
			. 'if(window._aviGuardianAlerts){'
			. 'var _gDeltaMap={title:0,phoneNumbers:4,categories:1,regularHours:3,websiteUri:5,openInfo:0,storefrontAddress:1,description:2,specialHours:1,serviceArea:1};'
			. 'window._aviGuardianAlerts.forEach(function(a){'
			. 'if(parseInt(a.is_read)===0&&_gDeltaMap.hasOwnProperty(a.alert_type)&&_gDeltaMap[a.alert_type]>0){'
			. 'var _alreadyCounted={'
			. 'websiteUri:!sd.has_website,'
			. 'phoneNumbers:!sd.has_phone,'
			. 'regularHours:!sd.has_hours,'
			. 'description:!sd.has_description'
			. '};'
			. 'if(!_alreadyCounted[a.alert_type])_scoreDelta-=_gDeltaMap[a.alert_type];'
			. '}'
			. '});'
			. '}'
			. 'if(window._aviCitStale)_scoreDelta-=2;'
			. 'window.aviScoreDelta=_scoreDelta;'
			. 'criteria.forEach(function(c){'
			. 'var ok=!!sd[c.key];'
			. 'if(ok&&window._aviGuardianAlerts){'
			. 'var _gField=null;'
			. 'var _fMap={title:"name",phoneNumbers:"phone",categories:"categories",regularHours:"hours",websiteUri:"website",openInfo:"openInfo",storefrontAddress:"address",description:"description",specialHours:"specialHours",serviceArea:"serviceArea"};'
			. 'Object.keys(_fMap).forEach(function(k){if(_fMap[k]===c.field)_gField=k;});'
			. 'if(_gField&&window._aviGuardianAlerts.some(function(a){return a.alert_type===_gField&&parseInt(a.is_read)===0;})){'
			. 'ok=false;'
			. '}'
			. '}'
			. 'var ptsDisplay=c.pts;'
			. 'var ptsExtraClass="";'
			. 'if(!ok&&_scoreDelta<=-10){'
			. '  ptsDisplay=c.pts.replace("+","-");'
			. '  ptsExtraClass=" avi-score-nap-pts--neg";'
			. '}'
			. 'var val=criterionValues[c.field]||"";'
			. 'if(c.field==="openInfo"){'
			. 'var _oiStatus=sd.open_info_status||"";'
			. 'var _oiGuardianAlert=null;'
			. 'if(window._aviGuardianAlerts){'
			. '_oiGuardianAlert=window._aviGuardianAlerts.find(function(a){'
			. 'return a.alert_type==="openInfo"&&parseInt(a.is_read)===0;'
			. '});'
			. '}'
			. 'var _oiMap={'
			. '"OPEN":"\ud83d\udfe2 "+(_t.open_status_open||"Open — Normal business hours"),'
			. '"OPEN_FOR_BUSINESS":"\ud83d\udfe2 "+(_t.open_status_open||"Open — Normal business hours"),'
			. '"CLOSED_TEMPORARILY":"\ud83d\udfe1 "+(_t.open_status_temp||"Temporarily closed — will reopen"),'
			. '"CLOSED_PERMANENTLY":"\ud83d\udd34 "+(_t.open_status_perm||"Permanently closed")'
			. '};'
			. 'val=_oiMap[_oiStatus]||("\u2753 "+(_t.open_status_unknown||"Status unknown"));'
			. 'var _oiOk=(_oiStatus==="OPEN"||_oiStatus==="OPEN_FOR_BUSINESS");'
			. 'var _oiWarn=(_oiStatus==="CLOSED_TEMPORARILY");'
			. 'var _oiCrit=(_oiStatus==="CLOSED_PERMANENTLY");'
			. 'var row=document.createElement("div");'
			. 'row.className="avi-score-nap-row"+'
			. '(_oiCrit?" avi-score-nap-row--guardian":"")+(_oiWarn?" avi-score-nap-row--warn":"");'
			. 'var _gpClassOI=(function(){var _gpD=window._aviGuardianPlan||null;if(!_gpD||_gpD.plan==="free")return " avi-score-btn-guardian-off";if(_gpD.is_trial||_gpD.is_paid)return " avi-score-btn-guardian-trial";return " avi-score-btn-guardian-active";})();'
			. 'row.innerHTML='
			. '\'<div class="avi-score-nap-top">\''
			. '+(function(){var _tGT=_embedI18n[_embedLang]||_embedI18n.en;if(_gpClassOI.trim()==="avi-score-btn-guardian-active")return \'<span class="avi-guardian-field-warn" title="\'+(_tGT.guardian_tooltip_active||"\\u26a0\\ufe0f Trial ended \\u2014 credits active")+\'">\u26a0\ufe0f</span>\';if(_gpClassOI.trim()==="avi-score-btn-guardian-off")return \'<span class="avi-guardian-field-dot avi-score-btn-guardian-off" title="\'+(_tGT.guardian_tooltip_off||"Guardian deactivated")+\'"></span>\';return \'<span class="avi-guardian-field-dot avi-score-btn-guardian-trial" title="\'+(_tGT.guardian_tooltip_trial||"\\ud83d\\udee1\\ufe0f Monitored by Guardian")+\'"></span>\';})() '
			. '+\'<span class="avi-score-nap-icon">\'+c.icon+\'</span>\''
			. '+\'<span class="avi-score-nap-label">\'+c.label+\'</span>\''
			. '+\'<span class="avi-score-nap-pts">\'+c.pts+\'</span>\''
			. '+\'<span class="avi-score-nap-status \'+'
			. '(_oiGuardianAlert?"avi-score-ko":_oiCrit?"avi-score-ko":_oiWarn?"avi-score-warn":"avi-score-ok")+\'">\''
			. '+(_oiGuardianAlert?"\u26a0\ufe0f":_oiCrit?"\ud83d\udd34":_oiWarn?"\ud83d\udfe1":"\u2705")+\'</span>\''
			. '+(_oiGuardianAlert?\'<button type="button" class="avi-score-criterion-edit-btn avi-score-criterion-edit-btn--fix" data-score-field="openInfo">\'+(_t.fix||"Fix")+\'</button>\':\'<button type="button" class="avi-score-criterion-edit-btn" data-score-field="openInfo">\'+(_t.edit||"Edit")+\'</button>\')'
			. '+\'</div>\''
			. '+\'<div class="avi-score-nap-val">\'+val+\'</div>\';'
			. 'var _cardBodyTarget=c.group==="online"?_cardBodyOnline:_cardBodyNAP;'
			. 'if(_cardBodyTarget)_cardBodyTarget.appendChild(row);else crLeft.appendChild(row);'
			. '(function(){'
			. 'var _gAlerts=window._aviGuardianAlerts||[];'
			. 'var _tG=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _matchAlerts=_gAlerts.filter(function(a){return a.alert_type==="openInfo"&&parseInt(a.is_read)===0;});'
			. 'if(!_matchAlerts.length){return;}'
			. 'row.classList.add("avi-score-nap-row--guardian");'
			. '_matchAlerts.forEach(function(a){'
			. 'var diff=document.createElement("div");'
			. 'diff.className="avi-score-nap-guardian-diff";'
			. 'var lbl=document.createElement("div");'
			. 'lbl.className="avi-score-nap-guardian-label";'
			. 'lbl.textContent="\u26a0\ufe0f "+(_tG.guardian_field_openInfo||"Open/closed status changed")+" \u2014 "+(_tG.guardian_verify||"verify immediately");'
			. 'var oldDiv=document.createElement("div");oldDiv.className="avi-score-nap-guardian-old";'
			. 'var oldB=document.createElement("b");oldB.textContent=(_tG.guardian_old||"Before:")+" ";'
			. 'var oldSpan=document.createElement("span");oldSpan.textContent=a.old_value||"\u2014";'
			. 'oldDiv.appendChild(oldB);oldDiv.appendChild(oldSpan);'
			. 'var newDiv=document.createElement("div");newDiv.className="avi-score-nap-guardian-new";'
			. 'var newB=document.createElement("b");newB.textContent=(_tG.guardian_new||"After:")+" ";'
			. 'var newSpan=document.createElement("span");newSpan.textContent=a.new_value||"\u2014";'
			. 'newDiv.appendChild(newB);newDiv.appendChild(newSpan);'
			. 'var fixNowBtn=document.createElement("button");'
			. 'fixNowBtn.type="button";fixNowBtn.className="avi-score-nap-guardian-fix-now";'
			. 'fixNowBtn.textContent="\ud83d\udd27 "+(_tG.guardian_fix_now||"Fix now")+" \u2014 "+(_tG.guardian_field_openInfo||"Open/closed status");'
			. 'fixNowBtn.addEventListener("click",function(e){e.stopPropagation();var eb=row.querySelector(".avi-score-criterion-edit-btn");if(eb)eb.click();});'
			. 'diff.appendChild(lbl);diff.appendChild(oldDiv);diff.appendChild(newDiv);diff.appendChild(fixNowBtn);'
			. 'row.appendChild(diff);'
			. '});'
			. '})();'
			. '}else{'
			. 'var _gfMap={"name":"title","address":"storefrontAddress","phone":"phoneNumbers","categories":"categories","description":"description","openInfo":"openInfo","specialHours":"specialHours","serviceArea":"serviceArea","website":"websiteUri","hours":"regularHours"};'
			. 'var _gpData=window._aviGuardianPlan||null;'
			. 'var _gpKey=_gfMap[c.field]||null;'
			. 'var _gpMonitored=_gpKey!==null;'
			. 'var _gpClass="";'
			. 'if(_gpMonitored){'
			. 'if(!_gpData||_gpData.plan==="free"){_gpClass=" avi-score-btn-guardian-off";}'
			. 'else if(_gpData.is_trial||_gpData.is_paid){_gpClass=" avi-score-btn-guardian-trial";}'
			. 'else{_gpClass=" avi-score-btn-guardian-active";}'
			. '}'
			. 'var row=document.createElement("div");'
			. 'row.className="avi-score-nap-row";'
			. 'row.innerHTML='
			. '\'<div class="avi-score-nap-top">\''
			. '+(function(){if(!_gpMonitored)return "";var _tGT=_embedI18n[_embedLang]||_embedI18n.en;if(_gpClass.trim()==="avi-score-btn-guardian-active")return \'<span class="avi-guardian-field-warn" title="\'+(_tGT.guardian_tooltip_active||"\\u26a0\\ufe0f Trial ended \\u2014 credits active")+\'">\u26a0\ufe0f</span>\';if(_gpClass.trim()==="avi-score-btn-guardian-off")return \'<span class="avi-guardian-field-dot avi-score-btn-guardian-off" title="\'+(_tGT.guardian_tooltip_off||"Guardian deactivated")+\'"></span>\';return \'<span class="avi-guardian-field-dot avi-score-btn-guardian-trial" title="\'+(_tGT.guardian_tooltip_trial||"\\ud83d\\udee1\\ufe0f Monitored by Guardian")+\'"></span>\';})() '
			. '+\'<span class="avi-score-nap-icon">\'+c.icon+\'</span>\''
			. '+\'<span class="avi-score-nap-label">\'+c.label+\'</span>\''
			. '+\'<span class="avi-score-nap-pts\'+ptsExtraClass+\'">\'+ptsDisplay+\'</span>\''
			. '+\'<span class="avi-score-nap-status \'+(ok?"avi-score-ok":"avi-score-ko")+\'">\'+(ok?(_t.done||"\\u2713"):(_t.missing||"\\u2717"))+\'</span>\''
			. '+\'<button type="button" class="avi-score-criterion-edit-btn\'+(ok?"":" avi-score-criterion-edit-btn--fix")+\'" data-score-field="\'+c.field+\'">\'+(ok?(_t.edit||"Edit"):(_t.fix||"Fix"))+\'</button>\''
			. '+\'</div>\''
			. '+(val?\'<div class="avi-score-nap-val">\'+val+\'</div>\':"");'
			. 'var _cardBodyTarget=c.group==="online"?_cardBodyOnline:_cardBodyNAP;'
			. 'if(_cardBodyTarget)_cardBodyTarget.appendChild(row);else crLeft.appendChild(row);'
			. '}'
			. '(function(){'
			. 'if(c.field==="openInfo")return;'
			. 'var _gAlerts=window._aviGuardianAlerts||[];'
			. 'var _tG=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _fieldMap={title:"name",phoneNumbers:"phone",categories:"categories",regularHours:"hours",websiteUri:"website",openInfo:"openInfo",storefrontAddress:"address",description:"description",specialHours:"specialHours",serviceArea:"serviceArea"};'
			. 'var _matchField=null;'
			. 'Object.keys(_fieldMap).forEach(function(gField){'
			. 'if(_fieldMap[gField]===c.field)_matchField=gField;'
			. '});'
			. 'if(!_matchField)return;'
			. 'var _matchAlerts=_gAlerts.filter(function(a){return a.alert_type===_matchField&&parseInt(a.is_read)===0;});'
			. 'if(!_matchAlerts.length)return;'
			. 'row.classList.add("avi-score-nap-row--guardian");'
			. '_matchAlerts.forEach(function(a){'
			. 'var diff=document.createElement("div");'
			. 'diff.className="avi-score-nap-guardian-diff";'
			. 'var lbl=document.createElement("div");'
			. 'lbl.className="avi-score-nap-guardian-label";'
			. 'var _i18nKeyMap={title:"guardian_field_title",phoneNumbers:"guardian_field_phone",categories:"guardian_field_categories",regularHours:"guardian_field_hours",websiteUri:"guardian_field_website",openInfo:"guardian_field_openInfo",storefrontAddress:"guardian_field_address",description:"guardian_field_description",specialHours:"guardian_field_specialHours",serviceArea:"guardian_field_serviceArea"};'
			. 'var _i18nKey=_i18nKeyMap[a.alert_type]||("guardian_field_"+a.alert_type);'
			. 'var _guardianFieldLabel=_tG[_i18nKey]||a.alert_type;'
			. 'var _guardianAlertLabel="\u26a0\ufe0f "+_guardianFieldLabel+" \u2014 "+(_tG.guardian_verify||"verify immediately");'
			. 'lbl.textContent=_guardianAlertLabel;'
			. 'var oldDiv=document.createElement("div");'
			. 'oldDiv.className="avi-score-nap-guardian-old";'
			. 'var oldB=document.createElement("b");'
			. 'oldB.textContent=(_tG.guardian_old||"Before:")+" ";'
			. 'var oldSpan=document.createElement("span");'
			. 'oldSpan.textContent=a.old_value||"\u2014";'
			. 'oldDiv.appendChild(oldB);oldDiv.appendChild(oldSpan);'
			. 'var newDiv=document.createElement("div");'
			. 'newDiv.className="avi-score-nap-guardian-new";'
			. 'var newB=document.createElement("b");'
			. 'newB.textContent=(_tG.guardian_new||"After:")+" ";'
			. 'var newSpan=document.createElement("span");'
			. 'newSpan.textContent=a.new_value||"\u2014";'
			. 'newDiv.appendChild(newB);newDiv.appendChild(newSpan);'
			. 'var dateDiv=document.createElement("div");'
			. 'dateDiv.className="avi-score-nap-guardian-date";'
			. 'dateDiv.textContent=(_tG.guardian_detected||"Detected:")+" "+a.detected_at;'
			. 'var fixNowBtn=document.createElement("button");'
			. 'fixNowBtn.type="button";'
			. 'fixNowBtn.className="avi-score-nap-guardian-fix-now";'
			. 'fixNowBtn.textContent="\ud83d\udd27 "+(_tG.guardian_fix_now||"Fix now")+" \u2014 "+_guardianFieldLabel;'
			. 'fixNowBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var editBtn=row.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(editBtn)editBtn.click();'
			. '});'
			. 'diff.appendChild(lbl);'
			. 'diff.appendChild(oldDiv);'
			. 'diff.appendChild(newDiv);'
			. 'diff.appendChild(dateDiv);'
			. 'diff.appendChild(fixNowBtn);'
			. 'row.appendChild(diff);'
			. '});'
			. '})();'
			. '});'
			. 'var _cardActivity=_cardBodyActivity;'
			. 'var postPts=postOk&&!postStale?"+5 pts":"-5 pts";'
			. 'var postPtsClass=postOk&&!postStale?"avi-score-nap-pts":"avi-score-nap-pts avi-score-nap-pts--neg";'
			. 'var postStatus=postOk?"avi-score-ok":(postStale?"avi-score-ko":"avi-score-ko");'
			. 'var postBtnClass="avi-score-criterion-edit-btn"+((!postOk||postStale)?" avi-score-criterion-edit-btn--fix":"");'
			. 'var postBtnLabel=(!postOk||postStale)?(_t.fix||"Fix"):(_t.edit||"Edit");'
			. 'var postDateLabel=postDays>=0?(postDays===0?(_t.today||"Today"):postDays+"d ago"):"";'
			. 'var postFreshLabel=postStale?"\\u26a0\\uFE0F "+(_t.post_stale||"Last post > 7 days \\u2014 publish to keep your points"):'
			. '  (postOk?"\\u2705 "+(_t.post_fresh||"Fresh \\u2014 published within 7 days"):"");'
			. 'var postRow=document.createElement("div");'
			. 'postRow.className="avi-score-nap-row";'
			. 'postRow.innerHTML='
			. '\'<div class="avi-score-nap-top">\''
			. '+\'<span class="avi-score-nap-icon">\\uD83D\\uDCDD</span>\''
			. '+\'<span class="avi-score-nap-label">\'+(_t.crit_posts||"Recent posts")+\'</span>\''
			. '+\'<span class="\'+postPtsClass+\'">\'+postPts+\'</span>\''
			. '+\'<span class="avi-score-nap-status \'+postStatus+\'">\'+(postOk&&!postStale?(_t.done||"\\u2713"):(_t.missing||"\\u2717"))+\'</span>\''
			. '+\'<button type="button" class="\'+postBtnClass+\'">\'+postBtnLabel+\'</button>\''
			. '+\'</div>\''
			. '+(postDateLabel?\'<div class="avi-score-nap-val">\'+(postCount>0?postCount+" post"+(postCount>1?"s":"")+" \\u00b7 ":"")+postDateLabel+\'</div>\':"")'
			. '+(postFreshLabel?\'<div class="avi-score-nap-fresh \'+(postStale?"avi-score-nap-fresh--warn":"avi-score-nap-fresh--ok")+\'">\'+postFreshLabel+\'</div>\':"")'
			. '+( (!postOk||postStale)?\'<div class="avi-score-nap-upsell"><button type="button" class="avi-score-upsell-btn">\\uD83D\\uDCC5 \'+(_t.post_upsell||"Schedule a post to keep your score")+\'</button></div>\':"");'
			. 'if(_cardActivity)_cardActivity.appendChild(postRow);else crLeft.appendChild(postRow);'
			. 'var postBtn=postRow.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(postBtn)postBtn.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("posts");});'
			. 'var postUpsell=postRow.querySelector(".avi-score-upsell-btn");'
			. 'if(postUpsell)postUpsell.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("posts");});'
			. 'var photoPts=photoOk&&!photoStale?"+5 pts":"-5 pts";'
			. 'var photoPtsClass=photoOk&&!photoStale?"avi-score-nap-pts":"avi-score-nap-pts avi-score-nap-pts--neg";'
			. 'var photoDateLabel=photoDays>=0?(photoDays===0?(_t.today||"Today"):photoDays+"d ago"):"";'
			. 'var photoFreshLabel=photoStale?"\\u26a0\\uFE0F "+(_t.photo_stale||"Last photo > 7 days \\u2014 publish to keep your points"):'
			. '  (photoOk?"\\u2705 "+(_t.photo_fresh||"Fresh \\u2014 photo published within 7 days"):"");'
			. 'var photoRow=document.createElement("div");'
			. 'photoRow.className="avi-score-nap-row";'
			. 'photoRow.innerHTML='
			. '\'<div class="avi-score-nap-top">\''
			. '+\'<span class="avi-score-nap-icon">\\uD83D\\uDDBC\\uFE0F</span>\''
			. '+\'<span class="avi-score-nap-label">\'+(_t.crit_photos||"Published photos")+\'</span>\''
			. '+\'<span class="\'+photoPtsClass+\'">\'+photoPts+\'</span>\''
			. '+\'<span class="avi-score-nap-status \'+(photoOk&&!photoStale?"avi-score-ok":"avi-score-ko")+\'">\'+(photoOk&&!photoStale?(_t.done||"\\u2713"):(_t.missing||"\\u2717"))+\'</span>\''
			. '+\'<button type="button" class="avi-score-criterion-edit-btn\'+((!photoOk||photoStale)?" avi-score-criterion-edit-btn--fix":"")+\'">\'+((!photoOk||photoStale)?(_t.fix||"Fix"):(_t.edit||"Edit"))+\'</button>\''
			. '+\'</div>\''
			. '+\'<div class="avi-score-nap-val">\'+photoCount+\' \'+(_t.photos_published_label||"published")+(photoCount<3?" \\u2014 "+(_t.photos_min||"min. 3 recommended"):"")+(photoDateLabel?" \\u00b7 "+photoDateLabel:"")+\'</div>\''
			. '+(photoFreshLabel?\'<div class="avi-score-nap-fresh \'+(photoStale?"avi-score-nap-fresh--warn":"avi-score-nap-fresh--ok")+\'">\'+photoFreshLabel+\'</div>\':"")'
			. '+( (!photoOk||photoStale)?\'<div class="avi-score-nap-upsell"><button type="button" class="avi-score-upsell-btn">\\uD83D\\uDDBC\\uFE0F \'+(_t.photo_upsell||"Publish a photo to maintain your score")+\'</button></div>\':"");'
			. 'if(_cardActivity)_cardActivity.appendChild(photoRow);else crLeft.appendChild(photoRow);'
			. 'var photoBtn=photoRow.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(photoBtn)photoBtn.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("photos");});'
			. 'var photoUpsell=photoRow.querySelector(".avi-score-upsell-btn");'
			. 'if(photoUpsell)photoUpsell.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("photos");});'
			. 'var rvDays=lastRv&&lastRv.create_time?Math.round((Date.now()-new Date(lastRv.create_time))/(1000*86400)):-1;'
			. 'var rvRow=document.createElement("div");'
			. 'rvRow.className="avi-score-nap-row";'
			. 'rvRow.innerHTML='
			. '\'<div class="avi-score-nap-top">\''
			. '+\'<span class="avi-score-nap-icon">\\u2B50</span>\''
			. '+\'<span class="avi-score-nap-label">\'+(_t.crit_reviews_reply||"Latest review replied")+\'</span>\''
			. '+\'<span class="avi-score-nap-pts">+3 pts</span>\''
			. '+\'<span class="avi-score-nap-status \'+(rvOk?"avi-score-ok":"avi-score-ko")+\'">\'+(rvOk?(_t.done||"\\u2713"):(_t.missing||"\\u2717"))+\'</span>\''
			. '+\'<button type="button" class="avi-score-criterion-edit-btn\'+(rvOk?"":" avi-score-criterion-edit-btn--fix")+\'">\'+(rvOk?(_t.view||"View"):(_t.reply||"Reply"))+\'</button>\''
			. '+\'</div>\''
			. '+(lastRv?\'<div class="avi-score-nap-val">\'+(lastRv.reviewer_name||"Anonymous")+(rvDays>=0?" \\u00b7 "+rvDays+"d ago":"")+(rvReplied?" \\u00b7 \\u2713 "+(_t.replied||"Replied"):" \\u00b7 \\u2717 "+(_t.not_replied||"Not replied"))+\'</div>\''
			. ':\'<div class="avi-score-nap-val">\'+(_t.no_reviews_yet||"No reviews yet")+\'</div>\');'
			. 'if(_cardActivity)_cardActivity.appendChild(rvRow);else crLeft.appendChild(rvRow);'
			. 'var rvBtn=rvRow.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(rvBtn)rvBtn.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("avis");});'
			. 'var _cardVisibility=_cardBodyVisibility;'
			. 'var hmSep=document.createElement("div");'
			. 'hmSep.className="avi-score-hm-sep";'
			. 'hmSep.innerHTML='
			. '\'<span class="avi-score-hm-title">\'+(_t.hm_section_title||"\\uD83D\\uDDFA\\uFE0F Heatmap Visibility")+\'</span>\''
			. '+\'<button type="button" class="avi-header-info-btn" id="aviScoreHmInfoBtn">\\u2139\\uFE0F</button>\';'
			. 'if(_cardVisibility)_cardVisibility.appendChild(hmSep);else crLeft.appendChild(hmSep);'
			. 'var hmInfoBtn=hmSep.querySelector("#aviScoreHmInfoBtn");'
			. 'if(hmInfoBtn){'
			. 'hmInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.hm_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.hm_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.hm_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.hm_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.hm_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.hm_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.hm_info_s3_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.hm_info_s4_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.hm_info_s4_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviHmInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviHmInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var hmData=['
			. '{'
			. 'label:_t.hm_activity_label||"Scan activity",'
			. 'pts:sd.hm_pts_activity||0,'
			. 'max:8,'
			. 'ok:(sd.hm_pts_activity||0)>=3,'
			. 'detail:sd.hm_total_scans>0?'
			. '(sd.hm_total_scans+" scans \\u00b7 "+(sd.hm_is_stale?(_t.hm_stale_warn||"Data outdated"):sd.hm_days_since+"d ago"))'
			. ':(_t.hm_no_scan||"No scan yet"),'
			. 'stale:!!sd.hm_is_stale||!sd.hm_has_scans,'
			. 'tab:"home"'
			. '},'
			. '{'
			. 'label:_t.hm_performance_label||"Local performance",'
			. 'pts:sd.hm_pts_performance||0,'
			. 'max:7,'
			. 'ok:(sd.hm_pts_performance||0)>=5,'
			. 'detail:sd.hm_avg_rank>0?"Avg rank #"+sd.hm_avg_rank:(sd.hm_has_scans?"Rank pending":"\\u2014"),'
			. 'stale:!sd.hm_has_scans,'
			. 'tab:"home"'
			. '},'
			. '{'
			. 'label:_t.hm_coverage_label||"Territory coverage",'
			. 'pts:sd.hm_pts_coverage||0,'
			. 'max:5,'
			. 'ok:(sd.hm_pts_coverage||0)>=3,'
			. 'detail:sd.hm_max_grid>0?sd.hm_max_grid+"x"+sd.hm_max_grid+" \\u00b7 "+sd.hm_keywords_count+" keywords":"\\u2014",'
			. 'stale:!sd.hm_has_scans,'
			. 'tab:"home"'
			. '}'
			. '];'
			. 'hmData.forEach(function(hm){'
			. 'var hmPtsPos=hm.pts>=0;'
			. 'var hmPtsClass="avi-score-nap-pts"+(hmPtsPos?"":" avi-score-nap-pts--neg");'
			. 'var hmPtsSign=hmPtsPos?"+":"";'
			. 'var hmPtsText=hmPtsSign+hm.pts+"/"+hm.max+" pts";'
			. 'var hmStatusClass="avi-score-nap-status "+(hm.ok?"avi-score-ok":"avi-score-ko");'
			. 'var hmStatusText=hm.ok?(_t.done||"\\u2713"):(_t.missing||"\\u2717");'
			. 'var hmBtnClass="avi-score-criterion-edit-btn"+(hm.ok?"":" avi-score-criterion-edit-btn--fix");'
			. 'var hmBtnText=hm.ok?(_t.view||"View"):(_t.hm_scan_now||"Scan");'
			. 'var hmIcon=hm.ok?"\\uD83D\\uDFE2":"\\uD83D\\uDD34";'
			. 'var hmRow=document.createElement("div");'
			. 'hmRow.className="avi-score-nap-row avi-score-hm-row";'
			. 'var hmTop=document.createElement("div");'
			. 'hmTop.className="avi-score-nap-top";'
			. 'hmTop.innerHTML='
			. '\'<span class="avi-score-nap-icon">\'+hmIcon+\'</span>\''
			. '+\'<span class="avi-score-nap-label">\'+hm.label+\'</span>\''
			. '+\'<span class="\'+hmPtsClass+\'">\'+hmPtsText+\'</span>\''
			. '+\'<span class="\'+hmStatusClass+\'">\'+hmStatusText+\'</span>\''
			. '+\'<button type="button" class="\'+hmBtnClass+\'">\'+hmBtnText+\'</button>\';'
			. 'var hmVal=document.createElement("div");'
			. 'hmVal.className="avi-score-nap-val";'
			. 'hmVal.textContent=hm.detail;'
			. 'hmRow.appendChild(hmTop);'
			. 'hmRow.appendChild(hmVal);'
			. 'var hmBtn=hmRow.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(hmBtn)hmBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. '_switchEmbedTab("home");'
			. '});'
			. 'if(_cardVisibility)_cardVisibility.appendChild(hmRow);else crLeft.appendChild(hmRow);'
			. '});'
			. 'var _citData=(window.aviEmbedCitationsData)||{citations:{},score:0,done:0};'
			. 'var _citSaved=_citData.citations||{};'
			. 'var _citDirs=typeof _citationsGetDirectories==="function"?_citationsGetDirectories():{universal:[],local:[],niche:[]};'
			. 'var _citTotal=_citDirs.universal.length+_citDirs.local.length+_citDirs.niche.length;'
			. 'var _citDone=Object.values(_citSaved).filter(function(s){return s&&(s.status==="done"||s.status==="already_listed");}).length;'
			. 'var _citScore=_citTotal>0?Math.round((_citDone/_citTotal)*15):0;'
			. 'var _citLastUpdate=null;'
			. 'Object.values(_citSaved).forEach(function(s){'
			. 'if(s&&s.last_updated_at){'
			. 'var d=new Date(s.last_updated_at);'
			. 'if(!_citLastUpdate||d>_citLastUpdate)_citLastUpdate=d;'
			. '}'
			. '});'
			. 'var _citDaysSince=_citLastUpdate?Math.round((Date.now()-_citLastUpdate.getTime())/(1000*86400)):-1;'
			. 'var _citStale=_citDone>0&&_citDaysSince>30;'
			. 'var _citOk=_citDone>=1&&!_citStale;'
			. 'var _citWarn=_citDone>=1&&_citStale;'
			. 'if(_citStale)_citScore=Math.max(0,_citScore-2);'
			. 'var _citSep=document.createElement("div");'
			. '_citSep.className="avi-score-hm-sep";'
			. '_citSep.innerHTML='
			. '\'<span class="avi-score-hm-title">\'+(_t.cit_score_section||"\ud83d\udccb Citations")+\'</span>\''
			. '+\'<button type="button" class="avi-header-info-btn" id="aviScoreCitInfoBtn">\u2139\ufe0f</button>\';'
			. 'if(_cardVisibility)_cardVisibility.appendChild(_citSep);else crLeft.appendChild(_citSep);'
			. 'var _citScoreInfoBtn=_citSep.querySelector("#aviScoreCitInfoBtn");'
			. 'if(_citScoreInfoBtn){'
			. '_citScoreInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML=\'<div class="avi-edu-modal"><div class="avi-edu-modal-title">\'+(_tL.cit_info_title||"Citations & Local SEO")+\'</div><div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.cit_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.cit_info_s2_body||"")+\'</div></div><button type="button" class="avi-edu-modal-close" id="aviScoreCitInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button></div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviScoreCitInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var _citRow=document.createElement("div");'
			. '_citRow.className="avi-score-nap-row avi-score-hm-row";'
			. 'var _citTop=document.createElement("div");'
			. '_citTop.className="avi-score-nap-top";'
			. 'var _citIcon=_citOk?"\ud83d\udfe2":(_citWarn?"\ud83d\udfe1":"\ud83d\udd34");'
			. 'var _citStatusClass=_citOk?"avi-score-ok":(_citWarn?"avi-score-warn":"avi-score-ko");'
			. 'var _citStatusTxt=_citOk?(_t.done||"\u2713"):(_citWarn?"\u26a0\ufe0f":(_t.missing||"\u2717"));'
			. 'var _citBtnClass="avi-score-criterion-edit-btn"+(_citOk?"":" avi-score-criterion-edit-btn--fix");'
			. 'var _citBtnTxt=_citOk?(_t.view||"View"):(_t.fix||"Fix");'
			. '_citTop.innerHTML='
			. '\'<span class="avi-score-nap-icon">\'+_citIcon+\'</span>\''
			. '+\'<span class="avi-score-nap-label">\'+(_t.cit_score_label||"Directory listings")+\'</span>\''
			. '+\'<span class="avi-score-nap-pts">+\'+_citScore+"/15 pts</span>"'
			. '+\'<span class="avi-score-nap-status \'+_citStatusClass+\'">\'+_citStatusTxt+\'</span>\''
			. '+\'<button type="button" class="\'+_citBtnClass+\'">\'+_citBtnTxt+\'</button>\';'
			. 'var _citVal=document.createElement("div");'
			. '_citVal.className="avi-score-nap-val";'
			. 'var _citDetail=_citDone+" / "+_citTotal+" "+(_t.cit_score_detail||"directories listed");'
			. 'if(_citStale)_citDetail+=" \u2014 "+(_t.cit_stale_warn||"Add a new directory to keep your score");'
			. '_citVal.textContent=_citDetail;'
			. '_citRow.appendChild(_citTop);'
			. '_citRow.appendChild(_citVal);'
			. 'var _citRowBtn=_citRow.querySelector(".avi-score-criterion-edit-btn");'
			. 'if(_citRowBtn)_citRowBtn.addEventListener("click",function(e){e.preventDefault();e.stopPropagation();_switchEmbedTab("citations");});'
			. 'if(_cardVisibility)_cardVisibility.appendChild(_citRow);else crLeft.appendChild(_citRow);'
			. 'window._aviCitScore=_citScore;'
			. 'window._aviCitStale=_citStale;'
			. 'if(_scoreDelta!==0){'
			. '  var _deltaEl=document.createElement("div");'
			. '  _deltaEl.className="avi-score-delta"+(_scoreDelta<0?" avi-score-delta--neg":" avi-score-delta--pos");'
			. '  _deltaEl.textContent=(_scoreDelta>0?"+":"")+_scoreDelta+" pts";'
			. '  var _gaugeLeft=gw.querySelector(".avi-score-gc-gauge");'
			. '  if(_gaugeLeft)_gaugeLeft.appendChild(_deltaEl);'
			. '}'
			. 'cr.appendChild(crLeft);'
			. 'var crRight=document.createElement("div");'
			. 'crRight.className="avi-score-col";'
			. 'crRight.innerHTML=\'<div class="avi-score-col-title" id="aviScoreAttrsTitle" style="display:flex;align-items:center;gap:8px;">\'+(_t.gbp_attributes_title||"GBP Attributes")+\' <button type="button" class="avi-score-card-info-btn" id="aviAttrsInfoBtn">\\u2139\\ufe0f</button><span class="avi-score-attrs-loading" id="aviScoreAttrsLoading">\\u23F3</span></div>\';'
			. 'var _attrsInfoBtn=crRight.querySelector("#aviAttrsInfoBtn");'
			. 'if(_attrsInfoBtn){'
			. '_attrsInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.attrs_info_title||"GBP Attributes")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.attrs_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.attrs_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.attrs_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.attrs_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.attrs_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.attrs_info_s3_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviAttrsInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviAttrsInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'cr.appendChild(crRight);'
			. '_applyCardLimit("aviCardBodyNAP");'
			. '_applyCardLimit("aviCardBodyOnline");'
			. '_applyCardLimit("aviCardBodyActivity");'
			. '_applyCardLimit("aviCardBodyVisibility");'
			. 'var _scoreTabs=document.createElement("div");'
			. '_scoreTabs.className="avi-score-tabs";'
			. 'var _scoreTabDefs=[{id:"profile",icon:"\\ud83d\\udccb",label:(_t.tab_profile||"")},{id:"attributes",icon:"\\ud83d\\udd27",label:(_t.tab_attributes||"")},{id:"history",icon:"\\ud83d\\udcc8",label:(_t.tab_history||"")}];'
			. 'var _activeScoreTab="profile";'
			. '_scoreTabDefs.forEach(function(td){'
			. 'var tb=document.createElement("button");'
			. 'tb.type="button";'
			. 'tb.className="avi-score-tab-btn"+(td.id==="profile"?" avi-score-tab-btn--active":"");'
			. 'tb.setAttribute("data-score-tab",td.id);'
			. 'tb.textContent=td.icon+" "+td.label;'
			. '_scoreTabs.appendChild(tb);'
			. '});'
			. 'inner.appendChild(_scoreTabs);'
			. 'var _tabProfile=document.createElement("div");'
			. '_tabProfile.className="avi-score-tab-panel avi-score-tab-panel--active";'
			. '_tabProfile.setAttribute("data-score-tab-panel","profile");'
			. 'if(freshnessNote&&freshnessNote.parentNode)freshnessNote.parentNode.removeChild(freshnessNote);'
			. '_tabProfile.appendChild(freshnessNote);'
			. 'var _cardsGrid=document.createElement("div");'
			. '_cardsGrid.className="avi-score-cards-grid";'
			. 'var _cardNAP=document.createElement("div");'
			. '_cardNAP.className="avi-score-card";'
			. '_cardNAP.id="aviScoreCardNAP";'
			. '_cardNAP.innerHTML=\'<div class="avi-score-card-header"><div class="avi-score-card-header-left"><span>\\ud83d\\udccd</span><span class="avi-score-card-title">\'+(_t.card_nap||"")+\'</span></div><div style="display:flex;gap:6px;align-items:center;"><button type="button" class="avi-score-card-info-btn" data-card-info="nap">\\u2139\\ufe0f</button><span class="avi-score-card-chevron">\\u25be</span></div></div>\';'
			. '_cardNAP.appendChild(_cardBodyNAP);'
			. '_cardsGrid.appendChild(_cardNAP);'
			. 'var _cardOnline=document.createElement("div");'
			. '_cardOnline.className="avi-score-card";'
			. '_cardOnline.id="aviScoreCardOnline";'
			. '_cardOnline.innerHTML=\'<div class="avi-score-card-header"><div class="avi-score-card-header-left"><span>\\ud83c\\udf10</span><span class="avi-score-card-title">\'+(_t.card_online||"")+\'</span></div><div style="display:flex;gap:6px;align-items:center;"><button type="button" class="avi-score-card-info-btn" data-card-info="online">\\u2139\\ufe0f</button><span class="avi-score-card-chevron">\\u25be</span></div></div>\';'
			. '_cardOnline.appendChild(_cardBodyOnline);'
			. '_cardsGrid.appendChild(_cardOnline);'
			. 'var _cardActivity=document.createElement("div");'
			. '_cardActivity.className="avi-score-card";'
			. '_cardActivity.id="aviScoreCardActivity";'
			. '_cardActivity.innerHTML=\'<div class="avi-score-card-header"><div class="avi-score-card-header-left"><span>\\ud83d\\udcc5</span><span class="avi-score-card-title">\'+(_t.card_activity||"")+\'</span></div><div style="display:flex;gap:6px;align-items:center;"><button type="button" class="avi-score-card-info-btn" data-card-info="activity">\\u2139\\ufe0f</button><span class="avi-score-card-chevron">\\u25be</span></div></div>\';'
			. '_cardActivity.appendChild(_cardBodyActivity);'
			. '_cardsGrid.appendChild(_cardActivity);'
			. 'var _cardVisibility=document.createElement("div");'
			. '_cardVisibility.className="avi-score-card";'
			. '_cardVisibility.id="aviScoreCardVisibility";'
			. '_cardVisibility.innerHTML=\'<div class="avi-score-card-header"><div class="avi-score-card-header-left"><span>\\ud83d\\uddfa\\ufe0f</span><span class="avi-score-card-title">\'+(_t.card_visibility||"")+\'</span></div><div style="display:flex;gap:6px;align-items:center;"><button type="button" class="avi-score-card-info-btn" data-card-info="visibility">\\u2139\\ufe0f</button><span class="avi-score-card-chevron">\\u25be</span></div></div>\';'
			. '_cardVisibility.appendChild(_cardBodyVisibility);'
			. '_cardsGrid.appendChild(_cardVisibility);'
			. '_tabProfile.appendChild(_cardsGrid);'
			. 'inner.appendChild(_tabProfile);'
			. 'var _tabAttributes=document.createElement("div");'
			. '_tabAttributes.className="avi-score-tab-panel";'
			. '_tabAttributes.setAttribute("data-score-tab-panel","attributes");'
			. 'crRight.style.cssText="width:100%;max-width:100%;border-radius:12px;";'
			. '_tabAttributes.appendChild(crRight);'
			. 'inner.appendChild(_tabAttributes);'
			. 'var _tabHistory=document.createElement("div");'
			. '_tabHistory.className="avi-score-tab-panel";'
			. '_tabHistory.setAttribute("data-score-tab-panel","history");'
			. 'inner.appendChild(_tabHistory);'
			. '_scoreTabs.addEventListener("click",function(e){'
			. 'var tb=e.target.closest("[data-score-tab]");'
			. 'if(!tb)return;'
			. 'var tid=tb.getAttribute("data-score-tab");'
			. '_activeScoreTab=tid;'
			. '_scoreTabs.querySelectorAll(".avi-score-tab-btn").forEach(function(b){b.classList.toggle("avi-score-tab-btn--active",b.getAttribute("data-score-tab")===tid);});'
			. 'inner.querySelectorAll(".avi-score-tab-panel").forEach(function(p){p.classList.toggle("avi-score-tab-panel--active",p.getAttribute("data-score-tab-panel")===tid);});'
			. 'if(tid==="history")setTimeout(function(){if(typeof _shDrawSvg==="function")_shDrawSvg();},50);'
			. '});'
			. '_tabProfile.querySelectorAll(".avi-score-card-header").forEach(function(hdr){'
			. 'hdr.addEventListener("click",function(e){'
			. 'if(e.target.closest(".avi-score-card-info-btn"))return;'
			. 'hdr.closest(".avi-score-card").classList.toggle("avi-score-card--collapsed");'
			. '});'
			. '});'
			. '_tabProfile.addEventListener("click",function(e){'
			. 'var infoBtn=e.target.closest("[data-card-info]");'
			. 'if(!infoBtn)return;'
			. 'var card=infoBtn.getAttribute("data-card-info");'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _cardModals={'
			. 'nap:{title:_tL.card_nap_info_title||"NAP & Local SEO",steps:['
			. '{t:_tL.card_nap_s1_title||"",b:_tL.card_nap_s1_body||""},'
			. '{t:_tL.card_nap_s2_title||"",b:_tL.card_nap_s2_body||""},'
			. '{t:_tL.card_nap_s3_title||"",b:_tL.card_nap_s3_body||""},'
			. '{t:_tL.card_nap_s4_title||"",b:_tL.card_nap_s4_body||"",danger:true}'
			. ']},'
			. 'online:{title:_tL.card_online_info_title||"Online Presence",steps:['
			. '{t:_tL.card_online_s1_title||"",b:_tL.card_online_s1_body||""},'
			. '{t:_tL.card_online_s2_title||"",b:_tL.card_online_s2_body||""},'
			. '{t:_tL.card_online_s3_title||"",b:_tL.card_online_s3_body||""}'
			. ']},'
			. 'activity:{title:_tL.card_activity_info_title||"Activity & Engagement",steps:['
			. '{t:_tL.card_activity_s1_title||"",b:_tL.card_activity_s1_body||""},'
			. '{t:_tL.card_activity_s2_title||"",b:_tL.card_activity_s2_body||""},'
			. '{t:_tL.card_activity_s3_title||"",b:_tL.card_activity_s3_body||""}'
			. ']},'
			. 'visibility:{title:_tL.card_visibility_info_title||"Local Visibility",steps:['
			. '{t:_tL.card_visibility_s1_title||"",b:_tL.card_visibility_s1_body||""},'
			. '{t:_tL.card_visibility_s2_title||"",b:_tL.card_visibility_s2_body||""},'
			. '{t:_tL.card_visibility_s3_title||"",b:_tL.card_visibility_s3_body||""}'
			. ']}'
			. '};'
			. 'var _cm=_cardModals[card];if(!_cm)return;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'var stepsHtml=_cm.steps.map(function(s){return s.t?(s.danger?\'<div class="avi-edu-step avi-edu-step--danger"><div class="avi-edu-step-title">\'+s.t+\'</div><div class="avi-edu-step-body">\'+s.b+\'</div></div>\':\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+s.t+\'</div><div class="avi-edu-step-body">\'+s.b+\'</div></div>\'):"";}).join("");'
			. 'backdrop.innerHTML=\'<div class="avi-edu-modal"><div class="avi-edu-modal-title">\'+_cm.title+\'</div>\'+stepsHtml+\'<button type="button" class="avi-edu-modal-close" id="aviCardModalClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button></div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviCardModalClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/get-attributes-available",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,key_id:window.aviEmbedKeyId||""})'
			. '}).then(function(r){return r.json();}).then(function(data){'
			. 'var loader=document.getElementById("aviScoreAttrsLoading");'
			. 'if(loader)loader.remove();'
			. 'if(!data.success){crRight.innerHTML+=\'<div class="avi-attrs-load-error">\'+(_t.attrs_load_error||"Unable to load attributes")+\'<br><span class="avi-attrs-load-hint">\'+(_t.attrs_load_hint||"Click \\uD83D\\uDD04 Sync from Google to reload")+\'</span></div>\';return;}'
			. 'var meta=data.attributeMetadata||[];'
			. 'var current=data.currentValues||{};'
			. 'var groupsSet={};'
			. 'var groupsUnset={};'
			. 'function attrIsFilled(attrId,curVal,vtype){'
			. '  if(vtype==="BOOL")return current.hasOwnProperty(attrId);'
			. '  if(vtype==="REPEATED_ENUM")return Array.isArray(curVal)&&curVal.length>0;'
			. '  if(vtype==="URL"||vtype==="ENUM")return typeof curVal==="string"&&curVal.length>0;'
			. '  return curVal!==undefined&&curVal!==null&&curVal!=="";'
			. '}'
			. 'meta.forEach(function(m){'
			. '  var attrId=m.parent?m.parent.replace("attributes/",""):(m.attributeId||"");'
			. '  var vtype=m.valueType||"BOOL";'
			. '  var group=m.groupDisplayName||"Other";'
			. '  var curVal=current.hasOwnProperty(attrId)?current[attrId]:undefined;'
			. '  var filled=attrIsFilled(attrId,curVal,vtype);'
			. '  var bucket=filled?groupsSet:groupsUnset;'
			. '  if(!bucket[group])bucket[group]=[];'
			. '  bucket[group].push({'
			. '    id:attrId,'
			. '    label:m.displayName||attrId,'
			. '    valueType:vtype,'
			. '    value:curVal,'
			. '    valueMetadata:m.valueMetadata||[],'
			. '    isSet:filled'
			. '  });'
			. '});'
			. 'function renderAttrGroups(groupsObj,defaultOpen){'
			. '  var keys=Object.keys(groupsObj);'
			. '  keys.forEach(function(grp,idx){'
			. '    if(!groupsObj[grp]||!groupsObj[grp].length)return;'
			. '    var isOpen=defaultOpen&&idx===0;'
			. '    var grpEl=document.createElement("div");'
			. '    grpEl.className="avi-attrs-group";'
			. '    var grpHead=document.createElement("div");'
			. '    grpHead.className="avi-attrs-group-title avi-attrs-group-toggle";'
			. '    grpHead.innerHTML=grp+\' <span class="avi-attrs-chevron">\'+(isOpen?"\\u25BE":"\\u25B8")+\'</span>\';'
			. '    var grpBody=document.createElement("div");'
			. '    grpBody.className="avi-attrs-group-body";'
			. '    if(!isOpen)grpBody.style.display="none";'
			. '    grpHead.addEventListener("click",function(){'
			. '      var isOpen=grpBody.style.display!=="none";'
			. '      grpBody.style.display=isOpen?"none":"block";'
			. '      grpHead.querySelector(".avi-attrs-chevron").textContent=isOpen?"\\u25B8":"\\u25BE";'
			. '    });'
			. '    grpEl.appendChild(grpHead);'
			. '    grpEl.appendChild(grpBody);'
			. '    if(grp.toLowerCase().indexOf("url")>-1||grp.toLowerCase().indexOf("adresse")>-1){'
			. '      var hintEl=document.createElement("div");'
			. '      hintEl.className="avi-attrs-group-hint";'
			. '      hintEl.textContent=_t.attr_url_hint||"Add these URLs to improve your profile visibility.";'
			. '      grpBody.appendChild(hintEl);'
			. '    }'
			. '    groupsObj[grp].forEach(function(attr){'
			. '      var row=document.createElement("div");'
			. '      row.className="avi-score-attr-row";'
			. '      if(attr.valueType==="BOOL"){'
			. '        var isTrue=attr.value===true;'
			. '        row.innerHTML='
			. '          \'<span class="avi-score-attr-label">\'+attr.label+\'</span>\''
			. '          +\'<label class="avi-attr-toggle">\''
			. '          +\'<input type="checkbox" class="avi-attr-cb avi-attr-bool" data-attr-id="\'+attr.id+\'" \'+(isTrue?"checked":"")+\'>\''
			. '          +\'<span class="avi-attr-slider"></span>\''
			. '          +\'</label>\';'
			. '        var cb=row.querySelector(".avi-attr-bool");'
			. '        if(cb){'
			. '          cb.addEventListener("change",function(){'
			. '            var nv=cb.checked;cb.disabled=true;'
			. '            fetch(window.location.origin+"/wp-json/avision/v1/embed/update-attribute",{'
			. '              method:"POST",'
			. '              headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '              body:JSON.stringify({profile_id:window.aviEmbedProfileId,attr_id:attr.id,value:nv})'
			. '            }).then(function(r){return r.json();}).then(function(d){'
			. '              cb.disabled=false;'
			. '              if(d.success){_showEmbedToast((_t.attr_saved||"Updated")+": "+attr.label);}'
			. '              else{cb.checked=!nv;_showEmbedToast(d.message||(_t.attr_error||"Error"),true);}'
			. '            }).catch(function(){cb.disabled=false;cb.checked=!nv;_showEmbedToast(_t.err_network||"Error",true);});'
			. '          });'
			. '        }'
			. '      }else if(attr.valueType==="REPEATED_ENUM"){'
			. '        var setVals=Array.isArray(attr.value)?attr.value:[];'
			. '        var cbsHtml=\'<div class="avi-attr-enum-wrap"><span class="avi-score-attr-label">\'+attr.label+\'</span><div class="avi-attr-enum-options">\';'
			. '        attr.valueMetadata.forEach(function(vm){'
			. '          var checked=setVals.indexOf(vm.value)>-1?"checked":"";'
			. '          cbsHtml+=\'<label class="avi-attr-enum-opt"><input type="checkbox" class="avi-attr-enum-cb" data-attr-id="\'+attr.id+\'" data-val="\'+vm.value+\'" \'+checked+\'>\'+\' \'+vm.displayName+\'</label>\';'
			. '        });'
			. '        cbsHtml+=\'</div></div>\';'
			. '        row.innerHTML=cbsHtml;'
			. '        row.querySelectorAll(".avi-attr-enum-cb").forEach(function(ecb){'
			. '          ecb.addEventListener("change",function(){'
			. '            var allCbs=row.querySelectorAll(".avi-attr-enum-cb");'
			. '            var newSet=[];'
			. '            allCbs.forEach(function(c){if(c.checked)newSet.push(c.dataset.val);});'
			. '            fetch(window.location.origin+"/wp-json/avision/v1/embed/update-attribute",{'
			. '              method:"POST",'
			. '              headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '              body:JSON.stringify({profile_id:window.aviEmbedProfileId,attr_id:attr.id,value_type:"REPEATED_ENUM",set_values:newSet})'
			. '            }).then(function(r){return r.json();}).then(function(d){'
			. '              if(d.success){_showEmbedToast((_t.attr_saved||"Updated")+": "+attr.label);}'
			. '              else{_showEmbedToast(d.message||(_t.attr_error||"Error"),true);}'
			. '            }).catch(function(){_showEmbedToast(_t.err_network||"Error",true);});'
			. '          });'
			. '        });'
			. '      }else if(attr.valueType==="URL"){'
			. '        var curUrl=typeof attr.value==="string"?attr.value:"";'
			. '        row.innerHTML='
			. '          \'<div class="avi-attr-url-wrap">\''
			. '          +\'<span class="avi-score-attr-label">\'+attr.label+\'</span>\''
			. '          +\'<div class="avi-attr-url-row">\''
			. '          +\'<input type="url" class="avi-attr-url-input" data-attr-id="\'+attr.id+\'" value="\'+curUrl+\'" placeholder="https://..." />\''
			. '          +\'<button type="button" class="avi-attr-url-save avi-score-criterion-edit-btn" data-attr-id="\'+attr.id+\'">\'+(_t.save||"Save")+\'</button>\''
			. '          +(curUrl?"":\'<a href="https://business.google.com/" target="_blank" rel="noopener" class="avi-attr-url-gbp" title="\'+(_t.attr_url_gbp_hint||"Edit on Google Business Profile")+\'">\\uD83D\\uDCCD GBP</a>\')'
			. '          +\'</div>\''
			. '          +\'</div>\';'
			. '        var saveBtn=row.querySelector(".avi-attr-url-save");'
			. '        var urlInput=row.querySelector(".avi-attr-url-input");'
			. '        if(saveBtn&&urlInput){'
			. '          saveBtn.addEventListener("click",function(e){'
			. '            e.preventDefault();'
			. '            e.stopPropagation();'
			. '            var urlVal=urlInput.value.trim();'
			. '            if(!urlVal)return;'
			. '            saveBtn.disabled=true;'
			. '            fetch(window.location.origin+"/wp-json/avision/v1/embed/update-attribute",{'
			. '              method:"POST",'
			. '              headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '              body:JSON.stringify({profile_id:window.aviEmbedProfileId,attr_id:attr.id,value_type:"URL",uri_value:urlVal})'
			. '            }).then(function(r){return r.json();}).then(function(d){'
			. '              saveBtn.disabled=false;'
			. '              if(d.success){_showEmbedToast((_t.attr_saved||"Updated")+": "+attr.label);}'
			. '              else{_showEmbedToast(d.message||(_t.attr_error||"Error"),true);}'
			. '            }).catch(function(){saveBtn.disabled=false;_showEmbedToast(_t.err_network||"Error",true);});'
			. '          });'
			. '        }'
			. '      }else if(attr.valueType==="ENUM"){'
			. '        var curEnum=typeof attr.value==="string"?attr.value:"";'
			. '        var selHtml=\'<div class="avi-attr-enum-wrap"><span class="avi-score-attr-label">\'+attr.label+\'</span>\''
			. '          +\'<select class="avi-attr-enum-sel" data-attr-id="\'+attr.id+\'">\''
			. '          +\'<option value="">--</option>\';'
			. '        attr.valueMetadata.forEach(function(vm){'
			. '          selHtml+=\'<option value="\'+vm.value+\'"\'+(curEnum===vm.value?" selected":"")+\'>\'+vm.displayName+\'</option>\';'
			. '        });'
			. '        selHtml+=\'</select></div>\';'
			. '        row.innerHTML=selHtml;'
			. '        var sel=row.querySelector(".avi-attr-enum-sel");'
			. '        if(sel){'
			. '          sel.addEventListener("change",function(){'
			. '            fetch(window.location.origin+"/wp-json/avision/v1/embed/update-attribute",{'
			. '              method:"POST",'
			. '              headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '              body:JSON.stringify({profile_id:window.aviEmbedProfileId,attr_id:attr.id,value_type:"ENUM",value:sel.value})'
			. '            }).then(function(r){return r.json();}).then(function(d){'
			. '              if(d.success){_showEmbedToast((_t.attr_saved||"Updated")+": "+attr.label);}'
			. '              else{_showEmbedToast(d.message||(_t.attr_error||"Error"),true);}'
			. '            }).catch(function(){_showEmbedToast(_t.err_network||"Error",true);});'
			. '          });'
			. '        }'
			. '      }'
			. '      grpBody.appendChild(row);'
			. '    });'
			. '    crRight.appendChild(grpEl);'
			. '  });'
			. '}'
			. 'var hasSet=Object.keys(groupsSet).some(function(g){return groupsSet[g]&&groupsSet[g].length>0;});'
			. 'var hasUnset=Object.keys(groupsUnset).some(function(g){return groupsUnset[g]&&groupsUnset[g].length>0;});'
			. 'if(hasSet){'
			. '  renderAttrGroups(groupsSet,true);'
			. '}'
			. 'if(hasSet&&hasUnset){'
			. '  var sepEl=document.createElement("div");'
			. '  sepEl.className="avi-attrs-sep";'
			. '  crRight.appendChild(sepEl);'
			. '}'
			. 'if(hasUnset){'
			. '  renderAttrGroups(groupsUnset,false);'
			. '}'
			. '}).catch(function(){'
			. 'var loader=document.getElementById("aviScoreAttrsLoading");'
			. 'if(loader)loader.remove();'
			. 'crRight.innerHTML+=\'<div class="avi-attrs-load-error">\'+(_t.attrs_load_error||"Unable to load attributes")+\'<br><span class="avi-attrs-load-hint">\'+(_t.attrs_load_hint||"Click \\uD83D\\uDD04 Sync from Google to reload")+\'</span></div>\';'
			. '});'
			. 'var exp=document.createElement("div");'
			. 'exp.className="avi-score-export";'
			. 'var csvBtn=document.createElement("button");'
			. 'csvBtn.type="button";csvBtn.className="avi-score-export-btn csv";'
			. 'csvBtn.textContent=_t.export_csv;'
			. 'csvBtn.addEventListener("click",function(){'
			. 'var rows=[_t.export_col_criterion+","+_t.col_status+","+_t.export_col_points];'
			. 'criteria.forEach(function(c){'
			. 'rows.push("\\""+c.label+"\\","+(sd[c.key]?_t.score_export_done:_t.score_export_missing)+","+c.pts);'
			. '});'
			. 'rows.push(_t.score_export_score+","+score+",/100");'
			. 'rows.push(_t.score_export_rating+","+(sd.average_rating?parseFloat(sd.average_rating).toFixed(1):0)+",");'
			. 'rows.push(_t.reviews_label+","+(sd.review_count||0)+",");'
			. 'rows.push(_t.score_export_photos+","+(sd.total_photos||0)+",");'
			. 'var blob=new Blob([rows.join("\\n")],{type:"text/csv;charset=utf-8;"});'
			. 'var url=URL.createObjectURL(blob);'
			. 'var a=document.createElement("a");'
			. 'a.href=url;a.download="gbp-score.csv";'
			. 'document.body.appendChild(a);a.click();'
			. 'document.body.removeChild(a);URL.revokeObjectURL(url);'
			. '});'
			. 'var pdfBtn=document.createElement("button");'
			. 'pdfBtn.type="button";pdfBtn.className="avi-score-export-btn";'
			. 'pdfBtn.textContent=_t.export_pdf;'
			. 'pdfBtn.addEventListener("click",function(){'
			. 'var brand=window.aviEmbedWhiteLabel||"Avision";'
			. 'var logo=window.aviEmbedLogoUrl'
			. '?"<img src=\\""+window.aviEmbedLogoUrl+"\\" style=\\"height:36px;margin-bottom:8px;\\">"'
			. ':"";'
			. 'var rows=criteria.map(function(c){'
			. 'return "<tr><td>"+c.icon+" "+c.label+"</td>"'
			. '+"<td style=\\"color:"+(sd[c.key]?"#16a34a":"#dc2626")+";\\">"'
			. '+(sd[c.key]?"✅ "+_t.score_export_done:"❌ "+_t.score_export_missing)+"</td>"'
			. '+"<td>"+c.pts+"</td></tr>";'
			. '}).join("");'
			. 'var win=window.open("","_blank");'
			. 'win.document.write("<html><head><title>"+brand+" — "+_t.score_report_title+"</title>"'
			. '+"<style>body{font-family:Inter,sans-serif;padding:32px;color:#1e293b;}"'
			. '+"h1{font-size:20px;}h2{font-size:14px;color:#475569;margin-top:20px;}"'
			. '+".score-big{font-size:64px;font-weight:800;color:"+tier.color+";}"'
			. '+"table{width:100%;border-collapse:collapse;margin-top:12px;font-size:13px;}"'
			. '+"th{background:#f1f5f9;padding:8px;text-align:left;}"'
			. '+"td{padding:7px 8px;border-bottom:1px solid #f1f5f9;}"'
			. '+"</style></head><body>"'
			. '+logo'
			. '+"<h1>"+brand+" — "+_t.score_report_title+"</h1>"'
			. '+"<p style=\\"color:#64748b;font-size:12px;\\">"+sd.business_name+" · "+(sd.city||"")+" · "+new Date().toLocaleDateString()+"</p>"'
			. '+"<div class=\\"score-big\\">"+score+"<span style=\\"font-size:20px;color:#94a3b8;\\">/100</span></div>"'
			. '+"<div style=\\"color:"+tier.color+";font-weight:600;margin-bottom:16px;\\">"+tier.label+"</div>"'
			. '+"<h2>"+_t.profile_completeness+"</h2>"'
			. '+"<table><thead><tr><th>"+_t.export_col_criterion+"</th><th>"+_t.col_status+"</th><th>"+_t.export_col_points+"</th></tr></thead>"'
			. '+"<tbody>"+rows+"</tbody></table>"'
			. '+"<h2>"+_t.score_pdf_stats+"</h2>"'
			. '+"<p>"+_t.score_pdf_rating+(sd.average_rating?parseFloat(sd.average_rating).toFixed(1):"—")+" ("+(sd.review_count||0)+_t.reviews_pdf_reviews_suffix+")</p>"'
			. '+"<p>"+_t.score_pdf_photos+(sd.total_photos||"—")+"</p>"'
			. '+"<p>"+_t.last_sync+syncLabel+"</p>"'
			. '+"</body></html>");'
			. 'win.document.close();win.focus();'
			. 'setTimeout(function(){win.print();},400);'
			. '});'
			. 'exp.appendChild(csvBtn);exp.appendChild(pdfBtn);'
			. 'var _shWrap=document.createElement("div");'
			. '_shWrap.className="avi-sh-wrap";'
			. 'var _t3=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _shHdr=document.createElement("div");'
			. '_shHdr.className="avi-sh-header";'
			. 'var _shTitleDiv=document.createElement("div");'
			. '_shTitleDiv.className="avi-sh-title";'
			. '_shTitleDiv.innerHTML="\\ud83d\\udcc8 "+(_t3.sh_title||"Score & Rank History")+" <button type=\\"button\\" class=\\"avi-sh-info-btn\\" id=\\"aviShInfoBtn\\">\\u2139\\ufe0f</button>";'
			. '_shHdr.appendChild(_shTitleDiv);'
			. 'var _shFsBtn=document.createElement("button");'
			. '_shFsBtn.type="button";_shFsBtn.className="avi-sh-fullscreen-btn";'
			. '_shFsBtn.textContent="\u26f6 "+(_t3.sh_fullscreen||"Full screen");'
			. '_shFsBtn.style.cssText="";'
			. 'var _shOriginalParent=null;var _shOriginalNext=null;'
			. '_shFsBtn.addEventListener("click",function(){'
			. '_shOriginalParent=_shWrap.parentNode;'
			. '_shOriginalNext=_shWrap.nextSibling;'
			. '_shWrap.style.position="";'
			. '_shWrap.classList.add("avi-sh-wrap--fullscreen");'
			. 'document.body.appendChild(_shWrap);'
			. '_shExitBtn.style.display="block";'
			. '_shFsBtn.style.display="none";'
			. 'setTimeout(function(){if(typeof _shDrawSvg==="function")_shDrawSvg();},100);'
			. '});'
			. 'var _shCtrl=document.createElement("div");'
			. '_shCtrl.className="avi-sh-controls";'
			. 'var _shPeriods=["daily","7d","30d","90d","1y"];'
			. 'var _shPeriodLabels={daily:(_t3.sh_daily||"Daily"),"7d":"7d","30d":"30d","90d":"90d","1y":"1y"};'
			. 'var _shActivePeriod="30d";'
			. '_shPeriods.forEach(function(p){'
			. 'var b=document.createElement("button");'
			. 'b.type="button";b.className="avi-sh-period-btn"+(p===_shActivePeriod?" avi-sh-period-btn--active":"");'
			. 'b.textContent=_shPeriodLabels[p]||p;'
			. 'b.setAttribute("data-sh-period",p);'
			. '_shCtrl.appendChild(b);'
			. '});'
			. 'var _shShowScore=true;var _shShowRank=true;'
			. 'var _shBtnScore=document.createElement("button");'
			. '_shBtnScore.type="button";_shBtnScore.className="avi-sh-curve-btn avi-sh-curve-btn--active";'
			. '_shBtnScore.textContent="\\ud83d\\udcca "+(_t3.sh_score||"Score");'
			. '_shBtnScore.setAttribute("data-sh-curve","score");'
			. 'var _shBtnRank=document.createElement("button");'
			. '_shBtnRank.type="button";_shBtnRank.className="avi-sh-curve-btn avi-sh-curve-btn--active";'
			. '_shBtnRank.textContent="\\ud83d\\udccd "+(_t3.sh_rank||"Rank");'
			. '_shBtnRank.setAttribute("data-sh-curve","rank");'
			. '_shCtrl.appendChild(_shBtnScore);_shCtrl.appendChild(_shBtnRank);'
			. 'var _shKwSelect=document.createElement("select");'
			. '_shKwSelect.className="avi-sh-kw-select";'
			. 'var _shKwAll=document.createElement("option");'
			. '_shKwAll.value="";_shKwAll.textContent=(_t3.sh_all_kw||"All keywords");'
			. '_shKwSelect.appendChild(_shKwAll);'
			. 'if(typeof _kwData!=="undefined"&&_kwData.length){'
			. 'var _shKwSeen={};'
			. '_kwData.forEach(function(k){'
			. 'if(k.keyword&&!_shKwSeen[k.keyword]){'
			. '_shKwSeen[k.keyword]=1;'
			. 'var opt=document.createElement("option");'
			. 'opt.value=k.keyword;opt.textContent=k.keyword;'
			. '_shKwSelect.appendChild(opt);'
			. '}'
			. '});'
			. '}'
			. '_shCtrl.appendChild(_shKwSelect);'
			. '_shCtrl.appendChild(_shFsBtn);'
			. 'var _shExitBtn=document.createElement("button");'
			. '_shExitBtn.type="button";'
			. '_shExitBtn.className="avi-sh-fullscreen-btn";'
			. '_shExitBtn.textContent="\u00d7 "+(_t3.sh_exit_fs||"Exit");'
			. '_shExitBtn.style.cssText="position:fixed;top:12px;right:16px;z-index:2147483647;display:none;font-size:13px;padding:4px 12px;";'
			. '_shExitBtn.addEventListener("click",function(){'
			. '_shWrap.classList.remove("avi-sh-wrap--fullscreen");'
			. '_shWrap.style.position="relative";'
			. 'if(_shOriginalParent){'
			. 'if(_shOriginalNext){'
			. '_shOriginalParent.insertBefore(_shWrap,_shOriginalNext);'
			. '}else{'
			. '_shOriginalParent.appendChild(_shWrap);'
			. '}'
			. '}'
			. '_shExitBtn.style.display="none";'
			. '_shFsBtn.style.display="";'
			. 'setTimeout(function(){if(typeof _shDrawSvg==="function")_shDrawSvg();},100);'
			. '});'
			. 'document.body.appendChild(_shExitBtn);'
			. '_shHdr.appendChild(_shCtrl);'
			. '_shWrap.appendChild(_shHdr);'
			. 'var _shSvgWrap=document.createElement("div");'
			. '_shSvgWrap.className="avi-sh-svg-wrap";'
			. '_shSvgWrap.id="aviShSvgWrap";'
			. '_shWrap.appendChild(_shSvgWrap);'
			. 'var _shStat=document.createElement("div");'
			. '_shStat.className="avi-sh-stat";_shStat.id="aviShStat";'
			. '_shWrap.appendChild(_shStat);'
			. 'var _shLegend=document.createElement("div");'
			. '_shLegend.className="avi-sh-legend";'
			. '_shLegend.innerHTML='
			. '\'<div class="avi-sh-legend-item"><div class="avi-sh-legend-dot" style="background:#6d28d9"></div>\'+(_t3.sh_score||"Score GBP")+\'</div>\''
			. '+\'<div class="avi-sh-legend-item"><div class="avi-sh-legend-dot" style="background:#f59e0b"></div>\'+(_t3.sh_rank||"Avg Rank")+\'</div>\''
			. '+\'<div class="avi-sh-legend-item"><div class="avi-sh-legend-dot" style="background:#ef4444;border-radius:2px;width:14px;height:4px;margin:3px 0"></div>\'+(_t3.sh_drop||"Sharp drop")+\'</div>\';'
			. '_shWrap.appendChild(_shLegend);'
			. 'var _shData={history:[],heatmap:[]};'
			. 'function _shDrawSvg(){'
			. 'var svgWrap=document.getElementById("aviShSvgWrap");'
			. 'var statEl=document.getElementById("aviShStat");'
			. 'if(!svgWrap)return;'
			. 'var _shOldSvg=svgWrap.querySelector("svg");'
			. 'if(_shOldSvg)_shOldSvg.remove();'
			. 'var _shTipEl=document.getElementById("aviShTooltip");'
			. 'if(!_shTipEl){'
			. '_shTipEl=document.createElement("div");'
			. '_shTipEl.className="avi-sh-tooltip";'
			. '_shTipEl.id="aviShTooltip";'
			. 'svgWrap.appendChild(_shTipEl);'
			. '}'
			. 'if(statEl)statEl.innerHTML="";'
			. 'var _shByDate={};'
			. '(_shData.history||[]).forEach(function(r){_shByDate[r.date]=_shByDate[r.date]||{};_shByDate[r.date].score=r.score;_shByDate[r.date].avg_rank=r.avg_rank;});'
			. 'var _shKwFilter=_shKwSelect.value;'
			. 'var _shHmFiltered=(_shData.heatmap||[]).filter(function(r){return !_shKwFilter||r.keyword===_shKwFilter;});'
			. 'var _shHmByDate={};'
			. '_shHmFiltered.forEach(function(r){'
			. 'if(!_shHmByDate[r.date])_shHmByDate[r.date]={total:0,count:0};'
			. '_shHmByDate[r.date].total+=r.avg_rank*r.scan_count;'
			. '_shHmByDate[r.date].count+=r.scan_count;'
			. '});'
			. 'Object.keys(_shHmByDate).forEach(function(d){'
			. '_shByDate[d]=_shByDate[d]||{};'
			. '_shByDate[d].hm_rank=_shHmByDate[d].total/_shHmByDate[d].count;'
			. '});'
			. 'var _shDates=Object.keys(_shByDate).sort();'
			. 'if(!_shDates.length){'
			. 'svgWrap.innerHTML=\'<div class="avi-sh-empty">\'+(_t3.sh_no_data||"No data yet. Come back after your first heatmap scan.")+\'</div>\';'
			. 'return;'
			. '}'
			. 'var W=svgWrap.offsetWidth||700;'
			. 'var H=180;'
			. 'if(_shWrap.classList.contains("avi-sh-wrap--fullscreen")){'
			. 'H=svgWrap.getBoundingClientRect().height||Math.max(300,window.innerHeight-210);'
			. '}'
			. 'var PAD_L=36;var PAD_R=16;var PAD_T=14;var PAD_B=28;'
			. 'var CW=W-PAD_L-PAD_R;var CH=H-PAD_T-PAD_B;'
			. 'var _shScores=_shDates.map(function(d){return _shByDate[d].score!=null?_shByDate[d].score:null;});'
			. 'var _shRanks=_shDates.map(function(d){var r=_shByDate[d].hm_rank!=null?_shByDate[d].hm_rank:(_shByDate[d].avg_rank!=null?_shByDate[d].avg_rank:null);return r;});'
			. 'var _shScoreMin=0;var _shScoreMax=100;'
			. 'var _shRankValues=_shRanks.filter(function(r){return r!=null;});'
			. 'var _shRankMin=_shRankValues.length?Math.max(1,Math.floor(Math.min.apply(null,_shRankValues)-1)):1;'
			. 'var _shRankMax=_shRankValues.length?Math.ceil(Math.max.apply(null,_shRankValues)+1):20;'
			. 'function _shXp(i){return PAD_L+Math.round(i/Math.max(_shDates.length-1,1)*CW);}'
			. 'function _shYscore(v){return PAD_T+Math.round((1-(v-_shScoreMin)/(_shScoreMax-_shScoreMin))*CH);}'
			. 'function _shYrank(v){return PAD_T+Math.round(((v-_shRankMin)/Math.max(_shRankMax-_shRankMin,1))*CH);}'
			. 'var svg=\'<svg viewBox="0 0 \'+W+\' \'+H+\'" xmlns="http://www.w3.org/2000/svg" style="overflow:visible">\';'
			. 'for(var gi=0;gi<=4;gi++){'
			. 'var gy=PAD_T+Math.round(gi/4*CH);'
			. 'svg+=\'<line x1="\'+PAD_L+\'" y1="\'+gy+\'" x2="\'+(PAD_L+CW)+\'" y2="\'+gy+\'" stroke="#f1f5f9" stroke-width="1"/>\';'
			. 'var scoreLabel=Math.round(_shScoreMax-gi/4*(_shScoreMax-_shScoreMin));'
			. 'svg+=\'<text x="\'+(PAD_L-4)+\'" y="\'+(gy+4)+\'" font-size="9" fill="#94a3b8" text-anchor="end">\'+scoreLabel+\'</text>\';'
			. '}'
			. 'if(_shShowScore){'
			. 'var _shScorePts=[];'
			. '_shScores.forEach(function(v,i){if(v!=null)_shScorePts.push([_shXp(i),_shYscore(v)]);});'
			. 'if(_shScorePts.length>1){'
			. 'var _shScorePath="M"+_shScorePts[0][0]+","+_shScorePts[0][1];'
			. 'for(var si=1;si<_shScorePts.length;si++){_shScorePath+=" L"+_shScorePts[si][0]+","+_shScorePts[si][1];}'
			. 'svg+=\'<path d="\'+_shScorePath+\'" fill="none" stroke="#6d28d9" stroke-width="2.5" stroke-linejoin="round"/>\';'
			. '}'
			. '_shScores.forEach(function(v,i){'
			. 'if(v==null)return;'
			. 'var isDrop=i>0&&_shScores[i-1]!=null&&(v-_shScores[i-1])<=-10;'
			. 'svg+=\'<circle cx="\'+_shXp(i)+\'" cy="\'+_shYscore(v)+\'" r="3" fill="\'+(isDrop?"#ef4444":"#6d28d9")+\'" stroke="#fff" stroke-width="1.5"/>\';'
			. 'if(isDrop)svg+=\'<rect x="\'+(_shXp(i)-1)+\'" y="\'+PAD_T+\'" width="2" height="\'+CH+\'" fill="#ef4444" opacity="0.15"/>\';'
			. '});'
			. '}'
			. 'if(_shShowRank){'
			. 'var _shRankPts=[];'
			. '_shRanks.forEach(function(v,i){if(v!=null)_shRankPts.push([_shXp(i),_shYrank(v)]);});'
			. 'if(_shRankPts.length>1){'
			. 'var _shRankPath="M"+_shRankPts[0][0]+","+_shRankPts[0][1];'
			. 'for(var ri=1;ri<_shRankPts.length;ri++){_shRankPath+=" L"+_shRankPts[ri][0]+","+_shRankPts[ri][1];}'
			. 'svg+=\'<path d="\'+_shRankPath+\'" fill="none" stroke="#f59e0b" stroke-width="2" stroke-dasharray="5,3" stroke-linejoin="round"/>\';'
			. '}'
			. '_shRanks.forEach(function(v,i){'
			. 'if(v==null)return;'
			. 'var isDrop=i>0&&_shRanks[i-1]!=null&&(v-_shRanks[i-1])>=5;'
			. 'svg+=\'<circle cx="\'+_shXp(i)+\'" cy="\'+_shYrank(v)+\'" r="3" fill="\'+(isDrop?"#ef4444":"#f59e0b")+\'" stroke="#fff" stroke-width="1.5"/>\';'
			. '});'
			. '}'
			. 'var _shStep=Math.ceil(_shDates.length/6);'
			. '_shDates.forEach(function(d,i){'
			. 'if(i%_shStep!==0&&i!==_shDates.length-1)return;'
			. 'var _shLabel=d.substring(5);'
			. 'svg+=\'<text x="\'+_shXp(i)+\'" y="\'+(H-6)+\'" font-size="9" fill="#94a3b8" text-anchor="middle">\'+_shLabel+\'</text>\';'
			. '});'
			. 'svg+="</svg>";'
			. 'var _shTmp=document.createElement("div");'
			. '_shTmp.innerHTML=svg;'
			. 'svgWrap.insertBefore(_shTmp.firstChild,svgWrap.firstChild);'
			. 'var _shSvgEl=svgWrap.querySelector("svg");'
			. 'if(_shSvgEl){'
			. '_shSvgEl.addEventListener("mousemove",function(e){'
			. 'var rect=_shSvgEl.getBoundingClientRect();'
			. 'var mx=e.clientX-rect.left;'
			. 'var tip=document.getElementById("aviShTooltip");'
			. 'if(!tip)return;'
			. 'var _shClosestIdx=-1;var _shClosestDist=9999;'
			. '_shDates.forEach(function(d,i){'
			. 'var dist=Math.abs(_shXp(i)-mx);'
			. 'if(dist<_shClosestDist){_shClosestDist=dist;_shClosestIdx=i;}'
			. '});'
			. 'if(_shClosestIdx<0||_shClosestDist>30){tip.style.opacity="0";return;}'
			. 'var _shTipDate=_shDates[_shClosestIdx];'
			. 'var _shTipScore=_shScores[_shClosestIdx];'
			. 'var _shTipRank=_shRanks[_shClosestIdx];'
			. 'var _shTipHtml=\'<div class="avi-sh-tooltip-date">\'+_shTipDate+\'</div>\';'
			. 'if(_shTipScore!=null&&_shShowScore){'
			. '_shTipHtml+=\'<div class="avi-sh-tooltip-row"><div class="avi-sh-tooltip-dot" style="background:#6d28d9"></div>Score: <strong>\'+_shTipScore+\'</strong></div>\';'
			. '}'
			. 'if(_shTipRank!=null&&_shShowRank){'
			. '_shTipHtml+=\'<div class="avi-sh-tooltip-row"><div class="avi-sh-tooltip-dot" style="background:#f59e0b"></div>Rank: <strong>#\'+Math.round(_shTipRank*10)/10+\'</strong></div>\';'
			. '}'
			. 'if(_shClosestIdx>0){'
			. 'var _shScoreDrop=_shTipScore!=null&&_shScores[_shClosestIdx-1]!=null&&(_shTipScore-_shScores[_shClosestIdx-1])<=-10;'
			. 'var _shRankDrop=_shTipRank!=null&&_shRanks[_shClosestIdx-1]!=null&&(_shTipRank-_shRanks[_shClosestIdx-1])>=5;'
			. 'if(_shScoreDrop)_shTipHtml+=\'<div style="color:#ef4444;margin-top:4px;font-size:10px;">\\u26a0\\ufe0f Score drop</div>\';'
			. 'if(_shRankDrop)_shTipHtml+=\'<div style="color:#ef4444;margin-top:2px;font-size:10px;">\\u26a0\\ufe0f Rank drop</div>\';'
			. '}'
			. 'tip.innerHTML=_shTipHtml;'
			. 'var tipX=_shXp(_shClosestIdx)+10;'
			. 'var tipMaxX=rect.width-160;'
			. 'if(tipX>tipMaxX)tipX=_shXp(_shClosestIdx)-150;'
			. 'tip.style.left=tipX+"px";'
			. 'tip.style.top=(PAD_T+10)+"px";'
			. 'tip.style.opacity="1";'
			. '});'
			. '_shSvgEl.addEventListener("mouseleave",function(){'
			. 'var tip=document.getElementById("aviShTooltip");'
			. 'if(tip)tip.style.opacity="0";'
			. '});'
			. 'function _shHandleTouch(e){'
			. 'e.preventDefault();'
			. 'var touch=e.touches[0]||e.changedTouches[0];'
			. 'if(!touch)return;'
			. 'var rect=_shSvgEl.getBoundingClientRect();'
			. 'var mx=touch.clientX-rect.left;'
			. 'var tip=document.getElementById("aviShTooltip");'
			. 'if(!tip)return;'
			. 'var _shClosestIdx=-1;var _shClosestDist=9999;'
			. '_shDates.forEach(function(d,i){'
			. 'var dist=Math.abs(_shXp(i)-mx);'
			. 'if(dist<_shClosestDist){_shClosestDist=dist;_shClosestIdx=i;}'
			. '});'
			. 'if(_shClosestIdx<0||_shClosestDist>50){tip.style.opacity="0";return;}'
			. 'var _shTipDate=_shDates[_shClosestIdx];'
			. 'var _shTipScore=_shScores[_shClosestIdx];'
			. 'var _shTipRank=_shRanks[_shClosestIdx];'
			. 'var _shTipHtml=\'<div class="avi-sh-tooltip-date">\'+_shTipDate+\'</div>\';'
			. 'if(_shTipScore!=null&&_shShowScore){'
			. '_shTipHtml+=\'<div class="avi-sh-tooltip-row"><div class="avi-sh-tooltip-dot" style="background:#6d28d9"></div>Score: <strong>\'+_shTipScore+\'</strong></div>\';'
			. '}'
			. 'if(_shTipRank!=null&&_shShowRank){'
			. '_shTipHtml+=\'<div class="avi-sh-tooltip-row"><div class="avi-sh-tooltip-dot" style="background:#f59e0b"></div>Rank: <strong>#\'+Math.round(_shTipRank*10)/10+\'</strong></div>\';'
			. '}'
			. 'if(_shClosestIdx>0){'
			. 'var _shScoreDrop=_shTipScore!=null&&_shScores[_shClosestIdx-1]!=null&&(_shTipScore-_shScores[_shClosestIdx-1])<=-10;'
			. 'var _shRankDrop=_shTipRank!=null&&_shRanks[_shClosestIdx-1]!=null&&(_shTipRank-_shRanks[_shClosestIdx-1])>=5;'
			. 'if(_shScoreDrop)_shTipHtml+=\'<div style="color:#ef4444;margin-top:4px;font-size:10px;">\\u26a0\\ufe0f Score drop</div>\';'
			. 'if(_shRankDrop)_shTipHtml+=\'<div style="color:#ef4444;margin-top:2px;font-size:10px;">\\u26a0\\ufe0f Rank drop</div>\';'
			. '}'
			. 'tip.innerHTML=_shTipHtml;'
			. 'var tipX=_shXp(_shClosestIdx)+10;'
			. 'var tipMaxX=rect.width-160;'
			. 'if(tipX>tipMaxX)tipX=_shXp(_shClosestIdx)-150;'
			. 'tip.style.left=tipX+"px";'
			. 'tip.style.top=(PAD_T+10)+"px";'
			. 'tip.style.opacity="1";'
			. '}'
			. '_shSvgEl.addEventListener("touchstart",_shHandleTouch,{passive:false});'
			. '_shSvgEl.addEventListener("touchmove",_shHandleTouch,{passive:false});'
			. '_shSvgEl.addEventListener("touchend",function(){setTimeout(function(){var tip=document.getElementById("aviShTooltip");if(tip)tip.style.opacity="0";},1500);});'
			. '}'
			. 'if(statEl){'
			. 'var _shFirst=_shScores.find(function(v){return v!=null;});'
			. 'var _shLast=null;for(var li=_shScores.length-1;li>=0;li--){if(_shScores[li]!=null){_shLast=_shScores[li];break;}}'
			. 'var _shDelta=(_shFirst!=null&&_shLast!=null)?(_shLast-_shFirst):null;'
			. 'var _shBestRank=_shRankValues.length?Math.min.apply(null,_shRankValues):null;'
			. 'statEl.innerHTML='
			. '(_shFirst!=null?\'<div class="avi-sh-stat-item">\'+(_t3.sh_start||"Start")+\': <strong>\'+_shFirst+\'</strong></div>\':"")'
			. '+(_shLast!=null?\'<div class="avi-sh-stat-item">\'+(_t3.sh_now||"Now")+\': <strong>\'+_shLast+\'</strong></div>\':"")'
			. '+(_shDelta!=null?\'<div class="avi-sh-stat-item">\'+(_shDelta>=0?"\\u2197 +":"\\u2198 ")+_shDelta+\' pts</div>\':"")'
			. '+(_shBestRank!=null?\'<div class="avi-sh-stat-item">\'+(_t3.sh_best_rank||"Best rank")+\': <strong>#\'+Math.round(_shBestRank*10)/10+\'</strong></div>\':"")'
			. ';'
			. '}'
			. '}'
			. 'var _shCache={};'
			. 'function _shFetch(period,keyword){'
			. 'if(!window.aviEmbedProfileId||!window.aviEmbedToken)return;'
			. 'var _shCacheKey=(period||"30d")+"|"+(keyword||"");'
			. 'if(_shCache[_shCacheKey]){_shData=_shCache[_shCacheKey];_shDrawSvg();return;}'
			. 'var url=window.aviEmbedRestUrl+"embed/score-history?profile_id="+window.aviEmbedProfileId+"&period="+(period||"30d");'
			. 'if(keyword)url+="&keyword="+encodeURIComponent(keyword);'
			. 'fetch(url,{headers:{"X-Embed-Token":window.aviEmbedToken||""}})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){if(!d)return;_shData=d;_shCache[_shCacheKey]=d;_shDrawSvg();})'
			. '.catch(function(){});'
			. '}'
			. '_shCtrl.querySelectorAll("[data-sh-period]").forEach(function(btn){'
			. 'btn.addEventListener("click",function(){'
			. '_shCtrl.querySelectorAll("[data-sh-period]").forEach(function(b){b.classList.remove("avi-sh-period-btn--active");});'
			. 'btn.classList.add("avi-sh-period-btn--active");'
			. '_shActivePeriod=btn.getAttribute("data-sh-period");'
			. '_shFetch(_shActivePeriod,_shKwSelect.value);'
			. '});'
			. '});'
			. '_shBtnScore.addEventListener("click",function(){'
			. '_shShowScore=!_shShowScore;'
			. '_shBtnScore.classList.toggle("avi-sh-curve-btn--active",_shShowScore);'
			. '_shDrawSvg();'
			. '});'
			. '_shBtnRank.addEventListener("click",function(){'
			. '_shShowRank=!_shShowRank;'
			. '_shBtnRank.classList.toggle("avi-sh-curve-btn--active",_shShowRank);'
			. '_shDrawSvg();'
			. '});'
			. '_shKwSelect.addEventListener("change",function(){'
			. '_shFetch(_shActivePeriod,_shKwSelect.value);'
			. '});'
			. 'var _shInfoBtn=_shTitleDiv.querySelector("#aviShInfoBtn");'
			. 'if(_shInfoBtn){'
			. '_shInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.sh_info_title||"Score & Rank History")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.sh_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.sh_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.sh_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.sh_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.sh_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.sh_info_s3_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.sh_info_s4_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.sh_info_s4_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviShInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviShInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var _shTooltip=document.createElement("div");'
			. '_shTooltip.className="avi-sh-tooltip";'
			. '_shTooltip.id="aviShTooltip";'
			. '_shSvgWrap.appendChild(_shTooltip);'
			. '_tabHistory.appendChild(_shWrap);'
			. '_tabHistory.appendChild(exp);'
			. '_shFetch("30d","");'
			. '_scorePanel.appendChild(inner);'
			. '}'
			. 'function _initCatAutocomplete(inputId,resultsId,hiddenId,isAdditional){'
			. 'var input=document.getElementById(inputId);'
			. 'var results=document.getElementById(resultsId);'
			. 'if(!input||!results)return;'
			. 'var _debounce=null;'
			. 'input.addEventListener("input",function(){'
			. 'clearTimeout(_debounce);'
			. 'var q=input.value.trim();'
			. 'if(q.length<2){results.style.display="none";return;}'
			. '_debounce=setTimeout(function(){'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/gbp-categories?q="'
			. '+encodeURIComponent(q)+"&lang="+_embedLang'
			. '+"&profile_id="+(window.aviEmbedProfileId||"")'
			. '+"&key_id="+encodeURIComponent(window.aviEmbedKeyId||""),'
			. '{headers:{"X-Embed-Token":window.aviEmbedToken||""}})'
			. '.then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(!data.categories||!data.categories.length){results.style.display="none";return;}'
			. 'results.innerHTML="";'
			. 'data.categories.slice(0,10).forEach(function(cat){'
			. 'var item=document.createElement("div");'
			. 'item.className="avi-score-cat-result-item";'
			. 'item.textContent=cat.displayName;'
			. 'item.addEventListener("click",function(){'
			. 'if(!isAdditional){'
			. 'input.value=cat.displayName;'
			. 'var hid=document.getElementById(hiddenId);'
			. 'if(hid)hid.value=cat.name;'
			. '}else{_addAdditionalCat(cat);input.value="";}'
			. 'results.style.display="none";'
			. '});'
			. 'results.appendChild(item);'
			. '});'
			. 'results.style.display="block";'
			. '}).catch(function(){results.style.display="none";});'
			. '},300);'
			. '});'
			. 'document.addEventListener("click",function(e){'
			. 'if(!input.contains(e.target)&&!results.contains(e.target)){results.style.display="none";}'
			. '});'
			. '}'
			. 'function _scoreGbpTimeStr(t){'
			. 'if(!t)return "";'
			. 'if(typeof t==="string")return t.length>=5?t.substring(0,5):t;'
			. 'if(typeof t==="object"&&t.hours!=null){'
			. 'var h=String(t.hours).padStart(2,"0");'
			. 'var m=String(t.minutes!=null?t.minutes:0).padStart(2,"0");'
			. 'return h+":"+m;'
			. '}'
			. 'return "";'
			. '}'
			. 'function _openScoreEditModal(field){'
			. 'if(!_scoreEditModal)return;'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var titles={name:_t.edit_name,website:_t.edit_website,phone:_t.edit_phone,hours:_t.edit_hours,'
			. 'description:_t.edit_description,categories:_t.edit_categories,address:_t.edit_address,'
			. 'openInfo:(_t.crit_open_status||"Business status")};'
			. 'var icons={name:"\\uD83C\\uDFE2",website:"\\uD83C\\uDF10",phone:"\\uD83D\\uDCDE",hours:"\\uD83D\\uDD50",'
			. 'description:"\\uD83D\\uDCDD",categories:"\\uD83D\\uDCC2",address:"\\uD83D\\uDCCD",openInfo:"\\uD83D\\uDFE2"};'
			. 'var bodyHtml="";'
			. 'if(field==="openInfo"){'
			. 'var _curStatus=(window.aviEmbedScoreData&&window.aviEmbedScoreData.open_info_status)||"";'
			. 'var _oiOptions=['
			. '{val:"OPEN",label:"\ud83d\udfe2 "+(_t.open_status_open||"Open \u2014 Normal business hours")},'
			. '{val:"OPEN_FOR_BUSINESS",label:"\ud83d\udfe2 "+(_t.open_status_open_no_hours||"Open \u2014 No main hours displayed")},'
			. '{val:"CLOSED_TEMPORARILY",label:"\ud83d\udfe1 "+(_t.open_status_temp||"Temporarily closed \u2014 will reopen")},'
			. '{val:"CLOSED_PERMANENTLY",label:"\ud83d\udd34 "+(_t.open_status_perm||"Permanently closed \u2014 verify urgently")}'
			. '];'
			. 'bodyHtml=\'<div class="avi-score-edit-lodging-warn">\u26a0\ufe0f \'+(_t.open_info_warn||"Modifying this status will update your Google Business Profile immediately.")+\'</div>\';'
			. 'bodyHtml+=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+(_t.crit_open_status||"Business status")+\'</label><select id="aviScoreOpenInfoVal" class="avi-score-edit-input">\';'
			. '_oiOptions.forEach(function(o){'
			. 'bodyHtml+=\'<option value="\'+o.val+\'"\'+(_curStatus===o.val?\' selected="selected"\':\'\')+">"+(o.label)+"</option>";'
			. '});'
			. 'bodyHtml+=\'</select></div>\';'
			. '}else if(field==="name"){'
			. 'bodyHtml=\'<div class="avi-score-edit-lodging-warn">\u26a0\ufe0f \'+_t.name_warn+\'</div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.edit_name'
			. '+\'</label><input type="text" id="aviScoreEditVal" class="avi-score-edit-input" value="\'+(sd.name_value||"")+\'" maxlength="100" /></div>\';'
			. '}else if(field==="website"){'
			. 'bodyHtml=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">URL</label>\''
			. '+\'<input type="url" id="aviScoreEditVal" class="avi-score-edit-input" value="\'+(sd.website_url||"")+\'" placeholder="https://..." /></div>\';'
			. '}else if(field==="phone"){'
			. 'bodyHtml=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.edit_phone'
			. '+\'</label><input type="tel" id="aviScoreEditVal" class="avi-score-edit-input" value="\'+(sd.phone_value||"")+\'" placeholder="+33612345678" />\''
			. '+\'<small style="color:#94a3b8;font-size:11px;margin-top:4px;display:block">\''
			. '+\'Format: +[country code][number] \u2014 ex: +33612345678, +34612345678, +14155552671\''
			. '+\'</small></div>\';'
			. '}else if(field==="description"){'
			. 'bodyHtml=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.edit_description'
			. '+\'</label><textarea id="aviScoreEditVal" class="avi-score-edit-input">\'+(sd.description_value||"")+\'</textarea></div>\';'
			. '}else if(field==="address"){'
			. 'var lines=(sd.address_lines||[]).join(", ");'
			. 'bodyHtml=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_street'
			. '+\'</label><input type="text" id="aviScoreEditAddrLines" class="avi-score-edit-input" value="\'+lines+\'" /></div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_neighborhood'
			. '+\'</label><input type="text" id="aviScoreEditAddrNeighborhood" class="avi-score-edit-input" value="\'+(sd.address_neighborhood||"")+\'" /></div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_city'
			. '+\'</label><input type="text" id="aviScoreEditAddrCity" class="avi-score-edit-input" value="\'+(sd.address_locality||"")+\'" /></div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_region'
			. '+\'</label><input type="text" id="aviScoreEditAddrRegion" class="avi-score-edit-input" value="\'+(sd.address_region||"")+\'" /></div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_postal'
			. '+\'</label><input type="text" id="aviScoreEditAddrPostal" class="avi-score-edit-input" value="\'+(sd.address_postal||"")+\'" /></div>\''
			. '+\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.addr_country'
			. '+\'</label><input type="text" id="aviScoreEditAddrCountry" class="avi-score-edit-input" value="\'+(sd.address_country||"")+\'" maxlength="2" placeholder="FR" /></div>\';'
			. '}else if(field==="hours"){'
			. '/* #SprintL2-hours-fix — grille éditable même sans périodes (mode Fix) */'
			. 'var days=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"];'
			. 'var dayLabels={MONDAY:"Monday",TUESDAY:"Tuesday",WEDNESDAY:"Wednesday",THURSDAY:"Thursday",FRIDAY:"Friday",SATURDAY:"Saturday",SUNDAY:"Sunday"};'
			. 'if(_embedLang==="fr")dayLabels={MONDAY:"Lundi",TUESDAY:"Mardi",WEDNESDAY:"Mercredi",THURSDAY:"Jeudi",FRIDAY:"Vendredi",SATURDAY:"Samedi",SUNDAY:"Dimanche"};'
			. 'else if(_embedLang==="es")dayLabels={MONDAY:"Lunes",TUESDAY:"Martes",WEDNESDAY:"Mi\u00e9rcoles",THURSDAY:"Jueves",FRIDAY:"Viernes",SATURDAY:"S\u00e1bado",SUNDAY:"Domingo"};'
			. 'var periodsMap={};'
			. '(sd.hours_periods||[]).forEach(function(p){if(p&&p.openDay)periodsMap[p.openDay]=p;});'
			. 'bodyHtml=\'<div class="avi-score-hours-grid" id="aviScoreHoursGrid">\';'
			. 'days.forEach(function(day){'
			. 'var p=periodsMap[day];'
			. 'var open=_scoreGbpTimeStr(p?p.openTime:null);'
			. 'var close=_scoreGbpTimeStr(p?p.closeTime:null);'
			. 'bodyHtml+=\'<span class="avi-score-hours-day">\'+(dayLabels[day]||day)+\'</span>\''
			. '+\'<input type="time" class="avi-score-hours-input" data-day="\'+day+\'" data-type="open" value="\'+open+\'" />\''
			. '+\'<input type="time" class="avi-score-hours-input" data-day="\'+day+\'" data-type="close" value="\'+close+\'" />\';'
			. '});'
			. 'bodyHtml+="</div>";'
			. '}else if(field==="specialHours"){'
			. 'bodyHtml=\'<div class="avi-score-edit-field" style="padding:12px 0;">\''
			. '+\'<p style="margin:0 0 12px;font-size:13px;color:#555;">\''
			. '+(_t.special_hours_edit_info||"Special hours must be managed directly on Google Business Profile.")'
			. '+\'</p>\''
			. '+\'<a href="https://business.google.com/dashboard" target="_blank" class="avi-fix-now-btn" style="display:inline-block;padding:8px 16px;background:#e67e22;color:#fff;border-radius:6px;text-decoration:none;font-size:13px;">\''
			. '+(_t.guardian_fix_gbp||"Fix on GBP \u2192")'
			. '+\'</a></div>\';'
			. '}else if(field==="serviceArea"){'
			. 'bodyHtml=\'<div class="avi-score-edit-field" style="padding:12px 0;">\''
			. '+\'<p style="margin:0 0 12px;font-size:13px;color:#555;">\''
			. '+(_t.service_area_edit_info||"Service area must be managed directly on Google Business Profile.")'
			. '+\'</p>\''
			. '+\'<a href="https://business.google.com/dashboard" target="_blank" class="avi-fix-now-btn" style="display:inline-block;padding:8px 16px;background:#e67e22;color:#fff;border-radius:6px;text-decoration:none;font-size:13px;">\''
			. '+(_t.guardian_fix_gbp||"Fix on GBP \u2192")'
			. '+\'</a></div>\';'
			. '}else if(field==="categories"){'
			. 'if(_isLodging()){'
			. 'bodyHtml=\'<div class="avi-score-edit-lodging-warn">\u26a0\ufe0f \'+_t.lodging_posts_warn+\'</div>\''
			. '+\'<div class="avi-score-edit-lodging-warn">\u26a0\ufe0f \'+_t.cat_lodging_warn+\'</div>\';'
			. '}'
			. 'bodyHtml+=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.cat_primary+\'</label><div class="avi-score-cat-search"><input type="text" id="aviScoreCatSearch" class="avi-score-edit-input" placeholder="\'+_t.cat_search_placeholder+\'" value="\'+(sd.primary_category_name||"")+\'" autocomplete="off" /><div class="avi-score-cat-results" id="aviScoreCatResults"></div></div><input type="hidden" id="aviScoreCatPrimaryId" value="\'+(sd.primary_category_id||"")+\'" /></div>\';'
			. 'bodyHtml+=\'<div class="avi-score-edit-field"><label class="avi-score-edit-label">\'+_t.cat_additional+\'</label><div id="aviScoreCatAdditional" class="avi-score-cat-selected"></div><div class="avi-score-cat-search" style="margin-top:6px"><input type="text" id="aviScoreCatAddSearch" class="avi-score-edit-input" placeholder="\'+_t.cat_search_placeholder+\'" autocomplete="off" /><div class="avi-score-cat-results" id="aviScoreCatAddResults"></div></div></div>\';'
			. '}'
			. '_scoreEditModal.innerHTML=\'<div class="avi-score-edit-modal"><div class="avi-score-edit-modal-header"><span class="avi-score-edit-modal-title">\'+(icons[field]||"")+" "+(titles[field]||field)+\'</span><button type="button" class="avi-score-edit-modal-close" id="aviScoreEditClose">\u00d7</button></div><div class="avi-score-edit-modal-body">\'+bodyHtml+\'</div><div class="avi-score-edit-modal-footer"><span class="avi-score-edit-error" id="aviScoreEditError">\'+_t.edit_error+\'</span><span class="avi-score-edit-success" id="aviScoreEditSuccess">\'+_t.edit_success+\'</span><button type="button" class="avi-score-edit-btn-cancel" id="aviScoreEditCancel">\'+_t.cancel+\'</button><button type="button" class="avi-score-edit-btn-save" id="aviScoreEditSave">\'+_t.save+\'</button></div></div>\';'
			. '_scoreEditModal.style.display="flex";'
			. 'var closeBtn=document.getElementById("aviScoreEditClose");'
			. 'var cancelBtn=document.getElementById("aviScoreEditCancel");'
			. 'if(closeBtn)closeBtn.addEventListener("click",_closeScoreEditModal);'
			. 'if(cancelBtn)cancelBtn.addEventListener("click",_closeScoreEditModal);'
			. 'if(field==="categories"){'
			. '_initCatAutocomplete("aviScoreCatSearch","aviScoreCatResults","aviScoreCatPrimaryId",false);'
			. '_initCatAutocomplete("aviScoreCatAddSearch","aviScoreCatAddResults",null,true);'
			. '_renderAdditionalCats(sd.additional_categories||[]);'
			. '}'
			. 'var saveBtn=document.getElementById("aviScoreEditSave");'
			. 'if(saveBtn){saveBtn.addEventListener("click",function(){_submitScoreEdit(field,_t);});}'
			. '}'
			. 'function _submitScoreEdit(field,_t){'
			. 'var saveBtn=document.getElementById("aviScoreEditSave");'
			. 'var errEl=document.getElementById("aviScoreEditError");'
			. 'var okEl=document.getElementById("aviScoreEditSuccess");'
			. 'if(!saveBtn)return;'
			. 'saveBtn.disabled=true;'
			. 'saveBtn.textContent=_t.saving;'
			. 'if(errEl)errEl.style.display="none";'
			. 'if(okEl)okEl.style.display="none";'
			. 'var value;'
			. 'if(field==="openInfo"){value=(document.getElementById("aviScoreOpenInfoVal")||{}).value||"";}'
			. 'else if(field==="name"){value=(document.getElementById("aviScoreEditVal")||{}).value||"";}'
			. 'else if(field==="website"){value=(document.getElementById("aviScoreEditVal")||{}).value||"";}'
			. 'else if(field==="phone"){value=(document.getElementById("aviScoreEditVal")||{}).value||"";}'
			. 'else if(field==="description"){value=(document.getElementById("aviScoreEditVal")||{}).value||"";}'
			. 'else if(field==="address"){'
			. 'value={addressLines:[(document.getElementById("aviScoreEditAddrLines")||{}).value||""],'
			. 'sublocality:(document.getElementById("aviScoreEditAddrNeighborhood")||{}).value||"",'
			. 'locality:(document.getElementById("aviScoreEditAddrCity")||{}).value||"",'
			. 'region:(document.getElementById("aviScoreEditAddrRegion")||{}).value||"",'
			. 'postal:(document.getElementById("aviScoreEditAddrPostal")||{}).value||"",'
			. 'country:(document.getElementById("aviScoreEditAddrCountry")||{}).value||""};'
			. '}else if(field==="hours"){'
			. 'var periods=[];'
			. 'var opens=document.querySelectorAll(".avi-score-hours-input[data-type=\'open\']");'
			. 'var closes=document.querySelectorAll(".avi-score-hours-input[data-type=\'close\']");'
			. 'opens.forEach(function(inp,i){'
			. 'if(inp.value&&closes[i]&&closes[i].value){'
			. 'periods.push({openDay:inp.getAttribute("data-day"),openTime:inp.value,closeTime:closes[i].value});'
			. '}'
			. '});'
			. 'value=periods;'
			. '}else if(field==="categories"){'
			. 'value={primary:(document.getElementById("aviScoreCatPrimaryId")||{}).value||"",'
			. 'additional:_additionalCats.map(function(c){return c.name;})};'
			. '}'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/update-gbp",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,key_id:window.aviEmbedKeyId,field:field,value:value})'
			. '})'
			. '.then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'saveBtn.disabled=false;'
			. 'saveBtn.textContent=_t.save;'
			. 'if(data.success){'
			. 'if(okEl)okEl.style.display="inline";'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'if(field==="openInfo"){sd.open_info_status=value;sd.is_open=(value==="OPEN"||value==="OPEN_FOR_BUSINESS");sd.is_closed_temp=(value==="CLOSED_TEMPORARILY");sd.is_closed_perm=(value==="CLOSED_PERMANENTLY");}'
			. 'else if(field==="name"){sd.business_name=value;sd.name_value=value;sd.has_name=!!value;}'
			. 'if(field==="website"){sd.website_url=value;sd.has_website=!!value;}'
			. 'if(field==="phone"){sd.phone_value=value;sd.has_phone=!!value;}'
			. 'if(field==="description"){sd.description_value=value;sd.has_description=!!value;}'
			. 'if(field==="hours"){sd.hours_periods=value;sd.has_hours=value.length>0;}'
			. 'if(field==="address"){sd.address_locality=value.locality;sd.has_address=!!value.locality;}'
			. 'if(field==="categories"){sd.primary_category_id=value.primary;sd.additional_categories=_additionalCats;sd.has_category=!!value.primary;}'
			. 'window.aviEmbedScoreData=sd;'
			. 'if(field==="categories")_applyLodgingPostsTab();'
			. 'if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. 'setTimeout(function(){_closeScoreEditModal();_scoreRender();},1500);'
			. '}else{'
			. 'if(errEl){errEl.textContent=data.message||_t.edit_error;errEl.style.display="inline";}'
			. '}'
			. '})'
			. '.catch(function(){'
			. 'saveBtn.disabled=false;'
			. 'saveBtn.textContent=_t.save;'
			. 'if(errEl)errEl.style.display="inline";'
			. '});'
			. '}'
			. '_scoreRender();'
			. 'var _scoreWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_scoreWrap.appendChild(_scorePanel);'
			. '_scorePanel.addEventListener("click",function(e){'
			. 'if(e.target&&e.target.id==="aviScoreSyncBtn"){_syncProfileFromGoogle(e.target);return;}'
			. 'var _sfBtn=e.target.closest("[data-score-field]");'
			. 'if(_sfBtn&&_scorePanel.contains(_sfBtn)){'
			. 'e.preventDefault();'
			. '_openScoreEditModal(_sfBtn.getAttribute("data-score-field"));'
			. '}'
			. '});'
			. 'function _rvStars(rating){'
			. 'var map={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5};'
			. 'var n=map[rating]||0;'
			. 'return "⭐".repeat(n)+"☆".repeat(5-n);'
			. '}'
			. 'function _rvRelDate(dt){'
			. 'if(!dt)return "";'
			. 'var d=new Date(dt),now=new Date();'
			. 'var diff=Math.floor((now-d)/86400000);'
			. 'if(diff===0)return _t.today;if(diff===1)return _t.yesterday;'
			. 'if(diff<30)return diff+_t.rel_d_ago;'
			. 'if(diff<365)return Math.floor(diff/30)+_t.rel_mo_ago;'
			. 'return Math.floor(diff/365)+_t.rel_y_ago;'
			. '}'
			. '_reviewsPanel=document.createElement("div");'
			. '_reviewsPanel.className="avi-reviews-panel";'
			. '_reviewsPanel.id="aviEmbedReviewsPanel";'
			. 'var _rvPage=1;'
			. 'var _rvPerPage=10;'
			. 'var _rvFilter="all";'
			. 'var _rvSort="recent";'
			. 'var _rvStarFilter=0;'
			. 'var _rvYear="all";'
			. 'var _yrSel=null;'
			. 'var _rvMonth="all";'
			. 'var _rvWeek="all";'
			. 'var _rvReplyFilter="all";'
			. 'var _taResizeInit=null;'
			. 'function _wrapReplyTa(ta){'
			. 'var wrap=document.createElement("div");'
			. 'wrap.className="avi-rv-reply-ta-wrap";'
			. 'wrap.appendChild(ta);'
			. 'var handle=document.createElement("div");'
			. 'handle.className="avi-rv-reply-resize";'
			. 'handle.textContent="\\u283F resize";'
			. 'handle.addEventListener("mousedown",function(e){'
			. 'e.preventDefault();'
			. 'var startY=e.clientY;'
			. 'var startH=ta.offsetHeight;'
			. 'function onMove(ev){'
			. 'var newH=Math.max(120,Math.min(500,startH+ev.clientY-startY));'
			. 'ta.style.height=newH+"px";'
			. '}'
			. 'function onUp(){'
			. 'document.removeEventListener("mousemove",onMove);'
			. 'document.removeEventListener("mouseup",onUp);'
			. '_taResizeInit=null;'
			. '}'
			. '_taResizeInit=handle;'
			. 'document.addEventListener("mousemove",onMove);'
			. 'document.addEventListener("mouseup",onUp);'
			. '});'
			. 'wrap.appendChild(handle);'
			. 'return wrap;'
			. '}'
			. 'function _showEmbedToast(msg,isErr,onClick){'
			. 'var toast=document.createElement("div");'
			. 'toast.className="avi-toast"+(isErr?" avi-toast--error":" avi-toast--success");'
			. 'toast.textContent=isErr?msg:("\\u2705 "+msg);'
			. 'if(typeof onClick==="function"){'
			. 'toast.style.cursor="pointer";'
			. 'toast.addEventListener("click",onClick);'
			. '}'
			. 'document.body.appendChild(toast);'
			. 'setTimeout(function(){'
			. 'toast.classList.add("avi-toast--hide");'
			. 'setTimeout(function(){toast.remove();},400);'
			. '},2500);'
			. '}'
			. 'function _reviewEditExisting(btn){'
			. 'var currentReply=decodeURIComponent(btn.getAttribute("data-current-reply")||"");'
			. 'var form=btn.closest("[data-reply-form]")||btn.parentNode;'
			. 'var ta=form?form.querySelector("textarea"):null;'
			. 'if(ta){'
			. 'ta.value=currentReply;'
			. 'ta.focus();'
			. 'ta.dispatchEvent(new Event("input"));'
			. '}'
			. '}'
			. 'function _reviewAiWrite(btn){'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _aiMode=btn.getAttribute("data-ai-mode")||"write";'
			. 'var _aiLabel=_aiMode==="rewrite"?(_t.avi_rewrite_reply||"\\u2728 Rewrite with AVI"):(_t.avi_writes_review||"\\u2728 AVI writes");'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var reviewer=btn.getAttribute("data-reviewer")||"";'
			. 'var rating=parseInt(btn.getAttribute("data-rating"),10)||5;'
			. 'var reviewTxt=decodeURIComponent(btn.getAttribute("data-review-text")||"");'
			. 'var form=btn.closest("[data-reply-form]")||btn.parentNode;'
			. 'var ta=form?form.querySelector("textarea"):null;'
			. 'btn.disabled=true;'
			. 'btn.textContent=_t.generating_reply||"\\u2728 Generating...";'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/ai-review-reply",{'
			. 'method:"POST",'
			. 'headers:{'
			. '"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken||""'
			. '},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'key_id:window.aviEmbedKeyId,'
			. 'reviewer_name:reviewer,'
			. 'rating:rating,'
			. 'review_text:reviewTxt,'
			. 'lang:_embedLang,'
			. 'business_name:sd.business_name||""'
			. '})'
			. '})'
			. '.then(function(r){return r.json().then(function(d){return {ok:r.ok,d:d};});})'
			. '.then(function(res){'
			. 'btn.disabled=false;'
			. 'btn.textContent=_aiLabel;'
			. 'if(res.ok&&res.d.success&&res.d.reply){'
			. 'if(ta){'
			. 'ta.value=res.d.reply;'
			. 'var tw=ta.parentNode;'
			. 'if(tw&&tw.classList&&tw.classList.contains("avi-rv-reply-ta-wrap"))tw.style.display="block";'
			. 'else ta.style.display="block";'
			. 'ta.dispatchEvent(new Event("input"));'
			. '}'
			. 'var repTxt=form?form.querySelector(".avi-rv-expand-reply-text"):null;'
			. 'if(repTxt)repTxt.style.display="none";'
			. 'var regen=form?form.querySelector(".avi-review-ai-regen"):null;'
			. 'if(!regen&&form){'
			. 'regen=document.createElement("button");'
			. 'regen.type="button";'
			. 'regen.className="avi-review-ai-regen";'
			. 'regen.textContent=_t.regenerate_reply||"\\u21BA Regenerate";'
			. 'regen.addEventListener("click",function(){_reviewAiWrite(btn);});'
			. 'btn.parentNode.insertBefore(regen,btn.nextSibling);'
			. '}'
			. '}else{'
			. 'if(ta)ta.placeholder=_t.ai_reply_error||"AVI couldn\\u0027t generate a reply.";'
			. '}'
			. '})'
			. '.catch(function(){'
			. 'btn.disabled=false;'
			. 'btn.textContent=_aiLabel;'
			. '});'
			. '}'
			. 'function _reviewsRenderList(listZone){'
			. 'var rd=window.aviEmbedReviewsData||{reviews:[]};'
			. 'var starMap={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5};'
			. 'var filtered=(rd.reviews||[]).filter(function(rv){'
			. 'var ct=rv.create_time&&rv.create_time!=""?rv.create_time:null;'
			. 'var d=ct?new Date(ct):null;'
			. 'if(_rvYear!=="all"){'
			. 'if(!d||d.getFullYear()!==parseInt(_rvYear,10))return false;'
			. '}'
			. 'if(_rvMonth!=="all"){'
			. 'if(!d||d.getMonth()+1!==parseInt(_rvMonth,10))return false;'
			. '}'
			. 'if(_rvWeek!=="all"){'
			. 'if(!d)return false;'
			. 'var monday=new Date(_rvWeek);'
			. 'var sunday=new Date(monday);sunday.setDate(monday.getDate()+6);sunday.setHours(23,59,59,999);'
			. 'if(d<monday||d>sunday)return false;'
			. '}'
			. 'if(_rvReplyFilter==="replied"&&!rv.has_reply)return false;'
			. 'if(_rvReplyFilter==="unanswered"&&rv.has_reply)return false;'
			. 'if(_rvStarFilter>0&&(starMap[rv.star_rating]||0)!==_rvStarFilter)return false;'
			. 'return true;'
			. '});'
			. 'filtered.sort(function(a,b){'
			. 'if(_rvSort==="oldest")return new Date(a.create_time)-new Date(b.create_time);'
			. 'if(_rvSort==="lowest")return (starMap[a.star_rating]||0)-(starMap[b.star_rating]||0);'
			. 'if(_rvSort==="unanswered")return (a.has_reply?1:0)-(b.has_reply?1:0);'
			. 'return new Date(b.create_time)-new Date(a.create_time);'
			. '});'
			. 'var total=filtered.length;'
			. 'var totalPages=Math.max(1,Math.ceil(total/_rvPerPage));'
			. 'if(_rvPage>totalPages)_rvPage=totalPages;'
			. 'var start=(_rvPage-1)*_rvPerPage;'
			. 'var pageItems=filtered.slice(start,start+_rvPerPage);'
			. 'listZone.innerHTML="";'
			. 'var countDiv=document.createElement("div");'
			. 'countDiv.className="avi-rv-count";'
			. 'if(total===0){'
			. 'countDiv.textContent=_t.reviews_0;'
			. '}else{'
			. 'countDiv.textContent=_t.reviews_showing+(start+1)+"–"+Math.min(start+_rvPerPage,total)+_t.reviews_of+total+_t.reviews_suffix;'
			. '}'
			. 'listZone.appendChild(countDiv);'
			. 'if(pageItems.length===0){'
			. 'var noRv=document.createElement("div");'
			. 'noRv.style.cssText="background:#fff;border:1px solid #e2e8f0;'
			. 'border-radius:10px;padding:40px;text-align:center;color:#94a3b8;";'
			. 'noRv.innerHTML="<div style=\\"font-size:32px;\\">⭐</div>"'
			. '+"<div>"+_t.no_reviews_filter+"</div>";'
			. 'listZone.appendChild(noRv);'
			. '}else{'
			. 'var tbl=document.createElement("table");'
			. 'tbl.className="avi-rv-table";'
			. 'var thead=document.createElement("thead");'
			. 'thead.innerHTML="<tr>"'
			. '+"<th style=\\"width:36px;\\"></th>"'
			. '+"<th title=\\""+(_t.tip_th_reviewer||"")+"\\">"+_t.th_reviewer+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_stars||"")+"\\">"+_t.th_stars+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_date||"")+"\\">"+_t.th_date+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_review||"")+"\\">"+_t.th_review+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_replied||"")+"\\">"+_t.th_replied+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_actions||"")+"\\">"+_t.th_actions+"</th>"'
			. '+"<th title=\\""+(_t.tip_th_report||"")+"\\">"+(_t.th_report||"Report")+"</th>"'
			. '+"</tr>";'
			. 'tbl.appendChild(thead);'
			. 'var tbody=document.createElement("tbody");'
			. 'var starMap2={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5};'
			. 'pageItems.forEach(function(rv){'
			. 'var tr=document.createElement("tr");'
			. 'tr.style.cursor="pointer";'
			. 'var expandRow=null;'
			. 'var isExpanded=false;'
			. 'var tdAv=document.createElement("td");'
			. 'if(rv.reviewer_photo){'
			. 'var img=document.createElement("img");'
			. 'img.className="avi-rv-avatar-sm";'
			. 'img.src=rv.reviewer_photo;img.alt=rv.reviewer_name;'
			. 'tdAv.appendChild(img);'
			. '}else{'
			. 'var av=document.createElement("div");'
			. 'av.className="avi-rv-avatar-sm-initials";'
			. 'av.textContent=(rv.reviewer_name||"?")[0].toUpperCase();'
			. 'tdAv.appendChild(av);'
			. '}'
			. 'var tdName=document.createElement("td");'
			. 'tdName.style.fontWeight="600";tdName.style.color="#1e293b";'
			. 'tdName.textContent=rv.reviewer_name;'
			. 'var tdStars=document.createElement("td");'
			. 'var n=starMap2[rv.star_rating]||0;'
			. 'tdStars.innerHTML="<span class=\\"avi-rv-stars-sm\\">"'
			. '+"⭐".repeat(n)+"</span>"'
			. '+"<span style=\\"color:#94a3b8;font-size:10px;margin-left:4px;\\">"'
			. '+n+"/5</span>";'
			. 'var tdDate=document.createElement("td");'
			. 'tdDate.style.color="#94a3b8";tdDate.style.fontSize="11px";'
			. 'tdDate.textContent=_rvRelDate(rv.create_time);'
			. 'var tdSnip=document.createElement("td");'
			. 'var snip=document.createElement("div");'
			. 'snip.className="avi-rv-snippet";'
			. 'snip.textContent=(rv.comment||"").substring(0,80)+(rv.comment&&rv.comment.length>80?"...":"");'
			. 'tdSnip.appendChild(snip);'
			. 'var tdRep=document.createElement("td");'
			. 'tdRep.innerHTML=rv.has_reply'
			. '?"<span class=\\"avi-rv-badge-replied\\">"+_t.rv_replied_yes+"</span>"'
			. ':"<span class=\\"avi-rv-badge-pending\\">"+_t.rv_replied_no+"</span>";'
			. 'var tdAct=document.createElement("td");'
			. 'tdAct.style.whiteSpace="nowrap";'
			. 'var viewBtn=document.createElement("button");'
			. 'viewBtn.type="button";viewBtn.className="avi-rv-action-btn";'
			. 'viewBtn.textContent=_t.view_btn;'
			. 'var replyActBtn=null;'
			. 'if(!rv.has_reply){'
			. 'replyActBtn=document.createElement("button");'
			. 'replyActBtn.type="button";replyActBtn.className="avi-rv-action-btn reply";'
			. 'replyActBtn.textContent=_t.reply_btn;'
			. '}'
			. 'tdAct.appendChild(viewBtn);'
			. 'if(replyActBtn)tdAct.appendChild(replyActBtn);'
			. 'var _flagUrl="https://support.google.com/business/answer/4596773";'
			. 'var tdReport=document.createElement("td");'
			. 'tdReport.style.whiteSpace="nowrap";'
			. 'if(_flagUrl){'
			. 'var _flagBtn=document.createElement("a");'
			. '_flagBtn.href=_flagUrl;'
			. '_flagBtn.target="_blank";'
			. '_flagBtn.rel="noopener";'
			. '_flagBtn.className="avi-rv-flag-btn";'
			. '_flagBtn.title=_t.tip_th_report||_t.flag_review_tip||"Report this review to Google";'
			. '_flagBtn.textContent="\\uD83D\\uDEA9";'
			. 'tdReport.appendChild(_flagBtn);'
			. '}'
			. 'tr.appendChild(tdAv);tr.appendChild(tdName);tr.appendChild(tdStars);'
			. 'tr.appendChild(tdDate);tr.appendChild(tdSnip);'
			. 'tr.appendChild(tdRep);tr.appendChild(tdAct);tr.appendChild(tdReport);'
			. 'function _buildExpandRow(showReplyForm){'
			. 'var exTr=document.createElement("tr");'
			. 'exTr.className="avi-rv-expand-row";'
			. 'var exTd=document.createElement("td");'
			. 'exTd.colSpan=8;'
			. 'var exText=document.createElement("div");'
			. 'exText.className="avi-rv-expand-content";'
			. 'exText.textContent=rv.comment||"";'
			. 'exTd.appendChild(exText);'
			. 'if(rv.has_reply){'
			. 'var repDiv=document.createElement("div");'
			. 'repDiv.className="avi-rv-expand-reply";'
			. 'repDiv.setAttribute("data-reply-form","");'
			. 'var repHead=document.createElement("div");'
			. 'repHead.className="avi-rv-expand-reply-head";'
			. 'var repLabel=document.createElement("div");'
			. 'repLabel.className="avi-rv-expand-reply-label";'
			. 'repLabel.textContent=_t.your_reply+_rvRelDate(rv.reply_time);'
			. 'var repBtns=document.createElement("div");'
			. 'repBtns.className="avi-rv-expand-reply-btns";'
			. 'var editBtn=document.createElement("button");'
			. 'editBtn.type="button";'
			. 'editBtn.className="avi-review-edit-btn";'
			. 'editBtn.setAttribute("data-review-edit",rv.review_name||"");'
			. 'editBtn.setAttribute("data-current-reply",encodeURIComponent(rv.reply_comment||""));'
			. 'editBtn.textContent=_t.edit_reply||"\\u270F\\uFE0F";'
			. 'var rewriteBtn=document.createElement("button");'
			. 'rewriteBtn.type="button";'
			. 'rewriteBtn.className="avi-review-ai-btn";'
			. 'rewriteBtn.setAttribute("data-ai-mode","rewrite");'
			. 'rewriteBtn.setAttribute("data-review-ai",rv.review_name||"");'
			. 'rewriteBtn.setAttribute("data-reviewer",rv.reviewer_name||"");'
			. 'rewriteBtn.setAttribute("data-rating",String(starMap2[rv.star_rating]||5));'
			. 'rewriteBtn.setAttribute("data-review-text",encodeURIComponent(rv.comment||""));'
			. 'rewriteBtn.textContent=_t.avi_rewrite_reply||"\\u2728";'
			. 'repBtns.appendChild(editBtn);'
			. 'repBtns.appendChild(rewriteBtn);'
			. 'repHead.appendChild(repLabel);'
			. 'repHead.appendChild(repBtns);'
			. 'var repText=document.createElement("div");'
			. 'repText.className="avi-rv-expand-reply-text";'
			. 'repText.textContent=rv.reply_comment;'
			. 'var editTa=document.createElement("textarea");'
			. 'editTa.className="avi-rv-reply-ta";'
			. 'editTa.placeholder=_t.write_reply_ph;'
			. 'editTa.value="";'
			. 'var editTaWrap=_wrapReplyTa(editTa);'
			. 'editTaWrap.style.display="none";'
			. 'var editActs=document.createElement("div");'
			. 'editActs.className="avi-rv-reply-acts";'
			. 'editActs.style.display="none";'
			. 'var updateBtn=document.createElement("button");'
			. 'updateBtn.type="button";'
			. 'updateBtn.className="avi-rv-reply-submit";'
			. 'updateBtn.textContent=_t.publish_reply;'
			. 'function _showReplyEdit(){'
			. 'repText.style.display="none";'
			. 'editTaWrap.style.display="block";'
			. 'editActs.style.display="flex";'
			. '}'
			. 'editBtn.addEventListener("click",function(){'
			. '_showReplyEdit();'
			. '_reviewEditExisting(editBtn);'
			. '});'
			. 'rewriteBtn.addEventListener("click",function(){'
			. '_showReplyEdit();'
			. 'editTa.value="";'
			. '_reviewAiWrite(rewriteBtn);'
			. '});'
			. 'updateBtn.addEventListener("click",function(){'
			. 'var txt=editTa.value.trim();if(!txt)return;'
			. 'updateBtn.textContent=_t.publishing_reply;updateBtn.disabled=true;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/reply-review",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'key_id:window.aviEmbedKeyId,'
			. 'review_name:rv.review_name,'
			. 'reply_text:txt'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. '_showEmbedToast(_t.reply_published||"Reply published on Google!",false);'
			. 'setTimeout(function(){'
			. 'rv.reply_comment=txt;rv.reply_time=new Date().toISOString();'
			. 'editBtn.setAttribute("data-current-reply",encodeURIComponent(txt));'
			. 'repText.textContent=txt;'
			. 'repText.style.display="block";'
			. 'editTaWrap.style.display="none";'
			. 'editActs.style.display="none";'
			. 'repLabel.textContent=_t.your_reply+_rvRelDate(rv.reply_time);'
			. 'updateBtn.textContent=_t.publish_reply;updateBtn.disabled=false;'
			. '},2500);'
			. '}else{'
			. 'updateBtn.textContent=_t.publish_reply;updateBtn.disabled=false;'
			. '_showEmbedToast(data.message||_t.err_generic,true);'
			. '}'
			. '}).catch(function(){'
			. 'updateBtn.textContent=_t.publish_reply;updateBtn.disabled=false;'
			. '_showEmbedToast(_t.err_network,true);'
			. '});'
			. '});'
			. 'editActs.appendChild(updateBtn);'
			. 'repDiv.appendChild(repHead);'
			. 'repDiv.appendChild(repText);'
			. 'repDiv.appendChild(editTaWrap);'
			. 'repDiv.appendChild(editActs);'
			. 'exTd.appendChild(repDiv);'
			. '}'
			. 'if(showReplyForm&&!rv.has_reply){'
			. 'var rf=document.createElement("div");'
			. 'rf.className="avi-rv-reply-form";'
			. 'rf.setAttribute("data-reply-form","");'
			. 'var actsTop=document.createElement("div");'
			. 'actsTop.className="avi-rv-reply-acts-top";'
			. 'var acts=document.createElement("div");'
			. 'acts.className="avi-rv-reply-acts";'
			. 'var cancelBtn=document.createElement("button");'
			. 'cancelBtn.type="button";cancelBtn.className="avi-rv-reply-cancel";'
			. 'cancelBtn.textContent=_t.cancel_reply;'
			. 'cancelBtn.addEventListener("click",function(){'
			. 'if(expandRow&&expandRow.parentNode){'
			. 'expandRow.parentNode.removeChild(expandRow);'
			. '}'
			. 'tr.classList.remove("avi-rv-row-expanded");'
			. 'isExpanded=false;expandRow=null;'
			. '});'
			. 'var aiBtn=document.createElement("button");'
			. 'aiBtn.type="button";'
			. 'aiBtn.className="avi-review-ai-btn";'
			. 'aiBtn.setAttribute("data-review-ai",rv.review_name||"");'
			. 'aiBtn.setAttribute("data-reviewer",rv.reviewer_name||"");'
			. 'aiBtn.setAttribute("data-rating",String(starMap2[rv.star_rating]||5));'
			. 'aiBtn.setAttribute("data-review-text",encodeURIComponent(rv.comment||""));'
			. 'aiBtn.textContent=_t.avi_writes_review||"\\u2728";'
			. 'aiBtn.addEventListener("click",function(){_reviewAiWrite(aiBtn);});'
			. 'actsTop.appendChild(cancelBtn);'
			. 'actsTop.appendChild(aiBtn);'
			. 'var ta=document.createElement("textarea");'
			. 'ta.className="avi-rv-reply-ta";'
			. 'ta.placeholder=_t.write_reply_ph;'
			. 'var taWrap=_wrapReplyTa(ta);'
			. 'var submitBtn=document.createElement("button");'
			. 'submitBtn.type="button";submitBtn.className="avi-rv-reply-submit";'
			. 'submitBtn.textContent=_t.publish_reply;'
			. 'submitBtn.addEventListener("click",function(){'
			. 'var txt=ta.value.trim();if(!txt)return;'
			. 'submitBtn.textContent=_t.publishing_reply;submitBtn.disabled=true;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/reply-review",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'key_id:window.aviEmbedKeyId,'
			. 'review_name:rv.review_name,'
			. 'reply_text:txt'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. '_showEmbedToast(_t.reply_published||"Reply published on Google!",false);'
			. 'setTimeout(function(){'
			. 'rv.has_reply=true;rv.reply_comment=txt;rv.reply_time=new Date().toISOString();'
			. 'tdRep.innerHTML="<span class=\\"avi-rv-badge-replied\\">"+_t.rv_replied_yes+"</span>";'
			. 'if(replyActBtn)replyActBtn.style.display="none";'
			. 'if(window.aviEmbedUnansweredCount>0){'
			. 'window.aviEmbedUnansweredCount--;_reviewsUpdateBadge();'
			. '}'
			. 'if(expandRow&&expandRow.parentNode){'
			. 'expandRow.parentNode.removeChild(expandRow);'
			. '}'
			. 'expandRow=_buildExpandRow(false);'
			. 'tr.parentNode.insertBefore(expandRow,tr.nextSibling);'
			. 'submitBtn.textContent=_t.publish_reply;submitBtn.disabled=false;'
			. '},2500);'
			. '}else{'
			. 'submitBtn.textContent=_t.publish_reply;submitBtn.disabled=false;'
			. '_showEmbedToast(data.message||_t.err_generic,true);'
			. '}'
			. '}).catch(function(){'
			. 'submitBtn.textContent=_t.publish_reply;submitBtn.disabled=false;'
			. '_showEmbedToast(_t.err_network,true);'
			. '});'
			. '});'
			. 'acts.appendChild(submitBtn);'
			. 'rf.appendChild(actsTop);'
			. 'rf.appendChild(taWrap);'
			. 'rf.appendChild(acts);'
			. 'exTd.appendChild(rf);'
			. 'setTimeout(function(){ta.focus();},50);'
			. '}'
			. 'exTr.appendChild(exTd);'
			. 'return exTr;'
			. '}'
			. 'viewBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(isExpanded&&expandRow){'
			. 'expandRow.parentNode.removeChild(expandRow);'
			. 'tr.classList.remove("avi-rv-row-expanded");'
			. 'isExpanded=false;expandRow=null;'
			. '}else{'
			. 'expandRow=_buildExpandRow(false);'
			. 'tbody.insertBefore(expandRow,tr.nextSibling);'
			. 'tr.classList.add("avi-rv-row-expanded");'
			. 'isExpanded=true;'
			. '}'
			. '});'
			. 'if(replyActBtn){'
			. 'replyActBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(expandRow&&expandRow.parentNode){'
			. 'expandRow.parentNode.removeChild(expandRow);'
			. '}'
			. 'expandRow=_buildExpandRow(true);'
			. 'tbody.insertBefore(expandRow,tr.nextSibling);'
			. 'tr.classList.add("avi-rv-row-expanded");'
			. 'isExpanded=true;'
			. '});'
			. '}'
			. 'tbody.appendChild(tr);'
			. '});'
			. 'tbl.appendChild(tbody);'
			. 'listZone.appendChild(tbl);'
			. '}'
			. 'if(totalPages>1){'
			. 'var pg=document.createElement("div");'
			. 'pg.className="avi-rv-pagination";'
			. 'var prevBtn=document.createElement("button");'
			. 'prevBtn.type="button";prevBtn.className="avi-rv-page-btn";'
			. 'prevBtn.textContent=_t.previous;prevBtn.disabled=_rvPage<=1;'
			. 'prevBtn.addEventListener("click",function(){'
			. 'if(_rvPage>1){_rvPage--;_reviewsRenderList(listZone);'
			. 'listZone.scrollIntoView({behavior:"smooth"});}'
			. '});'
			. 'var pageInfo=document.createElement("span");'
			. 'pageInfo.className="avi-rv-page-info";'
			. 'pageInfo.textContent=_t.page_of+_rvPage+" / "+totalPages;'
			. 'var nextBtn=document.createElement("button");'
			. 'nextBtn.type="button";nextBtn.className="avi-rv-page-btn";'
			. 'nextBtn.textContent=_t.next;nextBtn.disabled=_rvPage>=totalPages;'
			. 'nextBtn.addEventListener("click",function(){'
			. 'if(_rvPage<totalPages){_rvPage++;_reviewsRenderList(listZone);'
			. 'listZone.scrollIntoView({behavior:"smooth"});}'
			. '});'
			. 'pg.appendChild(prevBtn);pg.appendChild(pageInfo);pg.appendChild(nextBtn);'
			. 'listZone.appendChild(pg);'
			. '}'
			. 'var lmBtn=document.createElement("button");'
			. 'lmBtn.type="button";lmBtn.className="avi-rv-load-more";'
			. 'lmBtn.textContent=_t.load_more;'
			. 'lmBtn.addEventListener("click",function(){'
			. '  if(window._aviReviewsLoadMoreCooldown){return;}'
			. '  window._aviReviewsLoadMoreCooldown=true;'
			. '  lmBtn.disabled=true;'
			. '  lmBtn.textContent=_t.load_more_loading||"Loading...";'
			. '  setTimeout(function(){window._aviReviewsLoadMoreCooldown=false;},2000);'
			. '  fetch(window.aviEmbedRestUrl+"embed/reviews-more",{'
			. '    method:"POST",'
			. '    headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '    body:JSON.stringify({'
			. '      profile_id:window.aviEmbedProfileId,'
			. '      key_id:window.aviEmbedKeyId,'
			. '      page_token:window._aviReviewsNextPageToken,'
			. '      page_size:50'
			. '    })'
			. '  }).then(function(r){return r.json();}).then(function(d){'
			. '    if(d.reviews&&d.reviews.length>0){'
			. '      var existing={}; '
			. '      (window.aviEmbedReviewsData.reviews||[]).forEach(function(r){existing[r.review_id]=1;});'
			. '      var added=0;'
			. '      d.reviews.forEach(function(r){'
			. '        if(!existing[r.review_id]){'
			. '          window.aviEmbedReviewsData.reviews.push(r);'
			. '          added++;'
			. '        }'
			. '      });'
			. '      window._aviReviewsNextPageToken=d.next_page_token||"";'
			. '      if(d.total_count) window.aviEmbedReviewsData.total_count=d.total_count;'
			. '      _reviewsRebuildYearFilter();'
			. '      _reviewsRenderList(listZone);'
			. '      if(!window._aviReviewsNextPageToken){'
			. '        lmBtn.style.display="none";'
			. '        fetch(window.aviEmbedRestUrl+"embed/reviews-cache-save",{'
			. '          method:"POST",'
			. '          headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},'
			. '          body:JSON.stringify({'
			. '            profile_id:window.aviEmbedProfileId,'
			. '            key_id:window.aviEmbedKeyId,'
			. '            reviews:window.aviEmbedReviewsData.reviews'
			. '          })'
			. '        }).then(function(r){return r.json();}).then(function(d){'
			. '          if(d.success) console.log("[AVI] "+d.total+" avis persistes en cache");'
			. '        }).catch(function(){});'
			. '        var lmInfo=document.createElement("div");'
			. '        lmInfo.className="avi-rv-load-more-info";'
			. '        lmInfo.textContent=_t.load_more_info+d.total_count+_t.load_more_info_end;'
			. '        listZone.appendChild(lmInfo);'
			. '      } else {'
			. '        lmBtn.disabled=false;'
			. '        lmBtn.textContent=_t.load_more;'
			. '      }'
			. '    } else {'
			. '      lmBtn.style.display="none";'
			. '      var lmDone=document.createElement("div");'
			. '      lmDone.className="avi-rv-load-more-info";'
			. '      lmDone.textContent=_t.load_more_info+(window.aviEmbedReviewsData.total_count||"")+_t.load_more_info_end;'
			. '      listZone.appendChild(lmDone);'
			. '    }'
			. '  }).catch(function(){'
			. '    lmBtn.disabled=false;'
			. '    lmBtn.textContent=_t.load_more;'
			. '    window._aviReviewsLoadMoreCooldown=false;'
			. '  });'
			. '});'
			. 'listZone.appendChild(lmBtn);'
			. '}'
			. 'function _reviewsRebuildYearFilter(){'
			. 'if(!_yrSel)return;'
			. '_yrSel.innerHTML="";'
			. 'var _years=["all"];'
			. '(window.aviEmbedReviewsData&&window.aviEmbedReviewsData.reviews||[]).forEach(function(r){'
			. 'if(!r.create_time)return;'
			. 'var y=new Date(r.create_time).getFullYear();'
			. 'if(y&&_years.indexOf(String(y))===-1)_years.push(String(y));'
			. '});'
			. '_years.sort(function(a,b){return a==="all"?-1:b-a;});'
			. '_years.forEach(function(y){'
			. 'var o=document.createElement("option");'
			. 'o.value=y;o.textContent=y==="all"?(_t.filter_all_years||"All years"):y;'
			. 'if(y===_rvYear)o.selected=true;'
			. '_yrSel.appendChild(o);'
			. '});'
			. '}'
			. 'function _reviewsRender(){'
			. 'var rd=window.aviEmbedReviewsData||{reviews:[]};'
			. '_reviewsPanel.innerHTML="";'
			. 'var rc=document.createElement("button");'
			. 'rc.type="button";rc.style.cssText="position:absolute;top:12px;right:16px;'
			. 'background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;";'
			. 'rc.textContent="×";'
			. 'rc.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_reviewsPanel.appendChild(rc);'
			. 'var inner=document.createElement("div");'
			. 'inner.className="avi-reviews-inner";'
			. 'var rhdr=document.createElement("div");'
			. 'rhdr.className="avi-reviews-header";'
			. 'var avgStars="⭐".repeat(Math.round(rd.average_rating||0));'
			. 'rhdr.innerHTML="<div style=\\"text-align:center;min-width:80px;\\">"'
			. '+"<div class=\\"avi-reviews-avg\\">"+(rd.average_rating?parseFloat(rd.average_rating).toFixed(1):"—")+"</div>"'
			. '+"<div class=\\"avi-reviews-stars\\">"+avgStars+"</div>"'
			. '+"<div class=\\"avi-reviews-avg-sub\\">"+(rd.total_count||0)+" "+_t.reviews_label+"</div>"'
			. '+"</div>"'
			. '+"<div style=\\"flex:1;\\">"'
			. '+"<div style=\\"font-size:13px;color:rgba(255,255,255,.9);\\">"'
			. '+_t.gbp_reviews_title'
			. '+" <button type=\\"button\\" class=\\"avi-header-info-btn\\" id=\\"aviReviewsInfoBtn\\">\\u2139\\uFE0F</button></div>"'
			. '+"<div style=\\"font-size:11px;color:rgba(255,255,255,.7);margin-top:4px;\\">"+_t.gbp_reviews_sub+"</div>"'
			. '+"</div>";'
			. 'inner.appendChild(rhdr);'
			. 'var listZone=document.createElement("div");'
			. 'listZone.id="aviRvListZone";'
			. 'var _rvFilterBar=document.createElement("div");'
			. '_rvFilterBar.className="avi-rv-filter-bar";'
			. '_yrSel=document.createElement("select");'
			. '_yrSel.className="avi-rv-filter-sel";'
			. '_reviewsRebuildYearFilter();'
			. 'var _mthSel=document.createElement("select");'
			. '_mthSel.className="avi-rv-filter-sel";'
			. 'var _wkSel=document.createElement("select");'
			. '_wkSel.className="avi-rv-filter-sel";'
			. '_yrSel.addEventListener("change",function(){'
			. '_rvYear=this.value;_rvMonth="all";_rvWeek="all";'
			. '_mthSel.value="all";_wkSel.value="all";'
			. '_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. '_rvFilterBar.appendChild(_yrSel);'
			. 'function _buildMonthOptions(){'
			. '_mthSel.innerHTML="";'
			. 'var months=[["all",_t.filter_all_months||"All months"],'
			. '["1","Jan"],["2","Feb"],["3","Mar"],["4","Apr"],["5","May"],["6","Jun"],'
			. '["7","Jul"],["8","Aug"],["9","Sep"],["10","Oct"],["11","Nov"],["12","Dec"]];'
			. 'months.forEach(function(m){'
			. 'var o=document.createElement("option");'
			. 'o.value=m[0];o.textContent=m[1];'
			. 'if(m[0]===_rvMonth)o.selected=true;'
			. '_mthSel.appendChild(o);'
			. '});'
			. '}'
			. '_buildMonthOptions();'
			. '_mthSel.addEventListener("change",function(){'
			. '_rvMonth=this.value;_rvWeek="all";_wkSel.value="all";'
			. '_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. '_rvFilterBar.appendChild(_mthSel);'
			. 'function _buildWeekOptions(){'
			. '_wkSel.innerHTML="";'
			. 'var o0=document.createElement("option");'
			. 'o0.value="all";o0.textContent=_t.filter_all_weeks||"All weeks";'
			. '_wkSel.appendChild(o0);'
			. 'for(var w=0;w<8;w++){'
			. 'var d=new Date();d.setDate(d.getDate()-w*7);'
			. 'var monday=new Date(d);monday.setDate(d.getDate()-((d.getDay()+6)%7));'
			. 'var sunday=new Date(monday);sunday.setDate(monday.getDate()+6);'
			. 'var label=monday.toLocaleDateString(undefined,{day:"2-digit",month:"short"})'
			. '+" \\u2192 "+sunday.toLocaleDateString(undefined,{day:"2-digit",month:"short"});'
			. 'var val=monday.toISOString().slice(0,10);'
			. 'var o=document.createElement("option");o.value=val;o.textContent=label;'
			. 'if(val===_rvWeek)o.selected=true;'
			. '_wkSel.appendChild(o);'
			. '}'
			. '}'
			. '_buildWeekOptions();'
			. '_wkSel.addEventListener("change",function(){'
			. '_rvWeek=this.value;_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. '_rvFilterBar.appendChild(_wkSel);'
			. 'var _replySel=document.createElement("select");'
			. '_replySel.className="avi-rv-filter-sel";'
			. '[["all",_t.filter_all_replies||"All replies"],'
			. '["replied",_t.filter_with_reply||"With reply"],'
			. '["unanswered",_t.without_reply||"Without reply"]]'
			. '.forEach(function(r){'
			. 'var o=document.createElement("option");o.value=r[0];o.textContent=r[1];'
			. 'if(r[0]===_rvReplyFilter)o.selected=true;'
			. '_replySel.appendChild(o);'
			. '});'
			. '_replySel.addEventListener("change",function(){'
			. '_rvReplyFilter=this.value;'
			. '_rvFilter=this.value==="unanswered"?"unanswered":"all";'
			. '_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. '_rvFilterBar.appendChild(_replySel);'
			. 'inner.appendChild(_rvFilterBar);'
			. 'var _rvInfoBtn=rhdr.querySelector("#aviReviewsInfoBtn");'
			. 'if(_rvInfoBtn){'
			. '_rvInfoBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.reviews_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.reviews_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.reviews_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.reviews_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.reviews_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.reviews_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.reviews_info_s3_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviReviewsInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviReviewsInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var tb=document.createElement("div");'
			. 'tb.className="avi-rv-toolbar";'
			. 'var starFilters=[0,5,4,3,2,1];'
			. 'starFilters.forEach(function(n){'
			. 'var fb=document.createElement("button");'
			. 'fb.type="button";fb.className="avi-rv-filter-btn"+(n===_rvStarFilter?" active":"");'
			. 'fb.textContent=n===0?_t.filter_all_stars:"⭐".repeat(n);'
			. 'fb.addEventListener("click",function(){'
			. '_rvStarFilter=n;_rvPage=1;'
			. 'tb.querySelectorAll(".avi-rv-filter-btn").forEach(function(b){'
			. 'b.classList.remove("active");'
			. '});'
			. 'fb.classList.add("active");'
			. '_reviewsRenderList(listZone);'
			. '});'
			. 'tb.appendChild(fb);'
			. '});'
			. 'var sortSel=document.createElement("select");'
			. 'sortSel.className="avi-rv-sort-sel";'
			. 'var sortOpts=[["recent",_t.sort_recent],["oldest",_t.sort_oldest],'
			. '["lowest",_t.sort_lowest],["unanswered",_t.sort_unanswered]];'
			. 'sortOpts.forEach(function(o){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=o[0];opt.textContent=o[1];'
			. 'if(o[0]===_rvSort)opt.selected=true;'
			. 'sortSel.appendChild(opt);'
			. '});'
			. 'sortSel.addEventListener("change",function(){'
			. '_rvSort=this.value;_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. 'tb.appendChild(sortSel);'
			. 'var ppSel=document.createElement("select");'
			. 'ppSel.className="avi-rv-per-page";'
			. '[10,20,50,100,150,200,300,500].forEach(function(n){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=n;opt.textContent=n+_t.per_page;'
			. 'if(n===_rvPerPage)opt.selected=true;'
			. 'ppSel.appendChild(opt);'
			. '});'
			. 'ppSel.addEventListener("change",function(){'
			. '_rvPerPage=parseInt(this.value,10);_rvPage=1;_reviewsRenderList(listZone);'
			. '});'
			. 'inner.appendChild(tb);'
			. 'var _ppWrap=document.createElement("div");'
			. '_ppWrap.style.cssText="display:flex;justify-content:flex-end;margin-bottom:8px;";'
			. '_ppWrap.appendChild(ppSel);'
			. 'inner.appendChild(_ppWrap);'
			. 'inner.appendChild(listZone);'
			. 'var _rvUpKey="avi_reviews_upsell_dismissed";'
			. 'var _rvUpDismissed=false;'
			. 'try{_rvUpDismissed=sessionStorage.getItem(_rvUpKey)==="1";}catch(e){}'
			. 'if(!_rvUpDismissed){'
			. 'var upDiv=document.createElement("div");'
			. 'upDiv.className="avi-reviews-upsell";'
			. 'upDiv.innerHTML='
			. '\'<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">\''
			. '+\'<div>\''
			. '+\'<div style="font-size:12px;font-weight:700;color:#fff;margin-bottom:2px;">\'+(_t.upgrade_ai_title||"")+\'</div>\''
			. '+\'<div style="font-size:11px;color:rgba(255,255,255,0.75);">\'+(_t.upgrade_ai_sub||"")+\'</div>\''
			. '+\'</div>\''
			. '+\'<div style="display:flex;align-items:center;gap:8px;flex-shrink:0;">\''
			. '+\'<a href="\'+(window.aviEmbedKeyType==="agency"?"https://avision.org/":"https://avision.org/local-business/")+\'" target="_blank" rel="noopener" style="background:rgba(255,255,255,.2);border:1px solid rgba(255,255,255,.3);border-radius:6px;color:#fff;font-size:11px;font-weight:700;padding:6px 14px;text-decoration:none;white-space:nowrap;">\'+(_t.upgrade_link||"Upgrade \\u2192")+\'</a>\''
			. '+\'<button type="button" id="aviReviewsUpsellClose" style="background:none;border:none;color:rgba(255,255,255,.6);cursor:pointer;font-size:16px;padding:0;line-height:1;">×</button>\''
			. '+\'</div>\''
			. '+\'</div>\';'
			. 'inner.appendChild(upDiv);'
			. 'document.addEventListener("click",function _ruClose(e){'
			. 'if(e.target&&e.target.id==="aviReviewsUpsellClose"){'
			. 'try{sessionStorage.setItem(_rvUpKey,"1");}catch(e){}'
			. 'upDiv.remove();'
			. 'document.removeEventListener("click",_ruClose);'
			. '}'
			. '});'
			. '}'
			. 'var rexp=document.createElement("div");'
			. 'rexp.className="avi-reviews-export";'
			. 'var rcsvBtn=document.createElement("button");'
			. 'rcsvBtn.type="button";rcsvBtn.className="avi-reviews-export-btn csv";'
			. 'rcsvBtn.textContent=_t.export_csv;'
			. 'rcsvBtn.addEventListener("click",function(){'
			. 'var rows=[_t.th_reviewer+","+_t.th_stars+","+_t.th_date+","+_t.th_review+","+_t.export_col_has_reply+","+_t.export_col_reply];'
			. 'var starMap={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5};'
			. '(rd.reviews||[]).forEach(function(rv){'
			. 'var safeComment=(rv.comment||"").replace(/"/g,"\'");'
			. 'var safeReply=(rv.reply_comment||"").replace(/"/g,"\'");'
			. 'rows.push(["\\""+rv.reviewer_name+"\\"",starMap[rv.star_rating]||0,'
			. '_rvRelDate(rv.create_time),'
			. '"\\""+safeComment+"\\"",'
			. 'rv.has_reply?_t.export_yes:_t.export_no,'
			. '"\\""+safeReply+"\\""].join(","));'
			. '});'
			. 'var blob=new Blob([rows.join("\\n")],{type:"text/csv;charset=utf-8;"});'
			. 'var url=URL.createObjectURL(blob);'
			. 'var a=document.createElement("a");'
			. 'a.href=url;a.download="reviews-export.csv";'
			. 'document.body.appendChild(a);a.click();'
			. 'document.body.removeChild(a);URL.revokeObjectURL(url);'
			. '});'
			. 'var rpdfBtn=document.createElement("button");'
			. 'rpdfBtn.type="button";rpdfBtn.className="avi-reviews-export-btn pdf";'
			. 'rpdfBtn.textContent=_t.export_pdf;'
			. 'rpdfBtn.addEventListener("click",function(){'
			. 'var brand=window.aviEmbedWhiteLabel||"Avision";'
			. 'var logo=window.aviEmbedLogoUrl'
			. '?"<img src=\\""+window.aviEmbedLogoUrl+"\\" style=\\"height:36px;margin-bottom:8px;\\">"'
			. ':"";'
			. 'var starMap={ONE:1,TWO:2,THREE:3,FOUR:4,FIVE:5};'
			. 'var rows=(rd.reviews||[]).map(function(rv){'
			. 'return "<tr><td>"+rv.reviewer_name+"</td>"'
			. '+"<td>"+(starMap[rv.star_rating]||0)+"/5</td>"'
			. '+"<td>"+_rvRelDate(rv.create_time)+"</td>"'
			. '+"<td style=\\"max-width:300px;\\">"+(rv.comment||"").substring(0,200)+"</td>"'
			. '+"<td>"+(rv.has_reply?"✅":"❌")+"</td></tr>";'
			. '}).join("");'
			. 'var win=window.open("","_blank");'
			. 'win.document.write("<html><head><title>"+brand+" — "+_t.reviews_page_title+"</title>"'
			. '+"<style>body{font-family:Inter,sans-serif;padding:32px;color:#1e293b;}"'
			. '+"table{width:100%;border-collapse:collapse;font-size:12px;}"'
			. '+"th{background:#f1f5f9;padding:8px;text-align:left;}"'
			. '+"td{padding:7px 8px;border-bottom:1px solid #f1f5f9;vertical-align:top;}"'
			. '+"</style></head><body>"'
			. '+logo'
			. '+"<h1>"+brand+" — "+_t.reviews_report_title+"</h1>"'
			. '+"<p>"+_t.reviews_pdf_avg+(rd.average_rating?parseFloat(rd.average_rating).toFixed(1):"—")+" · "+(rd.total_count||0)+_t.reviews_pdf_reviews_suffix+"</p>"'
			. '+"<table><thead><tr><th>"+_t.th_reviewer+"</th><th>"+_t.th_stars+"</th><th>"+_t.th_date+"</th>"'
			. '+"<th>"+_t.th_review+"</th><th>"+_t.th_replied+"</th></tr></thead>"'
			. '+"<tbody>"+rows+"</tbody></table></body></html>");'
			. 'win.document.close();win.focus();'
			. 'setTimeout(function(){win.print();},400);'
			. '});'
			. 'rexp.appendChild(rcsvBtn);rexp.appendChild(rpdfBtn);'
			. 'inner.appendChild(rexp);'
			. '_reviewsPanel.appendChild(inner);'
			. '_reviewsRenderList(listZone);'
			. '}'
			. 'function _reviewsUpdateBadge(){'
			. 'var count=window.aviEmbedUnansweredCount||0;'
			. 'var btn=_navBtns["avis"];'
			. 'if(!btn)return;'
			. 'var existing=btn.querySelector(".avi-review-badge");'
			. 'if(existing)existing.remove();'
			. 'if(count>0){'
			. 'var badge=document.createElement("span");'
			. 'badge.className="avi-review-badge";'
			. 'badge.textContent=count;'
			. 'btn.appendChild(badge);'
			. '}'
			. '}'
			. '_reviewsRender();'
			. '_reviewsUpdateBadge();'
			. 'var _rvWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_rvWrap.appendChild(_reviewsPanel);'
			. 'function _postTypeLabel(t){'
			. 'return{update:_t.post_type_update_short,offer:_t.post_type_offer_short,event:_t.post_type_event_short}[t]||t;'
			. '}'
			. 'function _postTypeCls(t){'
			. 'return{update:"avi-post-type-update",'
			. 'offer:"avi-post-type-offer",'
			. 'event:"avi-post-type-event"}[t]||"";'
			. '}'
			. 'function _postStatusLabel(s){'
			. 'return{published:_t.post_status_published,scheduled:_t.post_status_scheduled,'
			. 'pending:_t.post_status_pending,failed:_t.post_status_failed,draft:_t.post_status_draft}[s]||s;'
			. '}'
			. 'function _postStatusCls(s){'
			. 'return"avi-post-status-badge avi-post-status-"+(s||"draft");'
			. '}'
			. 'function _postRelDate(dt){'
			. 'if(!dt)return "—";'
			. 'var d=new Date(dt),now=new Date();'
			. 'var diff=Math.floor((now-d)/86400000);'
			. 'if(diff===0)return _t.today;if(diff===1)return _t.yesterday;'
			. 'if(diff<30)return diff+_t.rel_d_ago;'
			. 'if(diff<365)return Math.floor(diff/30)+_t.rel_mo_ago;'
			. 'return Math.floor(diff/365)+_t.rel_y_ago;'
			. '}'
			. '_postsPanel=document.createElement("div");'
			. '_postsPanel.className="avi-posts-panel";'
			. '_postsPanel.id="aviEmbedPostsPanel";'
			. 'function _postsRender(){'
			. '_postsPanel.innerHTML="";'
			. 'var pc=document.createElement("button");'
			. 'pc.type="button";'
			. 'pc.style.cssText="position:absolute;top:12px;right:16px;'
			. 'background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;";'
			. 'pc.textContent="×";'
			. 'pc.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_postsPanel.appendChild(pc);'
			. 'var _postsHeader=document.createElement("div");'
			. '_postsHeader.id="aviPostsHeader";'
			. '_postsHeader.className="avi-posts-header";'
			. '_postsHeader.innerHTML='
			. '\'<div class="avi-kw-header-title">\''
			. '+\'\\uD83D\\uDCDD \'+(_t.posts_panel_title||"")'
			. '+\' <button type="button" class="avi-header-info-btn" id="aviPostsInfoBtn">\\u2139\\uFE0F</button>\''
			. '+\'</div>\''
			. '+\'<div class="avi-kw-header-sub">\'+(_t.posts_panel_sub||"")+\'</div>\';'
			. '_postsPanel.appendChild(_postsHeader);'
			. 'var _postsInfoBtn=_postsHeader.querySelector("#aviPostsInfoBtn");'
			. 'if(_postsInfoBtn){'
			. '_postsInfoBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.posts_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.posts_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.posts_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.posts_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.posts_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.posts_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.posts_info_s3_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviPostsInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(e){if(e.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviPostsInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var inner=document.createElement("div");'
			. 'inner.className="avi-posts-inner";'
			. 'var topbar=document.createElement("div");'
			. 'topbar.className="avi-posts-topbar";'
			. 'var newBtn=document.createElement("button");'
			. 'newBtn.type="button";newBtn.className="avi-posts-new-btn";'
			. 'newBtn.textContent=_t.new_post_btn;'
			. 'newBtn.addEventListener("click",function(){'
			. '_postsOpenPanel(null);'
			. '});'
			. 'topbar.appendChild(newBtn);'
			. 'var filters=[["all",_t.filter_all],["published",_t.post_status_published],'
			. '["scheduled",_t.post_status_scheduled],["pending",_t.post_status_pending],'
			. '["failed",_t.post_status_failed],["draft",_t.post_status_draft]];'
			. 'filters.forEach(function(f){'
			. 'var fb=document.createElement("button");'
			. 'fb.type="button";'
			. 'fb.className="avi-posts-filter-btn"+(f[0]===_postsFilter?" active":"");'
			. 'fb.textContent=f[1];'
			. 'fb.addEventListener("click",function(){'
			. '_postsFilter=f[0];'
			. 'topbar.querySelectorAll(".avi-posts-filter-btn").forEach(function(b){'
			. 'b.classList.remove("active");'
			. '});'
			. 'fb.classList.add("active");'
			. '_postsRenderTable(tableZone);'
			. '});'
			. 'topbar.appendChild(fb);'
			. '});'
			. 'inner.appendChild(topbar);'
			. 'var tableZone=document.createElement("div");'
			. 'tableZone.id="aviPostsTableZone";'
			. 'inner.appendChild(tableZone);'
			. 'var _postsUpKey="avi_posts_upsell_dismissed";'
			. 'var _postsUpDismissed=false;'
			. 'try{_postsUpDismissed=sessionStorage.getItem(_postsUpKey)==="1";}catch(e){}'
			. 'if(!_postsUpDismissed){'
			. 'var upDiv=document.createElement("div");'
			. 'upDiv.className="avi-posts-upsell";'
			. 'upDiv.innerHTML='
			. '\'<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">\''
			. '+\'<div>\''
			. '+\'<div style="font-size:12px;font-weight:700;color:#fff;margin-bottom:2px;">\'+(_t.upgrade_posts_title||"")+\'</div>\''
			. '+\'<div style="font-size:11px;color:rgba(255,255,255,0.75);">\'+(_t.upgrade_posts_sub||"")+\'</div>\''
			. '+\'</div>\''
			. '+\'<div style="display:flex;align-items:center;gap:8px;flex-shrink:0;">\''
			. '+\'<a href="\'+(window.aviEmbedKeyType==="agency"?"https://avision.org/":"https://avision.org/local-business/")+\'" target="_blank" rel="noopener" style="background:rgba(255,255,255,.2);border:1px solid rgba(255,255,255,.3);border-radius:6px;color:#fff;font-size:11px;font-weight:700;padding:6px 14px;text-decoration:none;white-space:nowrap;">\'+(_t.upgrade_link||"\\u2192")+\'</a>\''
			. '+\'<button type="button" id="aviPostsUpsellClose" style="background:none;border:none;color:rgba(255,255,255,.6);cursor:pointer;font-size:16px;padding:0;line-height:1;">×</button>\''
			. '+\'</div>\''
			. '+\'</div>\';'
			. 'inner.appendChild(upDiv);'
			. 'document.addEventListener("click",function _puClose(e){'
			. 'if(e.target&&e.target.id==="aviPostsUpsellClose"){'
			. 'try{sessionStorage.setItem(_postsUpKey,"1");}catch(e){}'
			. 'upDiv.remove();'
			. 'document.removeEventListener("click",_puClose);'
			. '}'
			. '});'
			. '}'
			. 'var pexp=document.createElement("div");'
			. 'pexp.className="avi-posts-export";'
			. 'var pcsvBtn=document.createElement("button");'
			. 'pcsvBtn.type="button";pcsvBtn.className="avi-posts-export-btn csv";'
			. 'pcsvBtn.textContent=_t.export_csv;'
			. 'pcsvBtn.addEventListener("click",function(){'
			. 'var pd=window.aviEmbedPostsData||[];'
			. 'var rows=[_t.th_type+","+_t.th_status+","+_t.th_content+","+_t.th_scheduled+","+_t.th_published+","+_t.export_col_created];'
			. 'pd.forEach(function(p){'
			. 'var safeContent=(p.content||"").substring(0,100).replace(/"/g,"\'");'
			. 'rows.push([p.post_type,p.status,'
			. '"\\""+safeContent+"\\"",'
			. 'p.scheduled_at||"",p.published_at||"",p.created_at||""]'
			. '.join(","));'
			. '});'
			. 'var blob=new Blob([rows.join("\\n")],{type:"text/csv;charset=utf-8;"});'
			. 'var url=URL.createObjectURL(blob);'
			. 'var a=document.createElement("a");'
			. 'a.href=url;a.download="gbp-posts.csv";'
			. 'document.body.appendChild(a);a.click();'
			. 'document.body.removeChild(a);URL.revokeObjectURL(url);'
			. '});'
			. 'var ppdfBtn=document.createElement("button");'
			. 'ppdfBtn.type="button";ppdfBtn.className="avi-posts-export-btn pdf";'
			. 'ppdfBtn.textContent=_t.export_pdf;'
			. 'ppdfBtn.addEventListener("click",function(){'
			. 'var brand=window.aviEmbedWhiteLabel||"Avision";'
			. 'var logo=window.aviEmbedLogoUrl'
			. '?"<img src=\\""+window.aviEmbedLogoUrl+"\\" style=\\"height:36px;margin-bottom:8px;\\">"'
			. ':"";'
			. 'var pd=window.aviEmbedPostsData||[];'
			. 'var rows=pd.map(function(p){'
			. 'return "<tr><td>"+_postTypeLabel(p.post_type)+"</td>"'
			. '+"<td>"+_postStatusLabel(p.status)+"</td>"'
			. '+"<td style=\\"max-width:300px;\\">"+(p.content||"").substring(0,150)+"</td>"'
			. '+"<td>"+(p.scheduled_at||"—")+"</td>"'
			. '+"<td>"+(p.published_at||"—")+"</td></tr>";'
			. '}).join("");'
			. 'var win=window.open("","_blank");'
			. 'win.document.write("<html><head><title>"+brand+" — "+_t.posts_page_title+"</title>"'
			. '+"<style>body{font-family:Inter,sans-serif;padding:32px;color:#1e293b;}"'
			. '+"table{width:100%;border-collapse:collapse;font-size:12px;}"'
			. '+"th{background:#f1f5f9;padding:8px;text-align:left;}"'
			. '+"td{padding:7px 8px;border-bottom:1px solid #f1f5f9;vertical-align:top;}"'
			. '+"</style></head><body>"'
			. '+logo+"<h1>"+brand+" — "+_t.posts_report_title+"</h1>"'
			. '+"<table><thead><tr><th>"+_t.th_type+"</th><th>"+_t.th_status+"</th>"'
			. '+"<th>"+_t.th_content+"</th><th>"+_t.th_scheduled+"</th><th>"+_t.th_published+"</th></tr></thead>"'
			. '+"<tbody>"+rows+"</tbody></table></body></html>");'
			. 'win.document.close();win.focus();'
			. 'setTimeout(function(){win.print();},400);'
			. '});'
			. 'pexp.appendChild(pcsvBtn);pexp.appendChild(ppdfBtn);'
			. 'inner.appendChild(pexp);'
			. '_postsPanel.appendChild(inner);'
			. '_postsRenderTable(tableZone);'
			. '}'
			. 'function _postsRenderTable(tableZone){'
			. 'var pd=window.aviEmbedPostsData||[];'
			. 'var filtered=pd.filter(function(p){'
			. 'if(_postsFilter==="all")return true;'
			. 'return p.status===_postsFilter;'
			. '});'
			. 'tableZone.innerHTML="";'
			. 'var countDiv=document.createElement("div");'
			. 'countDiv.className="avi-posts-count";'
			. 'countDiv.textContent=filtered.length+_t.posts_count_suffix;'
			. 'tableZone.appendChild(countDiv);'
			. 'if(filtered.length===0){'
			. 'var empty=document.createElement("div");'
			. 'empty.className="avi-posts-empty";'
			. 'empty.innerHTML="<div style=\\"font-size:32px;margin-bottom:8px;\\">📝</div>"'
			. '+"<div style=\\"font-size:14px;font-weight:600;color:#475569;\\">"+_t.no_posts+"</div>"'
			. '+"<div style=\\"font-size:12px;margin-top:4px;\\">"+_t.no_posts_sub+"</div>";'
			. 'tableZone.appendChild(empty);'
			. 'return;'
			. '}'
			. 'var tbl=document.createElement("table");'
			. 'tbl.className="avi-posts-table";'
			. 'var thead=document.createElement("thead");'
			. 'thead.innerHTML="<tr>"'
			. '+"<th>"+_t.th_type+"</th><th>"+_t.th_content+"</th><th>"+_t.th_status+"</th>"'
			. '+"<th>"+_t.th_scheduled+"</th><th>"+_t.th_published+"</th><th>"+_t.th_actions+"</th>"'
			. '+"</tr>";'
			. 'tbl.appendChild(thead);'
			. 'var tbody=document.createElement("tbody");'
			. 'filtered.forEach(function(p){'
			. 'var tr=document.createElement("tr");'
			. 'var tdType=document.createElement("td");'
			. 'tdType.innerHTML="<span class=\\"avi-post-type-badge "+_postTypeCls(p.post_type)+"\\">"'
			. '+_postTypeLabel(p.post_type)+"</span>";'
			. 'var tdContent=document.createElement("td");'
			. 'var snip=document.createElement("div");'
			. 'snip.className="avi-posts-snippet";'
			. 'snip.textContent=(p.content||"").substring(0,80)'
			. '+(p.content&&p.content.length>80?"...":"");'
			. 'tdContent.appendChild(snip);'
			. 'var tdStatus=document.createElement("td");'
			. 'tdStatus.innerHTML="<span class=\\""+_postStatusCls(p.status)+"\\">"'
			. '+_postStatusLabel(p.status)+"</span>";'
			. 'var tdSched=document.createElement("td");'
			. 'tdSched.style.color="#64748b";tdSched.style.fontSize="11px";'
			. 'tdSched.textContent=p.scheduled_at?_postRelDate(p.scheduled_at):"—";'
			. 'var tdPub=document.createElement("td");'
			. 'tdPub.style.color="#64748b";tdPub.style.fontSize="11px";'
			. 'tdPub.textContent=p.published_at?_postRelDate(p.published_at):"—";'
			. 'var tdAct=document.createElement("td");'
			. 'var viewBtn2=document.createElement("button");'
			. 'viewBtn2.type="button";viewBtn2.className="avi-posts-action-btn";'
			. 'viewBtn2.textContent=_t.view_btn;'
			. 'viewBtn2.addEventListener("click",function(){'
			. 'alert(p.content||_t.no_content);'
			. '});'
			. 'tdAct.appendChild(viewBtn2);'
			. 'tr.appendChild(tdType);tr.appendChild(tdContent);'
			. 'tr.appendChild(tdStatus);tr.appendChild(tdSched);'
			. 'tr.appendChild(tdPub);tr.appendChild(tdAct);'
			. 'tbody.appendChild(tr);'
			. '});'
			. 'tbl.appendChild(tbody);'
			. 'tableZone.appendChild(tbl);'
			. '}'
			. 'var _postsCreateOverlay=document.createElement("div");'
			. '_postsCreateOverlay.className="avi-posts-create-overlay";'
			. 'document.body.appendChild(_postsCreateOverlay);'
			. 'var _postsCreatePanel=document.createElement("div");'
			. '_postsCreatePanel.className="avi-posts-create-panel";'
			. 'document.body.appendChild(_postsCreatePanel);'
			. 'function _postsOpenPanel(post){'
			. 'window._postsEditRef=post;'
			. '_postsCreatePanel.innerHTML="";'
			. 'var isScheduled=false;'
			. 'var balance=window.aviEmbedAgencyCredits'
			. '?window.aviEmbedAgencyCredits.available'
			. ':parseInt((document.querySelector(".avi-heatmap-credit-balance")||{}).textContent||"0",10);'
			. 'var phdr=document.createElement("div");'
			. 'phdr.className="avi-posts-create-header";'
			. 'var pTitle=document.createElement("h3");'
			. 'pTitle.textContent=post?_t.edit_post:_t.new_post;'
			. 'var pClose=document.createElement("button");'
			. 'pClose.type="button";pClose.className="avi-posts-create-close";'
			. 'pClose.textContent="×";'
			. 'pClose.addEventListener("click",function(){'
			. '_postsCreatePanel.classList.remove("open");'
			. '_postsCreateOverlay.classList.remove("open");'
			. '});'
			. 'phdr.appendChild(pTitle);phdr.appendChild(pClose);'
			. '_postsCreatePanel.appendChild(phdr);'
			. 'var pbody=document.createElement("div");'
			. 'pbody.className="avi-posts-create-body";'
			. 'var typeField=document.createElement("div");'
			. 'typeField.className="avi-posts-field";'
			. 'var typeLabel=document.createElement("label");'
			. 'typeLabel.textContent=_t.post_type_label;'
			. 'var typeSel=document.createElement("select");'
			. 'typeSel.id="avi-post-type";'
			. '[["update",_t.post_type_update],'
			. '["offer",_t.post_type_offer],'
			. '["event",_t.post_type_event]].forEach(function(o){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=o[0];opt.textContent=o[1];'
			. 'typeSel.appendChild(opt);'
			. '});'
			. 'typeField.appendChild(typeLabel);typeField.appendChild(typeSel);'
			. 'pbody.appendChild(typeField);'
			. 'var eventFields=document.createElement("div");'
			. 'eventFields.className="avi-posts-event-fields";'
			. 'var evTitleField=document.createElement("div");'
			. 'evTitleField.className="avi-posts-field";'
			. 'var evTLabel=document.createElement("label");'
			. 'evTLabel.textContent=_t.event_title;'
			. 'var evTInput=document.createElement("input");'
			. 'evTInput.type="text";evTInput.placeholder=_t.event_title_ph;'
			. 'evTInput.style.cssText="border:1px solid #e2e8f0;border-radius:6px;'
			. 'font-size:13px;padding:8px 12px;width:100%;box-sizing:border-box;outline:none;";'
			. 'evTitleField.appendChild(evTLabel);evTitleField.appendChild(evTInput);'
			. 'var evDatesDiv=document.createElement("div");'
			. 'evDatesDiv.style.cssText="display:grid;grid-template-columns:1fr 1fr;gap:10px;";'
			. 'var evStartField=document.createElement("div");'
			. 'evStartField.className="avi-posts-field";'
			. 'var evSLabel=document.createElement("label");evSLabel.textContent=_t.start_date;'
			. 'var evSInput=document.createElement("input");evSInput.type="datetime-local";'
			. 'evStartField.appendChild(evSLabel);evStartField.appendChild(evSInput);'
			. 'var evEndField=document.createElement("div");'
			. 'evEndField.className="avi-posts-field";'
			. 'var evELabel=document.createElement("label");evELabel.textContent=_t.end_date;'
			. 'var evEInput=document.createElement("input");evEInput.type="datetime-local";'
			. 'evEndField.appendChild(evELabel);evEndField.appendChild(evEInput);'
			. 'evDatesDiv.appendChild(evStartField);evDatesDiv.appendChild(evEndField);'
			. 'eventFields.appendChild(evTitleField);eventFields.appendChild(evDatesDiv);'
			. 'pbody.appendChild(eventFields);'
			. 'typeSel.addEventListener("change",function(){'
			. 'eventFields.classList.toggle("show",typeSel.value==="event");'
			. '});'
			. 'var contentField=document.createElement("div");'
			. 'contentField.className="avi-posts-field";'
			. 'var contentLabel=document.createElement("label");'
			. 'contentLabel.textContent=_t.write_content;'
			. 'var _aviGenI18n={'
			. 'en:{btn:"✨ AVI writes",loader:"Generating…",'
			. 'tooltip:"AVI drafts an optimized GBP post based on your business, city and language. Review and adjust before publishing.",'
			. 'error:"AVI could not generate the post. Please try again.",'
			. 'errNet:"Network error during generation.",'
			. 'ctxLabel:"Give AVI some context (optional)",'
			. 'ctxPlaceholder:"e.g. weekend promo -20%, new AC service, Marais district...",'
			. 'regenBtn:"🔄 Try another angle"},'
			. 'fr:{btn:"✨ AVI rédige",loader:"Génération en cours…",'
			. 'tooltip:"AVI génère un post optimisé GBP selon votre activité, ville et langue. Relisez et ajustez avant de publier.",'
			. 'error:"AVI n\\u0027a pas pu générer le post. Réessaie.",'
			. 'errNet:"Erreur réseau lors de la génération.",'
			. 'ctxLabel:"Donnez un contexte à AVI (optionnel)",'
			. 'ctxPlaceholder:"ex: promo week-end -20%, nouveau service clim, quartier Marais...",'
			. 'regenBtn:"🔄 Autre angle"},'
			. 'es:{btn:"✨ AVI redacta",loader:"Generando…",'
			. 'tooltip:"AVI redacta un post GBP optimizado según tu negocio, ciudad e idioma. Revisa y ajusta antes de publicar.",'
			. 'error:"AVI no pudo generar el post. Inténtalo de nuevo.",'
			. 'errNet:"Error de red durante la generación.",'
			. 'ctxLabel:"Da contexto a AVI (opcional)",'
			. 'ctxPlaceholder:"ej: promo fin de semana -20%, nuevo servicio AC, barrio Marais...",'
			. 'regenBtn:"🔄 Otro enfoque"},'
			. '"pt-br":{btn:"✨ AVI escreve",loader:"Gerando…",'
			. 'tooltip:"AVI cria um post GBP otimizado com base no seu negócio, cidade e idioma. Revise e ajuste antes de publicar.",'
			. 'error:"AVI não conseguiu gerar o post. Tente novamente.",'
			. 'errNet:"Erro de rede durante a geração.",'
			. 'ctxLabel:"Dê contexto ao AVI (opcional)",'
			. 'ctxPlaceholder:"ex: promoção fim de semana -20%, novo serviço AC, bairro Centro...",'
			. 'regenBtn:"🔄 Outro ângulo"},'
			. 'tr:{btn:"✨ AVI yazar",loader:"Oluşturuluyor…",'
			. 'tooltip:"AVI, işletmenize, şehrinize ve dilinize göre optimize edilmiş bir GBP gönderisi oluşturur. Yayınlamadan önce gözden geçirin.",'
			. 'error:"AVI gönderiyi oluşturamadı. Lütfen tekrar deneyin.",'
			. 'errNet:"Oluşturma sırasında ağ hatası.",'
			. 'ctxLabel:"AVI\\u0027ye bağlam verin (isteğe bağlı)",'
			. 'ctxPlaceholder:"ör: hafta sonu kampanyası -%20, yeni klima hizmeti, Beşiktaş...",'
			. 'regenBtn:"🔄 Farklı açı"},'
			. 'de:{btn:"✨ AVI schreibt",loader:"Wird generiert…",'
			. 'tooltip:"AVI erstellt einen optimierten GBP-Beitrag basierend auf Ihrem Unternehmen, Ihrer Stadt und Sprache. Prüfen Sie vor der Veröffentlichung.",'
			. 'error:"AVI konnte den Beitrag nicht generieren. Bitte erneut versuchen.",'
			. 'errNet:"Netzwerkfehler bei der Generierung.",'
			. 'ctxLabel:"AVI Kontext geben (optional)",'
			. 'ctxPlaceholder:"z.B. Wochenend-Promo -20%, neuer Klimaservice, Bezirk Mitte...",'
			. 'regenBtn:"🔄 Anderer Winkel"}'
			. '};'
			. 'var _aviGenLang=window.aviEmbedLang||"en";'
			. 'if(!_aviGenI18n[_aviGenLang])_aviGenLang="en";'
			. 'var _aviGenT=_aviGenI18n[_aviGenLang]||_aviGenI18n.en;'
			. 'var ctxLabel=document.createElement("label");'
			. 'ctxLabel.style.cssText="font-size:12px;color:#888;display:block;margin-bottom:4px;";'
			. 'ctxLabel.textContent=_aviGenT.ctxLabel;'
			. 'var ctxTa=document.createElement("textarea");'
			. 'ctxTa.id="avi-gen-context";'
			. 'ctxTa.rows=2;'
			. 'ctxTa.style.cssText="width:100%;font-size:12px;padding:6px;border:1px solid #e5e7eb;'
			. 'border-radius:6px;resize:vertical;margin-bottom:8px;";'
			. 'ctxTa.placeholder=_aviGenT.ctxPlaceholder;'
			. 'var genBtn=document.createElement("button");'
			. 'genBtn.type="button";genBtn.id="avi-generate-btn";'
			. 'genBtn.style.cssText="margin-bottom:8px;padding:6px 14px;background:#7c3aed;color:#fff;'
			. 'border:none;border-radius:6px;cursor:pointer;font-size:13px;";'
			. 'genBtn.textContent=_aviGenT.btn;'
			. 'var genLoader=document.createElement("span");'
			. 'genLoader.id="avi-generate-loader";'
			. 'genLoader.style.cssText="display:none;font-size:12px;color:#888;margin-left:8px;";'
			. 'genLoader.textContent=_aviGenT.loader;'
			. 'var genTip=document.createElement("div");'
			. 'genTip.className="avi-gen-tip";'
			. 'genTip.style.cssText="font-size:11px;color:#94a3b8;margin-bottom:8px;line-height:1.4;";'
			. 'genTip.textContent=_aviGenT.tooltip;'
			. 'var regenBtn=document.createElement("button");'
			. 'regenBtn.type="button";regenBtn.id="avi-regenerate-btn";'
			. 'regenBtn.style.cssText="display:none;margin-bottom:8px;margin-left:8px;padding:6px 14px;'
			. 'background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;border-radius:6px;'
			. 'cursor:pointer;font-size:13px;";'
			. 'regenBtn.textContent=_aviGenT.regenBtn;'
			. 'var contentTa=document.createElement("textarea");'
			. 'contentTa.id="avi-post-summary";'
			. 'contentTa.placeholder=_t.write_content_ph;'
			. 'var charCount=document.createElement("div");'
			. 'charCount.className="avi-posts-char-count";'
			. 'charCount.textContent="0"+_t.post_char_of;'
			. 'contentTa.addEventListener("input",function(){'
			. 'var len=contentTa.value.length;'
			. 'charCount.textContent=len+_t.post_char_of;'
			. 'charCount.className="avi-posts-char-count"+(len>1400?" warn":"")+(len>1500?" over":"");'
			. '});'
			. 'contentField.appendChild(contentLabel);'
			. 'contentField.appendChild(ctxLabel);'
			. 'contentField.appendChild(ctxTa);'
			. 'contentField.appendChild(genBtn);'
			. 'contentField.appendChild(regenBtn);'
			. 'contentField.appendChild(genLoader);'
			. 'contentField.appendChild(genTip);'
			. 'contentField.appendChild(contentTa);'
			. 'contentField.appendChild(charCount);'
			. 'pbody.appendChild(contentField);'
			. 'function _aviDoGenerate(isRegen){'
			. 'var btn=isRegen?regenBtn:genBtn;'
			. 'var loader=document.getElementById("avi-generate-loader");'
			. 'var ptMap={update:"STANDARD",offer:"OFFER",event:"EVENT"};'
			. 'var postTypeEl=document.getElementById("avi-post-type");'
			. 'var postType=ptMap[postTypeEl?postTypeEl.value:"update"]||"STANDARD";'
			. 'var lang=window.aviEmbedLang||_embedLang||"en";'
			. 'if(!_aviGenI18n[lang])lang="en";'
			. 'var _gT=_aviGenI18n[lang]||_aviGenI18n.en;'
			. 'var ctxEl=document.getElementById("avi-gen-context");'
			. 'var payload={'
			. 'post_type:postType,'
			. 'lang:lang,'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'context:ctxEl?ctxEl.value.trim():""'
			. '};'
			. 'if(isRegen){'
			. 'var taPrev=document.getElementById("avi-post-summary");'
			. 'payload.regenerate=true;'
			. 'payload.previous_draft=taPrev?taPrev.value.trim():"";'
			. '}'
			. 'btn.disabled=true;genBtn.disabled=true;regenBtn.disabled=true;'
			. 'if(loader)loader.style.display="inline";'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/avi-generate-post",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify(payload)'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success&&data.draft){'
			. 'var ta=document.getElementById("avi-post-summary");'
			. 'if(ta){ta.value=data.draft;ta.dispatchEvent(new Event("input"));}'
			. 'regenBtn.style.display="inline-block";'
			. '}else{alert(_gT.error);}'
			. '}).catch(function(){alert(_gT.errNet);})'
			. '.finally(function(){'
			. 'genBtn.disabled=false;regenBtn.disabled=false;'
			. 'if(loader)loader.style.display="none";'
			. '});'
			. '}'
			. 'genBtn.addEventListener("click",function(){_aviDoGenerate(false);});'
			. 'regenBtn.addEventListener("click",function(){_aviDoGenerate(true);});'
			. 'var photoField=document.createElement("div");'
			. 'photoField.className="avi-posts-field";'
			. 'var photoLabel=document.createElement("label");'
			. 'photoLabel.textContent=_t.photo_optional;'
			. 'photoField.appendChild(photoLabel);'
			. 'var photoZone=document.createElement("div");'
			. 'photoZone.className="avi-posts-photo-zone";'
			. 'photoZone.innerHTML="<div style=\\"color:#94a3b8;font-size:13px;\\">"+_t.post_add_photo+"</div>"'
			. '+"<div class=\\"avi-posts-photo-info\\">"+_t.post_photo_formats+"</div>";'
			. 'var photoFile=document.createElement("input");'
			. 'photoFile.type="file";photoFile.accept="image/jpeg,image/png,image/webp";'
			. 'photoFile.style.display="none";'
			. 'var photoPreview=null;'
			. 'var photoBase64=null;'
			. 'var photoFromGallery=null;'
			. 'var photoBtns=document.createElement("div");'
			. 'photoBtns.className="avi-posts-photo-btns";'
			. 'var uploadBtn=document.createElement("button");'
			. 'uploadBtn.type="button";uploadBtn.className="avi-posts-photo-btn";'
			. 'uploadBtn.textContent=_t.upload_device;'
			. 'uploadBtn.addEventListener("click",function(){'
			. 'photoFile.click();'
			. '});'
			. 'var galleryBtn=document.createElement("button");'
			. 'galleryBtn.type="button";galleryBtn.className="avi-posts-photo-btn from-gallery";'
			. 'galleryBtn.textContent=_t.choose_photos;'
			. 'galleryBtn.title=_t.gallery_soon;'
			. 'galleryBtn.addEventListener("click",function(){'
			. 'if(typeof _photosPickerOpen==="function"){'
			. '_photosPickerOpen(function(url){'
			. 'if(!url)return;'
			. 'photoFromGallery=url;photoBase64=null;'
			. 'photoZone.classList.add("has-photo");'
			. 'if(photoPreview)photoPreview.remove();'
			. 'photoPreview=document.createElement("img");'
			. 'photoPreview.className="avi-posts-photo-preview";'
			. 'photoPreview.src=url;'
			. 'photoZone.appendChild(photoPreview);'
			. '});'
			. '}else{'
			. 'alert(_t.gallery_first_alert);'
			. '}'
			. '});'
			. 'photoBtns.appendChild(uploadBtn);photoBtns.appendChild(galleryBtn);'
			. 'photoField.appendChild(photoZone);'
			. 'photoField.appendChild(photoBtns);'
			. 'photoField.appendChild(photoFile);'
			. 'pbody.appendChild(photoField);'
			. 'photoFile.addEventListener("change",function(){'
			. 'var file=photoFile.files[0];'
			. 'if(!file)return;'
			. 'if(file.size>5*1024*1024){'
			. 'alert(_t.image_too_large);return;'
			. '}'
			. 'var reader=new FileReader();'
			. 'reader.onload=function(e){'
			. 'photoBase64=e.target.result;'
			. 'photoFromGallery=null;'
			. 'photoZone.classList.add("has-photo");'
			. 'if(photoPreview)photoPreview.remove();'
			. 'photoPreview=document.createElement("img");'
			. 'photoPreview.className="avi-posts-photo-preview";'
			. 'photoPreview.src=photoBase64;'
			. 'photoZone.appendChild(photoPreview);'
			. 'photoZone.querySelector("div").style.display="none";'
			. '};'
			. 'reader.readAsDataURL(file);'
			. '});'
			. 'var schedLabel=document.createElement("label");'
			. 'schedLabel.style.cssText="display:block;font-size:12px;font-weight:600;'
			. 'color:#374151;margin-bottom:8px;";'
			. 'schedLabel.textContent=_t.publication;'
			. 'pbody.appendChild(schedLabel);'
			. 'var schedTypes=document.createElement("div");'
			. 'schedTypes.className="avi-posts-schedule-type";'
			. 'var optNow=document.createElement("div");'
			. 'optNow.className="avi-posts-schedule-opt selected";'
			. 'optNow.setAttribute("data-sched","now");'
			. 'optNow.innerHTML="<div class=\\"avi-posts-schedule-opt-title\\">"+_t.publish_now_title+"</div>"'
			. '+"<div class=\\"avi-posts-schedule-opt-sub\\">"+_t.free+"</div>";'
			. 'var optSched=document.createElement("div");'
			. 'optSched.className="avi-posts-schedule-opt";'
			. 'optSched.setAttribute("data-sched","scheduled");'
			. 'optSched.innerHTML="<div class=\\"avi-posts-schedule-opt-title\\">"+_t.schedule_title+"</div>"'
			. '+"<div class=\\"avi-posts-schedule-opt-sub credit\\">"+_t.credits_2+"</div>";'
			. 'schedTypes.appendChild(optNow);schedTypes.appendChild(optSched);'
			. 'pbody.appendChild(schedTypes);'
			. 'var creditInfo=document.createElement("div");'
			. 'creditInfo.className="avi-posts-credit-info";'
			. 'creditInfo.textContent=_t.credits_info;'
			. 'pbody.appendChild(creditInfo);'
			. 'var schedDateField=document.createElement("div");'
			. 'schedDateField.className="avi-posts-field";'
			. 'schedDateField.style.display="none";'
			. 'var schedDLabel=document.createElement("label");'
			. 'schedDLabel.textContent=_t.scheduled_date;'
			. 'var schedDInput=document.createElement("input");'
			. 'schedDInput.type="datetime-local";'
			. 'var minDate=new Date();minDate.setMinutes(minDate.getMinutes()+30);'
			. 'schedDInput.min=minDate.toISOString().slice(0,16);'
			. 'schedDateField.appendChild(schedDLabel);schedDateField.appendChild(schedDInput);'
			. 'pbody.appendChild(schedDateField);'
			. '[optNow,optSched].forEach(function(opt){'
			. 'opt.addEventListener("click",function(){'
			. 'isScheduled=opt.getAttribute("data-sched")==="scheduled";'
			. 'optNow.classList.toggle("selected",!isScheduled);'
			. 'optSched.classList.toggle("selected",isScheduled);'
			. 'schedDateField.style.display=isScheduled?"block":"none";'
			. 'creditInfo.classList.toggle("show",isScheduled);'
			. '});'
			. '});'
			. '_postsCreatePanel.appendChild(pbody);'
			. 'var pfooter=document.createElement("div");'
			. 'pfooter.className="avi-posts-create-footer";'
			. 'var cancelBtn2=document.createElement("button");'
			. 'cancelBtn2.type="button";cancelBtn2.className="avi-posts-cancel-btn";'
			. 'cancelBtn2.textContent=_t.cancel;'
			. 'cancelBtn2.addEventListener("click",function(){'
			. '_postsCreatePanel.classList.remove("open");'
			. '_postsCreateOverlay.classList.remove("open");'
			. '});'
			. 'var submitBtn2=document.createElement("button");'
			. 'submitBtn2.type="button";submitBtn2.className="avi-posts-submit-btn";'
			. 'submitBtn2.textContent=isScheduled?_t.schedule_post_credits:_t.publish_now;'
			. '[optNow,optSched].forEach(function(opt){'
			. 'opt.addEventListener("click",function(){'
			. 'submitBtn2.textContent=isScheduled'
			. '?_t.schedule_post_credits:_t.publish_now;'
			. '});'
			. '});'
			. 'submitBtn2.addEventListener("click",function(){'
			. 'var content=contentTa.value.trim();'
			. 'if(!content){alert(_t.err_no_content);return;}'
			. 'if(content.length>1500){alert(_t.err_content_long);return;}'
			. 'if(isScheduled&&!schedDInput.value){'
			. 'alert(_t.err_no_schedule);return;'
			. '}'
			. 'submitBtn2.disabled=true;'
			. 'submitBtn2.textContent=_t.publishing;'
			. 'var payload={'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'post_type:typeSel.value,'
			. 'content:content'
			. '};'
			. 'if(isScheduled)payload.scheduled_at=schedDInput.value;'
			. 'if(photoBase64)payload.photo_base64=photoBase64;'
			. 'if(photoFromGallery)payload.photo_url=photoFromGallery;'
			. 'if(typeSel.value==="event"){'
			. 'payload.event_title=evTInput.value;'
			. 'payload.event_start=evSInput.value;'
			. 'payload.event_end=evEInput.value;'
			. '}'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/create-post",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify(payload)'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. '_postsCreatePanel.classList.remove("open");'
			. '_postsCreateOverlay.classList.remove("open");'
			. 'if(!window.aviEmbedPostsData)window.aviEmbedPostsData=[];'
			. 'window.aviEmbedPostsData.unshift({'
			. 'id:data.post_id,'
			. 'post_type:typeSel.value,'
			. 'content:content,'
			. 'status:isScheduled?"scheduled":"published",'
			. 'scheduled_at:isScheduled?schedDInput.value:null,'
			. 'published_at:isScheduled?null:new Date().toISOString(),'
			. 'created_at:new Date().toISOString()'
			. '});'
			. '_postsRender();'
			. '}else{'
			. 'submitBtn2.disabled=false;'
			. 'submitBtn2.textContent=isScheduled?_t.schedule_post_credits:_t.publish_now;'
			. 'alert(data.message||_t.err_create_post);'
			. '}'
			. '}).catch(function(){'
			. 'submitBtn2.disabled=false;'
			. 'submitBtn2.textContent=isScheduled?_t.schedule_post_credits:_t.publish_now;'
			. 'alert(_t.err_network);'
			. '});'
			. '});'
			. 'pfooter.appendChild(cancelBtn2);pfooter.appendChild(submitBtn2);'
			. '_postsCreatePanel.appendChild(pfooter);'
			. '_postsCreateOverlay.classList.add("open");'
			. '_postsCreatePanel.classList.add("open");'
			. '}'
			. '_postsCreateOverlay.addEventListener("click",function(){'
			. '_postsCreatePanel.classList.remove("open");'
			. '_postsCreateOverlay.classList.remove("open");'
			. '});'
			. 'var _postsWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_postsWrap.appendChild(_postsPanel);'
			. '_agHubPanel=document.createElement("div");'
			. '_agHubPanel.id="aviEmbedAgHubPanel";'
			. '_agHubPanel.style.cssText="position:absolute;inset:0;background:#f8fafc;'
			. '  z-index:10;display:none;overflow-y:auto;padding:24px;";'
			. 'var _agHubClose=document.createElement("button");'
			. '_agHubClose.type="button";'
			. '_agHubClose.style.cssText="position:absolute;top:12px;right:16px;'
			. 'background:none;border:none;font-size:24px;color:#94a3b8;'
			. 'cursor:pointer;line-height:1;padding:4px;z-index:20;";'
			. '_agHubClose.textContent="×";'
			. '_agHubClose.addEventListener("click",function(){_switchEmbedTab("home");});'
			. 'function _agHubRender(){'
			. 'if(!_agHubPanel)return;'
			. 'var cr=window.aviEmbedAgencyCredits||{available:0,used:0};'
			. 'var logoUrl=window.aviEmbedLogoUrl||"";'
			. 'var brandName=window.aviEmbedWhiteLabel||"";'
			. '_agHubPanel.innerHTML=""'
			. '  +"<div style=\\"max-width:720px;margin:0 auto;\\">"'
			. '  +"<h2 style=\\"font-size:20px;font-weight:700;color:#0f172a;margin-bottom:4px;\\">"+_t.agency_hub_title+"</h2>"'
			. '  +"<p style=\\"color:#64748b;font-size:13px;margin-bottom:24px;\\">"+_t.hub_subtitle+"</p>";'
			. 'var tierLabel=_t.hub_tier_t1;'
			. 'if(window.aviEmbedAgencyTier===2){tierLabel=_t.hub_tier_t2;}'
			. 'if(window.aviEmbedAgencyTier===3){tierLabel=_t.hub_tier_t3;}'
			. 'var usedPct=window.aviEmbedAgencyMaxListings>0'
			. '  ?Math.min(100,Math.round((window.aviEmbedAgencyUsedListings/window.aviEmbedAgencyMaxListings)*100))'
			. '  :0;'
			. 'var gaugeColor=usedPct>=90?"#ef4444":usedPct>=70?"#f97316":"#7c3aed";'
			. 'var tierBlock=document.createElement("div");'
			. 'tierBlock.className="avi-hub-tier-block";'
			. 'tierBlock.innerHTML="<div class=\\"avi-hub-tier-header\\"><span class=\\"avi-hub-tier-badge\\">"+tierLabel+"</span></div>"'
			. '  +"<div class=\\"avi-hub-tier-info\\"><strong>\\u2139\\ufe0f "+_t.hub_tier_label+"</strong><br>"'
			. '  +"<div style=\\"display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap;\\">"'
			. '  +"<span style=\\"background:#f5f3ff;border:1px solid #ddd6fe;border-radius:6px;padding:3px 10px;font-size:11px;color:#7c3aed;font-weight:600;\\">T1 "+window.aviEmbedAgencyPrices.t1+" — 10 listings</span>"'
			. '  +"<span style=\\"background:#f5f3ff;border:1px solid #ddd6fe;border-radius:6px;padding:3px 10px;font-size:11px;color:#7c3aed;font-weight:600;\\">T2 "+window.aviEmbedAgencyPrices.t2+" — 50 listings</span>"'
			. '  +"<span style=\\"background:#f5f3ff;border:1px solid #ddd6fe;border-radius:6px;padding:3px 10px;font-size:11px;color:#7c3aed;font-weight:600;\\">T3 "+window.aviEmbedAgencyPrices.t3+" — unlimited</span>"'
			. '  +"</div>"'
			. '  +_t.hub_info_upgrade+"<br>"'
			. '  +"<span style=\\"color:#64748b;font-size:11px;\\">"+_t.hub_info_downgrade+"</span></div>"'
			. '  +"<div class=\\"avi-hub-gauge-wrap\\">"'
			. '  +"<div class=\\"avi-hub-gauge-label\\">"+_t.hub_listings_gauge+" : <strong>"+window.aviEmbedAgencyUsedListings+"/"+window.aviEmbedAgencyMaxListings+"</strong></div>"'
			. '  +"<div class=\\"avi-hub-gauge-bar\\"><div class=\\"avi-hub-gauge-fill\\" style=\\"width:"+usedPct+"%;background:"+gaugeColor+"\\"></div></div>"'
			. '  +"</div>"'
			. '  +"<div class=\\"avi-hub-tier-actions\\">"'
			. '  +(window.aviEmbedAgencyTier<3'
			. '    ?"<button type=\\"button\\" class=\\"avi-hub-tier-btn avi-hub-tier-up\\" data-tier=\\""+(window.aviEmbedAgencyTier+1)+"\\">"+_t.hub_tier_upgrade+" \\u2191</button>"'
			. '    :"")'
			. '  +(window.aviEmbedAgencyTier>1'
			. '    ?"<button type=\\"button\\" class=\\"avi-hub-tier-btn avi-hub-tier-down\\" data-tier=\\""+(window.aviEmbedAgencyTier-1)+"\\">"+_t.hub_tier_downgrade+" \\u2193</button>"'
			. '    :"")'
			. '  +"</div>";'
			. 'if(_agHubPanel.firstElementChild){_agHubPanel.firstElementChild.appendChild(tierBlock);}'
			. 'var upBtn=tierBlock.querySelector(".avi-hub-tier-up");'
			. 'var downBtn=tierBlock.querySelector(".avi-hub-tier-down");'
			. 'if(upBtn){upBtn.addEventListener("click",function(){window._agTierChange(parseInt(this.getAttribute("data-tier"),10));});}'
			. 'if(downBtn){downBtn.addEventListener("click",function(){window._agTierChange(parseInt(this.getAttribute("data-tier"),10));});}'
			. 'if(_agHubPanel.firstElementChild){_agHubPanel.firstElementChild.insertAdjacentHTML("beforeend",'
			. '  "<div style=\\"background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:20px;margin-bottom:16px;\\">"'
			. '  +"<h3 class=\\"avi-hub-credit-title\\" style=\\"font-size:14px;font-weight:600;color:#1e293b;margin-bottom:12px;\\">"+_t.hub_credit_pool+"</h3>"'
			. '  +"<div style=\\"display:flex;gap:16px;flex-wrap:wrap;margin-bottom:12px;\\">"'
			. '  +"<div style=\\"flex:1;min-width:120px;background:#f5f3ff;border-radius:8px;padding:12px;text-align:center;\\">"'
			. '  +"<div style=\\"font-size:24px;font-weight:700;color:#7c3aed;\\">"+cr.available+"</div>"'
			. '  +"<div style=\\"font-size:11px;color:#64748b;margin-top:4px;\\">"+_t.hub_available+"</div></div>"'
			. '  +"<div style=\\"flex:1;min-width:120px;background:#f8fafc;border-radius:8px;padding:12px;text-align:center;\\">"'
			. '  +"<div style=\\"font-size:24px;font-weight:700;color:#475569;\\">"+cr.used+"</div>"'
			. '  +"<div style=\\"font-size:11px;color:#64748b;margin-top:4px;\\">"+_t.hub_used+"</div></div>"'
			. '  +"</div>"'
			. '  +"</div>");}'
			. 'var _agCredInfoBtn=document.createElement("button");'
			. '_agCredInfoBtn.type="button";'
			. '_agCredInfoBtn.style.cssText="background:none;'
			. '  border:1px solid #7c3aed;border-radius:50%;'
			. '  width:18px;height:18px;font-size:10px;'
			. '  color:#7c3aed;cursor:pointer;'
			. '  margin-left:8px;line-height:1;padding:0;";'
			. '_agCredInfoBtn.textContent="\\u2139";'
			. '_agCredInfoBtn.title=_t.credits_modal_agency_title'
			. '  ||"How credits work";'
			. 'var _agCredModal=document.createElement("div");'
			. '_agCredModal.style.cssText="display:none;'
			. '  position:fixed;inset:0;background:rgba(0,0,0,.5);'
			. '  z-index:99999;align-items:center;'
			. '  justify-content:center;";'
			. 'var _agCredModalBox=document.createElement("div");'
			. '_agCredModalBox.style.cssText="background:#fff;'
			. '  border-radius:14px;padding:28px;'
			. '  max-width:440px;width:90%;'
			. '  max-height:80vh;overflow-y:auto;'
			. '  position:relative;";'
			. 'var _agCredModalClose=document.createElement("button");'
			. '_agCredModalClose.type="button";'
			. '_agCredModalClose.style.cssText="position:absolute;'
			. '  top:12px;right:16px;background:none;border:none;'
			. '  font-size:20px;cursor:pointer;color:#64748b;";'
			. '_agCredModalClose.textContent="\\u00d7";'
			. 'var _agCredModalTitle=document.createElement("h3");'
			. '_agCredModalTitle.style.cssText="font-size:16px;'
			. '  font-weight:700;color:#0f172a;margin-bottom:16px;";'
			. '_agCredModalTitle.textContent='
			. '  _t.credits_modal_agency_title'
			. '  ||"\\uD83D\\uDCB3 Your Agency Credit Pool";'
			. 'var _agCredModalContent=document.createElement("div");'
			. '_agCredModalContent.style.cssText="font-size:13px;'
			. '  color:#475569;line-height:1.7;";'
			. 'var _agItems=['
			. '  {t:"p",c:_t.credits_modal_agency_p1},'
			. '  {t:"h",c:_t.credits_modal_usage_title},'
			. '  {t:"li",c:_t.credits_modal_heatmap},'
			. '  {t:"li",c:_t.credits_modal_post},'
			. '  {t:"li",c:_t.credits_modal_photo},'
			. '  {t:"li",c:_t.credits_modal_guardian},'
			. '  {t:"h",c:_t.credits_modal_agency_wholesale},'
			. '  {t:"p",c:_t.credits_modal_agency_noexpiry}'
			. '];'
			. '_agItems.forEach(function(item){'
			. '  var el=document.createElement("p");'
			. '  if(item.t==="h"){'
			. '    el.style.cssText="font-weight:600;'
			. '      color:#0f172a;margin:14px 0 6px;";'
			. '  }else if(item.t==="li"){'
			. '    el.style.cssText="padding-left:16px;'
			. '      margin-bottom:4px;";'
			. '  }else{'
			. '    el.style.marginBottom="10px";'
			. '  }'
			. '  el.textContent=item.c||"";'
			. '  _agCredModalContent.appendChild(el);'
			. '});'
			. '_agCredModalBox.appendChild(_agCredModalClose);'
			. '_agCredModalBox.appendChild(_agCredModalTitle);'
			. '_agCredModalBox.appendChild(_agCredModalContent);'
			. '_agCredModal.appendChild(_agCredModalBox);'
			. 'document.body.appendChild(_agCredModal);'
			. 'var _agCrTitle=_agHubPanel.querySelector('
			. '  ".avi-hub-credit-title"'
			. ');'
			. 'if(_agCrTitle){'
			. '  _agCrTitle.appendChild(_agCredInfoBtn);'
			. '}'
			. '_agCredInfoBtn.addEventListener("click",function(){'
			. '  _agCredModal.style.display="flex";'
			. '});'
			. '_agCredModalClose.addEventListener("click",function(){'
			. '  _agCredModal.style.display="none";'
			. '});'
			. '_agCredModal.addEventListener("click",function(e){'
			. '  if(e.target===_agCredModal){'
			. '    _agCredModal.style.display="none";'
			. '  }'
			. '});'
			. '_agHubPanel.appendChild(_agHubClose);'
			. 'var _agInnerWrap=_agHubPanel.firstElementChild;'
			. 'var _agAccordion=document.createElement("div");'
			. '_agAccordion.style.cssText="background:#fff;'
			. '  border:1px solid #e2e8f0;border-radius:10px;'
			. '  margin-bottom:16px;max-width:640px;'
			. '  margin-left:auto;margin-right:auto;'
			. '  overflow:hidden;";'
			. 'var _agAccHeader=document.createElement("button");'
			. '_agAccHeader.type="button";'
			. '_agAccHeader.style.cssText="width:100%;display:flex;'
			. '  align-items:center;justify-content:space-between;'
			. '  padding:16px 20px;background:none;border:none;'
			. '  cursor:pointer;font-size:14px;font-weight:600;'
			. '  color:#0f172a;";'
			. 'var _agAccLabel=document.createElement("span");'
			. '_agAccLabel.textContent='
			. '  (_t.profile_buy||"+ Buy credits");'
			. 'var _agAccArrow=document.createElement("span");'
			. '_agAccArrow.textContent="\\u25be";'
			. '_agAccArrow.style.cssText="font-size:16px;'
			. '  color:#7c3aed;transition:transform .2s;";'
			. '_agAccHeader.appendChild(_agAccLabel);'
			. '_agAccHeader.appendChild(_agAccArrow);'
			. 'var _agAccBody=document.createElement("div");'
			. '_agAccBody.style.cssText="display:none;'
			. '  padding:0 20px 16px;";'
			. '_agAccHeader.addEventListener("click",function(){'
			. '  var open=_agAccBody.style.display!=="none";'
			. '  _agAccBody.style.display=open?"none":"block";'
			. '  _agAccArrow.style.transform='
			. '    open?"":"rotate(-180deg)";'
			. '});'
			. '_agAccordion.appendChild(_agAccHeader);'
			. '_agAccordion.appendChild(_agAccBody);'
			. 'var _agPacks=[['
			. '  "starter_agency",'
			. '  "ag_pack_starter",'
			. '  "ag_price_starter",'
			. '  "-16%","100"'
			. '],['
			. '  "standard_agency",'
			. '  "ag_pack_standard",'
			. '  "ag_price_standard",'
			. '  "-30%","300"'
			. '],['
			. '  "pro_agency",'
			. '  "ag_pack_pro",'
			. '  "ag_price_pro",'
			. '  "-40%","750"'
			. '],['
			. '  "enterprise_agency",'
			. '  "ag_pack_enterprise",'
			. '  "ag_price_enterprise",'
			. '  "-47%","2000"'
			. ']];'
			. 'var packType="agency";'
			. 'var _agDiscountMap={'
			. '  "-16%":(_t.badge_discount_16||"-16%")+" "+(_t.vs_standard||"vs standard"),'
			. '  "-30%":(_t.badge_discount_30||"-30%")+" "+(_t.vs_standard||"vs standard"),'
			. '  "-40%":(_t.badge_discount_40||"-40%")+" "+(_t.vs_standard||"vs standard"),'
			. '  "-47%":(_t.badge_discount_47||"-47%")+" "+(_t.vs_standard||"vs standard")'
			. '};'
			. '_agPacks.forEach(function(pk){'
			. '  var row=document.createElement("div");'
			. '  row.style.cssText="display:flex;align-items:center;'
			. '    justify-content:space-between;background:#fff;'
			. '    border:1px solid #e2e8f0;border-radius:10px;'
			. '    padding:14px 16px;margin-bottom:10px;'
			. '    cursor:pointer;";'
			. '  row.addEventListener("mouseenter",function(){'
			. '    row.style.borderColor="#7c3aed";'
			. '  });'
			. '  row.addEventListener("mouseleave",function(){'
			. '    row.style.borderColor="#e2e8f0";'
			. '  });'
			. '  var left=document.createElement("div");'
			. '  var name=document.createElement("div");'
			. '  name.style.cssText="font-weight:600;color:#0f172a;'
			. '    font-size:14px;";'
			. '  name.textContent=(_t[pk[1]]||pk[1]);'
			. '  var credits=document.createElement("div");'
			. '  credits.style.cssText="font-size:12px;color:#7c3aed;'
			. '    margin-top:2px;";'
			. '  credits.textContent=pk[4]+" "+(_t.slider_credits||"credits");'
			. '  left.appendChild(name);left.appendChild(credits);'
			. '  var right=document.createElement("div");'
			. '  right.style.cssText="display:flex;align-items:center;'
			. '    gap:8px;";'
			. '  if(pk[3]){'
			. '    var badge=document.createElement("span");'
			. '    badge.style.cssText="background:#dcfce7;color:#16a34a;'
			. '      font-size:10px;font-weight:700;padding:2px 6px;'
			. '      border-radius:99px;";'
			. '    badge.textContent=_agDiscountMap[pk[3]]||pk[3];'
			. '    right.appendChild(badge);'
			. '  }'
			. '  var price=document.createElement("div");'
			. '  price.style.cssText="font-size:16px;font-weight:700;'
			. '    color:#0f172a;";'
			. '  price.textContent=(_t[pk[2]]||pk[2]);'
			. '  var buyBtn=document.createElement("button");'
			. '  buyBtn.type="button";'
			. '  buyBtn.style.cssText="background:#7c3aed;color:#fff;'
			. '    border:none;border-radius:6px;padding:7px 14px;'
			. '    font-size:12px;font-weight:600;cursor:pointer;";'
			. '  buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '  (function(packId,packType){'
			. '    buyBtn.addEventListener("click",function(e){'
			. '      e.stopPropagation();'
			. '      buyBtn.disabled=true;'
			. '      buyBtn.textContent="...";'
			. '      fetch(window.aviEmbedRestUrl'
			. '        +"embed/checkout",{'
			. '        method:"POST",'
			. '        headers:{'
			. '          "Content-Type":"application/json",'
			. '          "X-Embed-Token":window.aviEmbedToken||""'
			. '        },'
			. '        body:JSON.stringify({'
			. '          pack:packId,'
			. '          key_id:window.aviEmbedKeyId||"",'
			. '          profile_id:window.aviEmbedProfileId||0,'
			. '          type:packType'
			. '        })'
			. '      })'
			. '      .then(function(r){return r.json();})'
			. '      .then(function(d){'
			. '        if(d&&d.checkout_url){'
			. '          window.open(d.checkout_url,"_blank");'
			. '        }else{'
			. '          alert(d.message||_t.error_generic||"Error");'
			. '        }'
			. '        buyBtn.disabled=false;'
			. '        buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '      })'
			. '      .catch(function(){'
			. '        buyBtn.disabled=false;'
			. '        buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '      });'
			. '    });'
			. '  })(pk[0],packType);'
			. '  right.appendChild(price);'
			. '  right.appendChild(buyBtn);'
			. '  row.appendChild(left);row.appendChild(right);'
			. '  _agAccBody.appendChild(row);'
			. '});'
			. 'var _agSep=document.createElement("div");'
			. '_agSep.style.cssText="display:flex;'
			. '  align-items:center;gap:12px;margin:20px 0 16px;";'
			. 'var _agLine1=document.createElement("div");'
			. '_agLine1.style.cssText="flex:1;height:1px;'
			. '  background:#e2e8f0;";'
			. 'var _agSlLabel=document.createElement("span");'
			. '_agSlLabel.style.cssText="font-size:12px;'
			. '  color:#94a3b8;white-space:nowrap;";'
			. '_agSlLabel.textContent=_t.slider_title'
			. '  ||"Or choose your own amount";'
			. 'var _agLine2=document.createElement("div");'
			. '_agLine2.style.cssText="flex:1;height:1px;'
			. '  background:#e2e8f0;";'
			. '_agSep.appendChild(_agLine1);'
			. '_agSep.appendChild(_agSlLabel);'
			. '_agSep.appendChild(_agLine2);'
			. '_agAccBody.appendChild(_agSep);'
			. 'var _agTiers=['
			. '  {min:1,max:99,price:0.140},'
			. '  {min:100,max:299,price:0.117},'
			. '  {min:300,max:749,price:0.100},'
			. '  {min:750,max:1999,price:0.093},'
			. '  {min:2000,max:5000,price:0.088}'
			. '];'
			. 'function _agGetPrice(cr){'
			. '  var p=0.140;'
			. '  _agTiers.forEach(function(t){'
			. '    if(cr>=t.min&&cr<=t.max)p=t.price;'
			. '  });'
			. '  return p;'
			. '}'
			. 'function _agFormat(n){'
			. '  return "$"+(n%1===0?n.toFixed(2):'
			. '    n.toFixed(2));'
			. '}'
			. 'function _agSaving(price){'
			. '  var base=0.140;'
			. '  var pct=Math.round((base-price)/base*100);'
			. '  return pct>0?"-"+pct+"% "+(_t.slider_vs_nano'
			. '    ||"vs Nano"):"";'
			. '}'
			. 'var _agSlWrap=document.createElement("div");'
			. '_agSlWrap.style.cssText="background:#fff;'
			. '  border:1px solid #e2e8f0;border-radius:10px;'
			. '  padding:20px;margin-bottom:10px;";'
			. 'var _agMinMax=document.createElement("div");'
			. '_agMinMax.style.cssText="display:flex;'
			. '  justify-content:space-between;'
			. '  font-size:11px;color:#94a3b8;'
			. '  margin-bottom:6px;";'
			. 'var _agMinLbl=document.createElement("span");'
			. '_agMinLbl.textContent=_t.slider_min_label||"10 cr";'
			. 'var _agMaxLbl=document.createElement("span");'
			. '_agMaxLbl.textContent=_t.slider_max_label_agency'
			. '  ||"5,000 cr";'
			. '_agMinMax.appendChild(_agMinLbl);'
			. '_agMinMax.appendChild(_agMaxLbl);'
			. '_agSlWrap.appendChild(_agMinMax);'
			. 'var _agInput=document.createElement("input");'
			. '_agInput.type="range";'
			. '_agInput.min="10";'
			. '_agInput.max="5000";'
			. '_agInput.step="50";'
			. '_agInput.value="100";'
			. '_agInput.style.cssText="width:100%;'
			. '  accent-color:#7c3aed;cursor:pointer;'
			. '  margin-bottom:16px;";'
			. '_agSlWrap.appendChild(_agInput);'
			. 'var _agSummary=document.createElement("div");'
			. '_agSummary.style.cssText="display:flex;'
			. '  align-items:center;justify-content:space-between;'
			. '  flex-wrap:wrap;gap:8px;";'
			. 'var _agLeft=document.createElement("div");'
			. 'var _agCrDisplay=document.createElement("div");'
			. '_agCrDisplay.style.cssText="font-size:22px;'
			. '  font-weight:700;color:#0f172a;";'
			. 'var _agPriceDisplay=document.createElement("div");'
			. '_agPriceDisplay.style.cssText="font-size:12px;'
			. '  color:#7c3aed;margin-top:2px;";'
			. 'var _agSavingDisplay=document.createElement("div");'
			. '_agSavingDisplay.style.cssText="font-size:11px;'
			. '  color:#16a34a;margin-top:2px;";'
			. '_agLeft.appendChild(_agCrDisplay);'
			. '_agLeft.appendChild(_agPriceDisplay);'
			. '_agLeft.appendChild(_agSavingDisplay);'
			. 'var _agBuyBtn=document.createElement("button");'
			. '_agBuyBtn.type="button";'
			. '_agBuyBtn.style.cssText="background:#7c3aed;'
			. '  color:#fff;border:none;border-radius:8px;'
			. '  padding:12px 24px;font-size:14px;'
			. '  font-weight:700;cursor:pointer;'
			. '  white-space:nowrap;";'
			. '_agSummary.appendChild(_agLeft);'
			. '_agSummary.appendChild(_agBuyBtn);'
			. '_agSlWrap.appendChild(_agSummary);'
			. '_agAccBody.appendChild(_agSlWrap);'
			. 'function _agUpdate(){'
			. '  var cr=parseInt(_agInput.value,10);'
			. '  var price=_agGetPrice(cr);'
			. '  var total=cr*price;'
			. '  var saving=_agSaving(price);'
			. '  _agCrDisplay.textContent=cr+" "+'
			. '    (_t.slider_credits||"credits");'
			. '  _agPriceDisplay.textContent='
			. '    _agFormat(total)+" — "'
			. '    +price.toFixed(3)+" "'
			. '    +(_t.slider_price_per||"per credit");'
			. '  _agSavingDisplay.textContent=saving;'
			. '  _agBuyBtn.textContent='
			. '    (_t.slider_buy_btn||"Buy")+" "'
			. '    +_agFormat(total);'
			. '}'
			. '_agInput.addEventListener("input",_agUpdate);'
			. '_agBuyBtn.addEventListener("click",function(){'
			. '  var cr=parseInt(_agInput.value,10);'
			. '  _agBuyBtn.disabled=true;'
			. '  _agBuyBtn.textContent="...";'
			. '  fetch(window.aviEmbedRestUrl+"embed/checkout",{'
			. '    method:"POST",'
			. '    headers:{'
			. '      "Content-Type":"application/json",'
			. '      "X-Embed-Token":window.aviEmbedToken||""'
			. '    },'
			. '    body:JSON.stringify({'
			. '      credits:cr,'
			. '      key_id:window.aviEmbedKeyId||"",'
			. '      profile_id:window.aviEmbedProfileId||0,'
			. '      type:"agency"'
			. '    })'
			. '  })'
			. '  .then(function(r){return r.json();})'
			. '  .then(function(d){'
			. '    if(d&&d.checkout_url){'
			. '      window.open(d.checkout_url,"_blank");'
			. '    }else{'
			. '      alert(d.message||_t.error_generic||"Error");'
			. '    }'
			. '    _agBuyBtn.disabled=false;'
			. '    _agUpdate();'
			. '  })'
			. '  .catch(function(){'
			. '    _agBuyBtn.disabled=false;'
			. '    _agUpdate();'
			. '  });'
			. '});'
			. '_agUpdate();'
			. 'if(_agInnerWrap)_agInnerWrap.appendChild(_agAccordion);'
			. 'else _agHubPanel.appendChild(_agAccordion);'
			. 'if(_agInnerWrap){'
			. '_agInnerWrap.insertAdjacentHTML("beforeend",'
			. '  "<div style=\\"background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:20px;margin-bottom:16px;\\">"'
			. '  +"<h3 style=\\"font-size:14px;font-weight:600;color:#1e293b;margin-bottom:12px;\\">"+_t.hub_whitelabel+"</h3>"'
			. '  +"<p style=\\"font-size:12px;color:#64748b;margin-bottom:12px;\\">"+_t.hub_whitelabel_desc+"</p>"'
			. '  +"<input type=\\"text\\" id=\\"aviAgLogoUrl\\" placeholder=\\""+_t.hub_logo_ph+"\\" value=\\""+logoUrl+"\\" style=\\"border:1px solid #e2e8f0;border-radius:6px;font-size:12px;padding:8px 12px;width:100%;box-sizing:border-box;margin-bottom:4px;\\">"'
			. '  +"<img id=\\"aviAgLogoPreview\\" src=\\""+logoUrl+"\\" style=\\"max-height:48px;max-width:160px;object-fit:contain;border:1px solid #e2e8f0;border-radius:6px;padding:4px;margin-top:6px;display:block;\\" onerror=\\"this.style.display=\\u0027none\\u0027\\" onload=\\"this.style.display=\\u0027block\\u0027\\" />"'
			. '  +"<input type=\\"text\\" id=\\"aviAgBrandName\\" placeholder=\\""+_t.hub_brand_ph+"\\" value=\\""+brandName+"\\" style=\\"border:1px solid #e2e8f0;border-radius:6px;font-size:12px;padding:8px 12px;width:100%;box-sizing:border-box;margin-bottom:8px;margin-top:8px;\\">"'
			. '  +"<button type=\\"button\\" id=\\"aviAgHubSaveBtn\\"'
			. '    style=\\"background:#0f172a;border:none;border-radius:6px;color:#fff;cursor:pointer;'
			. '    font-size:12px;padding:8px 16px;\\">"+_t.hub_save_settings+"</button>"'
			. '  +"</div>"'
			. '  +"<div style=\\"background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:20px;margin-bottom:16px;\\">"'
			. '  +"<h3 style=\\"font-size:14px;font-weight:600;color:#1e293b;margin-bottom:8px;\\">"+_t.hub_import_clients+"</h3>"'
			. '  +"<p style=\\"font-size:12px;color:#64748b;margin-bottom:12px;\\">"+_t.hub_import_csv_desc+"</p>"'
			. '  +"<button type=\\"button\\" id=\\"aviAgHubImportBtn\\"'
			. '    style=\\"background:#0284c7;border:none;border-radius:6px;color:#fff;cursor:pointer;'
			. '    font-size:12px;padding:8px 16px;\\">"+_t.hub_import_csv_btn+"</button>"'
			. '  +"</div>"'
			. '  +"<div style=\\"background:linear-gradient(135deg,#1e1b4b,#312e81);border-radius:10px;padding:20px;text-align:center;\\">"'
			. '  +"<div style=\\"font-size:16px;font-weight:700;color:#fff;margin-bottom:6px;\\">"+_t.hub_pro_title+"</div>"'
			. '  +"<div style=\\"font-size:12px;color:rgba(255,255,255,0.7);margin-bottom:14px;\\">"+_t.hub_pro_sub+"</div>"'
			. '  +"<a href=\\"https://avision.org/\\" target=\\"_blank\\"'
			. '    style=\\"background:#7c3aed;border-radius:6px;color:#fff;display:inline-block;'
			. '    font-size:13px;font-weight:700;padding:10px 24px;text-decoration:none;\\">"+_t.hub_pro_cta+"</a>"'
			. '  +"</div>"'
			. '  +"</div>");'
			. '}'
			. 'var _agLogoInput=document.getElementById("aviAgLogoUrl");'
			. 'if(_agLogoInput)_agLogoInput.addEventListener("input",function(){'
			. 'var prev=document.getElementById("aviAgLogoPreview");'
			. 'if(prev)prev.src=this.value;'
			. '});'
			. 'var _hubSave=document.getElementById("aviAgHubSaveBtn");'
			. 'if(_hubSave)_hubSave.addEventListener("click",function(){'
			. 'var saveBtn=_hubSave;'
			. 'fetch("/wp-json/avision/v1/embed/update-key",{'
			. 'method:"POST",'
			. 'headers:{'
			. '"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken||""'
			. '},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'key_id:window.aviEmbedKeyId,'
			. 'logo_url:document.getElementById("aviAgLogoUrl").value||"",'
			. 'white_label_name:document.getElementById("aviAgBrandName").value||""'
			. '})'
			. '})'
			. '.then(function(r){return r.json();})'
			. '.then(function(d){'
			. 'if(d.success){'
			. 'window.aviEmbedLogoUrl=d.logo_url||"";'
			. 'window.aviEmbedWhiteLabel=d.white_label_name||window.aviEmbedWhiteLabel;'
			. 'if(typeof _applyWlBanner==="function")_applyWlBanner();'
			. 'saveBtn.textContent=_t.saved||"Saved \\u2713";'
			. 'setTimeout(function(){saveBtn.textContent=_t.hub_save_settings;},2000);'
			. '}else{'
			. 'saveBtn.textContent=_t.edit_error||"Error";'
			. 'setTimeout(function(){saveBtn.textContent=_t.hub_save_settings;},2000);'
			. '}'
			. '})'
			. '.catch(function(){'
			. 'saveBtn.textContent=_t.edit_error||"Error";'
			. 'setTimeout(function(){saveBtn.textContent=_t.hub_save_settings;},2000);'
			. '});'
			. '});'
			. 'var _hubImp=document.getElementById("aviAgHubImportBtn");'
			. 'if(_hubImp)_hubImp.addEventListener("click",function(){alert(_t.hub_import_alert);});'
			. '}'
			. 'function _agTierChange(newTier){'
			. 'var confirmed=true;'
			. 'if(newTier<window.aviEmbedAgencyTier){'
			. '  confirmed=confirm(_t.hub_downgrade_confirm);'
			. '}'
			. 'if(!confirmed){return;}'
			. 'var upgradeBtn=document.querySelector(".avi-hub-tier-up");'
			. 'var downgradeBtn=document.querySelector(".avi-hub-tier-down");'
			. 'if(upgradeBtn){upgradeBtn.disabled=true;upgradeBtn.textContent=_t.hub_upgrade_processing;}'
			. 'if(downgradeBtn){downgradeBtn.disabled=true;}'
			. 'fetch(window.aviEmbedRestUrl+"embed/agency-tier-change",{'
			. '  method:"POST",'
			. '  headers:{'
			. '    "Content-Type":"application/json",'
			. '    "X-Embed-Token":window.aviEmbedToken||""'
			. '  },'
			. '  body:JSON.stringify({'
			. '    key_id:window.aviEmbedKeyId,'
			. '    profile_id:window.aviEmbedProfileId,'
			. '    agency_id:window.aviEmbedAgencyId,'
			. '    new_tier:newTier,'
			. '    lang:_embedLang'
			. '  })'
			. '}).then(function(r){return r.json();}).then(function(data){'
			. '  if(data.success){'
			. '    if(data.action==="upgrade"){'
			. '      window.location.href=data.checkout_url;'
			. '    }else{'
			. '      window.aviEmbedAgencyTier=newTier;'
			. '      window.aviEmbedAgencyMaxListings=data.max_listings;'
			. '      _agHubRender();'
			. '      var msg=document.createElement("div");'
			. '      msg.className="avi-hub-tier-success";'
			. '      msg.textContent=_t.hub_downgrade_success;'
			. '      document.body.appendChild(msg);'
			. '      setTimeout(function(){msg.remove();},3000);'
			. '    }'
			. '  }else{'
			. '    var errMsg=data.message||(data.code==="downgrade_blocked"?_t.hub_downgrade_blocked:"Error");'
			. '    alert(errMsg);'
			. '    if(upgradeBtn){upgradeBtn.disabled=false;upgradeBtn.textContent=_t.hub_tier_upgrade+" \\u2191";}'
			. '    if(downgradeBtn){downgradeBtn.disabled=false;}'
			. '  }'
			. '}).catch(function(){'
			. '  alert("Network error");'
			. '  if(upgradeBtn){upgradeBtn.disabled=false;}'
			. '  if(downgradeBtn){downgradeBtn.disabled=false;}'
			. '});'
			. '}'
			. 'window._agTierChange=_agTierChange;'
			. 'var _agHubWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_agHubWrap.appendChild(_agHubPanel);'
			. '_agHubRender();'
			. 'if(window.aviEmbedKeyType!=="agency"){'
			. '  _profilePanel=document.createElement("div");'
			. '  _profilePanel.id="aviEmbedProfilePanel";'
			. '  _profilePanel.style.cssText="position:absolute;'
			. '    inset:0;background:#f8fafc;z-index:10;'
			. '    display:none;overflow-y:auto;padding:24px;";'
			. '  var _profileClose=document.createElement("button");'
			. '  _profileClose.type="button";'
			. '  _profileClose.style.cssText="position:absolute;'
			. '    top:16px;right:16px;background:none;border:none;'
			. '    font-size:20px;cursor:pointer;color:#64748b;";'
			. '  _profileClose.textContent="\\u00d7";'
			. '  _profileClose.addEventListener("click",function(){'
			. '    _switchEmbedTab("home");'
			. '  });'
			. '  _profilePanel.appendChild(_profileClose);'
			. '  function _profileRender(){'
			. '    var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. '    var _pWrap=document.createElement("div");'
			. '    _pWrap.style.cssText="max-width:480px;margin:0 auto;'
			. '      padding-top:16px;";'
			. '    var _pTitle=document.createElement("h2");'
			. '    _pTitle.style.cssText="font-size:18px;font-weight:700;'
			. '      color:#0f172a;margin-bottom:4px;";'
			. '    _pTitle.textContent=_t.profile_title||"My Profile";'
			. '    _pWrap.appendChild(_pTitle);'
			. '    var _pSub=document.createElement("p");'
			. '    _pSub.style.cssText="color:#64748b;font-size:13px;'
			. '      margin-bottom:24px;";'
			. '    _pSub.textContent=_t.profile_subtitle||'
			. '      "Manage your credits and account.";'
			. '    _pWrap.appendChild(_pSub);'
			. '    var _pCredBox=document.createElement("div");'
			. '    _pCredBox.style.cssText="background:#fff;border-radius:12px;'
			. '      border:1px solid #e2e8f0;padding:20px;margin-bottom:20px;";'
			. '    var _pCredTitle=document.createElement("div");'
			. '    _pCredTitle.style.cssText="font-size:13px;font-weight:600;'
			. '      color:#64748b;text-transform:uppercase;'
			. '      letter-spacing:.05em;margin-bottom:12px;";'
			. '    _pCredTitle.textContent='
			. '      (_t.hub_credit_pool||"Credits");'
			. '    var _pCredInfoBtn=document.createElement("button");'
			. '    _pCredInfoBtn.type="button";'
			. '    _pCredInfoBtn.style.cssText="background:none;'
			. '      border:1px solid #7c3aed;border-radius:50%;'
			. '      width:18px;height:18px;font-size:10px;'
			. '      color:#7c3aed;cursor:pointer;'
			. '      margin-left:8px;line-height:1;'
			. '      vertical-align:middle;padding:0;";'
			. '    _pCredInfoBtn.textContent="\\u2139";'
			. '    _pCredInfoBtn.title=_t.credits_modal_title'
			. '      ||"How credits work";'
			. '    _pCredTitle.appendChild(_pCredInfoBtn);'
			. '    var _pCredModal=document.createElement("div");'
			. '    _pCredModal.style.cssText="display:none;'
			. '      position:fixed;inset:0;background:rgba(0,0,0,.5);'
			. '      z-index:99999;align-items:center;'
			. '      justify-content:center;";'
			. '    var _pCredModalBox=document.createElement("div");'
			. '    _pCredModalBox.style.cssText="background:#fff;'
			. '      border-radius:14px;padding:28px;'
			. '      max-width:440px;width:90%;'
			. '      max-height:80vh;overflow-y:auto;'
			. '      position:relative;";'
			. '    var _pCredModalClose=document.createElement("button");'
			. '    _pCredModalClose.type="button";'
			. '    _pCredModalClose.style.cssText="position:absolute;'
			. '      top:12px;right:16px;background:none;border:none;'
			. '      font-size:20px;cursor:pointer;color:#64748b;";'
			. '    _pCredModalClose.textContent="\\u00d7";'
			. '    var _pCredModalTitle=document.createElement("h3");'
			. '    _pCredModalTitle.style.cssText="font-size:16px;'
			. '      font-weight:700;color:#0f172a;margin-bottom:16px;";'
			. '    _pCredModalTitle.textContent='
			. '      _t.credits_modal_title||"\\uD83D\\uDCB3 Your LocalEdge Credits";'
			. '    var _pCredModalContent=document.createElement("div");'
			. '    _pCredModalContent.style.cssText="font-size:13px;'
			. '      color:#475569;line-height:1.7;";'
			. '    var _soloItems=['
			. '      {t:"p",c:_t.credits_modal_solo_p1},'
			. '      {t:"h",c:_t.credits_modal_usage_title},'
			. '      {t:"li",c:_t.credits_modal_heatmap},'
			. '      {t:"li",c:_t.credits_modal_post},'
			. '      {t:"li",c:_t.credits_modal_photo},'
			. '      {t:"li",c:_t.credits_modal_guardian},'
			. '      {t:"h",c:_t.credits_modal_savings_title},'
			. '      {t:"p",c:_t.credits_modal_savings_sub}'
			. '    ];'
			. '    _soloItems.forEach(function(item){'
			. '      var el;'
			. '      if(item.t==="p"){'
			. '        el=document.createElement("p");'
			. '        el.style.marginBottom="10px";'
			. '      }else if(item.t==="h"){'
			. '        el=document.createElement("p");'
			. '        el.style.cssText="font-weight:600;'
			. '          color:#0f172a;margin:14px 0 6px;";'
			. '      }else{'
			. '        el=document.createElement("p");'
			. '        el.style.cssText="padding-left:16px;'
			. '          margin-bottom:4px;";'
			. '      }'
			. '      el.textContent=item.c||"";'
			. '      _pCredModalContent.appendChild(el);'
			. '    });'
			. '    _pCredModalBox.appendChild(_pCredModalClose);'
			. '    _pCredModalBox.appendChild(_pCredModalTitle);'
			. '    _pCredModalBox.appendChild(_pCredModalContent);'
			. '    _pCredModal.appendChild(_pCredModalBox);'
			. '    document.body.appendChild(_pCredModal);'
			. '    _pCredInfoBtn.addEventListener("click",function(){'
			. '      _pCredModal.style.display="flex";'
			. '    });'
			. '    _pCredModalClose.addEventListener("click",function(){'
			. '      _pCredModal.style.display="none";'
			. '    });'
			. '    _pCredModal.addEventListener("click",function(e){'
			. '      if(e.target===_pCredModal){'
			. '        _pCredModal.style.display="none";'
			. '      }'
			. '    });'
			. '    _pCredBox.appendChild(_pCredTitle);'
			. '    var _pCredRow=document.createElement("div");'
			. '    _pCredRow.style.cssText="display:flex;gap:16px;";'
			. '    var _pAvail=parseInt('
			. '      (window.aviEmbedSoloCredits'
			. '        &&window.aviEmbedSoloCredits.available)||0,10'
			. '    );'
			. '    var _pUsed=parseInt('
			. '      (window.aviEmbedSoloCredits'
			. '        &&window.aviEmbedSoloCredits.used)||0,10'
			. '    );'
			. '    [['
			. '      _pAvail,'
			. '      _t.profile_credits_available||"Available",'
			. '      "#7c3aed"'
			. '    ],['
			. '      _pUsed,'
			. '      _t.profile_credits_used||"Used",'
			. '      "#64748b"'
			. '    ]].forEach(function(item){'
			. '      var box=document.createElement("div");'
			. '      box.style.cssText="flex:1;text-align:center;'
			. '        background:#f8fafc;border-radius:8px;padding:12px;";'
			. '      var val=document.createElement("div");'
			. '      val.style.cssText="font-size:28px;font-weight:700;'
			. '        color:"+item[2]+";";'
			. '      val.textContent=String(item[0]);'
			. '      var lbl=document.createElement("div");'
			. '      lbl.style.cssText="font-size:11px;color:#94a3b8;'
			. '        margin-top:4px;";'
			. '      lbl.textContent=item[1];'
			. '      box.appendChild(val);box.appendChild(lbl);'
			. '      _pCredRow.appendChild(box);'
			. '    });'
			. '    _pCredBox.appendChild(_pCredRow);'
			. '    _pWrap.appendChild(_pCredBox);'
			. '    var _pPackTitle=document.createElement("div");'
			. '    _pPackTitle.style.cssText="font-size:13px;font-weight:600;'
			. '      color:#64748b;text-transform:uppercase;'
			. '      letter-spacing:.05em;margin-bottom:12px;";'
			. '    _pPackTitle.textContent=_t.profile_buy||"+ Buy credits";'
			. '    _pWrap.appendChild(_pPackTitle);'
			. '    var _packs=[['
			. '      "nano","profile_pack_nano","profile_price_nano",'
			. '      "","10"'
			. '    ],['
			. '      "mini","profile_pack_mini","profile_price_mini",'
			. '      "-17%","30"'
			. '    ],['
			. '      "standard","profile_pack_standard",'
			. '      "profile_price_standard","-27%","75"'
			. '    ],['
			. '      "pro","profile_pack_pro","profile_price_pro",'
			. '      "-38%","200"'
			. '    ]];'
			. '    var packType="solo";'
			. '    var _discountMap={'
			. '      "-17%":_t.badge_discount_17||"-17%",'
			. '      "-27%":_t.badge_discount_27||"-27%",'
			. '      "-38%":_t.badge_discount_38||"-38%"'
			. '    };'
			. '    _packs.forEach(function(pk){'
			. '      var row=document.createElement("div");'
			. '      row.style.cssText="display:flex;align-items:center;'
			. '        justify-content:space-between;background:#fff;'
			. '        border:1px solid #e2e8f0;border-radius:10px;'
			. '        padding:14px 16px;margin-bottom:10px;'
			. '        cursor:pointer;transition:border-color .2s;";'
			. '      row.addEventListener("mouseenter",function(){'
			. '        row.style.borderColor="#7c3aed";'
			. '      });'
			. '      row.addEventListener("mouseleave",function(){'
			. '        row.style.borderColor="#e2e8f0";'
			. '      });'
			. '      var left=document.createElement("div");'
			. '      var name=document.createElement("div");'
			. '      name.style.cssText="font-weight:600;color:#0f172a;'
			. '        font-size:14px;";'
			. '      name.textContent=(_t[pk[1]]||pk[1]);'
			. '      var credits=document.createElement("div");'
			. '      credits.style.cssText="font-size:12px;color:#7c3aed;'
			. '        margin-top:2px;";'
			. '      credits.textContent=pk[4]+" "+(_t.slider_credits||"credits");'
			. '      left.appendChild(name);left.appendChild(credits);'
			. '      var right=document.createElement("div");'
			. '      right.style.cssText="display:flex;align-items:center;'
			. '        gap:8px;";'
			. '      if(pk[3]){'
			. '        var badge=document.createElement("span");'
			. '        badge.style.cssText="background:#dcfce7;color:#16a34a;'
			. '          font-size:10px;font-weight:700;padding:2px 6px;'
			. '          border-radius:99px;";'
			. '        badge.textContent=_discountMap[pk[3]]||pk[3];'
			. '        right.appendChild(badge);'
			. '      }'
			. '      var price=document.createElement("div");'
			. '      price.style.cssText="font-size:16px;font-weight:700;'
			. '        color:#0f172a;";'
			. '      price.textContent=(_t[pk[2]]||pk[2]);'
			. '      var buyBtn=document.createElement("button");'
			. '      buyBtn.type="button";'
			. '      buyBtn.style.cssText="background:#7c3aed;color:#fff;'
			. '        border:none;border-radius:6px;padding:7px 14px;'
			. '        font-size:12px;font-weight:600;cursor:pointer;";'
			. '      buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '      (function(packId,packType){'
			. '        buyBtn.addEventListener("click",function(e){'
			. '          e.stopPropagation();'
			. '          buyBtn.disabled=true;'
			. '          buyBtn.textContent="...";'
			. '          fetch(window.aviEmbedRestUrl'
			. '            +"embed/checkout",{'
			. '            method:"POST",'
			. '            headers:{'
			. '              "Content-Type":"application/json",'
			. '              "X-Embed-Token":window.aviEmbedToken||""'
			. '            },'
			. '            body:JSON.stringify({'
			. '              pack:packId,'
			. '              key_id:window.aviEmbedKeyId||"",'
			. '              profile_id:window.aviEmbedProfileId||0,'
			. '              type:packType'
			. '            })'
			. '          })'
			. '          .then(function(r){return r.json();})'
			. '          .then(function(d){'
			. '            if(d&&d.checkout_url){'
			. '              window.open(d.checkout_url,"_blank");'
			. '            }else{'
			. '              alert(d.message||_t.error_generic||"Error");'
			. '            }'
			. '            buyBtn.disabled=false;'
			. '            buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '          })'
			. '          .catch(function(){'
			. '            buyBtn.disabled=false;'
			. '            buyBtn.textContent=_t.slider_buy_btn||"Buy";'
			. '          });'
			. '        });'
			. '      })(pk[0],packType);'
			. '      right.appendChild(price);'
			. '      right.appendChild(buyBtn);'
			. '      row.appendChild(left);row.appendChild(right);'
			. '      _pWrap.appendChild(row);'
			. '    });'
			. '    var _slSep=document.createElement("div");'
			. '    _slSep.style.cssText="display:flex;'
			. '      align-items:center;gap:12px;margin:20px 0 16px;";'
			. '    var _slLine1=document.createElement("div");'
			. '    _slLine1.style.cssText="flex:1;height:1px;'
			. '      background:#e2e8f0;";'
			. '    var _slLabel=document.createElement("span");'
			. '    _slLabel.style.cssText="font-size:12px;'
			. '      color:#94a3b8;white-space:nowrap;";'
			. '    _slLabel.textContent=_t.slider_title'
			. '      ||"Or choose your own amount";'
			. '    var _slLine2=document.createElement("div");'
			. '    _slLine2.style.cssText="flex:1;height:1px;'
			. '      background:#e2e8f0;";'
			. '    _slSep.appendChild(_slLine1);'
			. '    _slSep.appendChild(_slLabel);'
			. '    _slSep.appendChild(_slLine2);'
			. '    _pWrap.appendChild(_slSep);'
			. '    var _slTiers=['
			. '      {min:1,max:99,price:0.200},'
			. '      {min:100,max:299,price:0.167},'
			. '      {min:300,max:749,price:0.147},'
			. '      {min:750,max:999,price:0.125}'
			. '    ];'
			. '    function _slGetPrice(cr){'
			. '      var p=0.200;'
			. '      _slTiers.forEach(function(t){'
			. '        if(cr>=t.min&&cr<=t.max)p=t.price;'
			. '      });'
			. '      return p;'
			. '    }'
			. '    function _slFormat(n){'
			. '      return "$"+(n%1===0?n.toFixed(2):'
			. '        n.toFixed(2));'
			. '    }'
			. '    function _slSaving(price){'
			. '      var base=0.200;'
			. '      var pct=Math.round((base-price)/base*100);'
			. '      return pct>0?"-"+pct+"% "+(_t.slider_vs_nano'
			. '        ||"vs Nano"):"";'
			. '    }'
			. '    var _slWrap=document.createElement("div");'
			. '    _slWrap.style.cssText="background:#fff;'
			. '      border:1px solid #e2e8f0;border-radius:10px;'
			. '      padding:20px;margin-bottom:10px;";'
			. '    var _slMinMax=document.createElement("div");'
			. '    _slMinMax.style.cssText="display:flex;'
			. '      justify-content:space-between;'
			. '      font-size:11px;color:#94a3b8;'
			. '      margin-bottom:6px;";'
			. '    var _slMinLbl=document.createElement("span");'
			. '    _slMinLbl.textContent=_t.slider_min_label||"10 cr";'
			. '    var _slMaxLbl=document.createElement("span");'
			. '    _slMaxLbl.textContent=_t.slider_max_label_solo'
			. '      ||"1,000 cr";'
			. '    _slMinMax.appendChild(_slMinLbl);'
			. '    _slMinMax.appendChild(_slMaxLbl);'
			. '    _slWrap.appendChild(_slMinMax);'
			. '    var _slInput=document.createElement("input");'
			. '    _slInput.type="range";'
			. '    _slInput.min="10";'
			. '    _slInput.max="1000";'
			. '    _slInput.step="10";'
			. '    _slInput.value="100";'
			. '    _slInput.style.cssText="width:100%;'
			. '      accent-color:#7c3aed;cursor:pointer;'
			. '      margin-bottom:16px;";'
			. '    _slWrap.appendChild(_slInput);'
			. '    var _slSummary=document.createElement("div");'
			. '    _slSummary.style.cssText="display:flex;'
			. '      align-items:center;justify-content:space-between;'
			. '      flex-wrap:wrap;gap:8px;";'
			. '    var _slLeft=document.createElement("div");'
			. '    var _slCrDisplay=document.createElement("div");'
			. '    _slCrDisplay.style.cssText="font-size:22px;'
			. '      font-weight:700;color:#0f172a;";'
			. '    var _slPriceDisplay=document.createElement("div");'
			. '    _slPriceDisplay.style.cssText="font-size:12px;'
			. '      color:#7c3aed;margin-top:2px;";'
			. '    var _slSavingDisplay=document.createElement("div");'
			. '    _slSavingDisplay.style.cssText="font-size:11px;'
			. '      color:#16a34a;margin-top:2px;";'
			. '    _slLeft.appendChild(_slCrDisplay);'
			. '    _slLeft.appendChild(_slPriceDisplay);'
			. '    _slLeft.appendChild(_slSavingDisplay);'
			. '    var _slBuyBtn=document.createElement("button");'
			. '    _slBuyBtn.type="button";'
			. '    _slBuyBtn.style.cssText="background:#7c3aed;'
			. '      color:#fff;border:none;border-radius:8px;'
			. '      padding:12px 24px;font-size:14px;'
			. '      font-weight:700;cursor:pointer;'
			. '      white-space:nowrap;";'
			. '    _slSummary.appendChild(_slLeft);'
			. '    _slSummary.appendChild(_slBuyBtn);'
			. '    _slWrap.appendChild(_slSummary);'
			. '    _pWrap.appendChild(_slWrap);'
			. '    function _slUpdate(){'
			. '      var cr=parseInt(_slInput.value,10);'
			. '      var price=_slGetPrice(cr);'
			. '      var total=cr*price;'
			. '      var saving=_slSaving(price);'
			. '      _slCrDisplay.textContent=cr+" "+'
			. '        (_t.slider_credits||"credits");'
			. '      _slPriceDisplay.textContent='
			. '        _slFormat(total)+" — "'
			. '        +price.toFixed(3)+" "'
			. '        +(_t.slider_price_per||"per credit");'
			. '      _slSavingDisplay.textContent=saving;'
			. '      _slBuyBtn.textContent='
			. '        (_t.slider_buy_btn||"Buy")+" "'
			. '        +_slFormat(total);'
			. '    }'
			. '    _slInput.addEventListener("input",_slUpdate);'
			. '    _slBuyBtn.addEventListener("click",function(){'
			. '      var cr=parseInt(_slInput.value,10);'
			. '      _slBuyBtn.disabled=true;'
			. '      _slBuyBtn.textContent="...";'
			. '      fetch(window.aviEmbedRestUrl+"embed/checkout",{'
			. '        method:"POST",'
			. '        headers:{'
			. '          "Content-Type":"application/json",'
			. '          "X-Embed-Token":window.aviEmbedToken||""'
			. '        },'
			. '        body:JSON.stringify({'
			. '          credits:cr,'
			. '          key_id:window.aviEmbedKeyId||"",'
			. '          profile_id:window.aviEmbedProfileId||0,'
			. '          type:"solo"'
			. '        })'
			. '      })'
			. '      .then(function(r){return r.json();})'
			. '      .then(function(d){'
			. '        if(d&&d.checkout_url){'
			. '          window.open(d.checkout_url,"_blank");'
			. '        }else{'
			. '          alert(d.message||_t.error_generic||"Error");'
			. '        }'
			. '        _slBuyBtn.disabled=false;'
			. '        _slUpdate();'
			. '      })'
			. '      .catch(function(){'
			. '        _slBuyBtn.disabled=false;'
			. '        _slUpdate();'
			. '      });'
			. '    });'
			. '    _slUpdate();'
			. '    var _pUpsell=document.createElement("div");'
			. '    _pUpsell.style.cssText="background:linear-gradient('
			. '      135deg,#7c3aed,#4f46e5);border-radius:12px;'
			. '      padding:20px;margin-top:24px;color:#fff;'
			. '      text-align:center;";'
			. '    var _pUTitle=document.createElement("div");'
			. '    _pUTitle.style.cssText="font-size:15px;font-weight:700;'
			. '      margin-bottom:6px;";'
			. '    _pUTitle.textContent='
			. '      _t.profile_upsell_title||"\\uD83D\\uDE80 Avision Pro";'
			. '    var _pUSub=document.createElement("div");'
			. '    _pUSub.style.cssText="font-size:12px;opacity:.85;'
			. '      margin-bottom:14px;";'
			. '    _pUSub.textContent='
			. '      _t.profile_upsell_sub||'
			. '      "Full dashboard \\u00b7 Guardian \\u00b7 Advanced SEO";'
			. '    var _pUBtn=document.createElement("a");'
			. '    var _pUUrls={'
			. '      fr:"https://avision.org/fr/visibilite-locale/",'
			. '      es:"https://avision.org/es/visibilidad-local/",'
			. '      en:"https://avision.org/local-business/",'
			. '      de:"https://avision.org/local-business/",'
			. '      pt:"https://avision.org/local-business/",'
			. '      tr:"https://avision.org/local-business/"'
			. '    };'
			. '    var _pUUrl=_pUUrls[_embedLang]'
			. '      ||"https://avision.org/local-business/";'
			. '    _pUBtn.href=_pUUrl;'
			. '    _pUBtn.target="_blank";'
			. '    _pUBtn.style.cssText="display:inline-block;'
			. '      background:#fff;color:#7c3aed;border-radius:6px;'
			. '      padding:8px 20px;font-size:13px;font-weight:700;'
			. '      text-decoration:none;";'
			. '    _pUBtn.textContent='
			. '      _t.profile_upsell_cta||"Upgrade to Avision Pro \\u2192";'
			. '    _pUpsell.appendChild(_pUTitle);'
			. '    _pUpsell.appendChild(_pUSub);'
			. '    _pUpsell.appendChild(_pUBtn);'
			. '    _pWrap.appendChild(_pUpsell);'
			. '    _profilePanel.appendChild(_pWrap);'
			. '  }'
			. '  var _profileWrap='
			. '    document.querySelector(".avi-embed-wrap")||document.body;'
			. '  _profileWrap.appendChild(_profilePanel);'
			. '  _profileRender();'
			. '}'
			. 'function _photoStatusLabel(s){'
			. 'return{published:_t.post_status_published,in_stock:_t.photo_status_in_stock,'
			. 'scheduled:_t.post_status_scheduled,failed:_t.post_status_failed}[s]||s;'
			. '}'
			. 'function _photoStatusCls(s){'
			. 'return"avi-photo-status avi-photo-status-"+(s||"in_stock");'
			. '}'
			. 'function _photoRelDate(dt){'
			. 'if(!dt)return "";'
			. 'var d=new Date(dt),now=new Date();'
			. 'var diff=Math.floor((now-d)/86400000);'
			. 'if(diff===0)return _t.today;if(diff===1)return _t.yesterday;'
			. 'if(diff<30)return diff+_t.rel_d_ago;'
			. 'return Math.floor(diff/30)+_t.rel_mo_ago;'
			. '}'
			. 'function _photosPickerOpen(callback){'
			. '_switchEmbedTab("photos");'
			. 'window._photosPickerCallback=callback;'
			. '}'
			. '_photosPanel=document.createElement("div");'
			. '_photosPanel.className="avi-photos-panel";'
			. '_photosPanel.id="aviEmbedPhotosPanel";'
			. 'function _gbpCatsCommon(){'
			. 'return['
			. '{val:"COVER",label:_t.cat_cover},'
			. '{val:"PROFILE",label:_t.cat_profile},'
			. '{val:"INTERIOR",label:_t.cat_interior},'
			. '{val:"EXTERIOR",label:_t.cat_exterior},'
			. '{val:"PRODUCT",label:_t.cat_product},'
			. '{val:"FOOD_AND_DRINK",label:_t.cat_food_drink}'
			. '];}'
			. 'function _gbpCatsAll(){'
			. 'return['
			. '{val:"COVER",label:_t.cat_cover},'
			. '{val:"PROFILE",label:_t.cat_profile},'
			. '{val:"LOGO",label:_t.cat_logo},'
			. '{val:"INTERIOR",label:_t.cat_interior},'
			. '{val:"EXTERIOR",label:_t.cat_exterior},'
			. '{val:"PRODUCT",label:_t.cat_product},'
			. '{val:"AT_WORK",label:_t.cat_at_work},'
			. '{val:"FOOD_AND_DRINK",label:_t.cat_food_drink},'
			. '{val:"MENU",label:_t.cat_menu},'
			. '{val:"COMMON_AREA",label:_t.cat_common_area},'
			. '{val:"ROOMS",label:_t.cat_rooms},'
			. '{val:"TEAMS",label:_t.cat_teams},'
			. '{val:"ADDITIONAL",label:_t.photo_category_label}'
			. '];}'
			. 'var _gbpCatsExpanded=false;'
			. 'function _photosRender(){'
			. '_photosPanel.innerHTML="";'
			. 'var phc=document.createElement("button");'
			. 'phc.type="button";'
			. 'phc.style.cssText="position:absolute;top:12px;right:16px;'
			. 'background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;";'
			. 'phc.textContent="×";'
			. 'phc.addEventListener("click",function(){'
			. 'window._photosPickerCallback=null;'
			. '_switchEmbedTab("home");'
			. '});'
			. '_photosPanel.appendChild(phc);'
			. 'var _phHeader=document.createElement("div");'
			. '_phHeader.className="avi-photos-header";'
			. '_phHeader.innerHTML='
			. '\'<div class="avi-kw-header-title">\''
			. '+\'\\uD83D\\uDDBC\\uFE0F \'+(_t.photos_panel_title||"")'
			. '+\' <button type="button" class="avi-header-info-btn" id="aviPhotosInfoBtn">\\u2139\\uFE0F</button>\''
			. '+\'</div>\''
			. '+\'<div class="avi-kw-header-sub">\'+(_t.photos_panel_sub||"")+\'</div>\';'
			. '_photosPanel.appendChild(_phHeader);'
			. 'var _phInfoBtn=_phHeader.querySelector("#aviPhotosInfoBtn");'
			. 'if(_phInfoBtn){'
			. '_phInfoBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.photos_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.photos_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.photos_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.photos_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.photos_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.photos_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.photos_info_s3_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.photos_info_s4_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.photos_info_s4_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviPhotosInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(e){if(e.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviPhotosInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var inner=document.createElement("div");'
			. 'inner.className="avi-photos-inner";'
			. 'if(window._photosPickerCallback){'
			. 'var pickerMsg=document.createElement("div");'
			. 'pickerMsg.style.cssText="background:#f5f3ff;border:1px solid #a78bfa;'
			. 'border-radius:8px;padding:12px 16px;margin-bottom:16px;'
			. 'font-size:13px;color:#7c3aed;font-weight:600;";'
			. 'pickerMsg.textContent=_t.select_photo_picker;'
			. 'inner.appendChild(pickerMsg);'
			. '}'
			. '/* #SprintL2-photos-ux — barre outils 2 lignes */'
			. 'var topbar=document.createElement("div");'
			. 'topbar.className="avi-photos-toolbar";'
			. 'var tbRow1=document.createElement("div");'
			. 'tbRow1.className="avi-photos-toolbar-row1";'
			. 'var tbRow2=document.createElement("div");'
			. 'tbRow2.className="avi-photos-toolbar-row2";'
			. 'var upBtn=document.createElement("button");'
			. 'upBtn.type="button";upBtn.className="avi-photos-upload-btn";'
			. 'upBtn.textContent=_t.upload_photo;'
			. 'var dropZone=document.createElement("div");'
			. 'dropZone.className="avi-photos-upload-drop";'
			. 'upBtn.addEventListener("click",function(){'
			. 'dropZone.classList.toggle("open");'
			. '});'
			. 'tbRow1.appendChild(upBtn);'
			. 'var syncBtn=document.createElement("button");'
			. 'syncBtn.type="button";syncBtn.className="avi-photos-sync-btn";'
			. 'syncBtn.textContent=_t.sync_gbp;'
			. 'syncBtn.addEventListener("click",function(){'
			. 'syncBtn.textContent=_t.syncing;syncBtn.disabled=true;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/sync-photos",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,key_id:window.aviEmbedKeyId||""})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'window.aviEmbedPhotosData=data.photos||[];'
			. '_photosRender();'
			. '_showEmbedToast(_t.photos_sync_success||"Photos synced successfully");'
			. '}else{'
			. 'alert(data.message||_t.sync_failed);'
			. 'syncBtn.textContent=_t.sync_gbp;syncBtn.disabled=false;'
			. '}'
			. '}).catch(function(){'
			. 'alert(_t.err_network);'
			. 'syncBtn.textContent=_t.sync_gbp;syncBtn.disabled=false;'
			. '});'
			. '});'
			. 'tbRow1.appendChild(syncBtn);'
			. '/* #SprintL2-photos-ux — filtres photos uniquement (retrait published/scheduled posts) */'
			. 'var phFilters=[["all",_t.filter_all],["in_stock",_t.photos_filter_library],'
			. '["gbp_published",_t.photos_filter_gbp_pub],["gbp_unpublished",_t.photos_filter_gbp_unpub]];'
			. 'phFilters.forEach(function(f){'
			. 'var fb=document.createElement("button");'
			. 'fb.type="button";'
			. 'fb.className="avi-photos-filter-btn"+(f[0]===_photosFilter?" active":"");'
			. 'fb.textContent=f[1];'
			. 'fb.addEventListener("click",function(){'
			. '_photosFilter=f[0];'
			. 'tbRow2.querySelectorAll(".avi-photos-filter-btn").forEach(function(b){'
			. 'b.classList.remove("active");'
			. '});'
			. 'fb.classList.add("active");'
			. '_photosRenderGrid(gridZone);'
			. '});'
			. 'tbRow2.appendChild(fb);'
			. '});'
			. 'var tbSep=document.createElement("span");'
			. 'tbSep.className="avi-photos-toolbar-sep";'
			. 'tbRow2.appendChild(tbSep);'
			. '/* #SprintL2-photos-filter-download — filtre par catégorie */'
			. 'var catFilterSel=document.createElement("select");'
			. 'catFilterSel.className="avi-photos-cols-sel";'
			. 'var catAllOpt=document.createElement("option");'
			. 'catAllOpt.value="all";catAllOpt.textContent=_t.filter_all_cats;'
			. 'if(_photosFilterCat==="all")catAllOpt.selected=true;'
			. 'catFilterSel.appendChild(catAllOpt);'
			. '_gbpCatsAll().forEach(function(c){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=c.val;opt.textContent=c.label;'
			. 'if(c.val===_photosFilterCat)opt.selected=true;'
			. 'catFilterSel.appendChild(opt);'
			. '});'
			. 'catFilterSel.addEventListener("change",function(){'
			. '_photosFilterCat=this.value;'
			. '_photosRenderGrid(gridZone);'
			. '});'
			. 'tbRow2.appendChild(catFilterSel);'
			. 'var colsSel=document.createElement("select");'
			. 'colsSel.className="avi-photos-cols-sel avi-photos-cols-select";'
			. '[1,2,3,4,5,6].forEach(function(n){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=n;opt.textContent=n+(n>1?_t.cols_suffix:_t.col_suffix);'
			. 'if(n===_photosCols)opt.selected=true;'
			. 'colsSel.appendChild(opt);'
			. '});'
			. 'colsSel.addEventListener("change",function(){'
			. '_photosCols=parseInt(this.value,10);'
			. '_photosRenderGrid(gridZone);'
			. '});'
			. 'tbRow1.appendChild(colsSel);'
			. 'topbar.appendChild(tbRow1);'
			. 'topbar.appendChild(tbRow2);'
			. 'inner.appendChild(topbar);'
			. 'dropZone.innerHTML="<div style=\\"font-size:36px;margin-bottom:8px;\\">📷</div>"'
			. '+"<div style=\\"font-size:14px;font-weight:600;color:#475569;\\">"+_t.upload_drag+"</div>"'
			. '+"<div style=\\"font-size:12px;color:#94a3b8;margin-top:4px;\\">"+_t.upload_drag_sub+"</div>";'
			. 'var dropInput=document.createElement("input");'
			. 'dropInput.type="file";dropInput.accept="image/*,video/mp4,video/quicktime,video/webm";'
			. 'dropInput.multiple=true;dropInput.style.display="none";'
			. 'dropZone.appendChild(dropInput);'
			. 'dropZone.addEventListener("click",function(e){'
			. 'if(e.target===dropInput)return;'
			. 'dropInput.click();'
			. '});'
			. 'dropZone.addEventListener("dragover",function(e){'
			. 'e.preventDefault();dropZone.classList.add("dragover");'
			. '});'
			. 'dropZone.addEventListener("dragleave",function(){'
			. 'dropZone.classList.remove("dragover");'
			. '});'
			. 'dropZone.addEventListener("drop",function(e){'
			. 'e.preventDefault();dropZone.classList.remove("dragover");'
			. '_photosHandleFiles(e.dataTransfer.files);'
			. '});'
			. 'dropInput.addEventListener("change",function(){'
			. '_photosHandleFiles(dropInput.files);'
			. '});'
			. 'inner.appendChild(dropZone);'
			. 'var gridZone=document.createElement("div");'
			. 'gridZone.id="aviPhotosGrid";'
			. 'var _bulkBar=document.createElement("div");'
			. '_bulkBar.className="avi-photos-bulk-bar";'
			. '_bulkBar.id="aviPhotosBulkBar";'
			. '_bulkBar.style.display="none";'
			. '_bulkBar.innerHTML='
			. '\'<span class="avi-bulk-count" id="aviPhotosBulkCount">0 selected</span>\''
			. '+\'<button type="button" class="avi-bulk-btn" id="aviPhotosBulkDownload">\\u2B07\\uFE0F \'+(_t.bulk_download||"Download selected")+\'</button>\''
			. '+\'<button type="button" class="avi-bulk-btn avi-bulk-btn--danger" id="aviPhotosBulkDelete">🗑️ \'+(_t.bulk_delete||"")+\'</button>\''
			. '+\'<span class="avi-bulk-gbp-note">\'+(_t.bulk_gbp_note||"")+\'</span>\''
			. '+\'<button type="button" class="avi-bulk-btn avi-bulk-btn--ghost" id="aviPhotosBulkCancel">\'+(_t.cancel||"Cancel")+\'</button>\';'
			. 'inner.appendChild(gridZone);'
			. 'inner.insertBefore(_bulkBar,gridZone);'
			. 'var _phUpKey="avi_photos_upsell_dismissed";'
			. 'var _phUpDismissed=false;'
			. 'try{_phUpDismissed=sessionStorage.getItem(_phUpKey)==="1";}catch(e){}'
			. 'if(!_phUpDismissed){'
			. 'var upDiv=document.createElement("div");'
			. 'upDiv.className="avi-photos-upsell";'
			. 'upDiv.innerHTML='
			. '\'<div style="display:flex;align-items:center;justify-content:space-between;gap:8px;">\''
			. '+\'<div>\''
			. '+\'<div style="font-size:12px;font-weight:700;color:#fff;margin-bottom:2px;">\'+(_t.upgrade_photos_title||"")+\'</div>\''
			. '+\'<div style="font-size:11px;color:rgba(255,255,255,0.75);">\'+(_t.upgrade_photos_sub||"")+\'</div>\''
			. '+\'</div>\''
			. '+\'<div style="display:flex;align-items:center;gap:8px;flex-shrink:0;">\''
			. '+\'<a href="\'+(window.aviEmbedKeyType==="agency"?"https://avision.org/":"https://avision.org/local-business/")+\'" target="_blank" rel="noopener" style="background:rgba(255,255,255,.2);border:1px solid rgba(255,255,255,.3);border-radius:6px;color:#fff;font-size:11px;font-weight:700;padding:6px 14px;text-decoration:none;white-space:nowrap;">\'+(_t.upgrade_link||"\\u2192")+\'</a>\''
			. '+\'<button type="button" id="aviPhotosUpsellClose" style="background:none;border:none;color:rgba(255,255,255,.6);cursor:pointer;font-size:16px;padding:0;line-height:1;">×</button>\''
			. '+\'</div>\''
			. '+\'</div>\';'
			. 'inner.appendChild(upDiv);'
			. 'document.addEventListener("click",function _phUpClose(e){'
			. 'if(e.target&&e.target.id==="aviPhotosUpsellClose"){'
			. 'try{sessionStorage.setItem(_phUpKey,"1");}catch(e){}'
			. 'upDiv.remove();'
			. 'document.removeEventListener("click",_phUpClose);'
			. '}'
			. '});'
			. '}'
			. 'var phExp=document.createElement("div");'
			. 'phExp.className="avi-photos-export";'
			. 'var phCsvBtn=document.createElement("button");'
			. 'phCsvBtn.type="button";phCsvBtn.className="avi-photos-export-btn csv";'
			. 'phCsvBtn.textContent=_t.export_csv;'
			. 'phCsvBtn.addEventListener("click",function(){'
			. 'var rows=[_t.export_col_file+","+_t.col_status+","+_t.export_col_category+","+_t.th_scheduled+","+_t.th_published+","+_t.export_col_created];'
			. '(window.aviEmbedPhotosData||[]).forEach(function(p){'
			. 'rows.push([p.file_path||"",p.status||"",p.category||"",'
			. 'p.scheduled_at||"",p.published_at||"",p.created_at||""]'
			. '.join(","));'
			. '});'
			. 'var blob=new Blob([rows.join("\\n")],{type:"text/csv;charset=utf-8;"});'
			. 'var url=URL.createObjectURL(blob);'
			. 'var a=document.createElement("a");'
			. 'a.href=url;a.download="gbp-photos.csv";'
			. 'document.body.appendChild(a);a.click();'
			. 'document.body.removeChild(a);URL.revokeObjectURL(url);'
			. '});'
			. 'var phPdfBtn=document.createElement("button");'
			. 'phPdfBtn.type="button";phPdfBtn.className="avi-photos-export-btn pdf";'
			. 'phPdfBtn.textContent=_t.export_pdf;'
			. 'phPdfBtn.addEventListener("click",function(){'
			. 'var brand=window.aviEmbedWhiteLabel||"Avision";'
			. 'var logo=window.aviEmbedLogoUrl'
			. '?"<img src=\\""+window.aviEmbedLogoUrl+"\\" style=\\"height:36px;margin-bottom:8px;\\">"'
			. ':"";'
			. 'var rows=(window.aviEmbedPhotosData||[]).map(function(p){'
			. 'return "<tr><td>"+(p.category||"—")+"</td>"'
			. '+"<td>"+_photoStatusLabel(p.status)+"</td>"'
			. '+"<td>"+_photoRelDate(p.published_at)+"</td></tr>";'
			. '}).join("");'
			. 'var win=window.open("","_blank");'
			. 'win.document.write("<html><head><title>"+brand+" — "+_t.photos_page_title+"</title>"'
			. '+"<style>body{font-family:Inter,sans-serif;padding:32px;color:#1e293b;}"'
			. '+"table{width:100%;border-collapse:collapse;font-size:12px;}"'
			. '+"th{background:#f1f5f9;padding:8px;}td{padding:7px 8px;border-bottom:1px solid #f1f5f9;}"'
			. '+"</style></head><body>"'
			. '+logo+"<h1>"+brand+" — "+_t.photos_report_title+"</h1>"'
			. '+"<p>"+(window.aviEmbedPhotosData||[]).length+_t.photos_library_count_suffix+"</p>"'
			. '+"<table><thead><tr><th>"+_t.export_col_category+"</th><th>"+_t.col_status+"</th><th>"+_t.th_published+"</th></tr></thead>"'
			. '+"<tbody>"+rows+"</tbody></table></body></html>");'
			. 'win.document.close();win.focus();'
			. 'setTimeout(function(){win.print();},400);'
			. '});'
			. 'phExp.appendChild(phCsvBtn);phExp.appendChild(phPdfBtn);'
			. 'inner.appendChild(phExp);'
			. '_photosPanel.appendChild(inner);'
			. '_photosRenderGrid(gridZone);'
			. 'function _updateBulkBar(){'
			. 'var cbs=document.querySelectorAll(".avi-photo-bulk-cb:checked");'
			. 'var bar=document.getElementById("aviPhotosBulkBar");'
			. 'var countEl=document.getElementById("aviPhotosBulkCount");'
			. 'if(!bar)return;'
			. 'bar.style.display=cbs.length>0?"flex":"none";'
			. 'if(countEl)countEl.textContent=cbs.length+" "+(_t.selected||"selected");'
			. '}'
			. 'if(!window._photosBulkChangeBound){'
			. 'window._photosBulkChangeBound=true;'
			. 'document.addEventListener("change",function(e){'
			. 'if(e.target&&e.target.classList.contains("avi-photo-bulk-cb"))_updateBulkBar();'
			. '});'
			. '}'
			. 'var _bulkDlBtn=document.getElementById("aviPhotosBulkDownload");'
			. 'if(_bulkDlBtn){'
			. '_bulkDlBtn.addEventListener("click",function(){'
			. 'document.querySelectorAll(".avi-photo-bulk-cb:checked").forEach(function(cb){'
			. 'var pid=Number(cb.dataset.photoId);'
			. 'var ph=window.aviEmbedPhotosData.find(function(x){return x.id===pid;});'
			. 'if(ph&&ph.file_path){'
			. 'var a=document.createElement("a");'
			. 'a.href="/wp-json/avision/v1/embed/proxy-photo?url="+encodeURIComponent(ph.file_path)+"&token="+encodeURIComponent(window.aviEmbedToken);'
			. 'a.download=ph.display_name||("photo-"+pid);'
			. 'a.style.display="none";'
			. 'document.body.appendChild(a);'
			. 'a.click();'
			. 'setTimeout(function(){a.remove();},1000);'
			. '}'
			. '});'
			. '});'
			. '}'
			. 'var _bulkDelBtn=document.getElementById("aviPhotosBulkDelete");'
			. 'if(_bulkDelBtn){'
			. '_bulkDelBtn.addEventListener("click",function(){'
			. 'var cbs=document.querySelectorAll(".avi-photo-bulk-cb:checked");'
			. 'if(!cbs.length)return;'
			. 'if(!confirm((_t.bulk_delete_confirm||"Delete {n} photo(s) from library?").replace("{n}",cbs.length)))return;'
			. 'var ids=Array.from(cbs).map(function(cb){return Number(cb.dataset.photoId);});'
			. 'ids.forEach(function(pid){'
			. 'window.aviEmbedPhotosData=window.aviEmbedPhotosData.filter(function(x){return x.id!==pid;});'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/delete-photo",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,photo_id:pid})'
			. '}).catch(function(){});'
			. '});'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. '_showEmbedToast((_t.bulk_delete_success||"{n} photo(s) deleted").replace("{n}",ids.length));'
			. 'var bar=document.getElementById("aviPhotosBulkBar");'
			. 'if(bar)bar.style.display="none";'
			. '});'
			. '}'
			. 'var _bulkCancelBtn=document.getElementById("aviPhotosBulkCancel");'
			. 'if(_bulkCancelBtn){'
			. '_bulkCancelBtn.addEventListener("click",function(){'
			. 'document.querySelectorAll(".avi-photo-bulk-cb:checked").forEach(function(cb){cb.checked=false;});'
			. 'var bar=document.getElementById("aviPhotosBulkBar");'
			. 'if(bar)bar.style.display="none";'
			. '});'
			. '}'
			. '}'
			. 'function _photosRenderGrid(gridZone){'
			. 'var pd=window.aviEmbedPhotosData||[];'
			. 'var filtered=pd.filter(function(p){'
			. '/* #SprintL2-photos-filter-download — filtre catégorie combinable */'
			. 'if(_photosFilterCat!=="all"&&p.category!==_photosFilterCat)return false;'
			. 'if(_photosFilter==="all")return true;'
			. 'if(_photosFilter==="gbp_published")return p.gbp_status==="published";'
			. 'if(_photosFilter==="gbp_unpublished")return p.gbp_status!=="published";'
			. 'return p.status===_photosFilter;'
			. '});'
			. 'gridZone.innerHTML="";'
			. 'var countDiv=document.createElement("div");'
			. 'countDiv.className="avi-photos-count";'
			. 'countDiv.textContent=filtered.length+_t.photos_count_suffix;'
			. 'gridZone.appendChild(countDiv);'
			. 'if(filtered.length===0){'
			. 'var empty=document.createElement("div");'
			. 'empty.className="avi-photos-empty";'
			. 'empty.innerHTML="<div style=\\"font-size:36px;\\">📷</div>"'
			. '+"<div style=\\"font-size:14px;font-weight:600;color:#475569;margin-top:8px;\\">"+_t.no_photos+"</div>"'
			. '+"<div style=\\"font-size:12px;margin-top:4px;\\">"+_t.no_photos_sub+"</div>";'
			. 'gridZone.appendChild(empty);'
			. 'return;'
			. '}'
			. 'var grid=document.createElement("div");'
			. 'grid.className="avi-photos-grid cols-"+_photosCols;'
			. 'filtered.forEach(function(p){'
			. 'var card=document.createElement("div");'
			. 'card.className="avi-photo-card";'
			. 'if(p.id){card.dataset.mediaId=String(p.id);}'
			. 'if(p.display_name){card.dataset.displayName=p.display_name;}'
			. 'var _bulkCb=document.createElement("input");'
			. '_bulkCb.type="checkbox";'
			. '_bulkCb.className="avi-photo-bulk-cb";'
			. '_bulkCb.dataset.photoId=p.id;'
			. 'card.appendChild(_bulkCb);'
			. 'var _imgSrc=p.file_path;'
			. 'var imgWrap=document.createElement("div");'
			. 'imgWrap.className="avi-photo-img-wrap avi-photo-card-img";'
			. 'if(_imgSrc&&p.media_type==="video"){'
			. 'var vid=document.createElement("video");'
			. 'vid.className="avi-photo-video";'
			. 'vid.src=_imgSrc;vid.muted=true;'
			. 'vid.setAttribute("playsinline","");'
			. 'imgWrap.appendChild(vid);'
			. 'var vBadge=document.createElement("div");'
			. 'vBadge.className="avi-photo-video-badge";'
			. 'vBadge.textContent=_t.video_badge;'
			. 'imgWrap.appendChild(vBadge);'
			. '}else if(_imgSrc){'
			. 'var img=document.createElement("img");'
			. 'img.className="avi-photo-img";'
			. 'img.src=_imgSrc;'
			. 'img.alt=p.category||_t.photo_alt_default;'
			. 'img.onerror=function(){this.style.display="none";};'
			. 'imgWrap.appendChild(img);'
			. '}else{'
			. 'var ph=document.createElement("div");'
			. 'ph.className="avi-photo-img-placeholder";'
			. 'ph.textContent="📷";'
			. 'imgWrap.appendChild(ph);'
			. '}'
			. '/* #SprintL2-photos-fix — badge statut GBP (mêmes icônes que les filtres) */'
			. 'var _gbpPub=p.gbp_status==="published";'
			. 'var gbpBadge=document.createElement("div");'
			. 'gbpBadge.className="avi-photo-gbp-badge "+(_gbpPub?"avi-photo-gbp-badge--pub":"avi-photo-gbp-badge--unpub");'
			. 'gbpBadge.textContent=_gbpPub?_t.photos_filter_gbp_pub:_t.photos_filter_gbp_unpub;'
			. 'imgWrap.appendChild(gbpBadge);'
			. 'var acts=document.createElement("div");'
			. 'acts.className="avi-photo-actions";'
			. 'if(p.status!=="published"){'
			. 'var pubBtn=document.createElement("button");'
			. 'pubBtn.type="button";pubBtn.className="avi-photo-action-btn publish";'
			. 'pubBtn.textContent=_t.publish_photo;'
			. 'pubBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'pubBtn.disabled=true;pubBtn.textContent=_t.publishing;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/publish-photo",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'media_id:p.id'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'p.status="published";p.published_at=new Date().toISOString();p.gbp_status="published";'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. '}else{alert(data.message||_t.err_generic);'
			. 'pubBtn.disabled=false;pubBtn.textContent=_t.publish_photo;}'
			. '}).catch(function(){alert(_t.err_network);'
			. 'pubBtn.disabled=false;pubBtn.textContent=_t.publish_photo;});'
			. '});'
			. 'acts.appendChild(pubBtn);'
			. '}'
			. 'if(p.status!=="published"){'
			. 'var schedBtn=document.createElement("button");'
			. 'schedBtn.type="button";schedBtn.className="avi-photo-action-btn";'
			. 'var schedCost=p.media_type==="video"?_t.photo_sched_vid:_t.photo_sched_img;'
			. 'schedBtn.textContent=_t.schedule_photo+" ("+schedCost+")";'
			. 'schedBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var schedDate=prompt(_t.schedule_date_prompt,"");'
			. 'if(!schedDate)return;'
			. 'schedBtn.disabled=true;schedBtn.textContent=_t.scheduling;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/publish-photo",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'media_id:p.id,'
			. 'scheduled_at:schedDate'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'p.status="scheduled";p.scheduled_at=schedDate;'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. '}else{alert(data.message||_t.err_generic);'
			. 'schedBtn.disabled=false;schedBtn.textContent=_t.schedule_photo+" ("+schedCost+")";}'
			. '}).catch(function(){alert(_t.err_network);'
			. 'schedBtn.disabled=false;schedBtn.textContent=_t.schedule_photo+" ("+schedCost+")";});'
			. '});'
			. 'acts.appendChild(schedBtn);'
			. '}'
			. '/* #SprintL2-photos-ux — téléchargement via proxy pour URLs Google (cross-origin) */'
			. 'var _dlSrc=p.googleUrl||p.file_path||"";'
			. 'if(_dlSrc){'
			. 'var _dlName=(p.display_name||p.file_name||"photo")+".jpg";'
			. 'var _isGoogle=/googleusercontent\\.com|storage\\.googleapis\\.com/.test(_dlSrc);'
			. 'var _dlUrl=_isGoogle'
			. '?(window.location.origin+"/wp-json/avision/v1/embed/proxy-photo?url="'
			. '+encodeURIComponent(_dlSrc)+"&filename="+encodeURIComponent(_dlName))'
			. ':_dlSrc;'
			. 'var dlBtn=document.createElement("a");'
			. 'dlBtn.className="avi-photo-download-btn avi-photo-action-btn";'
			. 'dlBtn.href=_dlUrl;'
			. 'dlBtn.setAttribute("download",_dlName);'
			. 'dlBtn.target="_blank";'
			. 'dlBtn.rel="noopener noreferrer";'
			. 'dlBtn.title=_t.download_label||"Download";'
			. 'dlBtn.textContent="\\u2b07\\ufe0f";'
			. 'dlBtn.addEventListener("click",function(e){e.stopPropagation();});'
			. 'acts.appendChild(dlBtn);'
			. '}'
			. 'if(window._photosPickerCallback){'
			. 'var selBtn=document.createElement("button");'
			. 'selBtn.type="button";selBtn.className="avi-photo-action-btn publish";'
			. 'selBtn.textContent=_t.select_btn;'
			. 'selBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(window._photosPickerCallback){'
			. 'window._photosPickerCallback(p.file_path);'
			. 'window._photosPickerCallback=null;'
			. '_switchEmbedTab("posts");'
			. '}'
			. '});'
			. 'acts.appendChild(selBtn);'
			. '}'
			. '/* #SprintL2-photos-ux — bouton Delete dans le corps de la card */'
			. 'var delPhBtn=document.createElement("button");'
			. 'delPhBtn.type="button";delPhBtn.className="avi-photo-card-btn avi-photo-card-btn--danger";'
			. 'delPhBtn.textContent="🗑️ "+_t.delete_photo_title;'
			. 'delPhBtn.title=_t.delete_photo_title;'
			. 'delPhBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(!confirm(_t.delete_confirm))return;'
			. 'window.aviEmbedPhotosData=window.aviEmbedPhotosData.filter(function(x){'
			. 'return x.id!==p.id;'
			. '});'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. 'if(typeof p.id==="number"){'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/delete-photo",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,photo_id:p.id})'
			. '}).catch(function(){});'
			. '}'
			. '});'
			. 'var delGbpBtn=document.createElement("button");'
			. 'delGbpBtn.type="button";'
			. 'delGbpBtn.className="avi-photo-card-btn avi-photo-card-btn--danger-gbp";'
			. 'delGbpBtn.textContent="\\uD83C\\uDF10 "+(_t.delete_gbp_title||"Delete from GBP");'
			. 'delGbpBtn.title=_t.delete_gbp_title||"Delete from GBP";'
			. 'var _isPublishedGbp=(p.gbp_status==="published"||p.status==="published");'
			. 'if(!_isPublishedGbp){delGbpBtn.disabled=true;delGbpBtn.style.opacity="0.4";}'
			. 'delGbpBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(!confirm(_t.delete_gbp_confirm||"Delete this photo from your Google Business Profile?"))return;'
			. 'delGbpBtn.disabled=true;'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/delete-photo-gbp",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({profile_id:window.aviEmbedProfileId,photo_id:p.id})'
			. '}).then(function(r){return r.json();}).then(function(d){'
			. 'if(d.success){'
			. 'var idx=window.aviEmbedPhotosData.findIndex(function(x){return x.id===p.id;});'
			. 'if(idx>-1){window.aviEmbedPhotosData[idx].gbp_status="deleted";window.aviEmbedPhotosData[idx].status="unpublished";}'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. '_showEmbedToast(_t.delete_gbp_success||"Photo deleted from GBP");'
			. '}else{'
			. '_showEmbedToast((d.message||_t.delete_gbp_error||"Error"),true);'
			. 'delGbpBtn.disabled=false;'
			. '}'
			. '}).catch(function(){'
			. '_showEmbedToast(_t.err_network||"Network error",true);'
			. 'delGbpBtn.disabled=false;'
			. '});'
			. '});'
			. 'imgWrap.appendChild(acts);'
			. 'card.appendChild(imgWrap);'
			. '/* #SprintL2-photos-ux — corps de card restructuré */'
			. 'var body=document.createElement("div");'
			. 'body.className="avi-photo-card-body";'
			. 'var fname=p.display_name||(p.file_path?p.file_path.split("/").pop():"photo");'
			. 'var nameRow=document.createElement("div");'
			. 'nameRow.className="avi-photo-card-name";'
			. 'var nameIcon=document.createElement("span");'
			. 'nameIcon.textContent="📝";'
			. 'var nameSpan=document.createElement("span");'
			. 'nameSpan.className="avi-photo-name";'
			. 'nameSpan.textContent=fname;'
			. 'nameSpan.title=_t.rename_hint;'
			. 'var editIcon=document.createElement("button");'
			. 'editIcon.type="button";editIcon.className="avi-photo-copy-btn";'
			. 'editIcon.textContent="✏️";editIcon.title=_t.rename_hint;'
			. 'var copyBtn=document.createElement("button");'
			. 'copyBtn.type="button";copyBtn.className="avi-photo-copy-btn";'
			. 'copyBtn.textContent="📋";copyBtn.title=_t.copy_url;'
			. 'copyBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'if(p.file_path){'
			. 'navigator.clipboard.writeText(p.file_path)'
			. '.then(function(){copyBtn.textContent="✅";'
			. 'setTimeout(function(){copyBtn.textContent="📋";},1500);})'
			. '.catch(function(){alert(p.file_path);});'
			. '}'
			. '});'
			. 'nameRow.appendChild(nameIcon);nameRow.appendChild(nameSpan);'
			. 'nameRow.appendChild(editIcon);nameRow.appendChild(copyBtn);'
			. 'body.appendChild(nameRow);'
			. 'var catRow=document.createElement("div");'
			. 'catRow.className="avi-photo-card-meta";'
			. 'var catIcon=document.createElement("span");'
			. 'catIcon.textContent="🗂️";'
			. 'var catLabel=p.category'
			. '?(_gbpCatsAll().find(function(c){return c.val===p.category;})||{label:p.category}).label'
			. ':_t.no_category;'
			. 'var catBadge=document.createElement("span");'
			. 'catBadge.className="avi-photo-cat-badge";'
			. 'catBadge.textContent=catLabel;'
			. 'catBadge.style.cursor="pointer";'
			. 'catBadge.title=_t.change_category;'
			. 'catRow.appendChild(catIcon);catRow.appendChild(catBadge);'
			. 'body.appendChild(catRow);'
			. 'var dateRow=document.createElement("div");'
			. 'dateRow.className="avi-photo-card-meta";'
			. 'var dateSpan=document.createElement("span");'
			. 'dateSpan.className="avi-photo-date-pub";'
			. 'var dateStr=p.published_at?("📅 "+_photoRelDate(p.published_at))'
			. ':(p.scheduled_at?("🕐 "+_photoRelDate(p.scheduled_at)):("📅 "+_photoRelDate(p.created_at)));'
			. 'dateSpan.textContent=dateStr;'
			. 'dateRow.appendChild(dateSpan);'
			. 'body.appendChild(dateRow);'
			. 'var actRow=document.createElement("div");'
			. 'actRow.className="avi-photo-card-actions";'
			. 'actRow.appendChild(delPhBtn);'
			. 'actRow.appendChild(delGbpBtn);'
			. 'body.appendChild(actRow);'
			. 'card.appendChild(body);'
			. 'var editForm=document.createElement("div");'
			. 'editForm.className="avi-photo-edit-form";'
			. 'var renameInput=document.createElement("input");'
			. 'renameInput.type="text";renameInput.className="avi-photo-edit-input";'
			. 'renameInput.placeholder=_t.rename_ph;'
			. 'renameInput.value=fname;'
			. 'var catSel=document.createElement("select");'
			. 'catSel.className="avi-photo-edit-sel";'
			. 'var noOpt=document.createElement("option");'
			. 'noOpt.value="";noOpt.textContent=_t.select_category;'
			. 'catSel.appendChild(noOpt);'
			. '/* #SprintL2-photos-cats-fix — afficher TOUTES les catégories GBP sans troncature */'
			. 'var catsToShow=_gbpCatsAll();'
			. 'catsToShow.forEach(function(c){'
			. 'var opt=document.createElement("option");'
			. 'opt.value=c.val;opt.textContent=c.label;'
			. 'if(c.val===p.category)opt.selected=true;'
			. 'catSel.appendChild(opt);'
			. '});'
			. 'var editActs=document.createElement("div");'
			. 'editActs.className="avi-photo-edit-acts";'
			. 'var saveBtn=document.createElement("button");'
			. 'saveBtn.type="button";saveBtn.className="avi-photo-edit-save";'
			. 'saveBtn.textContent=_t.save;'
			. 'saveBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var newName=renameInput.value.trim();'
			. 'var photoId=card.dataset.mediaId;'
			. 'var mediaIdNum=photoId?parseInt(photoId,10):0;'
			. 'p.category=catSel.value;'
			. 'saveBtn.disabled=true;saveBtn.textContent=_t.saving;'
			. 'if(!mediaIdNum||isNaN(mediaIdNum)){'
			. 'if(newName&&newName!==fname){p.display_name=newName;}'
			. 'var idxLocal=window.aviEmbedPhotosData.findIndex(function(x){return x.id===p.id;});'
			. 'if(idxLocal>=0){'
			. 'window.aviEmbedPhotosData[idxLocal].category=p.category;'
			. 'window.aviEmbedPhotosData[idxLocal].display_name=p.display_name||fname;'
			. '}'
			. 'nameSpan.textContent=p.display_name||fname;'
			. 'card.dataset.displayName=p.display_name||fname;'
			. 'var catLblLocal=p.category'
			. '?(_gbpCatsAll().find(function(c){return c.val===p.category;})||{label:p.category}).label'
			. ':_t.no_category;'
			. 'catBadge.textContent=catLblLocal;'
			. 'editForm.classList.remove("open");'
			. 'saveBtn.disabled=false;saveBtn.textContent=_t.save;'
			. 'return;'
			. '}'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/update-photo",{'
			. 'method:"PATCH",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'media_id:mediaIdNum,'
			. 'display_name:newName,'
			. 'category:catSel.value'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'p.display_name=data.display_name||newName||fname;'
			. 'p.category=data.category||catSel.value;'
			. 'var idx=window.aviEmbedPhotosData.findIndex(function(x){return x.id===p.id;});'
			. 'if(idx>=0){'
			. 'window.aviEmbedPhotosData[idx].category=p.category;'
			. 'window.aviEmbedPhotosData[idx].display_name=p.display_name;'
			. '}'
			. 'nameSpan.textContent=p.display_name;'
			. 'nameSpan.title=_t.rename_hint;'
			. 'card.dataset.displayName=p.display_name;'
			. 'var catLbl=p.category'
			. '?(_gbpCatsAll().find(function(c){return c.val===p.category;})||{label:p.category}).label'
			. ':_t.no_category;'
			. 'catBadge.textContent=catLbl;'
			. 'editForm.classList.remove("open");'
			. '}else{alert(data.message||_t.err_rename_failed);}'
			. 'saveBtn.disabled=false;saveBtn.textContent=_t.save;'
			. '}).catch(function(){'
			. 'alert(_t.err_rename);'
			. 'saveBtn.disabled=false;saveBtn.textContent=_t.save;'
			. '});'
			. '});'
			. 'var cancelEdit=document.createElement("button");'
			. 'cancelEdit.type="button";cancelEdit.className="avi-photo-edit-cancel";'
			. 'cancelEdit.textContent=_t.cancel;'
			. 'cancelEdit.addEventListener("click",function(e){'
			. 'e.stopPropagation();editForm.classList.remove("open");'
			. '});'
			. 'editActs.appendChild(cancelEdit);editActs.appendChild(saveBtn);'
			. 'editForm.appendChild(renameInput);editForm.appendChild(catSel);'
			. 'editForm.appendChild(editActs);'
			. 'card.appendChild(editForm);'
			. '[nameSpan,catBadge,editIcon].forEach(function(el){'
			. 'el.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'editForm.classList.toggle("open");'
			. '});'
			. '});'
			. 'grid.appendChild(card);'
			. '});'
			. 'gridZone.appendChild(grid);'
			. '}'
			. 'function _photosHandleFiles(files){'
			. 'if(!files||files.length===0)return;'
			. 'Array.from(files).forEach(function(file){'
			. 'var isVideo=file.type.indexOf("video")===0;'
			. 'var maxSize=isVideo?75*1024*1024:5*1024*1024;'
			. 'var maxLabel=isVideo?"75MB":"5MB";'
			. 'if(file.size>maxSize){alert(_t.err_file_too_large+": "+file.name+" (max "+maxLabel+")");return;}'
			. 'var reader=new FileReader();'
			. 'reader.onload=function(e){'
			. 'var localPhoto={'
			. 'id:"local_"+Date.now(),'
			. 'file_path:e.target.result,'
			. 'media_type:isVideo?"video":"photo",'
			. 'category:"",'
			. 'status:"in_stock",'
			. 'gbp_status:"pending",'
			. 'scheduled_at:null,'
			. 'published_at:null,'
			. 'created_at:new Date().toISOString(),'
			. '_base64:e.target.result,'
			. '_filename:file.name'
			. '};'
			. 'if(!window.aviEmbedPhotosData)window.aviEmbedPhotosData=[];'
			. 'window.aviEmbedPhotosData.unshift(localPhoto);'
			. '_photosFilter="all";'
			. 'var gridZone=document.getElementById("aviPhotosGrid");'
			. 'if(gridZone)_photosRenderGrid(gridZone);'
			. 'var dz=document.querySelector(".avi-photos-upload-drop");'
			. 'if(dz)dz.classList.remove("open");'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/upload-photo",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'photo_base64:e.target.result,'
			. 'media_type:isVideo?"video":"photo"'
			. '})'
			. '}).then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'var idx=window.aviEmbedPhotosData.findIndex(function(x){'
			. 'return x._filename===file.name&&x.status==="in_stock";'
			. '});'
			. 'if(idx>=0){'
			. 'window.aviEmbedPhotosData[idx].id=data.media_id;'
			. 'window.aviEmbedPhotosData[idx].file_path=data.file_path;'
			. 'delete window.aviEmbedPhotosData[idx]._base64;'
			. '}'
			. 'var gz=document.getElementById("aviPhotosGrid");'
			. 'if(gz)_photosRenderGrid(gz);'
			. '}'
			. '}).catch(function(){});'
			. '};'
			. 'reader.readAsDataURL(file);'
			. '});'
			. '}'

			. 'function _citationsGetDirectories(){'
			. 'var _lang=_embedLang||"en";'
			. 'var _cat=(window.aviEmbedScoreData&&window.aviEmbedScoreData.primary_category_name)||"";'
			. 'var _universal=['
			. '{slug:"google_business",name:"Google Business Profile",url:"https://business.google.com",type:"universal"},'
			. '{slug:"bing_places",name:"Bing Places",url:"https://bingplaces.com",type:"universal"},'
			. '{slug:"yelp",name:"Yelp",url:"https://biz.yelp.com",type:"universal"},'
			. '{slug:"facebook",name:"Facebook Business",url:"https://facebook.com/business",type:"universal"},'
			. '{slug:"apple_maps",name:"Apple Maps Connect",url:"https://mapsconnect.apple.com",type:"universal"}'
			. '];'
			. 'var _byLang={'
			. 'fr:['
			. '{slug:"pages_jaunes",name:"Pages Jaunes",url:"https://www.pagesjaunes.fr",type:"local"},'
			. '{slug:"kompass_fr",name:"Kompass France",url:"https://fr.kompass.com",type:"local"},'
			. '{slug:"cylex_fr",name:"Cylex France",url:"https://www.cylex.fr",type:"local"},'
			. '{slug:"local_fr",name:"Local.fr",url:"https://www.local.fr",type:"local"},'
			. '{slug:"hotfrog_fr",name:"Hotfrog France",url:"https://www.hotfrog.fr",type:"local"},'
			. '{slug:"societe_com",name:"Societe.com",url:"https://www.societe.com",type:"local"},'
			. '{slug:"manageo",name:"Manageo",url:"https://www.manageo.fr",type:"local"},'
			. '{slug:"verif",name:"V\u00e9rif.com",url:"https://www.verif.com",type:"local"},'
			. '{slug:"europages_fr",name:"Europages FR",url:"https://www.europages.fr",type:"local"},'
			. '{slug:"infobel_fr",name:"Infobel France",url:"https://www.infobel.com/fr",type:"local"},'
			. '{slug:"mappy",name:"Mappy",url:"https://www.mappy.com",type:"local"},'
			. '{slug:"118000",name:"118000.fr",url:"https://www.118000.fr",type:"local"},'
			. '{slug:"tripadvisor_fr",name:"TripAdvisor",url:"https://www.tripadvisor.fr",type:"local"},'
			. '{slug:"linkedin_fr",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"local"},'
			. '{slug:"foursquare_fr",name:"Foursquare",url:"https://foursquare.com",type:"local"}'
			. '],'
			. 'es:['
			. '{slug:"paginas_amarillas",name:"P\u00e1ginas Amarillas",url:"https://www.paginasamarillas.es",type:"local"},'
			. '{slug:"qdq",name:"QDQ",url:"https://www.qdq.com",type:"local"},'
			. '{slug:"11870",name:"11870.com",url:"https://11870.com",type:"local"},'
			. '{slug:"cylex_es",name:"Cylex Espa\u00f1a",url:"https://www.cylex.es",type:"local"},'
			. '{slug:"hotfrog_es",name:"Hotfrog Espa\u00f1a",url:"https://www.hotfrog.es",type:"local"},'
			. '{slug:"europages_es",name:"Europages ES",url:"https://www.europages.es",type:"local"},'
			. '{slug:"infobel_es",name:"Infobel Espa\u00f1a",url:"https://www.infobel.com/es",type:"local"},'
			. '{slug:"kompass_es",name:"Kompass Espa\u00f1a",url:"https://es.kompass.com",type:"local"},'
			. '{slug:"tripadvisor_es",name:"TripAdvisor",url:"https://www.tripadvisor.es",type:"local"},'
			. '{slug:"linkedin_es",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"local"},'
			. '{slug:"foursquare_es",name:"Foursquare",url:"https://foursquare.com",type:"local"},'
			. '{slug:"guiaempresas",name:"Guia Empresas",url:"https://www.guiaempresas.eu",type:"local"},'
			. '{slug:"einforma",name:"eInforma",url:"https://www.einforma.com",type:"local"},'
			. '{slug:"infoisinfo_es",name:"Infoisinfo",url:"https://www.infoisinfo.es",type:"local"},'
			. '{slug:"empresia",name:"Empresia",url:"https://www.empresia.es",type:"local"}'
			. '],'
			. '"pt-BR":['
			. '{slug:"apontador",name:"Apontador",url:"https://www.apontador.com.br",type:"local"},'
			. '{slug:"telelistas",name:"TeleListas",url:"https://www.telelistas.net",type:"local"},'
			. '{slug:"guia_mais",name:"Guia Mais",url:"https://www.guiamais.com.br",type:"local"},'
			. '{slug:"foursquare_br",name:"Foursquare",url:"https://foursquare.com",type:"local"},'
			. '{slug:"hotfrog_br",name:"Hotfrog Brasil",url:"https://www.hotfrog.com.br",type:"local"},'
			. '{slug:"linkedin_br",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"local"},'
			. '{slug:"tripadvisor_br",name:"TripAdvisor",url:"https://www.tripadvisor.com.br",type:"local"},'
			. '{slug:"kompass_br",name:"Kompass Brasil",url:"https://br.kompass.com",type:"local"},'
			. '{slug:"empresasdobrasil",name:"Empresas do Brasil",url:"https://www.empresasdobrasil.com.br",type:"local"},'
			. '{slug:"infobel_br",name:"Infobel Brasil",url:"https://www.infobel.com/pt",type:"local"},'
			. '{slug:"cylex_br",name:"Cylex Brasil",url:"https://www.cylex.com.br",type:"local"},'
			. '{slug:"achei",name:"Achei",url:"https://www.achei.com.br",type:"local"},'
			. '{slug:"tudo_sobre",name:"Tudo Sobre",url:"https://www.tudosobre.com.br",type:"local"},'
			. '{slug:"negocios_br",name:"Neg\u00f3cios",url:"https://www.negocios.com.br",type:"local"},'
			. '{slug:"europages_br",name:"Europages PT",url:"https://www.europages.com.br",type:"local"}'
			. '],'
			. 'tr:['
			. '{slug:"yellow_pages_tr",name:"Yellow Pages Turkey",url:"https://www.yellowpages.com.tr",type:"local"},'
			. '{slug:"cylex_tr",name:"Cylex T\u00fcrkiye",url:"https://www.cylex.com.tr",type:"local"},'
			. '{slug:"turkiye_rehberi",name:"T\u00fcrkiye Rehberi",url:"https://www.turkiyerehberi.com",type:"local"},'
			. '{slug:"hotfrog_tr",name:"Hotfrog T\u00fcrkiye",url:"https://www.hotfrog.com.tr",type:"local"},'
			. '{slug:"foursquare_tr",name:"Foursquare",url:"https://foursquare.com",type:"local"},'
			. '{slug:"linkedin_tr",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"local"},'
			. '{slug:"tripadvisor_tr",name:"TripAdvisor",url:"https://www.tripadvisor.com.tr",type:"local"},'
			. '{slug:"europages_tr",name:"Europages TR",url:"https://www.europages.com.tr",type:"local"},'
			. '{slug:"kompass_tr",name:"Kompass T\u00fcrkiye",url:"https://tr.kompass.com",type:"local"},'
			. '{slug:"sahibinden",name:"Sahibinden",url:"https://www.sahibinden.com",type:"local"},'
			. '{slug:"firmarehberi",name:"Firma Rehberi",url:"https://www.firmarehberi.com.tr",type:"local"},'
			. '{slug:"infobel_tr",name:"Infobel Turkiye",url:"https://www.infobel.com/tr",type:"local"},'
			. '{slug:"ustalar",name:"\u00dcstalar",url:"https://www.ustalar.com",type:"local"},'
			. '{slug:"markadir",name:"Markadir",url:"https://www.markadir.com",type:"local"},'
			. '{slug:"cylex2_tr",name:"Cylex TR 2",url:"https://www.cylex-tr.com",type:"local"}'
			. '],'
			. 'de:['
			. '{slug:"gelbe_seiten",name:"Gelbe Seiten",url:"https://www.gelbeseiten.de",type:"local"},'
			. '{slug:"das_oertliche",name:"Das \u00d6rtliche",url:"https://www.dasoertliche.de",type:"local"},'
			. '{slug:"11880",name:"11880.com",url:"https://www.11880.com",type:"local"},'
			. '{slug:"cylex_de",name:"Cylex Deutschland",url:"https://www.cylex.de",type:"local"},'
			. '{slug:"hotfrog_de",name:"Hotfrog Deutschland",url:"https://www.hotfrog.de",type:"local"},'
			. '{slug:"europages_de",name:"Europages DE",url:"https://www.europages.de",type:"local"},'
			. '{slug:"kompass_de",name:"Kompass Deutschland",url:"https://de.kompass.com",type:"local"},'
			. '{slug:"infobel_de",name:"Infobel Deutschland",url:"https://www.infobel.com/de",type:"local"},'
			. '{slug:"tripadvisor_de",name:"TripAdvisor",url:"https://www.tripadvisor.de",type:"local"},'
			. '{slug:"linkedin_de",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"local"},'
			. '{slug:"foursquare_de",name:"Foursquare",url:"https://foursquare.com",type:"local"},'
			. '{slug:"wlw",name:"Wer liefert was",url:"https://www.wlw.de",type:"local"},'
			. '{slug:"kennstdueinen",name:"Kennst du einen",url:"https://www.kennstdueinen.de",type:"local"},'
			. '{slug:"meine_stadt",name:"meinestadt.de",url:"https://www.meinestadt.de",type:"local"},'
			. '{slug:"branchenbuch",name:"Branchenbuch",url:"https://www.branchenbuch.de",type:"local"}'
			. ']'
			. '};'
			. 'var _cat_lower=_cat.toLowerCase();'
			. 'var _family="generic";'
			. 'if(/restaurant|caf\u00e9|cafe|bar|bakery|boulangerie|pizza|sushi|bistro|brasserie/.test(_cat_lower))_family="food";'
			. 'else if(/doctor|dentist|pharmacy|clinic|health|m\u00e9decin|pharmacie|sant\u00e9|klinik|doktor/.test(_cat_lower))_family="health";'
			. 'else if(/plumber|electric|paint|carpenter|builder|plombier|\u00e9lectr|ma\u00e7on|artisan|handwerk/.test(_cat_lower))_family="home";'
			. 'else if(/hair|salon|spa|beauty|nail|coiffeur|beaut\u00e9|estheti/.test(_cat_lower))_family="beauty";'
			. 'else if(/lawyer|account|consult|notary|avocat|comptable|conseil|anwalt|steuer|marketing|seo|digital|communication/.test(_cat_lower))_family="professional";'
			. 'else if(/hotel|b&b|hostel|travel|tourism|h\u00f4tel|tourisme|reise/.test(_cat_lower))_family="travel";'
			. 'else if(/car|auto|garage|mechanic|voiture|kfz/.test(_cat_lower))_family="automotive";'
			. 'else if(/school|tutor|coach|training|\u00e9cole|formation|schule/.test(_cat_lower))_family="education";'
			. 'var _nicheMap={'
			. 'food:[{slug:"thefork",name:"TheFork",url:"https://restaurant.thefork.com",type:"niche"},{slug:"deliveroo",name:"Deliveroo Partners",url:"https://restaurants.deliveroo.com",type:"niche"},{slug:"ubereats",name:"Uber Eats",url:"https://merchants.ubereats.com",type:"niche"},{slug:"zomato",name:"Zomato",url:"https://www.zomato.com",type:"niche"},{slug:"tripadvisor_food",name:"TripAdvisor Food",url:"https://www.tripadvisor.com",type:"niche"}],'
			. 'health:[{slug:"doctolib",name:"Doctolib",url:"https://pro.doctolib.fr",type:"niche"},{slug:"doctoralia",name:"Doctoralia",url:"https://pro.doctoralia.es",type:"niche"},{slug:"healthgrades",name:"Healthgrades",url:"https://www.healthgrades.com",type:"niche"},{slug:"zocdoc",name:"ZocDoc",url:"https://www.zocdoc.com",type:"niche"},{slug:"vitaldoc",name:"Vitaldoc",url:"https://www.vitaldoc.fr",type:"niche"}],'
			. 'home:[{slug:"houzz",name:"Houzz Pro",url:"https://www.houzz.com/pro",type:"niche"},{slug:"habitissimo",name:"Habitissimo",url:"https://pro.habitissimo.es",type:"niche"},{slug:"travaux_com",name:"Travaux.com",url:"https://entreprise.travaux.com",type:"niche"},{slug:"homify",name:"Homify",url:"https://www.homify.com",type:"niche"},{slug:"checkatrade",name:"Checkatrade",url:"https://www.checkatrade.com",type:"niche"}],'
			. 'beauty:[{slug:"treatwell",name:"Treatwell",url:"https://partners.treatwell.com",type:"niche"},{slug:"booksy",name:"Booksy",url:"https://booksy.com/en-us/for-business",type:"niche"},{slug:"fresha",name:"Fresha",url:"https://www.fresha.com/for-business",type:"niche"},{slug:"planity",name:"Planity",url:"https://www.planity.com/pro",type:"niche"},{slug:"wahanda",name:"Wahanda",url:"https://www.wahanda.com",type:"niche"}],'
			. 'professional:[{slug:"malt",name:"Malt",url:"https://www.malt.fr",type:"niche"},{slug:"clutch",name:"Clutch",url:"https://clutch.co",type:"niche"},{slug:"linkedin_pro",name:"LinkedIn Company",url:"https://www.linkedin.com/company/add/show",type:"niche"},{slug:"bark",name:"Bark.com",url:"https://www.bark.com",type:"niche"},{slug:"sortlist",name:"Sortlist",url:"https://www.sortlist.com",type:"niche"}],'
			. 'travel:[{slug:"booking",name:"Booking.com",url:"https://partner.booking.com",type:"niche"},{slug:"expedia",name:"Expedia Partner",url:"https://www.expediagroup.com",type:"niche"},{slug:"airbnb",name:"Airbnb Host",url:"https://www.airbnb.com/host/homes",type:"niche"},{slug:"tripadvisor_hotel",name:"TripAdvisor Hotels",url:"https://www.tripadvisor.com",type:"niche"},{slug:"hotels_com",name:"Hotels.com",url:"https://www.hotels.com",type:"niche"}],'
			. 'automotive:[{slug:"vroomly",name:"Vroomly",url:"https://www.vroomly.com",type:"niche"},{slug:"oscaro",name:"Oscaro Pro",url:"https://pro.oscaro.com",type:"niche"},{slug:"autosphere",name:"Autosphere",url:"https://www.autosphere.fr",type:"niche"},{slug:"motorists",name:"Motorists",url:"https://www.motorists.org",type:"niche"},{slug:"garages_fr",name:"Garages.fr",url:"https://www.garages.fr",type:"niche"}],'
			. 'education:[{slug:"superprof",name:"Superprof",url:"https://www.superprof.fr",type:"niche"},{slug:"preply",name:"Preply",url:"https://preply.com/en/teach",type:"niche"},{slug:"teacheron",name:"TeacherOn",url:"https://www.teacheron.com",type:"niche"},{slug:"italki",name:"iTalki",url:"https://www.italki.com/teacher",type:"niche"},{slug:"lessonface",name:"Lessonface",url:"https://www.lessonface.com",type:"niche"}],'
			. 'generic:[{slug:"hotfrog",name:"Hotfrog",url:"https://www.hotfrog.com",type:"niche"},{slug:"cylex",name:"Cylex",url:"https://www.cylex.com",type:"niche"},{slug:"brownbook",name:"Brownbook",url:"https://www.brownbook.net",type:"niche"},{slug:"n49",name:"N49",url:"https://www.n49.com",type:"niche"},{slug:"spoke",name:"Spoke",url:"https://www.spoke.com",type:"niche"}]'
			. '};'
			. 'var _niche=_nicheMap[_family]||_nicheMap.generic;'
			. 'var _local=_byLang[_lang]||[];'
			. 'return {universal:_universal,local:_local,niche:_niche,family:_family,category:_cat};'
			. '}'
			. 'function _helpFaqCard(question,answer,tabId,googleUrl){'
			. 'var navT=_embedNavI18n[_embedLang]||_embedNavI18n.en;'
			. 'var tabLabel=navT[tabId]||tabId;'
			. 'var googleBtn=googleUrl?"<a href=\\""+googleUrl+"\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\" style=\\"display:inline-flex;align-items:center;gap:4px;font-size:12px;color:#2563eb;text-decoration:none;padding:4px 10px;border:1px solid #bfdbfe;border-radius:6px;background:#eff6ff;\\">\u2197 Google Support</a>":"";'
			. 'var tabBtn=tabId?"<button type=\\"button\\" class=\\"avi-help-tab-btn\\" data-tab=\\""+tabId+"\\" style=\\"display:inline-flex;align-items:center;gap:4px;font-size:12px;color:#5b21b6;padding:4px 10px;border:1px solid #ddd6fe;border-radius:6px;background:#f5f3ff;cursor:pointer;\\">\u2192 "+tabLabel+"</button>":"";'
			. 'return "<div class=\\"avi-help-faq-card\\" style=\\"border-bottom:1px solid #f1f5f9;\\">"'
			. '+"<div class=\\"avi-help-faq-hdr\\" style=\\"display:flex;align-items:center;justify-content:space-between;padding:12px 14px;cursor:pointer;user-select:none;\\">"'
			. '+"<span style=\\"font-size:13px;font-weight:600;color:#1e293b;\\">"+question+"</span>"'
			. '+"<span class=\\"avi-help-chevron\\" style=\\"color:#6d28d9;font-size:14px;\\">▸</span>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-help-faq-body\\" style=\\"display:none;padding:0 14px 12px 14px;border-top:1px solid #f8f5ff;\\">"'
			. '+"<p style=\\"font-size:12px;color:#374151;line-height:1.6;margin:10px 0 8px 0;\\">"+answer+"</p>"'
			. '+"<div style=\\"display:flex;gap:6px;flex-wrap:wrap;align-items:center;\\">"+tabBtn+googleBtn+"</div>"'
			. '+"</div>"'
			. '+"</div>";'
			. '}'
			. 'function _helpSectionCard(title,borderColor,bgHeader,faqs){'
			. 'return "<div class=\\"avi-help-section-card\\" style=\\"background:#fff;border:1px solid "+borderColor+";border-radius:12px;overflow:hidden;margin-bottom:0;\\">"'
			. '+"<div class=\\"avi-help-section-hdr\\" style=\\"display:flex;align-items:center;justify-content:space-between;padding:14px 16px;cursor:pointer;user-select:none;background:"+bgHeader+";border-bottom:1px solid "+borderColor+";\\">"'
			. '+"<span style=\\"font-size:13px;font-weight:700;color:#1e293b;\\">"+title+"</span>"'
			. '+"<span class=\\"avi-help-section-chevron\\" style=\\"color:#6d28d9;font-size:14px;\\">▾</span>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-help-section-body\\" style=\\"display:none;\\">"+faqs+"</div>"'
			. '+"</div>";'
			. '}'
			. 'function _renderHelpPanel(){'
			. 'if(!_helpPanel)return;'
			. '_helpPanel.scrollTop=0;'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _supportUrl="https://support.google.com/business?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang);'
			. '_helpPanel.innerHTML=""'
			. '+"<div style=\\"padding:16px 16px 80px 16px;\\">"'
			. '+"<div style=\\"background:linear-gradient(135deg,#6d28d9,#4f46e5);border-radius:12px;padding:20px 24px;margin-bottom:20px;color:#fff;\\">"'
			. '+"<div style=\\"font-size:18px;font-weight:700;margin-bottom:4px;\\">"+(_t.help_title||"Help & FAQ")+"</div>"'
			. '+"<div style=\\"font-size:13px;opacity:0.85;\\">"+(_t.help_subtitle||"Find answers to common questions about your Google Business Profile")+"</div>"'
			. '+"</div>"'
			. '+"<div style=\\"display:grid;grid-template-columns:1fr 1fr;gap:12px;\\">"'
			. '+_helpSectionCard(_t.help_s1_title||"🔴 Top 5 — Common Problems","#fecaca","#fff8f8",'
			. '_helpFaqCard(_t.help_faq1_q||"🚫 My listing is suspended",_t.help_faq1_a||"","home","https://support.google.com/business/answer/4596754?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang))'
			. '+_helpFaqCard(_t.help_faq2_q||"🔍 My listing doesn\'t appear on Google Maps",_t.help_faq2_a||"","score","https://support.google.com/business/answer/6001972?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang))'
			. '+_helpFaqCard(_t.help_faq3_q||"✅ How to verify my listing (video)",_t.help_faq3_a||"","home","https://support.google.com/business/answer/4596754?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang))'
			. '+_helpFaqCard(_t.help_faq4_q||"✏️ Unauthorized edits were made to my listing",_t.help_faq4_a||"","home","")'
			. '+_helpFaqCard(_t.help_faq5_q||"⭐ I can\'t reply to reviews",_t.help_faq5_a||"","avis","https://support.google.com/business/answer/3474050?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang))'
			. ')'
			. '+_helpSectionCard(_t.help_s2_title||"🟣 Optimize My Profile","#ddd6fe","#f5f3ff",'
			. '_helpFaqCard(_t.help_faq6_q||"📸 Which photos should I post?",_t.help_faq6_a||"","photos","")'
			. '+_helpFaqCard(_t.help_faq7_q||"🏷️ How do I choose the right category?",_t.help_faq7_a||"","score","")'
			. '+_helpFaqCard(_t.help_faq8_q||"📝 How do I write a good description?",_t.help_faq8_a||"","score","")'
			. '+_helpFaqCard(_t.help_faq9_q||"🗓️ How often should I post?",_t.help_faq9_a||"","posts","")'
			. '+_helpFaqCard(_t.help_faq10_q||"⭐ How do I get more reviews?",_t.help_faq10_a||"","avis","")'
			. '+_helpFaqCard(_t.help_faq11_q||"📍 Address or service area?",_t.help_faq11_a||"","score","")'
			. '+_helpFaqCard(_t.help_faq12_q||"🔄 I have a duplicate listing",_t.help_faq12_a||"","home","https://support.google.com/business/answer/3474050?hl="+(_embedLang==="pt-br"?"pt-BR":_embedLang))'
			. ')'
			. '+_helpSectionCard(_t.help_s3_title||"🔵 Google\'s Updates","#bfdbfe","#eff6ff",'
			. '_helpFaqCard(_t.help_faq13_q||"🤖 Q&A removed — Ask Maps (Gemini)",_t.help_faq13_a||"","score","")'
			. '+_helpFaqCard(_t.help_faq14_q||"🛡️ New review rules",_t.help_faq14_a||"","avis","")'
			. '+_helpFaqCard(_t.help_faq15_q||"⚡ Rapid edits can trigger suspension",_t.help_faq15_a||"","home","")'
			. ')'
			. '+"</div>"'
			. '+"</div>";'
			. 'if(!window._aviHelpAccordionAdded){'
			. 'window._aviHelpAccordionAdded=true;'
			. '_helpPanel.addEventListener("click",function(ev){'
			. 'var hdr=ev.target.closest(".avi-help-faq-hdr,.avi-help-section-hdr");'
			. 'if(hdr){'
			. 'var isSec=hdr.classList.contains("avi-help-section-hdr");'
			. 'if(isSec){'
			. 'var sec=hdr.closest(".avi-help-section-card");'
			. 'var body=sec?sec.querySelector(".avi-help-section-body"):null;'
			. 'if(body){var open=body.style.display==="none";body.style.display=open?"block":"none";hdr.querySelector(".avi-help-section-chevron").textContent=open?"▾":"▸";}'
			. '}else{'
			. 'var card=hdr.closest(".avi-help-faq-card");'
			. 'var body=card?card.querySelector(".avi-help-faq-body"):null;'
			. 'if(body){var open=body.style.display==="block";body.style.display=open?"none":"block";hdr.querySelector(".avi-help-chevron").textContent=open?"▸":"▾";}'
			. '}'
			. 'return;'
			. '}'
			. 'var tabBtn=ev.target.closest(".avi-help-tab-btn");'
			. 'if(tabBtn){_switchEmbedTab(tabBtn.getAttribute("data-tab"));return;}'
			. '});'
			. '}'
			. 'var _hpClose=document.createElement("button");'
			. '_hpClose.type="button";'
			. '_hpClose.className="avi-score-close";'
			. '_hpClose.textContent="\u00d7";'
			. '_hpClose.style.cssText="position:absolute;top:12px;right:16px;background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;z-index:20;";'
			. '_hpClose.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_helpPanel.appendChild(_hpClose);'
			. '}'
			. 'function _citationsRender(){'
			. 'if(!_citationsPanel)return;'
			. '_citationsPanel.innerHTML="";'
			. 'var _citCloseBtn=document.createElement("button");'
			. '_citCloseBtn.type="button";'
			. '_citCloseBtn.className="avi-score-close";'
			. '_citCloseBtn.textContent="\u00d7";'
			. '_citCloseBtn.style.cssText="position:absolute;top:12px;right:16px;background:none;border:none;font-size:24px;color:#94a3b8;cursor:pointer;z-index:5;";'
			. '_citCloseBtn.addEventListener("click",function(){_switchEmbedTab("home");});'
			. '_citationsPanel.appendChild(_citCloseBtn);'
			. 'var _citInner=document.createElement("div");'
			. '_citInner.style.cssText="max-width:900px;margin:0 auto;";'
			. 'var _t2=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _dirs=_citationsGetDirectories();'
			. 'var _saved=(window.aviEmbedCitationsData&&window.aviEmbedCitationsData.citations)||{};'
			. 'var _custom=(window.aviEmbedCitationsData&&window.aviEmbedCitationsData.custom)||[];'
			. 'var _topbar=document.createElement("div");'
			. '_topbar.className="avi-score-topbar";'
			. '_topbar.innerHTML='
			. '\'<div class="avi-score-topbar-left">\''
			. '+\'<div class="avi-score-topbar-title">\''
			. '+"\\ud83d\\udccb "+(_t2.cit_title||"Citations")'
			. '+\' <button type="button" class="avi-header-info-btn" id="aviCitInfoBtn">\u2139\ufe0f</button>\''
			. '+\'</div>\''
			. '+(window.aviEmbedScoreData&&window.aviEmbedScoreData.business_name?\'<div class="avi-score-topbar-biz">\'+window.aviEmbedScoreData.business_name+\'</div>\':"")'
			. '+\'<div class="avi-score-topbar-sub">\'+(_t2.cit_panel_sub||"")+\'</div>\''
			. '+\'</div>\''
			. '+\'<div class="avi-score-topbar-right"></div>\';'
			. '_citInner.appendChild(_topbar);'
			. 'var _citInfoBtn=_topbar.querySelector("#aviCitInfoBtn");'
			. 'if(_citInfoBtn){'
			. '_citInfoBtn.addEventListener("click",function(e){'
			. 'e.preventDefault();e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_tL.cit_info_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.cit_info_s1_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.cit_info_s1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.cit_info_s2_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.cit_info_s2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.cit_info_s3_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.cit_info_s3_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-title">\'+(_tL.cit_info_s4_title||"")+\'</div><div class="avi-edu-step-body">\'+(_tL.cit_info_s4_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviCitInfoClose">\'+(_tL.edu_banner_close||"Got it \\u2713")+\'</button>\''
			. '+\'</div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(ev){if(ev.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviCitInfoClose").addEventListener("click",function(){backdrop.remove();});'
			. '});'
			. '}'
			. 'var _body=document.createElement("div");'
			. '_body.className="avi-cit-body";'
			. '_body.style.padding="0";'
			. 'var _bannerKey="avi_cit_banner_dismissed_"+(_embedLang||"en");'
			. 'var _bannerDismissed=false;try{_bannerDismissed=!!localStorage.getItem(_bannerKey);}catch(e){}'
			. 'if(!_bannerDismissed){'
			. 'var _banner=document.createElement("div");'
			. '_banner.className="avi-cit-info-banner";'
			. 'var _bannerTxt=document.createElement("div");'
			. '_bannerTxt.className="avi-cit-info-banner-text";'
			. 'var _catLabel=_dirs.category||(_t2.cit_your_category||"your category");'
			. 'var _bannerMsg=(_t2.cit_banner_msg||"We automatically selected directories based on your Google Business category \\"{cat}\\". Some suggestions may not be a perfect fit \u2014 feel free to remove them or add your own.").replace("{cat}",_catLabel);'
			. '_bannerTxt.textContent="\u2139\ufe0f "+_bannerMsg;'
			. 'var _bannerClose=document.createElement("button");'
			. '_bannerClose.className="avi-cit-info-close";'
			. '_bannerClose.textContent="\u00d7";'
			. '_bannerClose.addEventListener("click",function(){'
			. 'try{localStorage.setItem(_bannerKey,"1");}catch(e){}'
			. '_banner.style.display="none";'
			. '});'
			. '_banner.appendChild(_bannerTxt);_banner.appendChild(_bannerClose);'
			. '_body.appendChild(_banner);'
			. '}'
			. 'var _allDirs=_dirs.universal.concat(_dirs.local).concat(_dirs.niche);'
			. 'var _customDirs=_custom.map(function(c){return {slug:c.slug,name:c.name,url:c.url,type:"custom"};});'
			. 'var _allWithCustom=_allDirs.concat(_customDirs);'
			. 'var _visibleDirs=_allWithCustom.filter(function(d){return !_saved[d.slug]||_saved[d.slug].status!=="hidden";});'
			. 'var _doneDirs=_visibleDirs.filter(function(d){var s=_saved[d.slug];return s&&(s.status==="done"||s.status==="already_listed");});'
			. 'var _todoDirs=_visibleDirs.filter(function(d){var s=_saved[d.slug];return !s||s.status==="none"||s.status==="hidden"||!s.status;});'
			. 'var _total=_visibleDirs.length;'
			. 'var _doneCount=_doneDirs.length;'
			. 'var _pct=_total>0?Math.round((_doneCount/_total)*100):0;'
			. 'var _prog=document.createElement("div");'
			. '_prog.className="avi-cit-progress";'
			. 'var _progLbl=document.createElement("div");'
			. '_progLbl.className="avi-cit-progress-label";'
			. '_progLbl.textContent=_doneCount+"/"+_total+" "+(_t2.cit_listed||"listed");'
			. 'var _progWrap=document.createElement("div");'
			. '_progWrap.className="avi-cit-progress-bar-wrap";'
			. 'var _progBar=document.createElement("div");'
			. '_progBar.className="avi-cit-progress-bar";'
			. '_progBar.style.width=_pct+"%";'
			. '_progWrap.appendChild(_progBar);'
			. '_prog.appendChild(_progLbl);_prog.appendChild(_progWrap);'
			. '_body.appendChild(_prog);'
			. 'function _renderItem(dir,isDoneSection){'
			. 'var saved=_saved[dir.slug]||{status:"none"};'
			. 'var isDone=saved.status==="done"||saved.status==="already_listed";'
			. 'var isAlready=saved.status==="already_listed";'
			. 'var isNicheOrCustom=dir.type==="niche"||dir.type==="custom";'
			. 'var _badgeMap={universal:"\ud83c\udf0d",local:"\ud83c\udff3\ufe0f",niche:"\ud83c\udfaf",custom:"\u2795"};'
			. 'var item=document.createElement("div");'
			. 'item.className="avi-cit-item"+(isDone?(isAlready?" avi-cit-item--already":" avi-cit-item--done"):"");'
			. 'var _row=document.createElement("div");'
			. '_row.style.cssText="display:flex;align-items:center;gap:10px;";'
			. 'var _badge=document.createElement("span");'
			. '_badge.className="avi-cit-badge";'
			. '_badge.textContent=_badgeMap[dir.type]||"\ud83c\udf0d";'
			. 'var _name=document.createElement("div");'
			. '_name.className="avi-cit-name";'
			. 'var _link=document.createElement("a");'
			. '_link.href=dir.url;_link.target="_blank";_link.rel="noopener";'
			. '_link.textContent=dir.name+" \u2197";'
			. '_name.appendChild(_link);'
			. 'var _acts=document.createElement("div");'
			. '_acts.className="avi-cit-actions";'
			. 'if(!isDoneSection){'
			. 'var _btnD=document.createElement("button");'
			. '_btnD.className="avi-cit-btn"+(saved.status==="done"?" avi-cit-btn--done":"");'
			. '_btnD.textContent=saved.status==="done"?"\u2713 "+(_t2.cit_done||"Done"):(_t2.cit_mark_done||"\u2713 Done");'
			. 'var _btnA=document.createElement("button");'
			. '_btnA.className="avi-cit-btn"+(saved.status==="already_listed"?" avi-cit-btn--already":"");'
			. '_btnA.textContent=saved.status==="already_listed"?"\u2713 "+(_t2.cit_already||"Already listed"):(_t2.cit_mark_already||"\u2713 Already listed");'
			. '_acts.appendChild(_btnD);_acts.appendChild(_btnA);'
			. 'if(isNicheOrCustom){'
			. 'var _btnX=document.createElement("button");'
			. '_btnX.className="avi-cit-btn--remove";'
			. '_btnX.title=(_t2.cit_remove||"Remove");'
			. '_btnX.textContent="\u00d7";'
			. '_btnX.addEventListener("click",function(e){e.stopPropagation();_citationSave(dir.slug,"hidden","",function(){_citationsRender();_citationsUpdateScore();});});'
			. '_acts.appendChild(_btnX);'
			. '}'
			. '(function(d,s,b1,b2){'
			. 'b1.addEventListener("click",function(){var ns=s.status==="done"?"none":"done";_citationSave(d.slug,ns,"",function(){_citationsRender();_citationsUpdateScore();});});'
			. 'b2.addEventListener("click",function(){var ns=s.status==="already_listed"?"none":"already_listed";_citationSave(d.slug,ns,s.listing_url||"",function(){_citationsRender();_citationsUpdateScore();});});'
			. '})(dir,saved,_btnD,_btnA);'
			. '}else{'
			. 'var _btnUndo=document.createElement("button");'
			. '_btnUndo.className="avi-cit-btn";'
			. '_btnUndo.textContent=(_t2.cit_undo||"\u21a9 Annuler");'
			. '_btnUndo.addEventListener("click",function(){_citationSave(dir.slug,"none","",function(){_citationsRender();_citationsUpdateScore();});});'
			. '_acts.appendChild(_btnUndo);'
			. '}'
			. '_row.appendChild(_badge);_row.appendChild(_name);_row.appendChild(_acts);'
			. 'item.appendChild(_row);'
			. 'if(isDoneSection){'
			. 'var _urlRow=document.createElement("div");'
			. '_urlRow.className="avi-cit-url-row";'
			. 'var _urlInput=document.createElement("input");'
			. '_urlInput.type="url";_urlInput.className="avi-cit-url-input";'
			. '_urlInput.placeholder=(_t2.cit_url_placeholder||"Your listing URL (optional)");'
			. '_urlInput.value=saved.listing_url||"";'
			. 'var _urlBtn=document.createElement("button");'
			. '_urlBtn.className="avi-cit-url-save";'
			. '_urlBtn.textContent=(_t2.save||"Save");'
			. '_urlBtn.addEventListener("click",function(){_citationSave(dir.slug,saved.status,_urlInput.value,function(){_citationsRender();_citationsUpdateScore();});});'
			. '_urlRow.appendChild(_urlInput);_urlRow.appendChild(_urlBtn);'
			. 'item.appendChild(_urlRow);'
			. '}'
			. 'return item;'
			. '}'
			. 'if(_todoDirs.length){'
			. 'var _todoLbl=document.createElement("div");'
			. '_todoLbl.className="avi-cit-section-label";'
			. '_todoLbl.textContent=(_t2.cit_todo||"\ud83d\udccb To do")+" ("+_todoDirs.length+")";'
			. '_body.appendChild(_todoLbl);'
			. '_todoDirs.forEach(function(d){_body.appendChild(_renderItem(d,false));});'
			. '}'
			. 'var _addRow=document.createElement("div");'
			. '_addRow.className="avi-cit-add-row";'
			. 'var _addName=document.createElement("input");'
			. '_addName.type="text";_addName.className="avi-cit-add-input";'
			. '_addName.placeholder=(_t2.cit_add_name||"Directory name");'
			. 'var _addUrl=document.createElement("input");'
			. '_addUrl.type="url";_addUrl.className="avi-cit-add-input";'
			. '_addUrl.placeholder=(_t2.cit_add_url||"https://...");'
			. 'var _addBtn=document.createElement("button");'
			. '_addBtn.className="avi-cit-add-btn";'
			. '_addBtn.textContent=(_t2.cit_add_btn||"+ Add");'
			. '_addBtn.addEventListener("click",function(){'
			. 'var _n=_addName.value.trim();var _u=_addUrl.value.trim();'
			. 'if(!_n)return;'
			. 'var _slug="custom_"+Date.now();'
			. 'if(!window.aviEmbedCitationsData)window.aviEmbedCitationsData={};'
			. 'if(!window.aviEmbedCitationsData.custom)window.aviEmbedCitationsData.custom=[];'
			. 'window.aviEmbedCitationsData.custom.push({slug:_slug,name:_n,url:_u||"#"});'
			. '_citationSave(_slug,"none",_u,function(){_citationsRender();});'
			. '_addName.value="";_addUrl.value="";'
			. '});'
			. '_addRow.appendChild(_addName);_addRow.appendChild(_addUrl);_addRow.appendChild(_addBtn);'
			. '_body.appendChild(_addRow);'
			. 'var _trustNote=document.createElement("div");'
			. '_trustNote.className="avi-cit-tooltip";'
			. '_trustNote.style.cssText="text-align:center;margin:8px 0 16px;font-size:11px;";'
			. '_trustNote.textContent=(_t2.cit_trust||"We trust you \u2014 we don\u0027t verify this automatically");'
			. '_body.appendChild(_trustNote);'
			. 'if(_doneDirs.length){'
			. 'var _doneHdr=document.createElement("div");'
			. '_doneHdr.className="avi-cit-done-section-hdr";'
			. 'var _doneLbl=document.createElement("div");'
			. '_doneLbl.className="avi-cit-done-label";'
			. '_doneLbl.textContent="\u2705 "+(_t2.cit_completed||"Completed")+" ("+_doneCount+")";'
			. 'var _doneToggle=document.createElement("button");'
			. '_doneToggle.className="avi-cit-done-toggle";'
			. '_doneToggle.textContent=(_t2.cit_collapse||"\u25b2 Collapse");'
			. '_doneHdr.appendChild(_doneLbl);_doneHdr.appendChild(_doneToggle);'
			. '_body.appendChild(_doneHdr);'
			. 'var _doneList=document.createElement("div");'
			. '_doneDirs.forEach(function(d){_doneList.appendChild(_renderItem(d,true));});'
			. '_body.appendChild(_doneList);'
			. '_doneToggle.addEventListener("click",function(){'
			. 'var _v=_doneList.style.display==="none";'
			. '_doneList.style.display=_v?"block":"none";'
			. '_doneToggle.textContent=_v?(_t2.cit_collapse||"\u25b2 Collapse"):(_t2.cit_expand||"\u25bc Expand");'
			. '});'
			. '}'
			. '_citInner.appendChild(_body);'
			. '_citationsPanel.appendChild(_citInner);'
			. '}'
			. 'function _citationsFetch(){'
			. 'if(!window.aviEmbedProfileId||!window.aviEmbedToken)return;'
			. 'fetch(window.aviEmbedRestUrl+"embed/citations?profile_id="+window.aviEmbedProfileId,{headers:{"X-Embed-Token":window.aviEmbedToken||""}})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){'
			. 'if(!d||!d.citations)return;'
			. 'if(!window.aviEmbedCitationsData)window.aviEmbedCitationsData={};'
			. 'window.aviEmbedCitationsData.citations=d.citations;'
			. 'if(typeof _citationsRender==="function"&&_embedCurrentTab==="citations")_citationsRender();'
			. 'if(typeof _scoreRender==="function"&&_embedCurrentTab==="score")_scoreRender();'
			. '})'
			. '.catch(function(){});'
			. '}'
			. 'function _citationSave(slug,status,url,cb){'
			. 'if(!window.aviEmbedProfileId||!window.aviEmbedToken)return;'
			. 'fetch(window.aviEmbedRestUrl+"embed/citations/save",{method:"POST",headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken||""},body:JSON.stringify({profile_id:window.aviEmbedProfileId,directory_slug:slug,status:status,listing_url:url||""})})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){'
			. 'if(d&&d.success){'
			. 'if(!window.aviEmbedCitationsData)window.aviEmbedCitationsData={};'
			. 'if(!window.aviEmbedCitationsData.citations)window.aviEmbedCitationsData.citations={};'
			. 'var _now=new Date().toISOString();'
			. 'var _existing=window.aviEmbedCitationsData.citations[slug]||{};'
			. 'window.aviEmbedCitationsData.citations[slug]=Object.assign({},_existing,{'
			. 'status:status,'
			. 'listing_url:url||_existing.listing_url||"",'
			. 'done_at:status==="none"?null:(_existing.done_at||_now),'
			. 'last_updated_at:_now'
			. '});'
			. 'if(cb)cb();'
			. '}'
			. '})'
			. '.catch(function(){});'
			. '}'
			. 'function _citationsUpdateScore(){'
			. 'var _dirs=_citationsGetDirectories();'
			. 'var _saved=(window.aviEmbedCitationsData&&window.aviEmbedCitationsData.citations)||{};'
			. 'var _total=_dirs.universal.length+_dirs.local.length+_dirs.niche.length;'
			. 'var _done=Object.values(_saved).filter(function(s){return s.status==="done"||s.status==="already_listed";}).length;'
			. 'var _score=_total>0?Math.round((_done/_total)*15):0;'
			. 'if(window.aviEmbedCitationsData){window.aviEmbedCitationsData.score=_score;window.aviEmbedCitationsData.done=_done;}'
			. '}'
			. 'var _phWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_phWrap.appendChild(_photosPanel);'

			. '_citationsPanel=document.createElement("div");'
			. '_citationsPanel.className="avi-cit-panel avi-citations-panel";'
			. '_citationsPanel.id="aviEmbedCitationsPanel";'
			. 'var _citWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_citWrap.appendChild(_citationsPanel);'
			. '_helpPanel=document.createElement("div");'
			. '_helpPanel.id="aviEmbedHelpPanel";'
			. '_helpPanel.className="avi-embed-panel";'
			. '_helpPanel.style.cssText="position:absolute;inset:0;background:#f8fafc;z-index:10;display:none;overflow-y:auto;padding:0;";'
			. 'var _helpWrap=document.querySelector(".avi-embed-wrap")||document.body;'
			. '_helpWrap.appendChild(_helpPanel);'
			. '_citationsFetch();'

			. '/* === VOLET AGENCE === */'
			. 'function _resolveGbpDashboardHref(placeId,locationName){'
			. '  var pid=String(placeId||"").trim();'
			. '  if(pid){'
			. '    return "https://www.google.com/maps/place/?q=place_id:"'
			. '      +encodeURIComponent(pid);'
			. '  }'
			. '  var loc=String(locationName||"").trim()'
			. '    .replace(/^locations\\//i,"").replace(/^\\//,"");'
			. '  if(loc){'
			. '    return "https://www.google.com/maps/search/"'
			. '      +encodeURIComponent(loc);'
			. '  }'
			. '  return "https://www.google.com/maps/";'
			. '}'
			. 'if(window.aviEmbedKeyType==="agency"){'
			. '  _agActiveProfileId=window.aviEmbedProfileId;'
			. '  var _homeBtn=_navBtns["home"];'
			. '  if(_homeBtn&&_homeBtn.parentNode){'
			. '    _subWrap=document.createElement("div");'
			. '    _subWrap.className="avi-submenu-wrap";'
			. '    _homeBtn.parentNode.insertBefore(_subWrap,_homeBtn);'
			. '    _subWrap.appendChild(_homeBtn);'
			. '    var _subArrow=document.createElement("button");'
			. '    _subArrow.type="button";_subArrow.className="avi-submenu-arrow";'
			. '    _subArrow.textContent="▾";'
			. '    _subArrow.title=_t.agency_hub_title;'
			. '    _subWrap.appendChild(_subArrow);'
			. '    _subDrop=document.createElement("div");'
			. '    _subDrop.className="avi-submenu-drop";'
			. '    document.body.appendChild(_subDrop);'
			. '    var _subDropOpen=false;'
			. '    var _subOpts=[["agency_hub",(_embedNavI18n[_embedLang]||_embedNavI18n.en).agency_hub||"🏢 Agency Hub"]];'
			. '    _subOpts.forEach(function(o){'
			. '      var opt=document.createElement("button");'
			. '      opt.type="button";opt.className="avi-submenu-opt";'
			. '      opt.setAttribute("data-submenu-tab",o[0]);'
			. '      opt.textContent=o[1];'
			. '      opt.addEventListener("click",function(){'
			. '        _subDrop.classList.remove("open");_subDropOpen=false;'
			. '        _subDrop.style.display="none";'
			. '        _switchEmbedTab(o[0]);'
			. '      });'
			. '      _subDrop.appendChild(opt);'
			. '    });'
			. '    _subArrow.addEventListener("click",function(e){'
			. '      e.stopPropagation();'
			. '      _subDropOpen=!_subDropOpen;'
			. '      if(_subDropOpen){'
			. '        var r=_subArrow.getBoundingClientRect();'
			. '        _subDrop.style.top=(r.bottom+4)+"px";'
			. '        _subDrop.style.left=r.left+"px";'
			. '        _subDrop.style.display="block";'
			. '      }else{_subDrop.style.display="none";}'
			. '    });'
			. '    document.addEventListener("click",function(e){'
			. '      if(!_subDrop.contains(e.target)&&e.target!==_subArrow){'
			. '        _subDropOpen=false;_subDrop.style.display="none";'
			. '      }'
			. '    });'
			. '  }'
			. '  if(window.aviEmbedKeyType==="agency"){'
			. '  function _agScoreTier(score){'
			. '    if(score<=45)return{cls:"avi-ag-score-red",label:"🔴 "+score};'
			. '    if(score<=60)return{cls:"avi-ag-score-orange",label:"🟠 "+score};'
			. '    if(score<=75)return{cls:"avi-ag-score-yellow",label:"🟡 "+score};'
			. '    if(score<=90)return{cls:"avi-ag-score-green",label:"🟢 "+score};'
			. '    return{cls:"avi-ag-score-gold",label:"⭐ "+score};'
			. '  }'
			. '  function _agRelDate(dt){'
			. '    if(!dt||String(dt).indexOf("1970-01-01")===0)return _t.never;'
			. '    var d=new Date(dt),now=new Date();'
			. '    var diff=Math.floor((now-d)/86400000);'
			. '    if(diff===0)return _t.today;'
			. '    if(diff===1)return _t.yesterday;'
			. '    if(diff<7)return diff+_t.rel_d_ago;'
			. '    if(diff<30)return Math.floor(diff/7)+_t.rel_w_ago;'
			. '    if(diff<365)return Math.floor(diff/30)+_t.rel_mo_ago;'
			. '    return Math.floor(diff/365)+_t.rel_y_ago;'
			. '  }'
			. '  _agOverlay=document.createElement("div");'
			. '  _agOverlay.className="avi-agency-overlay";'
			. '  document.body.appendChild(_agOverlay);'
			. '  _agPanel=document.createElement("div");'
			. '  _agPanel.className="avi-agency-panel";'
			. '  var _agHeader=document.createElement("div");'
			. '  _agHeader.className="avi-agency-header";'
			. '  var _agTitle=document.createElement("h3");'
			. '  _agTitle.textContent=_t.clients_title+" ("+window.aviEmbedAgencyProfiles.length+")";'
			. '  var _agCloseBtn=document.createElement("button");'
			. '  _agCloseBtn.type="button";_agCloseBtn.className="avi-agency-close";'
			. '  _agCloseBtn.textContent="×";'
			. '  _agHeader.appendChild(_agTitle);_agHeader.appendChild(_agCloseBtn);'
			. '  _agPanel.appendChild(_agHeader);'
			. '  var _agSearch=document.createElement("input");'
			. '  _agSearch.type="text";_agSearch.className="avi-agency-search";'
			. '  _agSearch.placeholder=_t.search_client_ph;'
			. '  _agPanel.appendChild(_agSearch);'
			. '  if(window.aviEmbedAgencyCredits){'
			. '    var _agCrBar=document.createElement("div");'
			. '    _agCrBar.className="avi-agency-credits-bar";'
			. '    var _agCrLeft=document.createElement("div");'
			. '    var _agCr=window.aviEmbedAgencyCredits;'
			. '    _agCrLeft.innerHTML=_t.pool_credits+"<span class=\\"avi-agency-credits-val\\">"'
			. '      +_agCr.available+"</span>"+_t.available_word+_agCr.used+_t.used_word;'
			. '    var _agCrBtn=document.createElement("button");'
			. '    _agCrBtn.type="button";_agCrBtn.className="avi-agency-credits-add";'
			. '    _agCrBtn.textContent=_t.add_credits;'
			. '    _agCrBtn.addEventListener("click",function(){'
			. '      _agOpenCreditsHub();'
			. '    });'
			. '    _agCrBar.appendChild(_agCrLeft);_agCrBar.appendChild(_agCrBtn);'
			. '    _agPanel.insertBefore(_agCrBar,_agSearch);'
			. '  }'
			. '  var _agList=document.createElement("div");'
			. '  _agList.className="avi-agency-list";'
			. '  var _agSortSel=document.createElement("select");'
			. '  _agSortSel.className="avi-agency-sort";'
			. '  _agSortSel.style.cssText="margin:8px 16px;width:calc(100% - 32px);'
			. 'display:block;border:1px solid #e2e8f0;border-radius:6px;'
			. 'padding:6px 8px;font-size:11px;";'
			. '  var _agSortOpts=[["score_asc",_t.sort_priority],'
			. '["score_desc",_t.sort_best_score],'
			. '["activity",_t.sort_activity],'
			. '["name",_t.sort_name],'
			. '["kw",_t.sort_kw]];'
			. '  _agSortOpts.forEach(function(o){'
			. '    var opt=document.createElement("option");'
			. '    opt.value=o[0];opt.textContent=o[1];'
			. '    _agSortSel.appendChild(opt);'
			. '  });'
			. '  _agSortSel.addEventListener("change",function(){'
			. '    _agRenderList(_agSearch.value);'
			. '  });'
			. '  _agPanel.appendChild(_agSortSel);'
			. '  _agPanel.appendChild(_agList);'
			. '  var _agFooter=document.createElement("div");'
			. '  _agFooter.className="avi-agency-footer";'
			. '  var _agCount=document.createElement("div");'
			. '  _agCount.className="avi-agency-count";'
			. '  _agCount.textContent=window.aviEmbedAgencyProfiles.length+_t.clients_count_suffix;'
			. '  _agFooter.appendChild(_agCount);'
			. '  _agPanel.appendChild(_agFooter);'
			. '  document.body.appendChild(_agPanel);'
			. '  var _agAssignModal=null;'
			. '  var _agAssignProfileId=0;'
			. '  function _agRefreshPoolDisplay(avail){'
			. '    var poolEl=document.getElementById("aviAssignPoolVal");'
			. '    if(poolEl)poolEl.textContent=avail;'
			. '    var qtyIn=document.getElementById("aviAssignQty");'
			. '    if(qtyIn)qtyIn.max=String(avail);'
			. '    var crVal=document.querySelector(".avi-agency-credits-val");'
			. '    if(crVal)crVal.textContent=avail;'
			. '  }'
			. '  function _agEnsureAssignModal(){'
			. '    if(_agAssignModal)return;'
			. '    var pool0=window.aviEmbedAgencyCredits?window.aviEmbedAgencyCredits.available:0;'
			. '    _agAssignModal=document.createElement("div");'
			. '    _agAssignModal.className="avi-assign-modal-backdrop";'
			. '    _agAssignModal.id="aviAssignModal";'
			. '    _agAssignModal.innerHTML=\'<div class="avi-assign-modal">\''
			. '      +\'<div class="avi-assign-modal-header">\''
			. '      +\'<span>\\uD83D\\uDCB3 Assign credits</span>\''
			. '      +\'<button type="button" id="aviAssignClose">\\u00D7</button>\''
			. '      +\'</div><div class="avi-assign-modal-body">\''
			. '      +\'<p class="avi-assign-client-name" id="aviAssignClientName"></p>\''
			. '      +\'<p class="avi-assign-client-credits" id="aviAssignClientCredits"></p>\''
			. '      +\'<p class="avi-assign-pool">Pool available: <strong id="aviAssignPoolVal">\'+pool0+\'</strong> credits</p>\''
			. '      +\'<div class="avi-assign-qty-wrap">\''
			. '      +\'<button type="button" class="avi-assign-qty-btn" id="aviAssignMinus">-</button>\''
			. '      +\'<input type="number" id="aviAssignQty" value="10" min="10" step="10" max="\'+pool0+\'" />\''
			. '      +\'<button type="button" class="avi-assign-qty-btn" id="aviAssignPlus">+</button>\''
			. '      +\'</div>\''
			. '      +\'<p class="avi-assign-qty-hint" id="aviAssignQtyHint">\'+(_t.assign_min_hint||"Min. 10 cr \\u00b7 Multiples of 10")+\'</p>\''
			. '      +\'<button type="button" class="avi-assign-confirm-btn" id="aviAssignConfirm">\\u2705 Assign credits</button>\''
			. '      +\'<p class="avi-assign-msg" id="aviAssignMsg" style="display:none"></p>\''
			. '      +\'</div></div>\';'
			. '    document.body.appendChild(_agAssignModal);'
			. '    var closeBtn=document.getElementById("aviAssignClose");'
			. '    if(closeBtn)closeBtn.addEventListener("click",function(){_agAssignModal.style.display="none";});'
			. '    _agAssignModal.addEventListener("click",function(e){'
			. '      if(e.target===_agAssignModal)_agAssignModal.style.display="none";'
			. '    });'
			. '    var minusBtn=document.getElementById("aviAssignMinus");'
			. '    var plusBtn=document.getElementById("aviAssignPlus");'
			. '    var qtyInput=document.getElementById("aviAssignQty");'
			. '    if(minusBtn&&qtyInput)minusBtn.addEventListener("click",function(){'
			. '      var v=parseInt(qtyInput.value,10)||10;'
			. '      qtyInput.value=String(Math.max(10,v-10));'
			. '    });'
			. '    if(plusBtn&&qtyInput)plusBtn.addEventListener("click",function(){'
			. '      var maxV=parseInt(qtyInput.max,10)||9999;'
			. '      var v=parseInt(qtyInput.value,10)||10;'
			. '      qtyInput.value=String(Math.min(maxV,v+10));'
			. '    });'
			. '    var confirmBtn=document.getElementById("aviAssignConfirm");'
			. '    if(confirmBtn)confirmBtn.addEventListener("click",function(){'
			. '      var qty=parseInt(qtyInput.value,10);'
			. '      if(!qty||qty<10||qty%10!==0||!_agAssignProfileId)return;'
			. '      var msgEl=document.getElementById("aviAssignMsg");'
			. '      confirmBtn.disabled=true;'
			. '      if(msgEl){msgEl.style.display="none";}'
			. '      fetch(window.location.origin+"/wp-json/avision/v1/embed/assign-credits",{'
			. '        method:"POST",'
			. '        headers:{'
			. '          "Content-Type":"application/json",'
			. '          "X-Embed-Token":window.aviEmbedToken||""'
			. '        },'
			. '        body:JSON.stringify({'
			. '          key_id:window.aviEmbedKeyId,'
			. '          profile_id:window.aviEmbedProfileId,'
			. '          target_profile_id:parseInt(_agAssignProfileId,10)||0,'
			. '          qty:qty'
			. '        })'
			. '      })'
			. '      .then(function(r){return r.json();})'
			. '      .then(function(d){'
			. '        confirmBtn.disabled=false;'
			. '        if(d.success){'
			. '          var profiles=window.aviEmbedAgencyProfiles||[];'
			. '          for(var i=0;i<profiles.length;i++){'
			. '            if(profiles[i].id===parseInt(_agAssignProfileId,10)){'
			. '              profiles[i].client_credits=(profiles[i].client_credits||0)+d.assigned;'
			. '              break;'
			. '            }'
			. '          }'
			. '          window.aviEmbedAgencyProfiles=profiles;'
			. '          _agRenderList(_agSearch?_agSearch.value:"");'
			. '          window.aviEmbedAgencyCredits.available=d.pool_available;'
			. '          var poolVal=document.querySelector(".avi-agency-credits-val");'
			. '          if(poolVal)poolVal.textContent=d.pool_available;'
			. '          _agRefreshPoolDisplay(d.pool_available);'
			. '          if(msgEl){'
			. '            msgEl.style.display="block";'
			. '            msgEl.style.color="#16a34a";'
			. '            msgEl.textContent="\\u2705 "+d.assigned+" credits assigned!";'
			. '          }'
			. '          _showEmbedToast("\\u2705 "+d.assigned+" credits assigned!");'
			. '          setTimeout(function(){'
			. '            if(_agAssignModal)_agAssignModal.style.display="none";'
			. '            if(msgEl)msgEl.style.display="none";'
			. '          },1500);'
			. '        }else{'
			. '          _showEmbedToast(d.message||"Error assigning credits",true);'
			. '          if(msgEl){'
			. '            msgEl.style.display="block";'
			. '            msgEl.style.color="#dc2626";'
			. '            msgEl.textContent=d.message||"Error";'
			. '          }'
			. '        }'
			. '      })'
			. '      .catch(function(){'
			. '        confirmBtn.disabled=false;'
			. '        _showEmbedToast("Network error",true);'
			. '      });'
			. '    });'
			. '  }'
			. '  function _agOpenAssignModal(btn){'
			. '    if(!window.aviEmbedAgencyCredits||!btn)return;'
			. '    _agEnsureAssignModal();'
			. '    _agAssignProfileId=parseInt(btn.getAttribute("data-assign-profile"),10)||0;'
			. '    console.log("[AVI-assign] target_profile_id=",_agAssignProfileId);'
			. '    var businessName="";'
			. '    try{businessName=decodeURIComponent(btn.getAttribute("data-assign-name")||"");}'
			. '    catch(_e){businessName=btn.getAttribute("data-assign-name")||"";}'
			. '    var clientCredits=parseInt(btn.getAttribute("data-assign-credits"),10)||0;'
			. '    var pool=window.aviEmbedAgencyCredits.available||0;'
			. '    var nameEl=document.getElementById("aviAssignClientName");'
			. '    if(nameEl)nameEl.textContent=businessName||"";'
			. '    var clientCrEl=document.getElementById("aviAssignClientCredits");'
			. '    if(clientCrEl){'
			. '      var cc=typeof clientCredits!=="undefined"?clientCredits:0;'
			. '      clientCrEl.innerHTML=(_t.client_balance||"Client balance")+": <strong>"+cc+"</strong> "+(_t.slider_credits||"credits");'
			. '    }'
			. '    _agRefreshPoolDisplay(pool);'
			. '    var qtyIn=document.getElementById("aviAssignQty");'
			. '    if(qtyIn)qtyIn.value="10";'
			. '    var msgEl=document.getElementById("aviAssignMsg");'
			. '    if(msgEl)msgEl.style.display="none";'
			. '    _agAssignModal.style.display="flex";'
			. '  }'
			. '  var _bulkSelected=[];'
			. '  function _updateBulkUI(){'
			. '    var _tBulk=_embedI18n[_embedLang]||_embedI18n.en;'
			. '    var countEl=document.getElementById("aviBulkCount");'
			. '    var btn=document.getElementById("aviBulkAssignBtn");'
			. '    var qtyEl=document.getElementById("aviBulkQty");'
			. '    var qty=qtyEl?(parseInt(qtyEl.value,10)||10):10;'
			. '    var n=_bulkSelected.length;'
			. '    var avail=(window.aviEmbedAgencyCredits&&window.aviEmbedAgencyCredits.available)||0;'
			. '    var need=qty*n;'
			. '    var insufficient=n>0&&need>avail;'
			. '    if(countEl)countEl.textContent=n+" selected";'
			. '    var existingAlert=document.getElementById("aviBulkAlert");'
			. '    if(insufficient){'
			. '      var missing=need-avail;'
			. '      if(!existingAlert){'
			. '        var bulkBar=document.getElementById("aviBulkBar");'
			. '        if(bulkBar){'
			. '          var alertDiv=document.createElement("div");'
			. '          alertDiv.id="aviBulkAlert";'
			. '          alertDiv.style.cssText="width:100%;padding:6px 10px;"'
			. '            +"background:#fef2f2;border:1px solid #fecaca;"'
			. '            +"border-radius:6px;font-size:11px;color:#dc2626;"'
			. '            +"display:flex;align-items:center;"'
			. '            +"justify-content:space-between;gap:8px;margin-top:4px;";'
			. '          bulkBar.appendChild(alertDiv);'
			. '          existingAlert=alertDiv;'
			. '        }'
			. '      }'
			. '      if(existingAlert){'
			. '        existingAlert.innerHTML="\\u26A0\\uFE0F "+(_t.cr_need||"Need")+" "+need'
			. '          +"cr \\u00B7 "+(_t.cr_available||"Available")'
			. '          +" "+avail+"cr \\u00B7 "+(_t.cr_missing||"Missing")+" "+missing+"cr"'
			. '          +"<button type=\\"button\\" "'
			. '          +"onclick=\\"window._agOpenCreditsHub()\\" "'
			. '          +"style=\\"background:#dc2626;color:#fff;border:none;"'
			. '          +"border-radius:4px;padding:3px 8px;font-size:10px;"'
			. '          +"cursor:pointer;white-space:nowrap;flex-shrink:0;\\">"'
			. '          +"\\uD83D\\uDCB3 Buy credits</button>";'
			. '      }'
			. '      if(btn)btn.disabled=true;'
			. '    }else{'
			. '      if(existingAlert)existingAlert.remove();'
			. '      if(btn){'
			. '        btn.disabled=n===0;'
			. '        btn.textContent=n>0'
			. '          ?"\\uD83D\\uDCB3 "+qty+"cr \\u00D7 "+n+" = "+need+"cr"'
			. '          :"\\uD83D\\uDCB3 "+(_tBulk.bulk_assign||"Assign to selected");'
			. '      }'
			. '    }'
			. '  }'
			. '  function _agRenderList(filter){'
			. '    _agList.innerHTML="";'
			. '    if(window.aviEmbedAgencyCredits){'
			. '      var bulkBar=document.createElement("div");'
			. '      bulkBar.className="avi-bulk-bar";'
			. '      bulkBar.id="aviBulkBar";'
			. '      bulkBar.innerHTML=\'<label class="avi-bulk-select-all">\''
			. '        +\'<input type="checkbox" id="aviBulkSelectAll"> \''
			. '        +(_t.select_all||"Select all")+\'</label>\''
			. '        +\'<span class="avi-bulk-count" id="aviBulkCount">0 selected</span>\''
			. '        +\'<div class="avi-bulk-qty-wrap">\''
			. '        +\'<input type="number" class="avi-bulk-qty-input" id="aviBulkQty" \''
			. '        +\'value="10" min="10" step="10">\''
			. '        +\'<span style="font-size:10px;color:#94a3b8">\''
			. '        +(_t.bulk_cr_each||"cr each")+\'</span></div>\''
			. '        +\'<button type="button" class="avi-bulk-assign-btn" id="aviBulkAssignBtn" disabled>\''
			. '        +"\\uD83D\\uDCB3 "+(_t.bulk_assign||"Assign to selected")'
			. '        +\'</button>\';'
			. '      _agList.appendChild(bulkBar);'
			. '    }'
			. '    var items=window.aviEmbedAgencyProfiles.filter(function(p){'
			. '      if(!filter)return true;'
			. '      var q=filter.toLowerCase();'
			. '      return p.business_name.toLowerCase().indexOf(q)>=0'
			. '        ||p.city.toLowerCase().indexOf(q)>=0'
			. '        ||(p.gbp_category&&p.gbp_category.toLowerCase().indexOf(q)>=0);'
			. '    });'
			. '    var _masterId=window.aviEmbedAgencyMasterId||window.aviEmbedProfileId;'
			. '    items=items.filter(function(p){return p.id!==_masterId;});'
			. '    var sortVal=_agSortSel?_agSortSel.value:"score_asc";'
			. '    items.sort(function(a,b){'
			. '      if(sortVal==="score_asc")return a.score-b.score;'
			. '      if(sortVal==="score_desc")return b.score-a.score;'
			. '      if(sortVal==="name")return a.business_name.localeCompare(b.business_name);'
			. '      if(sortVal==="kw")return b.kw_count-a.kw_count;'
			. '      if(sortVal==="activity"){'
			. '        return new Date(b.last_activity_at||0)-new Date(a.last_activity_at||0);'
			. '      }'
			. '      return 0;'
			. '    });'
			. '    var _masterLabel=window.aviEmbedWhiteLabel||"My Agency";'
			. '    var _masterMatch=!filter||_masterLabel.toLowerCase().indexOf(filter.toLowerCase())>=0;'
			. '    if(_masterMatch){'
			. '      var _masterBtn=document.createElement("button");'
			. '      _masterBtn.type="button";'
			. '      _masterBtn.className="avi-agency-item avi-agency-master-item"'
			. '        +(_agActiveProfileId===_masterId?" active":"");'
			. '      _masterBtn.innerHTML=\'<div class="avi-agency-item-avatar" style="background:#6d28d9">AG</div>\''
			. '        +\'<div class="avi-agency-item-info"><div class="avi-agency-item-name">\''
			. '        +_masterLabel.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")'
			. '        +\'</div><div class="avi-agency-item-meta">\''
			. '        +\'<span class="avi-ag-badge" style="background:#ede9fe;color:#6d28d9">\\uD83C\\uDFE2 Agency profile</span></div></div>\';'
			. '      _masterBtn.addEventListener("click",function(){'
			. '        if(window.aviEmbedProfileId===_masterId){_agClose();return;}'
			. '        _agActiveProfileId=_masterId;'
			. '        _agRenderList(_agSearch?_agSearch.value:"");'
			. '        var _nameSpanEl=document.getElementById("aviEmbedClientName");'
			. '        if(_nameSpanEl){_nameSpanEl.textContent=_t.loading;}'
			. '        fetch(window.aviEmbedSwitchUrl,{'
			. '          method:"POST",'
			. '          headers:{"Content-Type":"application/json",'
			. '            "X-Embed-Token":window.aviEmbedToken},'
			. '          body:JSON.stringify({'
			. '            key_id:window.aviEmbedKeyId,'
			. '            profile_id:_masterId,'
			. '            current_profile_id:window.aviEmbedProfileId,'
			. '            lang:_embedLang,'
			. '            theme:window.aviEmbedTheme||"light"'
			. '          })'
			. '        }).then(function(r){return r.json();})'
			. '        .then(function(data){'
			. '          if(data.url)window.location.replace(data.url);'
			. '          else alert(data.message||_t.err_generic);'
			. '        })'
			. '        .catch(function(){alert(_t.err_network);});'
			. '      });'
			. '      _agList.appendChild(_masterBtn);'
			. '    }'
			. '    items.forEach(function(p){'
			. '      var item=document.createElement("button");'
			. '      item.type="button";item.className="avi-agency-item";'
			. '      if(p.id===_agActiveProfileId)item.classList.add("active");'
			. '      if(p.score<=45)item.classList.add("avi-agency-urgency-high");'
			. '      else if(p.score<=60)item.classList.add("avi-agency-urgency-med");'
			. '      var tier=_agScoreTier(p.score);'
			. '      var initials=p.business_name.split(" ").slice(0,2)'
			. '        .map(function(w){return w[0]||"";}).join("").toUpperCase();'
			. '      var avatarBg=p.score<=45?"#dc2626":p.score<=60?"#ea580c"'
			. '        :p.score<=75?"#ca8a04":p.score<=90?"#16a34a":"#b45309";'
			. '      var avatar=document.createElement("div");'
			. '      avatar.className="avi-agency-item-avatar";'
			. '      avatar.style.background=avatarBg;'
			. '      avatar.textContent=initials||"?";'
			. '      var info=document.createElement("div");'
			. '      info.className="avi-agency-item-info";'
			. '      var name=document.createElement("div");'
			. '      name.className="avi-agency-item-name";'
			. '      name.textContent=p.business_name;'
			. '      var lines=document.createElement("div");'
			. '      lines.className="avi-agency-item-lines";'
			. '      var line1=document.createElement("div");'
			. '      line1.className="avi-agency-item-line";'
			. '      var l1s1=document.createElement("span");'
			. '      l1s1.className="avi-ag-badge "+tier.cls;'
			. '      l1s1.textContent=tier.label+"/100";'
			. '      line1.appendChild(l1s1);'
			. '      var l1d1=document.createElement("span");l1d1.textContent="\\u00B7";'
			. '      line1.appendChild(l1d1);'
			. '      var l1s2=document.createElement("span");'
			. '      l1s2.textContent=p.city||"\\u2014";'
			. '      line1.appendChild(l1s2);'
			. '      var l1d2=document.createElement("span");l1d2.textContent="\\u00B7";'
			. '      line1.appendChild(l1d2);'
			. '      var l1s4=document.createElement("span");'
			. '      l1s4.textContent="\\uD83D\\uDD11 "+(p.kw_count||0)+_t.kw_badge;'
			. '      line1.appendChild(l1s4);'
			. '      var line2=document.createElement("div");'
			. '      line2.className="avi-agency-item-line";'
			. '      var l2s1=document.createElement("span");'
			. '      l2s1.textContent="\\uD83D\\uDCB3 "+(typeof p.client_credits!=="undefined"?p.client_credits:0)+" cr";'
			. '      line2.appendChild(l2s1);'
			. '      var l2d1=document.createElement("span");l2d1.textContent="\\u00B7";'
			. '      line2.appendChild(l2d1);'
			. '      var l2s2=document.createElement("span");'
			. '      l2s2.textContent=p.average_rating'
			. '        ?"\\u2B50 "+parseFloat(p.average_rating).toFixed(1)+" ("+(p.review_count||0)+")"'
			. '        :"\\u2014";'
			. '      line2.appendChild(l2s2);'
			. '      var l2d2=document.createElement("span");l2d2.textContent="\\u00B7";'
			. '      line2.appendChild(l2d2);'
			. '      if(p.google_place_id){'
			. '        var gbpL=document.createElement("a");'
			. '        gbpL.href="https://www.google.com/maps/search/?api=1&query=Google&query_place_id="+encodeURIComponent(p.google_place_id);'
			. '        gbpL.target="_blank";gbpL.rel="noopener";'
			. '        gbpL.style.cssText="font-size:11px;color:#4285f4;text-decoration:none;";'
			. '        gbpL.textContent="\\uD83D\\uDCCD GBP";'
			. '        gbpL.addEventListener("click",function(e){e.stopPropagation();});'
			. '        line2.appendChild(gbpL);'
			. '      }else{'
			. '        var l2s3=document.createElement("span");l2s3.textContent="\\u2014";'
			. '        line2.appendChild(l2s3);'
			. '      }'
			. '      var line3=document.createElement("div");'
			. '      line3.className="avi-agency-item-line";'
			. '      var catSpan=document.createElement("span");'
			. '      catSpan.className="avi-ag-cat-trunc";'
			. '      var _cat=p.gbp_category||"";'
			. '      if(_cat){catSpan.title=_cat;catSpan.textContent="\\uD83D\\uDCC2 "+_cat;}'
			. '      else{catSpan.textContent="\\u2014";}'
			. '      line3.appendChild(catSpan);'
			. '      var l3Right=document.createElement("span");'
			. '      l3Right.className="avi-ag-line3-right";'
			. '      var _actLabel=p.last_activity_at?_agRelDate(p.last_activity_at):"\\u2014";'
			. '      var _scansLabel=(p.heatmap_scan_count||0)+_t.scan_badge;'
			. '      l3Right.textContent="\\u00B7 \\uD83D\\uDD50 "+_actLabel'
			. '        +" \\u00B7 \\uD83D\\uDDFA\\uFE0F "+_scansLabel;'
			. '      line3.appendChild(l3Right);'
			. '      lines.appendChild(line1);lines.appendChild(line2);lines.appendChild(line3);'
			. '      info.appendChild(name);info.appendChild(lines);'
			. '      if(window.aviEmbedAgencyCredits){'
			. '        var clientCb=document.createElement("input");'
			. '        clientCb.type="checkbox";'
			. '        clientCb.className="avi-client-checkbox";'
			. '        clientCb.setAttribute("data-client-id",String(p.id));'
			. '        clientCb.style.marginRight="4px";'
			. '        if(_bulkSelected.indexOf(p.id)!==-1)clientCb.checked=true;'
			. '        clientCb.addEventListener("click",function(e){e.stopPropagation();});'
			. '        item.appendChild(clientCb);'
			. '      }'
			. '      item.appendChild(avatar);item.appendChild(info);'
			. '      item.addEventListener("click",function(){'
			. '        if(p.id===window.aviEmbedProfileId){_agClose();return;}'
			. '        _agActiveProfileId=p.id;'
			. '        _agRenderList(_agSearch?_agSearch.value:"");'
			. '        _agUpdateGbpBadge(p);'
			. '        var _nameSpanEl=document.getElementById("aviEmbedClientName");'
			. '        if(_nameSpanEl){'
			. '          _nameSpanEl.textContent="📍 "+p.business_name+(p.city?" · "+p.city:"");'
			. '        }'
			. '        name.textContent=_t.loading;'
			. '        fetch(window.aviEmbedSwitchUrl,{'
			. '          method:"POST",'
			. '          headers:{"Content-Type":"application/json",'
			. '            "X-Embed-Token":window.aviEmbedToken},'
			. '          body:JSON.stringify({'
			. '            key_id:window.aviEmbedKeyId,'
			. '            profile_id:p.id,'
			. '            current_profile_id:window.aviEmbedProfileId,'
			. '            lang:_embedLang,'
			. '            theme:window.aviEmbedTheme||"light"'
			. '          })'
			. '        }).then(function(r){return r.json();})'
			. '        .then(function(data){'
			. '          if(data.url)window.location.replace(data.url);'
			. '          else{name.textContent=p.business_name;alert(data.message||_t.err_generic);}'
			. '        })'
			. '        .catch(function(){'
			. '          name.textContent=p.business_name;'
			. '          alert(_t.err_network);'
			. '        });'
			. '      });'
			. '      var rowWrap=document.createElement("div");'
			. '      rowWrap.className="avi-agency-item-wrap";'
			. '      rowWrap.appendChild(item);'
			. '      if(window.aviEmbedAgencyCredits){'
			. '        var assignBtn=document.createElement("button");'
			. '        assignBtn.type="button";'
			. '        assignBtn.className="avi-ag-assign-btn";'
			. '        assignBtn.setAttribute("data-assign-profile",String(p.id));'
			. '        assignBtn.setAttribute("data-assign-name",encodeURIComponent(p.business_name||""));'
			. '        assignBtn.setAttribute("data-assign-credits",String(typeof p.client_credits!=="undefined"?p.client_credits:0));'
			. '        assignBtn.textContent=_t.assign_credits||"+";'
			. '        assignBtn.addEventListener("click",function(e){'
			. '          e.stopPropagation();'
			. '          _agOpenAssignModal(assignBtn);'
			. '        });'
			. '        rowWrap.appendChild(assignBtn);'
			. '      }'
			. '      _agList.appendChild(rowWrap);'
			. '    });'
			. '    if(items.length===0){'
			. '      var empty=document.createElement("div");'
			. '      empty.style.cssText="color:#94a3b8;font-size:13px;padding:24px;text-align:center;";'
			. '      empty.textContent=_t.no_client;'
			. '      _agList.appendChild(empty);'
			. '    }'
			. '    if(window.aviEmbedAgencyCredits){'
			. '      var _selectAllCb=document.getElementById("aviBulkSelectAll");'
			. '      if(_selectAllCb){'
			. '        _selectAllCb.addEventListener("change",function(){'
			. '          var checked=this.checked;'
			. '          _bulkSelected=[];'
			. '          document.querySelectorAll(".avi-client-checkbox").forEach(function(cb){'
			. '            cb.checked=checked;'
			. '            if(checked)_bulkSelected.push(parseInt(cb.getAttribute("data-client-id"),10));'
			. '          });'
			. '          _updateBulkUI();'
			. '        });'
			. '      }'
			. '      document.querySelectorAll(".avi-client-checkbox").forEach(function(cb){'
			. '        cb.addEventListener("change",function(e){'
			. '          e.stopPropagation();'
			. '          var cid=parseInt(this.getAttribute("data-client-id"),10);'
			. '          if(this.checked){'
			. '            if(_bulkSelected.indexOf(cid)===-1)_bulkSelected.push(cid);'
			. '          }else{'
			. '            _bulkSelected=_bulkSelected.filter(function(id){return id!==cid;});'
			. '          }'
			. '          _updateBulkUI();'
			. '        });'
			. '      });'
			. '      var _bulkQtyEl=document.getElementById("aviBulkQty");'
			. '      if(_bulkQtyEl)_bulkQtyEl.addEventListener("input",_updateBulkUI);'
			. '      var _bulkBtn=document.getElementById("aviBulkAssignBtn");'
			. '      if(_bulkBtn){'
			. '        _bulkBtn.addEventListener("click",function(){'
			. '          var _tBulk=_embedI18n[_embedLang]||_embedI18n.en;'
			. '          var btn=this;'
			. '          var qty=parseInt(document.getElementById("aviBulkQty").value,10)||10;'
			. '          if(qty<10||qty%10!==0){'
			. '            _showEmbedToast(_tBulk.assign_min_hint||"Min 10cr, multiples of 10",true);'
			. '            return;'
			. '          }'
			. '          if(_bulkSelected.length===0)return;'
			. '          btn.disabled=true;'
			. '          btn.textContent="\\u23F3 "+(_tBulk.bulk_assigning||"Assigning...");'
			. '          fetch(window.location.origin+"/wp-json/avision/v1/embed/assign-credits-bulk",{'
			. '            method:"POST",'
			. '            headers:{'
			. '              "Content-Type":"application/json",'
			. '              "X-Embed-Token":window.aviEmbedToken||""'
			. '            },'
			. '            body:JSON.stringify({'
			. '              key_id:window.aviEmbedKeyId,'
			. '              profile_id:window.aviEmbedProfileId,'
			. '              target_profile_ids:_bulkSelected,'
			. '              qty:qty'
			. '            })'
			. '          })'
			. '          .then(function(r){return r.json();})'
			. '          .then(function(d){'
			. '            if(d.success||d.assigned_count>0){'
			. '              (d.results||[]).forEach(function(res){'
			. '                if(res.success){'
			. '                  var profs=window.aviEmbedAgencyProfiles||[];'
			. '                  for(var i=0;i<profs.length;i++){'
			. '                    if(profs[i].id===res.profile_id){'
			. '                      profs[i].client_credits=(profs[i].client_credits||0)+qty;'
			. '                      break;'
			. '                    }'
			. '                  }'
			. '                }'
			. '              });'
			. '              window.aviEmbedAgencyCredits.available=d.pool_available;'
			. '              _agRefreshPoolDisplay(d.pool_available);'
			. '              _bulkSelected=[];'
			. '              _agRenderList(_agSearch?_agSearch.value:"");'
			. '              _showEmbedToast("\\u2705 "+d.assigned_count+" "+(_tBulk.bulk_assigned||"clients credited!"));'
			. '            }else{'
			. '              if(d.message&&d.message.indexOf("Insufficient")!==-1){'
			. '                var need=parseInt(_bulkSelected.length,10)*qty;'
			. '                var avail=window.aviEmbedAgencyCredits.available||0;'
			. '                var missing=need-avail;'
			. '                var toastMsg="\\u26A0\\uFE0F Not enough credits. Need "'
			. '                  +need+"cr, available "+avail+"cr. "'
			. '                  +"Missing: "+missing+"cr. ";'
			. '                _showEmbedToast(toastMsg,true,function(){'
			. '                  _agOpenCreditsHub();'
			. '                });'
			. '                var bulkBar=document.getElementById("aviBulkBar");'
			. '                var existingAlert=document.getElementById("aviBulkAlert");'
			. '                if(existingAlert)existingAlert.remove();'
			. '                if(bulkBar){'
			. '                  var alertEl=document.createElement("div");'
			. '                  alertEl.id="aviBulkAlert";'
			. '                  alertEl.style.cssText="width:100%;padding:8px 10px;"'
			. '                    +"background:#fef2f2;border:1px solid #fecaca;"'
			. '                    +"border-radius:6px;font-size:11px;color:#dc2626;"'
			. '                    +"display:flex;align-items:center;justify-content:space-between;gap:8px;";'
			. '                  alertEl.innerHTML="\\u26A0\\uFE0F "+(_t.cr_need||"Need")+" "+need'
			. '                    +"cr \\u00B7 "+(_t.cr_available||"Available")'
			. '                    +" "+avail+"cr \\u00B7 "+(_t.cr_missing||"Missing")+" "+missing+"cr"'
			. '                    +"<button type=\\"button\\" onclick=\\"window._agOpenCreditsHub()\\" "'
			. '                    +"style=\\"background:#dc2626;color:#fff;border:none;border-radius:4px;"'
			. '                    +"padding:4px 10px;font-size:11px;cursor:pointer;white-space:nowrap;\\">"'
			. '                    +"\\uD83D\\uDCB3 Buy pool credits</button>";'
			. '                  bulkBar.appendChild(alertEl);'
			. '                  setTimeout(function(){alertEl.remove();},8000);'
			. '                }'
			. '              }else{'
			. '                _showEmbedToast(d.message||"Error",true);'
			. '              }'
			. '              btn.disabled=false;'
			. '              btn.textContent="\\uD83D\\uDCB3 "+(_tBulk.bulk_assign||"Assign to selected");'
			. '            }'
			. '          })'
			. '          .catch(function(){'
			. '            btn.disabled=false;'
			. '            btn.textContent="\\uD83D\\uDCB3 "+(_tBulk.bulk_assign||"Assign to selected");'
			. '            _showEmbedToast("Network error",true);'
			. '          });'
			. '        });'
			. '      }'
			. '      _updateBulkUI();'
			. '    }'
			. '  }'
			. '  window._agRenderList=_agRenderList;'
			. '  _agRenderList("");'
			. '  _agSearch.addEventListener("input",function(){_agRenderList(this.value);});'
			. '  function _agOpen(){'
			. '    _agPanel.classList.add("open");'
			. '    _agOverlay.classList.add("open");'
			. '    _agSearch.focus();'
			. '  }'
			. '  function _agClose(){'
			. '    _agPanel.classList.remove("open");'
			. '    _agOverlay.classList.remove("open");'
			. '  }'
			. '  function _agOpenCreditsHub(){'
			. '    _agClose();'
			. '    _switchEmbedTab("agency_hub");'
			. '  }'
			. '  window._agOpenCreditsHub=_agOpenCreditsHub;'
			. '  _agCloseBtn.addEventListener("click",_agClose);'
			. '  _agOverlay.addEventListener("click",_agClose);'
			. '  _agTrigger=document.createElement("button");'
			. '  _agTrigger.type="button";_agTrigger.className="avi-agency-trigger";'
			. '  _agTrigger.setAttribute("data-avi-ag-trigger","1");'
			. '  _agTrigger.textContent=_t.clients_trigger;'
			. '  _agTrigger.addEventListener("click",_agOpen);'
			. '  if(_nav)_nav.insertBefore(_agTrigger,_nav.firstChild);'
			. '  /* Badge GBP permanent — après volet agence complet */'
			. '  _gbpBadge=document.createElement("a");'
			. '  _gbpBadge.id="aviEmbedGbpBadge";'
			. '  _gbpBadge.target="_blank";_gbpBadge.rel="noopener";'
			. '  _gbpBadge.style.cssText="background:rgba(255,255,255,0.15);border-radius:4px;'
			. '    color:#fff;font-size:10px;font-weight:600;padding:3px 10px;text-decoration:none;'
			. '    white-space:nowrap;border:1px solid rgba(255,255,255,0.2);'
			. '    transition:background .15s;display:inline-flex;align-items:center;gap:4px;'
			. '    flex-shrink:0;";'
			. '  _gbpBadge.textContent=_t.gbp_badge;'
			. '  function _agUpdateGbpBadge(profile){'
			. '    if(!profile){return;}'
			. '    var _href=_resolveGbpDashboardHref('
			. '      profile.google_place_id,profile.google_location_name);'
			. '    _gbpBadge.href=_href;'
			. '    _gbpBadge.title=_t.gbp_open_title+(profile.business_name||"");'
			. '    _gbpBadge.style.opacity=(_href.indexOf("place_id=")>-1'
			. '      ||_href.indexOf("/maps/search/")>-1)?"1":"0.6";'
			. '  }'
			. '  var _agHdr=document.querySelector(".avi-heatmap-closed");'
			. '  if(_agHdr){'
			. '    var _agMeta=_agHdr.querySelector(".avi-heatmap-closed-meta");'
			. '    _agActiveName=document.createElement("span");'
			. '    _agActiveName.id="aviEmbedClientName";'
			. '    _agActiveName.className="avi-hm-profile-badge";'
			. '    _agActiveName.setAttribute("data-avi-profile-badge","");'
			. '    _agActiveName.style.cssText="color:rgba(255,255,255,0.92);font-weight:600;'
			. '      background:rgba(124,58,237,0.35);flex:1;text-align:center;min-width:0;";'
			. '    if(_agMeta){'
			. '      _agMeta.insertBefore(_gbpBadge,_agMeta.firstChild);'
			. '    }'
			. '    if(_agMeta){'
			. '      _agHdr.insertBefore(_agActiveName,_agMeta);'
			. '    }else{'
			. '      _agHdr.appendChild(_agActiveName);'
			. '    }'
			. '    var _agActiveProfile=window.aviEmbedAgencyProfiles.find(function(p){'
			. '      return p.id===window.aviEmbedProfileId;'
			. '    });'
			. '    if(_agActiveProfile){'
			. '      _agActiveName.textContent="📍 "+_agActiveProfile.business_name'
			. '        +(_agActiveProfile.city?" · "+_agActiveProfile.city:"");'
			. '      _agUpdateGbpBadge(_agActiveProfile);'
			. '    }else{'
			. '      _agUpdateGbpBadge({'
			. '        google_place_id:window.aviEmbedSoloPlaceId||"",'
			. '        google_location_name:(window.aviEmbedScoreData'
			. '          &&window.aviEmbedScoreData.google_location_name)||"",'
			. '        business_name:(window.aviEmbedScoreData'
			. '          &&window.aviEmbedScoreData.business_name)||""'
			. '      });'
			. '    }'
			. '  }'
			. '}'
			. '}'
			. 'if(window.aviEmbedKeyType!=="agency"){'
			. '  var _homeBtn=_navBtns["home"];'
			. '  if(_homeBtn&&_homeBtn.parentNode){'
			. '    var _solSubWrap=document.createElement("div");'
			. '    _solSubWrap.className="avi-submenu-wrap";'
			. '    _homeBtn.parentNode.insertBefore('
			. '      _solSubWrap,_homeBtn'
			. '    );'
			. '    _solSubWrap.appendChild(_homeBtn);'
			. '    var _solArrow=document.createElement("button");'
			. '    _solArrow.type="button";'
			. '    _solArrow.className="avi-submenu-arrow";'
			. '    _solArrow.textContent="\\u25be";'
			. '    _solArrow.title=_t.profile_title||"My Profile";'
			. '    _solSubWrap.appendChild(_solArrow);'
			. '    var _solDrop=document.createElement("div");'
			. '    _solDrop.className="avi-submenu-drop";'
			. '    document.body.appendChild(_solDrop);'
			. '    var _solDropOpen=false;'
			. '    var _solProfileLabel="\\uD83D\\uDC64 My Profile";'
			. '    try{'
			. '      var _ni=_embedNavI18n[_embedLang]'
			. '        ||_embedNavI18n["en"]||{};'
			. '      if(_ni["profile_solo"]){'
			. '        _solProfileLabel=_ni["profile_solo"];'
			. '      }'
			. '    }catch(e){}'
			. '    var _solOpts=[["profile_solo",_solProfileLabel]];'
			. '    _solOpts.forEach(function(o){'
			. '      var opt=document.createElement("button");'
			. '      opt.type="button";'
			. '      opt.className="avi-submenu-opt";'
			. '      opt.setAttribute("data-submenu-tab",o[0]);'
			. '      opt.textContent=o[1];'
			. '      opt.addEventListener("click",function(){'
			. '        _solDrop.classList.remove("open");'
			. '        _solDropOpen=false;'
			. '        _solDrop.style.display="none";'
			. '        _switchEmbedTab(o[0]);'
			. '      });'
			. '      _solDrop.appendChild(opt);'
			. '    });'
			. '    _solArrow.addEventListener("click",function(e){'
			. '      e.stopPropagation();'
			. '      _solDropOpen=!_solDropOpen;'
			. '      if(_solDropOpen){'
			. '        var r=_solArrow.getBoundingClientRect();'
			. '        _solDrop.style.cssText='
			. '          "position:fixed;top:"+(r.bottom+4)+"px;'
			. '          left:"+r.left+"px;background:#fff;'
			. '          border:1px solid #e2e8f0;border-radius:8px;'
			. '          box-shadow:0 4px 16px rgba(0,0,0,.12);'
			. '          z-index:99999;min-width:160px;display:block;";'
			. '        _solDrop.classList.add("open");'
			. '      }else{'
			. '        _solDrop.classList.remove("open");'
			. '        _solDrop.style.display="none";'
			. '      }'
			. '    });'
			. '    document.addEventListener("click",function(){'
			. '      if(_solDropOpen){'
			. '        _solDrop.classList.remove("open");'
			. '        _solDrop.style.display="none";'
			. '        _solDropOpen=false;'
			. '      }'
			. '    });'
			. '  }'
			. '}'
			. 'if(window.aviEmbedKeyType!=="agency"){'
			. '  var _soloHdr=document.querySelector(".avi-heatmap-closed");'
			. '  if(_soloHdr){'
			. '    var _soloBadge=document.createElement("a");'
			. '    _soloBadge.target="_blank";_soloBadge.rel="noopener";'
			. '    _soloBadge.style.cssText="background:rgba(255,255,255,0.15);'
			. '      border-radius:4px;color:#fff;font-size:10px;font-weight:600;'
			. '      margin-left:8px;padding:3px 10px;text-decoration:none;'
			. '      white-space:nowrap;border:1px solid rgba(255,255,255,0.2);'
			. '      display:inline-flex;align-items:center;gap:4px;";'
			. '    _soloBadge.textContent=_t.gbp_badge;'
			. '    var _soloGbpHref=_resolveGbpDashboardHref('
			. '      window.aviEmbedSoloPlaceId,'
			. '      window.aviEmbedSoloLocationName'
			. '      ||(window.aviEmbedScoreData&&window.aviEmbedScoreData.google_location_name)||""'
			. '    );'
			. '    _soloBadge.href=_soloGbpHref;'
			. '    _soloBadge.style.opacity=(_soloGbpHref.indexOf("place_id=")>-1'
			. '      ||_soloGbpHref.indexOf("/maps/search/")>-1)?"1":"0.6";'
			. '    var _soloMeta=_soloHdr.querySelector(".avi-heatmap-closed-meta");'
			. '    if(_soloMeta)_soloMeta.appendChild(_soloBadge);'
			. '    else _soloHdr.appendChild(_soloBadge);'
			. 'var _soloLangSel=document.createElement("div");'
			. '_soloLangSel.style.cssText="display:inline-flex;align-items:center;gap:4px;margin-left:8px;position:relative;pointer-events:auto !important;z-index:100;";'
			. 'var _soloLangCodes=["en","fr","es","pt","tr","de"];'
			. 'var _soloLangLabels={"en":"\uD83C\uDF10 EN","fr":"\uD83C\uDF10 FR","es":"\uD83C\uDF10 ES","pt":"\uD83C\uDF10 PT","tr":"\uD83C\uDF10 TR","de":"\uD83C\uDF10 DE"};'
			. 'var _soloLangBtn=document.createElement("button");'
			. '_soloLangBtn.type="button";'
			. '_soloLangBtn.style.cssText="background:rgba(255,255,255,0.1);border:1px solid rgba(255,255,255,0.2);border-radius:5px;color:#fff;cursor:pointer;font-size:11px;font-weight:600;padding:3px 8px;display:flex;align-items:center;gap:3px;transition:background .15s;";'
			. '_soloLangBtn.textContent=(_soloLangLabels[_embedLang]||"\uD83C\uDF10 EN");'
			. 'var _soloLangDrop=document.createElement("div");'
			. '_soloLangDrop.style.cssText="position:fixed;background:#1e293b;border:1px solid rgba(255,255,255,0.15);border-radius:6px;box-shadow:0 4px 12px rgba(0,0,0,.4);min-width:80px;overflow:hidden;z-index:2147483647;display:none;";'
			. '_soloLangBtn.addEventListener("click",function(e){'
			. 'e.stopPropagation();e.preventDefault();'
			. 'if(_soloLangDrop.style.display==="block"){_soloLangDrop.style.display="none";return;}'
			. 'var _r=_soloLangBtn.getBoundingClientRect();'
			. '_soloLangDrop.style.top=(_r.bottom+4)+"px";'
			. '_soloLangDrop.style.right=(window.innerWidth-_r.right)+"px";'
			. '_soloLangDrop.style.display="block";'
			. '});'
			. '_soloLangCodes.forEach(function(lc){'
			. 'var _soloOpt=document.createElement("button");'
			. '_soloOpt.type="button";'
			. '_soloOpt.style.cssText="width:100%;text-align:left;background:none;border:none;color:rgba(255,255,255,0.8);cursor:pointer;font-size:12px;padding:7px 12px;display:block;";'
			. '_soloOpt.textContent=(_soloLangLabels[lc]||lc.toUpperCase());'
			. '_soloOpt.addEventListener("click",function(){'
			. 'var _url=new URL(window.location.href);'
			. '_url.searchParams.set("lang",lc);'
			. 'window.location.href=_url.toString();'
			. '});'
			. '_soloOpt.addEventListener("mouseover",function(){_soloOpt.style.background="rgba(255,255,255,0.08)";});'
			. '_soloOpt.addEventListener("mouseout",function(){_soloOpt.style.background="none";});'
			. '_soloLangDrop.appendChild(_soloOpt);'
			. '});'
			. '_soloLangSel.addEventListener("click",function(e){e.stopPropagation();});'
			. 'document.addEventListener("click",function(){_soloLangDrop.style.display="none";});'
			. '_soloLangSel.appendChild(_soloLangBtn);'
			. 'document.body.appendChild(_soloLangDrop);'
			. 'if(_soloMeta)_soloMeta.appendChild(_soloLangSel);'
			. '  }'
			. '}'
			. 'function _initHeatmapAddKwBtn(){'
			. 'var _tKw=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _hmKwPanel=document.querySelector(".avi-heatmap-panel--keywords");'
			. 'if(!_hmKwPanel)return;'
			. 'var _addKwBtn=_hmKwPanel.querySelector(".avi-add-kw-btn");'
			. 'if(!_addKwBtn){'
			. '_addKwBtn=document.createElement("button");'
			. '_addKwBtn.type="button";'
			. '_addKwBtn.className="avi-add-kw-btn";'
			. '_addKwBtn.addEventListener("click",function(){_switchEmbedTab("keywords");});'
			. 'var _anchor=_hmKwPanel.querySelector(\'[data-avi-heatmap-kw-controls="drawer"]\')'
			. '||_hmKwPanel.querySelector(".avi-heatmap-keyword-list")'
			. '||_hmKwPanel.querySelector(".avi-heatmap-empty");'
			. 'if(_anchor){_anchor.parentNode.insertBefore(_addKwBtn,_anchor);}'
			. 'else{'
			. 'var _hmHead=_hmKwPanel.querySelector(".avi-heatmap-panel-head");'
			. 'if(_hmHead&&_hmHead.nextSibling){_hmKwPanel.insertBefore(_addKwBtn,_hmHead.nextSibling);}'
			. 'else{_hmKwPanel.appendChild(_addKwBtn);}'
			. '}'
			. '}'
			. '_addKwBtn.textContent=_tKw.add_keyword||"+ Add keyword";'
			. '}'
			. 'function _renderHomeDashboard(){'
			. 'if(!_homePanel)return;'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var score=sd.score||0;'
			. 'if(window._aviGuardianAlerts){'
			. 'var _gPenaltyMap={title:0,phoneNumbers:4,categories:1,regularHours:3,websiteUri:5,openInfo:0,storefrontAddress:1,description:2,specialHours:1,serviceArea:1};'
			. 'var _gPenalty=0;'
			. 'window._aviGuardianAlerts.forEach(function(a){'
			. 'if(parseInt(a.is_read)===0&&_gPenaltyMap.hasOwnProperty(a.alert_type)){'
			. '_gPenalty+=_gPenaltyMap[a.alert_type];'
			. '}'
			. '});'
			. 'score=Math.max(0,score-_gPenalty);'
			. '}'
			. 'var _homeDelta=0;'
			. 'var _hdPostOk=!!sd.has_recent_post;'
			. 'var _hdPostCount=sd.posts_count||0;'
			. 'var _hdPostDays=sd.last_post_at?Math.round((Date.now()-new Date(sd.last_post_at))/(1000*86400)):-1;'
			. 'var _hdPostStale=_hdPostCount>0&&_hdPostDays>7;'
			. 'var _hdPhotoOk=!!sd.has_photos;'
			. 'var _hdPhotoCount=sd.photos_published||0;'
			. 'var _hdPhotoDays=sd.last_photo_at?Math.round((Date.now()-new Date(sd.last_photo_at))/(1000*86400)):-1;'
			. 'var _hdPhotoStale=_hdPhotoCount>0&&_hdPhotoDays>7;'
			. 'var _hdRvData=window.aviEmbedReviewsData||{};'
			. 'var _hdRvList=_hdRvData.reviews||[];'
			. 'var _hdLastRv=_hdRvList.length>0?_hdRvList[0]:null;'
			. 'var _hdRvOk=_hdLastRv&&!!_hdLastRv.has_reply;'
			. 'if(!_hdPostOk||_hdPostStale)_homeDelta-=5;'
			. 'if(!_hdPhotoOk||_hdPhotoStale)_homeDelta-=5;'
			. 'if(!_hdRvOk)_homeDelta-=3;'
			. 'if(!sd.has_website)_homeDelta-=5;'
			. 'if(!sd.has_phone)_homeDelta-=4;'
			. 'if(!sd.has_hours)_homeDelta-=3;'
			. 'if(!sd.has_description)_homeDelta-=2;'
			. 'if(window._aviGuardianAlerts){'
			. 'var _hdGMap={title:0,phoneNumbers:4,categories:1,regularHours:3,websiteUri:5,openInfo:0,storefrontAddress:1,description:2,specialHours:1,serviceArea:1};'
			. 'var _hdAlreadyCounted={websiteUri:!sd.has_website,phoneNumbers:!sd.has_phone,regularHours:!sd.has_hours,description:!sd.has_description};'
			. 'window._aviGuardianAlerts.forEach(function(a){'
			. 'if(parseInt(a.is_read)===0&&_hdGMap[a.alert_type]>0&&!_hdAlreadyCounted[a.alert_type]){'
			. '_homeDelta-=_hdGMap[a.alert_type];'
			. '}'
			. '});'
			. '}'
			. 'var unanswered=window.aviEmbedUnansweredCount||0;'
			. 'var schedules=window._aviActiveSchedules||[];'
			. 'var nextScan=_t.no_scan;'
			. 'if(schedules.length>0&&schedules[0].next_run_at){'
			. 'var d=new Date(schedules[0].next_run_at);'
			. 'nextScan=d.toLocaleDateString('
			. '_embedLang==="fr"?"fr-FR":'
			. '_embedLang==="es"?"es-ES":'
			. '_embedLang==="pt-br"?"pt-BR":'
			. '_embedLang==="de"?"de-DE":'
			. '_embedLang==="tr"?"tr-TR":"en-US",'
			. '{day:"2-digit",month:"short"});'
			. '}'
			. 'var _hv=sd.verification_state||"unverified";'
			. 'var _hvl=_hv==="verified"?(_t.verified||"")'
			. ':_hv==="pending"?(_t.pending_verification||"")'
			. ':(_t.not_verified||"");'
			. 'var _homeVerifBadge=\'<span class="avi-verified-badge avi-verified-badge--\'+_hv+\'">\'+_hvl+\'</span>\';'
			. 'var _bannerDismissed=false;'
			. 'try{_bannerDismissed=localStorage.getItem("avi_home_banner_dismissed")==="1";}catch(e){}'
			. 'var _bannerHtml="";'
			. 'if(!_bannerDismissed){'
			. '_bannerHtml=\'<div class="avi-edu-banner" id="aviEduBanner">\''
			. '+\'<button type="button" class="avi-edu-banner-close" id="aviEduBannerClose">\\u00d7</button>\''
			. '+\'<div class="avi-edu-banner-title">\'+(_t.edu_banner_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-banner-body">\'+(_t.edu_banner_body||"")+\'</div>\''
			. '+\'<button type="button" class="avi-edu-banner-btn" id="aviEduBannerOpen">\''
			. '+\'\\uD83D\\uDCA1 \'+(_t.edu_learn_more||"")+\'</button>\''
			. '+\'</div>\';'
			. '}'
			. '_homePanel.innerHTML='
			. '"<div class=\\"avi-ehd-title\\"><span class=\\"avi-hm-step-badge\\">2</span>"+(_t.control_center||"Control Center")'
			. '+"<button type=\\"button\\" class=\\"avi-ehd-info-btn\\" data-info=\\"cc\\" style=\\"margin-left:4px;\\">\\u2139\\uFE0F</button>"'
			. '+"<span class=\\"avi-guardian-badge\\" data-guardian-info=\\"home\\">\\uD83D\\uDEE1\\uFE0F "+(_t.guardian_home_title||"Guardian")+" <span class=\\"avi-guardian-dot avi-guardian-loading\\" style=\\"background:#9ca3af;width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0;animation:none\\"></span><span class=\\"avi-guardian-badge-status\\" style=\\"color:#9ca3af\\">"+(_t.guardian_checking||"...")+"</span><button type=\\"button\\" class=\\"avi-guardian-badge-info\\">\\u2139\\uFE0F</button></span>"'
			. '+"</div>"'
			. '+_bannerHtml'
			. '+"<div class=\\"avi-ehd-widgets\\">"'
			. '+"<div class=\\"avi-ehd-widget avi-ehd-widget--score\\" data-ehd-tab=\\"score\\">"'
			. '+_homeVerifBadge'
			. '+"<span class=\\"avi-ehd-widget-icon\\">\\u2B50</span>"'
			. '+"<div class=\\"avi-ehd-widget-body\\">"'
			. '+"<div class=\\"avi-ehd-widget-label-row\\"><span class=\\"avi-ehd-widget-label\\">"+_t.gbp_score+"</span>"'
			. '+"<button type=\\"button\\" class=\\"avi-ehd-info-btn\\" data-info=\\"score\\">\\u2139\\uFE0F</button></div>"'
			. '+"<span class=\\"avi-ehd-widget-value\\">"+score+"<small style=\\"font-size:10px;font-weight:400;color:#94a3b8\\">/100</small>"'
			. '+(_homeDelta&&_homeDelta!==0?'
			. '\'<span class="avi-score-delta-home\'+(_homeDelta<0?" avi-score-delta--neg":" avi-score-delta--pos")+\'">\'+'
			. '(_homeDelta>0?"+":"")+_homeDelta+\' pts</span>\''
			. ':"")'
			. '+"</span>"'
			. '+"</div></div>"'
			. '+"<div class=\\"avi-ehd-widget avi-ehd-widget--reviews\\" data-count=\\""+unanswered+"\\" data-ehd-tab=\\"avis\\">"'
			. '+"<span class=\\"avi-ehd-widget-icon\\">\\uD83D\\uDCAC</span>"'
			. '+"<div class=\\"avi-ehd-widget-body\\">"'
			. '+"<div class=\\"avi-ehd-widget-label-row\\"><span class=\\"avi-ehd-widget-label\\">"+_t.unanswered+"</span>"'
			. '+"<button type=\\"button\\" class=\\"avi-ehd-info-btn\\" data-info=\\"unanswered\\">\\u2139\\uFE0F</button></div>"'
			. '+"<span class=\\"avi-ehd-widget-value\\">"+unanswered+"</span>"'
			. '+"</div></div>"'
			. '+"<div class=\\"avi-ehd-widget avi-ehd-widget--scan\\" data-ehd-scan=\\"1\\">"'
			. '+"<span class=\\"avi-ehd-widget-icon\\">\\uD83D\\uDDD3\\uFE0F</span>"'
			. '+"<div class=\\"avi-ehd-widget-body\\">"'
			. '+"<div class=\\"avi-ehd-widget-label-row\\"><span class=\\"avi-ehd-widget-label\\">"+_t.next_scan+"</span>"'
			. '+"<button type=\\"button\\" class=\\"avi-ehd-info-btn\\" data-info=\\"next_scan\\">\\u2139\\uFE0F</button></div>"'
			. '+"<span class=\\"avi-ehd-widget-value\\">"+nextScan+"</span>"'
			. '+"</div></div>"'
			. '+"</div>"'
			. '+"<div class=\\"avi-sync-btn-wrap\\">"'
			. '+"<button type=\\"button\\" class=\\"avi-sync-btn\\" id=\\"aviHomeSyncBtn\\" data-context=\\"home\\">"'
			. '+(_t.sync_btn||"\\uD83D\\uDD04")'
			. '+"<span class=\\"avi-sync-info-btn\\" data-context=\\"home\\" aria-label=\\"info\\" style=\\"display:inline-flex;align-items:center;margin-left:6px;font-size:14px;cursor:pointer;line-height:1;\\">&#x2139;&#xFE0F;</span>"'
			. '+"</button>"'
			. '+"</div>";'
			. 'if(!document.getElementById("aviSyncInfoModal")){'
			. 'var sim=document.createElement("div");'
			. 'sim.id="aviSyncInfoModal";'
			. 'sim.style.cssText="display:none;position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.45);align-items:center;justify-content:center;";'
			. 'sim.innerHTML="<div style=\\"background:#fff;border-radius:14px;max-width:420px;width:90%;padding:28px 24px;position:relative;box-shadow:0 8px 32px rgba(0,0,0,0.18);\\">"'
			. '+"<button type=\\"button\\" id=\\"aviSyncInfoClose\\" style=\\"position:absolute;top:12px;right:16px;background:none;border:none;font-size:22px;cursor:pointer;color:#6b7280;\\">&times;</button>"'
			. '+"<div style=\\"font-size:20px;font-weight:700;margin-bottom:12px;color:#111827;\\" id=\\"aviSyncInfoTitle\\"></div>"'
			. '+"<div style=\\"font-size:14px;color:#374151;line-height:1.6;margin-bottom:14px;\\" id=\\"aviSyncInfoBody\\"></div>"'
			. '+"<div style=\\"font-size:12px;color:#6b7280;border-top:1px solid #e5e7eb;padding-top:10px;\\" id=\\"aviSyncInfoFooter\\"></div>"'
			. '+"</div>";'
			. 'document.body.appendChild(sim);'
			. 'document.getElementById("aviSyncInfoClose").addEventListener("click",function(){'
			. 'document.getElementById("aviSyncInfoModal").style.display="none";'
			. '});'
			. 'sim.addEventListener("click",function(ev){'
			. 'if(ev.target===sim){sim.style.display="none";}'
			. '});'
			. '}'
			. 'if(!window._aviSyncInfoListenerAdded){'
			. 'window._aviSyncInfoListenerAdded=true;'
			. 'document.addEventListener("click",function(ev){'
			. 'var btn=ev.target.closest(".avi-sync-info-btn");'
			. 'if(!btn)return;'
			. 'ev.stopPropagation();ev.stopImmediatePropagation();ev.preventDefault();'
			. 'var ctx=btn.getAttribute("data-context");'
			. 'var t=_embedI18n[_embedLang]||_embedI18n.en||{};'
			. 'var title=t.sync_info_title||"Sync from Google";'
			. 'var body=ctx==="score"?(t.sync_info_score_body||""):(t.sync_info_home_body||"");'
			. 'var footer=t.sync_info_footer||"";'
			. 'var modal=document.getElementById("aviSyncInfoModal");'
			. 'document.getElementById("aviSyncInfoTitle").textContent=title;'
			. 'document.getElementById("aviSyncInfoBody").textContent=body;'
			. 'document.getElementById("aviSyncInfoFooter").textContent=footer;'
			. 'modal.style.display="flex";'
			. '});'
			. '}'
			. 'if(!_homePanel._guardianListenerAdded){'
			. '_homePanel._guardianListenerAdded=true;'
			. '_homePanel.addEventListener("click",function(e){'
			. 'if(!e.target.closest("[data-guardian-info]"))return;'
			. 'var _tG=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _gSteps=['
			. '{t:_tG.guardian_info_s1_title||"",b:_tG.guardian_info_s1_body||""},'
			. '{t:_tG.guardian_info_s2_title||"",b:_tG.guardian_info_s2_body||""},'
			. '{t:_tG.guardian_info_s3_title||"",b:_tG.guardian_info_s3_body||""},'
			. '{t:_tG.guardian_info_s4_title||"",b:_tG.guardian_info_s4_body||"",danger:false}'
			. '];'
			. 'var _gp2=window._aviGuardianPlan||null;'
			. 'var _gIsDisabled=_gp2&&_gp2.plan==="free";'
			. 'var _gIsPaid=_gp2&&_gp2.is_paid;'
			. 'var _gIsTrial=!_gIsDisabled&&(!_gp2||_gp2.is_trial);'
			. 'var _gIsTrialExpired=!_gIsDisabled&&!_gIsTrial&&!_gIsPaid;'
			. 'var _gDaysLeft=_gp2?Math.max(0,(_gp2.trial_days||15)-(_gp2.days_active||0)):15;'
			. 'var _gPricingHtml="";'
			. 'if(_gIsDisabled){'
			. '_gPricingHtml="<div class=\"avi-guardian-pricing-box avi-guardian-disabled\">"'
			. '+"<div class=\"avi-guardian-pricing-title\">\ud83d\udeab "+(_tG.guardian_disabled_title||"Guardian Deactivated")+"</div>"'
			. '+"<div class=\"avi-guardian-pricing-warning\">"+(_tG.guardian_disabled_warn||"Your profile is no longer monitored. Competitors can modify your GBP without you knowing.")+"</div>"'
			. '+"<button type=\"button\" class=\"avi-guardian-activate-btn\" id=\"aviGuardianActivateBtn\">"+(_tG.guardian_activate||"Activate Guardian \u2192")+"</button>"'
			. '+"</div>";'
			. '}else if(_gIsTrial){'
			. '_gPricingHtml="<div class=\"avi-guardian-pricing-box avi-guardian-trial\">"'
			. '+"<div class=\"avi-guardian-pricing-title\">✅ "+(_tG.guardian_trial_active||"Free Trial Active")+"</div>"'
			. '+"<div class=\"avi-guardian-pricing-body\">"+_gDaysLeft+" "+(_tG.guardian_trial_days_left||"days left")+"</div>"'
			. '+"<div class=\"avi-guardian-pricing-detail\">"+(_tG.guardian_pricing_detail||"After trial: 3 credits/month + 2 credits per change detected")+"</div>"'
			. '+"</div>";'
			. '}else if(_gIsTrialExpired){'
			. '_gPricingHtml="<div class=\"avi-guardian-pricing-box avi-guardian-disabled\">"'
			. '+"<div class=\"avi-guardian-pricing-title\">\u23f1\ufe0f "+(_tG.guardian_trial_expired_title||"Free Trial Ended")+"</div>"'
			. '+"<div class=\"avi-guardian-pricing-warning\">"+(_tG.guardian_trial_expired_warn||"Your 15-day free trial has ended. Activate Guardian to keep monitoring your profile.")+"</div>"'
			. '+"<div class=\"avi-guardian-pricing-detail\">"+(_tG.guardian_pricing_detail||"After trial: 3 credits/month + 2 credits per change detected")+"</div>"'
			. '+"<button type=\"button\" class=\"avi-guardian-activate-btn\" id=\"aviGuardianActivateBtn\">"+(_tG.guardian_activate||"Activate Guardian \u2192")+"</button>"'
			. '+"</div>";'
			. '}else{'
			. 'var _gCredits=_gp2?(_gp2.credits_available||0):0;'
			. 'var _gLowCredits=_gCredits<10;'
			. '_gPricingHtml="<div class=\"avi-guardian-pricing-box "+(_gLowCredits?"avi-guardian-low-credits":"avi-guardian-paid-active")+"\">"'
			. '+(_gLowCredits?"<div class=\"avi-guardian-pricing-title\">\ud83d\udea8 "+(_tG.guardian_low_credits_title||"Low Credits — Guardian at risk")+"</div>":"<div class=\"avi-guardian-pricing-title\">\ud83d\udee1\ufe0f "+(_tG.guardian_paid_active_title||"Guardian Active")+"</div>")'
			. '+(_gLowCredits?"<div class=\"avi-guardian-pricing-warning\">"+(_tG.guardian_low_credits_warn||"⚠️ You have fewer than 10 credits. Guardian may stop monitoring soon.")+"</div>":"")'
			. '+"<div class=\"avi-guardian-pricing-detail\">"+(_tG.guardian_pricing_detail_active||"3 credits/month · 2 credits per change detected")+"</div>"'
			. '+"<div class=\"avi-guardian-credits-count\">"+(_tG.guardian_credits_remaining||"Credits remaining:")+(" <strong>"+_gCredits+"</strong>")+"</div>"'
			. '+(_gp2&&_gp2.next_billing_date?"<div class=\"avi-guardian-next-billing\">"+(_tG.guardian_next_billing||"Next billing:")+(" <strong>"+_gp2.next_billing_date+"</strong>")+"</div>":"")'
			. '+(_gLowCredits?"<button type=\"button\" class=\"avi-guardian-buy-btn\" id=\"aviGuardianBuyBtn\">"+(_tG.guardian_buy_credits||"Buy credits \u2192")+"</button>":"")'
			. '+"<button type=\"button\" class=\"avi-guardian-deactivate-btn\" id=\"aviGuardianDeactivateBtn\">"+(_tG.guardian_deactivate||"Deactivate Guardian")+"</button>"'
			. '+"</div>";'
			. '}'
			. 'var _gHtml=_gSteps.map(function(s){return s.t?"<div class=\"avi-edu-step\"><div class=\"avi-edu-step-title\">"+s.t+"</div><div class=\"avi-edu-step-body\">"+s.b+"</div></div>":"";}).join("");'
			. 'var _gBd=document.createElement("div");'
			. '_gBd.className="avi-edu-modal-backdrop";'
			. '_gBd.innerHTML="<div class=\"avi-edu-modal\"><div class=\"avi-edu-modal-title\">"+(_tG.guardian_info_title||"🛡️ Guardian")+"</div>"+_gHtml+_gPricingHtml+"<button type=\"button\" class=\"avi-edu-modal-close\" id=\"aviGuardianModalClose\">"+(_tG.guardian_info_cta||"Got it ✓")+"</button></div>";'
			. 'document.body.appendChild(_gBd);'
			. '_gBd.addEventListener("click",function(ev){'
			. 'if(ev.target===_gBd||ev.target.closest("#aviGuardianModalClose"))_gBd.remove();'
			. 'if(ev.target.closest("#aviGuardianBuyBtn")){'
			. '_gBd.remove();'
			. '_switchEmbedTab("profile_solo");'
			. '}'
			. 'if(ev.target.closest("#aviGuardianActivateBtn")){'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-activate",{'
			. 'method:"POST",'
			. 'headers:{"X-Embed-Token":window.aviEmbedToken||"","Content-Type":"application/json"},'
			. 'body:JSON.stringify({"profile_id":window.aviEmbedProfileId})'
			. '})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){'
			. 'if(d&&d.success){'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-plan?profile_id="+window.aviEmbedProfileId,{'
			. 'headers:{"X-Embed-Token":window.aviEmbedToken||""}'
			. '})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(p){if(p){window._aviGuardianPlan=p;_aviGuardianInjectScore();}_gBd.remove();}).catch(function(){});'
			. '}'
			. '}).catch(function(){});'
			. '}'
			. 'if(ev.target.closest("#aviGuardianDeactivateBtn")){'
			. 'fetch(window.aviEmbedRestUrl+"embed/guardian-deactivate",{'
			. 'method:"POST",'
			. 'headers:{"X-Embed-Token":window.aviEmbedToken||"","Content-Type":"application/json"},'
			. 'body:JSON.stringify({"profile_id":window.aviEmbedProfileId})'
			. '})'
			. '.then(function(r){return r.ok?r.json():null;})'
			. '.then(function(d){'
			. 'if(d&&d.success){'
			. 'window._aviGuardianPlan=null;'
			. '_aviGuardianInjectScore();'
			. '_gBd.remove();'
			. '}'
			. '}).catch(function(){});'
			. '}'
			. '});'
			. '});'
			. '}'
			. '_homePanel.querySelectorAll("[data-ehd-tab]").forEach(function(el){'
			. 'el.addEventListener("click",function(){'
			. '_switchEmbedTab(this.getAttribute("data-ehd-tab"));'
			. '});'
			. '});'
			. '_homePanel.querySelectorAll("[data-ehd-scan]").forEach(function(el){'
			. 'el.addEventListener("click",function(){'
			. 'if(typeof openSchedulePanel==="function")openSchedulePanel();'
			. '});'
			. '});'
			. 'var _homeSyncBtn=_homePanel.querySelector("#aviHomeSyncBtn");'
			. 'if(_homeSyncBtn){_homeSyncBtn.addEventListener("click",function(ev){if(ev.target.closest(".avi-sync-info-btn"))return;_syncProfileFromGoogle(this);});}'
			. 'var _bannerClose=document.getElementById("aviEduBannerClose");'
			. 'var _bannerOpen=document.getElementById("aviEduBannerOpen");'
			. 'if(_bannerClose)_bannerClose.addEventListener("click",function(){'
			. 'try{localStorage.setItem("avi_home_banner_dismissed","1");}catch(e){}'
			. 'var b=document.getElementById("aviEduBanner");'
			. 'if(b)b.remove();'
			. '});'
			. 'if(_bannerOpen)_bannerOpen.addEventListener("click",_openEduModal);'
			. '_homePanel.querySelectorAll(".avi-ehd-info-btn").forEach(function(btn){'
			. 'btn.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. 'var _tL=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var key=btn.getAttribute("data-info");'
			. 'var titles={'
			. 'cc:_tL.control_center||"Control Center",'
			. 'score:_tL.gbp_score||"GBP Score",'
			. 'unanswered:_tL.unanswered||"Unanswered Reviews",'
			. 'next_scan:_tL.next_scan||"Next Scan",'
			. 'nap:_tL.nap_status||"Profile Completeness"'
			. '};'
			. 'var bodies={'
			. 'cc:_tL.tt_control_center||"",'
			. 'score:_tL.tt_score||"",'
			. 'unanswered:_tL.tt_unanswered||"",'
			. 'next_scan:_tL.tt_next_scan||"",'
			. 'nap:_tL.tt_nap||""'
			. '};'
			. '_openInfoModal(titles[key]||key, bodies[key]||"");'
			. '});'
			. '});'
			. 'document.dispatchEvent(new CustomEvent("avi-home-rendered"));'
			. '}'
			. 'function _syncProfileFromGoogle(btnEl){'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'if(btnEl){'
			. 'btnEl.disabled=true;'
			. 'btnEl.textContent=_t.syncing_btn||"\\u23F3";'
			. 'btnEl.classList.add("avi-sync-btn--syncing");'
			. '}'
			. 'document.querySelectorAll(".avi-sync-btn").forEach(function(b){'
			. 'b.disabled=true;'
			. 'b.textContent=_t.syncing_btn||"\\u23F3";'
			. 'b.classList.add("avi-sync-btn--syncing");'
			. '});'
			. 'fetch(window.location.origin+"/wp-json/avision/v1/embed/sync-profile",{'
			. 'method:"POST",'
			. 'headers:{'
			. '"Content-Type":"application/json",'
			. '"X-Embed-Token":window.aviEmbedToken||""'
			. '},'
			. 'body:JSON.stringify({'
			. 'profile_id:window.aviEmbedProfileId,'
			. 'key_id:window.aviEmbedKeyId'
			. '})'
			. '})'
			. '.then(function(r){return r.json();})'
			. '.then(function(data){'
			. 'if(data.success){'
			. 'var sd=window.aviEmbedScoreData||{};'
			. 'var keys=["has_name","name_value","is_verified","verification_state","has_website","website_url",'
			. '"has_phone","phone_value","has_hours","hours_periods","has_description",'
			. '"has_category","category_name","has_address","city",'
			. '"primary_category_name","primary_category_id","score",'
			. '"gbp_attributes","attr_count"];'
			. 'keys.forEach(function(k){'
			. 'if(data[k]!==undefined)sd[k]=data[k];'
			. '});'
			. 'window.aviEmbedScoreData=sd;'
			. 'if(_embedCurrentTab==="score")_scoreRender();'
			. 'if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. '_renderHomeDashboard();'
			. 'document.querySelectorAll(".avi-sync-btn").forEach(function(b){'
			. 'b.disabled=false;'
			. 'b.textContent=_t.sync_success||"\\u2705";'
			. 'b.classList.remove("avi-sync-btn--syncing");'
			. '});'
			. 'setTimeout(function(){'
			. 'document.querySelectorAll(".avi-sync-btn").forEach(function(b){'
			. 'b.textContent=_t.sync_btn||"\\uD83D\\uDD04";'
			. 'var ctx=b.getAttribute("data-context");'
			. 'if(ctx){var sp=document.createElement("span");sp.className="avi-sync-info-btn";sp.setAttribute("data-context",ctx);sp.setAttribute("aria-label","info");sp.style.cssText="display:inline-flex;align-items:center;margin-left:6px;font-size:14px;cursor:pointer;line-height:1;";sp.innerHTML="&#x2139;&#xFE0F;";b.appendChild(sp);}'
			. '});'
			. '},3000);'
			. '}else{'
			. 'throw new Error("sync failed");'
			. '}'
			. '})'
			. '.catch(function(){'
			. 'document.querySelectorAll(".avi-sync-btn").forEach(function(b){'
			. 'b.disabled=false;'
			. 'b.textContent=_t.sync_error||"";'
			. 'b.classList.remove("avi-sync-btn--syncing");'
			. 'setTimeout(function(){'
			. 'b.textContent=_t.sync_btn||"\\uD83D\\uDD04";'
			. 'var ctx=b.getAttribute("data-context");'
			. 'if(ctx){var sp=document.createElement("span");sp.className="avi-sync-info-btn";sp.setAttribute("data-context",ctx);sp.setAttribute("aria-label","info");sp.style.cssText="display:inline-flex;align-items:center;margin-left:6px;font-size:14px;cursor:pointer;line-height:1;";sp.innerHTML="&#x2139;&#xFE0F;";b.appendChild(sp);}'
			. '},3000);'
			. '});'
			. '});'
			. '}'
			. 'function _switchEmbedTab(tab){'
			. 'if(tab==="posts"&&_isLodging())return;'
			. '_embedCurrentTab=tab;'
			. 'Object.keys(_navBtns).forEach(function(k){'
			. '_navBtns[k].setAttribute("aria-selected",k===tab?"true":"false");'
			. '});'
			. 'if(_mobileMenu){'
			. '_mobileMenu.querySelectorAll(".avi-embed-mobile-menu-btn").forEach(function(b){'
			. 'b.setAttribute("aria-selected",'
			. 'b.getAttribute("data-embed-tab")===tab?"true":"false");'
			. '});'
			. '}'
			. 'if(tab==="home"){'
			. 'if(_drawer){'
			. '_drawer.removeAttribute("hidden");'
			. '_drawer.style.removeProperty("display");'
			. '}'
			. 'if(_modal){_modal.setAttribute("hidden","");}'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_homePanel){_homePanel.style.display="block";_renderHomeDashboard();_kwLoad();}'
			. 'if(_module)_module.classList.add("avi-embed-home-active");'
			. '}else if(tab==="keywords"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel){'
			. '_kwPanel.style.display="block";'
			. '_kwLoad();'
			. '}'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. '}else if(tab==="map"||tab==="evolution"||tab==="competitors"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal){'
			. '_modal.removeAttribute("hidden");'
			. 'var _tabBtn=_modal.querySelector(\'[data-avi-heatmap-tab="\'+tab+\'"]\');'
			. 'if(_tabBtn)setTimeout(function(){_tabBtn.click();},50);'
			. '}'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. '}else if(tab==="agency_hub"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="block";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. '}else if(tab==="profile_solo"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="block";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. '}else if(tab==="score"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_scorePanel){'
			. '_scorePanel.style.display="block";'
			. '_scoreRender();'
			. '_aviGuardianInjectScore();'
			. '_aviGuardianMarkReadAuto();'
			. 'document.dispatchEvent(new CustomEvent("avi-score-rendered"));'
			. '}'
			. '}else if(tab==="avis"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_reviewsPanel){_reviewsPanel.style.display="block";_reviewsRender();}'
			. '}else if(tab==="posts"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_postsPanel){_postsPanel.style.display="block";_postsRender();}'
			. '}else if(tab==="photos"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_photosPanel){_photosPanel.style.display="block";_photosRender();}'
			. '}else if(tab==="citations"){'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){_drawer.setAttribute("hidden","");_drawer.style.setProperty("display","none","important");}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel)_helpPanel.style.display="none";'
			. 'if(_citationsPanel){_citationsPanel.style.display="block";_citationsRender();}'
			. '}else{'
			. 'if(_homePanel)_homePanel.style.display="none";'
			. 'if(_module)_module.classList.remove("avi-embed-home-active");'
			. 'if(_drawer){'
			. '_drawer.setAttribute("hidden","");'
			. '_drawer.style.setProperty("display","none","important");'
			. '}'
			. 'if(_modal)_modal.setAttribute("hidden","");'
			. 'if(_kwPanel)_kwPanel.style.display="none";'
			. 'if(_agHubPanel)_agHubPanel.style.display="none";'
			. 'if(_profilePanel)_profilePanel.style.display="none";'
			. 'if(_scorePanel)_scorePanel.style.display="none";'
			. 'if(_reviewsPanel)_reviewsPanel.style.display="none";'
			. 'if(_postsPanel)_postsPanel.style.display="none";'
			. 'if(_photosPanel)_photosPanel.style.display="none";'
			. 'if(_citationsPanel)_citationsPanel.style.display="none";'
			. 'if(_helpPanel){_helpPanel.style.display="block";_renderHelpPanel();}'
			. '}'
			. 'var _eduBtn=document.getElementById("aviEduTipsBtn");'
			. 'if(_eduBtn)_eduBtn.style.display=tab==="home"?"flex":"none";'
			. '}'
			. 'function _setEmbedLang(lang){'
			. 'if(!_embedNavI18n[lang])return;'
			. 'var _curUrl=new URL(window.location.href);'
			. '_curUrl.searchParams.set("lang",lang);'
			. 'window.location.replace(_curUrl.toString());'
			. 'return;'
			. '_embedLang=lang;'
			. 'if(!_embedNavI18n[_embedLang])_embedLang="en";'
			. 'window.aviEmbedLang=_embedLang||"en";'
			. '_t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'kwClose.title=_t.close;'
			. 'if(_kwHeader){'
			. '_kwHeader.innerHTML='
			. '\'<div class="avi-kw-header-title">\\uD83D\\uDD11 \'+(_t.kw_panel_title||"")+\'</div>\''
			. '+\'<div class="avi-kw-header-sub">\'+(_t.kw_panel_sub||"")+\'</div>\';'
			. '}'
			. 'si.placeholder=_t.search_kw;'
			. 'ab.textContent=_t.add_kw;'
			. 'ib.textContent=_t.import_kw;'
			. 'ib.title=_t.import_kw_tip;'
			. 'expBtn.textContent=_t.export_kw;'
			. 'csvOpt.textContent=_t.export_csv;'
			. 'pdfOpt.textContent=_t.export_pdf;'
			. 'cb.textContent=_t.cancel;'
			. 'sb.textContent=_t.save;'
			. 'impLabel.textContent=_t.import_label;'
			. 'impCb.textContent=_t.cancel;'
			. 'impSb.textContent=_t.import_btn;'
			. 'ai.placeholder=_t.add_kw_ph;'
			. 'impTa.placeholder=_t.import_kw_ph;'
			. 'var _hmAddKwBtn=document.querySelector(".avi-add-kw-btn");'
			. 'if(_hmAddKwBtn)_hmAddKwBtn.textContent=_t.add_keyword||"+ Add keyword";'
			. 'if(_kwPanel&&_kwPanel.style.display==="block")_kwRenderTable();'
			. 'if(_scorePanel&&_scorePanel.style.display==="block")_scoreRender();'
			. 'if(_reviewsPanel&&_reviewsPanel.style.display==="block")_reviewsRender();'
			. 'if(_postsPanel&&_postsPanel.style.display==="block")_postsRender();'
			. 'if(_photosPanel&&_photosPanel.style.display==="block")_photosRender();'
			. 'if(_citationsPanel&&_citationsPanel.style.display==="block")_citationsRender();'
			. 'if(typeof _postsCreatePanel!=="undefined"&&_postsCreatePanel&&_postsCreatePanel.classList.contains("open")){var _pe=window._postsEditRef||null;_postsOpenPanel(_pe);}'
			. 'if(_agPanel&&_agPanel.classList.contains("open")){var _agH=_agPanel.querySelector(".avi-agency-header h3");if(_agH)_agH.textContent=_t.clients_title+" ("+window.aviEmbedAgencyProfiles.length+")";var _agS=_agPanel.querySelector(".avi-agency-search");if(_agS){_agS.placeholder=_t.search_client_ph;if(typeof window._agRenderList==="function")window._agRenderList(_agS.value);}if(_agTrigger)_agTrigger.textContent=_t.clients_trigger;}'
			. 'if(_agHubPanel&&_agHubPanel.style.display==="block")_agHubRender();'
			. '_embedNavLabels=_embedNavI18n[lang];'
			. '/* i18n refresh — profile solo panel */'
			. 'try{'
			. '  var _pEl=document.getElementById("aviEmbedProfilePanel");'
			. '  if(_pEl&&typeof _profileRender==="function"){'
			. '    Array.from(_pEl.children).forEach(function(c){'
			. '      if(c.tagName!=="BUTTON")c.remove();'
			. '    });'
			. '    _profileRender();'
			. '  }'
			. '  var _niR=_embedNavI18n[_embedLang]||_embedNavI18n["en"]||{};'
			. '  if(_niR["profile_solo"]){'
			. '    document.querySelectorAll("[data-submenu-tab=\"profile_solo\"]").forEach(function(el){'
			. '      el.textContent=_niR["profile_solo"];'
			. '    });'
			. '  }'
			. '  var _sArr=document.querySelector(".avi-submenu-arrow");'
			. '  if(_sArr&&_t["profile_title"])_sArr.title=_t["profile_title"];'
			. '}catch(e){}'
			. '_embedNavTabs.forEach(function(tab){'
			. 'if(_navBtns[tab])_setNavBtnLabel(_navBtns[tab],_embedNavLabels[tab]);'
			. '});'
			. 'if(_mobileMenu){'
			. '_mobileMenu.querySelectorAll(".avi-embed-mobile-menu-btn").forEach(function(b){'
			. 'var _mt=b.getAttribute("data-embed-tab");'
			. 'if(_embedNavLabels[_mt])b.textContent=_embedNavLabels[_mt];'
			. '});'
			. '}'
			. 'var root=document.getElementById("avision-dashboard-root");'
			. 'if(root){'
			. 'root.setAttribute("data-lang",lang);'
			. 'root.setAttribute("data-language",lang);'
			. '}'
			. 'var _newLangData=_embedLangs.find(function(l){return l.code===lang;})||_embedLangs[0];'
			. '_langTrigger.textContent=_embedLangDisplay(_newLangData)+" ▾";'
			. '_langDropdown.querySelectorAll(".avi-embed-lang-option").forEach(function(o){'
			. 'o.classList.toggle("active",o.getAttribute("data-embed-lang")===lang);'
			. '});'
			. '_langDropdownOpen=false;'
			. '_langDropdown.style.display="none";'
			. 'if(!_upsellDismissed)_renderUpsell(lang);'
			. 'if(_embedCurrentTab==="home")_renderHomeDashboard();'
			. 'try{'
			. '  var _freqLabels={"once":{"en":"One-time scan","fr":"Scan unique","es":"Escaneo único","de":"Einmaliger Scan","pt-br":"Scan único","tr":"Tek tarama"},'
			. '  "daily":{"en":"Daily","fr":"Quotidien","es":"Diario","de":"Täglich","pt-br":"Diário","tr":"Günlük"},'
			. '  "every3days":{"en":"Every 3 days","fr":"Tous les 3 jours","es":"Cada 3 días","de":"Alle 3 Tage","pt-br":"A cada 3 dias","tr":"Her 3 günde"},'
			. '  "weekly":{"en":"Weekly","fr":"Hebdomadaire","es":"Semanal","de":"Wöchentlich","pt-br":"Semanal","tr":"Haftalık"},'
			. '  "every2weeks":{"en":"Every 2 weeks","fr":"Toutes les 2 semaines","es":"Cada 2 semanas","de":"Alle 2 Wochen","pt-br":"A cada 2 semanas","tr":"Her 2 haftada"},'
			. '  "monthly":{"en":"Monthly","fr":"Mensuel","es":"Mensual","de":"Monatlich","pt-br":"Mensal","tr":"Aylık"}};'
			. '  var _creditWord={"en":"credits","fr":"crédits","es":"créditos","de":"Credits","pt-br":"créditos","tr":"kredi"};'
			. '  var _freqSel=document.querySelector("[data-avi-hm-frequency]");'
			. '  if(_freqSel){Array.from(_freqSel.options).forEach(function(o){'
			. '    var _fl=_freqLabels[o.value];'
			. '    if(_fl)o.textContent=(_fl[lang]||_fl["en"]);'
			. '  });}'
			. '  var _gridSel=document.querySelector("[data-avi-heatmap-grid-size]");'
			. '  var _cw=_creditWord[lang]||_creditWord["en"];'
			. '  if(_gridSel){Array.from(_gridSel.options).forEach(function(o){'
			. '    var _s=parseInt(o.value,10);'
			. '    if(_s)o.textContent=window._leGridLabel(_s,_cw);'
			. '  });}'
			. '}catch(e){}'
			. '}'
			. '_nav.addEventListener("click",function(e){'
			. 'var btn=e.target.closest("[data-embed-tab]");'
			. 'if(!btn)return;'
			. 'var tab=btn.getAttribute("data-embed-tab");'
			. '_switchEmbedTab(tab);'
			. '});'
			. 'if(_hamburger&&_mobileMenu){'
			. '_hamburger.addEventListener("click",function(e){'
			. 'e.stopPropagation();'
			. '_mobileMenu.classList.toggle("is-open");'
			. '_hamburger.textContent=_mobileMenu.classList.contains("is-open")'
			. '?"\\u2715":"\\u2630";'
			. '});'
			. '_mobileMenu.querySelectorAll(".avi-embed-mobile-menu-btn").forEach(function(btn){'
			. 'btn.addEventListener("click",function(){'
			. '_mobileMenu.classList.remove("is-open");'
			. '_hamburger.textContent="\\u2630";'
			. 'var tab=this.getAttribute("data-embed-tab");'
			. 'if(tab)_switchEmbedTab(tab);'
			. '});'
			. '});'
			. 'document.addEventListener("click",function(e){'
			. 'if(_mobileMenu&&_mobileMenu.classList.contains("is-open")'
			. '&&!_mobileMenu.contains(e.target)&&e.target!==_hamburger){'
			. '_mobileMenu.classList.remove("is-open");'
			. '_hamburger.textContent="\\u2630";'
			. '}'
			. '});'
			. '}'
			. 'if(_embedCurrentTab==="home"&&_homePanel){_homePanel.style.display="block";_renderHomeDashboard();_kwLoad();if(_module)_module.classList.add("avi-embed-home-active");}'
			. 'if(window.aviEmbedPurchaseSuccess){'
			. '  var _t=_embedI18n[_embedLang]'
			. '    ||_embedI18n["en"];'
			. '  var _psBanner=document.createElement("div");'
			. '  _psBanner.style.cssText="position:fixed;'
			. '    top:20px;left:50%;transform:translateX(-50%);'
			. '    background:#16a34a;color:#fff;'
			. '    border-radius:10px;padding:16px 24px;'
			. '    z-index:999999;box-shadow:'
			. '    0 4px 20px rgba(0,0,0,.15);'
			. '    text-align:center;min-width:280px;'
			. '    max-width:90vw;";'
			. '  var _psBTitle=document.createElement("div");'
			. '  _psBTitle.style.cssText="font-size:15px;'
			. '    font-weight:700;margin-bottom:6px;";'
			. '  _psBTitle.textContent='
			. '    _t.purchase_success_title'
			. '    ||"\\u2713 Payment received!";'
			. '  var _psBSub=document.createElement("div");'
			. '  _psBSub.style.cssText="font-size:12px;'
			. '    opacity:.9;margin-bottom:12px;";'
			. '  _psBSub.textContent='
			. '    _t.purchase_success_sub'
			. '    ||"Your credits will be available shortly.";'
			. '  var _psBClose=document.createElement("button");'
			. '  _psBClose.type="button";'
			. '  _psBClose.style.cssText="background:#fff;'
			. '    color:#16a34a;border:none;border-radius:6px;'
			. '    padding:6px 16px;font-size:12px;'
			. '    font-weight:700;cursor:pointer;";'
			. '  _psBClose.textContent='
			. '    _t.purchase_success_close||"Got it";'
			. '  _psBClose.addEventListener("click",function(){'
			. '    _psBanner.style.display="none";'
			. '  });'
			. '  _psBanner.appendChild(_psBTitle);'
			. '  _psBanner.appendChild(_psBSub);'
			. '  _psBanner.appendChild(_psBClose);'
			. '  document.body.appendChild(_psBanner);'
			. '  setTimeout(function(){'
			. '    _psBanner.style.display="none";'
			. '  },8000);'
			. '}'
			. '_initHeatmapAddKwBtn();'
			. 'if(!window._aviSpCancelConfirmBound){'
			. 'window._aviSpCancelConfirmBound=true;'
			. 'document.addEventListener("click",function(e){'
			. 'var _spBtn=e.target.closest(".avi-hm-sp-cancel-btn");'
			. 'if(!_spBtn)return;'
			. 'e.stopImmediatePropagation();'
			. 'e.preventDefault();'
			. 'var _tSp=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'if(!confirm(_tSp.confirm_delete_scan||"Delete this scheduled scan?"))return;'
			. 'var _sid=Number(_spBtn.getAttribute("data-schedule-id"));'
			. 'if(_sid){'
			. 'var _base=(window.aviEmbedRestUrl||"").replace(/heatmap-scan.*$/,"");'
			. 'fetch(_base+"heatmap-schedule/"+_sid,{'
			. 'method:"DELETE",'
			. 'credentials:"same-origin",'
			. 'headers:{"X-WP-Nonce":window.aviEmbedNonce||"","Content-Type":"application/json"}'
			. '}).then(function(){'
			. 'if(typeof loadHeatmapSchedules==="function")loadHeatmapSchedules(function(){'
			. 'if(typeof openSchedulePanel==="function")openSchedulePanel();'
			. '});'
			. '});'
			. '}'
			. '},true);'
			. '}'
			. 'document.addEventListener("click",function(e){'
			. 'if(e.target.closest("[data-avi-heatmap-modal-close]")){'
			. 'setTimeout(function(){_switchEmbedTab("home");},50);'
			. '}'
			. '});'
			. 'var _upsellUrls={'
			. 'en:{btoc:"https://avision.org/local-business/",btob:"https://avision.org/"},'
			. 'fr:{btoc:"https://avision.org/fr/visibilite-locale/",btob:"https://avision.org/fr/"},'
			. 'es:{btoc:"https://avision.org/es/visibilidad-local/",btob:"https://avision.org/es/"}'
			. '};'
			. 'var _upsellI18n={'
			. 'en:{'
			. 'btoc_msg:"Protect & automate your Google presence",'
			. 'btoc_sub:"Guardian Mode watches 24/7",'
			. 'btoc_cta:"Unlock Full Protection ↗",'
			. 'btoc_badge:"$69 instead of $99 · LAUNCH_BTOC",'
			. 'btob_msg:"Manage all your clients GBP listings from one dashboard",'
			. 'btob_sub:"Save 10h/week",'
			. 'btob_cta:"Manage Your Fleet ↗",'
			. 'btob_badge:"38% off · LAUNCH_BTOB"'
			. '},'
			. 'fr:{'
			. 'btoc_msg:"Protégez et automatisez votre présence Google",'
			. 'btoc_sub:"Guardian Mode surveille 24h/24",'
			. 'btoc_cta:"Activer la protection complète ↗",'
			. 'btoc_badge:"69€ au lieu de 99€ · LAUNCH_BTOC",'
			. 'btob_msg:"Gérez tous vos profils clients depuis un seul tableau de bord",'
			. 'btob_sub:"Gagnez 10h/semaine",'
			. 'btob_cta:"Gérer ma flotte ↗",'
			. 'btob_badge:"38% de réduction · LAUNCH_BTOB"'
			. '},'
			. 'es:{'
			. 'btoc_msg:"Protege y automatiza tu presencia en Google",'
			. 'btoc_sub:"Guardian Mode vigila 24/7",'
			. 'btoc_cta:"Activar protección completa ↗",'
			. 'btoc_badge:"69€ en vez de 99€ · LAUNCH_BTOC",'
			. 'btob_msg:"Gestiona todos tus perfiles GBP desde un panel",'
			. 'btob_sub:"Ahorra 10h/semana",'
			. 'btob_cta:"Gestionar mi flota ↗",'
			. 'btob_badge:"38% descuento · LAUNCH_BTOB"'
			. '},'
			. '"pt-br":{'
			. 'btoc_msg:"Proteja e automatize sua presen\u00e7a no Google",'
			. 'btoc_sub:"Guardian Mode monitora 24/7",'
			. 'btoc_cta:"Ativar prote\u00e7\u00e3o completa \u2197",'
			. 'btoc_badge:"$69 em vez de $99 \u00b7 LAUNCH_BTOC",'
			. 'btob_msg:"Gerencie todas as fichas GBP dos seus clientes em um painel",'
			. 'btob_sub:"Economize 10h/semana",'
			. 'btob_cta:"Gerenciar minha frota \u2197",'
			. 'btob_badge:"38% de desconto \u00b7 LAUNCH_BTOB"'
			. '},'
			. 'tr:{'
			. 'btoc_msg:"Google varl\u0131\u011f\u0131n\u0131z\u0131 koruyun ve otomatikle\u015ftirin",'
			. 'btoc_sub:"Guardian Mode 7/24 izliyor",'
			. 'btoc_cta:"Tam korumay\u0131 etkinle\u015ftir \u2197",'
			. 'btoc_badge:"$69, $99 yerine \u00b7 LAUNCH_BTOC",'
			. 'btob_msg:"T\u00fcm m\u00fc\u015fterilerinizin GBP listelerini tek panelden y\u00f6netin",'
			. 'btob_sub:"Haftada 10 saat kazan\u0131n",'
			. 'btob_cta:"Filomi y\u00f6net \u2197",'
			. 'btob_badge:"%38 indirim \u00b7 LAUNCH_BTOB"'
			. '},'
			. 'de:{'
			. 'btoc_msg:"Sch\u00fctzen und automatisieren Sie Ihre Google-Pr\u00e4senz",'
			. 'btoc_sub:"Guardian Mode \u00fcberwacht rund um die Uhr",'
			. 'btoc_cta:"Vollschutz aktivieren \u2197",'
			. 'btoc_badge:"$69 statt $99 \u00b7 LAUNCH_BTOC",'
			. 'btob_msg:"Verwalten Sie alle GBP-Eintr\u00e4ge Ihrer Kunden in einem Dashboard",'
			. 'btob_sub:"Sparen Sie 10h\/Woche",'
			. 'btob_cta:"Meine Flotte verwalten \u2197",'
			. 'btob_badge:"38% Rabatt \u00b7 LAUNCH_BTOB"'
			. '}'
			. '};'
			. 'var _upsellDismissed=false;'
			. '_upsellBar=document.createElement("div");'
			. '_upsellBar.className="avi-embed-upsell";'
			. '_upsellBar.id="aviEmbedUpsell";'
			. 'function _renderUpsell(lang){'
			. '  var l=_upsellI18n[lang]||_upsellI18n.en;'
			. '  var urls=_upsellUrls[lang]||_upsellUrls.en;'
			. '  _upsellBar.innerHTML="";'
			. '  _upsellBar.classList.remove("expanded");'
			. '  var slim=document.createElement("div");'
			. '  slim.className="avi-embed-upsell-slim";'
			. '  var slimText=document.createElement("span");'
			. '  slimText.className="avi-embed-upsell-slim-text";'
			. '  slimText.textContent=_t.upsell_slim;'
			. '  var slimBtn=document.createElement("button");'
			. '  slimBtn.type="button";slimBtn.className="avi-embed-upsell-slim-btn";'
			. '  slimBtn.textContent=_t.learn_more;'
			. '  slim.appendChild(slimText);slim.appendChild(slimBtn);'
			. '  slim.addEventListener("click",function(){'
			. '    var expanded=_upsellBar.classList.toggle("expanded");'
			. '    slimBtn.textContent=expanded?_t.learn_close:_t.learn_more;'
			. '  });'
			. '  _upsellBar.appendChild(slim);'
			. '  var content=document.createElement("div");'
			. '  content.className="avi-embed-upsell-content";'
			. '  var b1=document.createElement("div");'
			. '  b1.className="avi-embed-upsell-block";'
			. '  b1.innerHTML="<div class=\\"avi-embed-upsell-msg\\"><strong>"+_t.upsell_local+"</strong> — "'
			. '    +l.btoc_msg+"<br><span style=\\"color:rgba(255,255,255,0.6);font-size:11px;\\">"'
			. '    +l.btoc_sub+"</span></div>";'
			. '  var btn1=document.createElement("a");'
			. '  btn1.href=urls.btoc;btn1.target="_blank";btn1.rel="noopener";'
			. '  btn1.className="avi-embed-upsell-btn";btn1.textContent=l.btoc_cta;'
			. '  var badge1=document.createElement("span");'
			. '  badge1.className="avi-embed-upsell-badge";badge1.textContent=l.btoc_badge;'
			. '  b1.appendChild(badge1);b1.appendChild(btn1);'
			. '  content.appendChild(b1);'
			. '  var b2=document.createElement("div");'
			. '  b2.className="avi-embed-upsell-block";'
			. '  b2.innerHTML="<div class=\\"avi-embed-upsell-msg\\"><strong>"+_t.upsell_agency+"</strong> — "'
			. '    +l.btob_msg+"<br><span style=\\"color:rgba(255,255,255,0.6);font-size:11px;\\">"'
			. '    +l.btob_sub+"</span></div>";'
			. '  var btn2=document.createElement("a");'
			. '  btn2.href=urls.btob;btn2.target="_blank";btn2.rel="noopener";'
			. '  btn2.className="avi-embed-upsell-btn";btn2.textContent=l.btob_cta;'
			. '  var badge2=document.createElement("span");'
			. '  badge2.className="avi-embed-upsell-badge";badge2.textContent=l.btob_badge;'
			. '  b2.appendChild(badge2);b2.appendChild(btn2);'
			. '  content.appendChild(b2);'
			. '  var dis=document.createElement("button");'
			. '  dis.type="button";dis.className="avi-embed-upsell-dismiss";'
			. '  dis.title=_t.close;dis.textContent="×";'
			. '  dis.addEventListener("click",function(e){'
			. '    e.stopPropagation();'
			. '    _upsellDismissed=true;_upsellBar.style.display="none";'
			. '  });'
			. '  content.appendChild(dis);'
			. '  _upsellBar.appendChild(content);'
			. '}'
			. '_renderUpsell(_embedLang);'
			. 'document.body.appendChild(_upsellBar);'
			. 'setTimeout(function(){'
			. 'var firstKwDrawer=document.querySelector(\'[data-avi-heatmap-kw-list="drawer"] .avi-heatmap-keyword\');'
			. 'var activeKwDrawer=document.querySelector(\'[data-avi-heatmap-kw-list="drawer"] .avi-heatmap-keyword.is-selected\');'
			. 'var kwTarget=activeKwDrawer||firstKwDrawer;'
			. 'if(kwTarget)kwTarget.click();'
			. '},800);'
			. 'var _layout=document.querySelector(".avi-heatmap-modal-layout");'
			. 'var _map=document.querySelector(".avi-heatmap-modal-map");'
			. 'var _stats=document.querySelector(".avi-heatmap-modal-map-stats");'
			. 'if(_stats)_stats.style.gridTemplateColumns="1fr";'
			. 'document.addEventListener("click",function(e){'
			. 'var tab=e.target.closest("[data-avi-heatmap-tab]");'
			. 'if(!tab||!_layout)return;'
			. 'var target=tab.getAttribute("data-avi-heatmap-tab");'
			. 'if(target==="map"){'
			. 'setTimeout(function(){'
			. '_layout.style.setProperty("grid-template-columns","340px minmax(0,1fr)","important");'
			. 'if(_map)_map.style.setProperty("grid-column","2","important");'
			. '},50);'
			. '}else{'
			. 'setTimeout(function(){'
			. '_layout.style.setProperty("grid-template-columns","1fr","important");'
			. 'if(_map)_map.style.setProperty("grid-column","1","important");'
			. '},50);'
			. '}'
			. '});'
			. 'function _initEmbedLocationPicker(){'
			. 'if(window.aviEmbedGbpConnected)return;'
			. 'var pending=window.aviEmbedPendingLocations;'
			. 'if(!pending||!pending.locations||!pending.locations.length)return;'
			. 'if(document.getElementById("aviPickerOverlay"))return;'
			. 'var _obConflict=document.getElementById("aviOnboardingOverlay");'
			. 'if(_obConflict)_obConflict.remove();'
			. 'var _tP=(_embedI18n&&_embedI18n[_embedLang])||_embedI18n.en;'
			. 'var _isAgency=window.aviEmbedKeyType==="agency";'
			. 'var overlay=document.createElement("div");'
			. 'overlay.id="aviPickerOverlay";'
			. 'overlay.style.cssText="position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:9999;display:flex;align-items:center;justify-content:center;padding:16px;";'
			. 'var locs=pending.locations;'
			. 'var items=locs.map(function(l,i){'
			. 'if(_isAgency){'
			. 'return "<label class=\"avi-picker-item avi-picker-item--agency\" style=\"display:flex;align-items:flex-start;gap:10px;padding:12px 16px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;cursor:pointer;font-size:14px;margin-bottom:4px;\">"'
			. '+"<input type=\"checkbox\" class=\"avi-picker-cb\" data-fn=\""+l.location_full_name+"\" data-title=\""+(l.title||"")+"\" style=\"margin-top:3px;flex-shrink:0;\">"'
			. '+"<span><strong>"+(l.title||"Sans nom")+"</strong>"'
			. '+(l.address?"<br><span style=\"font-size:12px;color:#6b7280;\">"+l.address+"</span>":"")+'
			. '"</span></label>";'
			. '}else{'
			. 'return "<button type=\"button\" class=\"avi-picker-item\" data-fn=\""+l.location_full_name+"\" data-title=\""+(l.title||"")+"\">"'
			. '+"<strong>"+(l.title||"Sans nom")+"</strong>"'
			. '+(l.address?"<br><span style=\"font-size:12px;color:#6b7280;\">"+l.address+"</span>":"")+'
			. '"</button>";'
			. '}'
			. '}).join("");'
			. 'var _selectAllHtml=_isAgency?"<label style=\"display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;color:#374151;margin-bottom:12px;cursor:pointer;\"><input type=\"checkbox\" id=\"aviPickerSelectAll\"> "+(_tP.picker_select_all||"Select all")+"</label>":"";'
			. 'var _importBtnHtml=_isAgency?"<button type=\"button\" id=\"aviPickerImportBtn\" style=\"width:100%;margin-top:16px;padding:12px;background:#f97316;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:600;cursor:pointer;\">"+(_tP.picker_import||"Import selected listings")+"</button>":"";'
			. 'overlay.innerHTML="<div style=\"background:#fff;border-radius:14px;padding:32px;max-width:480px;width:100%;max-height:80vh;overflow-y:auto;\">"'
			. '+"<h2 style=\"font-size:18px;font-weight:700;margin-bottom:8px;\">"+(_tP.picker_title||"Choose your listing")+"</h2>"'
			. '+"<p style=\"font-size:14px;color:#6b7280;margin-bottom:20px;\">"+(_tP.picker_subtitle||"Select the listing to manage.")+"</p>"'
			. '+_selectAllHtml'
			. '+"<div id=\"aviPickerList\" style=\"display:flex;flex-direction:column;gap:4px;\">"+items+"</div>"'
			. '+_importBtnHtml'
			. '+"<p id=\"aviPickerError\" style=\"color:#dc2626;font-size:13px;margin-top:12px;display:none;\"></p>"'
			. '+"</div>";'
			. 'document.body.appendChild(overlay);'
			. 'if(_isAgency){'
			. '/* Select All */'
			. 'var _saAll=document.getElementById("aviPickerSelectAll");'
			. 'if(_saAll)_saAll.addEventListener("change",function(){'
			. 'overlay.querySelectorAll(".avi-picker-cb").forEach(function(cb){cb.checked=_saAll.checked;});'
			. '});'
			. '/* Import button */'
			. 'var _importBtn=document.getElementById("aviPickerImportBtn");'
			. 'if(_importBtn)_importBtn.addEventListener("click",function(){'
			. 'var _selected=[];'
			. 'overlay.querySelectorAll(".avi-picker-cb:checked").forEach(function(cb){'
			. '_selected.push({location_full_name:cb.getAttribute("data-fn"),title:cb.getAttribute("data-title")});'
			. '});'
			. 'if(!_selected.length){var err=document.getElementById("aviPickerError");if(err){err.textContent="Please select at least one listing.";err.style.display="block";}return;}'
			. '_importBtn.disabled=true;_importBtn.textContent=_tP.picker_loading||"Importing...";'
			. 'fetch(window.aviEmbedRestUrl+"embed/choose-locations-bulk",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({key_id:window.aviEmbedKeyId,profile_id:window.aviEmbedProfileId,agency_id:window.aviEmbedAgencyId,locations:_selected})'
			. '}).then(function(r){return r.json();}).then(function(d){'
			. 'if(d.ok){'
			. 'window.aviEmbedPendingLocations=null;'
			. 'document.body.removeChild(overlay);'
			. 'location.reload();'
			. '}else{'
			. 'var err=document.getElementById("aviPickerError");'
			. 'if(err){err.textContent=_tP.picker_error||"Error. Please try again.";err.style.display="block";}'
			. '_importBtn.disabled=false;_importBtn.textContent=_tP.picker_import||"Import selected listings";'
			. '}'
			. '}).catch(function(){'
			. 'var err=document.getElementById("aviPickerError");'
			. 'if(err){err.textContent=_tP.picker_error||"Error. Please try again.";err.style.display="block";}'
			. '_importBtn.disabled=false;'
			. '});'
			. '});'
			. '}else{'
			. 'overlay.querySelectorAll(".avi-picker-item").forEach(function(btn){'
			. 'btn.style.cssText="width:100%;text-align:left;padding:12px 16px;border:1px solid #e5e7eb;border-radius:8px;background:#fff;cursor:pointer;font-size:14px;";'
			. 'btn.addEventListener("click",function(){'
			. 'var fn=btn.getAttribute("data-fn");'
			. 'var ttl=btn.getAttribute("data-title");'
			. 'btn.textContent=_tP.picker_loading||"Connecting...";'
			. 'btn.disabled=true;'
			. 'fetch(window.aviEmbedRestUrl+"embed/choose-location",{'
			. 'method:"POST",'
			. 'headers:{"Content-Type":"application/json","X-Embed-Token":window.aviEmbedToken},'
			. 'body:JSON.stringify({key_id:window.aviEmbedKeyId,profile_id:window.aviEmbedProfileId,location_full_name:fn,title:ttl})'
			. '}).then(function(r){return r.json();}).then(function(d){'
			. 'if(d.ok){'
			. 'window.aviEmbedGbpConnected=true;'
			. 'window.aviEmbedPendingLocations=null;'
			. 'document.body.removeChild(overlay);'
			. 'location.reload();'
			. '}else{'
			. 'var err=document.getElementById("aviPickerError");'
			. 'if(err){err.textContent=_tP.picker_error||"Error. Please try again.";err.style.display="block";}'
			. 'btn.disabled=false;'
			. 'btn.textContent=ttl;'
			. '}'
			. '}).catch(function(){'
			. 'var err=document.getElementById("aviPickerError");'
			. 'if(err){err.textContent=_tP.picker_error||"Error. Please try again.";err.style.display="block";}'
			. 'btn.disabled=false;'
			. '});'
			. '});'
			. '});'
			. '}'
			. '}'
			. 'function _initEmbedOnboarding(){'
			. 'if(window.aviEmbedGbpConnected||window.aviEmbedHasGoogleToken)return;'
			. 'if(window.aviEmbedScoreData&&window.aviEmbedScoreData.google_location_name)return;'
			. 'var _pendingPick=window.aviEmbedPendingLocations;'
			. 'if(_pendingPick&&_pendingPick.locations&&_pendingPick.locations.length){'
			. 'return;'
			. '}'
			. 'if(document.getElementById("aviOnboardingOverlay"))return;'
			. 'var _tOb=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _ob=document.createElement("div");'
			. '_ob.id="aviOnboardingOverlay";'
			. '_ob.className="avi-onboarding-overlay";'
			. '_ob.innerHTML=\'<div class="avi-onboarding-modal">\''
			. '+\'<div class="avi-onboarding-logo">\\uD83D\\uDCCD</div>\''
			. '+\'<h2 class="avi-onboarding-title">\'+(_tOb.onboarding_title||"Connect GBP")+\'</h2>\''
			. '+\'<p class="avi-onboarding-subtitle">\'+(_tOb.onboarding_subtitle||"")+\'</p>\''
			. '+\'<div class="avi-onboarding-steps">\''
			. '+\'<div class="avi-onboarding-step">\''
			. '+\'<div class="avi-onboarding-step-icon">\\uD83D\\uDD11</div>\''
			. '+\'<div class="avi-onboarding-step-title">\'+(_tOb.onboarding_step1_title||"1.")+\'</div>\''
			. '+\'<div>\'+(_tOb.onboarding_step1_desc||"")+\'</div></div>\''
			. '+\'<div class="avi-onboarding-step">\''
			. '+\'<div class="avi-onboarding-step-icon">\\uD83C\\uDFE2</div>\''
			. '+\'<div class="avi-onboarding-step-title">\'+(_tOb.onboarding_step2_title||"2.")+\'</div>\''
			. '+\'<div>\'+(_tOb.onboarding_step2_desc||"")+\'</div></div>\''
			. '+\'<div class="avi-onboarding-step">\''
			. '+\'<div class="avi-onboarding-step-icon">\\u2705</div>\''
			. '+\'<div class="avi-onboarding-step-title">\'+(_tOb.onboarding_step3_title||"3.")+\'</div>\''
			. '+\'<div>\'+(_tOb.onboarding_step3_desc||"")+\'</div></div></div>\''
			. '+\'<a href="\'+(window.aviEmbedConnectUrl||"https://avision.org/connect")+\'" \''
			. '+\'target="_blank" rel="noopener noreferrer" \''
			. '+\'class="avi-onboarding-connect-btn">\''
			. '+(_tOb.onboarding_connect||"\\uD83D\\uDD17 Connect Google Business")'
			. '+\'</a>\''
			. '+\'<span class="avi-onboarding-skip" id="aviOnboardingSkip">\''
			. '+(_tOb.onboarding_skip||"I\\u0027ll do this later")'
			. '+\'</span></div>\';'
			. 'document.body.appendChild(_ob);'
			. 'var _skipBtn=document.getElementById("aviOnboardingSkip");'
			. 'if(_skipBtn){'
			. '_skipBtn.addEventListener("click",function(){'
			. '_ob.style.display="none";'
			. 'try{sessionStorage.setItem("avi_onboarding_skipped","1");}catch(e){}'
			. '});'
			. '}'
			. 'try{'
			. 'if(sessionStorage.getItem("avi_onboarding_skipped")==="1"){'
			. '_ob.style.display="none";'
			. '}'
			. '}catch(e){}'
			. '}'
			. 'function _openEduModal(){'
			. 'var _t=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+(_t.edu_modal_title||"How it works")+\'</div>\''
			. '+\'<div class="avi-edu-step">\''
			. '+\'<div class="avi-edu-step-title">\'+(_t.edu_step1_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step-body">\'+(_t.edu_step1_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step">\''
			. '+\'<div class="avi-edu-step-title">\'+(_t.edu_step2_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step-body">\'+(_t.edu_step2_body||"")+\'</div></div>\''
			. '+\'<div class="avi-edu-step">\''
			. '+\'<div class="avi-edu-step-title">\'+(_t.edu_step3_title||"")+\'</div>\''
			. '+\'<div class="avi-edu-step-body">\'+(_t.edu_step3_body||"")+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviEduModalClose">\''
			. '+(_t.edu_banner_close||"Got it \\u2713")+\'</button></div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(e){'
			. 'if(e.target===backdrop)backdrop.remove();'
			. '});'
			. 'document.getElementById("aviEduModalClose")'
			. '.addEventListener("click",function(){backdrop.remove();});'
			. '}'
			. 'function _openInfoModal(title, body){'
			. 'var backdrop=document.createElement("div");'
			. 'backdrop.className="avi-edu-modal-backdrop";'
			. 'backdrop.innerHTML='
			. '\'<div class="avi-edu-modal">\''
			. '+\'<div class="avi-edu-modal-title">\'+title+\'</div>\''
			. '+\'<div class="avi-edu-step"><div class="avi-edu-step-body">\'+body+\'</div></div>\''
			. '+\'<button type="button" class="avi-edu-modal-close" id="aviInfoModalClose">\''
			. '+((_embedI18n[_embedLang]||_embedI18n.en).edu_banner_close||"Got it \\u2713")'
			. '+\'</button></div>\';'
			. 'document.body.appendChild(backdrop);'
			. 'backdrop.addEventListener("click",function(e){if(e.target===backdrop)backdrop.remove();});'
			. 'document.getElementById("aviInfoModalClose")'
			. '.addEventListener("click",function(){backdrop.remove();});'
			. '}'
			. 'function _initEduTipsBtn(){'
			. 'if(document.getElementById("aviEduTipsBtn"))return;'
			. 'var _tEdu=_embedI18n[_embedLang]||_embedI18n.en;'
			. 'var _eduBtn=document.createElement("button");'
			. '_eduBtn.id="aviEduTipsBtn";'
			. '_eduBtn.type="button";'
			. '_eduBtn.className="avi-edu-tips-btn";'
			. '_eduBtn.title=_tEdu.edu_modal_title||"How it works";'
			. '_eduBtn.textContent=_tEdu.edu_help_btn||"💡";'
			. 'document.body.appendChild(_eduBtn);'
			. '_eduBtn.addEventListener("click",_openEduModal);'
			. '}'
			. '_initEduTipsBtn();'
			. '_initEmbedLocationPicker();'
			. '_initEmbedOnboarding();'
			. 'var _embedTokenExpiry=Date.now()+6300000;'
			. 'var _embedRefreshInterval=setInterval(function(){'
			. 'if(Date.now()<_embedTokenExpiry)return;'
			. 'clearInterval(_embedRefreshInterval);'
			. 'window.location.reload();'
			. '},60000);'
			. '});'
			. 'document.addEventListener("DOMContentLoaded",function(){'
			. 'var _bootScanDone=false;'
			. 'setTimeout(function(){'
			. 'if(_bootScanDone)return;'
			. '_bootScanDone=true;'
			. 'var firstKw=document.querySelector("[data-avi-heatmap-modal-keyword]:not(.is-selected), .avi-heatmap-modal-keyword:not(.is-selected)");'
			. 'var activeKw=document.querySelector("[data-avi-heatmap-modal-keyword].is-selected, .avi-heatmap-modal-keyword.is-selected");'
			. 'var target=activeKw||firstKw;'
			. 'if(target){'
			. 'setTimeout(function(){'
			. 'target.click();'
			. 'console.log("[Avision Embed] Boot scan triggered for competitors");'
			. '},1200);'
			. '}'
			. '},100);'
			. '});'
			. '</script>'
			. '</body></html>';

		header( 'Content-Type: text/html; charset=UTF-8' );
		header( 'X-Frame-Options: ALLOWALL' );
		header( 'Content-Security-Policy: frame-ancestors *' );
		echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML module heatmap déjà échappé.
		exit;
	}

	/**
	 * Vérifie le token embed pour les endpoints POST (reply-review).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return bool|\WP_Error
	 */
	public static function verify_embed_request( \WP_REST_Request $request ) {
		$token = $request->get_header( 'X-Embed-Token' );
		if ( $token === '' || $token === null ) {
			return new \WP_Error( 'unauthorized', 'Invalid embed token', array( 'status' => 403 ) );
		}
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}
		$profile_id = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$key_id     = sanitize_text_field( isset( $body['key_id'] ) ? (string) $body['key_id'] : '' );
		if ( ! $profile_id ) {
			$profile_id = absint( $request->get_param( 'profile_id' ) );
		}
		if ( $key_id === '' ) {
			$key_id = sanitize_text_field( (string) $request->get_param( 'key_id' ) );
		}
		if ( ! $profile_id ) {
			return new \WP_Error( 'unauthorized', 'Invalid embed token', array( 'status' => 403 ) );
		}
		if ( self::verify_embed_token( (string) $token, $profile_id, $key_id ) ) {
			return true;
		}
		return new \WP_Error( 'unauthorized', 'Invalid embed token', array( 'status' => 403 ) );
	}

	/**
	 * Assigne des crédits du pool agence vers un profil client.
	 * #SprintL2-L2.3-assign-credits
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function assign_credits( \WP_REST_Request $request ) {
		global $wpdb;

		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}
		$key_id     = sanitize_text_field(
			isset( $body['key_id'] ) ? (string) $body['key_id'] : (string) $request->get_param( 'key_id' )
		);
		$target_profile_id = absint(
			isset( $body['target_profile_id'] ) ? $body['target_profile_id'] : 0
		);
		$qty        = absint(
			isset( $body['qty'] ) ? $body['qty'] : $request->get_param( 'qty' )
		);

		if ( ! $target_profile_id ) {
			return new \WP_Error(
				'missing_target',
				'Missing target profile',
				array( 'status' => 400 )
			);
		}

		if ( $qty < 10 || $qty > 10000 || ( $qty % 10 ) !== 0 ) {
			return new \WP_Error(
				'invalid_qty',
				'Minimum 10 credits, in multiples of 10',
				array( 'status' => 400 )
			);
		}

		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT agency_id FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND status = 'active' LIMIT 1",
				$key_id
			)
		);
		if ( ! $key_row || empty( $key_row->agency_id ) ) {
			return new \WP_Error( 'not_agency', 'Not an agency key', array( 'status' => 403 ) );
		}
		$agency_id = (int) $key_row->agency_id;

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id, agency_id FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d AND agency_id = %d LIMIT 1",
				$target_profile_id,
				$agency_id
			)
		);
		if ( ! $profile ) {
			return new \WP_Error( 'forbidden', 'Profile not in agency', array( 'status' => 403 ) );
		}

		$pool = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT credits_total, COALESCE(credits_bonus, 0) AS credits_bonus,
				        credits_used, COALESCE(credits_refunded, 0) AS credits_refunded
				 FROM `{$wpdb->prefix}avi_heatmap_credits`
				 WHERE owner_type = 'agency' AND agency_id = %d
				 LIMIT 1",
				$agency_id
			)
		);
		if ( ! $pool ) {
			return new \WP_Error( 'no_pool', 'No credit pool found', array( 'status' => 404 ) );
		}

		$available = (int) $pool->credits_total + (int) $pool->credits_bonus
			- (int) $pool->credits_used + (int) $pool->credits_refunded;

		if ( $qty > $available ) {
			return new \WP_Error(
				'insufficient',
				'Insufficient credits in pool (available: ' . $available . ')',
				array( 'status' => 400 )
			);
		}

		$pool_debited = $wpdb->query(
			$wpdb->prepare(
				"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
				 SET credits_used = credits_used + %d
				 WHERE owner_type = 'agency' AND agency_id = %d",
				$qty,
				$agency_id
			)
		);
		if ( false === $pool_debited ) {
			return new \WP_Error( 'pool_debit_failed', 'Failed to debit agency pool', array( 'status' => 500 ) );
		}

		$client_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id, credits_total FROM `{$wpdb->prefix}avi_heatmap_credits`
				 WHERE owner_type = 'profile' AND profile_id = %d
				 LIMIT 1",
				$target_profile_id
			)
		);
		$client_credited = false;
		if ( $client_row ) {
			$client_credited = $wpdb->query(
				$wpdb->prepare(
					"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
					 SET credits_total = credits_total + %d
					 WHERE owner_type = 'profile' AND profile_id = %d",
					$qty,
					$target_profile_id
				)
			);
		} else {
			$client_credited = $wpdb->insert(
				$wpdb->prefix . 'avi_heatmap_credits',
				array(
					'owner_type'    => 'profile',
					'profile_id'    => $target_profile_id,
					'credits_total' => $qty,
					'credits_used'  => 0,
				),
				array( '%s', '%d', '%d', '%d' )
			);
		}

		if ( false === $client_credited ) {
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
					 SET credits_used = GREATEST( 0, credits_used - %d )
					 WHERE owner_type = 'agency' AND agency_id = %d",
					$qty,
					$agency_id
				)
			);
			return new \WP_Error(
				'client_credit_failed',
				'Failed to credit client profile — pool refunded',
				array( 'status' => 500 )
			);
		}

		$new_available = $available - $qty;

		return rest_ensure_response(
			array(
				'success'        => true,
				'assigned'       => $qty,
				'pool_available' => $new_available,
			)
		);
	}

	/**
	 * Assigne des crédits du pool agence vers plusieurs profils clients.
	 * #SprintL2-L2.3-bulk-fix
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function assign_credits_bulk( \WP_REST_Request $request ) {
		global $wpdb;

		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}
		$key_id = sanitize_text_field(
			isset( $body['key_id'] ) ? (string) $body['key_id'] : (string) $request->get_param( 'key_id' )
		);
		$target_ids = isset( $body['target_profile_ids'] ) ? $body['target_profile_ids'] : array();
		$qty        = absint(
			isset( $body['qty'] ) ? $body['qty'] : $request->get_param( 'qty' )
		);

		if ( ! is_array( $target_ids ) || empty( $target_ids ) ) {
			return new \WP_Error( 'invalid', 'No profiles selected', array( 'status' => 400 ) );
		}

		if ( $qty < 10 || $qty > 10000 || ( $qty % 10 ) !== 0 ) {
			return new \WP_Error(
				'invalid_qty',
				'Minimum 10 credits, in multiples of 10',
				array( 'status' => 400 )
			);
		}

		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT agency_id FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND status = 'active' LIMIT 1",
				$key_id
			)
		);
		if ( ! $key_row || empty( $key_row->agency_id ) ) {
			return new \WP_Error( 'not_agency', 'Not an agency key', array( 'status' => 403 ) );
		}
		$agency_id = (int) $key_row->agency_id;

		$clean_ids = array();
		foreach ( $target_ids as $tid ) {
			$tid = absint( $tid );
			if ( $tid > 0 ) {
				$clean_ids[] = $tid;
			}
		}
		$clean_ids = array_values( array_unique( $clean_ids ) );
		if ( empty( $clean_ids ) ) {
			return new \WP_Error( 'invalid', 'Invalid profile IDs', array( 'status' => 400 ) );
		}

		$placeholders = implode( ',', array_fill( 0, count( $clean_ids ), '%d' ) );
		$valid_sql    = "SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_profiles`
			WHERE id IN ($placeholders) AND agency_id = %d";
		$valid_args   = array_merge( $clean_ids, array( $agency_id ) );
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- placeholders built from intval IDs.
		$valid_count  = (int) $wpdb->get_var( $wpdb->prepare( $valid_sql, ...$valid_args ) );
		if ( $valid_count !== count( $clean_ids ) ) {
			return new \WP_Error(
				'forbidden',
				'Some profiles do not belong to this agency',
				array( 'status' => 403 )
			);
		}

		$pool = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT credits_total, COALESCE(credits_bonus, 0) AS credits_bonus,
				        credits_used, COALESCE(credits_refunded, 0) AS credits_refunded
				 FROM `{$wpdb->prefix}avi_heatmap_credits`
				 WHERE owner_type = 'agency' AND agency_id = %d
				 LIMIT 1",
				$agency_id
			)
		);
		if ( ! $pool ) {
			return new \WP_Error( 'no_pool', 'No credit pool found', array( 'status' => 404 ) );
		}

		$available = (int) $pool->credits_total + (int) $pool->credits_bonus
			- (int) $pool->credits_used + (int) $pool->credits_refunded;
		$qty_total = $qty * count( $clean_ids );

		if ( $qty_total > $available ) {
			return new \WP_Error(
				'insufficient',
				'Insufficient credits. Need ' . $qty_total . ', available: ' . $available,
				array( 'status' => 400 )
			);
		}

		$pool_debited = $wpdb->query(
			$wpdb->prepare(
				"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
				 SET credits_used = credits_used + %d
				 WHERE owner_type = 'agency' AND agency_id = %d",
				$qty_total,
				$agency_id
			)
		);
		if ( false === $pool_debited ) {
			return new \WP_Error( 'pool_debit_failed', 'Failed to debit agency pool', array( 'status' => 500 ) );
		}

		$results = array();
		$failed  = 0;
		foreach ( $clean_ids as $tid ) {
			$exists = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT id FROM `{$wpdb->prefix}avi_heatmap_credits`
					 WHERE owner_type = 'profile' AND profile_id = %d
					 LIMIT 1",
					$tid
				)
			);
			if ( $exists ) {
				$ok = $wpdb->query(
					$wpdb->prepare(
						"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
						 SET credits_total = credits_total + %d
						 WHERE owner_type = 'profile' AND profile_id = %d",
						$qty,
						$tid
					)
				);
			} else {
				$ok = $wpdb->insert(
					$wpdb->prefix . 'avi_heatmap_credits',
					array(
						'owner_type'    => 'profile',
						'profile_id'    => $tid,
						'credits_total' => $qty,
						'credits_used'  => 0,
					),
					array( '%s', '%d', '%d', '%d' )
				);
			}
			if ( false === $ok ) {
				++$failed;
				$results[] = array(
					'profile_id' => $tid,
					'success'    => false,
				);
			} else {
				$results[] = array(
					'profile_id' => $tid,
					'success'    => true,
				);
			}
		}

		if ( $failed > 0 ) {
			$refund = $failed * $qty;
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
					 SET credits_used = GREATEST( 0, credits_used - %d )
					 WHERE owner_type = 'agency' AND agency_id = %d",
					$refund,
					$agency_id
				)
			);
		}

		$new_available = $available - $qty_total + ( $failed * $qty );

		return rest_ensure_response(
			array(
				'success'         => ( 0 === $failed ),
				'assigned_count'  => count( $clean_ids ) - $failed,
				'qty_per_profile' => $qty,
				'pool_available'  => $new_available,
				'results'         => $results,
			)
		);
	}

	/**
	 * Met à jour logo_url et white_label_name d'une clé embed active.
	 * #SprintL2-L2.4-whitelabel
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function update_embed_key( \WP_REST_Request $request ) {
		global $wpdb;
		$key_id   = sanitize_text_field( $request->get_param( 'key_id' ) );
		$logo_url = esc_url_raw( $request->get_param( 'logo_url' ) ?: '' );
		$wl_name  = sanitize_text_field( $request->get_param( 'white_label_name' ) ?: '' );

		if ( empty( $key_id ) ) {
			return new \WP_Error( 'invalid', 'Missing key_id', array( 'status' => 400 ) );
		}

		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT id, status FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND status = 'active'",
				$key_id
			)
		);
		if ( ! $key_row ) {
			return new \WP_Error( 'not_found', 'Key not found', array( 'status' => 404 ) );
		}

		$wpdb->update(
			$wpdb->prefix . 'avi_embed_keys',
			array(
				'logo_url'         => $logo_url,
				'white_label_name' => $wl_name,
			),
			array( 'key_id' => $key_id )
		);

		return rest_ensure_response(
			array(
				'success'          => true,
				'logo_url'         => $logo_url,
				'white_label_name' => $wl_name,
			)
		);
	}

	/**
	 * Résout embed_key_id (BIGINT) depuis key_id string.
	 * #SprintL2-L2.2-kw-crud
	 *
	 * @param string $key_id Clé publique embed.
	 * @return int
	 */
	private static function resolve_embed_key_id( $key_id ) {
		global $wpdb;
		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND status = 'active'",
				$key_id
			)
		);
	}

	/**
	 * Liste les keywords embed pour un profil.
	 * #SprintL2-L2.2-kw-crud
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function get_embed_keywords( \WP_REST_Request $request ) {
		global $wpdb;
		$key_id     = sanitize_text_field( $request->get_param( 'key_id' ) );
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$ekid       = self::resolve_embed_key_id( $key_id );
		if ( ! $ekid ) {
			return new \WP_Error( 'not_found', 'Key not found', array( 'status' => 404 ) );
		}

		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, keyword, target_city, current_rank, previous_rank,
						best_rank, is_strategic, scan_status, last_scan_at, created_at
				 FROM `{$wpdb->prefix}avi_embed_keywords`
				 WHERE embed_key_id = %d AND profile_id = %d
				 ORDER BY created_at ASC",
				$ekid,
				$profile_id
			)
		);

		return rest_ensure_response(
			array(
				'success'  => true,
				'keywords' => $rows ? $rows : array(),
			)
		);
	}

	/**
	 * Ajoute un keyword embed.
	 * #SprintL2-L2.2-kw-crud
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function add_embed_keyword( \WP_REST_Request $request ) {
		global $wpdb;
		$key_id     = sanitize_text_field( $request->get_param( 'key_id' ) );
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$keyword    = sanitize_text_field( $request->get_param( 'keyword' ) );
		$city       = sanitize_text_field( $request->get_param( 'target_city' ) ?: '' );

		if ( empty( $keyword ) ) {
			return new \WP_Error( 'invalid', 'Keyword required', array( 'status' => 400 ) );
		}

		$ekid = self::resolve_embed_key_id( $key_id );
		if ( ! $ekid ) {
			return new \WP_Error( 'not_found', 'Key not found', array( 'status' => 404 ) );
		}

		$count = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_embed_keywords`
				 WHERE embed_key_id = %d AND profile_id = %d",
				$ekid,
				$profile_id
			)
		);
		if ( $count >= 20 ) {
			return new \WP_Error( 'limit', 'Maximum 20 keywords reached', array( 'status' => 400 ) );
		}

		$inserted = $wpdb->insert(
			$wpdb->prefix . 'avi_embed_keywords',
			array(
				'embed_key_id' => $ekid,
				'profile_id'   => $profile_id,
				'keyword'      => $keyword,
				'target_city'  => $city,
				'scan_status'  => 'pending',
			),
			array( '%d', '%d', '%s', '%s', '%s' )
		);
		if ( ! $inserted ) {
			return new \WP_Error( 'duplicate', 'Keyword already exists', array( 'status' => 409 ) );
		}

		return rest_ensure_response(
			array(
				'success'      => true,
				'id'           => $wpdb->insert_id,
				'keyword'      => $keyword,
				'target_city'  => $city,
				'scan_status'  => 'pending',
				'current_rank' => null,
			)
		);
	}

	/**
	 * Supprime un keyword embed.
	 * #SprintL2-L2.2-kw-crud
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function delete_embed_keyword( \WP_REST_Request $request ) {
		global $wpdb;
		$key_id     = sanitize_text_field( $request->get_param( 'key_id' ) );
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$id         = absint( $request->get_param( 'id' ) );
		$ekid       = self::resolve_embed_key_id( $key_id );
		if ( ! $ekid ) {
			return new \WP_Error( 'not_found', 'Key not found', array( 'status' => 404 ) );
		}

		$deleted = $wpdb->delete(
			$wpdb->prefix . 'avi_embed_keywords',
			array(
				'id'           => $id,
				'embed_key_id' => $ekid,
				'profile_id'   => $profile_id,
			),
			array( '%d', '%d', '%d' )
		);
		if ( ! $deleted ) {
			return new \WP_Error( 'not_found', 'Keyword not found', array( 'status' => 404 ) );
		}

		return rest_ensure_response(
			array(
				'success'    => true,
				'deleted_id' => $id,
			)
		);
	}

	/**
	 * Met à jour un keyword embed (pending uniquement).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function update_embed_keyword( \WP_REST_Request $request ) {
		global $wpdb;
		$key_id     = sanitize_text_field( $request->get_param( 'key_id' ) );
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$id         = absint( $request->get_param( 'id' ) );
		$keyword    = sanitize_text_field( $request->get_param( 'keyword' ) ?: '' );
		$city       = sanitize_text_field( $request->get_param( 'target_city' ) ?: '' );

		if ( ! $key_id || ! $profile_id || ! $id ) {
			return new \WP_Error( 'missing', 'Missing parameters', array( 'status' => 400 ) );
		}

		$ekid = self::resolve_embed_key_id( $key_id );
		if ( ! $ekid ) {
			return new \WP_Error( 'invalid_key', 'Invalid key', array( 'status' => 403 ) );
		}

		$current = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT scan_status, keyword, target_city
				 FROM `{$wpdb->prefix}avi_embed_keywords`
				 WHERE id = %d
				   AND embed_key_id = %d
				   AND profile_id = %d
				 LIMIT 1",
				$id,
				$ekid,
				$profile_id
			)
		);

		if ( ! $current ) {
			return new \WP_Error( 'not_found', 'Keyword not found', array( 'status' => 404 ) );
		}

		if ( $current->scan_status !== 'pending' ) {
			return new \WP_Error(
				'scan_locked',
				'Keyword already scanned — editing disabled',
				array( 'status' => 403 )
			);
		}

		$update = array();
		$format = array();

		if ( $keyword !== '' ) {
			$update['keyword'] = $keyword;
			$format[]          = '%s';
		}
		if ( $city !== '' || $request->get_param( 'target_city' ) !== null ) {
			$update['target_city'] = $city;
			$format[]              = '%s';
		}

		if ( empty( $update ) ) {
			return new \WP_Error( 'nothing', 'Nothing to update', array( 'status' => 400 ) );
		}

		$updated = $wpdb->update(
			$wpdb->prefix . 'avi_embed_keywords',
			$update,
			array(
				'id'           => $id,
				'embed_key_id' => $ekid,
				'profile_id'   => $profile_id,
			),
			$format,
			array( '%d', '%d', '%d' )
		);

		if ( $updated === false ) {
			return new \WP_Error( 'db_error', 'Update failed', array( 'status' => 500 ) );
		}

		return rest_ensure_response(
			array(
				'success'     => true,
				'id'          => $id,
				'keyword'     => $update['keyword'] ?? $current->keyword,
				'target_city' => $update['target_city'] ?? $current->target_city,
			)
		);
	}

	/**
	 * Génère une réponse à un avis via OpenRouter (embed).
	 * #SprintL2-reviews-ai
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function ai_review_reply( \WP_REST_Request $request ) {
		$profile_id  = absint( $request->get_param( 'profile_id' ) );
		$reviewer    = sanitize_text_field( $request->get_param( 'reviewer_name' ) ?: 'the customer' );
		$rating      = absint( $request->get_param( 'rating' ) ?: 5 );
		$review_text = sanitize_textarea_field( $request->get_param( 'review_text' ) ?: '' );
		$lang        = sanitize_text_field( $request->get_param( 'lang' ) ?: 'en' );
		$business    = sanitize_text_field( $request->get_param( 'business_name' ) ?: '' );

		$api_key = defined( 'OPENROUTER_API_KEY' ) ? OPENROUTER_API_KEY : getenv( 'OPENROUTER_API_KEY' );
		if ( ! $api_key ) {
			return new \WP_Error( 'no_key', 'OpenRouter not configured', array( 'status' => 500 ) );
		}

		$lang_labels = array(
			'fr'    => 'français',
			'es'    => 'español',
			'pt-br' => 'português',
			'tr'    => 'türkçe',
			'de'    => 'deutsch',
			'en'    => 'English',
		);
		$lang_label = isset( $lang_labels[ $lang ] ) ? $lang_labels[ $lang ] : 'English';

		$rating     = min( 5, max( 1, $rating ) );
		$stars      = str_repeat( '⭐', $rating );
		$review_content = ! empty( $review_text )
			? 'Review: "' . $review_text . '"'
			: '(No text — rating only)';

		$prompt = "You are a local business reputation expert. Write a professional, warm and authentic reply to this Google review in {$lang_label}.\n\n"
			. "Business: {$business}\n"
			. "Reviewer: {$reviewer}\n"
			. "Rating: {$stars} ({$rating}/5)\n"
			. "{$review_content}\n\n"
			. "Rules:\n"
			. "- Reply in {$lang_label} only\n"
			. "- Max 120 words\n"
			. "- Professional but human tone\n"
			. "- Thank the reviewer by name\n"
			. "- If negative (1-2 stars): acknowledge, apologize, invite to contact privately\n"
			. "- If positive (4-5 stars): thank warmly, reinforce brand\n"
			. "- Never mention competitors\n"
			. "- No hashtags, no emojis\n"
			. "- Output ONLY the reply text, nothing else";

		$response = wp_remote_post(
			'https://openrouter.ai/api/v1/chat/completions',
			array(
				'timeout' => 30,
				'headers' => array(
					'Authorization' => 'Bearer ' . $api_key,
					'Content-Type'  => 'application/json',
					'HTTP-Referer'  => home_url(),
				),
				'body'    => wp_json_encode(
					array(
						'model'       => 'google/gemini-2.5-flash-lite',
						'messages'    => array(
							array(
								'role'    => 'user',
								'content' => $prompt,
							),
						),
						'max_tokens'  => 200,
						'temperature' => 0.7,
					)
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_Error( 'ai_error', $response->get_error_message(), array( 'status' => 502 ) );
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		$text = isset( $body['choices'][0]['message']['content'] )
			? trim( (string) $body['choices'][0]['message']['content'] )
			: '';

		if ( empty( $text ) ) {
			return new \WP_Error( 'ai_empty', 'No response from AI', array( 'status' => 502 ) );
		}

		return rest_ensure_response(
			array(
				'success' => true,
				'reply'   => $text,
			)
		);
	}

	/**
	 * Publie une réponse à un avis Google via l'API GBP (token en transient).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function reply_to_review( \WP_REST_Request $request ) {
		global $wpdb;
		$body        = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}
		$profile_id  = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$review_name = isset( $body['review_name'] ) ? sanitize_text_field( $body['review_name'] ) : '';
		$reply_text  = isset( $body['reply_text'] ) ? sanitize_textarea_field( $body['reply_text'] ) : '';

		if ( ! $profile_id || ! $review_name || ! $reply_text ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Missing parameters',
				),
				400
			);
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_refresh_token, google_location_name,
				        google_token_expires_at
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile || empty( $profile->google_location_name ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Profile not found or Google location not set',
				),
				404
			);
		}

		if ( empty( $profile->google_access_token ) && empty( $profile->google_refresh_token ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Google not connected',
				),
				401
			);
		}

		$needs_refresh = false;
		if ( ! empty( $profile->google_token_expires_at ) ) {
			$exp_ts = strtotime( (string) $profile->google_token_expires_at );
			if ( $exp_ts && $exp_ts < time() + 60 ) {
				$needs_refresh = true;
			}
		}
		if ( $needs_refresh ) {
			if ( class_exists( 'Avision_API' ) ) {
				\Avision_API::refresh_google_token( $profile_id );
			} elseif ( class_exists( 'Avision_Database' ) ) {
				$db = new \Avision_Database();
				$db->refresh_google_access_token_if_needed( $profile_id, true );
			}
			$profile = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT google_access_token, google_refresh_token, google_location_name,
					        google_token_expires_at
					 FROM `{$wpdb->prefix}avi_saas_profiles`
					 WHERE id = %d LIMIT 1",
					$profile_id
				)
			);
		}

		$access_token = $profile && ! empty( $profile->google_access_token )
			? $profile->google_access_token
			: '';
		if ( $access_token === '' ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Google not connected',
				),
				401
			);
		}

		$reply_url = 'https://mybusiness.googleapis.com/v4/'
			. $review_name . '/reply';
		$response  = wp_remote_request(
			$reply_url,
			array(
				'method'  => 'PUT',
				'headers' => array(
					'Authorization' => 'Bearer ' . $access_token,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode( array( 'comment' => $reply_text ) ),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => $response->get_error_message(),
				),
				500
			);
		}

		$code = wp_remote_retrieve_response_code( $response );
		if ( $code === 200 ) {
			return new \WP_REST_Response(
				array(
					'success' => true,
					'message' => 'Reply published',
				),
				200
			);
		}

		$body_resp = wp_remote_retrieve_body( $response );
		return new \WP_REST_Response(
			array(
				'success' => false,
				'message' => 'Google API error: ' . $body_resp,
			),
			$code
		);
	}

	/**
	 * Met à jour un champ GBP via Business Information API (PATCH).
	 * #SprintL2-L2.8-update-gbp-route
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function update_gbp_field( \WP_REST_Request $request ) {
		global $wpdb;

		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$field      = isset( $body['field'] ) ? sanitize_text_field( (string) $body['field'] ) : '';
		$value      = isset( $body['value'] ) ? $body['value'] : null;

		if ( ! $profile_id || $field === '' || $value === null ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Missing parameters',
				),
				400
			);
		}

		$allowed_fields = array( 'name', 'website', 'phone', 'description', 'address', 'hours', 'categories', 'openInfo' );
		if ( ! in_array( $field, $allowed_fields, true ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Field not allowed',
				),
				400
			);
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_refresh_token, google_location_name,
				        google_token_expires_at
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile || empty( $profile->google_location_name ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Profile not found or Google location not set',
				),
				404
			);
		}

		if ( empty( $profile->google_access_token ) && empty( $profile->google_refresh_token ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Google not connected',
				),
				401
			);
		}

		$needs_refresh = false;
		if ( ! empty( $profile->google_token_expires_at ) ) {
			$exp_ts = strtotime( (string) $profile->google_token_expires_at );
			if ( $exp_ts && $exp_ts < time() + 60 ) {
				$needs_refresh = true;
			}
		}
		if ( $needs_refresh ) {
			if ( class_exists( 'Avision_API' ) ) {
				\Avision_API::refresh_google_token( $profile_id );
			} elseif ( class_exists( 'Avision_Database' ) ) {
				$db = new \Avision_Database();
				$db->refresh_google_access_token_if_needed( $profile_id, true );
			}
			$profile = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT google_access_token, google_refresh_token, google_location_name,
					        google_token_expires_at
					 FROM `{$wpdb->prefix}avi_saas_profiles`
					 WHERE id = %d LIMIT 1",
					$profile_id
				)
			);
		}

		$access_token = $profile && ! empty( $profile->google_access_token )
			? $profile->google_access_token
			: '';
		if ( $access_token === '' ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Google not connected',
				),
				401
			);
		}

		$location_name = ltrim( (string) $profile->google_location_name, '/' );
		$gbp_base      = 'https://mybusinessbusinessinformation.googleapis.com/v1/';
		$headers       = array(
			'Authorization' => 'Bearer ' . $access_token,
			'Content-Type'  => 'application/json',
		);

		$update_mask = '';
		$patch_body  = array();

		if ( $field === 'name' ) {
			$update_mask = 'title';
			$patch_body  = array( 'title' => sanitize_text_field( (string) $value ) );
		} elseif ( $field === 'website' ) {
			$update_mask = 'websiteUri';
			$patch_body  = array( 'websiteUri' => esc_url_raw( (string) $value ) );
		} elseif ( $field === 'phone' ) {
			$phone_raw   = sanitize_text_field( (string) $value );
			$phone_clean = preg_replace( '/[\s\-\.\(\)]/', '', $phone_raw );
			if ( substr( $phone_clean, 0, 1 ) !== '+' ) {
				$phone_clean = '+' . $phone_clean;
			}
			if ( ! preg_match( '/^\+[1-9]\d{6,14}$/', $phone_clean ) ) {
				return new \WP_Error(
					'invalid_phone',
					'Phone must be in E.164 format (e.g. +33612345678)',
					array( 'status' => 400 )
				);
			}
			$update_mask = 'phoneNumbers';
			$patch_body  = array(
				'phoneNumbers' => array(
					'primaryPhone' => $phone_clean,
				),
			);
		} elseif ( $field === 'description' ) {
			$update_mask = 'profile.description';
			$patch_body  = array(
				'profile' => array(
					'description' => sanitize_textarea_field( (string) $value ),
				),
			);
		} elseif ( $field === 'address' ) {
			$update_mask = 'storefrontAddress';
			$addr        = is_array( $value ) ? $value : array();
			$addr_lines  = array();
			if ( isset( $addr['addressLines'] ) && is_array( $addr['addressLines'] ) ) {
				foreach ( $addr['addressLines'] as $line ) {
					$line = sanitize_text_field( (string) $line );
					if ( $line !== '' ) {
						$addr_lines[] = $line;
					}
				}
			}
			$patch_body = array(
				'storefrontAddress' => array(
					'addressLines'       => $addr_lines,
					'locality'           => isset( $addr['locality'] )
						? sanitize_text_field( (string) $addr['locality'] ) : '',
					'sublocality'        => isset( $addr['sublocality'] )
						? sanitize_text_field( (string) $addr['sublocality'] ) : '',
					'administrativeArea' => isset( $addr['region'] )
						? sanitize_text_field( (string) $addr['region'] ) : '',
					'postalCode'         => isset( $addr['postal'] )
						? sanitize_text_field( (string) $addr['postal'] ) : '',
					'regionCode'         => isset( $addr['country'] )
						? sanitize_text_field( (string) $addr['country'] ) : '',
				),
			);
		} elseif ( $field === 'hours' ) {
			$update_mask = 'regularHours';
			$periods     = is_array( $value ) ? $value : array();
			$clean       = array();
			foreach ( $periods as $p ) {
				if ( ! is_array( $p ) || empty( $p['openDay'] ) ) {
					continue;
				}
				$clean[] = array(
					'openDay'   => sanitize_text_field( (string) $p['openDay'] ),
					'openTime'  => sanitize_text_field( isset( $p['openTime'] ) ? (string) $p['openTime'] : '' ),
					'closeTime' => sanitize_text_field( isset( $p['closeTime'] ) ? (string) $p['closeTime'] : '' ),
				);
			}
			$patch_body = array(
				'regularHours' => array(
					'periods' => $clean,
				),
			);
		} elseif ( $field === 'categories' ) {
			$update_mask = 'categories';
			$cats        = is_array( $value ) ? $value : array();
			$primary     = isset( $cats['primary'] )
				? sanitize_text_field( (string) $cats['primary'] ) : '';
			$additional  = isset( $cats['additional'] ) && is_array( $cats['additional'] )
				? $cats['additional'] : array();
			$add_clean   = array();
			foreach ( $additional as $cat ) {
				$cat = sanitize_text_field( (string) $cat );
				if ( $cat !== '' ) {
					$add_clean[] = array( 'name' => $cat );
				}
			}
			$patch_body = array(
				'categories' => array(
					'primaryCategory'      => array( 'name' => $primary ),
					'additionalCategories' => $add_clean,
				),
			);
		}

		$url      = $gbp_base . $location_name . '?updateMask=' . rawurlencode( $update_mask );
		$response = wp_remote_request(
			$url,
			array(
				'method'  => 'PATCH',
				'headers' => $headers,
				'body'    => wp_json_encode( $patch_body ),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => $response->get_error_message(),
				),
				502
			);
		}

		$code     = (int) wp_remote_retrieve_response_code( $response );
		$gbp_body = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( $code < 200 || $code >= 300 ) {
			$msg = 'GBP API error';
			if ( is_array( $gbp_body ) && isset( $gbp_body['error']['message'] ) ) {
				$msg = (string) $gbp_body['error']['message'];
			} elseif ( is_string( wp_remote_retrieve_body( $response ) ) ) {
				$msg = wp_remote_retrieve_body( $response );
			}
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => $msg,
				),
				$code > 0 ? $code : 502
			);
		}

		/* Merge chirurgical google_data_cache — #SprintL2-L2.8-cache-merge */
		if ( ! is_array( $gbp_body ) ) {
			$gbp_body = array();
		}
		$cache_raw = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT google_data_cache FROM {$wpdb->prefix}avi_saas_profiles WHERE id = %d",
				$profile_id
			)
		);
		$cache = array();
		if ( ! empty( $cache_raw ) ) {
			$decoded = json_decode( $cache_raw, true );
			if ( is_array( $decoded ) ) {
				$cache = $decoded;
			}
		}
		if ( ! isset( $cache['nap'] ) || ! is_array( $cache['nap'] ) ) {
			$cache['nap'] = array();
		}

		switch ( $field ) {
			case 'name':
				$cache['nap']['title'] = isset( $gbp_body['title'] )
					? $gbp_body['title'] : $value;
				break;
			case 'phone':
				$cache['nap']['phoneNumbers'] = isset( $gbp_body['phoneNumbers'] )
					? $gbp_body['phoneNumbers']
					: ( isset( $patch_body['phoneNumbers'] )
						? $patch_body['phoneNumbers']
						: array( 'primaryPhone' => sanitize_text_field( (string) $value ) ) );
				break;
			case 'website':
				$cache['nap']['websiteUri'] = isset( $gbp_body['websiteUri'] )
					? $gbp_body['websiteUri'] : esc_url_raw( (string) $value );
				break;
			case 'description':
				if ( ! isset( $cache['nap']['profile'] ) || ! is_array( $cache['nap']['profile'] ) ) {
					$cache['nap']['profile'] = array();
				}
				$cache['nap']['profile']['description'] = isset( $gbp_body['profile']['description'] )
					? $gbp_body['profile']['description']
					: sanitize_textarea_field( (string) $value );
				break;
			case 'address':
				$existing_addr = isset( $cache['nap']['storefrontAddress'] )
					? $cache['nap']['storefrontAddress'] : array();
				$new_addr = isset( $gbp_body['storefrontAddress'] )
					? $gbp_body['storefrontAddress']
					: $patch_body['storefrontAddress'];
				$cache['nap']['storefrontAddress'] = array_merge( $existing_addr, $new_addr );
				break;
			case 'hours':
				$cache['nap']['regularHours'] = isset( $gbp_body['regularHours'] )
					? $gbp_body['regularHours']
					: $patch_body['regularHours'];
				break;
			case 'categories':
				$cache['nap']['categories'] = isset( $gbp_body['categories'] )
					? $gbp_body['categories']
					: $patch_body['categories'];
				break;
		}
		$cache['synced_at'] = gmdate( 'Y-m-d\TH:i:s\Z' );

		$wpdb->update(
			$wpdb->prefix . 'avi_saas_profiles',
			array( 'google_data_cache' => wp_json_encode( $cache, JSON_UNESCAPED_UNICODE ) ),
			array( 'id' => $profile_id )
		);

		return new \WP_REST_Response(
			array(
				'success' => true,
				'field'   => $field,
				'updated' => is_array( $gbp_body ) ? $gbp_body : array(),
			),
			200
		);
	}

	/**
	 * Resynchronise google_data_cache via FastAPI /auth/scan.
	 * #SprintL2-sync-btn
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function sync_profile_cache( \WP_REST_Request $request ) {
		global $wpdb;

		$json       = $request->get_json_params();
		$profile_id = 0;
		if ( is_array( $json ) && isset( $json['profile_id'] ) ) {
			$profile_id = absint( $json['profile_id'] );
		}
		if ( ! $profile_id ) {
			$profile_id = absint( $request->get_param( 'profile_id' ) );
		}
		if ( ! $profile_id ) {
			return new \WP_Error( 'invalid', 'Missing profile_id', array( 'status' => 400 ) );
		}

		$response = wp_remote_post(
			'http://127.0.0.1:8001/auth/scan',
			array(
				'body'    => wp_json_encode( array( 'profile_id' => $profile_id ) ),
				'headers' => array( 'Content-Type' => 'application/json' ),
				'timeout' => 30,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_Error( 'sync_error', $response->get_error_message(), array( 'status' => 502 ) );
		}

		$code = (int) wp_remote_retrieve_response_code( $response );
		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		if ( $code !== 200 || empty( $body['success'] ) ) {
			return new \WP_Error( 'sync_failed', 'Sync failed', array( 'status' => 502 ) );
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_data_cache, google_place_id, google_location_name FROM {$wpdb->prefix}avi_saas_profiles WHERE id = %d",
				$profile_id
			)
		);

		$score_data = array(
			'success' => true,
			'score'   => isset( $body['initial_score'] ) ? (int) $body['initial_score'] : 0,
		);

		if ( $profile ) {
			$score_data['google_location_name'] = isset( $profile->google_location_name )
				? $profile->google_location_name : '';
		}

		if ( $profile && ! empty( $profile->google_data_cache ) ) {
			$gdc = json_decode( $profile->google_data_cache, true );
			if ( ! is_array( $gdc ) ) {
				$gdc = array();
			}
			$nap = isset( $gdc['nap'] ) ? $gdc['nap'] : array();
			if ( ! is_array( $nap ) ) {
				$nap = array();
			}
			$score_data['has_name']        = ! empty( $nap['title'] );
			$score_data['name_value']      = isset( $nap['title'] ) ? $nap['title'] : '';
			$score_data                    = array_merge( $score_data, self::score_verification_from_nap( $nap ) );
			$score_data['has_website']     = ! empty( $nap['websiteUri'] );
			$score_data['website_url']     = isset( $nap['websiteUri'] ) ? $nap['websiteUri'] : '';
			$score_data['has_phone']       = ! empty( $nap['phoneNumbers'] );
			$score_data['phone_value']     = isset( $nap['phoneNumbers']['primaryPhone'] )
				? $nap['phoneNumbers']['primaryPhone'] : '';
			$score_data['has_hours']       = ! empty( $nap['regularHours'] );
			/* #SprintL2-hours-fix */
			$score_data['hours_periods']   = self::normalize_gbp_hours_periods(
				isset( $nap['regularHours']['periods'] ) ? (array) $nap['regularHours']['periods'] : array()
			);
			$score_data['has_description'] = ! empty( $nap['profile']['description'] ) || ! empty( $nap['description'] );
			$score_data['has_category']    = ! empty( $nap['categories']['primaryCategory']['displayName'] );
			$score_data['category_name']   = isset( $nap['categories']['primaryCategory']['displayName'] )
				? $nap['categories']['primaryCategory']['displayName'] : '';
			$score_data['has_address']     = ! empty( $nap['storefrontAddress']['locality'] );
			$score_data['city']            = isset( $nap['storefrontAddress']['locality'] )
				? $nap['storefrontAddress']['locality'] : '';
			$score_data['primary_category_name'] = $score_data['category_name'];
			$score_data['primary_category_id']   = isset( $nap['categories']['primaryCategory']['name'] )
				? $nap['categories']['primaryCategory']['name'] : '';
			$score_data['has_special_hours']   = ! empty( $nap['specialHours'] );
			$score_data['special_hours_value'] = ! empty( $nap['specialHours'] ) ? 'Configured' : '';
			$score_data['has_service_area']    = ! empty( $nap['serviceArea'] );
			$score_data['service_area_value']  = isset( $nap['serviceArea']['businessType'] )
				? $nap['serviceArea']['businessType'] : ( ! empty( $nap['serviceArea'] ) ? 'Configured' : '' );
			$score_data['gbp_attributes']        = isset( $nap['attributes'] ) && is_array( $nap['attributes'] )
				? $nap['attributes'] : array();
			$score_data['attr_count']            = isset( $nap['attributes'] ) && is_array( $nap['attributes'] )
				? count( $nap['attributes'] ) : 0;
		}

		return rest_ensure_response( $score_data );
	}

	/**
	 * Autocomplete catégories GBP (Business Information API).
	 * #SprintL2-L2.8-score-ui
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function search_gbp_categories( \WP_REST_Request $request ) {
		$q          = sanitize_text_field( (string) $request->get_param( 'q' ) );
		$lang       = sanitize_text_field( (string) ( $request->get_param( 'lang' ) ?: 'en' ) );
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$key_id     = sanitize_text_field( (string) $request->get_param( 'key_id' ) );

		if ( strlen( $q ) < 2 ) {
			return rest_ensure_response( array( 'categories' => array() ) );
		}

		$token = $request->get_header( 'X-Embed-Token' );
		if ( empty( $token ) || ! $profile_id ) {
			return new \WP_Error( 'unauthorized', 'Missing token', array( 'status' => 401 ) );
		}
		if ( ! self::verify_embed_token( (string) $token, $profile_id, $key_id ) ) {
			return new \WP_Error( 'unauthorized', 'Invalid embed token', array( 'status' => 403 ) );
		}

		global $wpdb;
		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_refresh_token, google_token_expires_at
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_Error( 'no_profile', 'Profile not found', array( 'status' => 404 ) );
		}

		$access_token = $profile->google_access_token;
		if ( ! empty( $profile->google_token_expires_at ) ) {
			$exp_ts = strtotime( (string) $profile->google_token_expires_at );
			if ( $exp_ts && $exp_ts < time() + 60 ) {
				if ( class_exists( 'Avision_API' ) ) {
					\Avision_API::refresh_google_token( $profile_id );
				} elseif ( class_exists( 'Avision_Database' ) ) {
					$db = new \Avision_Database();
					$db->refresh_google_access_token_if_needed( $profile_id, true );
				}
				$profile = $wpdb->get_row(
					$wpdb->prepare(
						"SELECT google_access_token FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
						$profile_id
					)
				);
				$access_token = $profile && ! empty( $profile->google_access_token )
					? $profile->google_access_token
					: '';
			}
		}
		if ( $access_token === '' ) {
			return rest_ensure_response( array( 'categories' => array() ) );
		}

		$lang_code  = in_array( $lang, array( 'fr', 'es', 'pt-br', 'tr', 'de' ), true ) ? $lang : 'en';
		$region_map = array(
			'fr'    => 'FR',
			'es'    => 'ES',
			'pt-br' => 'BR',
			'tr'    => 'TR',
			'de'    => 'DE',
			'en'    => 'US',
		);
		$region_code = isset( $region_map[ $lang_code ] ) ? $region_map[ $lang_code ] : 'US';

		$url = add_query_arg(
			array(
				'filter'       => 'displayName=' . rawurlencode( $q ),
				'languageCode' => $lang_code === 'pt-br' ? 'pt-BR' : $lang_code,
				'regionCode'   => $region_code,
				'pageSize'     => 15,
			),
			'https://mybusinessbusinessinformation.googleapis.com/v1/categories'
		);

		$response = wp_remote_get(
			$url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $access_token,
				),
				'timeout' => 10,
			)
		);

		if ( is_wp_error( $response ) ) {
			return rest_ensure_response( array( 'categories' => array() ) );
		}

		$data = json_decode( wp_remote_retrieve_body( $response ), true );
		$cats = ( is_array( $data ) && isset( $data['categories'] ) && is_array( $data['categories'] ) )
			? $data['categories']
			: array();

		return rest_ensure_response( array( 'categories' => $cats ) );
	}

	/**
	 * Crée un post GBP (publication immédiate ou programmée).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function create_post( $request ) {
		global $wpdb;
		$body         = $request->get_json_params();
		$profile_id   = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$post_type    = isset( $body['post_type'] )
			? sanitize_key( $body['post_type'] ) : 'update';
		$content      = isset( $body['content'] )
			? sanitize_textarea_field( $body['content'] ) : '';
		$is_scheduled = ! empty( $body['scheduled_at'] );
		$scheduled_at = $is_scheduled
			? sanitize_text_field( $body['scheduled_at'] ) : null;
		$event_title  = isset( $body['event_title'] )
			? sanitize_text_field( $body['event_title'] ) : '';
		$event_start  = isset( $body['event_start'] )
			? sanitize_text_field( $body['event_start'] ) : '';
		$event_end    = isset( $body['event_end'] )
			? sanitize_text_field( $body['event_end'] ) : '';
		$photo_base64 = isset( $body['photo_base64'] )
			? $body['photo_base64'] : '';
		$photo_url    = isset( $body['photo_url'] )
			? esc_url_raw( $body['photo_url'] ) : '';

		if ( ! $profile_id || ! $content ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing parameters' ),
				400
			);
		}

		if ( ! in_array( $post_type, array( 'update', 'offer', 'event' ), true ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Invalid post type' ),
				400
			);
		}

		if ( strlen( $content ) > 1500 ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Content exceeds 1500 characters' ),
				400
			);
		}

		if ( $is_scheduled ) {
			$credits_row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT (credits_total + COALESCE(credits_bonus,0)
					         - credits_used + COALESCE(credits_refunded,0))
					         AS available
					 FROM `{$wpdb->prefix}avi_heatmap_credits`
					 WHERE profile_id = %d
					    OR (owner_type = 'agency' AND agency_id = (
					        SELECT agency_id FROM `{$wpdb->prefix}avi_saas_profiles`
					        WHERE id = %d LIMIT 1
					    ))
					 ORDER BY id DESC LIMIT 1",
					$profile_id,
					$profile_id
				)
			);
			$available = $credits_row ? (int) $credits_row->available : 0;
			if ( $available < 2 ) {
				return new \WP_REST_Response(
					array(
						'success' => false,
						'message' => 'Insufficient credits (2 required for scheduled posts)',
					),
					402
				);
			}
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_location_name, user_id
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Google not connected' ),
				401
			);
		}

		$user_id = (int) $profile->user_id;
		$status  = $is_scheduled ? 'pending' : 'pending';
		$insert  = $wpdb->insert(
			$wpdb->prefix . 'avi_saas_posts',
			array(
				'user_id'      => $user_id,
				'profile_id'   => $profile_id,
				'post_type'    => $post_type,
				'content'      => $content,
				'status'       => $status,
				'scheduled_at' => $scheduled_at,
				'created_at'   => current_time( 'mysql' ),
			),
			array( '%d', '%d', '%s', '%s', '%s', '%s', '%s' )
		);

		if ( ! $insert ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Database error' ),
				500
			);
		}

		$post_id = (int) $wpdb->insert_id;

		if ( ! $is_scheduled ) {
			$location = $profile->google_location_name;
			if ( empty( $location ) ) {
				$wpdb->update(
					$wpdb->prefix . 'avi_saas_posts',
					array( 'status' => 'failed' ),
					array( 'id' => $post_id ),
					array( '%s' ),
					array( '%d' )
				);
				return new \WP_REST_Response(
					array( 'success' => false, 'message' => 'Google location not set' ),
					400
				);
			}

			$google_payload = array( 'summary' => $content );
			if ( $post_type === 'event' ) {
				$google_payload['topicType'] = 'EVENT';
				$google_payload['event']     = array(
					'title'    => $event_title,
					'schedule' => array(
						'startTime' => $event_start,
						'endTime'   => $event_end,
					),
				);
			} elseif ( $post_type === 'offer' ) {
				$google_payload['topicType'] = 'OFFER';
			} else {
				$google_payload['topicType'] = 'STANDARD';
			}

			$media_url = '';
			if ( ! empty( $photo_base64 ) ) {
				$upload = self::upload_base64_image( $photo_base64, $profile_id );
				if ( $upload && ! empty( $upload['url'] ) ) {
					$media_url = $upload['url'];
				}
			} elseif ( ! empty( $photo_url ) ) {
				$media_url = $photo_url;
			}

			if ( ! empty( $media_url ) ) {
				$google_payload['media'] = array(
					array(
						'mediaFormat' => 'PHOTO',
						'sourceUrl'   => $media_url,
					),
				);
			}

			$api_url  = 'https://mybusiness.googleapis.com/v4/'
				. $location . '/localPosts';
			$response = wp_remote_post(
				$api_url,
				array(
					'headers' => array(
						'Authorization' => 'Bearer ' . $profile->google_access_token,
						'Content-Type'  => 'application/json',
					),
					'body'    => wp_json_encode( $google_payload ),
					'timeout' => 15,
				)
			);

			$api_code = is_wp_error( $response )
				? 500
				: wp_remote_retrieve_response_code( $response );

			if ( $api_code === 200 ) {
				$wpdb->update(
					$wpdb->prefix . 'avi_saas_posts',
					array(
						'status'       => 'published',
						'published_at' => current_time( 'mysql' ),
					),
					array( 'id' => $post_id ),
					array( '%s', '%s' ),
					array( '%d' )
				);
				return new \WP_REST_Response(
					array( 'success' => true, 'message' => 'Post published', 'post_id' => $post_id ),
					200
				);
			} else {
				$err = is_wp_error( $response )
					? $response->get_error_message()
					: wp_remote_retrieve_body( $response );
				$wpdb->update(
					$wpdb->prefix . 'avi_saas_posts',
					array( 'status' => 'failed' ),
					array( 'id' => $post_id ),
					array( '%s' ),
					array( '%d' )
				);
				return new \WP_REST_Response(
					array( 'success' => false, 'message' => 'Google API error: ' . $err ),
					$api_code
				);
			}
		}

		$wpdb->query(
			$wpdb->prepare(
				"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
				 SET credits_used = credits_used + 2
				 WHERE profile_id = %d
				 ORDER BY id DESC LIMIT 1",
				$profile_id
			)
		);

		return new \WP_REST_Response(
			array(
				'success'      => true,
				'message'      => 'Post scheduled',
				'post_id'      => $post_id,
				'scheduled_at' => $scheduled_at,
			),
			200
		);
	}

	/**
	 * Génère un brouillon de post GBP via OpenRouter (Gemini Flash).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function handle_avi_generate_post( \WP_REST_Request $request ) {
		global $wpdb;
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$post_type  = isset( $body['post_type'] )
			? strtoupper( sanitize_text_field( (string) $body['post_type'] ) ) : 'STANDARD';
		$context    = isset( $body['context'] )
			? sanitize_textarea_field( (string) $body['context'] ) : '';
		$regenerate = ! empty( $body['regenerate'] );
		$previous   = isset( $body['previous_draft'] )
			? sanitize_textarea_field( (string) $body['previous_draft'] ) : '';

		if ( ! $profile_id ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Missing profile_id' ),
				400
			);
		}

		$type_map = array(
			'STANDARD' => 'Update',
			'UPDATE'   => 'Update',
			'OFFER'    => 'Offer',
			'EVENT'    => 'Event',
		);
		if ( ! isset( $type_map[ $post_type ] ) ) {
			$post_type = 'STANDARD';
		}
		$post_type_label = $type_map[ $post_type ];

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT business_name, city, language,
				        COALESCE(google_primary_category, category, '') AS category
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Profile not found' ),
				404
			);
		}

		$lang = ! empty( $profile->language )
			? strtolower( substr( (string) $profile->language, 0, 2 ) ) : 'en';
		if ( $lang === 'pt' ) {
			$lang = 'pt-br';
		}
		if ( ! in_array( $lang, array( 'en', 'fr', 'es', 'pt-br', 'tr', 'de' ), true ) ) {
			$lang = 'en';
		}

		$business_name = ! empty( $profile->business_name )
			? (string) $profile->business_name : 'Business';
		$city          = ! empty( $profile->city )
			? (string) $profile->city : '';
		$category      = ! empty( $profile->category )
			? (string) $profile->category : 'local business';

		if ( $context === '' ) {
			if ( $lang === 'fr' ) {
				$context_label = 'Aucun contexte fourni';
			} elseif ( $lang === 'es' ) {
				$context_label = 'Sin contexto';
			} else {
				$context_label = 'None provided';
			}
		} else {
			$context_label = $context;
		}

		if ( $lang === 'fr' ) {
			$prompt = sprintf(
				"Tu es AVI, expert en rédaction Google Business Profile.\n"
				. "Rédige UN post GBP pour %s, un(e) %s situé(e) à %s.\n"
				. "Type de post : %s.\n"
				. "Contexte utilisateur : %s\n"
				. "Règles :\n"
				. "- Maximum 1500 caractères (limite GBP), vise 150-300 caractères pour le meilleur engagement\n"
				. "- Mentionne un quartier ou un lieu de référence si pertinent (SEO local Google Maps)\n"
				. "- Intègre naturellement un mot-clé local\n"
				. "- Termine par un appel à l'action clair (ex : Appelez-nous, Réservez, Venez nous voir)\n"
				. "- Pas de hashtags, pas d'emojis sauf si naturels\n"
				. "- Réponds UNIQUEMENT avec le texte du post, rien d'autre",
				$business_name,
				$category,
				$city,
				$post_type_label,
				$context_label
			);
		} elseif ( $lang === 'es' ) {
			$prompt = sprintf(
				"Eres AVI, experto en redacción para Google Business Profile.\n"
				. "Redacta UN post GBP para %s, un(a) %s ubicado(a) en %s.\n"
				. "Tipo de post: %s.\n"
				. "Contexto del usuario: %s\n"
				. "Reglas:\n"
				. "- Máximo 1500 caracteres (límite GBP), apunta a 150-300 caracteres para mejor engagement\n"
				. "- Menciona un barrio o lugar de referencia si es relevante (SEO local Google Maps)\n"
				. "- Incluye una palabra clave local de forma natural\n"
				. "- Termina con una llamada a la acción clara (ej: Llámenos, Reserve ahora, Visítenos)\n"
				. "- Sin hashtags, sin emojis salvo que sean naturales\n"
				. "- Responde ÚNICAMENTE con el texto del post, nada más",
				$business_name,
				$category,
				$city,
				$post_type_label,
				$context_label
			);
		} elseif ( $lang === 'pt-br' ) {
			$prompt = sprintf(
				"Você é AVI, especialista em redação para Google Business Profile.\n"
				. "Escreva UM post GBP para %s, um(a) %s localizado(a) em %s.\n"
				. "Tipo de post: %s.\n"
				. "Contexto do usuário: %s\n"
				. "Regras:\n"
				. "- Máximo 1500 caracteres (limite GBP), mire em 150-300 caracteres para melhor engajamento\n"
				. "- Mencione um bairro ou ponto de referência se relevante (SEO local Google Maps)\n"
				. "- Inclua uma palavra-chave local de forma natural\n"
				. "- Termine com uma chamada para ação clara (ex: Ligue agora, Reserve já, Visite-nos)\n"
				. "- Sem hashtags, sem emojis salvo se naturais\n"
				. "- Responda APENAS com o texto do post, nada mais",
				$business_name,
				$category,
				$city,
				$post_type_label,
				$context_label
			);
		} elseif ( $lang === 'tr' ) {
			$prompt = sprintf(
				"Siz AVI'siniz, Google Business Profile metin yazarlığı uzmanısınız.\n"
				. "%s şehrinde bulunan %s işletmesi %s için BİR GBP gönderisi yazın.\n"
				. "Gönderi türü: %s.\n"
				. "Kullanıcı bağlamı: %s\n"
				. "Kurallar:\n"
				. "- Maksimum 1500 karakter (GBP limiti), en iyi etkileşim için 150-300 karakter hedefleyin\n"
				. "- İlgiliyse bir semt veya referans noktası belirtin (Google Maps yerel SEO)\n"
				. "- Doğal bir şekilde bir yerel anahtar kelime ekleyin\n"
				. "- Net bir harekete geçirici mesajla bitirin (ör: Hemen arayın, Rezervasyon yapın, Bizi ziyaret edin)\n"
				. "- Hashtag yok, doğal değilse emoji yok\n"
				. "- YALNIZCA gönderi metnini döndürün, başka hiçbir şey yok",
				$city,
				$category,
				$business_name,
				$post_type_label,
				$context_label
			);
		} elseif ( $lang === 'de' ) {
			$prompt = sprintf(
				"Sie sind AVI, Experte für Google Business Profile Texterstellung.\n"
				. "Schreiben Sie EINEN GBP-Beitrag für %s, ein(e) %s in %s.\n"
				. "Beitragstyp: %s.\n"
				. "Benutzerkontext: %s\n"
				. "Regeln:\n"
				. "- Maximal 1500 Zeichen (GBP-Limit), streben Sie 150-300 Zeichen für beste Interaktion an\n"
				. "- Erwähnen Sie einen Stadtteil oder Orientierungspunkt wenn relevant (Google Maps lokales SEO)\n"
				. "- Fügen Sie natürlich ein lokales Keyword ein\n"
				. "- Enden Sie mit einem klaren Call-to-Action (z.B.: Jetzt anrufen, Jetzt buchen, Besuchen Sie uns)\n"
				. "- Keine Hashtags, keine Emojis außer wenn natürlich\n"
				. "- Geben Sie NUR den Beitragstext zurück, nichts anderes",
				$business_name,
				$category,
				$city,
				$post_type_label,
				$context_label
			);
		} else {
			$prompt = sprintf(
				"You are AVI, a Google Business Profile copywriting expert.\n"
				. "Write ONE GBP post for %s, a %s located in %s.\n"
				. "Post type: %s.\n"
				. "User context: %s\n"
				. "Rules:\n"
				. "- Maximum 1500 characters (GBP limit), aim for 150-300 characters for best engagement\n"
				. "- Include a neighborhood or landmark reference if relevant (Google Maps local SEO)\n"
				. "- Include one local keyword naturally\n"
				. "- End with a clear call-to-action (e.g. Call us, Book now, Visit us)\n"
				. "- No hashtags, no emojis unless natural\n"
				. "- Return ONLY the post text, nothing else",
				$business_name,
				$category,
				$city,
				$post_type_label,
				$context_label
			);
		}

		if ( $regenerate && $previous !== '' ) {
			if ( $lang === 'fr' ) {
				$prompt .= "\n\nBrouillon précédent (propose un angle DIFFÉRENT, ne répète pas) :\n" . $previous;
			} elseif ( $lang === 'es' ) {
				$prompt .= "\n\nBorrador anterior (propón un enfoque DIFERENTE, no repitas) :\n" . $previous;
			} else {
				$prompt .= "\n\nPrevious draft (write a DIFFERENT angle, do not repeat):\n" . $previous;
			}
		}

		$api_key = defined( 'OPENROUTER_API_KEY' ) ? OPENROUTER_API_KEY : getenv( 'OPENROUTER_API_KEY' );
		if ( ! $api_key ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Generation failed' ),
				500
			);
		}

		$or_body = array(
			'model'      => 'google/gemini-2.5-flash-lite',
			'messages'   => array(
				array(
					'role'    => 'user',
					'content' => $prompt,
				),
			),
			'max_tokens' => 400,
		);

		$response = wp_remote_post(
			'https://openrouter.ai/api/v1/chat/completions',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $api_key,
					'Content-Type'  => 'application/json',
					'HTTP-Referer'  => 'https://avision.org',
				),
				'body'    => wp_json_encode( $or_body ),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Generation failed' ),
				500
			);
		}

		$code = wp_remote_retrieve_response_code( $response );
		$raw  = wp_remote_retrieve_body( $response );
		$data = json_decode( $raw, true );

		if ( $code !== 200 || ! is_array( $data ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Generation failed' ),
				500
			);
		}

		$draft = '';
		if ( isset( $data['choices'][0]['message']['content'] ) ) {
			$draft = trim( (string) $data['choices'][0]['message']['content'] );
			$draft = trim( $draft, "\"'" );
		}

		if ( $draft === '' ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'error' => 'Generation failed' ),
				500
			);
		}

		return new \WP_REST_Response(
			array(
				'success' => true,
				'draft'   => $draft,
			),
			200
		);
	}

	/**
	 * Construit le chemin location Format B pour API Media v4.
	 * #SprintL2-photos-fix
	 *
	 * @param object $profile Ligne profil (google_location_name, google_account_name).
	 * @return string
	 */
	private static function build_gbp_media_location_path( $profile ) {
		$loc_name = isset( $profile->google_location_name ) ? (string) $profile->google_location_name : '';
		$acc_name = isset( $profile->google_account_name ) ? (string) $profile->google_account_name : '';
		$loc_name = ltrim( $loc_name, '/' );
		$acc_name = ltrim( $acc_name, '/' );
		if ( strpos( $loc_name, 'accounts/' ) === 0 ) {
			return $loc_name;
		}
		if ( ! empty( $acc_name ) && strpos( $acc_name, 'accounts/' ) === 0 ) {
			return $acc_name . '/' . $loc_name;
		}
		return $loc_name;
	}

	/**
	 * Proxy de téléchargement d'une photo GBP (contourne le cross-origin).
	 * #SprintL2-photos-ux
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return void
	 */
	public static function proxy_photo_download( \WP_REST_Request $request ) {
		$url      = esc_url_raw( (string) $request->get_param( 'url' ) );
		$filename = sanitize_file_name( (string) ( $request->get_param( 'filename' ) ?: 'photo.jpg' ) );

		if ( empty( $url ) || ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
			wp_die( 'Invalid URL', '', array( 'response' => 400 ) );
		}

		$allowed = array(
			'lh3.googleusercontent.com',
			'lh4.googleusercontent.com',
			'lh5.googleusercontent.com',
			'lh6.googleusercontent.com',
			'storage.googleapis.com',
		);
		$host = wp_parse_url( $url, PHP_URL_HOST );
		if ( ! in_array( $host, $allowed, true ) ) {
			wp_die( 'Domain not allowed', '', array( 'response' => 403 ) );
		}

		$response = wp_remote_get( $url, array( 'timeout' => 15 ) );
		if ( is_wp_error( $response ) ) {
			wp_die( 'Fetch error', '', array( 'response' => 502 ) );
		}

		$body = wp_remote_retrieve_body( $response );
		$ct   = wp_remote_retrieve_header( $response, 'content-type' );
		if ( empty( $ct ) ) {
			$ct = 'image/jpeg';
		}

		header( 'Content-Type: ' . $ct );
		header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
		header( 'Content-Length: ' . strlen( $body ) );
		header( 'Cache-Control: no-cache' );
		echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binaire image proxy.
		exit;
	}

	/**
	 * Upload une photo/vidéo dans la médiathèque et avi_saas_media.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function upload_photo( $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$base64     = isset( $body['photo_base64'] ) ? $body['photo_base64'] : '';
		$media_type = isset( $body['media_type'] ) ? sanitize_key( $body['media_type'] ) : 'photo';
		$category   = isset( $body['category'] ) ? sanitize_text_field( $body['category'] ) : '';

		if ( ! $profile_id || ! $base64 ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing parameters' ),
				400
			);
		}

		$upload = self::upload_base64_image( $base64, $profile_id );
		if ( ! $upload ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Upload failed' ),
				500
			);
		}

		$wpdb->insert(
			$wpdb->prefix . 'avi_saas_media',
			array(
				'profile_id' => $profile_id,
				'file_path'  => $upload['url'],
				'media_type' => $media_type,
				'category'   => $category,
				'status'     => 'in_stock',
				'gbp_status' => 'pending',
				'created_at' => current_time( 'mysql' ),
			),
			array( '%d', '%s', '%s', '%s', '%s', '%s', '%s' )
		);

		$media_id = (int) $wpdb->insert_id;
		return new \WP_REST_Response(
			array(
				'success'   => true,
				'media_id'  => $media_id,
				'file_path' => $upload['url'],
			),
			200
		);
	}

	/**
	 * Publie ou programme une photo/vidéo sur Google GBP.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function publish_photo( $request ) {
		global $wpdb;
		$body         = $request->get_json_params();
		$profile_id   = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$media_id     = isset( $body['media_id'] ) ? absint( $body['media_id'] ) : 0;
		$scheduled_at = isset( $body['scheduled_at'] )
			? sanitize_text_field( $body['scheduled_at'] ) : '';
		$is_scheduled = ! empty( $scheduled_at );

		if ( ! $profile_id || ! $media_id ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing parameters' ),
				400
			);
		}

		$media = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT * FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE id = %d AND profile_id = %d LIMIT 1",
				$media_id,
				$profile_id
			)
		);

		if ( ! $media ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Media not found' ),
				404
			);
		}

		$credit_cost = ( $media->media_type === 'video' ) ? 5 : 3;
		if ( $is_scheduled ) {
			$credits_row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT (credits_total + COALESCE(credits_bonus,0)
					         - credits_used + COALESCE(credits_refunded,0)) AS available
					 FROM `{$wpdb->prefix}avi_heatmap_credits`
					 WHERE profile_id = %d
					 ORDER BY id DESC LIMIT 1",
					$profile_id
				)
			);
			$available = $credits_row ? (int) $credits_row->available : 0;
			if ( $available < $credit_cost ) {
				return new \WP_REST_Response(
					array(
						'success' => false,
						'message' => 'Insufficient credits (' . $credit_cost . ' required)',
					),
					402
				);
			}
			$wpdb->update(
				$wpdb->prefix . 'avi_saas_media',
				array(
					'status'       => 'scheduled',
					'scheduled_at' => $scheduled_at,
				),
				array( 'id' => $media_id ),
				array( '%s', '%s' ),
				array( '%d' )
			);
			$wpdb->query(
				$wpdb->prepare(
					"UPDATE `{$wpdb->prefix}avi_heatmap_credits`
					 SET credits_used = credits_used + %d
					 WHERE profile_id = %d ORDER BY id DESC LIMIT 1",
					$credit_cost,
					$profile_id
				)
			);
			return new \WP_REST_Response(
				array(
					'success'      => true,
					'message'      => 'Photo scheduled',
					'scheduled_at' => $scheduled_at,
				),
				200
			);
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_location_name, google_account_name
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Google not connected' ),
				401
			);
		}

		if ( empty( $profile->google_location_name ) ) {
			return new \WP_Error( 'no_location', 'Google location not configured', array( 'status' => 400 ) );
		}

		/* #SprintL2-photos-fix — Format B pour API Media v4 */
		$location_path = self::build_gbp_media_location_path( $profile );
		$api_url       = 'https://mybusiness.googleapis.com/v4/' . $location_path . '/media';
		$payload       = array(
			'mediaFormat' => ( $media->media_type === 'video' ) ? 'VIDEO' : 'PHOTO',
			'sourceUrl'   => $media->file_path,
		);
		$response = wp_remote_post(
			$api_url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $profile->google_access_token,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode( $payload ),
				'timeout' => 20,
			)
		);

		$code = is_wp_error( $response ) ? 500
			: wp_remote_retrieve_response_code( $response );

		if ( $code === 200 ) {
			$resp_body = json_decode( wp_remote_retrieve_body( $response ), true );
			$gbp_name  = ( is_array( $resp_body ) && ! empty( $resp_body['name'] ) )
				? sanitize_text_field( $resp_body['name'] ) : '';
			$update_data = array(
				'status'       => 'published',
				'gbp_status'   => 'published',
				'published_at' => current_time( 'mysql' ),
			);
			$update_fmt  = array( '%s', '%s', '%s' );
			if ( $gbp_name ) {
				$update_data['gbp_media_name'] = $gbp_name;
				$update_fmt[]                  = '%s';
			}
			$wpdb->update(
				$wpdb->prefix . 'avi_saas_media',
				$update_data,
				array( 'id' => $media_id ),
				$update_fmt,
				array( '%d' )
			);
			return new \WP_REST_Response(
				array( 'success' => true, 'message' => 'Photo published' ),
				200
			);
		}

		$err = is_wp_error( $response ) ? $response->get_error_message()
			: wp_remote_retrieve_body( $response );
		return new \WP_REST_Response(
			array( 'success' => false, 'message' => 'Google API error: ' . $err ),
			$code
		);
	}

	/**
	 * Synchronise les photos depuis Google GBP.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function sync_photos( $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;

		if ( ! $profile_id ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing profile_id' ),
				400
			);
		}

		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_location_name, google_account_name
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$profile_id
			)
		);

		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Google not connected — please reconnect' ),
				401
			);
		}

		if ( empty( $profile->google_location_name ) ) {
			return new \WP_Error( 'no_location', 'Google location not configured', array( 'status' => 400 ) );
		}

		/* #SprintL2-photos-fix — Format B pour API Media v4 */
		$location_path = self::build_gbp_media_location_path( $profile );
		$api_url       = 'https://mybusiness.googleapis.com/v4/' . $location_path . '/media';
		error_log( '[SprintL2-photos-fix] sync url=' . $api_url . ' acc=' . ( $profile->google_account_name ?? 'NULL' ) );
		$response      = wp_remote_get(
			$api_url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $profile->google_access_token,
				),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => $response->get_error_message() ),
				500
			);
		}

		$code = wp_remote_retrieve_response_code( $response );
		error_log( '[SprintL2-photos-fix] sync response_code=' . $code . ' body=' . str_replace( array( "\n", "\r" ), ' ', wp_remote_retrieve_body( $response ) ) );
		if ( $code !== 200 ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Google API error: ' . $code ),
				$code
			);
		}

		$data        = json_decode( wp_remote_retrieve_body( $response ), true );
		$media_items = isset( $data['mediaItems'] ) ? $data['mediaItems'] : array();
		$synced      = 0;

		foreach ( $media_items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$source_url = isset( $item['sourceUrl'] ) ? $item['sourceUrl'] : '';
			$google_url = isset( $item['googleUrl'] ) ? $item['googleUrl'] : $source_url;
			$gbp_name   = isset( $item['name'] ) ? $item['name'] : '';
			if ( empty( $google_url ) ) {
				continue;
			}

			$exists = $wpdb->get_var(
				$wpdb->prepare(
					"SELECT id FROM `{$wpdb->prefix}avi_saas_media`
					 WHERE profile_id = %d AND file_path = %s LIMIT 1",
					$profile_id,
					$google_url
				)
			);
			if ( $exists ) {
				if ( $gbp_name ) {
					$wpdb->update(
						$wpdb->prefix . 'avi_saas_media',
						array( 'gbp_media_name' => $gbp_name ),
						array(
							'id'         => (int) $exists,
							'profile_id' => $profile_id,
						),
						array( '%s' ),
						array( '%d', '%d' )
					);
				}
				continue;
			}

			$media_format = isset( $item['mediaFormat'] ) ? $item['mediaFormat'] : 'PHOTO';
			$insert_data  = array(
				'profile_id'   => $profile_id,
				'file_path'    => $google_url,
				'media_type'   => ( $media_format === 'VIDEO' ) ? 'video' : 'photo',
				'category'     => isset( $item['locationAssociation']['category'] )
					? $item['locationAssociation']['category'] : '',
				'status'       => 'published',
				'gbp_status'   => 'published',
				'published_at' => current_time( 'mysql' ),
				'created_at'   => current_time( 'mysql' ),
			);
			$insert_fmt   = array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' );
			if ( $gbp_name ) {
				$insert_data['gbp_media_name'] = $gbp_name;
				$insert_fmt[]                  = '%s';
			}
			$wpdb->insert(
				$wpdb->prefix . 'avi_saas_media',
				$insert_data,
				$insert_fmt
			);
			$synced++;
		}

		$all_media = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, file_path, display_name, media_type, category, status,
				        gbp_status, scheduled_at, published_at, created_at
				 FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE profile_id = %d
				 ORDER BY created_at DESC LIMIT 100",
				$profile_id
			)
		);

		$photos_data = array();
		if ( $all_media ) {
			foreach ( $all_media as $m ) {
				$photos_data[] = array(
					'id'           => (int) $m->id,
					'file_path'    => $m->file_path,
					'display_name' => $m->display_name,
					'media_type'   => $m->media_type,
					'category'     => $m->category,
					'status'       => $m->status,
					'gbp_status'   => $m->gbp_status,
					'scheduled_at' => $m->scheduled_at,
					'published_at' => $m->published_at,
					'created_at'   => $m->created_at,
				);
			}
		}

		return new \WP_REST_Response(
			array(
				'success' => true,
				'synced'  => $synced,
				'message' => $synced . ' new photo(s) synced from GBP',
				'photos'  => $photos_data,
			),
			200
		);
	}

	/**
	 * Supprime une photo de la médiathèque.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function delete_photo( $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$photo_id   = isset( $body['photo_id'] ) ? absint( $body['photo_id'] ) : 0;

		if ( ! $profile_id || ! $photo_id ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing parameters' ),
				400
			);
		}

		$deleted = $wpdb->delete(
			$wpdb->prefix . 'avi_saas_media',
			array(
				'id'         => $photo_id,
				'profile_id' => $profile_id,
			),
			array( '%d', '%d' )
		);

		if ( ! $deleted ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Photo not found or already deleted' ),
				404
			);
		}

		return new \WP_REST_Response(
			array( 'success' => true, 'message' => 'Photo deleted' ),
			200
		);
	}

	/**
	 * Supprime une photo de Google GBP (API Media v4).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function delete_photo_gbp( $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$photo_id   = isset( $body['photo_id'] ) ? absint( $body['photo_id'] ) : 0;
		if ( ! $profile_id || ! $photo_id ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Missing parameters' ), 400 );
		}
		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_account_name, google_location_name FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Profile not found or not connected' ), 404 );
		}
		$media = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT gbp_media_name FROM `{$wpdb->prefix}avi_saas_media` WHERE id = %d AND profile_id = %d LIMIT 1",
				$photo_id,
				$profile_id
			)
		);
		if ( ! $media || empty( $media->gbp_media_name ) ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Photo not found or not published on GBP' ), 404 );
		}
		$api_url  = 'https://mybusiness.googleapis.com/v4/' . $media->gbp_media_name;
		$response = wp_remote_request(
			$api_url,
			array(
				'method'  => 'DELETE',
				'headers' => array(
					'Authorization' => 'Bearer ' . $profile->google_access_token,
					'Content-Type'  => 'application/json',
				),
				'timeout' => 15,
			)
		);
		$code = wp_remote_retrieve_response_code( $response );
		if ( is_wp_error( $response ) || ( $code !== 200 && $code !== 204 ) ) {
			$msg = is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_body( $response );
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Google API error: ' . $msg ), 500 );
		}
		$wpdb->update(
			$wpdb->prefix . 'avi_saas_media',
			array(
				'gbp_status' => 'deleted',
				'status'     => 'unpublished',
			),
			array(
				'id'         => $photo_id,
				'profile_id' => $profile_id,
			),
			array( '%s', '%s' ),
			array( '%d', '%d' )
		);
		return new \WP_REST_Response( array( 'success' => true, 'message' => 'Photo deleted from GBP' ), 200 );
	}

	/**
	 * Rafraîchit le token Google si nécessaire (wrapper Avision_API).
	 *
	 * @param int $profile_id ID profil.
	 * @return bool
	 */
	private static function maybe_refresh_google_token( $profile_id ) {
		$profile_id = (int) $profile_id;
		if ( $profile_id <= 0 ) {
			return false;
		}
		if ( class_exists( 'Avision_API' ) ) {
			return \Avision_API::refresh_google_token( $profile_id );
		}
		if ( class_exists( 'Avision_Database' ) ) {
			$db = new \Avision_Database();
			return $db->refresh_google_access_token_if_needed( $profile_id, true );
		}
		return false;
	}

	/**
	 * Liste les attributs GBP disponibles pour la catégorie/région du profil.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function get_attributes_available( \WP_REST_Request $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		if ( ! $profile_id ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Missing profile_id' ), 400 );
		}
		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_location_name, google_token_expires_at FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Profile not found or not connected' ), 404 );
		}
		$location_name = $profile->google_location_name ?? '';
		$token         = $profile->google_access_token;
		if ( ! empty( $profile->google_token_expires_at ) ) {
			$expires = strtotime( $profile->google_token_expires_at );
			if ( $expires && $expires < time() + 60 ) {
				$refreshed = self::maybe_refresh_google_token( $profile_id );
				if ( $refreshed ) {
					$profile = $wpdb->get_row(
						$wpdb->prepare(
							"SELECT google_access_token FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
							$profile_id
						)
					);
					$token = $profile->google_access_token ?? $token;
				}
			}
		}
		/* Normaliser accounts/XXX/locations/ID → ID seul */
		if ( strpos( $location_name, '/locations/' ) !== false ) {
			$loc_id = substr( $location_name, strrpos( $location_name, '/locations/' ) + strlen( '/locations/' ) );
		} else {
			$loc_id = preg_replace( '/^locations\//', '', $location_name );
		}
		if ( ! $loc_id ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'No location configured' ), 400 );
		}
		$api_url  = 'https://mybusinessbusinessinformation.googleapis.com/v1/attributes?parent=locations/' . rawurlencode( $loc_id );
		$response = wp_remote_get(
			$api_url,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
					'Content-Type'  => 'application/json',
				),
				'timeout' => 15,
			)
		);
		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => $response->get_error_message() ), 500 );
		}
		$code = wp_remote_retrieve_response_code( $response );
		if ( $code !== 200 ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => 'Google API error: ' . $code,
					'body'    => wp_remote_retrieve_body( $response ),
				),
				500
			);
		}
		$data = json_decode( wp_remote_retrieve_body( $response ), true );
		$attrs_url      = 'https://mybusinessbusinessinformation.googleapis.com/v1/locations/' . rawurlencode( $loc_id ) . '/attributes';
		$attrs_response = wp_remote_get(
			$attrs_url,
			array(
				'headers' => array( 'Authorization' => 'Bearer ' . $token ),
				'timeout' => 10,
			)
		);
		$current_attrs = array();
		if ( ! is_wp_error( $attrs_response ) && wp_remote_retrieve_response_code( $attrs_response ) === 200 ) {
			$current_data = json_decode( wp_remote_retrieve_body( $attrs_response ), true );
			foreach ( ( $current_data['attributes'] ?? array() ) as $attr ) {
				$attr_id = preg_replace( '/^attributes\//', '', $attr['name'] ?? '' );
				if ( isset( $attr['uriValues'] ) ) {
					$uri_vals = $attr['uriValues'];
					$current_attrs[ $attr_id ] = isset( $uri_vals[0]['uri'] ) ? $uri_vals[0]['uri'] : '';
				} elseif ( isset( $attr['repeatedEnumValue'] ) ) {
					$current_attrs[ $attr_id ] = $attr['repeatedEnumValue']['setValues'] ?? array();
				} elseif ( isset( $attr['values'] ) ) {
					$current_attrs[ $attr_id ] = $attr['values'][0] ?? null;
				}
			}
		}
		return new \WP_REST_Response(
			array(
				'success'           => true,
				'attributeMetadata' => $data['attributeMetadata'] ?? array(),
				'currentValues'     => $current_attrs,
			),
			200
		);
	}

	/**
	 * Met à jour un attribut GBP booléen via Business Information API.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function update_gbp_attribute( \WP_REST_Request $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$attr_id     = isset( $body['attr_id'] ) ? sanitize_text_field( $body['attr_id'] ) : '';
		$value_bool  = isset( $body['value'] ) ? (bool) $body['value'] : false;
		$enum_value  = isset( $body['value'] ) ? sanitize_text_field( (string) $body['value'] ) : '';
		$value_type  = isset( $body['value_type'] ) ? sanitize_text_field( $body['value_type'] ) : 'BOOL';
		$set_values  = isset( $body['set_values'] ) && is_array( $body['set_values'] ) ? array_map( 'sanitize_text_field', $body['set_values'] ) : array();
		$uri_value   = isset( $body['uri_value'] ) ? esc_url_raw( $body['uri_value'] ) : '';
		if ( ! $profile_id || ! $attr_id ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Missing parameters' ), 400 );
		}
		$profile = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_access_token, google_location_name, google_token_expires_at, google_data_cache FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $profile || empty( $profile->google_access_token ) ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Profile not found' ), 404 );
		}
		$token = $profile->google_access_token;
		if ( ! empty( $profile->google_token_expires_at ) ) {
			$expires = strtotime( $profile->google_token_expires_at );
			if ( $expires && $expires < time() + 60 ) {
				$refreshed = self::maybe_refresh_google_token( $profile_id );
				if ( $refreshed ) {
					$profile = $wpdb->get_row(
						$wpdb->prepare(
							"SELECT google_access_token, google_location_name, google_token_expires_at, google_data_cache FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
							$profile_id
						)
					);
					$token = $profile->google_access_token ?? $token;
				}
			}
		}
		$location_name = $profile->google_location_name ?? '';
		/* Normaliser accounts/XXX/locations/ID → ID seul */
		if ( strpos( $location_name, '/locations/' ) !== false ) {
			$loc_id = substr( $location_name, strrpos( $location_name, '/locations/' ) + strlen( '/locations/' ) );
		} else {
			$loc_id = preg_replace( '/^locations\//', '', $location_name );
		}
		if ( ! $loc_id ) {
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'No location configured' ), 400 );
		}
		$attr_name = 'attributes/' . $attr_id;
		if ( $value_type === 'REPEATED_ENUM' ) {
			$patch_body = array(
				'name'       => 'locations/' . $loc_id . '/attributes',
				'attributes' => array(
					array(
						'name'              => $attr_name,
						'valueType'         => 'REPEATED_ENUM',
						'repeatedEnumValue' => array( 'setValues' => $set_values ),
					),
				),
			);
		} elseif ( $value_type === 'URL' ) {
			$patch_body = array(
				'name'       => 'locations/' . $loc_id . '/attributes',
				'attributes' => array(
					array(
						'name'      => $attr_name,
						'valueType' => 'URL',
						'uriValues' => array( array( 'uri' => $uri_value ) ),
					),
				),
			);
		} elseif ( $value_type === 'ENUM' ) {
			$patch_body = array(
				'name'       => 'locations/' . $loc_id . '/attributes',
				'attributes' => array(
					array(
						'name'      => $attr_name,
						'valueType' => 'ENUM',
						'values'    => array( $enum_value ),
					),
				),
			);
		} else {
			$patch_body = array(
				'name'       => 'locations/' . $loc_id . '/attributes',
				'attributes' => array(
					array(
						'name'      => $attr_name,
						'valueType' => 'BOOL',
						'values'    => array( $value_bool ),
					),
				),
			);
		}
		$api_url  = 'https://mybusinessbusinessinformation.googleapis.com/v1/locations/' . rawurlencode( $loc_id ) . '/attributes?attributeMask=' . rawurlencode( 'attributes/' . $attr_id );
		$response = wp_remote_request(
			$api_url,
			array(
				'method'  => 'PATCH',
				'headers' => array(
					'Authorization' => 'Bearer ' . $token,
					'Content-Type'  => 'application/json',
				),
				'body'    => wp_json_encode( $patch_body ),
				'timeout' => 15,
			)
		);
		$code = wp_remote_retrieve_response_code( $response );
		if ( is_wp_error( $response ) || ( $code !== 200 && $code !== 204 ) ) {
			$msg = is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_body( $response );
			return new \WP_REST_Response( array( 'success' => false, 'message' => 'Google API error: ' . $msg ), 500 );
		}
		if ( ! empty( $profile->google_data_cache ) ) {
			$cache = json_decode( $profile->google_data_cache, true );
			if ( is_array( $cache ) && isset( $cache['nap']['attributes'] ) ) {
				$found = false;
				foreach ( $cache['nap']['attributes'] as &$attr ) {
					$existing_id = preg_replace( '/^attributes\//', '', $attr['name'] ?? '' );
					if ( $existing_id === $attr_id ) {
						if ( $value_type === 'REPEATED_ENUM' ) {
							$attr['repeatedEnumValue'] = array( 'setValues' => $set_values );
						} elseif ( $value_type === 'URL' ) {
							$attr['uriValues'] = array( array( 'uri' => $uri_value ) );
						} elseif ( $value_type === 'ENUM' ) {
							$attr['values'] = array( $enum_value );
						} else {
							$attr['values'] = array( $value_bool );
						}
						$found          = true;
						break;
					}
				}
				unset( $attr );
				if ( ! $found ) {
					$new_attr = array(
						'name'      => $attr_name,
						'valueType' => $value_type,
					);
					if ( $value_type === 'REPEATED_ENUM' ) {
						$new_attr['repeatedEnumValue'] = array( 'setValues' => $set_values );
					} elseif ( $value_type === 'URL' ) {
						$new_attr['uriValues'] = array( array( 'uri' => $uri_value ) );
					} else {
						$new_attr['values'] = array( $value_type === 'ENUM' ? $enum_value : $value_bool );
					}
					$cache['nap']['attributes'][] = $new_attr;
				}
				$wpdb->update(
					$wpdb->prefix . 'avi_saas_profiles',
					array( 'google_data_cache' => wp_json_encode( $cache ) ),
					array( 'id' => $profile_id ),
					array( '%s' ),
					array( '%d' )
				);
			}
		}
		return new \WP_REST_Response(
			array(
				'success'    => true,
				'attr_id'    => $attr_id,
				'value_type' => $value_type,
			),
			200
		);
	}

	/**
	 * Met à jour display_name et category d'une photo en médiathèque.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function handle_update_photo( \WP_REST_Request $request ) {
		global $wpdb;
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}
		$profile_id   = isset( $body['profile_id'] ) ? absint( $body['profile_id'] ) : 0;
		$media_id     = isset( $body['media_id'] ) ? absint( $body['media_id'] ) : 0;
		$display_name = isset( $body['display_name'] )
			? sanitize_file_name( (string) $body['display_name'] ) : '';
		$category     = isset( $body['category'] )
			? sanitize_text_field( (string) $body['category'] ) : '';

		if ( ! $profile_id || ! $media_id ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Missing parameters' ),
				400
			);
		}

		$exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM `{$wpdb->prefix}avi_saas_media`
				 WHERE id = %d AND profile_id = %d LIMIT 1",
				$media_id,
				$profile_id
			)
		);

		if ( ! $exists ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Media not found' ),
				404
			);
		}

		$updated = $wpdb->update(
			$wpdb->prefix . 'avi_saas_media',
			array(
				'display_name' => $display_name,
				'category'     => $category,
			),
			array(
				'id'         => $media_id,
				'profile_id' => $profile_id,
			),
			array( '%s', '%s' ),
			array( '%d', '%d' )
		);

		if ( false === $updated ) {
			return new \WP_REST_Response(
				array( 'success' => false, 'message' => 'Update failed' ),
				500
			);
		}

		return new \WP_REST_Response(
			array(
				'success'      => true,
				'display_name' => $display_name,
				'category'     => $category,
			),
			200
		);
	}

	/**
	 * Normalise une valeur horaire GBP (string ou objet {hours, minutes}) en HH:MM.
	 * #SprintL2-hours-fix
	 *
	 * @param mixed $t Valeur openTime/closeTime brute.
	 * @return string
	 */
	private static function normalize_gbp_time_value( $t ): string {
		if ( is_string( $t ) && $t !== '' ) {
			return strlen( $t ) >= 5 ? substr( $t, 0, 5 ) : $t;
		}
		if ( is_array( $t ) && isset( $t['hours'] ) ) {
			return sprintf( '%02d:%02d', (int) $t['hours'], (int) ( $t['minutes'] ?? 0 ) );
		}
		return '';
	}

	/**
	 * Champs vérification GBP depuis metadata NAP.
	 * #SprintL1-L1.4-verified-badge
	 *
	 * @param array $nap Données NAP du cache Google.
	 * @return array
	 */
	private static function score_verification_from_nap( array $nap ): array {
		return array(
			'is_verified' => isset( $nap['metadata']['hasVoiceOfMerchant'] )
				? (bool) $nap['metadata']['hasVoiceOfMerchant']
				: false,
			'verification_state' => isset( $nap['metadata']['hasPendingVerification'] )
				? 'pending'
				: ( isset( $nap['metadata']['hasVoiceOfMerchant'] ) && $nap['metadata']['hasVoiceOfMerchant']
					? 'verified'
					: 'unverified' ),
		);
	}

	/**
	 * Lit un attribut GBP booléen depuis nap.attributes.
	 *
	 * @param array  $nap     Données NAP du cache Google.
	 * @param string $attr_id Identifiant d'attribut GBP.
	 * @return bool|null null si attribut non disponible pour cette catégorie.
	 */
	private static function nap_attr( array $nap, string $attr_id ): ?bool {
		if ( empty( $nap['attributes'] ) || ! is_array( $nap['attributes'] ) ) {
			return null;
		}
		foreach ( $nap['attributes'] as $attr ) {
			$name = isset( $attr['name'] ) ? $attr['name'] : '';
			// Format v1 : "locations/{id}/attributes/{attr_id}" ou juste attr_id
			if ( $name === $attr_id || substr( $name, -strlen( $attr_id ) ) === $attr_id ) {
				$vals = isset( $attr['values'] ) ? $attr['values'] : array();
				if ( ! empty( $vals ) ) {
					return (bool) $vals[0];
				}
				return true;
			}
		}
		return null; // null = attribut non disponible pour cette catégorie
	}

	/**
	 * Normalise les périodes regularHours.periods pour le score embed.
	 * #SprintL2-hours-fix
	 *
	 * @param array $periods Périodes GBP brutes.
	 * @return array
	 */
	private static function normalize_gbp_hours_periods( array $periods ): array {
		$out = array();
		foreach ( $periods as $p ) {
			if ( ! is_array( $p ) || empty( $p['openDay'] ) ) {
				continue;
			}
			$out[] = array(
				'openDay'   => $p['openDay'],
				'openTime'  => self::normalize_gbp_time_value( $p['openTime'] ?? '' ),
				'closeTime' => self::normalize_gbp_time_value( $p['closeTime'] ?? '' ),
			);
		}
		return $out;
	}

	/**
	 * Upload une image base64 dans la médiathèque WordPress.
	 *
	 * @param string $base64     Data URL base64.
	 * @param int    $profile_id ID profil.
	 * @return array|null
	 */
	private static function upload_base64_image( $base64, $profile_id ) {
		if ( ! preg_match( '/^data:(image\/[a-z]+);base64,(.+)$/', $base64, $matches ) ) {
			return null;
		}
		$mime     = $matches[1];
		$data     = base64_decode( $matches[2] );
		$ext      = str_replace( 'image/', '', $mime );
		$filename = 'gbp-post-' . $profile_id . '-' . time() . '.' . $ext;

		$upload = wp_upload_bits( $filename, null, $data );
		if ( $upload['error'] ) {
			return null;
		}

		$attach_id = wp_insert_attachment(
			array(
				'post_mime_type' => $mime,
				'post_title'     => $filename,
				'post_status'    => 'inherit',
			),
			$upload['file']
		);

		if ( ! $attach_id ) {
			return null;
		}

		return array(
			'id'  => $attach_id,
			'url' => $upload['url'],
		);
	}

	/**
	 * Switch profil agence embed : re-signe l URL iframe (auth via X-Embed-Token).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function switch_profile( \WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		$key_id             = sanitize_text_field( isset( $body['key_id'] ) ? (string) $body['key_id'] : '' );
		$new_profile_id     = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$current_profile_id = absint( isset( $body['current_profile_id'] ) ? $body['current_profile_id'] : 0 );
		$lang               = sanitize_text_field( isset( $body['lang'] ) ? (string) $body['lang'] : 'en' );
		$theme              = sanitize_text_field( isset( $body['theme'] ) ? (string) $body['theme'] : 'light' );
		$logo_url           = esc_url_raw( isset( $body['logo_url'] ) ? (string) $body['logo_url'] : '' );

		$embed_token = $request->get_header( 'X-Embed-Token' );
		if ( $embed_token === '' || $embed_token === null ) {
			$embed_token = isset( $body['embed_token'] ) ? (string) $body['embed_token'] : '';
		}

		if ( ! $key_id || $new_profile_id <= 0 || $current_profile_id <= 0 || $embed_token === '' ) {
			return new \WP_Error( 'invalid_params', 'Paramètres switch-profile invalides.', array( 'status' => 422 ) );
		}

		if ( ! self::verify_embed_token( (string) $embed_token, $current_profile_id, $key_id ) ) {
			return new \WP_Error( 'forbidden', 'Token embed invalide.', array( 'status' => 403 ) );
		}

		global $wpdb;
		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT key_type, agency_id, secret_hash, status
				 FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s LIMIT 1",
				$key_id
			)
		);

		if ( ! $key_row || $key_row->status !== 'active' || $key_row->key_type !== 'agency' ) {
			return new \WP_Error( 'invalid_key', 'Clé agence introuvable ou inactive.', array( 'status' => 403 ) );
		}

		$agency_id = (int) $key_row->agency_id;
		if ( $agency_id <= 0 || ! self::profile_belongs_to_agency( $new_profile_id, $agency_id ) ) {
			return new \WP_Error( 'forbidden_profile', 'Profil hors flotte agence.', array( 'status' => 403 ) );
		}

		$allowed_langs = array( 'en', 'fr', 'es', 'pt-br', 'tr', 'de' );
		if ( ! in_array( $lang, $allowed_langs, true ) ) {
			$lang = 'en';
		}

		$ts      = time();
		$payload = $key_id . '|' . $new_profile_id . '|' . $ts;
		$sig     = hash_hmac( 'sha256', $payload, $key_row->secret_hash );

		$le_switch_hosted = (int) $wpdb->get_var( $wpdb->prepare(
			"SELECT hosted FROM `{$wpdb->prefix}avi_embed_keys` WHERE key_id = %s LIMIT 1",
			$key_id
		) );

		$url = add_query_arg(
			array(
				'key_id'     => $key_id,
				'sig'        => $sig,
				'profile_id' => $new_profile_id,
				'ts'         => $ts,
				'lang'       => $lang,
				'theme'      => $theme,
				'logo_url'   => $logo_url,
			),
			rest_url( 'avision/v1/embed' )
		);
		if ( $le_switch_hosted === 1 ) {
			$url = add_query_arg( 'hosted', '1', $url );
		}

		return new \WP_REST_Response(
			array(
				'url'        => $url,
				'profile_id' => $new_profile_id,
			),
			200
		);
	}

	/**
	 * Vérifie qu un profil appartient à une agence.
	 *
	 * @param int $profile_id ID profil.
	 * @param int $agency_id  ID agence.
	 * @return bool
	 */
	private static function profile_belongs_to_agency( int $profile_id, int $agency_id ): bool {
		if ( $profile_id <= 0 || $agency_id <= 0 ) {
			return false;
		}
		global $wpdb;
		$found = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d AND agency_id = %d AND user_id IS NOT NULL
				 LIMIT 1",
				$profile_id,
				$agency_id
			)
		);
		return (bool) $found;
	}

	/**
	 * Importe plusieurs fiches GBP comme profils clients pour une agence hosted.
	 */
	public static function choose_gbp_locations_bulk( \WP_REST_Request $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$key_id     = isset( $body['key_id'] ) ? sanitize_text_field( (string) $body['key_id'] ) : '';
		$agency_id  = absint( isset( $body['agency_id'] ) ? $body['agency_id'] : 0 );
		$locations  = isset( $body['locations'] ) && is_array( $body['locations'] )
		              ? $body['locations'] : array();
		if ( ! $key_id || ! $agency_id || empty( $locations ) ) {
			return new \WP_Error( 'invalid_params', 'key_id, agency_id et locations requis.', array( 'status' => 422 ) );
		}
		/* Vérifier clé agency active */
		$key_row = $wpdb->get_row( $wpdb->prepare(
			"SELECT key_id, agency_id FROM `{$wpdb->prefix}avi_embed_keys`
			 WHERE key_id = %s AND key_type = 'agency' AND status = 'active' LIMIT 1",
			$key_id
		) );
		if ( ! $key_row || (int) $key_row->agency_id !== $agency_id ) {
			return new \WP_Error( 'unauthorized', 'Clé agency invalide.', array( 'status' => 403 ) );
		}
		/* Récupérer saas_user_id admin agency + token OAuth */
		$agency_row = $wpdb->get_row( $wpdb->prepare(
			"SELECT admin_user_id FROM `{$wpdb->prefix}avi_saas_agencies` WHERE id = %d LIMIT 1",
			$agency_id
		) );
		if ( ! $agency_row ) {
			return new \WP_Error( 'agency_not_found', 'Agence introuvable.', array( 'status' => 404 ) );
		}
		/* Token OAuth du profil admin pour propagation aux profils clients */
		$admin_profile_id_for_token = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$admin_token_row = null;
		if ( $admin_profile_id_for_token ) {
			$admin_token_row = $wpdb->get_row( $wpdb->prepare(
				"SELECT google_access_token, google_refresh_token, google_token_expires_at
				 FROM `{$wpdb->prefix}avi_saas_profiles`
				 WHERE id = %d LIMIT 1",
				$admin_profile_id_for_token
			) );
		}
		$t_profiles = $wpdb->prefix . 'avi_saas_profiles';
		$created    = array();
		$skipped    = array();
		// Check quota tier LocalEdge avant import bulk
		$le_meta_quota = $wpdb->get_row( $wpdb->prepare(
			"SELECT tier, max_listings FROM `{$wpdb->prefix}avi_localedge_agency_meta` WHERE agency_id = %d LIMIT 1",
			$agency_id
		) );
		if ( $le_meta_quota ) {
			$used_listings = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_profiles` WHERE agency_id = %d AND user_id IS NOT NULL",
				$agency_id
			) );
			$max_allowed   = (int) $le_meta_quota->max_listings;
			$requested     = count( $locations );
			if ( ( $used_listings + $requested ) > $max_allowed ) {
				$slots_left = max( 0, $max_allowed - $used_listings );
				return new \WP_Error(
					"quota_exceeded",
					"Quota tier depass\u{e9} : " . $used_listings . " fiches actives + " . $requested . " demand\u{e9}es > limite " . $max_allowed . ". Places restantes : " . $slots_left . ".",
					array( "status" => 409 )
				);
			}
		}
		foreach ( $locations as $loc ) {
			$location_fn = isset( $loc['location_full_name'] )
			               ? sanitize_text_field( (string) $loc['location_full_name'] ) : '';
			$title       = isset( $loc['title'] )
			               ? sanitize_text_field( (string) $loc['title'] ) : 'Client';
			$address     = isset( $loc['address'] )
			               ? sanitize_text_field( (string) $loc['address'] ) : '';
			if ( ! $location_fn || strpos( $location_fn, 'accounts/' ) !== 0 ) {
				$skipped[] = $location_fn;
				continue;
			}
			/* Vérifier si profil existe déjà pour cette location + agency */
			$existing = $wpdb->get_var( $wpdb->prepare(
				"SELECT id FROM `{$t_profiles}`
				 WHERE google_location_name = %s AND agency_id = %d LIMIT 1",
				$location_fn, $agency_id
			) );
			if ( $existing ) {
				$skipped[] = $location_fn;
				continue;
			}
			/* Extraire ville depuis adresse */
			$city_parts = explode( ',', $address );
			$city       = count( $city_parts ) > 1
			              ? trim( $city_parts[ count( $city_parts ) - 1 ] ) : '-';
			/* Créer profil client */
			$ins = array(
				'user_id'              => (int) $agency_row->admin_user_id,
				'business_name'        => $title,
				'city'                 => $city ?: '-',
				'category'             => 'Client',
				'current_level'        => 1,
				'score'                => 0,
				'country'              => 'US',
				'agency_id'            => $agency_id,
				'google_location_name' => $location_fn,
				'created_at'           => current_time( 'mysql' ),
				'updated_at'           => current_time( 'mysql' ),
			);
			$fmt = array( '%d', '%s', '%s', '%s', '%d', '%d', '%s', '%d', '%s', '%s', '%s' );
			/* Propager token OAuth admin vers profil client */
			if ( $admin_token_row && ! empty( $admin_token_row->google_access_token ) ) {
				$ins['google_access_token']    = $admin_token_row->google_access_token;
				$ins['google_refresh_token']   = $admin_token_row->google_refresh_token;
				$ins['google_token_expires_at'] = $admin_token_row->google_token_expires_at;
				$fmt[] = '%s';
				$fmt[] = '%s';
				$fmt[] = '%s';
			}
			$wpdb->insert( $t_profiles, $ins, $fmt );
			if ( $wpdb->insert_id ) {
				$new_pid = (int) $wpdb->insert_id;
				$created[] = array(
					'profile_id'           => $new_pid,
					'title'                => $title,
					'google_location_name' => $location_fn,
				);
				/* Sync GBP automatique post-import */
				wp_remote_post(
					'http://127.0.0.1:8001/auth/scan',
					array(
						'body'    => wp_json_encode( array( 'profile_id' => $new_pid ) ),
						'headers' => array( 'Content-Type' => 'application/json' ),
						'timeout' => 5,
						'blocking' => false,
					)
				);
				/* Sync photos GBP automatique post-import — non-bloquant (#BUG1 key_id + token) */
				wp_remote_post(
					rest_url( 'avision/v1/embed/sync-photos' ),
					array(
						'body'    => wp_json_encode( array(
							'profile_id' => $new_pid,
							'key_id'     => $key_id,
						) ),
						'headers' => array(
							'Content-Type'  => 'application/json',
							'X-Embed-Token' => self::generate_embed_token( $key_id, $new_pid ),
						),
						'timeout'  => 5,
						'blocking' => false,
					)
				);
			}
		}
		/* Vider pending_google_locations sur le profil admin après import */
		$admin_profile_id = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		if ( $admin_profile_id ) {
			$wpdb->update(
				$wpdb->prefix . 'avi_saas_profiles',
				array( 'pending_google_locations' => null ),
				array( 'id' => $admin_profile_id ),
				array( '%s' ),
				array( '%d' )
			);
		}
		return rest_ensure_response( array(
			'ok'      => true,
			'created' => $created,
			'skipped' => $skipped,
		) );
	}

	/**
	 * Lie une fiche GBP choisie par l'utilisateur (mode multi pending).
	 */
	public static function choose_gbp_location( \WP_REST_Request $request ) {
		global $wpdb;
		$body        = $request->get_json_params();
		$profile_id  = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$location_fn = isset( $body['location_full_name'] )
		               ? sanitize_text_field( (string) $body['location_full_name'] ) : '';
		$title       = isset( $body['title'] )
		               ? sanitize_text_field( (string) $body['title'] ) : '';
		if ( ! $profile_id || ! $location_fn ) {
			return new \WP_Error( 'invalid_params', 'profile_id et location_full_name requis.', array( 'status' => 422 ) );
		}
		if ( strpos( $location_fn, 'accounts/' ) !== 0 ) {
			return new \WP_Error( 'invalid_location', 'Format location invalide.', array( 'status' => 422 ) );
		}
		$t = $wpdb->prefix . 'avi_saas_profiles';
		$upd = array(
			'google_location_name'     => $location_fn,
			'pending_google_locations' => null,
			'updated_at'               => current_time( 'mysql' ),
		);
		$fmt = array( '%s', '%s', '%s' );
		if ( $title !== '' && $wpdb->get_var( $wpdb->prepare(
			"SHOW COLUMNS FROM `{$t}` LIKE %s", 'business_name'
		) ) === 'business_name' ) {
			$upd['business_name'] = $title;
			$fmt[]                = '%s';
		}
		$updated = $wpdb->update( $t, $upd, array( 'id' => $profile_id ), $fmt, array( '%d' ) );
		if ( $updated === false ) {
			return new \WP_Error( 'db_error', 'Erreur mise à jour profil.', array( 'status' => 500 ) );
		}
		return rest_ensure_response( array( 'ok' => true, 'google_location_name' => $location_fn ) );
	}

	/**
	 * Génère une URL embed signée et le snippet iframe.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function sign_embed_url( \WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		$key_id     = sanitize_text_field( isset( $body['key_id'] ) ? (string) $body['key_id'] : '' );
		$profile_id = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$lang       = sanitize_text_field( isset( $body['lang'] ) ? (string) $body['lang'] : 'en' );
		$theme      = sanitize_text_field( isset( $body['theme'] ) ? (string) $body['theme'] : 'light' );
		$logo_url   = esc_url_raw( isset( $body['logo_url'] ) ? (string) $body['logo_url'] : '' );
		$ttl        = absint( isset( $body['ttl'] ) ? $body['ttl'] : 86400 );
		$hosted     = ( isset( $body['hosted'] ) && (string) $body['hosted'] === '1' ) ? '1' : '';

		if ( ! $key_id || ! $profile_id ) {
			return new \WP_Error( 'invalid_params', 'key_id et profile_id requis.', array( 'status' => 422 ) );
		}

		global $wpdb;
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT secret_hash, status FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND status = 'active' LIMIT 1",
				$key_id
			)
		);
		if ( ! $row ) {
			return new \WP_Error( 'key_not_found', 'Clé embed introuvable ou inactive.', array( 'status' => 404 ) );
		}

		$ts      = time();
		$payload = $key_id . '|' . $profile_id . '|' . $ts;
		$sig     = hash_hmac( 'sha256', $payload, $row->secret_hash );

		$url_args = array(
			'key_id'     => $key_id,
			'sig'        => $sig,
			'profile_id' => $profile_id,
			'ts'         => $ts,
			'lang'       => $lang,
			'theme'      => $theme,
			'logo_url'   => $logo_url,
		);
		if ( $hosted === '1' ) {
			$url_args['hosted'] = '1';
		}
		$url = add_query_arg( $url_args, rest_url( 'avision/v1/embed' ) );

		$iframe = '<iframe src="' . esc_url( $url ) . '" '
			. 'width="100%" height="700" frameborder="0" '
			. 'allow="geolocation" loading="lazy"></iframe>';

		return new \WP_REST_Response(
			array(
				'url'        => $url,
				'iframe'     => $iframe,
				'expires_at' => gmdate( 'Y-m-d H:i:s', $ts + $ttl ),
			),
			200
		);
	}

	/**
	 * Crée une nouvelle clé embed.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function create_key( \WP_REST_Request $request ) {
		$body = $request->get_json_params();
		if ( ! is_array( $body ) ) {
			$body = array();
		}

		$key_type   = sanitize_key( isset( $body['key_type'] ) ? (string) $body['key_type'] : 'solo' );
		$profile_id = absint( isset( $body['profile_id'] ) ? $body['profile_id'] : 0 );
		$agency_id  = absint( isset( $body['agency_id'] ) ? $body['agency_id'] : 0 );
		$label      = sanitize_text_field( isset( $body['label'] ) ? (string) $body['label'] : '' );
		$domains    = null;
		if ( isset( $body['allowed_domains'] ) && is_array( $body['allowed_domains'] ) ) {
			$domains = wp_json_encode( $body['allowed_domains'] );
		}
		$expires = sanitize_text_field( isset( $body['expires_at'] ) ? (string) $body['expires_at'] : '' );

		if ( ! in_array( $key_type, array( 'solo', 'agency' ), true ) ) {
			return new \WP_Error( 'invalid_type', 'key_type doit être solo ou agency.', array( 'status' => 422 ) );
		}

		$key_id      = 'avi_' . bin2hex( random_bytes( 14 ) );
		$secret      = bin2hex( random_bytes( 32 ) );
		$secret_hash = hash( 'sha256', $secret );

		global $wpdb;
		$inserted = $wpdb->insert(
			$wpdb->prefix . 'avi_embed_keys',
			array(
				'key_id'          => $key_id,
				'secret_hash'     => $secret_hash,
				'key_type'        => $key_type,
				'profile_id'      => $profile_id ? $profile_id : null,
				'agency_id'       => $agency_id ? $agency_id : null,
				'label'           => $label,
				'allowed_domains' => $domains,
				'status'          => 'active',
				'expires_at'      => $expires ? $expires : null,
			),
			array( '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%s', '%s' )
		);

		if ( ! $inserted ) {
			return new \WP_Error( 'db_error', 'Erreur création clé.', array( 'status' => 500 ) );
		}

		return new \WP_REST_Response(
			array(
				'id'       => $wpdb->insert_id,
				'key_id'   => $key_id,
				'secret'   => $secret,
				'key_type' => $key_type,
				'warning'  => 'Sauvegardez ce secret maintenant — il ne sera plus affiché.',
			),
			201
		);
	}

	/**
	 * Active une licence embed via purchase code Envato (LocalEdge).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function activate_embed_license(
		\WP_REST_Request $request
	) {
		$purchase_code = sanitize_text_field(
			$request->get_param( 'purchase_code' ) ?: ''
		);
		$domain        = sanitize_text_field(
			$request->get_param( 'domain' ) ?: ''
		);
		$key_type      = sanitize_text_field(
			$request->get_param( 'key_type' ) ?: 'solo'
		);
		$profile_id    = absint(
			$request->get_param( 'profile_id' ) ?: 0
		);

		if ( ! $purchase_code || ! $domain ) {
			return new \WP_Error(
				'missing_params',
				'purchase_code and domain are required',
				array( 'status' => 400 )
			);
		}

		global $wpdb;

		$existing = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE purchase_code = %s LIMIT 1",
				$purchase_code
			)
		);
		if ( $existing ) {
			return new \WP_Error(
				'already_activated',
				'This purchase code is already activated',
				array( 'status' => 409 )
			);
		}

		// Validation licence depuis avi_localedge_licenses
		$license_row = $wpdb->get_row( $wpdb->prepare(
			"SELECT id, tier, lang, status, used_at FROM `{$wpdb->prefix}avi_localedge_licenses`
			 WHERE license_key = %s LIMIT 1",
			$purchase_code
		) );
		if ( ! $license_row ) {
			return new \WP_Error( 'invalid_license', 'License key not found.', array( 'status' => 404 ) );
		}
		if ( $license_row->status !== 'active' ) {
			return new \WP_Error( 'license_inactive', 'License key is not active.', array( 'status' => 403 ) );
		}
		if ( ! empty( $license_row->used_at ) ) {
			return new \WP_Error( 'license_used', 'License key already used on another domain.', array( 'status' => 409 ) );
		}
		// Override key_type depuis le tier licence (source de verite)
		$tier_to_keytype = array(
			'solo'      => 'solo',
			'agency_t1' => 'agency',
			'agency_t2' => 'agency',
			'agency_t3' => 'agency',
		);
		if ( isset( $tier_to_keytype[ $license_row->tier ] ) ) {
			$key_type = $tier_to_keytype[ $license_row->tier ];
		}
		// Recuperer la langue depuis la licence
		$license_lang = ! empty( $license_row->lang ) ? $license_row->lang : 'en';

		$envato_token   = defined( 'AVI_ENVATO_TOKEN' )
			? AVI_ENVATO_TOKEN : '';
		$envato_item_id = defined( 'AVI_LOCALEDGE_ITEM_ID' )
			? (int) AVI_LOCALEDGE_ITEM_ID : 0;

		if ( $envato_token && $envato_item_id ) {
			$response = wp_remote_get(
				'https://api.envato.com/v3/market/buyer/purchase'
				. '?code=' . rawurlencode( $purchase_code ),
				array(
					'headers' => array(
						'Authorization' => 'Bearer ' . $envato_token,
					),
					'timeout' => 10,
				)
			);

			if ( is_wp_error( $response ) ) {
				return new \WP_Error(
					'envato_unreachable',
					'Could not reach Envato API',
					array( 'status' => 502 )
				);
			}

			$body = json_decode(
				wp_remote_retrieve_body( $response ),
				true
			);

			if ( empty( $body['item']['id'] )
				|| (int) $body['item']['id'] !== $envato_item_id
			) {
				return new \WP_Error(
					'invalid_purchase',
					'Invalid or unauthorized purchase code',
					array( 'status' => 403 )
				);
			}
		}

		$key_id      = 'avi_' . bin2hex( random_bytes( 14 ) );
		$secret      = bin2hex( random_bytes( 32 ) );
		$secret_hash = hash( 'sha256', $secret );

		$insert_data = array(
			'key_id'        => $key_id,
			'secret_hash'   => $secret_hash,
			'key_type'      => in_array(
				$key_type,
				array( 'solo', 'agency' ),
				true
			) ? $key_type : 'solo',
			'profile_id'    => $profile_id ?: null,
			'domain'        => $domain,
			'purchase_code' => $purchase_code,
			'status'        => 'active',
			'guardian_plan' => 'lite',
		);
		$insert_format = array(
			'%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s',
		);
		$has_lang_col = $wpdb->get_var( "SHOW COLUMNS FROM `{$wpdb->prefix}avi_embed_keys` LIKE 'lang'" );
		if ( $has_lang_col ) {
			$insert_data['lang'] = $license_lang;
			$insert_format[]     = '%s';
		}

		$inserted = $wpdb->insert(
			$wpdb->prefix . 'avi_embed_keys',
			$insert_data,
			$insert_format
		);

		if ( ! $inserted ) {
			return new \WP_Error(
				'db_error',
				'Could not create embed key',
				array( 'status' => 500 )
			);
		}

		// Marquer la licence comme utilisee
		$wpdb->update(
			$wpdb->prefix . 'avi_localedge_licenses',
			array(
				'status'      => 'used',
				'used_at'     => current_time( 'mysql' ),
				'used_domain' => $domain,
			),
			array( 'id' => $license_row->id ),
			array( '%s', '%s', '%s' ),
			array( '%d' )
		);

		return new \WP_REST_Response(
			array(
				'success'  => true,
				'key_id'   => $key_id,
				'secret'   => $secret,
				'domain'   => $domain,
				'key_type' => $key_type,
				'warning'  => 'Save your secret now — it will not be shown again',
			),
			201
		);
	}

	/**
	 * Proxy FastAPI GET /reviews/more → shape aviEmbedReviewsData.reviews.
	 *
	 * @param \WP_REST_Request $request Requete REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function proxy_reviews_more( \WP_REST_Request $request ) {
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? intval( $body['profile_id'] ) : 0;
		$page_token = isset( $body['page_token'] ) ? sanitize_text_field( $body['page_token'] ) : '';
		$page_size  = isset( $body['page_size'] ) ? min( 50, intval( $body['page_size'] ) ) : 50;
		if ( ! $profile_id ) {
			return new \WP_Error( 'bad_request', 'profile_id manquant.', array( 'status' => 400 ) );
		}
		$url = 'http://127.0.0.1:8001/reviews/more?profile_id=' . $profile_id
			. '&page_size=' . $page_size
			. ( $page_token ? '&page_token=' . rawurlencode( $page_token ) : '' );
		$resp = wp_remote_get(
			$url,
			array(
				'timeout' => 15,
			)
		);
		if ( is_wp_error( $resp ) ) {
			return new \WP_Error( 'backend_error', 'Erreur backend reviews.', array( 'status' => 500 ) );
		}
		$status = wp_remote_retrieve_response_code( $resp );
		$data   = json_decode( wp_remote_retrieve_body( $resp ), true );
		if ( $status !== 200 || ! is_array( $data ) ) {
			return new \WP_Error( 'backend_error', 'Reponse backend invalide.', array( 'status' => 500 ) );
		}
		$star_map = array(
			1 => 'ONE',
			2 => 'TWO',
			3 => 'THREE',
			4 => 'FOUR',
			5 => 'FIVE',
		);
		$reviews  = array();
		$raw_list = isset( $data['reviews'] ) && is_array( $data['reviews'] ) ? $data['reviews'] : array();
		foreach ( $raw_list as $r ) {
			if ( ! is_array( $r ) ) {
				continue;
			}
			$star_num = isset( $r['star_rating'] ) ? (int) $r['star_rating'] : 5;
			$reviews[] = array(
				'review_id'      => isset( $r['review_id'] ) ? $r['review_id'] : '',
				'reviewer_name'  => isset( $r['reviewer'] ) ? $r['reviewer'] : 'Anonymous',
				'reviewer_photo' => isset( $r['reviewer_photo'] ) ? $r['reviewer_photo'] : '',
				'star_rating'    => isset( $star_map[ $star_num ] ) ? $star_map[ $star_num ] : 'FIVE',
				'comment'        => isset( $r['comment'] ) ? $r['comment'] : '',
				'create_time'    => isset( $r['create_time'] ) ? $r['create_time'] : '',
				'has_reply'      => ! empty( $r['has_reply'] ),
				'reply_comment'  => isset( $r['reply_text'] ) ? $r['reply_text'] : '',
				'reply_time'     => isset( $r['reply_time'] ) ? $r['reply_time'] : '',
				'review_name'    => isset( $r['review_name'] ) ? $r['review_name'] : '',
			);
		}
		// Persistance geree cote JS via /embed/reviews-cache-save (envoi batch complet sur derniere page)
		return rest_ensure_response(
			array(
				'reviews'         => $reviews,
				'next_page_token' => isset( $data['next_page_token'] ) ? $data['next_page_token'] : '',
				'total_count'     => isset( $data['total_count'] ) ? $data['total_count'] : 0,
				'average_rating'  => isset( $data['average_rating'] ) ? $data['average_rating'] : 0,
			)
		);
	}


	/**
	 * Persiste le batch complet des avis embed dans google_data_cache.
	 *
	 * @param \WP_REST_Request $request Requete REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function save_reviews_cache( \WP_REST_Request $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = isset( $body['profile_id'] ) ? intval( $body['profile_id'] ) : 0;
		$reviews    = isset( $body['reviews'] ) ? $body['reviews'] : array();
		if ( ! $profile_id || empty( $reviews ) ) {
			return new \WP_Error( 'bad_request', 'Parametres manquants.', array( 'status' => 400 ) );
		}
		$current = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT google_data_cache FROM `{$wpdb->prefix}avi_saas_profiles` WHERE id = %d LIMIT 1",
				$profile_id
			)
		);
		if ( ! $current || empty( $current->google_data_cache ) ) {
			return new \WP_Error( 'not_found', 'Cache introuvable.', array( 'status' => 404 ) );
		}
		$cache = json_decode( $current->google_data_cache, true );
		if ( ! is_array( $cache ) ) {
			return new \WP_Error( 'cache_error', 'Cache invalide.', array( 'status' => 500 ) );
		}
		// Remap shape embed → shape Google natif
		$star_map     = array(
			'ONE'   => 'ONE',
			'TWO'   => 'TWO',
			'THREE' => 'THREE',
			'FOUR'  => 'FOUR',
			'FIVE'  => 'FIVE',
		);
		$existing_ids = array();
		if ( isset( $cache['reviews']['reviews'] ) && is_array( $cache['reviews']['reviews'] ) ) {
			foreach ( $cache['reviews']['reviews'] as $er ) {
				if ( isset( $er['reviewId'] ) ) {
					$existing_ids[ $er['reviewId'] ] = true;
				}
			}
		} else {
			$cache['reviews']['reviews'] = array();
		}
		$added = 0;
		foreach ( $reviews as $r ) {
			if ( ! is_array( $r ) ) {
				continue;
			}
			$rid = isset( $r['review_id'] ) ? $r['review_id'] : '';
			if ( ! $rid || isset( $existing_ids[ $rid ] ) ) {
				continue;
			}
			$review_google = array(
				'reviewId'   => $rid,
				'reviewer'   => array(
					'displayName'     => isset( $r['reviewer_name'] ) ? $r['reviewer_name'] : '',
					'profilePhotoUrl' => isset( $r['reviewer_photo'] ) ? $r['reviewer_photo'] : '',
				),
				'starRating' => isset( $r['star_rating'] ) ? $r['star_rating'] : 'FIVE',
				'comment'    => isset( $r['comment'] ) ? $r['comment'] : '',
				'createTime' => isset( $r['create_time'] ) ? $r['create_time'] : '',
				'updateTime' => isset( $r['create_time'] ) ? $r['create_time'] : '',
				'name'       => isset( $r['review_name'] ) ? $r['review_name'] : '',
			);
			if ( ! empty( $r['has_reply'] ) && ! empty( $r['reply_comment'] ) ) {
				$review_google['reviewReply'] = array(
					'comment'    => $r['reply_comment'],
					'updateTime' => isset( $r['reply_time'] ) ? $r['reply_time'] : '',
				);
			}
			$cache['reviews']['reviews'][] = $review_google;
			$existing_ids[ $rid ]          = true;
			$added++;
		}
		// Supprimer nextPageToken (toutes les pages chargees)
		unset( $cache['reviews']['nextPageToken'] );
		$json = wp_json_encode( $cache, JSON_UNESCAPED_UNICODE );
		if ( ! is_string( $json ) || $json === '' ) {
			return new \WP_Error( 'encode_error', 'JSON encode failed.', array( 'status' => 500 ) );
		}
		$wpdb->update(
			$wpdb->prefix . 'avi_saas_profiles',
			array( 'google_data_cache' => $json ),
			array( 'id' => $profile_id ),
			array( '%s' ),
			array( '%d' )
		);
		error_log( '[AVI reviews] save_cache +' . $added . ' profil=' . $profile_id . ' total=' . count( $cache['reviews']['reviews'] ) );
		return rest_ensure_response(
			array(
				'success' => true,
				'added'   => $added,
				'total'   => count( $cache['reviews']['reviews'] ),
			)
		);
	}

	/**
	 * Upgrade/downgrade tier agence LocalEdge hosted (avi_localedge_agency_meta).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function handle_agency_tier_change( \WP_REST_Request $request ) {
		global $wpdb;

		$body      = $request->get_json_params();
		$key_id    = isset( $body['key_id'] ) ? sanitize_text_field( $body['key_id'] ) : '';
		$agency_id = isset( $body['agency_id'] ) ? intval( $body['agency_id'] ) : 0;
		$new_tier  = isset( $body['new_tier'] ) ? intval( $body['new_tier'] ) : 0;
		$lang      = isset( $body['lang'] ) ? sanitize_text_field( $body['lang'] ) : 'en';

		if ( ! $key_id || ! $agency_id || ! in_array( $new_tier, array( 1, 2, 3 ), true ) ) {
			return new \WP_Error( 'bad_request', 'Parametres manquants.', array( 'status' => 400 ) );
		}

		$key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT key_id, agency_id FROM `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s AND key_type = %s AND status = %s LIMIT 1",
				$key_id,
				'agency',
				'active'
			)
		);
		if ( ! $key_row || (int) $key_row->agency_id !== $agency_id ) {
			return new \WP_Error( 'unauthorized', 'Cle agency invalide.', array( 'status' => 403 ) );
		}

		$meta = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT tier, max_listings FROM `{$wpdb->prefix}avi_localedge_agency_meta`
				 WHERE agency_id = %d LIMIT 1",
				$agency_id
			)
		);
		if ( ! $meta ) {
			return new \WP_Error( 'not_found', 'Meta agence introuvable.', array( 'status' => 404 ) );
		}

		$current_tier = (int) $meta->tier;

		if ( $new_tier === $current_tier ) {
			return new \WP_Error( 'no_change', 'Tier identique au tier actuel.', array( 'status' => 400 ) );
		}

		$tier_max = array( 1 => 10, 2 => 50, 3 => 1000 );

		if ( $new_tier < $current_tier ) {
			$new_max    = $tier_max[ $new_tier ];
			$used_count = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(*) FROM `{$wpdb->prefix}avi_saas_profiles`
					 WHERE agency_id = %d AND user_id IS NOT NULL",
					$agency_id
				)
			);

			if ( $used_count > $new_max ) {
				return new \WP_Error(
					'downgrade_blocked',
					'Downgrade impossible : ' . $used_count . ' fiches actives, limite ' . $new_tier . ' = ' . $new_max . '.',
					array( 'status' => 409 )
				);
			}

			$wpdb->update(
				$wpdb->prefix . 'avi_localedge_agency_meta',
				array(
					'tier'         => $new_tier,
					'max_listings' => $new_max,
				),
				array( 'agency_id' => $agency_id ),
				array( '%d', '%d' ),
				array( '%d' )
			);

			return rest_ensure_response(
				array(
					'success'      => true,
					'action'       => 'downgrade',
					'new_tier'     => $new_tier,
					'max_listings' => $new_max,
				)
			);
		}

		$price_map = function_exists( 'avi_get_localedge_agency_price_map' )
			? avi_get_localedge_agency_price_map()
			: array();

		if ( empty( $price_map ) ) {
			return new \WP_Error( 'config_error', 'Price map indisponible.', array( 'status' => 500 ) );
		}

		$lang_key         = isset( $price_map[ $new_tier ][ $lang ] ) ? $lang : 'en';
		$new_price_id     = isset( $price_map[ $new_tier ][ $lang_key ] ) ? $price_map[ $new_tier ][ $lang_key ] : '';
		$current_price_id = isset( $price_map[ $current_tier ][ $lang_key ] ) ? $price_map[ $current_tier ][ $lang_key ] : '';

		if ( ! $new_price_id || ! $current_price_id ) {
			return new \WP_Error( 'price_not_found', 'Price ID introuvable pour ce tier/langue.', array( 'status' => 400 ) );
		}

		$stripe_key = defined( 'AVISION_STRIPE_SECRET_KEY' ) ? AVISION_STRIPE_SECRET_KEY : '';
		if ( ! $stripe_key ) {
			return new \WP_Error( 'stripe_config', 'Stripe non configure.', array( 'status' => 500 ) );
		}

		$new_price_resp = wp_remote_get(
			'https://api.stripe.com/v1/prices/' . $new_price_id,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $stripe_key,
				),
			)
		);
		$current_price_resp = wp_remote_get(
			'https://api.stripe.com/v1/prices/' . $current_price_id,
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $stripe_key,
				),
			)
		);

		if ( is_wp_error( $new_price_resp ) || is_wp_error( $current_price_resp ) ) {
			return new \WP_Error( 'stripe_error', 'Erreur lecture prix Stripe.', array( 'status' => 500 ) );
		}

		$new_price_data     = json_decode( wp_remote_retrieve_body( $new_price_resp ), true );
		$current_price_data = json_decode( wp_remote_retrieve_body( $current_price_resp ), true );

		$new_amount     = isset( $new_price_data['unit_amount'] ) ? (int) $new_price_data['unit_amount'] : 0;
		$current_amount = isset( $current_price_data['unit_amount'] ) ? (int) $current_price_data['unit_amount'] : 0;

		if ( ! $new_amount || ! $current_amount || $new_amount <= $current_amount ) {
			return new \WP_Error( 'price_error', 'Montants Stripe invalides pour prorata.', array( 'status' => 400 ) );
		}

		$prorata_amount = $new_amount - $current_amount;

		$admin_user_id = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT admin_user_id FROM `{$wpdb->prefix}avi_saas_agencies` WHERE id = %d LIMIT 1",
				$agency_id
			)
		);
		$user_email = '';
		if ( $admin_user_id ) {
			$admin_user = get_userdata( $admin_user_id );
			if ( $admin_user && ! empty( $admin_user->user_email ) ) {
				$user_email = $admin_user->user_email;
			}
		}

		// Construire l URL embed signee pour redirection post-paiement
		$embed_key_row = $wpdb->get_row( $wpdb->prepare(
			"SELECT key_id, profile_id, lang, hosted, secret_hash FROM `{$wpdb->prefix}avi_embed_keys`
			 WHERE agency_id = %d AND key_type = %s AND status = %s LIMIT 1",
			$agency_id, "agency", "active"
		) );
		$success_url = home_url( "/localedge/?upgrade=success&tier=" . $new_tier );
		if ( $embed_key_row ) {
			$ts        = time();
			$sig       = hash_hmac( "sha256", $embed_key_row->key_id . "|" . $embed_key_row->profile_id . "|" . $ts, $embed_key_row->secret_hash );
			$embed_url = home_url( "/wp-json/avision/v1/embed" )
				. "?key_id=" . urlencode( $embed_key_row->key_id )
				. "&sig=" . $sig
				. "&profile_id=" . (int) $embed_key_row->profile_id
				. "&ts=" . $ts
				. "&lang=" . urlencode( $embed_key_row->lang ?: "en" )
				. "&hosted=1"
				. "&upgrade=success&tier=" . $new_tier;
			$success_url = $embed_url;
		}

		$checkout_body = array(
			'mode'                    => 'payment',
			'allow_promotion_codes'   => 'true',
			'line_items[0][price_data][currency]'           => 'usd',
			'line_items[0][price_data][unit_amount]'        => (string) $prorata_amount,
			'line_items[0][price_data][product_data][name]' => 'LocalEdge Agency — Upgrade Tier ' . $current_tier . ' to Tier ' . $new_tier,
			'line_items[0][quantity]'                       => '1',
			'success_url'             => $success_url,
			'cancel_url'              => home_url( '/localedge/?upgrade=cancelled' ),
			'metadata[source]'        => 'localedge_tier_change',
			'metadata[agency_id]'     => (string) $agency_id,
			'metadata[old_tier]'      => (string) $current_tier,
			'metadata[new_tier]'      => (string) $new_tier,
			'metadata[lang]'            => $lang,
		);
		if ( $user_email ) {
			$checkout_body['customer_email'] = $user_email;
		}

		$session_resp = wp_remote_post(
			'https://api.stripe.com/v1/checkout/sessions',
			array(
				'headers' => array(
					'Authorization' => 'Bearer ' . $stripe_key,
				),
				'body'    => $checkout_body,
			)
		);

		if ( is_wp_error( $session_resp ) ) {
			return new \WP_Error( 'stripe_session', 'Erreur creation session Stripe.', array( 'status' => 500 ) );
		}

		$session_data = json_decode( wp_remote_retrieve_body( $session_resp ), true );

		if ( empty( $session_data['url'] ) ) {
			return new \WP_Error( 'stripe_session', 'Session Stripe sans URL.', array( 'status' => 500 ) );
		}

		return rest_ensure_response(
			array(
				'success'      => true,
				'action'       => 'upgrade',
				'checkout_url' => $session_data['url'],
				'new_tier'     => $new_tier,
				'prorata'      => $prorata_amount,
			)
		);
	}

	/**
	 * Crée une session Stripe Checkout pour achat crédits embed.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function create_embed_checkout(
		\WP_REST_Request $request
	) {
		$pack = sanitize_text_field(
			$request->get_param( 'pack' ) ?: ''
		);
		$key_id = sanitize_text_field(
			$request->get_param( 'key_id' ) ?: ''
		);
		$profile_id = absint(
			$request->get_param( 'profile_id' ) ?: 0
		);
		$credits = absint(
			$request->get_param( 'credits' ) ?: 0
		);
		$type = sanitize_text_field(
			$request->get_param( 'type' ) ?: 'solo'
		);

		if ( ! $key_id ) {
			return new \WP_Error(
				'missing_key',
				'key_id required',
				array( 'status' => 400 )
			);
		}

		$stripe_key = defined( 'AVISION_STRIPE_SECRET_KEY' )
			? AVISION_STRIPE_SECRET_KEY : '';
		if ( ! $stripe_key ) {
			return new \WP_Error(
				'stripe_missing',
				'Stripe not configured',
				array( 'status' => 500 )
			);
		}

		$line_items  = array();
		$credit_qty  = 0;
		$use_price_id = false;

		if ( $pack && isset( self::$embed_price_ids[ $pack ] ) ) {
			$line_items[] = array(
				'price'    => self::$embed_price_ids[ $pack ],
				'quantity' => 1,
			);
			$credit_qty   = self::$embed_pack_credits[ $pack ] ?? 0;
			$use_price_id = true;
		} elseif ( $credits >= 10 ) {
			$tiers = $type === 'agency'
				? self::$agency_credit_tiers
				: self::$solo_credit_tiers;

			$unit_price = 0.200;
			foreach ( $tiers as $tier ) {
				if ( $credits >= $tier['min']
					&& $credits <= $tier['max']
				) {
					$unit_price = $tier['price'];
					break;
				}
			}

			$total_cents = (int) round(
				$credits * $unit_price * 100
			);

			if ( $total_cents < 200 ) {
				return new \WP_Error(
					'min_amount',
					'Minimum $2.00 required',
					array( 'status' => 400 )
				);
			}

			$line_items[] = array(
				'price_data' => array(
					'currency'     => 'usd',
					'unit_amount'  => $total_cents,
					'product_data' => array(
						'name' => $credits . ' LocalEdge Credits',
					),
				),
				'quantity'   => 1,
			);
			$credit_qty = $credits;
		} else {
			return new \WP_Error(
				'invalid_pack',
				'Invalid pack or credits amount',
				array( 'status' => 400 )
			);
		}

		global $wpdb;
		/* Construire URL embed signée pour redirect Stripe */
		$embed_key_row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT secret_hash FROM
				 `{$wpdb->prefix}avi_embed_keys`
				 WHERE key_id = %s
				   AND status = 'active'
				 LIMIT 1",
				$key_id
			)
		);

		if ( ! $embed_key_row ) {
			return new \WP_Error(
				'invalid_key',
				'Invalid embed key',
				array( 'status' => 403 )
			);
		}

		$ts      = time();
		$payload = $key_id . '|' . $profile_id
		           . '|' . $ts;
		$sig     = hash_hmac(
			'sha256',
			$payload,
			$embed_key_row->secret_hash
		);

		$embed_base_args = array(
			'key_id'     => $key_id,
			'sig'        => $sig,
			'profile_id' => $profile_id,
			'ts'         => $ts,
		);

		$success_url = add_query_arg(
			array_merge(
				$embed_base_args,
				array( 'purchase' => 'success' )
			),
			rest_url( 'avision/v1/embed' )
		);

		$cancel_url = add_query_arg(
			$embed_base_args,
			rest_url( 'avision/v1/embed' )
		);

		$stripe_body = array(
			'mode'                     => 'payment',
			'line_items[0][quantity]'  => 1,
			'success_url'              => $success_url,
			'cancel_url'               => $cancel_url,
			'metadata[key_id]'         => $key_id,
			'metadata[profile_id]'     => (string) $profile_id,
			'metadata[credits]'          => (string) $credit_qty,
			'metadata[pack]'           => $pack ?: 'custom',
			'metadata[type]'           => $type,
			'metadata[source]'         => 'localedge_embed',
		);

		if ( $use_price_id ) {
			$stripe_body['line_items[0][price]'] = $line_items[0]['price'];
		} else {
			$stripe_body['line_items[0][price_data][currency]'] = $line_items[0]['price_data']['currency'];
			$stripe_body['line_items[0][price_data][unit_amount]'] = $line_items[0]['price_data']['unit_amount'];
			$stripe_body['line_items[0][price_data][product_data][name]'] = $line_items[0]['price_data']['product_data']['name'];
		}

		$response = wp_remote_post(
			'https://api.stripe.com/v1/checkout/sessions',
			array(
				'timeout' => 15,
				'headers' => array(
					'Authorization' => 'Bearer ' . $stripe_key,
					'Content-Type'  => 'application/x-www-form-urlencoded',
				),
				'body'    => http_build_query( $stripe_body ),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_Error(
				'stripe_error',
				$response->get_error_message(),
				array( 'status' => 502 )
			);
		}

		$body = json_decode(
			wp_remote_retrieve_body( $response ),
			true
		);

		if ( empty( $body['url'] ) ) {
			return new \WP_Error(
				'stripe_no_url',
				$body['error']['message'] ?? 'Stripe error',
				array( 'status' => 502 )
			);
		}

		return new \WP_REST_Response(
			array(
				'success'      => true,
				'checkout_url' => $body['url'],
				'credits'      => $credit_qty,
			),
			200
		);
	}

	/**
	 * Liste les clés embed (sans secret).
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function list_keys( \WP_REST_Request $request ) {
		global $wpdb;
		$rows = $wpdb->get_results(
			"SELECT id, key_id, key_type, profile_id, agency_id,
					label, allowed_domains, scopes, status,
					last_used_at, expires_at, created_at
			. FROM `{$wpdb->prefix}avi_embed_keys`
			. ORDER BY created_at DESC"
		);
		return new \WP_REST_Response( $rows, 200 );
	}

	/**
	 * Révoque une clé embed.
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function revoke_key( \WP_REST_Request $request ) {
		$id = absint( $request->get_param( 'id' ) );
		global $wpdb;
		$updated = $wpdb->update(
			$wpdb->prefix . 'avi_embed_keys',
			array( 'status' => 'revoked' ),
			array( 'id' => $id ),
			array( '%s' ),
			array( '%d' )
		);
		if ( ! $updated ) {
			return new \WP_Error( 'not_found', 'Clé introuvable.', array( 'status' => 404 ) );
		}
		return new \WP_REST_Response( array( 'revoked' => true ), 200 );
	}

	/**
	 * Affiche une erreur HTML pour l'iframe (pas JSON).
	 *
	 * @param string $code   Code erreur.
	 * @param string $msg    Message.
	 * @param int    $status Code HTTP.
	 * @return void
	 */
	private static function embed_error( string $code, string $msg, int $status ) {
		status_header( $status );
		header( 'Content-Type: text/html; charset=UTF-8' );
		echo '<!DOCTYPE html><html><body style="font-family:sans-serif;padding:20px">'
			. '<h3>⚠️ Avision Embed Error</h3>'
			. '<p><strong>' . esc_html( $code ) . '</strong>: ' . esc_html( $msg ) . '</p>'
			. ( $code === 'invalid_signature' ? '<p style="margin-top:12px;font-size:14px;color:#6b7280;">Please reload the page from your WordPress dashboard to generate a new session link.</p>' : '' )
			. '</body></html>';
		exit;
	}

	/**
	 * GET /embed/guardian-alerts?profile_id=X
	 * #SprintGL-C3-alerts
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function get_guardian_alerts( \WP_REST_Request $request ) {
		global $wpdb;
		$profile_id = intval( $request->get_param( 'profile_id' ) );
		if ( ! $profile_id ) {
			return new \WP_Error( 'missing_profile', 'profile_id requis', array( 'status' => 400 ) );
		}
		$table  = $wpdb->prefix . 'avi_guardian_alerts';
		$alerts = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT id, alert_type, old_value, new_value, detected_at, is_read, credits_used
				 FROM {$table}
				 WHERE profile_id = %d
				 ORDER BY detected_at DESC
				 LIMIT 20",
				$profile_id
			),
			ARRAY_A
		);
		$unread = 0;
		foreach ( $alerts ?: array() as $a ) {
			if ( ! intval( $a['is_read'] ) ) {
				$unread++;
			}
		}
		return rest_ensure_response(
			array(
				'alerts'       => $alerts ?: array(),
				'unread_count' => $unread,
			)
		);
	}

	/**
	 * POST /embed/guardian-alerts/mark-read
	 * Body JSON : { "profile_id": 583 }
	 * #SprintGL-C3-mark-read
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function mark_guardian_alerts_read( \WP_REST_Request $request ) {
		global $wpdb;
		$body       = $request->get_json_params();
		$profile_id = intval( $body['profile_id'] ?? 0 );
		if ( ! $profile_id ) {
			return new \WP_Error( 'missing_profile', 'profile_id requis', array( 'status' => 400 ) );
		}
		$table = $wpdb->prefix . 'avi_guardian_alerts';
		$wpdb->update(
			$table,
			array( 'is_read' => 1 ),
			array( 'profile_id' => $profile_id, 'is_read' => 0 ),
			array( '%d' ),
			array( '%d', '%d' )
		);
		return rest_ensure_response( array( 'success' => true ) );
	}

	/**
	 * GET /embed/guardian-plan?profile_id=X
	 * #SprintGL-C3-plan
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response|\WP_Error
	 */
	public static function get_guardian_plan( \WP_REST_Request $request ) {
		global $wpdb;
		$profile_id = intval( $request->get_param( 'profile_id' ) );
		if ( ! $profile_id ) {
			return new \WP_Error( 'missing_profile', 'profile_id requis', array( 'status' => 400 ) );
		}
		$keys_table     = $wpdb->prefix . 'avi_embed_keys';
		$profiles_table = $wpdb->prefix . 'avi_saas_profiles';
		$trial_days     = 15;
		$row = $wpdb->get_row(
			$wpdb->prepare(
				"SELECT k.guardian_plan, k.guardian_activated_at, p.agency_id
				FROM {$keys_table} k
				LEFT JOIN {$profiles_table} p ON p.id = k.profile_id
				WHERE k.profile_id = %d
				LIMIT 1",
				$profile_id
			)
		);
		if ( ! $row ) {
			return new \WP_Error( 'not_found', 'Profil introuvable', array( 'status' => 404 ) );
		}
		$plan       = $row->guardian_plan ?: 'free';
		$owner_type = ( $row->agency_id !== null ) ? 'agency' : 'profile';
		if ( empty( $row->guardian_activated_at ) ) {
			$wpdb->update(
				$keys_table,
				array( 'guardian_activated_at' => current_time( 'mysql', true ) ),
				array( 'profile_id' => $profile_id ),
				array( '%s' ),
				array( '%d' )
			);
			$activated_at = new \DateTime( 'now', new \DateTimeZone( 'UTC' ) );
		} else {
			$activated_at = new \DateTime( $row->guardian_activated_at, new \DateTimeZone( 'UTC' ) );
		}
		$now         = new \DateTime( 'now', new \DateTimeZone( 'UTC' ) );
		$days_active = (int) $now->diff( $activated_at )->days;
		$is_trial    = ( $plan !== 'paid' ) && ( $days_active < $trial_days );
		$credits_available = 0;
		if ( $owner_type === 'profile' ) {
			$credits_table = $wpdb->prefix . 'avi_embed_credits';
			$credits_available = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT GREATEST(0, credits_total + COALESCE(credits_bonus,0) - credits_used)
					FROM {$credits_table}
					WHERE profile_id = %d
					ORDER BY purchased_at DESC
					LIMIT 1",
					$profile_id
				)
			);
		}
		$next_billing_date = '';
		if ( $plan === 'paid' && ! empty( $row->guardian_activated_at ) ) {
			$activated_dt = new \DateTime( $row->guardian_activated_at, new \DateTimeZone( 'UTC' ) );
			$next_billing  = clone $activated_dt;
			$months_elapsed = $days_active > 0 ? (int) floor( $days_active / 30 ) : 0;
			$next_billing->modify( '+' . ( $months_elapsed + 1 ) . ' months' );
			$next_billing_date = $next_billing->format( 'Y-m-d' );
		}
		return rest_ensure_response(
			array(
				'plan'                  => $plan,
				'days_active'           => $days_active,
				'is_trial'              => $is_trial,
				'is_paid'               => $plan === 'paid',
				'trial_days'            => $trial_days,
				'owner_type'            => $owner_type,
				'credits_available'     => $credits_available,
				'credits_per_detection' => 2,
				'next_billing_date'     => $next_billing_date,
			)
		);
	}

	public static function run_guardian_monthly_billing() {
		global $wpdb;
		$keys_table     = $wpdb->prefix . 'avi_embed_keys';
		$credits_table  = $wpdb->prefix . 'avi_embed_credits';
		$profiles_table = $wpdb->prefix . 'avi_saas_profiles';
		$trial_days     = 15;
		$monthly_cost   = 3;
		$rows           = $wpdb->get_results(
			"SELECT k.profile_id, k.key_id, k.guardian_activated_at, p.agency_id
			FROM {$keys_table} k
			LEFT JOIN {$profiles_table} p ON p.id = k.profile_id
			WHERE k.guardian_plan IN ('paid')
			AND k.status = 'active'
			AND k.guardian_activated_at IS NOT NULL"
		);
		if ( empty( $rows ) ) {
			return;
		}
		foreach ( $rows as $row ) {
			$profile_id   = intval( $row->profile_id );
			$activated_at = new \DateTime( $row->guardian_activated_at, new \DateTimeZone( 'UTC' ) );
			$now          = new \DateTime( 'now', new \DateTimeZone( 'UTC' ) );
			$days_active  = (int) $now->diff( $activated_at )->days;
			if ( $days_active < $trial_days ) {
				continue;
			}
			if ( $row->agency_id !== null ) {
				continue;
			}
			$credit_row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT id,
					GREATEST(0, credits_total + COALESCE(credits_bonus,0) - credits_used) AS available
					FROM {$credits_table}
					WHERE profile_id = %d
					ORDER BY purchased_at DESC
					LIMIT 1",
					$profile_id
				)
			);
			if ( ! $credit_row || intval( $credit_row->available ) < $monthly_cost ) {
				$wpdb->update(
					$keys_table,
					array( 'guardian_plan' => 'free' ),
					array( 'profile_id' => $profile_id ),
					array( '%s' ),
					array( '%d' )
				);
				continue;
			}
			$wpdb->update(
				$credits_table,
				array(
					'credits_used' => $wpdb->get_var(
						$wpdb->prepare(
							"SELECT credits_used FROM {$credits_table} WHERE id = %d",
							intval( $credit_row->id )
						)
					) + $monthly_cost,
				),
				array( 'id' => intval( $credit_row->id ) ),
				array( '%d' ),
				array( '%d' )
			);
		}
	}

	public static function post_guardian_activate( \WP_REST_Request $request ) {
		global $wpdb;
		$profile_id = intval( $request->get_param( 'profile_id' ) );
		if ( ! $profile_id ) {
			return new \WP_Error( 'missing_profile', 'profile_id requis', array( 'status' => 400 ) );
		}
		$keys_table = $wpdb->prefix . 'avi_embed_keys';
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$keys_table}
				SET guardian_plan = 'paid', guardian_activated_at = NOW()
				WHERE profile_id = %d",
				$profile_id
			)
		);
		return rest_ensure_response( array( 'success' => true, 'plan' => 'paid' ) );
	}

	public static function post_guardian_deactivate( \WP_REST_Request $request ) {
		global $wpdb;
		$profile_id = intval( $request->get_param( 'profile_id' ) );
		if ( ! $profile_id ) {
			return new \WP_Error( 'missing_profile', 'profile_id requis', array( 'status' => 400 ) );
		}
		$keys_table = $wpdb->prefix . 'avi_embed_keys';
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE {$keys_table}
				SET guardian_plan = 'free', guardian_activated_at = NULL
				WHERE profile_id = %d",
				$profile_id
			)
		);
		$updated = $wpdb->rows_affected;
		if ( $updated === false ) {
			return new \WP_Error( 'db_error', 'Erreur base de données', array( 'status' => 500 ) );
		}
		return rest_ensure_response( array( 'success' => true, 'plan' => 'free' ) );
	}

	/**
	 * GET /embed/citations?profile_id=X
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function get_citations( \WP_REST_Request $request ): \WP_REST_Response {
		global $wpdb;
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		if ( ! $profile_id ) {
			return new \WP_REST_Response( array( 'error' => 'Missing profile_id' ), 400 );
		}
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT directory_slug, status, listing_url, done_at, last_updated_at
				 FROM {$wpdb->prefix}avi_citations
				 WHERE profile_id = %d",
				$profile_id
			),
			ARRAY_A
		);
		$citations = array();
		foreach ( $rows as $row ) {
			$citations[ $row['directory_slug'] ] = array(
				'status'          => $row['status'],
				'listing_url'     => $row['listing_url'],
				'done_at'         => $row['done_at'],
				'last_updated_at' => $row['last_updated_at'],
			);
		}
		return new \WP_REST_Response( array( 'citations' => $citations ), 200 );
	}

	/**
	 * POST /embed/citations/save
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function save_citation( \WP_REST_Request $request ): \WP_REST_Response {
		global $wpdb;
		$body        = $request->get_json_params();
		$profile_id  = absint( $body['profile_id'] ?? 0 );
		$slug        = sanitize_text_field( $body['directory_slug'] ?? '' );
		$status      = sanitize_text_field( $body['status'] ?? 'done' );
		$listing_url = esc_url_raw( $body['listing_url'] ?? '' );
		if ( ! $profile_id || ! $slug ) {
			return new \WP_REST_Response( array( 'error' => 'Missing params' ), 400 );
		}
		if ( ! in_array( $status, array( 'none', 'done', 'already_listed', 'hidden' ), true ) ) {
			return new \WP_REST_Response( array( 'error' => 'Invalid status' ), 400 );
		}
		$now = current_time( 'mysql' );
		$wpdb->replace(
			$wpdb->prefix . 'avi_citations',
			array(
				'profile_id'      => $profile_id,
				'directory_slug'  => $slug,
				'status'          => $status,
				'listing_url'     => $listing_url ?: null,
				'done_at'         => in_array( $status, array( 'done', 'already_listed' ), true ) ? $now : null,
				'last_updated_at' => $now,
			),
			array( '%d', '%s', '%s', '%s', '%s', '%s' )
		);
		return new \WP_REST_Response( array( 'success' => true ), 200 );
	}

	/**
	 * GET /embed/citations/score?profile_id=X&total=N
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function get_citations_score( \WP_REST_Request $request ): \WP_REST_Response {
		global $wpdb;
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$total      = absint( $request->get_param( 'total' ) ?? 0 );
		if ( ! $profile_id || ! $total ) {
			return new \WP_REST_Response( array( 'score' => 0, 'done' => 0 ), 200 );
		}
		$done = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$wpdb->prefix}avi_citations
				 WHERE profile_id = %d AND status IN ('done','already_listed')",
				$profile_id
			)
		);
		$score = $total > 0 ? (int) round( ( $done / $total ) * 15 ) : 0;
		return new \WP_REST_Response(
			array(
				'score' => $score,
				'done'  => $done,
				'total' => $total,
			),
			200
		);
	}

	/**
	 * GET /embed/score-history?profile_id=X&period=30d&keyword=
	 *
	 * @param \WP_REST_Request $request Requête REST.
	 * @return \WP_REST_Response
	 */
	public static function get_score_history( \WP_REST_Request $request ): \WP_REST_Response {
		$profile_id = absint( $request->get_param( 'profile_id' ) );
		$period     = sanitize_text_field( $request->get_param( 'period' ) ?? '30d' );
		$keyword    = sanitize_text_field( $request->get_param( 'keyword' ) ?? '' );
		if ( ! $profile_id ) {
			return new \WP_REST_Response( array( 'error' => 'Missing profile_id' ), 400 );
		}

		$allowed_periods = array( 'daily', '7d', '30d', '90d', '1y' );
		if ( ! in_array( $period, $allowed_periods, true ) ) {
			$period = '30d';
		}

		$backend_url = 'http://127.0.0.1:8001/guardian-lite/score-history';
		$params      = array(
			'profile_id' => $profile_id,
			'period'     => $period,
		);
		if ( $keyword ) {
			$params['keyword'] = $keyword;
		}

		$url      = $backend_url . '?' . http_build_query( $params );
		$response = wp_remote_get(
			$url,
			array(
				'timeout' => 10,
				'headers' => array(
					'X-AVI-Admin-Key' => defined( 'AVISION_ADMIN_API_KEY' ) ? AVISION_ADMIN_API_KEY : '',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return new \WP_REST_Response( array( 'history' => array(), 'heatmap' => array() ), 200 );
		}

		$body = json_decode( wp_remote_retrieve_body( $response ), true );
		return new \WP_REST_Response( $body ?: array( 'history' => array(), 'heatmap' => array() ), 200 );
	}
}

Avision_Embed::init();
