<?php

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

class Sabriel_Module_Settings extends Sabriel_Module {

	const MAX_LUNGHEZZA_CAMPO      = 200;
	const MAX_LUNGHEZZA_DESCRIZIONE = 200;
	const MAX_LUNGHEZZA_TONO        = 4000;

	const FIELDS = [
		'business_name'   => '',

		'descrizione_attivita' => '',
		'comportamento_tono' => '',

		'rate_abilitate'  => false,
		'permetti_fuori_tema' => false,
		'rate_soglia'     => '',

		'aliquota_iva_paese'    => '',

		'prezzi_regime_iva'     => 'esclusa',
		'aliquota_iva'          => '',

		'valuta_codice'         => 'EUR',
		'valuta_simbolo'        => '€',
		'valuta_posizione'      => 'dopo',
		'pagamento_struttura'   => 'non_applicabile',
		'pagamento_acconto_pct' => '',
		'pagamento_meta_pct'    => '',

		'bot_lingua' => 'it',
		'bot_lingua_fissa' => false,
		'wizard_completato' => false,
		'support_email'   => '',
		'whatsapp_number' => '',
		'phone_display'   => '',
		'address'         => '',
		'piva'            => '',
		'website_url'     => '',
		'tagline'         => '',
		'founder_name'    => '',
		'since_year'      => '',
		'service_area'    => '',

		'statistiche_attive' => true,

		'listino_servizi' => [],
		'pagine_link'     => [],
	];

	const IVA_VERIFICATE_IL = '2026-07-26';

	const LOCALE_COME_IL_SITO = 'sab_come_il_sito';

	const META_LINGUA_PANNELLO = 'sabriel_ai_locale_pannello';

	const LINGUE = [
		'it' => [ 'Italiano', 'it_IT', '🇮🇹' ],
		'en' => [ 'English', 'en_US', '🇬🇧' ],
		'es' => [ 'Español', 'es_ES', '🇪🇸' ],
		'fr' => [ 'Français', 'fr_FR', '🇫🇷' ],
		'de' => [ 'Deutsch', 'de_DE', '🇩🇪' ],
		'pt' => [ 'Português', 'pt_PT', '🇵🇹' ],
		'nl' => [ 'Nederlands', 'nl_NL', '🇳🇱' ],
		'ru' => [ 'Русский', 'ru_RU', '🇷🇺' ],
		'id' => [ 'Bahasa Indonesia', 'id_ID', '🇮🇩' ],
	];

	public static function etichetta_lingua_bot() {
		return __( 'The bot speaks every language', 'sabriel-ai' );
	}

	public static function lingue_codici() {
		return array_keys( self::LINGUE );
	}

	public static function lingue_etichette() {
		return array_map( static function ( $v ) { return $v[0]; }, self::LINGUE );
	}

	public static function lingue_con_bandiera() {
		return array_map( static function ( $v ) { return [ $v[0], $v[2] ]; }, self::LINGUE );
	}

	public static function lingue_locali() {
		return array_map( static function ( $v ) { return $v[1]; }, self::LINGUE );
	}

	public static function lingue_locale_bandiera() {
		$fuori = [];
		foreach ( self::LINGUE as $v ) {
			$fuori[ $v[1] ] = [ $v[0], $v[2] ];
		}
		return $fuori;
	}

	public static function lingue_pannello() {
		$fuori = [];
		foreach ( self::LINGUE as $v ) {
			$fuori[ $v[1] ] = $v[0];
		}
		return $fuori;
	}

	const VALUTE = [
		'EUR' => [ '€', 'Euro' ],
		'USD' => [ '$', 'US dollar' ],
		'GBP' => [ '£', 'Pound sterling' ],
		'CHF' => [ 'CHF', 'Swiss franc' ],
		'CAD' => [ 'CA$', 'Canadian dollar' ],
		'AUD' => [ 'AU$', 'Australian dollar' ],
		'SEK' => [ 'kr', 'Swedish krona' ],
		'NOK' => [ 'kr', 'Norwegian krone' ],
		'DKK' => [ 'kr', 'Danish krone' ],
		'PLN' => [ 'zł', 'Polish złoty' ],
		'JPY' => [ '¥', 'Japanese yen' ],
		'BRL' => [ 'R$', 'Brazilian real' ],
	];

	const IVA_PAESI = [
		'it' => [ 'Italy', 22 ],
		'de' => [ 'Germany', 19 ],
		'fr' => [ 'France', 20 ],
		'es' => [ 'Spain', 21 ],
		'nl' => [ 'Netherlands', 21 ],
		'be' => [ 'Belgium', 21 ],
		'pt' => [ 'Portugal', 23 ],
		'at' => [ 'Austria', 20 ],
		'ie' => [ 'Ireland', 23 ],
		'gb' => [ 'United Kingdom', 20 ],
		'ch' => [ 'Switzerland', 8.1 ],
		'pl' => [ 'Poland', 23 ],
		'se' => [ 'Sweden', 25 ],
		'dk' => [ 'Denmark', 25 ],
		'gr' => [ 'Greece', 24 ],
		'cz' => [ 'Czech Rep.', 21 ],
		'hu' => [ 'Hungary', 27 ],
		'ro' => [ 'Romania', 21 ],
		'ru' => [ 'Russia', 22 ],
		'id' => [ 'Indonesia', 11 ],
		'mx' => [ 'Mexico', 16 ],
		'ar' => [ 'Argentina', 21 ],
		'au' => [ 'Australia (GST)', 10 ],
		'ca' => [ 'Canada (federal GST)', 5 ],
	];

	public static function giorni_settimana() {
		$riserva = [
			1 => __( 'Monday', 'sabriel-ai' ),
			2 => __( 'Tuesday', 'sabriel-ai' ),
			3 => __( 'Wednesday', 'sabriel-ai' ),
			4 => __( 'Thursday', 'sabriel-ai' ),
			5 => __( 'Friday', 'sabriel-ai' ),
			6 => __( 'Saturday', 'sabriel-ai' ),
			7 => __( 'Sunday', 'sabriel-ai' ),
		];

		$locale_in_uso = function_exists( 'determine_locale' ) ? determine_locale() : get_locale();

		$sab_lingua_del_plugin = $locale_in_uso
			&& ( 'en_US' === $locale_in_uso
				|| file_exists( SABRIEL_AI_DIR . 'languages/sabriel-ai-' . $locale_in_uso . '.mo' ) );
		if ( $sab_lingua_del_plugin ) {
			return $riserva;
		}
		$wp_locale = $GLOBALS['wp_locale'] ?? null;
		$fuori     = [];
		foreach ( range( 1, 7 ) as $dow ) {
			$dal_locale   = ( $wp_locale instanceof WP_Locale ) ? $wp_locale->get_weekday( 7 === $dow ? 0 : $dow ) : '';
			$fuori[ $dow ] = $dal_locale ?: $riserva[ $dow ];
		}
		return $fuori;
	}

	public static function valute_tradotte() {
		$nomi = [
			'EUR' => __( 'Euro', 'sabriel-ai' ),
			'USD' => __( 'US dollar', 'sabriel-ai' ),
			'GBP' => __( 'Pound sterling', 'sabriel-ai' ),
			'CHF' => __( 'Swiss franc', 'sabriel-ai' ),
			'CAD' => __( 'Canadian dollar', 'sabriel-ai' ),
			'AUD' => __( 'Australian dollar', 'sabriel-ai' ),
			'SEK' => __( 'Swedish krona', 'sabriel-ai' ),
			'NOK' => __( 'Norwegian krone', 'sabriel-ai' ),
			'DKK' => __( 'Danish krone', 'sabriel-ai' ),
			'PLN' => __( 'Polish złoty', 'sabriel-ai' ),
			'JPY' => __( 'Japanese yen', 'sabriel-ai' ),
			'BRL' => __( 'Brazilian real', 'sabriel-ai' ),
		];
		$fuori = [];
		foreach ( self::VALUTE as $cod => $dati ) {
			$fuori[ $cod ] = [ $dati[0], $nomi[ $cod ] ?? $dati[1] ];
		}
		return $fuori;
	}

	public static function iva_paesi_tradotti() {
		$nomi = [
			'it' => __( 'Italy', 'sabriel-ai' ),
			'de' => __( 'Germany', 'sabriel-ai' ),
			'fr' => __( 'France', 'sabriel-ai' ),
			'es' => __( 'Spain', 'sabriel-ai' ),
			'nl' => __( 'Netherlands', 'sabriel-ai' ),
			'be' => __( 'Belgium', 'sabriel-ai' ),
			'pt' => __( 'Portugal', 'sabriel-ai' ),
			'at' => __( 'Austria', 'sabriel-ai' ),
			'ie' => __( 'Ireland', 'sabriel-ai' ),
			'gb' => __( 'United Kingdom', 'sabriel-ai' ),
			'ch' => __( 'Switzerland', 'sabriel-ai' ),
			'pl' => __( 'Poland', 'sabriel-ai' ),
			'se' => __( 'Sweden', 'sabriel-ai' ),
			'dk' => __( 'Denmark', 'sabriel-ai' ),
			'gr' => __( 'Greece', 'sabriel-ai' ),
			'cz' => __( 'Czech Rep.', 'sabriel-ai' ),
			'hu' => __( 'Hungary', 'sabriel-ai' ),
			'ro' => __( 'Romania', 'sabriel-ai' ),
			'ru' => __( 'Russia', 'sabriel-ai' ),
			'id' => __( 'Indonesia', 'sabriel-ai' ),
			'mx' => __( 'Mexico', 'sabriel-ai' ),
			'ar' => __( 'Argentina', 'sabriel-ai' ),
			'au' => __( 'Australia (GST)', 'sabriel-ai' ),
			'ca' => __( 'Canada (federal GST)', 'sabriel-ai' ),
		];
		$fuori = [];
		foreach ( self::IVA_PAESI as $cod => $dati ) {
			$fuori[ $cod ] = [ $nomi[ $cod ] ?? $dati[0], $dati[1] ];
		}
		return $fuori;
	}

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

	public function register_hooks() {

		add_action( 'init', [ $this, 'applica_lingua_pannello' ], 1 );
		add_action( 'admin_menu', [ $this, 'add_submenu_wizard' ], 5 );
		add_action( 'admin_menu', [ $this, 'add_submenu' ], 30 );
		add_action( 'admin_init', [ $this, 'maybe_process_wizard' ] );
		add_action( 'admin_notices', [ $this, 'avviso_chiavi_scartate' ] );
		add_action( 'wp_ajax_sabriel_ai_sincronizza_dal_sito', [ $this, 'ajax_sincronizza_dal_sito' ] );
		add_action( 'wp_ajax_sabriel_ai_leggi_homepage', [ $this, 'ajax_leggi_homepage_ai' ] );
		add_action( 'wp_ajax_sabriel_ai_cambia_lingua_pannello', [ $this, 'ajax_cambia_lingua_pannello' ] );
	}

	public function applica_lingua_pannello() {
		add_filter( 'pre_determine_locale', [ $this, 'lingua_scelta_per_il_pannello' ] );
	}

