<?php

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

class Sabriel_Module_Branding extends Sabriel_Module {

	const PILA_FONT = "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif";

	const FIELDS = [
		'bot_name'                => '',
		'logo_url'                => '',
		'primary_color'           => '#0d0d0d',
		'secondary_color'         => '#1461CC',
		'bg_color'                => '#f0f0f0',
		'chat_bg_color'           => '#ffffff',
		'bot_bubble_bg'           => '#ffffff',
		'bot_bubble_text'         => '#1a1a1a',
		'user_bubble_bg'          => '#0d0d0d',
		'user_bubble_text'        => '#f2f2f2',
		'name_color'              => '#f0f0f1',
		'border_color'            => '#e5e5e5',
		'input_bg'                => '#f5f5f5',
		'button_bg'               => '#0d0d0d',
		'dot_color'               => '#ffffff',
		'online_text_color'       => 'rgba(255,255,255,0.38)',
		'online_dot_color'        => '#22c55e',
		'header_icon_color'       => 'rgba(255,255,255,0.32)',
		'header_icon_hover_color' => 'rgba(255,255,255,0.75)',
		'icon_color'              => '#999999',
		'send_icon_color'         => '#ffffff',
		'bubble_icon_color'       => '#ffffff',
		'panel_bg_color'          => '#ffffff',
		'panel_text_color'        => '#111111',
		'profile_bg_color'        => '#ffffff',
		'profile_text_color'      => '#111111',
		'profile_button_bg_color'   => '#0d0d0d',
		'profile_button_text_color' => '#f0f0f0',
		'profile_label_color'       => '#666666',
		'history_card_bg_color'   => '#f8f8f8',
		'avatar_bg_color'         => '#1461CC',
		'input_text_color'        => '#111111',
		'closed_button_bg_color'  => '#0d0d0d',

		/*
		 * ⚠ SPENTO DI SERIE, E NON E' UNA SCELTA COMMERCIALE: la linea guida 10 di
		 * wordpress.org dice che ogni scritta «Powered by» e ogni link dell'autore
		 * devono essere facoltativi e NON comparire di partenza sul sito pubblico.
		 * Chi vuole mostrarlo lo accende da Personalizzazione. NON metterlo a true.
		 */
		'mostra_credito'          => false,
	];

	/**
	 * I campi d'aspetto che QUESTA edizione governa davvero, cioe' quelli che hanno
	 * un comando nel pannello.
	 *
	 * ⚠ Serve all'importazione. `FIELDS` elenca anche i colori che il widget sa
	 * disegnare ma che qui non si possono scegliere: un file esportato dall'edizione
	 * completa li porta tutti, e importandolo alla lettera un sito lasciava al
	 * proprietario dei colori che vedeva ma non poteva piu' toccare da nessuna parte.
	 * Un'importazione deve scrivere solo quello che questa edizione sa gestire.
	 * Chi aggiunge un comando nuovo al pannello lo aggiunge QUI e basta.
	 */
	const CAMPI_GESTITI = [
		'bot_name', 'logo_url', 'mostra_credito',
		'primary_color', 'secondary_color', 'bg_color', 'name_color', 'avatar_bg_color',
		'online_text_color', 'header_icon_color', 'header_icon_hover_color',
	];

	public function get_id() {
		return 'branding';
	}

	public function register_hooks() {

		add_action( 'admin_menu', [ $this, 'add_submenu' ], 20 );
	}

	public static function get( $key ) {
		$default = self::FIELDS[ $key ] ?? '';
		$valore  = Sabriel_Base::get( $key, $default );

		if ( '' === trim( (string) $valore ) ) {
			if ( 'bot_name' === $key ) {
				return self::nome_bot_predefinito();
			}
		}
		return $valore;
	}

	public static function nome_bot_predefinito() {
		$nome = trim( (string) Sabriel_Base::get( 'business_name', '' ) );
		if ( '' !== $nome ) {
			return $nome;
		}
		$sito = trim( (string) get_bloginfo( 'name' ) );
		if ( '' !== $sito ) {
			return $sito;
		}
		return (string) wp_parse_url( home_url(), PHP_URL_HOST );
	}

	public static function colore_email_sfondo() {
		return self::get( 'primary_color' ) ?: self::FIELDS['primary_color'];
	}

	public static function colore_email_testo_intestazione() {
		return self::get( 'name_color' ) ?: self::FIELDS['name_color'];
	}

	public static function colore_email_accento() {
		return self::get( 'secondary_color' ) ?: self::FIELDS['secondary_color'];
	}

