<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( class_exists( 'Truebe_Setup' ) ) { return; }

if ( ! defined( 'TRUEBE_CONNECT_URL' ) ) {
	define( 'TRUEBE_CONNECT_URL', 'https://truebe.io/connect' );
}
if ( ! defined( 'TRUEBE_EXCHANGE_URL' ) ) {
	define( 'TRUEBE_EXCHANGE_URL', 'https://truebe.io/api/connect/exchange' );
}
if ( ! defined( 'TRUEBE_FEEDBACK_URL' ) ) {
	define( 'TRUEBE_FEEDBACK_URL', 'https://www.truebe.io/api/feedback' );
}

class Truebe_Setup {

	private static $instance = null;
	private static $providers = array( 'anthropic', 'openai' );

	private static $previous_provider = null;
	private static $known_2fa = array(
		'two-factor/two-factor.php',
		'wp-2fa/wp-2fa.php',
		'wordfence-login-security/wordfence-login-security.php',
		'wordfence/wordfence.php',
		'miniorange-2-factor-authentication/miniorange_2_factor_settings.php',
		'google-authenticator-per-user-prompt/google-authenticator-per-user-prompt.php',
	);

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_init', array( $this, 'maybe_exchange_token' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_truebe_support_submit', array( $this, 'ajax_support_submit' ) );
	}

	public function enqueue_assets( $hook ) {
		if ( false === strpos( (string) $hook, 'truebe' ) ) { return; }
		wp_enqueue_style(
			'truebe-admin',
			plugins_url( '../assets/admin.css', __FILE__ ),
			array(),
			(string) filemtime( plugin_dir_path( __FILE__ ) . '../assets/admin.css' )
		);
		wp_add_inline_style( 'truebe-admin', '.truebe-field:has(#truebe-provider-anthropic:checked) #truebe-key-replace{margin-right:auto;margin-left:0;}.truebe-field:has(#truebe-provider-openai:checked) #truebe-key-replace{margin-left:auto;margin-right:0;}#truebe-key-replace{width:50%;min-width:260px;}.truebe-keyhelp-claude,.truebe-keyhelp-openai{display:none;}.truebe-field:has(#truebe-provider-anthropic:checked) .truebe-keyhelp-claude{display:block;}.truebe-field:has(#truebe-provider-openai:checked) .truebe-keyhelp-openai{display:block;}' );
		wp_enqueue_script(
			'truebe-setup',
			plugins_url( '../assets/setup.js', __FILE__ ),
			array(),
			(string) filemtime( plugin_dir_path( __FILE__ ) . '../assets/setup.js' ),
			true
		);
		wp_localize_script( 'truebe-setup', 'truebeSupport', array(
			'ajax'  => esc_url_raw( admin_url( 'admin-ajax.php' ) ),
			'nonce' => wp_create_nonce( 'truebe_support' ),
		) );
	}

	/** Forward a support message to the truebe.io feedback endpoint. */
	public function ajax_support_submit() {
		if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( 'forbidden', 403 ); }
		check_ajax_referer( 'truebe_support', 'nonce' );
		$message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
		$email   = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
		if ( '' === $message ) { wp_send_json_error( 'empty_message', 400 ); }
		$resp = wp_remote_post( TRUEBE_FEEDBACK_URL, array(
			'timeout' => 15,
			'body'    => array(
				'kind'    => 'support',
				'detail'  => $message,
				'reason'  => $email,
				'site'    => home_url(),
				'version' => defined( 'TRUEBE_VERSION' ) ? TRUEBE_VERSION : '',
			),
		) );
		if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
			wp_send_json_error( 'send_failed', 500 );
		}
		wp_send_json_success();
	}

	public static function mfa_active() {
		if ( ! function_exists( 'is_plugin_active' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		foreach ( self::$known_2fa as $plugin ) {
			if ( is_plugin_active( $plugin ) ) { return true; }
		}
		return false;
	}

	public static function mfa_gate() {
		return (bool) apply_filters( 'truebe_require_mfa', false ) ? self::mfa_active() : true;
	}

	/**
	 * Detects whether WordPress 7.0+ already has a usable AI provider connected
	 * via the native Connectors API (Settings > Connectors).
	 *
	 * @return string|null The connector id ('anthropic' or 'openai') if a provider
	 *                      is registered and configured with a valid key, else null.
	 */
	public static function detect_wp_ai_provider() {
		if ( ! function_exists( 'wp_is_connector_registered' ) || ! class_exists( '\WordPress\AiClient\AiClient' ) ) {
			return null;
		}
		foreach ( self::$providers as $provider_id ) {
			if ( ! wp_is_connector_registered( $provider_id ) ) {
				continue;
			}
			try {
				$ai_registry = \WordPress\AiClient\AiClient::defaultRegistry();
				if ( $ai_registry->hasProvider( $provider_id ) && $ai_registry->isProviderConfigured( $provider_id ) ) {
					return $provider_id;
				}
			} catch ( \Exception $e ) {
				continue;
			}
		}
		return null;
	}

	public function add_menu() {
		add_menu_page(
			__( 'Truebe', 'truebe-fact-based-ai-chatbot' ),
			__( 'Truebe', 'truebe-fact-based-ai-chatbot' ),
			'manage_options',
			'truebe',
			array( $this, 'render_settings_page' ),
			'dashicons-shield-alt',
			81
		);
		add_action( 'admin_menu', array( $this, 'reorder_settings' ), 50 );
	}

	public function reorder_settings() {
		global $submenu;
		if ( empty( $submenu['truebe'] ) ) { return; }
		foreach ( $submenu['truebe'] as $i => $item ) {
			if ( 'truebe' === $item[2] ) {
				$item[0] = __( 'Settings', 'truebe-fact-based-ai-chatbot' );
				unset( $submenu['truebe'][ $i ] );
				$submenu['truebe'][] = $item; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- intentional admin submenu reordering, the WordPress-sanctioned way to move the auto-added top item to the end.
				break;
			}
		}
	}

	public function register_settings() {
		register_setting( 'truebe_settings', 'truebe_business_name', array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => '' ) );
		register_setting( 'truebe_settings', 'truebe_ai_provider',   array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_provider' ), 'default' => 'anthropic' ) );
		register_setting( 'truebe_settings', 'truebe_ai_key',        array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_and_validate_ai_key' ), 'default' => '' ) );

		register_setting( 'truebe_appearance', 'truebe_chat_header',         array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => '' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_greeting',       array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', 'default' => '' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_accent',         array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_hex' ),   'default' => '#0f6e56' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_bot_color',      array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_hex' ),   'default' => '#f6f7f7' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_fallback_color', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_hex' ),   'default' => '#fff9e6' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_width',          array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_width' ), 'default' => 'standard' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_audio',          array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_bool' ),  'default' => '0' ) );
		register_setting( 'truebe_appearance', 'truebe_chat_suggestions',    array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_bool' ),  'default' => '1' ) );
		register_setting( 'truebe_appearance', 'truebe_show_powered_by',     array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_bool' ),  'default' => '0' ) );
		register_setting( 'truebe_appearance', 'truebe_fallback_message',    array( 'type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field',       'default' => '' ) );
		register_setting( 'truebe_settings', 'truebe_keep_documents', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_bool' ), 'default' => '1' ) );
		register_setting( 'truebe_settings', 'truebe_publish_default', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_bool' ), 'default' => '1' ) );
		register_setting( 'truebe_settings', 'truebe_contact_email', array( 'type' => 'string', 'sanitize_callback' => 'sanitize_email', 'default' => '' ) );
		register_setting( 'truebe_settings', 'truebe_contact_phone', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_phone' ), 'default' => '' ) );
	}

	public function maybe_exchange_token() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) { return; }
		$nonce = isset( $_GET['truebe_connect_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['truebe_connect_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'truebe_connect_return' ) ) { return; }
		$raw = isset( $_GET['truebe_token'] ) ? sanitize_text_field( wp_unslash( $_GET['truebe_token'] ) ) : '';
		if ( '' === $raw ) { return; }
		$resp = wp_remote_post( TRUEBE_EXCHANGE_URL, array(
			'timeout' => 15,
			'body'    => array(
				'token' => $raw,
				'site'  => home_url(),
			),
		) );

		if ( ! is_wp_error( $resp ) && 200 === (int) wp_remote_retrieve_response_code( $resp ) ) {
			$body = json_decode( wp_remote_retrieve_body( $resp ), true );
			if ( ! empty( $body['permission_token'] ) ) {
				self::store_permission_token( $body['permission_token'] );
				if ( class_exists( 'Truebe_License' ) ) {
					Truebe_License::ping();
				}
			}
		}

		wp_safe_redirect( admin_url( 'admin.php?page=truebe' ) );
		exit;
	}

	private static function store_permission_token( $plaintext ) {
		if ( ! class_exists( 'Truebe_Crypto' ) || ! Truebe_Crypto::available() ) { return; }
		try {
			update_option( 'truebe_permission_token', Truebe_Crypto::encrypt( $plaintext ) );
		} catch ( RuntimeException $e ) {
			// Silently fail — user will see "not connected" and can retry.
		}
	}

	public static function get_permission_token() {
		$stored = get_option( 'truebe_permission_token', '' );
		if ( '' === $stored || ! class_exists( 'Truebe_Crypto' ) ) { return ''; }
		$plain = Truebe_Crypto::decrypt( $stored );
		return ( false === $plain ) ? '' : $plain;
	}

	public static function is_connected() {
		return '' !== self::get_permission_token();
	}

	public function sanitize_provider( $value ) {
		if ( null === self::$previous_provider ) {
			$prev = get_option( 'truebe_ai_provider', 'anthropic' );
			self::$previous_provider = in_array( $prev, self::$providers, true ) ? $prev : 'anthropic';
		}
		$value = sanitize_key( $value );
		return in_array( $value, self::$providers, true ) ? $value : 'anthropic';
	}

	private static function revert_provider() {
		if ( null !== self::$previous_provider ) {
			update_option( 'truebe_ai_provider', self::$previous_provider );
		}
	}

	public function sanitize_hex( $value ) {
		$value = sanitize_text_field( $value );
		return preg_match( '/^#[0-9a-fA-F]{6}$/', $value ) ? strtolower( $value ) : '';
	}

	public function sanitize_width( $value ) {
		$value = sanitize_key( $value );
		return in_array( $value, array( 'compact', 'standard', 'wide' ), true ) ? $value : 'standard';
	}

	public function sanitize_bool( $value ) {
		return ( '1' === (string) $value ) ? '1' : '0';
	}

	public function sanitize_phone( $value ) {
		$value = sanitize_text_field( $value );
		return preg_replace( '/[^0-9+()\-.\s]/', '', $value );
	}

	public function sanitize_and_validate_ai_key( $value ) {
		$value = sanitize_text_field( $value );

		$provider = isset( $_POST['truebe_ai_provider'] ) ? sanitize_key( wp_unslash( $_POST['truebe_ai_provider'] ) ) : 'anthropic'; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- runs as a register_setting() sanitize callback; the Settings API (options.php) verifies the nonce before this is reached.
		if ( ! in_array( $provider, self::$providers, true ) ) { $provider = 'anthropic'; }
		$switched = ( null !== self::$previous_provider && $provider !== self::$previous_provider );

		if ( '' === $value ) {
			if ( $switched ) {
				self::revert_provider();
				add_settings_error( 'truebe_settings', 'truebe_provider_no_key', __( 'Provider not switched: paste an API key for the new provider and save again.', 'truebe-fact-based-ai-chatbot' ), 'error' );
			}
			return get_option( 'truebe_ai_key', '' );
		}
		if ( 0 === strpos( $value, 'tbenc1:' ) ) { return $value; }

		// This validates a pasted API key against the provider's own /models endpoint
		// (confirms the key is real and active). It is not an AI prompt or generation
		// call, so wp_ai_client_prompt() is not an applicable replacement here.
		if ( 'anthropic' === $provider ) {
			$response = wp_remote_get( 'https://api.anthropic.com/v1/models', array(
				'timeout' => 10,
				'headers' => array( 'x-api-key' => $value, 'anthropic-version' => '2023-06-01' ),
			) );
		} else {
			$response = wp_remote_get( 'https://api.openai.com/v1/models', array(
				'timeout' => 10,
				'headers' => array( 'Authorization' => 'Bearer ' . $value ),
			) );
		}

		$code = is_wp_error( $response ) ? 0 : (int) wp_remote_retrieve_response_code( $response );
		if ( 200 !== $code ) {
			if ( $switched ) { self::revert_provider(); }
			add_settings_error( 'truebe_settings', 'truebe_ai_key_invalid', __( 'That key did not work. Double check it is active in your provider account and try again.', 'truebe-fact-based-ai-chatbot' ), 'error' );
			return get_option( 'truebe_ai_key', '' );
		}
		return self::store_secret( $value, 'truebe_ai_key' );
	}

	private static function store_secret( $plaintext, $option_key ) {
		if ( ! class_exists( 'Truebe_Crypto' ) || ! Truebe_Crypto::available() ) {
			add_settings_error( 'truebe_settings', 'truebe_no_encryption', __( 'This server cannot securely encrypt your key, so it was not saved.', 'truebe-fact-based-ai-chatbot' ), 'error' );
			return get_option( $option_key, '' );
		}
		try {
			return Truebe_Crypto::encrypt( $plaintext );
		} catch ( RuntimeException $e ) {
			add_settings_error( 'truebe_settings', 'truebe_encryption_failed', __( 'Your key could not be encrypted, so it was not saved.', 'truebe-fact-based-ai-chatbot' ), 'error' );
			return get_option( $option_key, '' );
		}
	}

	public static function get_secret( $option_key ) {
		$stored = get_option( $option_key, '' );
		if ( '' === $stored || ! class_exists( 'Truebe_Crypto' ) ) { return ''; }
		$plaintext = Truebe_Crypto::decrypt( $stored );
		return ( false === $plaintext ) ? '' : $plaintext;
	}

	public function render_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) { return; }

		$has_key    = ( '' !== self::get_secret( 'truebe_ai_key' ) );
		$connected  = self::is_connected();
		$provider   = get_option( 'truebe_ai_provider', 'openai' );
		if ( ! in_array( $provider, self::$providers, true ) ) { $provider = ''; }
		$wp_ai_provider = self::detect_wp_ai_provider();

$current_user  = wp_get_current_user();
		$first_name    = ! empty( $current_user->first_name ) ? $current_user->first_name : $current_user->display_name;

		$return_url  = wp_nonce_url( admin_url( 'admin.php?page=truebe' ), 'truebe_connect_return', 'truebe_connect_nonce' );
		$connect_url = add_query_arg( array( 'return' => rawurlencode( $return_url ), 'email' => rawurlencode( $current_user->user_email ) ), TRUEBE_CONNECT_URL );
		$hour          = (int) current_time( 'G' );
		if ( $hour >= 5 && $hour < 12 ) {
			$greeting = '🚀 Good morning';
		} elseif ( $hour >= 12 && $hour < 17 ) {
			$greeting = '☀️ Good afternoon';
		} else {
			$greeting = '🦉 Good evening';
		}

		global $wpdb;
		// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- {$wpdb->prefix} is core-provided, not user input; SQL identifiers cannot be passed as prepare() parameters. Custom plugin tables, no core API or object cache.
		$seed_count    = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}truebe_seeds WHERE status = 'approved'" );
		$pending_count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}truebe_seeds WHERE status = 'pending'" );
		$gap_count     = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}truebe_gaps" );
		// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
		?>
		<div class="wrap truebe-settings">
			<h1><?php esc_html_e( 'Settings', 'truebe-fact-based-ai-chatbot' ); ?></h1>
			<?php
			$active_tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'connection'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only UI tab state, no data change; value is sanitized and whitelisted on the next line.
			if ( ! in_array( $active_tab, array( 'connection', 'appearance', 'support' ), true ) ) { $active_tab = 'connection'; }
			?>
			<nav class="truebe-tabs">
				<a class="truebe-tab <?php echo ( 'connection' === $active_tab ) ? 'is-active' : ''; ?>" href="<?php echo esc_url( admin_url( 'admin.php?page=truebe&tab=connection' ) ); ?>"><?php esc_html_e( 'Connection', 'truebe-fact-based-ai-chatbot' ); ?></a>
				<a class="truebe-tab <?php echo ( 'appearance' === $active_tab ) ? 'is-active' : ''; ?>" href="<?php echo esc_url( admin_url( 'admin.php?page=truebe&tab=appearance' ) ); ?>"><?php esc_html_e( 'Appearance', 'truebe-fact-based-ai-chatbot' ); ?></a>
				<a class="truebe-tab <?php echo ( 'support' === $active_tab ) ? 'is-active' : ''; ?>" href="<?php echo esc_url( admin_url( 'admin.php?page=truebe&tab=support' ) ); ?>"><?php esc_html_e( 'Support', 'truebe-fact-based-ai-chatbot' ); ?></a>
			</nav>

			<?php if ( 'connection' === $active_tab ) : ?>
			<?php settings_errors( 'truebe_settings' ); ?>
			<form method="post" action="options.php">
				<?php settings_fields( 'truebe_settings' ); ?>

				<div class="truebe-card">
					<div class="truebe-field">
						<div class="truebe-field-label-row">
							<label class="truebe-label" for="truebe_ai_key"><?php esc_html_e( 'AI key', 'truebe-fact-based-ai-chatbot' ); ?></label>
						</div>
						<p class="truebe-field-help" style="margin-top:2px;"><?php esc_html_e( "You need an AI API key. If you have one, please paste in the API key field below. If you don't have one, please pick a provider and then Show me how for a setup guide.", 'truebe-fact-based-ai-chatbot' ); ?></p>



						<div class="truebe-providers truebe-providers-sm" style="margin-top:12px;display:flex;gap:12px;">
							<div style="flex:1;">
								<label class="truebe-tile truebe-claude <?php echo ( 'anthropic' === $provider ) ? 'is-selected' : ''; ?>">
									<input type="radio" id="truebe-provider-anthropic" name="truebe_ai_provider" value="anthropic" <?php checked( $provider, 'anthropic' ); ?> />
									<span class="truebe-dot"></span>
									<span class="truebe-tile-name"><?php esc_html_e( 'Claude', 'truebe-fact-based-ai-chatbot' ); ?></span>
								</label>
								<div class="truebe-keyhelp-col truebe-keyhelp-claude" data-claude style="margin-top:6px;">
								<a class="truebe-keyhelp-link" href="https://platform.claude.com/settings/keys" target="_blank" rel="noopener"><?php esc_html_e( 'Get a Claude key →', 'truebe-fact-based-ai-chatbot' ); ?></a>
									<button type="button" class="truebe-keyhelp-guide" id="truebe-open-guide"><?php esc_html_e( 'Show me how', 'truebe-fact-based-ai-chatbot' ); ?></button>
								</div>
							</div>
							<div style="flex:1;">
								<label class="truebe-tile truebe-openai <?php echo ( 'openai' === $provider ) ? 'is-selected' : ''; ?>">
									<input type="radio" id="truebe-provider-openai" name="truebe_ai_provider" value="openai" <?php checked( $provider, 'openai' ); ?> />
									<span class="truebe-dot"></span>
									<span class="truebe-tile-name"><?php esc_html_e( 'ChatGPT', 'truebe-fact-based-ai-chatbot' ); ?></span>
								</label>
								<div class="truebe-keyhelp-col truebe-keyhelp-openai" data-openai style="margin-top:6px;">
								<a class="truebe-keyhelp-link" href="https://platform.openai.com/api-keys" target="_blank" rel="noopener"><?php esc_html_e( 'Get a ChatGPT key →', 'truebe-fact-based-ai-chatbot' ); ?></a>
									<button type="button" class="truebe-keyhelp-guide" id="truebe-open-guide-openai"><?php esc_html_e( 'Show me how', 'truebe-fact-based-ai-chatbot' ); ?></button>
								</div>
							</div>
						</div>









						<?php if ( $has_key ) : ?>
							<div class="truebe-connected-state" id="truebe-key-active" style="margin-top:12px;">
								<span class="truebe-connected-dot" aria-hidden="true"></span>
								<span class="truebe-connected-label"><?php esc_html_e( 'AI key active', 'truebe-fact-based-ai-chatbot' ); ?></span>
								<button type="button" id="truebe-replace-key" style="border:none;background:none;padding:0;margin-left:12px;color:#0f6e56;font-size:13px;font-weight:500;cursor:pointer;text-decoration:underline;"><?php esc_html_e( 'Replace key', 'truebe-fact-based-ai-chatbot' ); ?></button>
							</div>
							<div id="truebe-key-replace" style="display:none;margin-top:8px;">
							<p id="truebe-key-switch-note" style="display:none;margin:8px 0;font-size:13px;color:#92400e;background:#fef3c7;border-radius:6px;padding:8px 12px;white-space:nowrap;"><?php esc_html_e( 'Paste the new provider\'s key. It replaces your old one.', 'truebe-fact-based-ai-chatbot' ); ?></p>
							<input class="truebe-input" name="truebe_ai_key" id="truebe_ai_key" type="password"
									value="" autocomplete="new-password" data-lpignore="true" data-1p-ignore
									placeholder="<?php esc_attr_e( 'Paste the new provider API key', 'truebe-fact-based-ai-chatbot' ); ?>" />
							</div>
						<?php else : ?>
							<input class="truebe-input" name="truebe_ai_key" id="truebe_ai_key" type="password"
								value="" autocomplete="new-password" data-lpignore="true" data-1p-ignore
								placeholder="<?php esc_attr_e( 'Paste API key', 'truebe-fact-based-ai-chatbot' ); ?>" style="margin-top:12px;" />
						<?php endif; ?>
					</div>
					<?php /*
					<div class="truebe-field">
						<div class="truebe-field-label-row">
							<label class="truebe-label">Truebe account</label>
							<span class="truebe-tooltip-wrap" tabindex="0">
								<span class="dashicons dashicons-info-outline truebe-info-icon" aria-hidden="true"></span>
								<span class="truebe-tooltip">Your Truebe subscription lets you upload documents, approve answers, and get a daily report of user-suggested questions to increase customer responses.</span>
							</span>
						</div>

						<div class="truebe-connected-state">
							<span class="truebe-connected-dot" aria-hidden="true"></span>
							<span class="truebe-connected-label">Truebe account active</span>
						</div>

						<a class="truebe-btn truebe-connect-btn" href="#" target="_blank" rel="noopener">
							Start your subscription
						</a>
					</div>
					*/ ?>

			<div class="truebe-field">
				<div class="truebe-ap-row">
					<div>
						<div class="truebe-ap-rowtext"><?php esc_html_e( 'Publish approved answers by default', 'truebe-fact-based-ai-chatbot' ); ?></div>
					</div>
					<label class="truebe-ap-switch">
						<input type="hidden" name="truebe_publish_default" value="0" />
						<input type="checkbox" name="truebe_publish_default" value="1" <?php checked( '1', get_option( 'truebe_publish_default', '1' ) ); ?> />
						<span class="truebe-ap-track"><span class="truebe-ap-knob"></span></span>
					</label>
				</div>
			</div>

			<div class="truebe-field">
				<label class="truebe-label" for="truebe_contact_email"><?php esc_html_e( 'Contact email', 'truebe-fact-based-ai-chatbot' ); ?></label>
				<p class="truebe-field-help" style="margin-top:2px;"><?php esc_html_e( 'Shown to visitors when the chatbot has no answer.', 'truebe-fact-based-ai-chatbot' ); ?></p>
				<input class="truebe-input" type="email" id="truebe_contact_email" name="truebe_contact_email" value="<?php echo esc_attr( get_option( 'truebe_contact_email', '' ) ); ?>" placeholder="hello@yourbusiness.com" style="margin-top:8px;" />
			</div>

			<div class="truebe-field">
				<label class="truebe-label" for="truebe_contact_phone"><?php esc_html_e( 'Contact phone', 'truebe-fact-based-ai-chatbot' ); ?></label>
				<input class="truebe-input" type="text" id="truebe_contact_phone" name="truebe_contact_phone" value="<?php echo esc_attr( get_option( 'truebe_contact_phone', '' ) ); ?>" placeholder="(555) 555-5555" style="margin-top:8px;" />
			</div>

		</div>

		<div class="truebe-save-row">
			<button type="submit" class="truebe-btn truebe-save"><?php esc_html_e( 'Save', 'truebe-fact-based-ai-chatbot' ); ?></button>
		</div>
		</form>

		<?php
		$guide_url = plugins_url( '../assets/guide/claude/', __FILE__ );
		$steps = array(
			array( 'img' => '', 'title' => __( 'Get your Claude API key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Truebe uses your own Claude account to generate answers, so you need an API key from Claude. This short guide walks you through every screen — creating your account, adding credits, and copying your key. It takes about 5 minutes and you will need a credit card (Claude charges per use, usually pennies). Click Next to begin.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-1.png', 'title' => __( 'Sign in', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'On the "Build on the Claude Platform" page, either click the white Continue with Google button or type your email in the "Enter your email" field.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-2.png', 'title' => __( 'Pick Organization', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Select the box on the RIGHT labeled Organization.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-3.png', 'title' => __( 'Your organization', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Enter your business name. Select the "What type of entity" dropdown and choose Small or medium business. Then, select the "Where is your organization" and pick your country. Continue.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-4.png', 'title' => __( 'Usage questions', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Click No if you only operate in the US. Select the Select dropdown for internal/external/both and choose External. In the box, type Document Q&A. Continue.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-5.png', 'title' => __( 'Review & create account', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Three Yes/No questions: Legal/medical/financial advice → Yes. Professional reviews content → Yes (Truebe is that review). Used for under 18 → No, unless your site is for minors. Once all three are set, select the black Create account button.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-6.png', 'title' => __( 'Add credits', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Click the "Trying it out" $20 box on the left. Under Purchase summary on the right, click Buy credits. Credits pay for the AI that reads your documents and writes your answers — processing a document usually costs a few cents, so $20 covers most small businesses for months. Then enter your name, billing address, and card. Do NOT click "Skip for now" — your key will not work without credits.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-7.png', 'title' => __( 'Get your key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'On the Dashboard you now see, look at the top right next to the "Good afternoon" greeting. Click the white Get API key button in the middle (it has a small key icon).', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-8.png', 'title' => __( 'Copy your key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Your key appears in the box under "My test key." Click the black Copy button. You will not be able to view this key again so save it in a safe place. Close out this window and paste the key into the "AI Key" field in the Truebe plugin Settings page.', 'truebe-fact-based-ai-chatbot' ) ),
		);
		$guide_url_openai = plugins_url( '../assets/guide/openai/', __FILE__ );
		$steps_openai = array(
			array( 'img' => '', 'title' => __( 'Get your ChatGPT API key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'You will need a key from OpenAI to enable AI. This short guide walks you through every screen. It takes about 5 minutes and you will need a credit card (OpenAI charges per use, usually pennies). Click Next to begin.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-1.png', 'title' => __( 'Sign in', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'On the "Build on the OpenAI API Platform" page, Continue with Google, Apple, Microsoft, or your phone number or enter your email address.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-3.png', 'title' => __( 'Check your email', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'OpenAI emails you a six-digit code. Open your email, copy the code, type it into the "Code" box, and continue.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-4.png', 'title' => __( 'Your name and age', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Enter full name, age and click the black Finish creating account button.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-5.png', 'title' => __( 'Name your organization', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'In the "Organization name" field enter your business name. Leave "Project name" as Default project. Continue.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-6.png', 'title' => __( 'Choose your plan', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Select the Prototype plan. It starts at $5 and will give you access to use the AI. In the "API credits" box enter $20. Credits pay for the AI that reads your documents and writes your answers. Processing a document usually costs a few cents, so $20 covers most small businesses for months. Click the black Continue to checkout button and enter your card information. Do not pick Free.', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-7.png', 'title' => __( 'Name your key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'On "Make your first API call," type your business name followed by Fact Library in the "API key name" field, like "Smith Law Fact Library." Click the black Generate API Key button. Do not click "I\'ll do this later."', 'truebe-fact-based-ai-chatbot' ) ),
			array( 'img' => 'step-8.png', 'title' => __( 'Copy your key', 'truebe-fact-based-ai-chatbot' ), 'body' => __( 'Your key appears in the box under "My test key." Click the black Copy button. You will not be able to access again. Paste the key into the "AI key" field in the Truebe plugin Settings page.', 'truebe-fact-based-ai-chatbot' ) ),
		);
		?>
		<div class="truebe-modal" id="truebe-guide" hidden>
			<div class="truebe-modal-backdrop" data-close></div>
			<div class="truebe-modal-box" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr__( 'Get your Claude API key', 'truebe-fact-based-ai-chatbot' ); ?>">
				<button type="button" class="truebe-modal-x" data-close aria-label="<?php echo esc_attr__( 'Close', 'truebe-fact-based-ai-chatbot' ); ?>">&times;</button>
				<?php $total_steps = count( $steps ) - 1; foreach ( $steps as $i => $step ) : $is_intro = ( 0 === $i ); ?>
					<div class="truebe-step" data-step="<?php echo (int) $i; ?>" <?php echo ( 0 === $i ) ? '' : 'hidden'; ?>>
						<?php if ( $is_intro ) : ?><div class="truebe-step-count truebe-step-count-intro"><?php esc_html_e( 'Setup guide', 'truebe-fact-based-ai-chatbot' ); ?></div>
						<?php else : ?><div class="truebe-step-count"><?php /* translators: 1: current step number, 2: total number of steps */ echo esc_html( sprintf( __( 'Step %1$d of %2$d', 'truebe-fact-based-ai-chatbot' ), $i, $total_steps ) ); ?></div><?php endif; ?>
							<h2 class="truebe-step-title"><?php echo esc_html( $step['title'] ); ?></h2>
						<div class="truebe-step-body-box"><p class="truebe-step-body"><?php echo esc_html( $step['body'] ); ?></p></div>
						<div class="truebe-modal-nav">
							<button type="button" class="truebe-btn truebe-btn-ghost truebe-prev" disabled><?php esc_html_e( 'Back', 'truebe-fact-based-ai-chatbot' ); ?></button>
							<button type="button" class="truebe-btn truebe-next"><?php esc_html_e( 'Next', 'truebe-fact-based-ai-chatbot' ); ?></button>
						</div>
						<?php if ( ! empty( $step['img'] ) ) : ?><img class="truebe-step-img" src="<?php echo esc_url( $guide_url . $step['img'] ); ?>" alt="<?php echo esc_attr( $step['title'] ); ?>" loading="lazy" /><?php endif; ?>
					</div>
				<?php endforeach; ?>
			</div>
		</div>

		<div class="truebe-modal" id="truebe-guide-openai" hidden>
			<div class="truebe-modal-backdrop" data-close></div>
			<div class="truebe-modal-box" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr__( 'Get your ChatGPT API key', 'truebe-fact-based-ai-chatbot' ); ?>">
				<button type="button" class="truebe-modal-x" data-close aria-label="<?php echo esc_attr__( 'Close', 'truebe-fact-based-ai-chatbot' ); ?>">&times;</button>
				<?php $total_steps_openai = count( $steps_openai ) - 1; foreach ( $steps_openai as $i => $step ) : $is_intro = ( 0 === $i ); ?>
					<div class="truebe-step" data-step="<?php echo (int) $i; ?>" <?php echo ( 0 === $i ) ? '' : 'hidden'; ?>>
						<?php if ( $is_intro ) : ?><div class="truebe-step-count truebe-step-count-intro"><?php esc_html_e( 'Setup guide', 'truebe-fact-based-ai-chatbot' ); ?></div>
						<?php else : ?><div class="truebe-step-count"><?php /* translators: 1: current step number, 2: total number of steps */ echo esc_html( sprintf( __( 'Step %1$d of %2$d', 'truebe-fact-based-ai-chatbot' ), $i, $total_steps_openai ) ); ?></div><?php endif; ?>
							<h2 class="truebe-step-title"><?php echo esc_html( $step['title'] ); ?></h2>
						<div class="truebe-step-body-box"><p class="truebe-step-body"><?php echo esc_html( $step['body'] ); ?></p></div>
						<div class="truebe-modal-nav">
							<button type="button" class="truebe-btn truebe-btn-ghost truebe-prev" disabled><?php esc_html_e( 'Back', 'truebe-fact-based-ai-chatbot' ); ?></button>
							<button type="button" class="truebe-btn truebe-next"><?php esc_html_e( 'Next', 'truebe-fact-based-ai-chatbot' ); ?></button>
						</div>
						<?php if ( ! empty( $step['img'] ) ) : ?><img class="truebe-step-img" src="<?php echo esc_url( $guide_url_openai . $step['img'] ); ?>" alt="<?php echo esc_attr( $step['title'] ); ?>" loading="lazy" /><?php endif; ?>
					</div>
				<?php endforeach; ?>
			</div>
		</div>

		<?php elseif ( 'support' === $active_tab ) : ?>
			<div class="truebe-card">
				<div class="truebe-field" style="border-bottom:none;padding-bottom:0;">
					<div class="truebe-field-label-row">
						<label class="truebe-label"><?php esc_html_e( 'Get help', 'truebe-fact-based-ai-chatbot' ); ?></label>
						<span class="truebe-tooltip-wrap" tabindex="0">
							<span class="dashicons dashicons-info-outline truebe-info-icon" aria-hidden="true"></span>
							<span class="truebe-tooltip"><?php esc_html_e( 'Your message goes straight to the Truebe team, along with your site URL and plugin version so we can help faster.', 'truebe-fact-based-ai-chatbot' ); ?></span>
						</span>
					</div>
					<p class="truebe-field-help" style="margin-top:2px;"><?php esc_html_e( 'Stuck on setup, hit an error, or have a question? Send us a message and we will get back to you.', 'truebe-fact-based-ai-chatbot' ); ?></p>
					<textarea class="truebe-input" id="truebe-support-message" rows="5" style="height:auto;padding:10px 13px !important;resize:vertical;" placeholder="<?php esc_attr_e( 'Describe what you need help with…', 'truebe-fact-based-ai-chatbot' ); ?>"></textarea>
					<input class="truebe-input" type="email" id="truebe-support-email" style="margin-top:10px;" placeholder="<?php esc_attr_e( 'Your email (optional, so we can reply)', 'truebe-fact-based-ai-chatbot' ); ?>" />
					<div class="truebe-save-row" style="justify-content:flex-start;">
						<button type="button" class="truebe-btn truebe-save" id="truebe-support-submit"><?php esc_html_e( 'Send message', 'truebe-fact-based-ai-chatbot' ); ?></button>
						<span class="truebe-flash-pill" id="truebe-support-sent" style="display:none;"><?php esc_html_e( 'Sent. Thanks!', 'truebe-fact-based-ai-chatbot' ); ?></span>
					</div>
				</div>
			</div>
		<?php else : ?>
			<?php
			$ap_header = get_option( 'truebe_chat_header', '' );
			$ap_greet  = get_option( 'truebe_chat_greeting', '' );
			$ap_greet_default = ( class_exists( 'Truebe_Chatbot' ) && method_exists( 'Truebe_Chatbot', 'default_greeting' ) ) ? Truebe_Chatbot::default_greeting() : __( 'Ask me a question.', 'truebe-fact-based-ai-chatbot' );
			$ap_accent = get_option( 'truebe_chat_accent', '' ); $ap_accent = ( '' !== $ap_accent ) ? $ap_accent : '#0f6e56';
			$ap_bot    = get_option( 'truebe_chat_bot_color', '' ); $ap_bot = ( '' !== $ap_bot ) ? $ap_bot : '#f6f7f7';
			$ap_fb     = get_option( 'truebe_chat_fallback_color', '' ); $ap_fb = ( '' !== $ap_fb ) ? $ap_fb : '#fff9e6';
			$ap_width  = get_option( 'truebe_chat_width', 'standard' );
			if ( ! in_array( $ap_width, array( 'compact', 'standard', 'wide' ), true ) ) { $ap_width = 'standard'; }
			$ap_audio  = ( '1' === (string) get_option( 'truebe_chat_audio', '0' ) );
			$ap_sugg   = ( '1' === (string) get_option( 'truebe_chat_suggestions', '1' ) );
			$ap_site   = get_bloginfo( 'name' );
			$ap_px_map = array( 'compact' => 300, 'standard' => 360, 'wide' => 420 );
			$ap_px     = $ap_px_map[ $ap_width ];
			$ap_widths = array( 'compact' => __( 'Compact', 'truebe-fact-based-ai-chatbot' ), 'standard' => __( 'Standard', 'truebe-fact-based-ai-chatbot' ), 'wide' => __( 'Wide', 'truebe-fact-based-ai-chatbot' ) );
			?>
			<?php settings_errors(); ?>
			<form method="post" action="options.php" class="truebe-ap">
				<?php settings_fields( 'truebe_appearance' ); ?>
				<div class="truebe-ap-grid">
					<div>
					<p class="truebe-ap-pvlabel"><?php esc_html_e( 'Setup', 'truebe-fact-based-ai-chatbot' ); ?></p>
					<div class="truebe-card">

						<div class="truebe-field">
							<label class="truebe-label" for="truebe_chat_header"><?php esc_html_e( 'Header label', 'truebe-fact-based-ai-chatbot' ); ?></label>
							<input class="truebe-input" type="text" id="truebe_chat_header" name="truebe_chat_header" value="<?php echo esc_attr( $ap_header ); ?>" placeholder="<?php echo esc_attr( $ap_site ); ?>" />
						</div>

						<div class="truebe-field">
							<label class="truebe-label" for="truebe_chat_greeting"><?php esc_html_e( 'Greeting message', 'truebe-fact-based-ai-chatbot' ); ?></label>
							<input class="truebe-input" type="text" id="truebe_chat_greeting" name="truebe_chat_greeting" value="<?php echo esc_attr( $ap_greet ); ?>" placeholder="<?php echo esc_attr( $ap_greet_default ); ?>" />
						</div>

						<div class="truebe-field">
							<label class="truebe-label" for="truebe_fallback_message"><?php esc_html_e( 'No-answer message', 'truebe-fact-based-ai-chatbot' ); ?></label>
							<p class="truebe-field-help" style="margin-top:2px;"><?php esc_html_e( 'Shown when the chatbot has no answer for a question. Leave blank to use the default.', 'truebe-fact-based-ai-chatbot' ); ?></p>
							<textarea class="truebe-input" id="truebe_fallback_message" name="truebe_fallback_message" rows="3" autocomplete="off" data-lpignore="true" data-1p-ignore style="height:auto;padding:10px 13px !important;resize:vertical;margin-top:8px;" placeholder="<?php esc_attr_e( "We don't have an answer for that yet. Feel free to reach out to us directly.", 'truebe-fact-based-ai-chatbot' ); ?>"><?php echo esc_textarea( get_option( 'truebe_fallback_message', '' ) ); ?></textarea>
						</div>

						<div class="truebe-field">
							<label class="truebe-label"><?php esc_html_e( 'Colors', 'truebe-fact-based-ai-chatbot' ); ?></label>
							<div class="truebe-ap-colors">
								<div class="truebe-ap-cgroup">
								<div class="truebe-ap-chead"><span class="truebe-ap-cname"><?php esc_html_e( 'Visitor messages', 'truebe-fact-based-ai-chatbot' ); ?></span><input type="text" class="truebe-ap-chex" id="tap-hA" maxlength="7" value="<?php echo esc_attr( strtoupper( $ap_accent ) ); ?>" /></div>
								<input type="color" class="truebe-ap-cbar" name="truebe_chat_accent" value="<?php echo esc_attr( $ap_accent ); ?>" />
								</div>
								<div class="truebe-ap-cgroup">
								<div class="truebe-ap-chead"><span class="truebe-ap-cname"><?php esc_html_e( 'Bot messages', 'truebe-fact-based-ai-chatbot' ); ?></span><input type="text" class="truebe-ap-chex" id="tap-hB" maxlength="7" value="<?php echo esc_attr( strtoupper( $ap_bot ) ); ?>" /></div>
								<input type="color" class="truebe-ap-cbar" name="truebe_chat_bot_color" value="<?php echo esc_attr( $ap_bot ); ?>" />
								</div>
								<div class="truebe-ap-cgroup">
								<div class="truebe-ap-chead"><span class="truebe-ap-cname"><?php esc_html_e( 'Fallback', 'truebe-fact-based-ai-chatbot' ); ?></span><input type="text" class="truebe-ap-chex" id="tap-hF" maxlength="7" value="<?php echo esc_attr( strtoupper( $ap_fb ) ); ?>" /></div>
								<input type="color" class="truebe-ap-cbar" name="truebe_chat_fallback_color" value="<?php echo esc_attr( $ap_fb ); ?>" />
								</div>
							</div>
						</div>

						<div class="truebe-field">
							<label class="truebe-label"><?php esc_html_e( 'Width', 'truebe-fact-based-ai-chatbot' ); ?></label>
							<input type="hidden" name="truebe_chat_width" id="tap-width" value="<?php echo esc_attr( $ap_width ); ?>" />
							<div class="truebe-ap-presets">
								<?php foreach ( $ap_widths as $val => $lbl ) : ?>
									<div class="truebe-ap-preset <?php echo ( $ap_width === $val ) ? 'is-active' : ''; ?>" data-val="<?php echo esc_attr( $val ); ?>" data-w="<?php echo (int) $ap_px_map[ $val ]; ?>"><?php echo esc_html( $lbl ); ?></div>
								<?php endforeach; ?>
							</div>
						</div>

						<div class="truebe-field">
							<div class="truebe-ap-row">
								<div>
									<div class="truebe-ap-rowtext"><?php esc_html_e( 'Voice input', 'truebe-fact-based-ai-chatbot' ); ?></div>
									<div class="truebe-ap-rowhint"><?php esc_html_e( 'Adds a mic. Needs a secure (HTTPS) site.', 'truebe-fact-based-ai-chatbot' ); ?></div>
								</div>
								<label class="truebe-ap-switch">
									<input type="hidden" name="truebe_chat_audio" value="0" />
									<input type="checkbox" name="truebe_chat_audio" value="1" <?php checked( $ap_audio ); ?> />
									<span class="truebe-ap-track"><span class="truebe-ap-knob"></span></span>
								</label>
							</div>
						</div>
<div class="truebe-field">
							<div class="truebe-ap-row">
								<div>
									<div class="truebe-ap-rowtext"><?php esc_html_e( 'Suggestions on no match', 'truebe-fact-based-ai-chatbot' ); ?></div>
									<div class="truebe-ap-rowhint"><?php esc_html_e( 'Offer related questions instead of a dead end.', 'truebe-fact-based-ai-chatbot' ); ?></div>
								</div>
								<label class="truebe-ap-switch">
									<input type="hidden" name="truebe_chat_suggestions" value="0" />
									<input type="checkbox" name="truebe_chat_suggestions" value="1" <?php checked( $ap_sugg ); ?> />
									<span class="truebe-ap-track"><span class="truebe-ap-knob"></span></span>
								</label>
							</div>
						</div>

						<div class="truebe-field">
							<div class="truebe-ap-row">
								<div>
									<div class="truebe-ap-rowtext"><?php esc_html_e( 'Show "Powered by Truebe" badge', 'truebe-fact-based-ai-chatbot' ); ?></div>
									<div class="truebe-ap-rowhint"><?php esc_html_e( 'Adds a small credit link under the chatbot on your site.', 'truebe-fact-based-ai-chatbot' ); ?></div>
								</div>
								<label class="truebe-ap-switch">
									<input type="hidden" name="truebe_show_powered_by" value="0" />
									<input type="checkbox" name="truebe_show_powered_by" value="1" <?php checked( '1', get_option( 'truebe_show_powered_by', '0' ) ); ?> />
									<span class="truebe-ap-track"><span class="truebe-ap-knob"></span></span>
								</label>
							</div>
						</div>
					</div>
					</div>

					<div class="truebe-ap-pvcol" style="max-width:<?php echo (int) $ap_px; ?>px;">
						<p class="truebe-ap-pvlabel"><?php esc_html_e( 'Live preview', 'truebe-fact-based-ai-chatbot' ); ?></p>
						<div class="truebe-ap-pv" id="tap-pv" style="max-width:<?php echo (int) $ap_px; ?>px;">
							<div class="truebe-ap-pvhead" id="tap-head" data-ph="<?php echo esc_attr( $ap_site ); ?>"><?php echo esc_html( '' !== $ap_header ? $ap_header : $ap_site ); ?></div>
							<div class="truebe-ap-bub" id="tap-greet"><?php echo esc_html( '' !== $ap_greet ? $ap_greet : $ap_greet_default ); ?></div>
							<div class="truebe-ap-bub truebe-ap-user" id="tap-user"><?php esc_html_e( 'What is your refund window?', 'truebe-fact-based-ai-chatbot' ); ?></div>
							<div class="truebe-ap-fb" id="tap-fb" style="<?php echo $ap_sugg ? '' : 'display:none;'; ?>">
							<div class="truebe-ap-fbtitle" id="tap-fbtitle" data-default="<?php echo esc_attr__( "We don't have an answer for that yet", 'truebe-fact-based-ai-chatbot' ); ?>"><?php esc_html_e( "We don't have an answer for that yet", 'truebe-fact-based-ai-chatbot' ); ?></div>
							<div class="truebe-ap-fbsub"><?php esc_html_e( 'You might find these helpful:', 'truebe-fact-based-ai-chatbot' ); ?></div>
								<div class="truebe-ap-fbitem" id="tap-i1"><?php esc_html_e( 'What is your cancellation policy?', 'truebe-fact-based-ai-chatbot' ); ?></div>
								<div class="truebe-ap-fbitem" id="tap-i2"><?php esc_html_e( 'How do I update my billing details?', 'truebe-fact-based-ai-chatbot' ); ?></div>
							</div>
							<div class="truebe-ap-inrow">
								<div class="truebe-ap-inbox"><?php esc_html_e( 'Type or speak…', 'truebe-fact-based-ai-chatbot' ); ?></div>
								<div class="truebe-ap-ic" id="tap-send"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13m11-11l-7 20-4-9-9-4 20-7z"/></svg></div>
								<div class="truebe-ap-ic" id="tap-mic" style="color:#8a8a8a;<?php echo $ap_audio ? '' : 'display:none;'; ?>"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 1a3 3 0 0 0-3 3v12a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg></div>
							</div>
						</div>

						<div class="truebe-card" style="margin-top:20px;">
							<div class="truebe-field" style="border-bottom:none;padding-bottom:0;">
								<label class="truebe-label"><?php esc_html_e( 'Add chatbot to your site', 'truebe-fact-based-ai-chatbot' ); ?></label>
								<p class="truebe-field-help" style="margin-top:2px;"><?php esc_html_e( 'Paste this shortcode on any page or post where you want the chatbot to appear.', 'truebe-fact-based-ai-chatbot' ); ?></p>
								<div style="position:relative;">
									<input class="truebe-input" type="text" id="truebe-shortcode" value="[truebe_chat]" readonly style="background:#fff;padding-right:44px !important;font-family:Menlo,Monaco,Consolas,monospace;color:#0f6e56;" />
									<button type="button" id="truebe-shortcode-copy" data-code="[truebe_chat]" title="<?php esc_attr_e( 'Copy shortcode', 'truebe-fact-based-ai-chatbot' ); ?>" style="position:absolute;right:8px;top:50%;transform:translateY(-50%);border:none;background:none;cursor:pointer;color:#0f6e56;display:inline-flex;align-items:center;padding:4px;line-height:1;">
										<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
									</button>
								</div>
							</div>
						</div>
					</div>
				</div>

				<div class="truebe-save-row">
					<button type="submit" class="truebe-btn truebe-save"><?php esc_html_e( 'Save', 'truebe-fact-based-ai-chatbot' ); ?></button>
				</div>
			</form>
		<?php endif; ?>
		<?php
	}
}