	public function lingua_scelta_per_il_pannello( $locale ) {
		if ( ! empty( $locale ) || ! is_admin() || ! function_exists( 'wp_get_current_user' ) ) {
			return $locale;
		}

		$nostra_pagina = false;
		$pagina        = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- semplice lettura della pagina corrente, nessun dato viene salvato.
		if ( 0 === strpos( $pagina, 'sabriel-ai' ) ) {
			$nostra_pagina = true;
		} elseif ( wp_doing_ajax() ) {
			$azione = isset( $_REQUEST['action'] ) ? sanitize_key( wp_unslash( $_REQUEST['action'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- semplice lettura della pagina corrente, nessun dato viene salvato.
			if ( 0 === strpos( $azione, 'sabriel_ai_' ) ) {
				$nostra_pagina = true;
			}
		}
		if ( ! $nostra_pagina ) {
			return $locale;
		}

		$utente = get_current_user_id();
		if ( ! $utente ) {
			return $locale;
		}
		$scelta = (string) get_user_meta( $utente, self::META_LINGUA_PANNELLO, true );
		if ( '' === $scelta || ! in_array( $scelta, array_values( self::lingue_locali() ), true ) ) {
			return $locale;
		}
		return $scelta;
	}

	public function ajax_cambia_lingua_pannello() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'Permission denied.', 'sabriel-ai' ) ], 403 );
		}
		check_ajax_referer( 'sabriel_ai_cambia_lingua_pannello', 'nonce' );

		$lingue_disponibili = array_values( self::lingue_locali() );
		$locale_scelto      = sanitize_text_field( wp_unslash( $_POST['locale'] ?? '' ) );
		$utente             = get_current_user_id();

		if ( self::LOCALE_COME_IL_SITO === $locale_scelto ) {
			delete_user_meta( $utente, self::META_LINGUA_PANNELLO );
			wp_send_json_success();
		}

		if ( ! in_array( $locale_scelto, $lingue_disponibili, true ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'Invalid language.', 'sabriel-ai' ) ], 400 );
		}
		update_user_meta( $utente, self::META_LINGUA_PANNELLO, $locale_scelto );
		wp_send_json_success();
	}

	public function ajax_sincronizza_dal_sito() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'Permission denied.', 'sabriel-ai' ) ], 403 );
		}
		check_ajax_referer( 'sab_sync_sito', 'nonce' );

		$identita = [
			'business_name' => [ 'trovato' => get_bloginfo( 'name' ), 'attuale' => self::get( 'business_name' ), 'etichetta' => __( 'Business name', 'sabriel-ai' ) ],
			'tagline'       => [ 'trovato' => get_bloginfo( 'description' ), 'attuale' => self::get( 'tagline' ), 'etichetta' => __( 'Motto / tagline', 'sabriel-ai' ) ],
			'website_url'   => [ 'trovato' => home_url( '/' ), 'attuale' => self::get( 'website_url' ), 'etichetta' => __( 'Website', 'sabriel-ai' ) ],
			'support_email' => [ 'trovato' => get_option( 'admin_email' ), 'attuale' => self::get( 'support_email' ), 'etichetta' => __( 'Support email', 'sabriel-ai' ) ],
		];

		if ( class_exists( 'WooCommerce' ) ) {
			$pezzi_indirizzo = array_filter( [
				get_option( 'woocommerce_store_address' ),
				get_option( 'woocommerce_store_address_2' ),
				get_option( 'woocommerce_store_city' ),
				get_option( 'woocommerce_store_postcode' ),
			] );
			if ( $pezzi_indirizzo ) {
				$identita['address'] = [ 'trovato' => implode( ', ', $pezzi_indirizzo ), 'attuale' => self::get( 'address' ), 'etichetta' => __( 'Address (from WooCommerce)', 'sabriel-ai' ) ];
			}
		}
		foreach ( $identita as $chiave => $info ) {
			if ( '' === trim( (string) $info['trovato'] ) ) {
				unset( $identita[ $chiave ] );
			}
		}

		$logo_id  = get_theme_mod( 'custom_logo' );
		$logo_url = $logo_id ? wp_get_attachment_image_url( $logo_id, 'full' ) : '';

		$pattern_etichette = [
			'privacy'     => [ 'privacy', 'privacidad', 'privacidade', 'confidentialit', 'datenschutz', 'privacybeleid', 'конфиденциальн', 'privasi' ],
			'termini'     => [ 'termini', 'condizioni', 'terms', 'conditions', 'condiciones', 'términos', 'terminos', 'mentions-legales', 'mentions légales', 'cgv', 'cgu', 'agb', 'impressum', 'nutzungsbedingungen', 'termos', 'voorwaarden', 'условия', 'оферта', 'syarat', 'ketentuan' ],
			'chi siamo'   => [ 'chi siamo', 'chi-siamo', 'about', 'sobre nosotros', 'sobre-nosotros', 'quienes-somos', 'quiénes somos', 'à propos', 'a-propos', 'qui-sommes', 'über uns', 'ueber-uns', 'uber-uns', 'unternehmen', 'sobre nós', 'quem-somos', 'over ons', 'over-ons', 'о нас', 'о-компании', 'tentang' ],
			'faq'         => [ 'faq', 'domande frequenti', 'domande-frequenti', 'preguntas-frecuentes', 'preguntas frecuentes', 'questions-frequentes', 'foire-aux-questions', 'häufige-fragen', 'haeufige-fragen', 'perguntas-frequentes', 'veelgestelde', 'вопросы', 'pertanyaan' ],
			'portfolio'   => [ 'portfolio', 'progetti', 'lavori', 'projects', 'case-studies', 'proyectos', 'trabajos', 'projets', 'réalisations', 'realisations', 'projekte', 'referenzen', 'projetos', 'trabalhos', 'projecten', 'портфолио', 'проекты', 'portofolio', 'proyek' ],
			'woocommerce' => [ 'negozio', 'shop', 'store', 'woocommerce', 'tienda', 'boutique', 'laden', 'loja', 'winkel', 'магазин', 'toko' ],
			'blog'        => [ 'blog', 'notizie', 'articoli', 'news', 'noticias', 'actualites', 'actualités', 'neuigkeiten', 'nachrichten', 'notícias', 'nieuws', 'новости', 'berita' ],
		];

		$pagine_gia_configurate = array_column(
			array_filter(
				(array) self::get( 'pagine_link' ),
				static function ( $r ) { return is_array( $r ) && '' !== trim( (string) ( $r['url'] ?? '' ) ); }
			),
			'etichetta'
		);
		$pagine_trovate = [];

		$pagine_note = [];
		$id_privacy  = (int) get_option( 'wp_page_for_privacy_policy' );
		if ( $id_privacy && 'publish' === get_post_status( $id_privacy ) ) {
			$pagine_note['privacy'] = $id_privacy;
		}
		$id_blog = (int) get_option( 'page_for_posts' );
		if ( $id_blog && 'publish' === get_post_status( $id_blog ) ) {
			$pagine_note['blog'] = $id_blog;
		}
		if ( function_exists( 'wc_get_page_id' ) ) {
			$id_shop = (int) wc_get_page_id( 'shop' );
			if ( $id_shop > 0 && 'publish' === get_post_status( $id_shop ) ) {
				$pagine_note['woocommerce'] = $id_shop;
			}
		}
		foreach ( $pagine_note as $etichetta_nota => $id_nota ) {
			if ( in_array( $etichetta_nota, $pagine_gia_configurate, true ) ) {
				continue;
			}
			$pagine_trovate[] = [
				'etichetta'     => $etichetta_nota,
				'url'           => get_permalink( $id_nota ),
				'titolo_pagina' => get_the_title( $id_nota ),
			];
		}
		$pagine_wp = get_pages( [ 'post_status' => 'publish', 'number' => 1000 ] );
		foreach ( $pattern_etichette as $etichetta => $parole_chiave ) {
			if ( in_array( $etichetta, $pagine_gia_configurate, true ) || isset( $pagine_note[ $etichetta ] ) ) {
				continue;
			}
			$trovata = null;
			foreach ( $pagine_wp as $pagina ) {

				$titolo_lower = Sabriel_Helpers::minuscolo( $pagina->post_title );
				$slug_lower   = Sabriel_Helpers::minuscolo( $pagina->post_name );
				foreach ( $parole_chiave as $parola ) {
					if ( false !== strpos( $titolo_lower, $parola ) || false !== strpos( $slug_lower, str_replace( ' ', '-', $parola ) ) ) {
						$trovata = $pagina;
						break 2;
					}
				}
			}
			if ( $trovata ) {
				$pagine_trovate[] = [
					'etichetta'     => $etichetta,
					'url'           => get_permalink( $trovata ),
					'titolo_pagina' => $trovata->post_title,
				];
			}
		}

		wp_send_json_success( [
			'identita' => $identita,
			'pagine'   => $pagine_trovate,
			'logo_url' => $logo_url ?: '',
		] );
	}

	public function ajax_leggi_homepage_ai() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'Permission denied.', 'sabriel-ai' ) ], 403 );
		}
		check_ajax_referer( 'sab_wizard_ai', 'nonce' );

		$risposta_http = wp_remote_get( home_url( '/' ), [ 'timeout' => 10 ] );
		if ( is_wp_error( $risposta_http ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'I couldn\'t reach your site right now.', 'sabriel-ai' ) ] );
		}
		$testo = wp_strip_all_tags( wp_remote_retrieve_body( $risposta_http ) );
		$testo = preg_replace( '/\s+/', ' ', trim( $testo ) );
		if ( '' === $testo ) {
			wp_send_json_error( [ 'messaggio' => __( 'The homepage looks empty, I couldn\'t find any text to read.', 'sabriel-ai' ) ] );
		}
		$testo = mb_substr( $testo, 0, 3000 );

		$sab_lingua_lettura = Sabriel_Helpers::nome_lingua_bot();
		$sys_lettura = "Read this text taken from the homepage of a real business website. Reply ONLY with a valid JSON object, nothing before or after it, with exactly this structure: {\"tagline\":\"...\",\"tono_suggerito\":\"...\"}. tagline: a short motto or slogan (10 words maximum) that suits this business, written in {$sab_lingua_lettura}, inferred from the text: if you cannot infer a sensible one, leave it empty. tono_suggerito: 2-3 sentences written in {$sab_lingua_lettura} explaining to a virtual assistant of this business HOW to talk to customers (how formal to be, what to highlight, what to avoid), written as direct instructions such as 'Reply in a...': if the text is not enough to understand the kind of business, leave it empty.";
		$contents    = [ [ 'role' => 'user', 'parts' => [ [ 'text' => $testo ] ] ] ];

		$chat_module = new Sabriel_Module_Chat();
		$provider    = $chat_module->get_provider();

		$result      = $provider->generate( $sys_lettura, $contents, [
			'temperature'                    => 0.4,
			'maxOutputTokens'                => 300,
			Sabriel_AI_Provider::CHIAVE_JSON => true,
		] );

		if ( ! $result['ok'] ) {
			wp_send_json_error( [ 'messaggio' => __( 'I couldn\'t read the site with AI right now: check that you\'ve set up a key in AI Engine.', 'sabriel-ai' ) ] );
		}

		$testo_risposta = trim( Sabriel_AI_Provider::extract_text( $result['data'] ) );

		$testo_risposta = preg_replace( '/^\s*```[a-zA-Z]*\s*|\s*```\s*$/', '', $testo_risposta );
		$decoded        = json_decode( $testo_risposta, true );
		if ( ! is_array( $decoded ) ) {
			$sab_apre   = strpos( $testo_risposta, '{' );
			$sab_chiude = strrpos( $testo_risposta, '}' );
			if ( false !== $sab_apre && false !== $sab_chiude && $sab_chiude > $sab_apre ) {
				$decoded = json_decode( substr( $testo_risposta, $sab_apre, $sab_chiude - $sab_apre + 1 ), true );
			}
		}

		if ( ! is_array( $decoded ) ) {
			wp_send_json_error( [ 'messaggio' => __( 'Invalid response from the AI, please try again.', 'sabriel-ai' ) ] );
		}

		$sab_tagline = $decoded['tagline'] ?? '';
		$sab_tono    = $decoded['tono_suggerito'] ?? '';

		wp_send_json_success( [
			'tagline'        => sanitize_text_field( is_scalar( $sab_tagline ) ? (string) $sab_tagline : '' ),
			'tono_suggerito' => sanitize_textarea_field( is_scalar( $sab_tono ) ? (string) $sab_tono : '' ),
		] );
	}

	public function add_submenu() {

		add_submenu_page(
			'sabriel-ai',
			__( 'Settings', 'sabriel-ai' ),
			__( 'Settings', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai-settings',
			[ $this, 'render_page' ]
		);
	}

	public function add_submenu_wizard() {
		add_submenu_page(
			'sabriel-ai',
			__( 'Setup wizard', 'sabriel-ai' ),
			__( 'Setup wizard', 'sabriel-ai' ),
			'manage_options',
			'sabriel-ai-wizard',
			[ $this, 'render_wizard' ]
		);
	}

	/**
	 * Prints, once, the warning about keys the wizard refused to save.
	 * Cleared straight after showing: it is a passing message, not a state.
	 */
	public function avviso_chiavi_scartate() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$sab_chiave_transient = 'sabriel_ai_chiavi_scartate_' . get_current_user_id();
		$sab_avvisi           = get_transient( $sab_chiave_transient );
		if ( empty( $sab_avvisi ) || ! is_array( $sab_avvisi ) ) {
			return;
		}
		delete_transient( $sab_chiave_transient );

		foreach ( $sab_avvisi as $sab_avviso ) {
			if ( ! is_scalar( $sab_avviso ) ) {
				continue;
			}
			echo '<div class="notice notice-error"><p>' . esc_html( (string) $sab_avviso ) . '</p></div>';
		}
	}

	public function maybe_process_wizard() {
		if ( ! is_admin() || 'sabriel-ai-wizard' !== sanitize_key( wp_unslash( $_GET['page'] ?? '' ) ) || ! Sabriel_Helpers::e_una_post() ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['sab_wizard_nonce'] ) || ! check_admin_referer( 'sab_wizard_action', 'sab_wizard_nonce' ) ) {
			return;
		}

		$campi_wizard = [ 'business_name', 'bot_name', 'tagline', 'website_url', 'support_email', 'phone_display' ];
		foreach ( $campi_wizard as $key ) {

			$valore = ( isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ) ? sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) : '';

			$valore = function_exists( 'mb_substr' )
				? mb_substr( $valore, 0, self::MAX_LUNGHEZZA_CAMPO )
				: substr( $valore, 0, self::MAX_LUNGHEZZA_CAMPO );
			if ( 'support_email' === $key && $valore && ! is_email( $valore ) ) {
				continue;
			}
			if ( 'website_url' === $key && '' !== $valore ) {
				$valore = esc_url_raw( $valore );
			}
			Sabriel_Base::update( $key, $valore );
		}

		$lingua_scelta = sanitize_text_field( wp_unslash( $_POST['bot_lingua'] ?? self::get( 'bot_lingua' ) ) );
		if ( in_array( $lingua_scelta, self::lingue_codici(), true ) ) {
			Sabriel_Base::update( 'bot_lingua', $lingua_scelta );
		}
		Sabriel_Base::update( 'comportamento_tono', self::taglia( sanitize_textarea_field( wp_unslash( $_POST['comportamento_tono'] ?? '' ) ), self::MAX_LUNGHEZZA_TONO ) );

		Sabriel_Base::update( 'bot_lingua_fissa', ! isset( $_POST['bot_parla_tutte_le_lingue'] ) );

		$provider_scelto = sanitize_text_field( wp_unslash( $_POST['ai_provider'] ?? '' ) );
		if ( array_key_exists( $provider_scelto, Sabriel_Module_AI::PROVIDERS ) ) {
			Sabriel_Base::update( 'ai_provider', $provider_scelto );
		}
		/*
		 * Stesso problema della pagina Motore AI: le tre caselle della chiave sono
		 * campi password dentro UN SOLO modulo e due su tre sono nascoste, quindi
		 * il gestore password del browser le riempie da solo. Il controllo e' UNO
		 * SOLO e vive in Sabriel_Module_AI: qui si chiama, non si riscrive.
		 */
		$sab_inviate_wz = [];
		foreach ( Sabriel_Module_AI::PROVIDERS as $sab_pk_wz => $sab_info_wz ) {
			$sab_grezza_wz                = wp_unslash( $_POST[ $sab_info_wz[1] ] ?? '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ripulita nella riga successiva.
			$sab_inviate_wz[ $sab_pk_wz ] = is_scalar( $sab_grezza_wz ) ? trim( sanitize_text_field( (string) $sab_grezza_wz ) ) : '';
		}

		$sab_scartate_wz = [];
		foreach ( Sabriel_Module_AI::PROVIDERS as $sab_codice_wz => $info_provider ) {
			$chiave_nuova = $sab_inviate_wz[ $sab_codice_wz ];
			if ( '' === $chiave_nuova ) {
				continue;
			}

			$sab_altro_wz = Sabriel_Module_AI::chiave_di_un_altro( $chiave_nuova, $sab_codice_wz, $sab_inviate_wz, $provider_scelto );
			if ( '' !== $sab_altro_wz ) {
				$sab_scartate_wz[] = sprintf(
					/* translators: 1: name of the engine whose field was filled in; 2: name of the engine the key actually belongs to */
					__( 'The key in the %1$s field belongs to %2$s, so it was not saved. Each engine needs its own key: check you pasted it into the right box.', 'sabriel-ai' ),
					$info_provider[0],
					Sabriel_Module_AI::PROVIDERS[ $sab_altro_wz ][0]
				);
				continue;
			}

			update_option( $info_provider[1], Sabriel_Crypto::encrypt( $chiave_nuova ), false );
		}

		/*
		 * Il wizard finisce con un redirect e non ha una pagina su cui scrivere
		 * l'avviso: lo si parcheggia per il tempo di un caricamento e lo stampa
		 * avviso_chiavi_scartate() sulla pagina di arrivo. E' per utente, cosi'
		 * due amministratori che salvano insieme non si rubano il messaggio.
		 */
		if ( ! empty( $sab_scartate_wz ) ) {
			set_transient( 'sabriel_ai_chiavi_scartate_' . get_current_user_id(), $sab_scartate_wz, MINUTE_IN_SECONDS );
		}

		foreach ( Sabriel_Module_AI::PROVIDERS as $codice_prov_wz => $info_prov_wz ) {
			$scelta_wz = sanitize_text_field( wp_unslash( $_POST[ 'ai_model_' . $codice_prov_wz ] ?? '' ) );
			if ( '__custom__' === $scelta_wz ) {
				$scelta_wz = sanitize_text_field( wp_unslash( $_POST[ 'ai_model_' . $codice_prov_wz . '_custom' ] ?? '' ) );
			}
			$scelta_wz = trim( $scelta_wz );
			if ( '' !== $scelta_wz && preg_match( '/^[A-Za-z0-9._-]+$/', $scelta_wz ) ) {
				Sabriel_Base::update( 'ai_model_' . $codice_prov_wz, $scelta_wz );
			}
		}

		/* ⚠ Il credito si salva SOLO da questo modulo, che e' l'unico posto in cui la
		   domanda viene fatta in chiaro. Spento resta spento: la linea guida 10 di
		   wordpress.org vuole che sia una scelta esplicita, mai un default. */
		Sabriel_Base::update( 'mostra_credito', isset( $_POST['mostra_credito'] ) );

		Sabriel_Base::update( 'wizard_completato', true );

		wp_safe_redirect( admin_url( 'admin.php?page=sabriel-ai' ) );
		exit;
	}

	public function render_wizard() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Access denied', 'sabriel-ai' ) );
		}
		wp_enqueue_media();

		$lingue = self::lingue_con_bandiera();
		$lingua_attuale = self::bot_lingua_con_rilevamento();
		$provider_attivo_wizard = Sabriel_Module_AI::provider_attivo();
		?>
		<style>
		/*
		 * ⚠ GLI AVVISI DENTRO IL WIZARD NON DEVONO TRABOCCARE.
		 * Il wizard mette tutto in una colonna da 660px e WordPress infila li' dentro
		 * gli avvisi admin. Quello di Freemius (sito clonato) vuole tre schede
		 * affiancate: uscivano dallo sfondo giallo e sembrava rotto.
		 * Non si tocca il loro contenuto — non e' roba nostra e cambia da una versione
		 * all'altra: si mette solo un recinto. `overflow:auto` e' la rete che regge
		 * qualunque struttura interna abbiano (tabella, flex, griglia).
		 */
		#sab-wizard-root .notice,
		#sab-wizard-root .fs-notice,
		#sab-wizard-root .update-nag{max-width:100%;box-sizing:border-box;overflow-x:auto}
		#sab-wizard-root .fs-notice img,
		#sab-wizard-root .notice img{max-width:100%;height:auto}
		</style>
		<div class="wrap" id="sab-wizard-root">
			<div style="max-width:660px;margin:24px auto 60px">
				<div style="display:flex;justify-content:center;gap:8px;margin-bottom:28px">
					<?php for ( $i = 1; $i <= 6; $i++ ) : ?>
						<div class="sab-wiz-dot" data-dot="<?php echo (int) $i; ?>" style="width:34px;height:5px;border-radius:3px;background:<?php echo 1 === $i ? '#1461CC' : '#e2e8f0'; ?>;transition:background .25s"></div>
					<?php endfor; ?>
				</div>

				<div style="background:#fff;border:1px solid #e5e5e5;border-radius:16px;padding:36px 34px;box-shadow:0 4px 24px rgba(0,0,0,.06);position:relative">
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=sabriel-ai' ) ); ?>" title="<?php esc_attr_e( 'Skip, I\'ll set it up later from Settings', 'sabriel-ai' ); ?>" style="position:absolute;top:18px;right:20px;font-size:11.5px;color:#aaa;text-decoration:none;line-height:1">✕ <?php esc_html_e( 'Skip', 'sabriel-ai' ); ?></a>
					<form method="post" id="sab-wizard-form">
						<?php wp_nonce_field( 'sab_wizard_action', 'sab_wizard_nonce' ); ?>

						<div data-wiz-step="1">
							<div style="font-size:34px;margin-bottom:6px">👋</div>
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'Welcome to Sabriel AI', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 18px"><?php esc_html_e( 'A few minutes and your virtual assistant is ready to talk to customers on behalf of your business. You can change everything at any time, even after finishing here.', 'sabriel-ai' ); ?></p>
							<div style="display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-bottom:24px">
								<div style="background:#f8f9fb;border-radius:10px;padding:12px 13px;font-size:12.5px;color:#444;display:flex;align-items:center;gap:9px;line-height:1.3"><span style="font-size:17px;flex-shrink:0">💬</span><?php esc_html_e( 'Replies to customers 24/7', 'sabriel-ai' ); ?></div>
								<div style="background:#f8f9fb;border-radius:10px;padding:12px 13px;font-size:12.5px;color:#444;display:flex;align-items:center;gap:9px;line-height:1.3"><span style="font-size:17px;flex-shrink:0">💰</span><?php esc_html_e( 'Quotes the prices from your price list, without inventing them', 'sabriel-ai' ); ?></div>
								<div style="background:#f8f9fb;border-radius:10px;padding:12px 13px;font-size:12.5px;color:#444;display:flex;align-items:center;gap:9px;line-height:1.3"><span style="font-size:17px;flex-shrink:0">🌍</span><?php esc_html_e( 'Speaks the language of whoever writes to it, whichever one that is', 'sabriel-ai' ); ?></div>
								<div style="background:#f8f9fb;border-radius:10px;padding:12px 13px;font-size:12.5px;color:#444;display:flex;align-items:center;gap:9px;line-height:1.3"><span style="font-size:17px;flex-shrink:0">🤝</span><?php esc_html_e( 'Hands over to a real person when needed', 'sabriel-ai' ); ?></div>
							</div>
							<label style="font-weight:700;font-size:13px;display:block;margin-bottom:10px"><?php esc_html_e( 'What language should the bot speak to customers?', 'sabriel-ai' ); ?></label>
							<p style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:12px;padding:9px 12px;border-radius:8px;margin:0 0 8px;line-height:1.5"><?php esc_html_e( 'Warning: this choice affects ONLY the bot, that is what it says to your customers in the chat on the site. It does not change the language of this panel you are looking at now: that is chosen below, and it is a separate thing.', 'sabriel-ai' ); ?></p>
							<?php

							if ( ! self::get( 'wizard_completato' ) && $lingua_attuale === self::lingua_rilevata_da_wp() ) :
							?>
								<p style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:12px;padding:9px 12px;border-radius:8px;margin:0 0 8px;line-height:1.5"><?php echo esc_html( sprintf( /* translators: %s: language detected from the site */ __( 'Your WordPress site is set to %s, we\'ve already selected it below: feel free to change it if it isn\'t the right one for your customers.', 'sabriel-ai' ), $lingue[ $lingua_attuale ][0] ?? $lingua_attuale ) ); ?></p>
							<?php endif; ?>
							<p style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:12px;padding:9px 12px;border-radius:8px;margin:0 0 10px;line-height:1.5"><?php esc_html_e( 'These 9 are not a technical limit: the AI engine behind the bot can write many more. They are simply the languages for which the label, the flag and the widget texts are already ready here.', 'sabriel-ai' ); ?></p>
							<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
								<?php foreach ( $lingue as $codice => $info ) : ?>
									<label style="display:flex;align-items:center;gap:8px;padding:11px 14px;border:1.5px solid <?php echo $codice === $lingua_attuale ? '#1461CC' : '#e5e5e5'; ?>;border-radius:9px;cursor:pointer;font-size:13.5px" class="sab-wiz-lingua-label">
										<input type="radio" name="bot_lingua" value="<?php echo esc_attr( $codice ); ?>" <?php checked( $lingua_attuale, $codice ); ?> style="margin:0">
										<span style="flex-shrink:0;line-height:0"><?php echo Sabriel_Base::bandiera_svg( $codice ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?></span><?php echo esc_html( $info[0] ); ?>
									</label>
								<?php endforeach; ?>
							</div>
							<?php echo self::stile_interruttori(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>
							<?php echo $this->render_interruttore_lingua_bot( 'wiz-' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>
							<?php echo $this->render_selettore_lingua_pannello( 'wiz-' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>
						</div>

						<div data-wiz-step="2" style="display:none">
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'Your business', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 18px"><?php esc_html_e( 'The basic details the bot will use to introduce itself and get contacted back.', 'sabriel-ai' ); ?></p>
							<button type="button" id="sab-wiz-sync-btn" class="button" style="margin-bottom:16px">🔄 <?php esc_html_e( 'Try filling it in from the site', 'sabriel-ai' ); ?></button>
							<div id="sab-wiz-sync-risultato" style="margin-bottom:16px"></div>
							<div style="margin-bottom:14px">
								<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Business name', 'sabriel-ai' ); ?></label>
								<input type="text" name="business_name" id="sab-wiz-business_name" value="<?php echo esc_attr( self::get( 'business_name' ) ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
							</div>
							<div style="margin-bottom:14px">
								<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Bot name', 'sabriel-ai' ); ?></label>
								<input type="text" name="bot_name" id="sab-wiz-bot_name" value="<?php echo esc_attr( Sabriel_Base::has( 'bot_name' ) ? (string) Sabriel_Base::get( 'bot_name' ) : '' ); ?>" placeholder="<?php echo esc_attr( Sabriel_Module_Branding::nome_bot_predefinito() ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
								<p style="color:#888;font-size:11.5px;margin:5px 0 0"><?php esc_html_e( 'This is the name your customers read at the top of the chat and in the welcome message. If you leave it empty, your business name is used.', 'sabriel-ai' ); ?></p>
							</div>
							<div style="margin-bottom:14px">
								<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Motto / tagline (optional)', 'sabriel-ai' ); ?></label>
								<input type="text" name="tagline" id="sab-wiz-tagline" value="<?php echo esc_attr( self::get( 'tagline' ) ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
							</div>
							<div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px">
								<div>
									<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Support email', 'sabriel-ai' ); ?></label>
									<input type="email" name="support_email" id="sab-wiz-support_email" value="<?php echo esc_attr( self::get( 'support_email' ) ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
								</div>
								<div>
									<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Phone', 'sabriel-ai' ); ?></label>
									<input type="text" name="phone_display" id="sab-wiz-phone_display" value="<?php echo esc_attr( self::get( 'phone_display' ) ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
								</div>
							</div>
							<div style="margin-bottom:6px">
								<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Website', 'sabriel-ai' ); ?></label>
								<input type="url" name="website_url" id="sab-wiz-website_url" value="<?php echo esc_attr( self::get( 'website_url' ) ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box">
							</div>
							<p style="color:#999;font-size:11.5px;margin:10px 0 0"><?php esc_html_e( 'Address, VAT number, price list and more stay available in Settings afterwards: just the essentials here to get started.', 'sabriel-ai' ); ?></p>
						</div>

						<div data-wiz-step="3" style="display:none">
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'What type of business is it?', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 18px"><?php esc_html_e( 'Choose the closest match: it fills the bot\'s tone with a starting point you can edit however you like.', 'sabriel-ai' ); ?></p>
							<div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:16px">
								<?php foreach ( self::preset_comportamento() as $preset ) : ?>
									<button type="button" class="button sab-wiz-preset-btn" data-testo="<?php echo esc_attr( $preset['testo'] ); ?>" style="font-size:12.5px"><?php echo esc_html( $preset['etichetta'] ); ?></button>
								<?php endforeach; ?>
							</div>
							<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Bot behavior and tone', 'sabriel-ai' ); ?></label>
							<textarea name="comportamento_tono" id="sab-wiz-comportamento" rows="6" maxlength="4000" style="width:100%;padding:10px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-size:13px;line-height:1.5;resize:vertical"><?php echo esc_textarea( self::get( 'comportamento_tono' ) ); ?></textarea>
						</div>

						<div data-wiz-step="4" style="display:none">
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'The bot\'s brain', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 18px"><?php esc_html_e( 'Without this the bot can\'t reply to customers yet: choose which AI to use and paste its key. You can also skip and do it later from AI Engine, but without a key the bot stays off.', 'sabriel-ai' ); ?></p>
							<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin-bottom:18px">
								<?php foreach ( Sabriel_Module_AI::PROVIDERS as $codice_provider => $info_provider ) : ?>
									<label style="display:flex;flex-direction:column;align-items:center;gap:4px;padding:12px 8px;border:1.5px solid <?php echo $codice_provider === $provider_attivo_wizard ? '#1461CC' : '#e5e5e5'; ?>;border-radius:9px;cursor:pointer;font-size:12px;font-weight:600;text-align:center" class="sab-wiz-provider-label">
										<input type="radio" name="ai_provider" value="<?php echo esc_attr( $codice_provider ); ?>" <?php checked( $provider_attivo_wizard, $codice_provider ); ?> style="margin:0 0 2px" class="sab-wiz-provider-radio">
										<?php echo esc_html( $info_provider[0] ); ?>
									</label>
								<?php endforeach; ?>
							</div>
							<?php foreach ( Sabriel_Module_AI::PROVIDERS as $codice_provider => $info_provider ) :
								list( , $campo_chiave_wizard, $url_chiave_wizard ) = $info_provider;
								$chiave_presente_wizard = (bool) get_option( $campo_chiave_wizard, '' );
							?>
							<div class="sab-wiz-provider-key" data-provider-key="<?php echo esc_attr( $codice_provider ); ?>" style="<?php echo $codice_provider === $provider_attivo_wizard ? '' : 'display:none'; ?>">
								<input type="password" class="sab-api-key" name="<?php echo esc_attr( $campo_chiave_wizard ); ?>" placeholder="<?php echo $chiave_presente_wizard ? esc_attr__( '•••••••••••••••••••• (leave empty to keep it unchanged)', 'sabriel-ai' ) : esc_attr__( 'Paste your API key here', 'sabriel-ai' ); ?>" style="width:100%;padding:9px 11px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-family:monospace;font-size:12.5px" autocomplete="new-password" autocorrect="off" autocapitalize="off" spellcheck="false" data-lpignore="true" data-1p-ignore data-form-type="other">
								<div style="display:flex;align-items:center;gap:10px;margin-top:6px">
									<a href="<?php echo esc_url( $url_chiave_wizard ); ?>" target="_blank" rel="noopener" style="font-size:11.5px;color:#1461CC"><?php esc_html_e( 'Where do I find the key →', 'sabriel-ai' ); ?></a>
									<?php if ( $chiave_presente_wizard ) : ?><span style="font-size:11px;color:#1a7d3a;font-weight:600"><?php esc_html_e( '✓ Key already saved', 'sabriel-ai' ); ?></span><?php endif; ?>
								</div>
								<?php
								$modello_corr_wz = Sabriel_Module_AI::modello_provider( $codice_provider );
								$lista_mod_wz    = Sabriel_Module_AI::MODELLI[ $codice_provider ];
								$ids_mod_wz      = array_column( $lista_mod_wz, 0 );
								$is_custom_wz    = ! in_array( $modello_corr_wz, $ids_mod_wz, true );
								?>
								<label style="font-weight:600;font-size:12px;display:block;margin:10px 0 4px"><?php esc_html_e( 'Model', 'sabriel-ai' ); ?></label>
								<select name="ai_model_<?php echo esc_attr( $codice_provider ); ?>" class="sab-model-select" data-provider="<?php echo esc_attr( $codice_provider ); ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-size:12.5px;background:#fff">
									<?php foreach ( $lista_mod_wz as $m_wz ) :
										list( $mid_wz, $mlabel_wz, $mprice_wz, $mreco_wz ) = $m_wz;
										$suffisso_wz = $mreco_wz ? ' · ' . __( 'recommended', 'sabriel-ai' ) : '';
									?>
									<option value="<?php echo esc_attr( $mid_wz ); ?>" <?php selected( ! $is_custom_wz && $modello_corr_wz === $mid_wz ); ?>><?php echo esc_html( $mlabel_wz . ': ' . $mprice_wz . $suffisso_wz ); ?></option>
									<?php endforeach; ?>
									<option value="__custom__" <?php selected( $is_custom_wz ); ?>><?php esc_html_e( 'Custom model…', 'sabriel-ai' ); ?></option>
								</select>
								<input type="text" name="ai_model_<?php echo esc_attr( $codice_provider ); ?>_custom" class="sab-model-custom" data-provider="<?php echo esc_attr( $codice_provider ); ?>" value="<?php echo $is_custom_wz ? esc_attr( $modello_corr_wz ) : ''; ?>" placeholder="<?php echo esc_attr( sprintf( __( 'Exact model ID (e.g. %s)', 'sabriel-ai' ), $ids_mod_wz[0] ) ); ?>" style="width:100%;margin-top:6px;padding:8px 10px;border:1px solid #ccc;border-radius:7px;box-sizing:border-box;font-family:monospace;font-size:12.5px;display:<?php echo $is_custom_wz ? 'block' : 'none'; ?>" autocomplete="off">
							</div>
							<?php endforeach; ?>
							<p style="color:#999;font-size:11.5px;margin:14px 0 0"><?php esc_html_e( 'Saved encrypted, never in plain text. You can test it and change it at any time from AI Engine.', 'sabriel-ai' ); ?></p>
						</div>

						<div data-wiz-step="5" style="display:none">
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'An extra hand from AI (optional)', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 18px"><?php esc_html_e( 'If you saved a key in the previous step, I can read your site\'s homepage and suggest a more tailored motto and starting tone. Just a suggestion: you decide whether to use it.', 'sabriel-ai' ); ?></p>
							<button type="button" id="sab-wiz-ai-btn" class="button button-primary">✨ <?php esc_html_e( 'Read my site with AI', 'sabriel-ai' ); ?></button>
							<div id="sab-wiz-ai-risultato" style="margin-top:16px"></div>
							<input type="hidden" id="sab-wiz-nonce-ai" value="<?php echo esc_attr( wp_create_nonce( 'sab_wizard_ai' ) ); ?>">
						</div>

						<div data-wiz-step="6" style="display:none;text-align:center">
							<div style="font-size:40px;margin-bottom:8px">🎉</div>
							<h1 style="font-size:21px;margin:0 0 8px"><?php esc_html_e( 'Ready to go', 'sabriel-ai' ); ?></h1>
							<p style="color:#666;font-size:14px;line-height:1.6;margin:0 0 8px"><?php esc_html_e( 'Press Finish to save. You can always refine colours, logo, price list and everything else afterwards: this configuration is only the starting point.', 'sabriel-ai' ); ?></p>
							<p style="color:#999;font-size:12.5px;margin:0 0 22px"><?php esc_html_e( 'One last thing not covered here: the logo. You\'ll find a dedicated button in Customization, with automatic syncing there too if your site already has one.', 'sabriel-ai' ); ?></p>
							<?php echo self::stile_interruttori(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS statico scritto nel plugin. ?>
							<label class="sab-toggle-row" style="text-align:left;max-width:520px;margin:0 auto">
								<span class="sab-toggle-text"><?php esc_html_e( 'One small favour, if you feel like it', 'sabriel-ai' ); ?><span class="sab-toggle-desc"><?php esc_html_e( 'This plugin is given away and there is no account, no trial and no limit behind it. If you want to help, switch this on: a small "Powered by Sabriel AI" line appears under the chat, linking back to the author. It changes nothing else, and Customization lets you switch it off again 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>

						<div style="display:flex;justify-content:space-between;margin-top:30px;padding-top:22px;border-top:1px solid #eee">
							<button type="button" id="sab-wiz-indietro" class="button" style="visibility:hidden">← <?php esc_html_e( 'Back', 'sabriel-ai' ); ?></button>
							<button type="button" id="sab-wiz-avanti" class="button button-primary"><?php esc_html_e( 'Next', 'sabriel-ai' ); ?> →</button>
							<button type="submit" id="sab-wiz-fine" class="button button-primary" style="display:none"><?php esc_html_e( 'Finish: save everything', 'sabriel-ai' ); ?></button>
						</div>
					</form>
				</div>
			</div>
		</div>
		<?php
		$this->render_wizard_script();
	}

	private function render_wizard_script() {
		?>
		<script>
		(function(){
			/* Le tre caselle della chiave stanno nello stesso modulo e due su tre sono
			   nascoste: il gestore password del browser le riempie lo stesso. Il server
			   le disegna SEMPRE vuote, quindi quello che c'e' dentro al caricamento non
			   l'ha scritto l'utente e va tolto. Chrome riempie in ritardo e piu' di una
			   volta, percio' si ripassa a piu' riprese. `dataset.scritto` marca le
			   caselle toccate davvero a mano: quelle non si svuotano mai. */
			function svuotaChiavi(){
				document.querySelectorAll('.sab-api-key').forEach(function(c){
					if (c.value && !c.dataset.scritto) c.value = '';
				});
			}
			document.querySelectorAll('.sab-api-key').forEach(function(c){
				c.addEventListener('input', function(){ c.dataset.scritto = '1'; });
			});
			svuotaChiavi();
			[80, 300, 900].forEach(function(ms){ setTimeout(svuotaChiavi, ms); });
		})();
		</script>
		<script>
		(function(){
			var step = 1;
			var TOTALE = 6;
			function mostraStep(n){
				document.querySelectorAll('[data-wiz-step]').forEach(function(el){
					el.style.display = (parseInt(el.dataset.wizStep,10)===n) ? '' : 'none';
				});
				document.querySelectorAll('.sab-wiz-dot').forEach(function(d){
					d.style.background = (parseInt(d.dataset.dot,10)<=n) ? '#1461CC' : '#e2e8f0';
				});
				document.getElementById('sab-wiz-indietro').style.visibility = (n===1) ? 'hidden' : 'visible';
				document.getElementById('sab-wiz-avanti').style.display = (n===TOTALE) ? 'none' : '';
				document.getElementById('sab-wiz-fine').style.display = (n===TOTALE) ? '' : 'none';
				step = n;
			}
			document.getElementById('sab-wiz-avanti').addEventListener('click', function(){ if(step<TOTALE) mostraStep(step+1); });
			document.getElementById('sab-wiz-indietro').addEventListener('click', function(){ if(step>1) mostraStep(step-1); });

			document.querySelectorAll('input[name="bot_lingua"]').forEach(function(radio){
				radio.addEventListener('change', function(){
					document.querySelectorAll('.sab-wiz-lingua-label').forEach(function(lbl){ lbl.style.borderColor = '#e5e5e5'; });
					radio.closest('.sab-wiz-lingua-label').style.borderColor = '#1461CC';
				});
			});

			document.querySelectorAll('.sab-wiz-provider-radio').forEach(function(radio){
				radio.addEventListener('change', function(){
					document.querySelectorAll('.sab-wiz-provider-label').forEach(function(lbl){ lbl.style.borderColor = '#e5e5e5'; });
					radio.closest('.sab-wiz-provider-label').style.borderColor = '#1461CC';
					document.querySelectorAll('.sab-wiz-provider-key').forEach(function(box){
						box.style.display = (box.dataset.providerKey === radio.value) ? '' : 'none';
					});
				});
			});

			document.querySelectorAll('.sab-model-select').forEach(function(sel){
				sel.addEventListener('change', function(){
					var box = document.querySelector('.sab-model-custom[data-provider="'+this.dataset.provider+'"]');
					if (box) { box.style.display = (this.value === '__custom__') ? 'block' : 'none'; if (this.value === '__custom__') box.focus(); }
				});
			});

			document.querySelectorAll('.sab-wiz-preset-btn').forEach(function(btn){
				btn.addEventListener('click', function(){
					var ta = document.getElementById('sab-wiz-comportamento');
					if(ta.value.trim()!=='' && !confirm(<?php echo wp_json_encode( __( 'This replaces the text already written. Continue?', 'sabriel-ai' ) ); ?>)) return;
					ta.value = btn.dataset.testo;
				});
			});

			var syncBtn = document.getElementById('sab-wiz-sync-btn');
			if(syncBtn){
				syncBtn.addEventListener('click', function(){
					syncBtn.disabled = true;
					var testoOrig = syncBtn.textContent;
					syncBtn.textContent = <?php echo wp_json_encode( __( 'Searching…', 'sabriel-ai' ) ); ?>;
					var risultato = document.getElementById('sab-wiz-sync-risultato');
					var fd = new FormData();
					fd.append('action','sabriel_ai_sincronizza_dal_sito');
					fd.append('nonce', <?php echo wp_json_encode( wp_create_nonce( 'sab_sync_sito' ) ); ?>);
					fetch(ajaxurl, { method:'POST', body:fd, credentials:'same-origin' })
						.then(function(r){ return r.json(); })
						.then(function(res){
							syncBtn.disabled = false;
							syncBtn.textContent = testoOrig;
							if(!res.success){ risultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+<?php echo wp_json_encode( __( 'I couldn\'t manage it, feel free to fill it in by hand below.', 'sabriel-ai' ) ); ?>+'</p>'; return; }
							var mappa = { business_name:'sab-wiz-business_name', tagline:'sab-wiz-tagline', website_url:'sab-wiz-website_url', support_email:'sab-wiz-support_email' };
							var applicati = [];
							Object.keys(mappa).forEach(function(k){
								var info = res.data.identita[k];
								var campo = document.getElementById(mappa[k]);
								if(info && campo && campo.value.trim()===''){ campo.value = info.trovato; applicati.push(k); }
							});
							risultato.innerHTML = applicati.length
								? '<p style="color:#1a7d3a;font-size:12.5px">✓ '+<?php echo wp_json_encode( __( 'I found and filled in what I could: check it and correct anything that needs it.', 'sabriel-ai' ) ); ?>+'</p>'
								: '<p style="color:#666;font-size:12.5px">'+<?php echo wp_json_encode( __( 'I didn\'t find anything new to add.', 'sabriel-ai' ) ); ?>+'</p>';
						})
						.catch(function(){
							syncBtn.disabled = false;
							syncBtn.textContent = testoOrig;
							risultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+<?php echo wp_json_encode( __( 'Connection error, please try again.', 'sabriel-ai' ) ); ?>+'</p>';
						});
				});
			}

			var aiBtn = document.getElementById('sab-wiz-ai-btn');
			if(aiBtn){
				aiBtn.addEventListener('click', function(){
					aiBtn.disabled = true;
					var testoOrig = aiBtn.textContent;
					aiBtn.textContent = <?php echo wp_json_encode( __( 'Reading the site…', 'sabriel-ai' ) ); ?>;
					var risultato = document.getElementById('sab-wiz-ai-risultato');
					risultato.innerHTML = '';
					var fd = new FormData();
					fd.append('action','sabriel_ai_leggi_homepage');
					fd.append('nonce', document.getElementById('sab-wiz-nonce-ai').value);
					fetch(ajaxurl, { method:'POST', body:fd, credentials:'same-origin' })
						.then(function(r){ return r.json(); })
						.then(function(res){
							aiBtn.disabled = false;
							aiBtn.textContent = testoOrig;
							if(!res.success){
								risultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+ (res.data && res.data.messaggio ? String(res.data.messaggio).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') : <?php echo wp_json_encode( __( 'I couldn\'t manage it.', 'sabriel-ai' ) ); ?>) +'</p>';
								return;
							}
							var d = res.data;
							if(!d.tagline && !d.tono_suggerito){
								risultato.innerHTML = '<p style="color:#666;font-size:12.5px">'+<?php echo wp_json_encode( __( 'The site didn\'t tell me enough for a useful suggestion: no problem, what you\'ve written so far is just fine.', 'sabriel-ai' ) ); ?>+'</p>';
								return;
							}
							var html = '<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:9px;padding:14px;text-align:left">';
							if(d.tagline) html += '<p style="font-size:12.5px;margin:0 0 8px"><strong>'+<?php echo wp_json_encode( __( 'Suggested motto:', 'sabriel-ai' ) ); ?>+'</strong> '+d.tagline.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</p>';
							if(d.tono_suggerito) html += '<p style="font-size:12.5px;margin:0 0 10px;color:#444">'+d.tono_suggerito.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</p>';
							html += '<button type="button" id="sab-wiz-ai-applica" class="button button-small">'+<?php echo wp_json_encode( __( 'Use this suggestion', 'sabriel-ai' ) ); ?>+'</button>';

							html += '<p id="sab-wiz-ai-applicato" style="color:#1a7d3a;font-size:12px;margin:8px 0 0"></p></div>';
							risultato.innerHTML = html;
							document.getElementById('sab-wiz-ai-applica').addEventListener('click', function(){
								if(d.tagline) document.getElementById('sab-wiz-tagline').value = d.tagline;
								if(d.tono_suggerito) document.getElementById('sab-wiz-comportamento').value = d.tono_suggerito;
								document.getElementById('sab-wiz-ai-applicato').textContent = <?php echo wp_json_encode( __( 'Applied.', 'sabriel-ai' ) ); ?>;
							});
						})
						.catch(function(){
							aiBtn.disabled = false;
							aiBtn.textContent = testoOrig;
							risultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+<?php echo wp_json_encode( __( 'Connection error, please try again.', 'sabriel-ai' ) ); ?>+'</p>';
						});
				});
			}

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

	public static function taglia( $testo, $massimo ) {
		$testo = (string) $testo;
		return function_exists( 'mb_substr' ) ? mb_substr( $testo, 0, $massimo ) : substr( $testo, 0, $massimo );
	}

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

	public static function lingua_rilevata_da_wp() {
		$locale = get_locale();
		$prefisso = strtolower( substr( $locale, 0, 2 ) );
		$supportate = self::lingue_codici();

		return in_array( $prefisso, $supportate, true ) ? $prefisso : 'en';
	}

	public static function bot_lingua_con_rilevamento() {
		return Sabriel_Base::has( 'bot_lingua' ) ? self::get( 'bot_lingua' ) : self::lingua_rilevata_da_wp();
	}

	public static function locale_bot() {
		$mappa = self::lingue_locali();
		$lingua = self::bot_lingua_con_rilevamento();
		return $mappa[ $lingua ] ?? 'en_US';
	}

	public static function stile_interruttori() {
		return '<style>'
			. '.sab-toggle-row{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:12px;padding:14px 16px;background:#fafafa;border-radius:10px;border:1px solid #eee;cursor:pointer}'
			. '.sab-toggle-text{font-weight:600;font-size:13.5px;color:#111}'
			. '.sab-toggle-desc{display:block;color:#888;font-size:12px;font-weight:400;margin-top:3px;line-height:1.4}'
			. '.sab-toggle{position:relative;display:inline-block;width:42px;height:24px;flex-shrink:0}'
			. '.sab-toggle input{opacity:0;width:0;height:0;position:absolute}'
			. '.sab-toggle-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background:#d5d5d5;border-radius:24px;transition:background .2s}'
			. '.sab-toggle-slider:before{position:absolute;content:"";height:18px;width:18px;left:3px;top:3px;background:#fff;border-radius:50%;transition:transform .2s;box-shadow:0 1px 3px rgba(0,0,0,.25)}'
			. '.sab-toggle input:checked + .sab-toggle-slider{background:#1461CC}'
			. '.sab-toggle input:checked + .sab-toggle-slider:before{transform:translateX(18px)}'
			. '</style>';
	}

	private function render_interruttore_lingua_bot( $prefisso_id = '' ) {
		$parla_tutte = ! self::get( 'bot_lingua_fissa' );
		$id_avviso   = $prefisso_id . 'sab-lingua-avviso';
		$id_check    = $prefisso_id . 'sab-lingua-tutte';
		ob_start();
		?>
		<label class="sab-toggle-row" style="max-width:520px;margin-top:14px">
			<span class="sab-toggle-text"><?php echo esc_html( self::etichetta_lingua_bot() ); ?><span class="sab-toggle-desc"><?php esc_html_e( 'On (default): the bot replies to every customer in the language the customer uses to write, whatever it is. Off: the bot always replies only in the language chosen above, even to those who write in another one, unless the customer expressly asks to switch.', 'sabriel-ai' ); ?></span></span>
			<span class="sab-toggle">
				<input type="checkbox" name="bot_parla_tutte_le_lingue" id="<?php echo esc_attr( $id_check ); ?>" value="1" <?php checked( $parla_tutte ); ?>>
				<span class="sab-toggle-slider"></span>
			</span>
		</label>
		<p id="<?php echo esc_attr( $id_avviso ); ?>" style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:11.5px;padding:9px 12px;border-radius:8px;margin:8px 0 0;max-width:520px;line-height:1.5;<?php echo esc_attr( $parla_tutte ? '' : 'display:none' ); ?>"><?php esc_html_e( 'The assistant will reply to each customer in the language they start writing in. The language chosen above remains the widget\'s language (buttons, labels and first greeting), that is, what the customer sees before writing anything.', 'sabriel-ai' ); ?></p>
		<script>
		(function(){
			var c = document.getElementById('<?php echo esc_js( $id_check ); ?>');
			var a = document.getElementById('<?php echo esc_js( $id_avviso ); ?>');
			if (!c || !a) return;
			c.addEventListener('change', function(){ a.style.display = c.checked ? '' : 'none'; });
		})();
		</script>
		<?php
		return ob_get_clean();
	}

	private function render_selettore_lingua_pannello( $prefisso_id = '' ) {
		$lingue_pannello = self::lingue_pannello();

		$locale_personale = (string) get_user_meta( get_current_user_id(), self::META_LINGUA_PANNELLO, true );
		$segue_il_sito    = ( '' === $locale_personale || ! isset( $lingue_pannello[ $locale_personale ] ) );
		$valore_attuale   = $segue_il_sito ? self::LOCALE_COME_IL_SITO : $locale_personale;
		$bandiera_attuale = $segue_il_sito ? get_locale() : $locale_personale;
		$id_select   = $prefisso_id . 'sab-lingua-pannello';
		$id_stato    = $prefisso_id . 'sab-lingua-pannello-stato';
		$id_bandiera = $prefisso_id . 'sab-lingua-pannello-bandiera';
		ob_start();
		?>
		<div style="margin-top:14px;margin-bottom:6px">
			<label style="font-weight:700;font-size:13px;display:block;margin-bottom:6px"><?php esc_html_e( 'Language of this panel', 'sabriel-ai' ); ?></label>
			<p style="color:#888;font-size:11.5px;margin:0 0 8px;max-width:480px;line-height:1.5"><?php esc_html_e( 'Just for you and just here: change the language of this plugin\'s pages. It does not touch the rest of WordPress, it does not touch the other users and it does not touch what your customers see.', 'sabriel-ai' ); ?></p>
			<div style="display:flex;align-items:center;gap:8px;max-width:280px">
				<span id="<?php echo esc_attr( $id_bandiera ); ?>" style="flex-shrink:0;line-height:0"><?php echo Sabriel_Base::bandiera_svg( $bandiera_attuale ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
				<select id="<?php echo esc_attr( $id_select ); ?>" style="flex:1;width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					<option value="<?php echo esc_attr( self::LOCALE_COME_IL_SITO ); ?>" <?php selected( $valore_attuale, self::LOCALE_COME_IL_SITO ); ?>><?php esc_html_e( 'Same as the site (default)', 'sabriel-ai' ); ?></option>
					<?php foreach ( $lingue_pannello as $codice => $etichetta ) : ?>
						<option value="<?php echo esc_attr( $codice ); ?>" <?php selected( $valore_attuale, $codice ); ?>><?php echo esc_html( $etichetta ); ?></option>
					<?php endforeach; ?>
				</select>
			</div>
			<p style="color:#888;font-size:11.5px;margin:8px 0 0;max-width:480px;line-height:1.5">
				<?php if ( $segue_il_sito ) : ?>
					<?php esc_html_e( 'It currently follows the language set in WordPress Settings → General.', 'sabriel-ai' ); ?>
				<?php else : ?>
					<?php esc_html_e( 'You see this plugin\'s pages in this language. The rest of WordPress keeps following Settings → General. Set it back to «Same as the site» to align these pages too.', 'sabriel-ai' ); ?>
				<?php endif; ?>
			</p>
			<span id="<?php echo esc_attr( $id_stato ); ?>" style="font-size:11.5px;color:#888;margin-left:8px"></span>
		</div>
		<script>
		(function(){
			var mappaBandiere = {
				'<?php echo esc_js( self::LOCALE_COME_IL_SITO ); ?>': <?php echo wp_json_encode( Sabriel_Base::bandiera_svg( get_locale() ) ); ?>,
				<?php foreach ( array_keys( $lingue_pannello ) as $cod ) : ?>
				'<?php echo esc_js( $cod ); ?>': <?php echo wp_json_encode( Sabriel_Base::bandiera_svg( $cod ) ); ?>,
				<?php endforeach; ?>
			};
			var bandieraEl = document.getElementById('<?php echo esc_js( $id_bandiera ); ?>');
			var selLingua = document.getElementById('<?php echo esc_js( $id_select ); ?>');
			if (bandieraEl && selLingua) {
				selLingua.addEventListener('change', function(){
					if (mappaBandiere[selLingua.value]) bandieraEl.innerHTML = mappaBandiere[selLingua.value];
				});
			}
		})();
		</script>
		<script>
		(function(){
			var sel = document.getElementById('<?php echo esc_js( $id_select ); ?>');
			var stato = document.getElementById('<?php echo esc_js( $id_stato ); ?>');
			if(!sel) return;

			var form = sel.closest('form');
			var toccato = false;
			var guardia = function(e){ e.preventDefault(); e.returnValue = ''; return ''; };
			if (form) {
				form.addEventListener('input', function(e){
					if (e.target !== sel && !toccato) { toccato = true; window.addEventListener('beforeunload', guardia); }
				});
				form.addEventListener('submit', function(){ window.removeEventListener('beforeunload', guardia); });
			}
			sel.addEventListener('change', function(){
				stato.textContent = <?php echo wp_json_encode( __( 'Updating…', 'sabriel-ai' ) ); ?>;
				var fd = new FormData();
				fd.append('action', 'sabriel_ai_cambia_lingua_pannello');
				fd.append('nonce', '<?php echo esc_js( wp_create_nonce( 'sabriel_ai_cambia_lingua_pannello' ) ); ?>');
				fd.append('locale', sel.value);
				fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', body: fd })
					.then(function(r){ return r.json(); })
					.then(function(d){
						if (d && d.success) { location.reload(); }
						else { stato.textContent = <?php echo wp_json_encode( __( 'Error, please try again.', 'sabriel-ai' ) ); ?>; }
					})
					.catch(function(){ stato.textContent = <?php echo wp_json_encode( __( 'Connection error.', 'sabriel-ai' ) ); ?>; });
			});
		})();
</script>
		<?php
		return ob_get_clean();
	}

	public static function preset_comportamento() {
		return [
			'ecommerce' => [
				'etichetta' => __( 'E-commerce', 'sabriel-ai' ),
				'testo'     => __( "Reply in a practical, purchase-oriented way. If the customer asks about a product, give clear information on availability, price and features. For questions about orders already placed, shipping or returns, ask for the order number and direct them to customer service if a human is needed. Encourage the purchase without being pushy.", 'sabriel-ai' ),
			],
			'professionale' => [
				'etichetta' => __( 'Professional practice', 'sabriel-ai' ),
				'testo'     => __( "Keep a professional, discreet tone. Never give legal, tax or specialist advice in chat: your job is to gather the essential details of the request and offer a real consultation. Reassure about the confidentiality of what's written in chat.", 'sabriel-ai' ),
			],
			'estetica' => [
				'etichetta' => __( 'Beauty / wellness center', 'sabriel-ai' ),
				'testo'     => __( "Reply in a warm, welcoming tone. If the customer asks about a treatment, briefly explain what it involves and what it costs, then invite them to contact us to arrange a time. Be reassuring with people writing for the first time.", 'sabriel-ai' ),
			],
			'ristorazione' => [
				'etichetta' => __( 'Restaurant / bar', 'sabriel-ai' ),
				'testo'     => __( "Friendly, direct tone. Help with opening hours, questions about the menu and practical information; for booking a table, point them to direct contact. If you do not know a particular dish or ingredient, say so honestly instead of making it up: better to send them to a phone call for allergies.", 'sabriel-ai' ),
			],
			'medico' => [
				'etichetta' => __( 'Medical / dental practice', 'sabriel-ai' ),
				'testo'     => __( "Reassuring, professional tone. NEVER give medical advice, diagnoses or guidance on drugs or treatments, even if the customer insists: your job is only to give practical information about the practice and to point people to direct contact for booking a visit. For any health concern, always invite them to speak to the doctor directly.", 'sabriel-ai' ),
			],
			'artigiano' => [
				'etichetta' => __( 'Craftsperson / local shop', 'sabriel-ai' ),
				'testo'     => __( "Personal, direct tone, like someone who really knows the craft. Highlight the handmade quality and the option to customize the work. If the customer describes what they need, ask a few more questions to fully understand before suggesting a solution.", 'sabriel-ai' ),
			],
			'immobiliare' => [
				'etichetta' => __( 'Real estate', 'sabriel-ai' ),
				'testo'     => __( "Professional but warm tone. Help house-hunters understand the features of available properties and arrange a viewing. For those looking to sell or rent, gather the basic details of the property and offer a free valuation.", 'sabriel-ai' ),
			],
		];
	}

	public static function valuta() {
		$cod = self::get( 'valuta_codice' ) ?: 'EUR';
		$sim = self::get( 'valuta_simbolo' );
		if ( '' === (string) $sim ) {
			$sim = isset( self::VALUTE[ $cod ] ) ? self::VALUTE[ $cod ][0] : $cod;
		}
		$pos = self::get( 'valuta_posizione' ) === 'prima' ? 'prima' : 'dopo';
		return [ 'codice' => $cod, 'simbolo' => $sim, 'posizione' => $pos ];
	}

	public static function con_valuta( $importo ) {
		$v = self::valuta();
		return 'prima' === $v['posizione'] ? $v['simbolo'] . $importo : $importo . ' ' . $v['simbolo'];
	}

	/**
	 * Legge un campo di una riga del listino o dei link, sempre come testo.
	 *
	 * ⚠ NON basta `trim( $r['x'] ?? '' )`. Il `?? ''` copre il campo ASSENTE, non
	 * il campo che e' diventato un ELENCO: `trim( array )` in PHP 8 e' un errore
	 * FATALE, e queste due funzioni costruiscono il prompt della ROTTA PUBBLICA
	 * DELLA CHAT. Un listino annidato arriva dal ripristino di una configurazione
	 * esportata: da quel momento la chat risponde 500 a tutti i visitatori.
	 */
	private static function campo_riga( $riga, $campo ) {
		if ( ! is_array( $riga ) || ! isset( $riga[ $campo ] ) || ! is_scalar( $riga[ $campo ] ) ) {
			return '';
		}
		return trim( (string) $riga[ $campo ] );
	}

	public static function listino_come_testo() {
		$righe = self::get( 'listino_servizi' );
		if ( is_string( $righe ) ) {
			return $righe;
		}
		$pezzi = [];
		foreach ( (array) $righe as $r ) {
			$nome  = self::campo_riga( $r, 'nome' );
			$prezzo = self::campo_riga( $r, 'prezzo' );
			if ( '' === $nome || '' === $prezzo ) {
				continue;
			}
			$descrizione = self::campo_riga( $r, 'descrizione' );
			$pezzi[]     = $descrizione ? "{$nome}={$prezzo}({$descrizione})" : "{$nome}={$prezzo}";
		}
		return implode( '|', $pezzi );
	}

	public static function pagine_come_testo() {
		$righe = self::get( 'pagine_link' );
		if ( is_string( $righe ) ) {
			return $righe;
		}
		$pezzi = [];
		foreach ( (array) $righe as $r ) {
			$etichetta = self::campo_riga( $r, 'etichetta' );
			$url       = self::campo_riga( $r, 'url' );
			if ( '' === $etichetta || '' === $url ) {
				continue;
			}
			$pezzi[] = "{$etichetta}={$url}";
		}
		return implode( '|', $pezzi );
	}

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

		$campi_semplici = [ 'business_name', 'founder_name', 'tagline', 'support_email', 'phone_display', 'whatsapp_number', 'website_url', 'address', 'piva', 'since_year', 'service_area' ];

		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_settings_nonce'] ) && check_admin_referer( 'sab_settings_action', 'sab_settings_nonce' ) ) {
			foreach ( $campi_semplici as $key ) {

				$valore = ( isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ) ? sanitize_text_field( wp_unslash( $_POST[ $key ] ) ) : '';

				if ( function_exists( 'mb_substr' ) ) {
					$valore = mb_substr( $valore, 0, self::MAX_LUNGHEZZA_CAMPO );
				} else {
					$valore = substr( $valore, 0, self::MAX_LUNGHEZZA_CAMPO );
				}
				if ( 'support_email' === $key && $valore && ! is_email( $valore ) ) {
					continue;
				}

				if ( 'website_url' === $key && '' !== $valore ) {
					$valore = esc_url_raw( $valore );
				}
				Sabriel_Base::update( $key, $valore );
			}

			Sabriel_Base::update( 'comportamento_tono', self::taglia( sanitize_textarea_field( wp_unslash( $_POST['comportamento_tono'] ?? '' ) ), self::MAX_LUNGHEZZA_TONO ) );

			Sabriel_Base::update( 'descrizione_attivita', self::taglia( sanitize_text_field( wp_unslash( $_POST['descrizione_attivita'] ?? '' ) ), self::MAX_LUNGHEZZA_DESCRIZIONE ) );
			$lingua_scelta_impostazioni = sanitize_text_field( wp_unslash( $_POST['bot_lingua'] ?? self::get( 'bot_lingua' ) ) );
			if ( in_array( $lingua_scelta_impostazioni, self::lingue_codici(), true ) ) {
				Sabriel_Base::update( 'bot_lingua', $lingua_scelta_impostazioni );
			}

			Sabriel_Base::update( 'bot_lingua_fissa', ! isset( $_POST['bot_parla_tutte_le_lingue'] ) );
			$sab_orari_inviati = wp_unslash( $_POST['orari_apertura'] ?? [] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ogni cella viene ripulita una per una nel ciclo qui sotto.
			$sab_orari_puliti  = [];
			$sab_orari_errori  = [];
			$sab_orari_note    = [];
			$sab_giorni_label  = self::giorni_settimana();
			if ( is_array( $sab_orari_inviati ) ) {
				foreach ( range( 1, 7 ) as $sab_dow ) {
					$sab_riga     = $sab_orari_inviati[ $sab_dow ] ?? [];
					$sab_aperto   = ! empty( $sab_riga['aperto'] );
					$sab_fasce_in = ( isset( $sab_riga['fasce'] ) && is_array( $sab_riga['fasce'] ) ) ? $sab_riga['fasce'] : [];
					$sab_fasce_ok = [];
					foreach ( $sab_fasce_in as $sab_f ) {
						if ( ! is_array( $sab_f ) ) {
							continue;
						}
						$sab_dalle = sanitize_text_field( $sab_f['dalle'] ?? '' );
						$sab_alle  = sanitize_text_field( $sab_f['alle'] ?? '' );
						$sab_ok    = preg_match( '/^([01]\d|2[0-3]):([0-5]\d)$/', $sab_dalle ) && preg_match( '/^([01]\d|2[0-3]):([0-5]\d)$/', $sab_alle );
						if ( ! $sab_ok || $sab_dalle === $sab_alle ) {
							continue;
						}
						$sab_fasce_ok[] = [ 'dalle' => $sab_dalle, 'alle' => $sab_alle ];
					}
					if ( $sab_aperto && ! empty( $sab_fasce_ok ) ) {
						$sab_orari_puliti[ $sab_dow ] = [ 'aperto' => true, 'fasce' => $sab_fasce_ok ];
					} else {
						if ( $sab_aperto && empty( $sab_fasce_ok ) ) {
							$sab_orari_errori[] = sprintf(
								/* translators: %s: name of the weekday */
								__( '%s: no valid time range, the day has been left closed.', 'sabriel-ai' ),
								$sab_giorni_label[ $sab_dow ]
							);
						}

						$sab_orari_puliti[ $sab_dow ] = [ 'aperto' => false, 'fasce' => $sab_fasce_ok ];
					}
				}

				$sab_sconfini = [];
				$sab_note_sconfino = [];
				foreach ( $sab_orari_puliti as $sab_dow => $sab_giorno_dati ) {

					if ( empty( $sab_giorno_dati['aperto'] ) || empty( $sab_giorno_dati['fasce'] ) ) {
						continue;
					}
					$sab_restano = [];
					foreach ( $sab_giorno_dati['fasce'] as $sab_f ) {
						if ( $sab_f['alle'] >= $sab_f['dalle'] || '00:00' === $sab_f['alle'] ) {
							$sab_restano[] = $sab_f;
							continue;
						}
						$sab_dow_dopo = ( 7 === $sab_dow ) ? 1 : $sab_dow + 1;
						$sab_restano[]  = [ 'dalle' => $sab_f['dalle'], 'alle' => '00:00' ];
						$sab_sconfini[ $sab_dow_dopo ][] = [ 'dalle' => '00:00', 'alle' => $sab_f['alle'] ];
						$sab_note_sconfino[ $sab_dow_dopo ][] = sprintf(
							/* translators: 1: starting day; 2: start time; 3: end time; 4: next day */
							__( '%1$s %2$s → %3$s crosses midnight: we split it into %1$s %2$s → 00:00 and %4$s 00:00 → %3$s, so the assistant knows you are open on the right day.', 'sabriel-ai' ),
							$sab_giorni_label[ $sab_dow ],
							$sab_f['dalle'],
							$sab_f['alle'],
							$sab_giorni_label[ $sab_dow_dopo ]
						);
					}
					$sab_orari_puliti[ $sab_dow ]['fasce'] = $sab_restano;
				}
				foreach ( $sab_sconfini as $sab_dow_dopo => $sab_fasce_extra ) {

					if ( empty( $sab_orari_puliti[ $sab_dow_dopo ]['aperto'] ) ) {
						foreach ( $sab_fasce_extra as $sab_f_persa ) {
							$sab_orari_errori[] = sprintf(
								/* translators: 1: name of the next day; 2: end time of the overnight shift */
								__( '%1$s is marked as closed, so the after-midnight tail of the night shift (00:00 → %2$s) was not saved. If you really do work until then, open %1$s and add the 00:00 → %2$s slot.', 'sabriel-ai' ),
								$sab_giorni_label[ $sab_dow_dopo ],
								$sab_f_persa['alle']
							);
						}
						continue;
					}
					if ( ! empty( $sab_note_sconfino[ $sab_dow_dopo ] ) ) {
						$sab_orari_note = array_merge( $sab_orari_note, $sab_note_sconfino[ $sab_dow_dopo ] );
					}
					$sab_unite = array_merge( $sab_orari_puliti[ $sab_dow_dopo ]['fasce'], $sab_fasce_extra );

					$sab_viste = [];
					$sab_finali = [];
					foreach ( $sab_unite as $sab_f ) {
						$sab_chiave = $sab_f['dalle'] . '|' . $sab_f['alle'];
						if ( isset( $sab_viste[ $sab_chiave ] ) ) {
							continue;
						}
						$sab_viste[ $sab_chiave ] = true;
						$sab_finali[]             = $sab_f;
					}
					$sab_orari_puliti[ $sab_dow_dopo ] = [ 'aperto' => true, 'fasce' => $sab_finali ];
				}
			}
			Sabriel_Base::update( 'orari_apertura', $sab_orari_puliti );
			Sabriel_Base::update( 'rate_abilitate', isset( $_POST['rate_abilitate'] ) );
			Sabriel_Base::update( 'permetti_fuori_tema', isset( $_POST['permetti_fuori_tema'] ) );
			$soglia_grezza = sanitize_text_field( wp_unslash( $_POST['rate_soglia'] ?? '' ) );
			$soglia_numero = (int) preg_replace( '/[^0-9]/', '', $soglia_grezza );
			Sabriel_Base::update( 'rate_soglia', $soglia_numero > 0 ? (string) $soglia_numero : '' );

			$iva_paese = sanitize_text_field( wp_unslash( $_POST['aliquota_iva_paese'] ?? '' ) );
			$iva_valida = array_key_exists( $iva_paese, self::IVA_PAESI ) || in_array( $iva_paese, [ '', 'nessuna', 'altro' ], true );
			if ( ! $iva_valida ) {
				$iva_paese = '';
			}
			if ( 'altro' === $iva_paese ) {

				$iva_grezza = sanitize_text_field( wp_unslash( $_POST['aliquota_iva_custom'] ?? '' ) );
				$iva_numero = (float) str_replace( ',', '.', preg_replace( '/[^0-9.,]/', '', $iva_grezza ) );
				$iva_finale = ( $iva_numero > 0 && $iva_numero <= 100 ) ? (string) $iva_numero : '';

				if ( '' === $iva_finale ) {
					$iva_paese = '';
				}
			} elseif ( array_key_exists( $iva_paese, self::IVA_PAESI ) ) {
				$iva_finale = (string) self::IVA_PAESI[ $iva_paese ][1];
			} else {
				$iva_finale = '';
			}
			Sabriel_Base::update( 'aliquota_iva_paese', $iva_paese );
			Sabriel_Base::update( 'aliquota_iva', $iva_finale );

			$regime_iva = sanitize_text_field( wp_unslash( $_POST['prezzi_regime_iva'] ?? 'esclusa' ) );
			if ( ! in_array( $regime_iva, [ 'esclusa', 'inclusa' ], true ) ) {
				$regime_iva = 'esclusa';
			}
			Sabriel_Base::update( 'prezzi_regime_iva', $regime_iva );

			$val_cod = sanitize_text_field( wp_unslash( $_POST['valuta_codice'] ?? 'EUR' ) );
			if ( 'altro' === $val_cod ) {
				$val_cod_libero = strtoupper( sanitize_text_field( wp_unslash( $_POST['valuta_codice_custom'] ?? '' ) ) );
				$val_sim_libero = sanitize_text_field( wp_unslash( $_POST['valuta_simbolo_custom'] ?? '' ) );
				$val_cod = $val_cod_libero ?: 'EUR';
				$val_sim = $val_sim_libero ?: $val_cod;
			} elseif ( array_key_exists( $val_cod, self::VALUTE ) ) {
				$val_sim = self::VALUTE[ $val_cod ][0];
			} else {
				$val_cod = 'EUR';
				$val_sim = '€';
			}
			$val_pos = 'prima' === sanitize_text_field( wp_unslash( $_POST['valuta_posizione'] ?? 'dopo' ) ) ? 'prima' : 'dopo';
			Sabriel_Base::update( 'valuta_codice', $val_cod );
			Sabriel_Base::update( 'valuta_simbolo', $val_sim );
			Sabriel_Base::update( 'valuta_posizione', $val_pos );

			$struttura_scelta = sanitize_text_field( wp_unslash( $_POST['pagamento_struttura'] ?? 'non_applicabile' ) );
			if ( in_array( $struttura_scelta, [ 'non_applicabile', 'consegna', '50_50', '25_25_50', 'personalizzato' ], true ) ) {
				Sabriel_Base::update( 'pagamento_struttura', $struttura_scelta );
			}
			$sab_acconto_grezzo = wp_unslash( $_POST['pagamento_acconto_pct'] ?? '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ridotto alle sole cifre nella riga successiva.
			$sab_meta_grezzo    = wp_unslash( $_POST['pagamento_meta_pct'] ?? '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ridotto alle sole cifre nella riga successiva.
			$acconto_pct        = is_scalar( $sab_acconto_grezzo ) ? max( 0, min( 100, (int) preg_replace( '/[^0-9]/', '', (string) $sab_acconto_grezzo ) ) ) : 0;
			$meta_pct           = is_scalar( $sab_meta_grezzo ) ? max( 0, min( 100, (int) preg_replace( '/[^0-9]/', '', (string) $sab_meta_grezzo ) ) ) : 0;
			if ( $acconto_pct + $meta_pct > 100 ) {
				$meta_pct = 100 - $acconto_pct;
			}
			Sabriel_Base::update( 'pagamento_acconto_pct', $acconto_pct > 0 ? (string) $acconto_pct : '' );
			Sabriel_Base::update( 'pagamento_meta_pct', $meta_pct > 0 ? (string) $meta_pct : '' );

			$listino_pulito = [];
			foreach ( (array) wp_unslash( $_POST['listino'] ?? [] ) as $riga ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ogni campo della riga viene ripulito uno per uno qui sotto.
				$nome        = sanitize_text_field( $riga['nome'] ?? '' );
				$prezzo      = sanitize_text_field( $riga['prezzo'] ?? '' );
				$descrizione = sanitize_text_field( $riga['descrizione'] ?? '' );
				if ( '' === $nome && '' === $prezzo ) {
					continue;
				}
				$listino_pulito[] = [ 'nome' => $nome, 'prezzo' => $prezzo, 'descrizione' => $descrizione ];
			}
			Sabriel_Base::update( 'listino_servizi', $listino_pulito );

			$pagine_pulite = [];
			foreach ( (array) wp_unslash( $_POST['pagine'] ?? [] ) as $riga ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ogni campo della riga viene ripulito uno per uno qui sotto.
				$etichetta = sanitize_text_field( $riga['etichetta'] ?? '' );
				$url       = esc_url_raw( $riga['url'] ?? '' );

				if ( '' === $url ) {
					continue;
				}
				$pagine_pulite[] = [ 'etichetta' => $etichetta, 'url' => $url ];
			}
			Sabriel_Base::update( 'pagine_link', $pagine_pulite );

			Sabriel_Base::update( 'elimina_dati_alla_disinstallazione', isset( $_POST['elimina_dati_alla_disinstallazione'] ) );
			Sabriel_Base::update( 'statistiche_attive', isset( $_POST['statistiche_attive'] ) );

			foreach ( [ 'limite_msg_giornalieri' ] as $chiave_limite ) {
				$sab_limite_grezzo = wp_unslash( $_POST[ $chiave_limite ] ?? '' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- ridotto alle sole cifre nella riga successiva.
				$valore_limite     = is_scalar( $sab_limite_grezzo ) ? (int) preg_replace( '/[^0-9]/', '', (string) $sab_limite_grezzo ) : 0;
				Sabriel_Base::update( $chiave_limite, $valore_limite > 0 ? $valore_limite : '' );
			}

			$msg = __( 'Settings saved.', 'sabriel-ai' );
		}

		$sab_schede_valide = [ 'generali', 'listino', 'pagine', 'comportamento', 'moduli' ];
		$tab_attivo         = 'generali';
		if ( Sabriel_Helpers::e_una_post() && isset( $_POST['sab_settings_nonce'] ) ) {
			$tab_da_post = sanitize_text_field( wp_unslash( $_POST['sab_tab_attivo'] ?? '' ) );
			if ( in_array( $tab_da_post, $sab_schede_valide, true ) ) {
				$tab_attivo = $tab_da_post;
			}
		}
		$tab_da_url = sanitize_text_field( wp_unslash( $_GET['tab'] ?? '' ) );
		if ( in_array( $tab_da_url, $sab_schede_valide, true ) ) {
			$tab_attivo = $tab_da_url;
		}

		$campi = [
			'business_name'   => [ __( 'Business name', 'sabriel-ai' ), 'text' ],
			'founder_name'    => [ __( 'Owner\'s name (optional: used by the bot when talking about who founded the business)', 'sabriel-ai' ), 'text' ],
			'tagline'         => [ __( 'Motto / tagline (optional)', 'sabriel-ai' ), 'text' ],
			'support_email'   => [ __( 'Support email', 'sabriel-ai' ), 'email' ],
			'phone_display'   => [ __( 'Phone (shown in full, the way you\'d write it on a business card)', 'sabriel-ai' ), 'text' ],
			'whatsapp_number' => [ __( 'WhatsApp number (digits only, with your country\'s international prefix and without the + sign)', 'sabriel-ai' ), 'text' ],
			'website_url'     => [ __( 'Website', 'sabriel-ai' ), 'url' ],
			'address'         => [ __( 'Address (optional)', 'sabriel-ai' ), 'text' ],
			'piva'            => [ __( 'VAT number (optional)', 'sabriel-ai' ), 'text' ],
			'since_year'      => [ __( 'Year founded (optional)', 'sabriel-ai' ), 'text' ],
			'service_area'    => [ __( 'Service area (optional: the area you cover, or "remote" if it doesn\'t matter)', 'sabriel-ai' ), 'text' ],
		];
		$sab_valuta_pannello = self::valuta();
		$sab_simbolo_pannello = $sab_valuta_pannello['simbolo'];
		$listino_righe = self::get( 'listino_servizi' );
		if ( is_string( $listino_righe ) ) {
			$listino_righe = [];
		}
		$pagine_righe = self::get( 'pagine_link' );
		if ( is_string( $pagine_righe ) ) {
			$pagine_righe = [];
		}

		if ( empty( $pagine_righe ) ) {
			$pagine_righe = [

				[ 'etichetta' => 'portfolio', 'url' => '' ],
				[ 'etichetta' => 'prodotti', 'url' => '' ],
				[ 'etichetta' => 'articoli', 'url' => '' ],
			];
		}
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Settings', 'sabriel-ai' ); ?></h1>
			<p style="color:#666;max-width:680px"><?php esc_html_e( 'This data replaces what used to be hardcoded: the email/phone in notifications, the WhatsApp links in the widget, and the identity and price list the bot uses in chat. Fill it in with YOUR business\'s details: as soon as it\'s installed the plugin knows nothing about any specific company, you\'re the one who teaches it from here.', '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:680px"><?php echo esc_html( $msg ); ?></div>
			<?php endif; ?>

			<?php

			$sab_avvisi_orari = isset( $sab_orari_errori ) ? $sab_orari_errori : [];
			if ( $sab_avvisi_orari ) :
			?>
				<div style="background:#fffbeb;border:1.5px solid #f59e0b;color:#92400e;padding:12px 18px;border-radius:8px;margin:16px 0;max-width:680px">
					<strong><?php esc_html_e( 'Some times were not saved:', 'sabriel-ai' ); ?></strong>
					<ul style="margin:8px 0 0;padding-left:18px">
						<?php foreach ( $sab_avvisi_orari as $sab_avviso ) : ?>
							<li style="margin:2px 0"><?php echo esc_html( $sab_avviso ); ?></li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>

			<?php

			$sab_note_orari = isset( $sab_orari_note ) ? $sab_orari_note : [];
			if ( $sab_note_orari ) :
			?>
				<div style="background:#eff6ff;border:1.5px solid #93c5fd;color:#1e3a5f;padding:12px 18px;border-radius:8px;margin:16px 0;max-width:680px">
					<strong><?php esc_html_e( 'Overnight shifts sorted out:', 'sabriel-ai' ); ?></strong>
					<ul style="margin:8px 0 0;padding-left:18px">
						<?php foreach ( $sab_note_orari as $sab_nota ) : ?>
							<li style="margin:2px 0"><?php echo esc_html( $sab_nota ); ?></li>
						<?php endforeach; ?>
					</ul>
				</div>
			<?php endif; ?>

			<div style="max-width:680px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:16px 18px;margin-top:16px">
				<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap">
					<div>
						<strong style="font-size:13px"><?php esc_html_e( 'Sync from the site', 'sabriel-ai' ); ?></strong>
						<p style="color:#666;font-size:12px;margin:3px 0 0"><?php esc_html_e( 'Reads real data already present on your WordPress site (name, website, email, published pages) and suggests it to you: you choose what to accept, nothing is saved without your confirmation.', 'sabriel-ai' ); ?></p>
					</div>
					<button type="button" id="sab-sync-sito-btn" class="button" style="white-space:nowrap"><?php esc_html_e( '🔄 Sync from the site', 'sabriel-ai' ); ?></button>
				</div>
				<input type="hidden" id="sab-sync-nonce" value="<?php echo esc_attr( wp_create_nonce( 'sab_sync_sito' ) ); ?>">
				<div id="sab-sync-risultato" style="margin-top:14px"></div>
			</div>

			<form method="post" id="sab-settings-form" style="max-width:680px;background:#fff;border:1px solid #e5e5e5;border-radius:10px;padding:24px;margin-top:16px">
				<?php echo self::stile_interruttori(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>
				<?php wp_nonce_field( 'sab_settings_action', 'sab_settings_nonce' ); ?>
				<input type="hidden" name="sab_tab_attivo" id="sab-tab-attivo-input" value="<?php echo esc_attr( $tab_attivo ); ?>">

				<div style="display:flex;gap:4px;background:#f5f5f5;border-radius:9px;padding:4px;margin-bottom:22px">
					<button type="button" class="sab-stab-btn" data-stab="generali" style="flex:1;border:none;padding:9px 4px;border-radius:6px;font-size:12.5px;font-weight:600;cursor:pointer;<?php echo 'generali' === $tab_attivo ? 'background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15);color:#111' : 'background:transparent;color:#666'; ?>"><?php esc_html_e( 'General', 'sabriel-ai' ); ?></button>
					<button type="button" class="sab-stab-btn" data-stab="listino" style="flex:1;border:none;padding:9px 4px;border-radius:6px;font-size:12.5px;font-weight:600;cursor:pointer;<?php echo 'listino' === $tab_attivo ? 'background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15);color:#111' : 'background:transparent;color:#666'; ?>"><?php esc_html_e( 'Price list', 'sabriel-ai' ); ?></button>
					<button type="button" class="sab-stab-btn" data-stab="pagine" style="flex:1;border:none;padding:9px 4px;border-radius:6px;font-size:12.5px;font-weight:600;cursor:pointer;<?php echo 'pagine' === $tab_attivo ? 'background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15);color:#111' : 'background:transparent;color:#666'; ?>"><?php esc_html_e( 'Page links', 'sabriel-ai' ); ?></button>
				<button type="button" class="sab-stab-btn" data-stab="comportamento" style="flex:1;border:none;padding:9px 4px;border-radius:6px;font-size:12.5px;font-weight:600;cursor:pointer;<?php echo 'comportamento' === $tab_attivo ? 'background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15);color:#111' : 'background:transparent;color:#666'; ?>"><?php esc_html_e( 'Behavior', 'sabriel-ai' ); ?></button>
				<button type="button" class="sab-stab-btn" data-stab="moduli" style="flex:1;border:none;padding:9px 4px;border-radius:6px;font-size:12.5px;font-weight:600;cursor:pointer;<?php echo 'moduli' === $tab_attivo ? 'background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.15);color:#111' : 'background:transparent;color:#666'; ?>"><?php esc_html_e( 'Limits', 'sabriel-ai' ); ?></button>
				</div>

				<div data-stab-panel="generali" style="<?php echo 'generali' === $tab_attivo ? '' : 'display:none'; ?>">
				<h2 style="font-size:14px;margin:0 0 12px"><?php esc_html_e( 'Identity and contacts', 'sabriel-ai' ); ?></h2>
				<?php foreach ( $campi as $key => $info ) : list( $label, $type ) = $info; ?>
					<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="<?php echo esc_attr( $type ); ?>" name="<?php echo esc_attr( $key ); ?>" value="<?php echo esc_attr( self::get( $key ) ); ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					</div>
				<?php endforeach; ?>
				<div style="border-top:1px solid #eee;padding-top:16px;margin-top:4px">
					<?php echo $this->render_selettore_lingua_pannello( 'set-' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>
				</div>
				</div>

				<div data-stab-panel="listino" style="<?php echo 'listino' === $tab_attivo ? '' : 'display:none'; ?>">
				<h2 style="font-size:14px;margin:0 0 6px"><?php esc_html_e( 'Price list', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php echo esc_html( sprintf(
						/* translators: 1: example service name; 2: example price in the configured currency; 3: example description */
						__( 'One line for every service or product you want the bot to know about. The name and the price are always needed, the description is optional but it helps the bot explain better what\'s included. Example: Name "%1$s", Price "%2$s", Description "%3$s". The clearer the description, the better the bot answers customers.', 'sabriel-ai' ),
						__( 'Service name', 'sabriel-ai' ),
						self::con_valuta( '800' ),
						__( 'what\'s included in the price', 'sabriel-ai' )
					) ); ?></p>
				<div id="sab-listino-righe">
					<?php foreach ( $listino_righe as $i => $r ) : ?>
					<div class="sab-listino-riga" style="display:grid;grid-template-columns:1fr 1fr 1.4fr auto;gap:8px;margin-bottom:8px;align-items:start">
						<input type="text" name="listino[<?php echo (int) $i; ?>][nome]" value="<?php echo esc_attr( $r['nome'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'Service name', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="text" name="listino[<?php echo (int) $i; ?>][prezzo]" value="<?php echo esc_attr( $r['prezzo'] ?? '' ); ?>" placeholder="<?php echo esc_attr( sprintf(
						/* translators: %1$s: an example amount in the currency configured by the site owner */
						__( 'E.g. %1$s or from %1$s', 'sabriel-ai' ), self::con_valuta( '200' ) ) ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="text" name="listino[<?php echo (int) $i; ?>][descrizione]" value="<?php echo esc_attr( $r['descrizione'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'E.g. what\'s included, duration, quantity', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<button type="button" class="sab-riga-rimuovi" title="<?php esc_attr_e( 'Remove this row', 'sabriel-ai' ); ?>" style="width:34px;height:34px;border:none;border-radius:50%;background:#f2f2f2;color:#999;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s;flex-shrink:0" onmouseover="this.style.background='#fee2e2';this.style.color='#b91c1c'" onmouseout="this.style.background='#f2f2f2';this.style.color='#999'">✕</button>
					</div>
					<?php endforeach; ?>
				</div>
				<button type="button" id="sab-listino-aggiungi" class="button" style="margin-bottom:6px">+ <?php esc_html_e( 'Add service', 'sabriel-ai' ); ?></button>
				<template id="sab-listino-template">
					<div class="sab-listino-riga" style="display:grid;grid-template-columns:1fr 1fr 1.4fr auto;gap:8px;margin-bottom:8px;align-items:start">
						<input type="text" name="listino[__I__][nome]" placeholder="<?php esc_attr_e( 'Service name', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="text" name="listino[__I__][prezzo]" placeholder="<?php echo esc_attr( sprintf(
						/* translators: %1$s: an example amount in the currency configured by the site owner */
						__( 'E.g. %1$s or from %1$s', 'sabriel-ai' ), self::con_valuta( '200' ) ) ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="text" name="listino[__I__][descrizione]" placeholder="<?php esc_attr_e( 'E.g. what\'s included, duration, quantity', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<button type="button" class="sab-riga-rimuovi" title="<?php esc_attr_e( 'Remove this row', 'sabriel-ai' ); ?>" style="width:34px;height:34px;border:none;border-radius:50%;background:#f2f2f2;color:#999;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s;flex-shrink:0" onmouseover="this.style.background='#fee2e2';this.style.color='#b91c1c'" onmouseout="this.style.background='#f2f2f2';this.style.color='#999'">✕</button>
					</div>
				</template>
				</div>

				<div data-stab-panel="pagine" style="<?php echo 'pagine' === $tab_attivo ? '' : 'display:none'; ?>">
				<h2 style="font-size:14px;margin:0 0 6px"><?php esc_html_e( 'Links to site pages', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'The pages the bot can share in chat when it\'s useful. The label is only to recognize them here (e.g. "faq", "portfolio"), the customer in chat always sees a normal clickable link.', 'sabriel-ai' ); ?></p>
				<div id="sab-pagine-righe">
					<?php foreach ( $pagine_righe as $i => $r ) : ?>
					<div class="sab-pagine-riga" style="display:grid;grid-template-columns:0.7fr 2fr auto;gap:8px;margin-bottom:8px;align-items:start">
						<input type="text" name="pagine[<?php echo (int) $i; ?>][etichetta]" value="<?php echo esc_attr( $r['etichetta'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'Label', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="url" name="pagine[<?php echo (int) $i; ?>][url]" value="<?php echo esc_attr( $r['url'] ?? '' ); ?>" placeholder="https://" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<button type="button" class="sab-riga-rimuovi" title="<?php esc_attr_e( 'Remove this row', 'sabriel-ai' ); ?>" style="width:34px;height:34px;border:none;border-radius:50%;background:#f2f2f2;color:#999;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s;flex-shrink:0" onmouseover="this.style.background='#fee2e2';this.style.color='#b91c1c'" onmouseout="this.style.background='#f2f2f2';this.style.color='#999'">✕</button>
					</div>
					<?php endforeach; ?>
				</div>
				<button type="button" id="sab-pagine-aggiungi" class="button" style="margin-bottom:20px">+ <?php esc_html_e( 'Add page', 'sabriel-ai' ); ?></button>
				<template id="sab-pagine-template">
					<div class="sab-pagine-riga" style="display:grid;grid-template-columns:0.7fr 2fr auto;gap:8px;margin-bottom:8px;align-items:start">
						<input type="text" name="pagine[__I__][etichetta]" placeholder="<?php esc_attr_e( 'Label', 'sabriel-ai' ); ?>" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<input type="url" name="pagine[__I__][url]" placeholder="https://" style="padding:8px 9px;border:1px solid #ccc;border-radius:6px;font-size:12.5px">
						<button type="button" class="sab-riga-rimuovi" title="<?php esc_attr_e( 'Remove this row', 'sabriel-ai' ); ?>" style="width:34px;height:34px;border:none;border-radius:50%;background:#f2f2f2;color:#999;cursor:pointer;font-size:14px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s;flex-shrink:0" onmouseover="this.style.background='#fee2e2';this.style.color='#b91c1c'" onmouseout="this.style.background='#f2f2f2';this.style.color='#999'">✕</button>
					</div>
				</template>

				<?php

				?>
				</div>

				<div data-stab-panel="comportamento" style="<?php echo 'comportamento' === $tab_attivo ? '' : 'display:none'; ?>">
				<h2 style="font-size:14px;margin:0 0 6px"><?php esc_html_e( 'Type of business', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 10px"><?php esc_html_e( 'In one sentence, describe your business: the bot uses it to understand your industry and introduce itself accordingly. E.g.: «Dental practice in Milan, implantology and orthodontics» or «Seafood restaurant on the Bari seafront». If you leave it empty, the bot simply introduces itself as your business\'s assistant.', 'sabriel-ai' ); ?></p>
				<input type="text" name="descrizione_attivita" maxlength="200" placeholder="<?php esc_attr_e( 'E.g. Dental practice in Milan, implantology and orthodontics', 'sabriel-ai' ); ?>" style="width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box;font-size:13px;margin-bottom:22px" value="<?php echo esc_attr( self::get( 'descrizione_attivita' ) ); ?>">

				<h2 style="font-size:14px;margin:0 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Bot behavior and tone', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 14px"><?php esc_html_e( 'Name, price list and links (on the other tabs) tell the bot WHAT to sell. Here you write HOW it should talk and behave: how formal or informal, what to emphasize, phrases to avoid or use, how to handle requests specific to your field. Write it as you\'d explain it to a new hire on their first day: plain sentences, no need for technical language.', 'sabriel-ai' ); ?></p>
				<p style="color:#666;font-size:12px;margin:0 0 8px"><?php esc_html_e( 'Not sure where to start? Choose the business type closest to yours: it fills the field with a starting point you can edit however you like.', 'sabriel-ai' ); ?></p>
				<div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:14px">
					<?php foreach ( self::preset_comportamento() as $chiave => $preset ) : ?>
						<button type="button" class="button sab-preset-comportamento-btn" data-testo="<?php echo esc_attr( $preset['testo'] ); ?>" style="font-size:12px"><?php echo esc_html( $preset['etichetta'] ); ?></button>
					<?php endforeach; ?>
				</div>
				<textarea name="comportamento_tono" rows="8" maxlength="4000" placeholder="<?php esc_attr_e( "E.g. Reply warmly and reassuringly, many customers write worried. Never use the word \"problem\", always say \"situation\". If they ask for an urgent appointment, invite them to call directly...", 'sabriel-ai' ); ?>" style="width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box;font-size:13px;line-height:1.5;resize:vertical" id="sab-comportamento-textarea"><?php echo esc_textarea( self::get( 'comportamento_tono' ) ); ?></textarea>
				<script>
				(function(){
					var textarea = document.getElementById('sab-comportamento-textarea');
					document.querySelectorAll('.sab-preset-comportamento-btn').forEach(function(btn){
						btn.addEventListener('click', function(){
							if(textarea.value.trim() !== ''){
								if(!confirm(<?php echo wp_json_encode( __( 'This replaces the text already written below. Continue?', 'sabriel-ai' ) ); ?>)) return;
							}
							textarea.value = btn.dataset.testo;
						});
					});
				})();
				</script>

				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Bot language', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'Which language the bot speaks to customers in the chat. This is separate from the language of this panel, which you choose in the «General» tab above: changing one never affects the other.', 'sabriel-ai' ); ?></p>
				<div style="display:flex;align-items:center;gap:8px;max-width:280px">
					<span id="sab-botlingua-bandiera" style="flex-shrink:0;line-height:0"><?php echo Sabriel_Base::bandiera_svg( self::bot_lingua_con_rilevamento() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
					<select name="bot_lingua" id="sab-botlingua-select" style="flex:1;width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
						<?php
						$lingue_impostazioni = self::lingue_etichette();
						$lingua_attuale_impostazioni = self::bot_lingua_con_rilevamento();
						foreach ( $lingue_impostazioni as $codice => $etichetta ) :
						?>
							<option value="<?php echo esc_attr( $codice ); ?>" <?php selected( $lingua_attuale_impostazioni, $codice ); ?>><?php echo esc_html( $etichetta ); ?></option>
						<?php endforeach; ?>
					</select>
				</div>
				<script>
				(function(){
					var mappaB = {
						<?php foreach ( array_keys( $lingue_impostazioni ) as $cod ) : ?>
						'<?php echo esc_js( $cod ); ?>': <?php echo wp_json_encode( Sabriel_Base::bandiera_svg( $cod ) ); ?>,
						<?php endforeach; ?>
					};
					var b = document.getElementById('sab-botlingua-bandiera'), s = document.getElementById('sab-botlingua-select');
					if (b && s) { s.addEventListener('change', function(){ if (mappaB[s.value]) b.innerHTML = mappaB[s.value]; }); }
				})();
				</script>
				<p style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a5f;font-size:11.5px;padding:9px 12px;border-radius:8px;margin:8px 0 0;max-width:520px;line-height:1.5"><?php esc_html_e( 'These 9 languages aren\'t a technical limit: the AI engine behind the bot (Gemini, ChatGPT or Claude, whichever you chose in AI Engine) can actually write in many more. These are just the languages this page offers a ready-made label and a pre-tuned tone for: the bot can still try to reply in other languages if a customer uses one.', 'sabriel-ai' ); ?></p>
				<?php echo $this->render_interruttore_lingua_bot( 'set-' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML costruito nel plugin: le parti variabili sono gia' protette dentro il metodo. ?>

				<?php

				$sab_giorni_nomi  = self::giorni_settimana();
				$sab_orari_attuali = Sabriel_Orari::orari_configurati();
				?>
				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Opening hours', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'They let the bot say in chat whether you are open right now and when you reopen. Leave a day as "closed" if you do not work that day.', 'sabriel-ai' ); ?></p>
				<style>
				.sab-giorno-orari .sab-fascia{display:flex;align-items:center;gap:8px}
				.sab-giorno-orari .sab-fascia-time{flex:1 1 0;min-width:0;box-sizing:border-box;padding:8px 10px;border:1px solid #ccc;border-radius:6px;font-size:13px;background:#fff}
				.sab-giorno-orari .sab-fascia-time:focus{border-color:#1461CC;outline:none;box-shadow:0 0 0 2px rgba(20,97,204,.12)}
				.sab-giorno-orari .sab-fascia-sep{flex:0 0 auto;color:#999;font-size:12px}
				.sab-giorno-orari .sab-fascia-rimuovi{flex:0 0 auto;border:none;background:none;color:#c33;font-size:16px;cursor:pointer;line-height:1;padding:2px 6px}
				.sab-giorno-orari .sab-fascia-aggiungi{width:100%;box-sizing:border-box;margin-top:8px;border:1px dashed #bbb;background:#fff;color:#555;font-size:12px;border-radius:6px;padding:7px 12px;cursor:pointer}
				.sab-giorno-orari .sab-fascia-aggiungi:hover{border-color:#1461CC;color:#1461CC}
				@media (max-width:600px){.sab-giorno-orari .sab-fascia{flex-wrap:wrap}.sab-giorno-orari .sab-fascia-time{flex:1 1 120px}}
				</style>
				<div style="display:flex;flex-direction:column;gap:8px">
					<?php foreach ( $sab_giorni_nomi as $sab_dow => $sab_nome_giorno ) :
						$sab_g     = Sabriel_Orari::orari_del_giorno( $sab_dow );
						$sab_fasce = ! empty( $sab_g['fasce'] ) ? $sab_g['fasce'] : [ [ 'dalle' => '', 'alle' => '' ] ];
					?>
					<div class="sab-giorno-orari" data-dow="<?php echo (int) $sab_dow; ?>" style="padding:10px 12px;background:#fafafa;border-radius:8px;border:1px solid #eee">
						<div style="display:flex;align-items:center;gap:10px;margin-bottom:8px">
							<span style="font-size:13px;font-weight:600;width:92px"><?php echo esc_html( $sab_nome_giorno ); ?></span>
							<label style="display:flex;align-items:center;gap:6px;font-size:12px;color:#666">
								<input type="checkbox" class="sab-orario-aperto" name="orari_apertura[<?php echo (int) $sab_dow; ?>][aperto]" value="1" <?php checked( ! empty( $sab_g['aperto'] ) ); ?>>
								<?php esc_html_e( 'Open', 'sabriel-ai' ); ?>
							</label>
						</div>
						<div class="sab-fasce" style="display:flex;flex-direction:column;gap:6px;<?php echo empty( $sab_g['aperto'] ) ? 'opacity:.45' : ''; ?>">
							<?php foreach ( $sab_fasce as $sab_i => $sab_f ) : ?>
							<div class="sab-fascia">
								<input type="time" name="orari_apertura[<?php echo (int) $sab_dow; ?>][fasce][<?php echo (int) $sab_i; ?>][dalle]" value="<?php echo esc_attr( $sab_f['dalle'] ); ?>" class="sab-fascia-time" aria-label="<?php esc_attr_e( 'Opening time', 'sabriel-ai' ); ?>">
								<span class="sab-fascia-sep">→</span>
								<input type="time" name="orari_apertura[<?php echo (int) $sab_dow; ?>][fasce][<?php echo (int) $sab_i; ?>][alle]" value="<?php echo esc_attr( $sab_f['alle'] ); ?>" class="sab-fascia-time" aria-label="<?php esc_attr_e( 'Closing time', 'sabriel-ai' ); ?>">
								<button type="button" class="sab-fascia-rimuovi" title="<?php esc_attr_e( 'Remove time range', 'sabriel-ai' ); ?>">&times;</button>
							</div>
							<?php endforeach; ?>
						</div>
						<button type="button" class="sab-fascia-aggiungi">+ <?php esc_html_e( 'Add time range', 'sabriel-ai' ); ?></button>
					</div>
					<?php endforeach; ?>
				</div>
				<p style="color:#999;font-size:11.5px;margin-top:8px"><?php esc_html_e( 'You can add more than one slot for the same day (e.g. lunch and dinner). If a slot ends earlier than it starts, it is taken to cross midnight (e.g. Friday 19:00 → 02:00): on saving we split it between the two days ourselves, Friday until 00:00 and Saturday from 00:00, so that at one in the morning the assistant knows you are still open, because that hour already belongs to Saturday. To close exactly at midnight, put 00:00.', 'sabriel-ai' ); ?></p>
				<script>
				(function(){

					var etichettaDalle   = <?php echo wp_json_encode( esc_attr__( 'Opening time', 'sabriel-ai' ) ); ?>;
					var etichettaAlle    = <?php echo wp_json_encode( esc_attr__( 'Closing time', 'sabriel-ai' ) ); ?>;
					var etichettaRimuovi = <?php echo wp_json_encode( esc_attr__( 'Remove time range', 'sabriel-ai' ) ); ?>;
					function aggiornaStato(giorno){
						var cb = giorno.querySelector(".sab-orario-aperto");
						var on = cb && cb.checked;
						var fasce = giorno.querySelector(".sab-fasce");
						if (fasce) fasce.style.opacity = on ? "1" : ".45";
						giorno.querySelectorAll(".sab-fascia-aggiungi").forEach(function(b){ b.style.opacity = on ? "1" : ".5"; });
					}
					function nuovoIndice(giorno){
						var max = 0;
						giorno.querySelectorAll(".sab-fascia-time").forEach(function(t){
							var m = t.name.match(/\[fasce\]\[(\d+)\]/);
							if (m) { var n = parseInt(m[1],10); if (n >= max) max = n + 1; }
						});
						return max;
					}
					document.querySelectorAll(".sab-giorno-orari").forEach(function(giorno){
						var dow = giorno.getAttribute("data-dow");
						var cb = giorno.querySelector(".sab-orario-aperto");
						if (cb) cb.addEventListener("change", function(){ aggiornaStato(giorno); });
						giorno.addEventListener("click", function(e){
							var add = e.target.closest(".sab-fascia-aggiungi");
							var rem = e.target.closest(".sab-fascia-rimuovi");
							if (add) {
								e.preventDefault();
								if (add.disabled) return;
								var cont = giorno.querySelector(".sab-fasce");
								var idx = nuovoIndice(giorno);
								var div = document.createElement("div");
								div.className = "sab-fascia";

								div.innerHTML = '<input type="time" name="orari_apertura['+dow+'][fasce]['+idx+'][dalle]" class="sab-fascia-time" aria-label="'+etichettaDalle+'">'
									+ '<span class="sab-fascia-sep">→</span>'
									+ '<input type="time" name="orari_apertura['+dow+'][fasce]['+idx+'][alle]" class="sab-fascia-time" aria-label="'+etichettaAlle+'">'
									+ '<button type="button" class="sab-fascia-rimuovi" title="'+etichettaRimuovi+'">\u00d7</button>';
								cont.appendChild(div);
							} else if (rem) {
								e.preventDefault();
								if (rem.disabled) return;
								var righe = giorno.querySelectorAll(".sab-fascia");
								if (righe.length > 1) { rem.closest(".sab-fascia").remove(); }
								else { rem.closest(".sab-fascia").querySelectorAll(".sab-fascia-time").forEach(function(t){ t.value=""; }); }
							}
						});
						aggiornaStato(giorno);
					});
				})();
</script>

				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Payment structure', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'How you prefer to be paid for a project. The assistant will use this structure when it talks about it in chat.', 'sabriel-ai' ); ?></p>
				<?php
				$pagamento_struttura = self::get( 'pagamento_struttura' ) ?: 'non_applicabile';
				$pagamento_opzioni = [
					'non_applicabile' => __( 'Doesn\'t apply to my business (e.g. e-commerce with direct payment)', 'sabriel-ai' ),
					'consegna'      => __( '100% on delivery of the completed project', 'sabriel-ai' ),
					'50_50'         => __( '50% deposit + 50% on delivery', 'sabriel-ai' ),
					'25_25_50'      => __( '25% deposit + 25% at the midpoint + 50% on delivery', 'sabriel-ai' ),
					'personalizzato' => __( 'Custom', 'sabriel-ai' ),
				];
				foreach ( $pagamento_opzioni as $val => $etichetta ) :
				?>
					<label style="display:flex;align-items:center;gap:8px;margin-bottom:8px;font-size:13px">
						<input type="radio" name="pagamento_struttura" class="sab-pagamento-radio" value="<?php echo esc_attr( $val ); ?>" <?php checked( $pagamento_struttura, $val ); ?>>
						<?php echo esc_html( $etichetta ); ?>
					</label>
				<?php endforeach; ?>
				<div id="sab-pagamento-personalizzato-wrap" style="display:<?php echo 'personalizzato' === $pagamento_struttura ? 'grid' : 'none'; ?>;grid-template-columns:1fr 1fr 1fr;grid-template-rows:auto auto;column-gap:14px;row-gap:4px;margin:8px 0 4px 26px;max-width:400px;align-items:end">
					<label style="font-weight:600;font-size:12.5px;grid-column:1;grid-row:1"><?php esc_html_e( '% deposit', 'sabriel-ai' ); ?></label>
					<label style="font-weight:600;font-size:12.5px;grid-column:2;grid-row:1"><?php esc_html_e( '% at the midpoint (optional)', 'sabriel-ai' ); ?></label>
					<label style="font-weight:600;font-size:12.5px;grid-column:3;grid-row:1"><?php esc_html_e( '% on delivery', 'sabriel-ai' ); ?></label>
					<input type="text" inputmode="numeric" name="pagamento_acconto_pct" id="sab-pagamento-acconto" value="<?php echo esc_attr( self::get( 'pagamento_acconto_pct' ) ); ?>" style="grid-column:1;grid-row:2;width:100%;padding:7px 9px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					<input type="text" inputmode="numeric" name="pagamento_meta_pct" id="sab-pagamento-meta" value="<?php echo esc_attr( self::get( 'pagamento_meta_pct' ) ); ?>" style="grid-column:2;grid-row:2;width:100%;padding:7px 9px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					<div id="sab-pagamento-consegna-calc" style="grid-column:3;grid-row:2;padding:7px 9px;color:#666;font-size:13px">—</div>
				</div>
				<script>
				(function(){
					var wrap = document.getElementById('sab-pagamento-personalizzato-wrap');
					var mostraWrap = function(mostra){ wrap.style.display = mostra ? 'grid' : 'none'; };
					var acconto = document.getElementById('sab-pagamento-acconto');
					var meta = document.getElementById('sab-pagamento-meta');
					var calc = document.getElementById('sab-pagamento-consegna-calc');
					function aggiornaConsegna(){
						var a = parseInt(acconto.value,10)||0, m = parseInt(meta.value,10)||0;
						var c = 100 - a - m;
						calc.textContent = (c<0 ? 0 : c) + '%';
					}
					var personalizzatoRadio = document.querySelector('.sab-pagamento-radio[value="personalizzato"]');
					var radios = document.querySelectorAll('.sab-pagamento-radio');
					radios.forEach(function(r){
						r.addEventListener('change', function(){
							mostraWrap(personalizzatoRadio.checked);
						});
					});
					if(acconto){ acconto.addEventListener('input', aggiornaConsegna); meta.addEventListener('input', aggiornaConsegna); aggiornaConsegna(); }
				})();
				</script>

				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Installment payment', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'If enabled, the bot offers installment payment to customers whose project exceeds the threshold you set below. If disabled, the bot clearly says installments aren\'t available if someone asks: never a made-up threshold.', 'sabriel-ai' ); ?></p>
				<label class="sab-toggle-row" style="max-width:400px">
					<span class="sab-toggle-text"><?php esc_html_e( 'Offer installment payment', 'sabriel-ai' ); ?></span>
					<span class="sab-toggle">
						<input type="checkbox" name="rate_abilitate" id="sab-rate-abilitate" value="1" <?php checked( self::get( 'rate_abilitate' ) ); ?>>
						<span class="sab-toggle-slider"></span>
					</span>
				</label>
				<div id="sab-rate-soglia-wrap" style="max-width:280px;<?php echo self::get( 'rate_abilitate' ) ? '' : 'opacity:.45'; ?>">
					<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php echo esc_html( sprintf(
						/* translators: %s: the currency symbol configured by the site owner */
						__( 'Minimum threshold to access instalments (%s)', 'sabriel-ai' ), $sab_simbolo_pannello ) ); ?></label>
					<input type="text" inputmode="numeric" name="rate_soglia" id="sab-rate-soglia" value="<?php echo esc_attr( self::get( 'rate_soglia' ) ); ?>" placeholder="<?php esc_attr_e( 'E.g. 850', 'sabriel-ai' ); ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box"<?php echo self::get( 'rate_abilitate' ) ? '' : ' readonly'; ?>>
				</div>

				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Allowed topics', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'By default the bot always stays focused on your services: it politely refuses questions unrelated to the work (general knowledge, homework, off-topic requests) and never reveals what technology it\'s built on, only its name. This is the right choice for nearly all businesses. Turn this option on only if you really want a more permissive bot, capable of chatting about topics unrelated to work too.', 'sabriel-ai' ); ?></p>
				<label class="sab-toggle-row" style="max-width:500px">
					<span class="sab-toggle-text"><?php esc_html_e( 'Allow off-topic conversations', 'sabriel-ai' ); ?><span class="sab-toggle-desc"><?php esc_html_e( 'Off (recommended): the bot always stays focused on work. On: the bot can also answer generic questions or chat unrelated to the services.', 'sabriel-ai' ); ?></span></span>
					<span class="sab-toggle">
						<input type="checkbox" name="permetti_fuori_tema" id="sab-permetti-fuori-tema" value="1" <?php checked( self::get( 'permetti_fuori_tema' ) ); ?>>
						<span class="sab-toggle-slider"></span>
					</span>
				</label>

				<h2 style="font-size:14px;margin:22px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'VAT on prices', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 12px"><?php esc_html_e( 'How to treat VAT in the prices the assistant states in chat. Choose your country and we will fill in the rate.', 'sabriel-ai' ); ?></p>

				<?php $sab_regime_iva = self::get( 'prezzi_regime_iva' ); ?>
				<div style="max-width:320px;margin-bottom:14px">
					<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'The prices you entered in the price list are…', 'sabriel-ai' ); ?></label>
					<select name="prezzi_regime_iva" id="sab-regime-iva" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
						<option value="esclusa" <?php selected( $sab_regime_iva, 'esclusa' ); ?>><?php esc_html_e( 'VAT excluded: they\'re net amounts', 'sabriel-ai' ); ?></option>
						<option value="inclusa" <?php selected( $sab_regime_iva, 'inclusa' ); ?>><?php esc_html_e( 'VAT included: VAT is already in there', 'sabriel-ai' ); ?></option>
					</select>
					<div id="sab-regime-esclusa-info" style="margin-top:8px<?php echo 'esclusa' === $sab_regime_iva ? '' : ';display:none'; ?>">
						<p style="color:#1e40af;background:#eff6ff;border:1px solid #93c5fd;border-radius:6px;padding:8px 10px;font-size:11.5px;margin:0;line-height:1.5">
							<?php esc_html_e( 'Enter net prices in the price list, as usual. If you pick a country below, the assistant tells customers that the price excludes VAT and states the rate, every single time it quotes a figure: it never leaves it implied.', 'sabriel-ai' ); ?>
						</p>
					</div>
					<div id="sab-regime-inclusa-info" style="margin-top:8px<?php echo 'inclusa' === $sab_regime_iva ? '' : ';display:none'; ?>">
						<p style="color:#1e40af;background:#eff6ff;border:1px solid #93c5fd;border-radius:6px;padding:8px 10px;font-size:11.5px;margin:0;line-height:1.5">
							<?php esc_html_e( 'The prices in your list are already the final ones. The assistant quotes them exactly as you wrote them, adds nothing on top, and if a customer asks whether VAT is included it answers yes. Useful if you sell to consumers.', 'sabriel-ai' ); ?>
						</p>
					</div>
				</div>

				<?php $sab_iva_paese = self::get( 'aliquota_iva_paese' ); ?>
				<div style="max-width:320px">
					<select name="aliquota_iva_paese" id="sab-iva-paese" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
						<option value="" <?php selected( $sab_iva_paese, '' ); ?>><?php esc_html_e( '(Don\'t show the VAT line)', 'sabriel-ai' ); ?></option>
						<?php foreach ( self::iva_paesi_tradotti() as $sab_cod => $sab_dati ) : ?>
							<option value="<?php echo esc_attr( $sab_cod ); ?>" <?php selected( $sab_iva_paese, $sab_cod ); ?>><?php echo esc_html( $sab_dati[0] . ' (' . $sab_dati[1] . '%)' ); ?></option>
						<?php endforeach; ?>
						<option value="nessuna" <?php selected( $sab_iva_paese, 'nessuna' ); ?>><?php esc_html_e( 'United States / no VAT', 'sabriel-ai' ); ?></option>
						<option value="altro" <?php selected( $sab_iva_paese, 'altro' ); ?>><?php esc_html_e( 'Other / custom rate…', 'sabriel-ai' ); ?></option>
					</select>
					<div id="sab-iva-altro-wrap" style="margin-top:10px<?php echo 'altro' === $sab_iva_paese ? '' : ';display:none'; ?>">
						<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Your rate (%)', 'sabriel-ai' ); ?></label>
						<input type="text" inputmode="decimal" name="aliquota_iva_custom" value="<?php echo esc_attr( self::get( 'aliquota_iva' ) ); ?>" placeholder="<?php esc_attr_e( 'e.g. 4', 'sabriel-ai' ); ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					</div>
					<p style="color:#92400e;background:#fffbeb;border:1px solid #f59e0b;border-radius:6px;padding:8px 10px;font-size:11.5px;margin:10px 0 0;line-height:1.5">
						<?php
						printf(

							/* translators: %s: date the tax rates were checked */ esc_html__( 'STANDARD rates, checked on %s, but they change over time, and this list doesn\'t update by itself. If you\'re under a special or flat-rate scheme, apply a reduced rate, or a lot of time has passed since that date, choose "Other" and enter yours. When in doubt, ask your accountant: this line ends up on a document you send to clients.', 'sabriel-ai' ),
							esc_html( date_i18n( get_option( 'date_format' ), strtotime( self::IVA_VERIFICATE_IL ) ) )
						);
						?>
					</p>
				</div>
				<script>
				(function(){
					var sel = document.getElementById('sab-iva-paese');
					var wrap = document.getElementById('sab-iva-altro-wrap');
					if (!sel || !wrap) return;
					sel.addEventListener('change', function(){
						wrap.style.display = (sel.value === 'altro') ? '' : 'none';
					});
				})();
				(function(){
					var sel = document.getElementById('sab-regime-iva');
					var esc = document.getElementById('sab-regime-esclusa-info');
					var inc = document.getElementById('sab-regime-inclusa-info');
					if (!sel || !esc || !inc) return;
					sel.addEventListener('change', function(){
						var e = (sel.value === 'esclusa');
						esc.style.display = e ? '' : 'none';
						inc.style.display = e ? 'none' : '';
					});
				})();
				</script>

				<?php
				$sab_val = self::valuta();
				$sab_val_in_lista = array_key_exists( $sab_val['codice'], self::VALUTE );
				?>
				<h3 style="font-size:15px;margin:26px 0 4px"><?php esc_html_e( 'Currency', 'sabriel-ai' ); ?></h3>
				<p style="color:#888;font-size:12px;margin:0 0 10px;max-width:520px"><?php esc_html_e( 'The currency of the prices the assistant shows to customers. It applies to the whole assistant.', 'sabriel-ai' ); ?></p>
				<div style="max-width:320px">
					<select name="valuta_codice" id="sab-valuta" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
						<?php foreach ( self::valute_tradotte() as $sab_vc => $sab_vd ) : ?>
							<option value="<?php echo esc_attr( $sab_vc ); ?>" <?php selected( $sab_val_in_lista && $sab_val['codice'] === $sab_vc ); ?>><?php echo esc_html( $sab_vd[1] . ' (' . $sab_vd[0] . ')' ); ?></option>
						<?php endforeach; ?>
						<option value="altro" <?php selected( ! $sab_val_in_lista ); ?>><?php esc_html_e( 'Other / custom…', 'sabriel-ai' ); ?></option>
					</select>
					<div id="sab-valuta-altro" style="margin-top:10px;display:flex;gap:8px<?php echo $sab_val_in_lista ? ';display:none' : ''; ?>">
						<input type="text" name="valuta_codice_custom" value="<?php echo esc_attr( ! $sab_val_in_lista ? $sab_val['codice'] : '' ); ?>" placeholder="<?php esc_attr_e( 'Code (e.g. AED)', 'sabriel-ai' ); ?>" maxlength="6" style="flex:1;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box;text-transform:uppercase">
						<input type="text" name="valuta_simbolo_custom" value="<?php echo esc_attr( ! $sab_val_in_lista ? $sab_val['simbolo'] : '' ); ?>" placeholder="<?php esc_attr_e( 'Symbol (e.g. د.إ)', 'sabriel-ai' ); ?>" maxlength="8" style="flex:1;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					</div>
					<label style="font-weight:600;font-size:13px;display:block;margin:14px 0 5px"><?php esc_html_e( 'Symbol position', 'sabriel-ai' ); ?></label>
					<label style="display:inline-flex;align-items:center;gap:6px;margin-right:16px;font-size:13px;cursor:pointer"><input type="radio" name="valuta_posizione" value="dopo" <?php checked( $sab_val['posizione'], 'dopo' ); ?>><?php echo esc_html( sprintf(
					/* translators: %s: example amount with the symbol written AFTER the number */
					__( 'After (%s)', 'sabriel-ai' ), number_format_i18n( 1200 ) . ' ' . $sab_val['simbolo'] ) ); ?></label>
					<label style="display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer"><input type="radio" name="valuta_posizione" value="prima" <?php checked( $sab_val['posizione'], 'prima' ); ?>><?php echo esc_html( sprintf(
					/* translators: %s: example amount with the symbol written BEFORE the number */
					__( 'Before (%s)', 'sabriel-ai' ), $sab_val['simbolo'] . number_format_i18n( 1200 ) ) ); ?></label>
				</div>
				<script>
				(function(){
					var sel = document.getElementById('sab-valuta');
					var box = document.getElementById('sab-valuta-altro');
					if (!sel || !box) return;
					sel.addEventListener('change', function(){ box.style.display = (sel.value === 'altro') ? 'flex' : 'none'; });
				})();
				</script>

				<script>
				(function(){

					var cb = document.getElementById('sab-rate-abilitate');
					var wrap = document.getElementById('sab-rate-soglia-wrap');
					var input = document.getElementById('sab-rate-soglia');
					if(!cb) return;
					cb.addEventListener('change', function(){
						wrap.style.opacity = cb.checked ? '1' : '.45';
						input.readOnly = !cb.checked;
					});
				})();
</script>

				</div>

				<div data-stab-panel="moduli" style="<?php echo 'moduli' === $tab_attivo ? '' : 'display:none'; ?>">
				<?php

				?>

				<h2 style="font-size:14px;margin:26px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Limits', 'sabriel-ai' ); ?></h2>
				<p style="color:#888;font-size:12px;margin:0 0 14px"><?php esc_html_e( 'How many times a visitor can use each feature before the bot gently stops them and suggests direct contact. Empty field = the plugin\'s long-standing default value.', 'sabriel-ai' ); ?></p>
				<div style="display:grid;grid-template-columns:1fr;max-width:320px;gap:14px">
					<div>
						<label style="font-weight:600;font-size:13px;display:block;margin-bottom:5px"><?php esc_html_e( 'Chat messages, every 24 hours', 'sabriel-ai' ); ?></label>
						<input type="text" inputmode="numeric" name="limite_msg_giornalieri" value="<?php echo esc_attr( self::get( 'limite_msg_giornalieri' ) ); ?>" placeholder="<?php echo (int) Sabriel_Module_Chat::RATE_LIMIT_MAX; ?>" style="width:100%;padding:8px 10px;border:1px solid #ccc;border-radius:6px;box-sizing:border-box">
					</div>
					<div>
						<label style="font-weight:600;font-size:13px;display:flex;align-items:flex-start;gap:8px">
							<input type="checkbox" name="statistiche_attive" value="1" <?php checked( (bool) self::get( 'statistiche_attive' ) ); ?> style="margin-top:2px">
							<span><?php esc_html_e( 'Collect visit statistics', 'sabriel-ai' ); ?></span>
						</label>
						<p style="color:#888;font-size:12px;margin:6px 0 0;line-height:1.5"><?php esc_html_e( 'To count returning visitors without cookies, the widget builds a short code from the browser (screen size, language, time zone and similar) and sends it with the page address. Nothing leaves your site and no cookie is written, but in the EU this counts as accessing the device: turn it off if you do not ask for consent. The chat keeps working either way.', 'sabriel-ai' ); ?></p>
					</div>
					<?php

					?>
				</div>

				<?php

				?>

				<h2 style="font-size:14px;margin:26px 0 6px;border-top:1px solid #eee;padding-top:18px"><?php esc_html_e( 'Uninstall', 'sabriel-ai' ); ?></h2>
				<label class="sab-toggle-row">
					<span class="sab-toggle-text"><?php esc_html_e( 'Also delete customer data left over from a previous version', 'sabriel-ai' ); ?><span class="sab-toggle-desc"><?php esc_html_e( 'The configuration (colors, text, price list, everything else) is always removed completely when you uninstall the plugin from WordPress, with no leftovers. This extra switch only decides what happens to REAL customer DATA: off by default so you don\'t lose it by accident if you\'re just uninstalling to update or try something again.', 'sabriel-ai' ); ?></span></span>
					<span class="sab-toggle">
						<input type="checkbox" name="elimina_dati_alla_disinstallazione" value="1" <?php checked( self::get( 'elimina_dati_alla_disinstallazione' ) ); ?>>
						<span class="sab-toggle-slider"></span>
					</span>
				</label>

				</div>

				<div style="margin-top:28px;padding-top:22px;border-top:1px solid #eee">
					<button type="submit" style="background:#1461CC;color:#fff;border:none;padding:11px 26px;border-radius:8px;font-weight:700;cursor:pointer"><?php esc_html_e( 'Save settings', 'sabriel-ai' ); ?></button>
				</div>
			</form>
			<script>
			(function(){
				var tabInput = document.getElementById('sab-tab-attivo-input');
				function attiva(nome){
					document.querySelectorAll('[data-stab-panel]').forEach(function(p){ p.style.display = (p.dataset.stabPanel===nome) ? '' : 'none'; });
					document.querySelectorAll('.sab-stab-btn').forEach(function(b){
						var attivo = b.dataset.stab===nome;
						b.style.background = attivo ? '#fff' : 'transparent';
						b.style.boxShadow = attivo ? '0 1px 3px rgba(0,0,0,.15)' : 'none';
						b.style.color = attivo ? '#111' : '#666';
					});
					if(tabInput) tabInput.value = nome;
				}
				document.querySelectorAll('.sab-stab-btn').forEach(function(b){
					b.addEventListener('click', function(){ attiva(b.dataset.stab); });
				});
			})();
			</script>
		</div>
		<script>
		(function(){
			var contI = <?php echo (int) count( $listino_righe ); ?>;
			var contP = <?php echo (int) count( $pagine_righe ); ?>;
			function aggiungiRiga(contenitoreId, templateId, contatoreIniziale){
				var wrap = document.getElementById(contenitoreId);
				var tpl = document.getElementById(templateId).innerHTML;
				var div = document.createElement('div');
				div.innerHTML = tpl.split('__I__').join(contatoreIniziale);
				wrap.appendChild(div.firstElementChild);
			}
			document.getElementById('sab-listino-aggiungi').addEventListener('click', function(){
				aggiungiRiga('sab-listino-righe', 'sab-listino-template', contI); contI++;
			});
			document.getElementById('sab-pagine-aggiungi').addEventListener('click', function(){
				aggiungiRiga('sab-pagine-righe', 'sab-pagine-template', contP); contP++;
			});
			document.getElementById('sab-settings-form').addEventListener('click', function(e){
				if(e.target.classList.contains('sab-riga-rimuovi')){
					e.target.closest('.sab-listino-riga, .sab-pagine-riga').remove();
				}
			});
			if(<?php echo count( $listino_righe ) ? 'false' : 'true'; ?>) aggiungiRiga('sab-listino-righe','sab-listino-template', contI++);
			if(<?php echo count( $pagine_righe ) ? 'false' : 'true'; ?>) aggiungiRiga('sab-pagine-righe','sab-pagine-template', contP++);

			function escHtml(s){ var d=document.createElement('div'); d.textContent=s||''; return d.innerHTML; }
			function escAttr(s){ return (s||'').replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
			var syncBtn = document.getElementById('sab-sync-sito-btn');
			var syncRisultato = document.getElementById('sab-sync-risultato');
			function mostraSyncRisultato(dati){
				var idKeys = Object.keys(dati.identita||{});
				var pagine = dati.pagine||[];
				if(idKeys.length===0 && pagine.length===0){
					syncRisultato.innerHTML = '<p style="color:#666;font-size:12.5px;margin:0">'+<?php echo wp_json_encode( __( 'I didn\'t find anything new to suggest: you\'ve probably configured everything already, or the site doesn\'t have this information yet.', 'sabriel-ai' ) ); ?>+'</p>';
					return;
				}
				var html = '<div style="background:#fff;border:1px solid #dbe3ea;border-radius:8px;padding:14px">';
				if(idKeys.length){
					html += '<div style="font-weight:600;font-size:12.5px;margin-bottom:8px">'+<?php echo wp_json_encode( __( 'General information', 'sabriel-ai' ) ); ?>+'</div>';
					idKeys.forEach(function(k){
						var info = dati.identita[k];
						var giaPresente = info.attuale && info.attuale.length>0;
						html += '<label style="display:flex;align-items:flex-start;gap:8px;margin-bottom:8px;font-size:12.5px">'
							+'<input type="checkbox" class="sab-sync-id-check" data-campo="'+k+'" data-valore="'+escAttr(info.trovato)+'" '+(giaPresente?'':'checked')+' style="margin-top:3px">'
							+'<span><strong>'+escHtml(info.etichetta)+':</strong> '+escHtml(info.trovato)+(giaPresente?'<br><span style="color:#999">'+<?php echo wp_json_encode( __( 'Current:', 'sabriel-ai' ) ); ?>+' '+escHtml(info.attuale)+'</span>':'')+'</span>'
							+'</label>';
					});
				}
				if(pagine.length){
					html += '<div style="font-weight:600;font-size:12.5px;margin:14px 0 8px;border-top:1px solid #eee;padding-top:12px">'+<?php echo wp_json_encode( __( 'Pages found', 'sabriel-ai' ) ); ?>+'</div>';
					pagine.forEach(function(p){
						html += '<label style="display:flex;align-items:flex-start;gap:8px;margin-bottom:8px;font-size:12.5px">'
							+'<input type="checkbox" class="sab-sync-pagina-check" data-etichetta="'+escAttr(p.etichetta)+'" data-url="'+escAttr(p.url)+'" checked style="margin-top:3px">'
							+'<span><strong>'+escHtml(p.etichetta)+':</strong> "'+escHtml(p.titolo_pagina)+'" (<span style="color:#999">'+escHtml(p.url)+'</span>)</span>'
							+'</label>';
					});
				}
				html += '<div style="margin-top:10px"><button type="button" id="sab-sync-applica" class="button button-primary">'+<?php echo wp_json_encode( __( 'Apply selected', 'sabriel-ai' ) ); ?>+'</button> <button type="button" id="sab-sync-annulla" class="button">'+<?php echo wp_json_encode( __( 'Cancel', 'sabriel-ai' ) ); ?>+'</button></div>';
				html += '</div>';
				syncRisultato.innerHTML = html;
				document.getElementById('sab-sync-annulla').addEventListener('click', function(){ syncRisultato.innerHTML=''; });
				document.getElementById('sab-sync-applica').addEventListener('click', function(){
					document.querySelectorAll('.sab-sync-id-check:checked').forEach(function(cb){
						var input = document.querySelector('#sab-settings-form [name="'+cb.dataset.campo+'"]');
						if(input) input.value = cb.dataset.valore;
					});
					document.querySelectorAll('.sab-sync-pagina-check:checked').forEach(function(cb){
						aggiungiRiga('sab-pagine-righe','sab-pagine-template', contP);
						var righe = document.querySelectorAll('#sab-pagine-righe .sab-pagine-riga');
						var ultima = righe[righe.length-1];
						ultima.querySelector('[name^="pagine"][name$="[etichetta]"]').value = cb.dataset.etichetta;
						ultima.querySelector('[name^="pagine"][name$="[url]"]').value = cb.dataset.url;
						contP++;
					});
					syncRisultato.innerHTML = '<p style="color:#1a7d3a;font-size:12.5px">'+<?php echo wp_json_encode( __( 'Applied: check the values in the fields above before saving.', 'sabriel-ai' ) ); ?>+'</p>';
				});
			}
			if(syncBtn){
				syncBtn.addEventListener('click', function(){
					syncBtn.disabled = true;
					var testoOriginale = syncBtn.textContent;
					syncBtn.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').value);
					fetch(ajaxurl, { method:'POST', body:fd, credentials:'same-origin' })
						.then(function(r){ return r.json(); })
						.then(function(res){
							syncBtn.disabled = false;
							syncBtn.textContent = testoOriginale;
							if(!res.success){
								syncRisultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+<?php echo wp_json_encode( __( 'It wasn\'t possible to read the site right now.', 'sabriel-ai' ) ); ?>+'</p>';
								return;
							}
							mostraSyncRisultato(res.data);
						})
						.catch(function(){
							syncBtn.disabled = false;
							syncBtn.textContent = testoOriginale;
							syncRisultato.innerHTML = '<p style="color:#b91c1c;font-size:12.5px">'+<?php echo wp_json_encode( __( 'Connection error, please try again.', 'sabriel-ai' ) ); ?>+'</p>';
						});
				});
			}
		})();
		</script>
		<?php
	}
}