	public static function css_variables() {
		$font = self::PILA_FONT;
		$map  = [
			'--sab-primary'          => self::get( 'primary_color' ),
			'--sab-secondary'        => self::get( 'secondary_color' ),

			'--sab-bg'               => self::get( 'bg_color' ),
			'--sab-chat-bg'          => self::get( 'chat_bg_color' ),
			'--sab-bot-bubble-bg'    => self::get( 'bot_bubble_bg' ),
			'--sab-bot-bubble-text'  => self::get( 'bot_bubble_text' ),
			'--sab-user-bubble-bg'   => self::get( 'user_bubble_bg' ),
			'--sab-user-bubble-text' => self::get( 'user_bubble_text' ),
			'--sab-name-color'       => self::get( 'name_color' ),
			'--sab-border-color'     => self::get( 'border_color' ),
			'--sab-input-bg'         => self::get( 'input_bg' ),
			'--sab-button-bg'        => self::get( 'button_bg' ),
			'--sab-dot-color'        => self::get( 'dot_color' ),
			'--sab-online-text'      => self::get( 'online_text_color' ),
			'--sab-online-dot'       => self::get( 'online_dot_color' ),
			'--sab-header-icon'      => self::get( 'header_icon_color' ),
			'--sab-header-icon-hover' => self::get( 'header_icon_hover_color' ),
			'--sab-icon-color'       => self::get( 'icon_color' ),
			'--sab-send-icon'        => self::get( 'send_icon_color' ),
			'--sab-bubble-icon'      => self::get( 'bubble_icon_color' ),
			'--sab-panel-bg'         => self::get( 'panel_bg_color' ),
			'--sab-panel-text'       => self::get( 'panel_text_color' ),
			'--sab-profile-bg'       => self::get( 'profile_bg_color' ),
			'--sab-profile-text'     => self::get( 'profile_text_color' ),
			'--sab-profile-button-bg'   => self::get( 'profile_button_bg_color' ),
			'--sab-profile-button-text' => self::get( 'profile_button_text_color' ),
			'--sab-profile-label'       => self::get( 'profile_label_color' ),
			'--sab-history-card-bg'  => self::get( 'history_card_bg_color' ),
			'--sab-avatar-bg'        => self::get( 'avatar_bg_color' ),
			'--sab-input-text'       => self::get( 'input_text_color' ),
			'--sab-closed-btn-bg'    => self::get( 'closed_button_bg_color' ),

			'--sab-closed-btn-radius' => '50%',
		];
		$out = '';
		foreach ( $map as $var => $val ) {
			$out .= $var . ':' . esc_attr( $val ) . ';';
		}
		$out .= '--sab-font:' . $font . ';';
		return $out;
	}

	public function add_submenu() {
		add_submenu_page(
			'sabriel-ai',
			__( 'Customization', 'sabriel-ai' ),
			__( 'Customization', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai-branding',
			[ $this, 'render_page' ]
		);
	}

	public function enqueue_admin_assets( $hook ) {
		wp_enqueue_style( 'wp-color-picker' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_media();

	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Access denied', 'sabriel-ai' ) );
		}
		Sabriel_Base::toast_toggle_script();
		$this->enqueue_admin_assets( '' );
		$msg = '';

		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_branding_nonce'] ) && check_admin_referer( 'sab_branding_action', 'sab_branding_nonce' ) ) {

			if ( isset( $_POST['sab_reset_branding'] ) ) {

				foreach ( self::FIELDS as $key => $default ) {
					/* Il credito resta come l'ha lasciato il proprietario: e' una sua scelta,
					   non un colore, e l'avviso del ripristino non lo nomina. */
					if ( 'mostra_credito' === $key ) {
						continue;
					}
					Sabriel_Base::update( $key, $default );
				}
				$msg = __( 'Appearance reset to the starting values.', 'sabriel-ai' );
			} else {
				$bot_name = sanitize_text_field( wp_unslash( $_POST['bot_name'] ?? '' ) );
				Sabriel_Base::update( 'bot_name', $bot_name ?: self::FIELDS['bot_name'] );
				Sabriel_Base::update( 'logo_url', esc_url_raw( wp_unslash( $_POST['logo_url'] ?? '' ) ) );
				Sabriel_Base::update( 'mostra_credito', isset( $_POST['mostra_credito'] ) );

				$campi_colore = [ 'primary_color', 'secondary_color', 'bg_color', 'name_color', 'avatar_bg_color' ];
				foreach ( $campi_colore as $key ) {
					$val = sanitize_text_field( wp_unslash( $_POST[ $key ] ?? '' ) );
					if ( preg_match( '/^#[0-9a-fA-F]{6}$/', $val ) ) {
						Sabriel_Base::update( $key, $val );
					}
				}

				// Questi tre viaggiano come rgba(): la trasparenza fa parte del valore.
				$campi_colore_opachi = [ 'online_text_color', 'header_icon_color', 'header_icon_hover_color' ];
				foreach ( $campi_colore_opachi as $key ) {
					$val = sanitize_text_field( wp_unslash( $_POST[ $key ] ?? '' ) );
					if ( preg_match( '/^#[0-9a-fA-F]{6}$/', $val )
						|| preg_match( '/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(?:,\s*(?:0|1|0?\.\d+)\s*)?\)$/', $val ) ) {
						Sabriel_Base::update( $key, $val );
					}
				}
				$msg = __( 'Appearance saved: this is how your visitors will see it.', 'sabriel-ai' );
			}
		}

		$v = [];
		foreach ( self::FIELDS as $key => $default ) {
			$v[ $key ] = self::get( $key );
		}

		$this->render_page_html( $v, $msg );
	}

