<?php
/**
 * Admin settings page for Harbor Sync with Attio for WooCommerce
 *
 * @package WooAttioSync
 */

declare( strict_types=1 );

defined( 'ABSPATH' ) || exit;

/**
 * Registers and renders the plugin's admin settings UI
 */
class WooAttioSync_Admin_Settings {

	/**
	 * Option name for the Attio API key
	 */
	const OPTION_API_KEY = 'wcattio_api_key';

	/**
	 * Option name for the order statuses that trigger a sync
	 */
	const OPTION_SYNC_STATUSES = WooAttioSync_Sync_Queue::OPTION_SYNC_STATUSES;

	/**
	 * Wire up WordPress hooks
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'wp_ajax_wcattio_validate_key', array( $this, 'ajax_validate_key' ) );
		add_action( 'wp_ajax_wcattio_bulk_sync', array( $this, 'ajax_bulk_sync' ) );
		add_action( 'wp_ajax_wcattio_bulk_sync_orders', array( $this, 'ajax_bulk_sync_orders' ) );
		add_action( 'wp_ajax_wcattio_dismiss_onboarding', array( $this, 'ajax_dismiss_onboarding' ) );
	}

	/**
	 * Render the shared navigation tabs used on every plugin admin page.
	 *
	 * @param string $active_page Key identifying the currently active tab:
	 *                            'settings' | 'sync-log' | 'field-mapping' | 'webhook' | 'list-rules'
	 */
	public static function render_nav_tabs( string $active_page ): void {
		$tabs = array(
			'settings'      => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=settings' ),
				'label' => __( 'Settings', 'harbor-sync-with-attio-for-woocommerce' ),
			),
			'sync-log'      => array(
				'url'   => admin_url( 'admin.php?page=wcattio-sync-log' ),
				'label' => __( 'Sync Log', 'harbor-sync-with-attio-for-woocommerce' ),
			),
			'field-mapping' => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=field-mapping' ),
				'label' => __( 'Field Mapping', 'harbor-sync-with-attio-for-woocommerce' ),
				'pro'   => true,
			),
			'webhook'       => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=webhook' ),
				'label' => __( 'Webhook', 'harbor-sync-with-attio-for-woocommerce' ),
				'pro'   => true,
			),
			'list-rules'    => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=list-rules' ),
				'label' => __( 'List Rules', 'harbor-sync-with-attio-for-woocommerce' ),
				'pro'   => true,
			),
			'deals'         => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=deals' ),
				'label' => __( 'Deals', 'harbor-sync-with-attio-for-woocommerce' ),
				'pro'   => true,
			),
			'tasks'         => array(
				'url'   => admin_url( 'admin.php?page=wcattio-settings&tab=tasks' ),
				'label' => __( 'Tasks', 'harbor-sync-with-attio-for-woocommerce' ),
				'pro'   => true,
			),
		);
		?>
		<nav class="nav-tab-wrapper woo-nav-tab-wrapper" aria-label="<?php esc_attr_e( 'Plugin settings', 'harbor-sync-with-attio-for-woocommerce' ); ?>">
			<?php foreach ( $tabs as $key => $tab ) : ?>
				<a
					href="<?php echo esc_url( $tab['url'] ); ?>"
					class="nav-tab <?php echo $active_page === $key ? 'nav-tab-active' : ''; ?>"
					<?php echo $active_page === $key ? 'aria-current="page"' : ''; ?>
				>
					<?php echo esc_html( $tab['label'] ); ?>
					<?php if ( ! empty( $tab['pro'] ) && ! wcattio_is_pro() ) : ?>
						<span class="wcattio-pro-badge wcattio-pro-badge--tab"><?php esc_html_e( 'PRO', 'harbor-sync-with-attio-for-woocommerce' ); ?></span>
					<?php endif; ?>
				</a>
			<?php endforeach; ?>
		</nav>
		<?php
	}

	/**
	 * Add the settings submenu under the WooCommerce menu
	 */
	public function add_menu_page(): void {
		add_submenu_page(
			'woocommerce',
			__( 'Harbor Sync with Attio', 'harbor-sync-with-attio-for-woocommerce' ),
			__( 'Harbor Sync with Attio', 'harbor-sync-with-attio-for-woocommerce' ),
			'manage_woocommerce',
			'wcattio-settings',
			array( $this, 'render_settings_page' )
		);

		add_submenu_page(
			'wcattio-settings',
			__( 'Attio Sync Log', 'harbor-sync-with-attio-for-woocommerce' ),
			__( 'Sync Log', 'harbor-sync-with-attio-for-woocommerce' ),
			'manage_woocommerce',
			'wcattio-sync-log',
			array( 'WooAttioSync_Sync_Log', 'render_log_page' )
		);
	}

	/**
	 * Register all plugin settings with the WordPress Settings API
	 */
	public function register_settings(): void {
		// options.php requires manage_options by default; align the save path with
		// the manage_woocommerce menus so Shop Managers can actually save
		$groups = array(
			'wcattio_settings_group',
		);
		foreach ( $groups as $group ) {
			add_filter( "option_page_capability_{$group}", static fn(): string => 'manage_woocommerce' );
		}

		register_setting(
			'wcattio_settings_group',
			self::OPTION_API_KEY,
			array(
				'type'              => 'string',
				'sanitize_callback' => static function ( $value ) {
					$value = sanitize_text_field( (string) $value );
					// Sentinel submitted by the "Clear" button - erase the stored key
					if ( '__CLEAR__' === $value ) {
						return '';
					}
					// Blank submission means the user did not change the key - preserve stored value
					if ( '' === $value ) {
						return (string) get_option( 'wcattio_api_key', '' );
					}
					return $value;
				},
				'default'           => '',
			)
		);

		register_setting(
			'wcattio_settings_group',
			self::OPTION_SYNC_STATUSES,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( $this, 'sanitize_sync_statuses' ),
				'default'           => WooAttioSync_Sync_Queue::DEFAULT_SYNC_STATUSES,
			)
		);
	}

	/**
	 * Sanitize the array of order statuses to sync on
	 *
	 * @param mixed $value Raw value from the settings form
	 * @return string[] Sanitized array of WooCommerce order status slugs
	 */
	public function sanitize_sync_statuses( mixed $value ): array {
		if ( ! is_array( $value ) ) {
			return array();
		}

		$allowed = array_keys( wc_get_order_statuses() );

		return array_values(
			array_filter(
				array_map( 'sanitize_text_field', $value ),
				static fn( string $s ) => in_array( $s, $allowed, true )
			)
		);
	}

	/**
	 * Render the API key password input with inline "Test Connection" button
	 */
	public function render_api_key_field(): void {
		// "A key is configured" (constant or option) drives the placeholder copy.
		$has_key = WooAttioSync_Attio_Client::has_api_key();
		// The "Clear saved key" button only makes sense when an *option* exists to
		// clear; a key supplied via the WCATTIO_API_KEY constant cannot be cleared here.
		$has_option_key = '' !== (string) get_option( self::OPTION_API_KEY, '' );
		$placeholder    = $has_key
			? __( 'Key saved — enter a new value to replace it', 'harbor-sync-with-attio-for-woocommerce' )
			: __( 'Paste your Attio API key here', 'harbor-sync-with-attio-for-woocommerce' );
		?>
		<div class="wcattio-api-key-wrap">
			<input
				type="password"
				id="wcattio_api_key"
				name="<?php echo esc_attr( self::OPTION_API_KEY ); ?>"
				value=""
				class="regular-text"
				autocomplete="new-password"
				placeholder="<?php echo esc_attr( $placeholder ); ?>"
			/>
			<button
				type="button"
				id="wcattio-test-connection"
				class="button button-secondary"
			>
				<?php esc_html_e( 'Test Connection', 'harbor-sync-with-attio-for-woocommerce' ); ?>
			</button>
			<?php if ( $has_option_key ) : ?>
				<button
					type="button"
					id="wcattio-clear-api-key"
					class="button button-link-delete"
					data-confirm="<?php esc_attr_e( 'Clear the saved API key?', 'harbor-sync-with-attio-for-woocommerce' ); ?>"
				>
					<?php esc_html_e( 'Clear saved key', 'harbor-sync-with-attio-for-woocommerce' ); ?>
				</button>
			<?php endif; ?>
			<span id="wcattio-connection-status" class="wcattio-connection-status" aria-live="polite" aria-atomic="true"></span>
		</div>
		<p class="description">
			<?php
			printf(
				/* translators: %s: URL to Attio API keys page */
				esc_html__( 'Get your API key from %s', 'harbor-sync-with-attio-for-woocommerce' ),
				'<a href="' . esc_url( 'https://app.attio.com/settings/api-keys' ) . '" target="_blank" rel="noopener noreferrer">' .
					esc_html__( 'Attio Settings -> API Keys', 'harbor-sync-with-attio-for-woocommerce' ) .
				'</a>'
			);
			?>
		</p>
		<?php
	}

	/**
	 * Render checkboxes for which order statuses should trigger a sync
	 */
	public function render_sync_statuses_field(): void {
		$saved    = (array) get_option( self::OPTION_SYNC_STATUSES, WooAttioSync_Sync_Queue::DEFAULT_SYNC_STATUSES );
		$statuses = wc_get_order_statuses();
		?>
		<fieldset>
			<legend class="screen-reader-text">
				<?php esc_html_e( 'Sync on order status', 'harbor-sync-with-attio-for-woocommerce' ); ?>
			</legend>
			<?php foreach ( $statuses as $slug => $label ) : ?>
				<label>
					<input
						type="checkbox"
						name="<?php echo esc_attr( self::OPTION_SYNC_STATUSES ); ?>[]"
						value="<?php echo esc_attr( $slug ); ?>"
						<?php checked( in_array( $slug, $saved, true ) ); ?>
					/>
					<?php echo esc_html( $label ); ?>
				</label>
				<br>
			<?php endforeach; ?>
		</fieldset>
		<?php
	}

	/**
	 * AJAX handler: validate an Attio API key
	 */
	public function ajax_validate_key(): void {
		check_ajax_referer( 'wcattio_validate_nonce', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'harbor-sync-with-attio-for-woocommerce' ) ), 403 );
		}

		$key = sanitize_text_field( wp_unslash( $_POST['api_key'] ?? '' ) );

		if ( '' === $key ) {
			// Field was blank - test the already-configured key. Passing no argument
			// lets the client resolve the WCATTIO_API_KEY constant, then the option,
			// matching the resolution order used by background syncs.
			if ( ! WooAttioSync_Attio_Client::has_api_key() ) {
				wp_send_json_error( array( 'message' => __( 'API key is required.', 'harbor-sync-with-attio-for-woocommerce' ) ) );
			}
			$client = new WooAttioSync_Attio_Client();
		} else {
			$client = new WooAttioSync_Attio_Client( $key );
		}

		$valid = $client->validate_api_key();

		if ( $valid ) {
			wp_send_json_success( array( 'message' => __( 'Connected successfully.', 'harbor-sync-with-attio-for-woocommerce' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Could not connect. Check your API key.', 'harbor-sync-with-attio-for-woocommerce' ) ) );
		}
	}

	/**
	 * AJAX handler: kick off a bulk customer sync
	 */
	public function ajax_bulk_sync(): void {
		$this->run_bulk_sync(
			fn( WooAttioSync_Bulk_Sync $bulk ) => $bulk->start_bulk_sync(),
			__( 'A bulk customer sync is already running. Please wait for it to finish.', 'harbor-sync-with-attio-for-woocommerce' ),
			/* translators: %d: number of customers enqueued */
			__( 'Syncing %d customers in the background.', 'harbor-sync-with-attio-for-woocommerce' ),
			admin_url( 'admin.php?page=wc-status&tab=action-scheduler&s=wcattio_sync_customer&status=pending' )
		);
	}

	/**
	 * AJAX handler: kick off a bulk order sync
	 */
	public function ajax_bulk_sync_orders(): void {
		$this->run_bulk_sync(
			fn( WooAttioSync_Bulk_Sync $bulk ) => $bulk->start_order_bulk_sync(),
			__( 'A bulk order sync is already running. Please wait for it to finish.', 'harbor-sync-with-attio-for-woocommerce' ),
			/* translators: %d: number of orders enqueued */
			__( 'Syncing %d orders in the background.', 'harbor-sync-with-attio-for-woocommerce' ),
			admin_url( 'admin.php?page=wc-status&tab=action-scheduler&s=wcattio_sync_order&status=pending' )
		);
	}

	/**
	 * Shared auth + dispatch logic for bulk-sync AJAX handlers
	 *
	 * @param callable $start_fn        Calls the appropriate Bulk_Sync method; receives a WooAttioSync_Bulk_Sync instance
	 * @param string   $lock_message    User-facing error when a sync is already in progress
	 * @param string   $success_message sprintf template with a single %d placeholder for the enqueued count
	 * @param string   $actions_url     Link to the Action Scheduler queue for this sync type
	 */
	private function run_bulk_sync( callable $start_fn, string $lock_message, string $success_message, string $actions_url ): void {
		check_ajax_referer( 'wcattio_admin', 'nonce' );

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'harbor-sync-with-attio-for-woocommerce' ) ), 403 );
		}

		$bulk  = new WooAttioSync_Bulk_Sync();
		$count = $start_fn( $bulk );

		if ( $count < 0 ) {
			wp_send_json_error( array( 'message' => $lock_message ) );
		}

		wp_send_json_success(
			array(
				'message'               => sprintf( $success_message, $count ),
				'count'                 => $count,
				'scheduled_actions_url' => $actions_url,
			)
		);
	}

	/**
	 * AJAX handler: persist the onboarding notice dismissal for the current user
	 */
	public function ajax_dismiss_onboarding(): void {
		check_ajax_referer( 'wcattio_dismiss_onboarding', 'nonce' );
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array(), 403 );
		}
		update_user_meta( get_current_user_id(), 'wcattio_dismissed_onboarding', 1 );
		wp_send_json_success();
	}

	/**
	 * Render the full settings page HTML
	 */
	public function render_settings_page(): void {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'harbor-sync-with-attio-for-woocommerce' ) );
		}

		$last_customer_sync    = get_option( 'wcattio_last_customer_bulk_sync', '' );
		$last_order_sync       = get_option( 'wcattio_last_order_bulk_sync', '' );
		$customer_sync_running = WooAttioSync_Bulk_Sync::is_customer_sync_running();
		$order_sync_running    = WooAttioSync_Bulk_Sync::is_order_sync_running();
		$validate_nonce        = wp_create_nonce( 'wcattio_validate_nonce' );
		$has_api_key           = WooAttioSync_Attio_Client::has_api_key();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$current_tab = sanitize_key( wp_unslash( $_GET['tab'] ?? 'settings' ) );

		$log_instance  = new WooAttioSync_Sync_Log();
		$recent_errors = $log_instance->get_log_count(
			array(
				'status' => 'error',
				'since'  => '-24 hours',
			)
		);
		?>
		<div class="wrap">
			<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>

			<?php if ( ! $has_api_key && 'settings' === $current_tab && ! get_user_meta( get_current_user_id(), 'wcattio_dismissed_onboarding', true ) ) : ?>
				<div class="notice notice-warning is-dismissible wcattio-onboarding-notice">
					<p>
						<strong><?php esc_html_e( 'Welcome! One step to get started.', 'harbor-sync-with-attio-for-woocommerce' ); ?></strong>
						<?php esc_html_e( 'Paste your Attio API key below, click Test Connection to verify, then Save Settings.', 'harbor-sync-with-attio-for-woocommerce' ); ?>
						<a href="<?php echo esc_url( 'https://app.attio.com/settings/api-keys' ); ?>" target="_blank" rel="noopener noreferrer">
							<?php esc_html_e( 'Get your API key', 'harbor-sync-with-attio-for-woocommerce' ); ?>
						</a>
					</p>
				</div>
			<?php endif; ?>

			<?php if ( ! empty( sanitize_key( wp_unslash( $_GET['settings-updated'] ?? '' ) ) ) ) : // phpcs:ignore WordPress.Security.NonceVerification.Recommended ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Settings saved.', 'harbor-sync-with-attio-for-woocommerce' ); ?></p>
				</div>
			<?php endif; ?>

			<?php if ( $has_api_key && $recent_errors > 0 && 'settings' === $current_tab ) : ?>
				<div class="notice notice-error wcattio-health-notice is-dismissible">
					<p>
						<?php
						printf(
							wp_kses(
								/* translators: 1: error count, 2: link to sync log */
								_n(
									'%1$d sync error in the last 24 hours. %2$s',
									'%1$d sync errors in the last 24 hours. %2$s',
									$recent_errors,
									'harbor-sync-with-attio-for-woocommerce'
								),
								array( 'a' => array( 'href' => array() ) )
							),
							(int) $recent_errors,
							'<a href="' . esc_url( admin_url( 'admin.php?page=wcattio-sync-log&status_filter=error' ) ) . '">' .
								esc_html__( 'View errors', 'harbor-sync-with-attio-for-woocommerce' ) .
							'</a>'
						);
						?>
					</p>
				</div>
			<?php endif; ?>

			<?php self::render_nav_tabs( $current_tab ); ?>

			<?php
			switch ( $current_tab ) {
				case 'field-mapping':
				case 'webhook':
				case 'list-rules':
				case 'deals':
				case 'tasks':
					$this->render_pro_tab( $current_tab );
					break;
				default:
					$current_tab = 'settings';
			}

			if ( 'settings' !== $current_tab ) {
				echo '</div>';
				return;
			}
			?>

			<form method="post" action="options.php" id="wcattio-settings-form">
				<?php settings_fields( 'wcattio_settings_group' ); ?>

				<div class="wcattio-section">
					<h2><?php esc_html_e( 'API Configuration', 'harbor-sync-with-attio-for-woocommerce' ); ?></h2>
					<p><?php esc_html_e( 'Connect this site to your Attio workspace using an API key.', 'harbor-sync-with-attio-for-woocommerce' ); ?></p>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row">
								<label for="wcattio_api_key"><?php esc_html_e( 'Attio API Key', 'harbor-sync-with-attio-for-woocommerce' ); ?></label>
							</th>
							<td>
								<?php $this->render_api_key_field(); ?>
								<input type="hidden" id="wcattio-validate-nonce" value="<?php echo esc_attr( $validate_nonce ); ?>" />
							</td>
						</tr>
					</table>
				</div>

				<div class="wcattio-section">
					<h2><?php esc_html_e( 'Sync Settings', 'harbor-sync-with-attio-for-woocommerce' ); ?></h2>
					<table class="form-table" role="presentation">
						<tr>
							<th scope="row"><?php esc_html_e( 'Sync on order status', 'harbor-sync-with-attio-for-woocommerce' ); ?></th>
							<td><?php $this->render_sync_statuses_field(); ?></td>
						</tr>
					</table>
				</div>

				<?php submit_button( __( 'Save Settings', 'harbor-sync-with-attio-for-woocommerce' ) ); ?>
			</form>

			<div class="wcattio-section">
				<h2><?php esc_html_e( 'Manual Sync', 'harbor-sync-with-attio-for-woocommerce' ); ?></h2>
				<p><?php esc_html_e( 'Manually trigger a full sync of all customers or orders. Sync jobs run in the background via WooCommerce Action Scheduler.', 'harbor-sync-with-attio-for-woocommerce' ); ?></p>

				<div class="wcattio-manual-sync-actions">
					<div class="wcattio-sync-action">
						<button type="button" id="wcattio-bulk-sync-customers" class="button button-secondary" <?php disabled( $customer_sync_running ); ?>>
							<?php esc_html_e( 'Sync All Customers', 'harbor-sync-with-attio-for-woocommerce' ); ?>
						</button>
						<span id="wcattio-bulk-customers-status" class="wcattio-sync-status" aria-live="polite" aria-atomic="true">
							<?php if ( $customer_sync_running ) : ?>
								<?php esc_html_e( 'Sync in progress&hellip;', 'harbor-sync-with-attio-for-woocommerce' ); ?>
							<?php else : ?>
								<?php
								$ts = $last_customer_sync ? strtotime( $last_customer_sync ) : false;
								if ( false !== $ts ) :
									printf(
										/* translators: %s: formatted date/time */
										esc_html__( 'Last run: %s', 'harbor-sync-with-attio-for-woocommerce' ),
										esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $ts ) )
									);
								endif;
								?>
							<?php endif; ?>
						</span>
					</div>

					<div class="wcattio-sync-action">
						<button type="button" id="wcattio-bulk-sync-orders" class="button button-secondary" <?php disabled( $order_sync_running ); ?>>
							<?php esc_html_e( 'Sync All Orders', 'harbor-sync-with-attio-for-woocommerce' ); ?>
						</button>
						<span id="wcattio-bulk-orders-status" class="wcattio-sync-status" aria-live="polite" aria-atomic="true">
							<?php if ( $order_sync_running ) : ?>
								<?php esc_html_e( 'Sync in progress&hellip;', 'harbor-sync-with-attio-for-woocommerce' ); ?>
							<?php else : ?>
								<?php
								$ts = $last_order_sync ? strtotime( $last_order_sync ) : false;
								if ( false !== $ts ) :
									printf(
										/* translators: %s: formatted date/time */
										esc_html__( 'Last run: %s', 'harbor-sync-with-attio-for-woocommerce' ),
										esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), $ts ) )
									);
								endif;
								?>
							<?php endif; ?>
						</span>
					</div>
				</div>
			</div>

			<div class="wcattio-section wcattio-pro-features">
				<div class="wcattio-pro-badge"><?php esc_html_e( 'PRO', 'harbor-sync-with-attio-for-woocommerce' ); ?></div>
				<h2><?php esc_html_e( 'Unlock Pro Features', 'harbor-sync-with-attio-for-woocommerce' ); ?></h2>
				<p><?php esc_html_e( 'Upgrade to Harbor Sync with Attio for WooCommerce Pro for advanced automation and deeper CRM integration.', 'harbor-sync-with-attio-for-woocommerce' ); ?></p>
				<ul class="wcattio-pro-feature-list">
					<li><?php esc_html_e( 'Custom field mapping - map any WooCommerce field to any Attio attribute', 'harbor-sync-with-attio-for-woocommerce' ); ?></li>
					<li><?php esc_html_e( 'Real-time two-way sync - push Attio changes back to WooCommerce via webhook', 'harbor-sync-with-attio-for-woocommerce' ); ?></li>
					<li><?php esc_html_e( 'List automation - add customers to Attio lists automatically on purchase', 'harbor-sync-with-attio-for-woocommerce' ); ?></li>
					<li><?php esc_html_e( 'Priority support with 24-hour response guarantee', 'harbor-sync-with-attio-for-woocommerce' ); ?></li>
				</ul>
				<a
					href="<?php echo esc_url( 'https://harborplugins.com/plugins/attio-sync' ); ?>"
					class="button button-primary wcattio-pro-cta"
					target="_blank"
					rel="noopener noreferrer"
				>
					<?php esc_html_e( 'Upgrade to Pro', 'harbor-sync-with-attio-for-woocommerce' ); ?>
				</a>
				<p class="description wcattio-pro-cta-note">
					<?php esc_html_e( '14-day free trial — no credit card required.', 'harbor-sync-with-attio-for-woocommerce' ); ?>
				</p>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the upsell (or delegate to the Pro renderer) for a gated tab.
	 *
	 * @param string $tab Tab key: 'field-mapping' | 'webhook' | 'list-rules'.
	 */
	private function render_pro_tab( string $tab ): void {
		if ( has_action( "wcattio_render_tab_{$tab}" ) ) {
			do_action( "wcattio_render_tab_{$tab}" );
			return;
		}

		switch ( $tab ) {
			case 'field-mapping':
				$this->render_pro_upsell(
					__( 'Field Mapping', 'harbor-sync-with-attio-for-woocommerce' ),
					__( 'Map any WooCommerce field — billing city, shipping country, order note — to any Attio attribute. Keep your CRM records enriched automatically without manual data entry.', 'harbor-sync-with-attio-for-woocommerce' )
				);
				break;
			case 'webhook':
				$this->render_pro_upsell(
					__( 'Two-Way Sync Webhook', 'harbor-sync-with-attio-for-woocommerce' ),
					__( 'Push Attio record changes back to WooCommerce in real time via HMAC-verified webhook. Your CRM becomes the source of truth — no manual exports needed.', 'harbor-sync-with-attio-for-woocommerce' )
				);
				break;
			case 'list-rules':
				$this->render_pro_upsell(
					__( 'List Automation', 'harbor-sync-with-attio-for-woocommerce' ),
					__( 'Automatically add customers to an Attio list when they purchase a specific product, or by lifetime spend, order count, or recency. Run targeted campaigns without CSV exports or manual list management.', 'harbor-sync-with-attio-for-woocommerce' )
				);
				break;
			case 'deals':
				$this->render_pro_upsell(
					__( 'Deals', 'harbor-sync-with-attio-for-woocommerce' ),
					__( 'Turn every order into an Attio Deal with its value, deduplicated automatically, so your WooCommerce revenue shows up in your Attio pipeline.', 'harbor-sync-with-attio-for-woocommerce' )
				);
				break;
			case 'tasks':
				$this->render_pro_upsell(
					__( 'Tasks', 'harbor-sync-with-attio-for-woocommerce' ),
					__( 'Create Attio tasks automatically on lifecycle events — a welcome task on a first order, a follow-up when a payment fails — so nothing slips through the cracks.', 'harbor-sync-with-attio-for-woocommerce' )
				);
				break;
		}
	}

	/**
	 * Render a Pro upsell placeholder for a locked tab.
	 *
	 * @param string $feature_name  Human-readable name of the gated feature.
	 * @param string $description   Feature-specific benefit description.
	 */
	private function render_pro_upsell( string $feature_name, string $description = '' ): void {
		?>
		<div class="wcattio-section wcattio-pro-features">
			<div class="wcattio-pro-badge"><?php esc_html_e( 'PRO', 'harbor-sync-with-attio-for-woocommerce' ); ?></div>
			<h2>
				<?php
				printf(
					/* translators: %s: feature name */
					esc_html__( '%s is a Pro feature', 'harbor-sync-with-attio-for-woocommerce' ),
					esc_html( $feature_name )
				);
				?>
			</h2>
			<?php if ( '' !== $description ) : ?>
				<p><?php echo esc_html( $description ); ?></p>
			<?php endif; ?>
			<a href="<?php echo esc_url( 'https://harborplugins.com/plugins/attio-sync' ); ?>"
				class="button button-primary wcattio-pro-cta"
				target="_blank" rel="noopener noreferrer">
				<?php esc_html_e( 'Upgrade to Pro', 'harbor-sync-with-attio-for-woocommerce' ); ?>
			</a>
			<p class="description wcattio-pro-cta-note">
				<?php esc_html_e( '14-day free trial — no credit card required.', 'harbor-sync-with-attio-for-woocommerce' ); ?>
			</p>
		</div>
		<?php
	}
}