	private function render_page_html( $v, $msg ) {
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Customization', 'sabriel-ai' ); ?></h1>
			<p style="color:#666;max-width:900px"><?php esc_html_e( 'Every part of the widget can be customized on its own. Change a value and watch the preview update right away, before you even save.', 'sabriel-ai' ); ?></p>

			<?php if ( $msg ) : ?>
				<div style="background:#eff9f0;border:1.5px solid #86d29a;color:#1a7d3a;padding:12px 18px;border-radius:8px;margin:16px 0;max-width:900px"><?php echo esc_html( $msg ); ?></div>
			<?php endif; ?>

			<div style="display:flex;gap:28px;flex-wrap:wrap;margin-top:16px;align-items:flex-start">
				<form method="post" id="sab-branding-form" style="flex:1;min-width:340px;max-width:460px;background:#fff;border:1px solid #e5e5e5;border-radius:10px;padding:24px">
					<?php wp_nonce_field( 'sab_branding_action', 'sab_branding_nonce' ); ?>
					<input type="hidden" name="logo_url" id="sab-logo-url" value="<?php echo esc_attr( $v['logo_url'] ); ?>">

					<h2 style="font-size:14px;margin:0 0 6px"><?php esc_html_e( 'Identity', 'sabriel-ai' ); ?></h2>
					<p style="color:#888;font-size:12px;margin:0 0 14px"><?php esc_html_e( 'How the bot introduces itself: the name it uses and the image shown in the chat header.', 'sabriel-ai' ); ?></p>
					<div data-ptab="open">
					<?php
					/*
					 * ⚠ NEL CAMPO CI VA IL VALORE SALVATO, NON QUELLO CALCOLATO.
					 * `bot_name` vuoto significa «usa il nome dell'attivita'», ricavato a
					 * ogni lettura apposta. Mettendo qui dentro `value=` il nome gia'
					 * calcolato, un «Salva» senza toccare niente lo scriveva nel database
					 * come se fosse stato digitato: da quel momento chi rinominava la
					 * propria attivita' si ritrovava il bot che continuava a presentarsi
					 * ai visitatori col nome vecchio, e il campo mostrava il nome vecchio
					 * come se fosse suo. Il ripiego va nel `placeholder`.
					 * NON rimettere il valore calcolato dentro `value=`.
					 */
					$this->field_text(
						'bot_name',
						__( 'Bot name', 'sabriel-ai' ),
						(string) Sabriel_Base::get( 'bot_name', '' ),
						self::nome_bot_predefinito()
					);
					?>
					<div style="margin-bottom:18px">
						<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Logo / avatar', 'sabriel-ai' ); ?></label>
						<div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap">
							<img id="sab-logo-preview-img" src="<?php echo esc_url( $v['logo_url'] ); ?>" style="width:40px;height:40px;border-radius:50%;object-fit:contain;background:#eee;<?php echo $v['logo_url'] ? '' : 'display:none'; ?>">
							<button type="button" class="button" id="sab-logo-upload"><?php esc_html_e( 'Choose image', 'sabriel-ai' ); ?></button>
							<button type="button" class="button" id="sab-logo-remove" style="<?php echo $v['logo_url'] ? '' : 'display:none'; ?>"><?php esc_html_e( 'Remove', 'sabriel-ai' ); ?></button>
							<button type="button" class="button" id="sab-logo-dal-sito"><?php esc_html_e( '🔄 Use the site\'s logo', 'sabriel-ai' ); ?></button>
						</div>
						<input type="hidden" id="sab-sync-nonce-branding" value="<?php echo esc_attr( wp_create_nonce( 'sab_sync_sito' ) ); ?>">
						<div id="sab-logo-sito-risultato" style="font-size:12px;margin-top:6px"></div>
						<p style="color:#888;font-size:12px;margin-top:6px"><?php esc_html_e( 'If you don\'t choose one, the bot\'s initial is shown on a colored circle instead (below).', 'sabriel-ai' ); ?></p>
						<p style="background:#fef2f2;border:1.5px solid #ef4444;color:#991b1b;font-size:12px;font-weight:600;padding:9px 12px;border-radius:6px;margin-top:8px"><?php esc_html_e( 'Important: use a square image (e.g. 512×512 pixels), PNG format with a transparent background, not a rectangle, and not a solid white or colored background. The logo is shown whole inside a circle: if the file isn\'t square or isn\'t transparent, that background/edge will show around the artwork.', 'sabriel-ai' ); ?></p>
					</div>
					<?php $this->field_color( 'avatar_bg_color', __( 'Background behind the logo/initial', 'sabriel-ai' ), $v['avatar_bg_color'], '--sab-avatar-bg' ); ?>
					<?php echo Sabriel_Module_Settings::stile_interruttori(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS statico scritto nel plugin. ?>
					<label class="sab-toggle-row" style="margin-top:6px">
						<span class="sab-toggle-text"><?php esc_html_e( 'Show a small "Powered by Sabriel AI" credit', 'sabriel-ai' ); ?><span class="sab-toggle-desc"><?php esc_html_e( 'Off by default: nothing of ours appears on your site unless you decide otherwise. Turning it on adds one discreet line under the chat, linking to the plugin author. It changes nothing else, and you can switch it back off whenever you like.', 'sabriel-ai' ); ?></span></span>
						<span class="sab-toggle">
							<input type="checkbox" name="mostra_credito" value="1" <?php checked( (bool) Sabriel_Base::get( 'mostra_credito' ) ); ?>>
							<span class="sab-toggle-slider"></span>
						</span>
					</label>
					</div>

					<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Main colors (header, links, buttons)', 'sabriel-ai' ); ?></h2>
					<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'The two colors seen the most: they drive the whole look of the widget.', 'sabriel-ai' ); ?></p>
					<div data-ptab="open">
					<?php
					$this->field_color( 'primary_color', __( 'Primary colour (header, links, chat buttons)', 'sabriel-ai' ), $v['primary_color'], '--sab-primary' );
					$this->field_color( 'secondary_color', __( 'Secondary colour (links, bot bubble border)', 'sabriel-ai' ), $v['secondary_color'], '--sab-secondary' );
					$this->field_color( 'name_color', __( 'Bot name colour in the header', 'sabriel-ai' ), $v['name_color'], '--sab-name-color' );
					$this->field_color_alpha( 'online_text_color', __( '"Online" wording under the bot name', 'sabriel-ai' ), $v['online_text_color'], '--sab-online-text' );
					$this->field_color_alpha( 'header_icon_color', __( 'Header icons: profile, history, minimise, close', 'sabriel-ai' ), $v['header_icon_color'], '--sab-header-icon' );
					$this->field_color_alpha( 'header_icon_hover_color', __( 'Header icons with the mouse over them', 'sabriel-ai' ), $v['header_icon_hover_color'], '--sab-header-icon-hover' );
					$this->field_color( 'bg_color', __( 'Light contrast colour (text on primary buttons, neutral backgrounds and dividers)', 'sabriel-ai' ), $v['bg_color'], '--sab-bg' );
					?>
					</div>

					<button type="submit" style="background:#1461CC;color:#fff;border:none;padding:11px 26px;border-radius:8px;font-weight:700;cursor:pointer;margin-top:20px"><?php esc_html_e( 'Save appearance', 'sabriel-ai' ); ?></button>
				</form>

				<?php $this->render_preview( $v ); ?>
			</div>

			<div style="max-width:900px;margin-top:32px;border-top:1px solid #eee;padding-top:20px">
				<?php

				?>
				<form method="post" onsubmit="return confirm(<?php echo esc_attr( wp_json_encode( __( 'Are you sure? Everything goes back to its starting values: bot name, logo and the colours. Conversations and the other settings are left alone.', 'sabriel-ai' ) ) ); ?>);">
					<?php wp_nonce_field( 'sab_branding_action', 'sab_branding_nonce' ); ?>
					<input type="hidden" name="sab_reset_branding" value="1">
					<div style="background:#fef2f2;border:1.5px solid #f5a3a3;border-radius:8px;padding:14px 18px;max-width:640px">
						<p style="margin:0 0 10px;color:#b91c1c;font-size:13px"><strong><?php esc_html_e( 'Warning:', 'sabriel-ai' ); ?></strong> <?php esc_html_e( 'resets the bot name, the logo and every colour to their starting values. Your current customisations are lost and cannot be recovered. Conversations and the other settings are left untouched.', 'sabriel-ai' ); ?></p>
						<button type="submit" style="background:#fff;color:#b91c1c;border:1.5px solid #b91c1c;padding:9px 20px;border-radius:7px;font-weight:700;cursor:pointer"><?php esc_html_e( 'Reset appearance to starting values', 'sabriel-ai' ); ?></button>
					</div>
				</form>
			</div>
		</div>
		<?php
		$this->render_script();
	}

	private function field_text( $name, $label, $value, $placeholder = '' ) {
		?>
		<div style="margin-bottom:16px">
			<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php echo esc_html( $label ); ?></label>
			<input type="text" name="<?php echo esc_attr( $name ); ?>" id="sab-<?php echo esc_attr( str_replace( '_', '-', $name ) ); ?>" value="<?php echo esc_attr( $value ); ?>" placeholder="<?php echo esc_attr( $placeholder ); ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
		</div>
		<?php
	}

	/**
	 * Splits a stored colour into hex + opacity for the two-part picker.
	 * These four values ship as rgba() so they blend into the header,
	 * so a plain hex picker alone would throw the transparency away.
	 */
	private static function colore_e_opacita( $valore ) {
		$valore = trim( (string) $valore );
		if ( preg_match( '/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*([0-9.]+)\s*)?\)$/i', $valore, $m ) ) {
			$hex = sprintf( '#%02x%02x%02x', min( 255, (int) $m[1] ), min( 255, (int) $m[2] ), min( 255, (int) $m[3] ) );
			$a   = ( isset( $m[4] ) && '' !== $m[4] ) ? (float) $m[4] : 1.0;
			return [ $hex, (int) round( max( 0, min( 1, $a ) ) * 100 ) ];
		}
		if ( preg_match( '/^#([0-9a-fA-F]{6})$/', $valore, $m ) ) {
			return [ '#' . strtolower( $m[1] ), 100 ];
		}
		return [ '#ffffff', 100 ];
	}

	/**
	 * Colour field with an opacity slider. The hidden input must stay the
	 * immediate next sibling of .sab-alpha-picker: the script reads it as
	 * wrap.nextElementSibling.
	 */
	private function field_color_alpha( $name, $label, $value, $css_var ) {
		list( $sab_hex, $sab_op ) = self::colore_e_opacita( $value );
		?>
		<div style="margin-bottom:16px">
			<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php echo esc_html( $label ); ?></label>
			<div class="sab-alpha-picker" data-preview-var="<?php echo esc_attr( $css_var ); ?>" style="display:flex;align-items:center;gap:10px">
				<input type="color" class="sab-ca-color" value="<?php echo esc_attr( $sab_hex ); ?>" style="width:46px;height:30px;padding:0;border:1px solid #ccc;border-radius:6px;cursor:pointer;flex-shrink:0" aria-label="<?php esc_attr_e( 'Colour', 'sabriel-ai' ); ?>">
				<input type="range" class="sab-ca-alpha" min="0" max="100" step="1" value="<?php echo esc_attr( $sab_op ); ?>" style="flex:1;cursor:pointer;min-width:70px" aria-label="<?php esc_attr_e( 'Opacity', 'sabriel-ai' ); ?>">
				<span class="sab-ca-alpha-val" style="font-size:12px;color:#666;min-width:40px;text-align:right"><?php echo esc_html( $sab_op . '%' ); ?></span>
				<span class="sab-ca-swatch" style="display:inline-block;width:28px;height:28px;border-radius:6px;border:1px solid #ccc;flex-shrink:0"></span>
			</div>
			<input type="hidden" name="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $value ); ?>">
		</div>
		<?php
	}

	private function field_color( $name, $label, $value, $css_var ) {
		?>
		<div style="margin-bottom:16px">
			<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php echo esc_html( $label ); ?></label>
			<input type="text" name="<?php echo esc_attr( $name ); ?>" class="sab-color-field" data-preview-var="<?php echo esc_attr( $css_var ); ?>" value="<?php echo esc_attr( $value ); ?>">
		</div>
		<?php
	}

	private function render_preview( $v ) {
		$font_stack = self::PILA_FONT;
		?>
		<div style="flex:1;min-width:320px;max-width:400px;position:sticky;top:32px">
			<div style="font-weight:600;font-size:13px;color:#666;margin-bottom:8px"><?php esc_html_e( 'Live preview', 'sabriel-ai' ); ?></div>

			<style>#sab-preview-root .sab-preview-hicon:hover{color:var(--sab-header-icon-hover)!important}</style>
			<div id="sab-preview-root" style="<?php echo esc_attr( self::css_variables() ); ?>background:#e9e9ec;border-radius:14px;padding:24px 18px;font-family:<?php echo esc_attr( $font_stack ); ?>;min-height:420px;position:relative;transition:min-height .2s ease">

				<div id="sab-preview-open">
					<div style="background:var(--sab-chat-bg);border-radius:16px;overflow:hidden;box-shadow:0 8px 30px rgba(0,0,0,.15);max-width:320px;margin:0 auto">
						<div style="background:var(--sab-primary);padding:14px 16px;display:flex;align-items:center;gap:10px">
							<div id="sab-preview-avatar" style="width:34px;height:34px;border-radius:50%;background:var(--sab-avatar-bg);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;overflow:hidden;flex-shrink:0;padding:3px;background-origin:content-box;box-sizing:border-box;<?php echo $v['logo_url'] ? 'background-image:url(' . esc_url( $v['logo_url'] ) . ');background-size:contain;background-position:center;background-repeat:no-repeat' : ''; ?>">
								<span id="sab-preview-avatar-letter" style="<?php echo $v['logo_url'] ? 'display:none' : ''; ?>"><?php echo esc_html( mb_substr( $v['bot_name'], 0, 1 ) ); ?></span>
							</div>
							<div style="flex:1">
								<div id="sab-preview-name" style="color:var(--sab-name-color);font-weight:700;font-size:13.5px"><?php echo esc_html( $v['bot_name'] ); ?></div>
								<div style="color:var(--sab-online-text);font-size:11px;display:flex;align-items:center;gap:5px"><span style="width:6px;height:6px;border-radius:50%;background:var(--sab-online-dot);display:inline-block"></span><?php esc_html_e('Online', 'sabriel-ai'); ?></div>
							</div>
							<span class="sab-preview-hicon" style="color:var(--sab-header-icon);cursor:pointer;transition:color .15s" title="<?php esc_attr_e( 'Hover here to see the hover colour', 'sabriel-ai' ); ?>"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></span>
							<span class="sab-preview-hicon" style="color:var(--sab-header-icon);cursor:pointer;transition:color .15s" title="<?php esc_attr_e( 'Hover here to see the hover colour', 'sabriel-ai' ); ?>"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg></span>
						</div>
						<div style="padding:16px;background:var(--sab-bg);min-height:160px">
							<div style="display:flex;align-items:flex-end;gap:7px;margin-bottom:10px">
								<div class="sab-preview-msg-avatar" style="width:32px;height:32px;border-radius:50%;flex-shrink:0;overflow:hidden;background:var(--sab-avatar-bg);display:flex;align-items:center;justify-content:center;box-sizing:border-box;padding:2px;<?php echo $v['logo_url'] ? 'padding:2px' : ''; ?>">
									<?php if ( $v['logo_url'] ) : ?>
										<img src="<?php echo esc_url( $v['logo_url'] ); ?>" style="width:100%;height:100%;object-fit:contain;display:block">
									<?php else : ?>
										<span style="font-size:10px;font-weight:800;color:#fff"><?php echo esc_html( mb_substr( $v['bot_name'], 0, 1 ) ); ?></span>
									<?php endif; ?>
								</div>
								<div style="background:var(--sab-bot-bubble-bg);color:var(--sab-bot-bubble-text);border-left:3px solid var(--sab-secondary);border-radius:4px 14px 14px 14px;padding:9px 13px;font-size:13px;max-width:80%;box-shadow:0 1px 4px rgba(0,0,0,.06)"><?php esc_html_e('Hi! How can I help you today?', 'sabriel-ai'); ?></div>
							</div>
							<div style="display:flex;align-items:flex-end;gap:7px;margin-bottom:10px;justify-content:flex-end">
								<div style="background:var(--sab-user-bubble-bg);color:var(--sab-user-bubble-text);border-radius:14px 14px 4px 14px;padding:9px 13px;font-size:13px;max-width:80%"><?php esc_html_e('I\'d like a quote', 'sabriel-ai'); ?></div>
								<div style="width:32px;height:32px;border-radius:50%;flex-shrink:0;background:var(--sab-primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:700">U</div>
							</div>
							<div style="display:flex;align-items:flex-end;gap:7px">
								<div class="sab-preview-msg-avatar" style="width:32px;height:32px;border-radius:50%;flex-shrink:0;overflow:hidden;background:var(--sab-avatar-bg);display:flex;align-items:center;justify-content:center;box-sizing:border-box;padding:2px;<?php echo $v['logo_url'] ? 'padding:2px' : ''; ?>">
									<?php if ( $v['logo_url'] ) : ?>
										<img src="<?php echo esc_url( $v['logo_url'] ); ?>" style="width:100%;height:100%;object-fit:contain;display:block">
									<?php else : ?>
										<span style="font-size:10px;font-weight:800;color:#fff"><?php echo esc_html( mb_substr( $v['bot_name'], 0, 1 ) ); ?></span>
									<?php endif; ?>
								</div>
								<div style="background:var(--sab-bot-bubble-bg);color:var(--sab-bot-bubble-text);border-left:3px solid var(--sab-secondary);border-radius:4px 14px 14px 14px;padding:9px 13px;font-size:13px;max-width:80%;box-shadow:0 1px 4px rgba(0,0,0,.06)"><?php esc_html_e( 'Sure, tell me more about what you need', 'sabriel-ai' ); ?></div>
							</div>
						</div>
						<div style="padding:10px 12px;background:var(--sab-chat-bg);border-top:1px solid var(--sab-border-color);display:flex;gap:6px;align-items:center">
							<span style="width:30px;height:30px;border:1.5px solid var(--sab-border-color);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--sab-icon-color);flex-shrink:0" title="<?php esc_attr_e( 'Attachment icon', 'sabriel-ai' ); ?>"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg></span>
							<span style="width:30px;height:30px;border:1.5px solid var(--sab-border-color);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--sab-icon-color);flex-shrink:0" title="<?php esc_attr_e( 'Microphone icon', 'sabriel-ai' ); ?>"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/></svg></span>
							<div style="flex:1;background:var(--sab-input-bg);border:1px solid var(--sab-border-color);border-radius:9px;height:32px"></div>
							<span style="width:30px;height:30px;border-radius:8px;background:var(--sab-button-bg);display:flex;align-items:center;justify-content:center;color:var(--sab-send-icon);flex-shrink:0" title="<?php esc_attr_e( 'Send icon', 'sabriel-ai' ); ?>"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg></span>
						</div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	private function render_script() {
		?>
		<script>
		(function(){

			jQuery(document).ready(function($){
				$('.sab-color-field').wpColorPicker({
					change: function(event, ui){
						var v = ui.color.toString();
						document.getElementById('sab-preview-root').style.setProperty(event.target.dataset.previewVar, v);
					}
				});

				document.querySelectorAll('.sab-alpha-picker').forEach(function(wrap){
					var colorInp = wrap.querySelector('.sab-ca-color');
					var alphaInp = wrap.querySelector('.sab-ca-alpha');
					var alphaVal = wrap.querySelector('.sab-ca-alpha-val');
					var swatch   = wrap.querySelector('.sab-ca-swatch');
					var hidden   = wrap.nextElementSibling;
					var cssVar   = wrap.dataset.previewVar;
					function aggiorna(){
						var hex = colorInp.value;
						var a = alphaInp.value;
						var r = parseInt(hex.substr(1,2),16), g = parseInt(hex.substr(3,2),16), b = parseInt(hex.substr(5,2),16);
						var rgba = 'rgba('+r+','+g+','+b+','+(a/100)+')';
						alphaVal.textContent = a + '%';
						swatch.style.backgroundColor = rgba;
						hidden.value = rgba;
						document.getElementById('sab-preview-root').style.setProperty(cssVar, rgba);
					}
					colorInp.addEventListener('input', aggiorna);
					alphaInp.addEventListener('input', aggiorna);
					aggiorna();
				});

				document.getElementById('sab-bot-name').addEventListener('input', function(){
					var val = this.value || '?';
					document.getElementById('sab-preview-name').textContent = val;
					document.getElementById('sab-preview-avatar-letter').textContent = val.charAt(0).toUpperCase();
				});

				var frame;
				document.getElementById('sab-logo-upload').addEventListener('click', function(e){
					e.preventDefault();
					if(frame){ frame.open(); return; }
					frame = wp.media({ title:<?php echo wp_json_encode( __( 'Choose the logo', 'sabriel-ai' ) ); ?>, button:{text:<?php echo wp_json_encode( __( 'Use this image', 'sabriel-ai' ) ); ?>}, multiple:false, library:{type:'image'} });
					frame.on('select', function(){
						var att = frame.state().get('selection').first().toJSON();
						document.getElementById('sab-logo-url').value = att.url;
						var img = document.getElementById('sab-logo-preview-img');
						img.src = att.url; img.style.display = '';
						document.getElementById('sab-logo-remove').style.display = '';
						document.getElementById('sab-preview-avatar').style.backgroundImage = "url('"+String(att.url).replace(/["'\\()]/g,'')+"')";
						document.getElementById('sab-preview-avatar').style.backgroundSize = 'contain';
						document.getElementById('sab-preview-avatar').style.backgroundPosition = 'center';
						document.getElementById('sab-preview-avatar').style.backgroundRepeat = 'no-repeat';
						document.getElementById('sab-preview-avatar-letter').style.display = 'none';
						document.querySelectorAll('.sab-preview-msg-avatar').forEach(function(el){
							el.style.padding = '2px';
							el.innerHTML = '<img src="'+String(att.url).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'" style="width:100%;height:100%;object-fit:contain;display:block">';
						});
					});
					frame.open();
				});
				document.getElementById('sab-logo-remove').addEventListener('click', function(){
					document.getElementById('sab-logo-url').value = '';
					document.getElementById('sab-logo-preview-img').style.display = 'none';
					this.style.display = 'none';
					document.getElementById('sab-preview-avatar').style.backgroundImage = 'none';
					document.getElementById('sab-preview-avatar-letter').style.display = '';
					var lettera = (document.getElementById('sab-bot-name').value || '?').charAt(0).toUpperCase();
					document.querySelectorAll('.sab-preview-msg-avatar').forEach(function(el){
						el.style.padding = '';
						el.innerHTML = '<span style="font-size:10px;font-weight:800;color:#fff">'+lettera+'</span>';
					});
				});
				var logoSitoBtn = document.getElementById('sab-logo-dal-sito');
				if(logoSitoBtn){
					logoSitoBtn.addEventListener('click', function(){
						var risultato = document.getElementById('sab-logo-sito-risultato');
						logoSitoBtn.disabled = true;
						risultato.textContent = <?php echo wp_json_encode( __( 'Searching…', 'sabriel-ai' ) ); ?>;
						var fd = new FormData();
						fd.append('action','sabriel_ai_sincronizza_dal_sito');
						fd.append('nonce', document.getElementById('sab-sync-nonce-branding').value);
						fetch(ajaxurl, { method:'POST', body:fd, credentials:'same-origin' })
							.then(function(r){ return r.json(); })
							.then(function(res){
								logoSitoBtn.disabled = false;
								if(!res.success || !res.data.logo_url){
									risultato.textContent = <?php echo wp_json_encode( __( 'Your site doesn\'t have a logo set yet (Appearance → Customise → Site Identity in WordPress).', 'sabriel-ai' ) ); ?>;
									return;
								}
								var url = res.data.logo_url;
								risultato.innerHTML = '';
								var img = document.createElement('img');
								img.src = url; img.style.cssText = 'width:28px;height:28px;object-fit:contain;vertical-align:middle;margin-right:6px;border-radius:4px';
								var testo = document.createElement('span');
								testo.textContent = <?php echo wp_json_encode( __( 'Site logo found: ', 'sabriel-ai' ) ); ?>;
								var usa = document.createElement('button');
								usa.type = 'button'; usa.className = 'button button-small'; usa.textContent = <?php echo wp_json_encode( __( 'Use this one', 'sabriel-ai' ) ); ?>;
								usa.addEventListener('click', function(){
									document.getElementById('sab-logo-url').value = url;
									var prev = document.getElementById('sab-logo-preview-img');
									prev.src = url; prev.style.display = '';
									document.getElementById('sab-logo-remove').style.display = '';
									document.getElementById('sab-preview-avatar').style.backgroundImage = "url('"+String(url).replace(/["'\\()]/g,'')+"')";
									document.getElementById('sab-preview-avatar').style.backgroundSize = 'contain';
									document.getElementById('sab-preview-avatar').style.backgroundPosition = 'center';
									document.getElementById('sab-preview-avatar').style.backgroundRepeat = 'no-repeat';
									document.getElementById('sab-preview-avatar-letter').style.display = 'none';
									document.querySelectorAll('.sab-preview-msg-avatar').forEach(function(el){
										el.style.padding = '2px';
										el.innerHTML = '<img src="'+String(url).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'" style="width:100%;height:100%;object-fit:contain;display:block">';
									});
									risultato.textContent = <?php echo wp_json_encode( __( 'Applied: remember to save to confirm.', 'sabriel-ai' ) ); ?>;
								});
								risultato.appendChild(img); risultato.appendChild(testo); risultato.appendChild(usa);
							})
							.catch(function(){
								logoSitoBtn.disabled = false;
								risultato.textContent = <?php echo wp_json_encode( __( 'Connection error, please try again.', 'sabriel-ai' ) ); ?>;
							});
					});
				}

			});
		})();
		</script>
		<?php
	}
}
