<?php
defined( 'ABSPATH' ) || exit;

/**
 * Admin UI: settings page with Settings / Targets / UTM Builder / Test / Help tabs.
 */
class BW_Lead_AI_Admin {

	const PAGE_SLUG = 'bw-lead-ai';

	private static $instance = null;

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

	public function register() {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	public function menu() {
		add_options_page(
			__( 'BW Lead Attribution Intelligence', 'bw-lead-ai' ),
			__( 'BW Lead AI', 'bw-lead-ai' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render_page' )
		);
	}

	public function enqueue( $hook ) {
		if ( 'settings_page_' . self::PAGE_SLUG !== $hook ) {
			return;
		}
		wp_enqueue_style(
			'bw-lead-ai-admin',
			BW_LEAD_AI_URL . 'assets/css/admin.css',
			array(),
			BW_LEAD_AI_VERSION
		);
		wp_register_script(
			'bw-lead-ai-capture',
			BW_LEAD_AI_URL . 'assets/js/capture.js',
			array(),
			BW_LEAD_AI_VERSION,
			true
		);
		wp_localize_script( 'bw-lead-ai-capture', 'bwLeadAI', BW_Lead_AI_Frontend::instance()->client_config() );
		wp_register_script(
			'bw-lead-ai-admin-test',
			BW_LEAD_AI_URL . 'assets/js/admin-test.js',
			array( 'bw-lead-ai-capture' ),
			BW_LEAD_AI_VERSION,
			true
		);
		wp_register_script(
			'bw-lead-ai-utm-builder',
			BW_LEAD_AI_URL . 'assets/js/utm-builder.js',
			array(),
			BW_LEAD_AI_VERSION,
			true
		);
	}

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$tab = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'settings'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$tabs = array(
			'settings' => __( 'Settings', 'bw-lead-ai' ),
			'targets'  => __( 'Form Fields', 'bw-lead-ai' ),
			'utm'      => __( 'UTM Builder', 'bw-lead-ai' ),
			'test'     => __( 'Test', 'bw-lead-ai' ),
			'help'     => __( 'Help', 'bw-lead-ai' ),
		);
		if ( ! isset( $tabs[ $tab ] ) ) {
			$tab = 'settings';
		}
		echo '<div class="wrap bw-lead-ai">';
		echo '<h1>' . esc_html__( 'BW Lead Attribution Intelligence', 'bw-lead-ai' ) . '</h1>';
		echo '<h2 class="nav-tab-wrapper">';
		foreach ( $tabs as $key => $label ) {
			$class = ( $tab === $key ) ? ' nav-tab-active' : '';
			$url   = add_query_arg(
				array(
					'page' => self::PAGE_SLUG,
					'tab'  => $key,
				),
				admin_url( 'options-general.php' )
			);
			echo '<a class="nav-tab' . esc_attr( $class ) . '" href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
		}
		echo '</h2>';

		switch ( $tab ) {
			case 'targets':
				$this->render_targets_tab();
				break;
			case 'utm':
				$this->render_utm_tab();
				break;
			case 'test':
				$this->render_test_tab();
				break;
			case 'help':
				$this->render_help_tab();
				break;
			case 'settings':
			default:
				$this->render_settings_tab();
				break;
		}
		echo '</div>';
	}

	private function render_settings_tab() {
		$settings = BW_Lead_AI_Settings::get();
		$opt      = esc_attr( BW_LEAD_AI_OPTION );
		$standard_list = '<code>' . implode( '</code>, <code>', BW_Lead_AI_Settings::STANDARD_ALIAS_KEYS ) . '</code>';
		?>
		<form action="options.php" method="post">
			<?php settings_fields( BW_Lead_AI_Settings::OPTION_GROUP ); ?>

			<p class="description" style="max-width: 900px;"><?php
				echo wp_kses(
					__( 'All mapping sections share one format: <code>label : value1, value2, ...</code>. One rule per line. Rules are walked in order — earlier rules win over later ones when both could match.', 'bw-lead-ai' ),
					array( 'code' => array() )
				);
				?></p>

			<?php
			$aliases       = BW_Lead_AI_Settings::parse_parameter_aliases( $settings['parameter_aliases'] );
			$source_val    = implode( ', ', $aliases['standard']['source'] );
			$medium_val    = implode( ', ', $aliases['standard']['medium'] );
			$other_lines   = array();
			foreach ( array( 'campaign', 'term', 'content', 'adgroup' ) as $std_key ) {
				if ( ! empty( $aliases['standard'][ $std_key ] ) ) {
					$other_lines[] = $std_key . ' : ' . implode( ', ', $aliases['standard'][ $std_key ] );
				}
			}
			foreach ( $aliases['custom'] as $cust_key => $cust_vals ) {
				$other_lines[] = $cust_key . ' : ' . implode( ', ', $cust_vals );
			}
			$other_text = implode( "\n", $other_lines );
			?>
			<details class="bw-lead-ai-section" open>
				<summary><h2><?php esc_html_e( 'Parameter Aliases', 'bw-lead-ai' ); ?></h2></summary>
				<p class="description"><?php
					echo wp_kses(
						__( '<strong>Source</strong> and <strong>Medium</strong> are required — without them nothing else can be attributed, so they live in their own inputs and cannot be deleted. Enter URL parameter names comma-separated; earlier aliases win. Order matters: put <code>utm_source</code> first to prefer UTMs over custom conventions.', 'bw-lead-ai' ),
						array( 'code' => array(), 'strong' => array() )
					);
					?></p>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><label for="bw-lead-ai-pa-source"><?php esc_html_e( 'Source', 'bw-lead-ai' ); ?></label></th>
						<td><input type="text" id="bw-lead-ai-pa-source" name="<?php echo $opt; ?>[parameter_aliases_source]" value="<?php echo esc_attr( $source_val ); ?>" class="large-text" placeholder="utm_source, source, src"></td>
					</tr>
					<tr>
						<th scope="row"><label for="bw-lead-ai-pa-medium"><?php esc_html_e( 'Medium', 'bw-lead-ai' ); ?></label></th>
						<td><input type="text" id="bw-lead-ai-pa-medium" name="<?php echo $opt; ?>[parameter_aliases_medium]" value="<?php echo esc_attr( $medium_val ); ?>" class="large-text" placeholder="utm_medium, medium, med"></td>
					</tr>
				</table>
				<p class="description" style="margin-top: 16px;"><?php
					echo wp_kses(
						__( '<strong>Other dimensions &amp; custom parameters.</strong> One per line, format <code>label : param1, param2</code>. The remaining built-ins are <code>campaign</code>, <code>term</code>, <code>content</code>, <code>adgroup</code>. Any <em>other</em> label becomes a <strong>custom dimension</strong> exposed as a merge tag <code>{bw:your_label}</code>.', 'bw-lead-ai' ),
						array( 'code' => array(), 'strong' => array(), 'em' => array() )
					);
					?></p>
				<p class="description"><?php
					echo wp_kses(
						__( 'Example — add a row like <code>match_type : mt, match, utm_match_type</code> to track match type from any of those URL parameters, then use <code>{bw:match_type}</code> in a hidden form field.', 'bw-lead-ai' ),
						array( 'code' => array() )
					);
					?></p>
				<textarea name="<?php echo $opt; ?>[parameter_aliases_other]" rows="8" class="large-text code" placeholder="campaign : utm_campaign, cmp&#10;match_type : mt, utm_match_type"><?php echo esc_textarea( $other_text ); ?></textarea>
			</details>

			<details class="bw-lead-ai-section">
				<summary><h2><?php esc_html_e( 'Default Referrer Classification', 'bw-lead-ai' ); ?></h2></summary>
				<p class="description"><?php
					echo wp_kses(
						__( 'When a visit has no UTM tags and no click-ID, the referring hostname is used to guess the medium. The label on the left becomes the visit medium. This is a <strong>fallback</strong> only — explicit UTMs (<code>utm_medium=cpc</code>) and click-IDs always override these rules. Hostname matches are suffix-aware, so <code>google</code> matches <code>www.google.co.uk</code>.', 'bw-lead-ai' ),
						array( 'code' => array(), 'strong' => array() )
					);
					?></p>
				<p class="description"><?php
					echo wp_kses(
						__( 'Example — add <code>ai : openai.com, gemini.google.com, claude.ai, perplexity.ai</code> to classify AI-referrer traffic under the <code>ai</code> medium.', 'bw-lead-ai' ),
						array( 'code' => array() )
					);
					?></p>
				<textarea name="<?php echo $opt; ?>[referrer_classification]" rows="6" class="large-text code" placeholder="organic : google, bing&#10;ai : openai.com, claude.ai"><?php echo esc_textarea( $settings['referrer_classification'] ); ?></textarea>
			</details>

			<details class="bw-lead-ai-section">
				<summary><h2><?php esc_html_e( 'Click-ID Inference', 'bw-lead-ai' ); ?></h2></summary>
				<p class="description"><?php
					echo wp_kses(
						__( 'When a URL contains one of these click-ID parameters and no explicit UTMs are set, the visit is tagged with the <code>source/medium</code> on the left. Format per line: <code>source/medium : param1, param2</code>.', 'bw-lead-ai' ),
						array( 'code' => array() )
					);
					?></p>
				<textarea name="<?php echo $opt; ?>[click_ids]" rows="8" class="large-text code" placeholder="google/cpc : gclid, gclsrc&#10;facebook/social : fbclid"><?php echo esc_textarea( $settings['click_ids'] ); ?></textarea>
			</details>

			<details class="bw-lead-ai-section">
				<summary><h2><?php esc_html_e( 'Channel Mappings', 'bw-lead-ai' ); ?></h2></summary>
				<p class="description"><?php
					echo wp_kses(
						__( 'Map <code>source / medium</code> combinations to friendly channel labels (e.g. "Google Ads"). Rules are checked top-to-bottom; the first match wins. Unmatched visits fall back to the raw <code>source / medium</code> string.', 'bw-lead-ai' ),
						array( 'code' => array() )
					);
					?></p>
				<p class="description"><?php
					echo wp_kses(
						__( 'Wildcards: use <code>*</code> to match any source or medium. In the label, <code>{bw:source}</code> and <code>{bw:medium}</code> are substituted with the actual visit values (useful for generic rules like <code>{bw:source} : */referral</code>). Exposed as merge tags <code>{bw:channel}</code> and <code>{bw:first_channel}</code>.', 'bw-lead-ai' ),
						array( 'code' => array() )
					);
					?></p>
				<textarea name="<?php echo $opt; ?>[channels]" rows="14" class="large-text code" placeholder="Google Ads : google/cpc, google/ppc&#10;{bw:source} : */referral"><?php echo esc_textarea( $settings['channels'] ); ?></textarea>
			</details>

			<details class="bw-lead-ai-section">
				<summary><h2><?php esc_html_e( 'Formatting & Debug', 'bw-lead-ai' ); ?></h2></summary>
				<table class="form-table" role="presentation">
					<tr><th scope="row"><label for="source_medium_separator"><?php esc_html_e( 'Source / medium separator', 'bw-lead-ai' ); ?></label></th>
						<td><input type="text" id="source_medium_separator" name="<?php echo esc_attr( BW_LEAD_AI_OPTION ); ?>[source_medium_separator]" value="<?php echo esc_attr( $settings['source_medium_separator'] ); ?>" class="small-text"> <span class="description"><?php esc_html_e( 'Used when rendering {bw:source_medium}. Default: " / "', 'bw-lead-ai' ); ?></span></td>
					</tr>
					<tr><th scope="row"><?php esc_html_e( 'Debug mode', 'bw-lead-ai' ); ?></th>
						<td><label><input type="checkbox" name="<?php echo esc_attr( BW_LEAD_AI_OPTION ); ?>[debug]" value="1" <?php checked( 1, (int) $settings['debug'] ); ?>> <?php esc_html_e( 'Log capture activity to the browser console and expose window.BWLeadAI.', 'bw-lead-ai' ); ?></label></td>
					</tr>
				</table>
			</details>

			<?php submit_button(); ?>
		</form>
		<?php
	}

	private function render_targets_tab() {
		$settings = BW_Lead_AI_Settings::get();
		$targets  = $settings['field_targets'];
		$labels   = array(
			'summary'    => __( 'Full summary', 'bw-lead-ai' ),
			'source'     => __( 'Source (last)', 'bw-lead-ai' ),
			'medium'     => __( 'Medium (last)', 'bw-lead-ai' ),
			'sources'    => __( 'Sources (all, comma-joined)', 'bw-lead-ai' ),
			'terms'      => __( 'Terms (all, comma-joined)', 'bw-lead-ai' ),
			'first_page' => __( 'First landing page', 'bw-lead-ai' ),
		);
		?>
		<form action="options.php" method="post">
			<?php settings_fields( BW_Lead_AI_Settings::OPTION_GROUP ); ?>

			<?php foreach ( array_keys( BW_Lead_AI_Settings::defaults() ) as $hidden_key ) : ?>
				<?php if ( in_array( $hidden_key, array( 'field_targets' ), true ) ) continue; ?>
				<?php $val = $settings[ $hidden_key ]; ?>
				<?php if ( is_array( $val ) ) continue; ?>
				<input type="hidden" name="<?php echo esc_attr( BW_LEAD_AI_OPTION ); ?>[<?php echo esc_attr( $hidden_key ); ?>]" value="<?php echo esc_attr( $val ); ?>">
			<?php endforeach; ?>

			<h2><?php esc_html_e( 'Legacy form-field targets', 'bw-lead-ai' ); ?></h2>
			<div class="notice notice-info inline" style="margin: 12px 0;">
				<p><strong><?php esc_html_e( 'Using Gravity Forms?', 'bw-lead-ai' ); ?></strong>
				<?php esc_html_e( 'You do not need this tab. Use merge tags like {bw:source_medium} as hidden-field default values instead — they are more flexible and easier to maintain. See the Help tab for setup instructions.', 'bw-lead-ai' ); ?></p>
			</div>
			<p class="description">
				<?php esc_html_e( 'For non-Gravity-Forms setups only. These targets attach tracking data to form fields by CSS selector, id, class, or name attribute.', 'bw-lead-ai' ); ?>
			</p>
			<table class="form-table" role="presentation">
				<?php foreach ( $labels as $key => $label ) : ?>
					<?php $row = isset( $targets[ $key ] ) ? $targets[ $key ] : array( 'attr' => '', 'val' => '' ); ?>
					<tr>
						<th scope="row"><?php echo esc_html( $label ); ?></th>
						<td>
							<select name="<?php echo esc_attr( BW_LEAD_AI_OPTION ); ?>[field_targets][<?php echo esc_attr( $key ); ?>][attr]">
								<option value=""><?php esc_html_e( '(none)', 'bw-lead-ai' ); ?></option>
								<?php
								foreach ( array(
									'id'       => __( 'Field ID', 'bw-lead-ai' ),
									'class'    => __( 'CSS class', 'bw-lead-ai' ),
									'name'     => __( 'Field name', 'bw-lead-ai' ),
									'selector' => __( 'CSS selector', 'bw-lead-ai' ),
								) as $ak => $al ) {
									printf(
										'<option value="%1$s"%2$s>%3$s</option>',
										esc_attr( $ak ),
										selected( $row['attr'], $ak, false ),
										esc_html( $al )
									);
								}
								?>
							</select>
							<input type="text" name="<?php echo esc_attr( BW_LEAD_AI_OPTION ); ?>[field_targets][<?php echo esc_attr( $key ); ?>][val]" value="<?php echo esc_attr( $row['val'] ); ?>" class="regular-text">
						</td>
					</tr>
				<?php endforeach; ?>
			</table>

			<?php submit_button(); ?>
		</form>
		<?php
	}

	private function render_utm_tab() {
		wp_enqueue_script( 'bw-lead-ai-utm-builder' );
		wp_localize_script(
			'bw-lead-ai-utm-builder',
			'bwLeadAIUtm',
			array(
				'home' => home_url(),
				'rest' => rest_url( BW_Lead_AI_REST::NAMESPACE_V1 . '/links' ),
				'nonce' => wp_create_nonce( 'wp_rest' ),
			)
		);
		$options = get_option( BW_LEAD_AI_UTM_OPTION, array() );
		if ( ! is_array( $options ) ) {
			$options = array();
		}
		?>
		<form action="options.php" method="post">
			<?php settings_fields( BW_Lead_AI_Settings::OPTION_GROUP . '_utm' ); ?>
			<h2><?php esc_html_e( 'UTM Tracking Links', 'bw-lead-ai' ); ?></h2>
			<p class="description"><?php esc_html_e( 'Optional builder for outbound campaign URLs. Fill in fields; the tracked URL below updates live. Copy and use in your ad platforms.', 'bw-lead-ai' ); ?></p>
			<div class="bw-lead-ai-utm-items">
				<?php foreach ( $options as $index => $item ) :
					$item = wp_parse_args(
						is_array( $item ) ? $item : array(),
						array(
							'link_to_uri'  => home_url(),
							'utm_source'   => '',
							'utm_medium'   => '',
							'utm_campaign' => '',
							'utm_term'     => '',
							'utm_content'  => '',
							'note'         => '',
						)
					);
					?>
					<div class="bw-lead-ai-utm-item">
						<table class="form-table" role="presentation">
							<tbody>
							<?php
							$fields = array(
								'link_to_uri'  => __( 'Linked-to URL', 'bw-lead-ai' ),
								'utm_source'   => __( 'UTM Source', 'bw-lead-ai' ),
								'utm_medium'   => __( 'UTM Medium', 'bw-lead-ai' ),
								'utm_campaign' => __( 'UTM Campaign', 'bw-lead-ai' ),
								'utm_term'     => __( 'UTM Term', 'bw-lead-ai' ),
								'utm_content'  => __( 'UTM Content', 'bw-lead-ai' ),
							);
							foreach ( $fields as $fk => $fl ) :
								?>
								<tr>
									<th scope="row"><?php echo esc_html( $fl ); ?></th>
									<td><input type="text" name="<?php echo esc_attr( BW_LEAD_AI_UTM_OPTION ); ?>[<?php echo (int) $index; ?>][<?php echo esc_attr( $fk ); ?>]" value="<?php echo esc_attr( $item[ $fk ] ); ?>" class="regular-text bw-lead-ai-utm-input"></td>
								</tr>
								<?php
							endforeach;
							?>
							<tr>
								<th scope="row"><?php esc_html_e( 'Tracked URL', 'bw-lead-ai' ); ?></th>
								<td><input type="text" data-tracked-uri class="large-text" readonly> <button type="button" class="button bw-lead-ai-copy" data-target="data-tracked-uri"><?php esc_html_e( 'Copy', 'bw-lead-ai' ); ?></button></td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Parameters only', 'bw-lead-ai' ); ?></th>
								<td><input type="text" data-parameters class="large-text" readonly> <button type="button" class="button bw-lead-ai-copy" data-target="data-parameters"><?php esc_html_e( 'Copy', 'bw-lead-ai' ); ?></button></td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Note', 'bw-lead-ai' ); ?></th>
								<td><textarea name="<?php echo esc_attr( BW_LEAD_AI_UTM_OPTION ); ?>[<?php echo (int) $index; ?>][note]" rows="3" class="large-text"><?php echo esc_textarea( $item['note'] ); ?></textarea></td>
							</tr>
							<tr><td colspan="2"><button type="button" class="button bw-lead-ai-utm-open"><?php esc_html_e( 'Open tracked URL', 'bw-lead-ai' ); ?></button> <button type="button" class="button bw-lead-ai-utm-remove"><?php esc_html_e( 'Remove', 'bw-lead-ai' ); ?></button></td></tr>
							</tbody>
						</table>
						<hr>
					</div>
				<?php endforeach; ?>
			</div>
			<p><button type="button" class="button button-secondary bw-lead-ai-utm-add"><?php esc_html_e( 'Add tracking item', 'bw-lead-ai' ); ?></button></p>
			<?php submit_button(); ?>
		</form>
		<?php
	}

	private function render_test_tab() {
		wp_enqueue_script( 'bw-lead-ai-capture' );
		wp_enqueue_script( 'bw-lead-ai-admin-test' );
		?>
		<h2><?php esc_html_e( 'Live Capture State', 'bw-lead-ai' ); ?></h2>
		<p class="description"><?php esc_html_e( 'Shows the tracking state stored in your browser right now.', 'bw-lead-ai' ); ?></p>

		<div class="bw-lead-ai-test">
			<div class="bw-lead-ai-test-controls">
				<h3><?php esc_html_e( 'URL Simulator', 'bw-lead-ai' ); ?></h3>
				<p class="description"><?php esc_html_e( 'Type any URL to see how the plugin would classify it — without navigating or storing anything.', 'bw-lead-ai' ); ?></p>
				<p>
					<input type="text" id="bw-lead-ai-sim-url" class="large-text" placeholder="https://yoursite.com/landing?utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=spring-sale">
				</p>
				<p>
					<button type="button" class="button button-primary" id="bw-lead-ai-sim-run"><?php esc_html_e( 'Simulate', 'bw-lead-ai' ); ?></button>
					<button type="button" class="button" id="bw-lead-ai-sim-open"><?php esc_html_e( 'Open in new tab', 'bw-lead-ai' ); ?></button>
				</p>
				<div id="bw-lead-ai-sim-result"></div>
			</div>

			<div class="bw-lead-ai-test-panels">
				<h3><?php esc_html_e( 'Resolved merge tags (what forms would submit)', 'bw-lead-ai' ); ?></h3>
				<div id="bw-lead-ai-resolved" class="bw-lead-ai-panel">(loading)</div>

				<h3><?php esc_html_e( 'Summary counters', 'bw-lead-ai' ); ?></h3>
				<div id="bw-lead-ai-summary" class="bw-lead-ai-panel">(loading)</div>

				<details>
					<summary><?php esc_html_e( 'Visit history (JSON)', 'bw-lead-ai' ); ?></summary>
					<pre id="bw-lead-ai-visits" class="bw-lead-ai-pre">(loading)</pre>
				</details>

				<details>
					<summary><?php esc_html_e( 'Raw localStorage', 'bw-lead-ai' ); ?></summary>
					<pre id="bw-lead-ai-raw" class="bw-lead-ai-pre">(loading)</pre>
				</details>

				<p style="margin-top: 16px;">
					<button type="button" class="button" id="bw-lead-ai-refresh"><?php esc_html_e( 'Refresh state', 'bw-lead-ai' ); ?></button>
					<button type="button" class="button button-link-delete" id="bw-lead-ai-clear"><?php esc_html_e( 'Clear all tracking storage', 'bw-lead-ai' ); ?></button>
				</p>
			</div>
		</div>
		<?php
	}

	private function render_help_tab() {
		?>
		<h2><?php esc_html_e( 'Which merge tag should I use?', 'bw-lead-ai' ); ?></h2>
		<p><?php esc_html_e( 'Choose based on what you want to send to your CRM or email platform:', 'bw-lead-ai' ); ?></p>
		<table class="widefat striped" style="max-width: 800px;">
			<thead>
				<tr>
					<th><?php esc_html_e( 'I want to...', 'bw-lead-ai' ); ?></th>
					<th><?php esc_html_e( 'Use this merge tag', 'bw-lead-ai' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td><?php esc_html_e( 'Send one "Lead Source" field to Salesforce / HubSpot', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:source_medium}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'See which campaign generated the lead', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:campaign}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'See which keyword triggered the ad', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:term}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'Know what page they first landed on', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:first_page}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'Know what page they submitted the form on', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:submit_page}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'Compare the first vs. last source for multi-touch', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:first_source}</code> + <code>{bw:source}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'Dump the full attribution history into a notes field', 'bw-lead-ai' ); ?></td>
					<td><code>{bw:summary}</code></td>
				</tr>
				<tr>
					<td><?php esc_html_e( 'Track a custom parameter (e.g. match type)', 'bw-lead-ai' ); ?></td>
					<td><?php esc_html_e( 'Add a row in Parameter Aliases with a non-standard label — it becomes {bw:your_key} automatically.', 'bw-lead-ai' ); ?></td>
				</tr>
			</tbody>
		</table>

		<h2 style="margin-top: 24px;"><?php esc_html_e( 'All available merge tags', 'bw-lead-ai' ); ?></h2>
		<p><?php esc_html_e( 'Drop a Hidden field into your Gravity Form and set its default value to any tag below. The plugin replaces them with live tracking data before the form submits.', 'bw-lead-ai' ); ?></p>
		<table class="widefat striped" style="max-width: 800px;">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Merge tag', 'bw-lead-ai' ); ?></th>
					<th><?php esc_html_e( 'Description', 'bw-lead-ai' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr><td><code>{bw:source}</code></td><td><?php esc_html_e( 'Last visit source (e.g. google, facebook)', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:medium}</code></td><td><?php esc_html_e( 'Last visit medium (e.g. cpc, organic, social)', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:source_medium}</code></td><td><?php esc_html_e( 'Combined "source / medium" (configurable separator)', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:channel}</code></td><td><?php esc_html_e( 'Friendly channel label for the last visit, resolved from Channel Mappings (e.g. "Google Ads", "Email", "Direct"). Falls back to raw source / medium if no rule matches.', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:campaign}</code></td><td><?php esc_html_e( 'Last visit campaign name', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:term}</code></td><td><?php esc_html_e( 'Last visit keyword / term', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:content}</code></td><td><?php esc_html_e( 'Last visit ad content / creative', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:adgroup}</code></td><td><?php esc_html_e( 'Last visit ad group', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:first_page}</code></td><td><?php esc_html_e( 'First-ever landing page URL', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:last_page}</code></td><td><?php esc_html_e( 'Most recent landing page URL', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:submit_page}</code></td><td><?php esc_html_e( 'Page URL where the form was submitted (resolved live)', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:first_source}</code></td><td><?php esc_html_e( 'First-ever visit source', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:first_medium}</code></td><td><?php esc_html_e( 'First-ever visit medium', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:first_channel}</code></td><td><?php esc_html_e( 'Friendly channel label for the first visit.', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:visits}</code></td><td><?php esc_html_e( 'Total visit count', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:pages}</code></td><td><?php esc_html_e( 'Total page view count', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:tagged_visits}</code></td><td><?php esc_html_e( 'Number of visits that had UTM/click-ID tags', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:summary}</code></td><td><?php esc_html_e( 'Full attribution summary (dates, all sources, visit history)', 'bw-lead-ai' ); ?></td></tr>
				<tr><td><code>{bw:summary_detailed}</code></td><td><?php esc_html_e( 'Like {bw:summary} but journey expands to list every page visited within each touchpoint, including form submissions', 'bw-lead-ai' ); ?></td></tr>
				<?php
				$aliases = BW_Lead_AI_Settings::parse_parameter_aliases( BW_Lead_AI_Settings::get()['parameter_aliases'] );
				if ( ! empty( $aliases['custom'] ) ) {
					foreach ( $aliases['custom'] as $ckey => $cvals ) {
						printf(
							'<tr><td><code>{bw:%1$s}</code></td><td>%2$s <code>%3$s</code></td></tr>',
							esc_html( $ckey ),
							esc_html__( 'Custom dimension, populated from URL parameters:', 'bw-lead-ai' ),
							esc_html( implode( ', ', $cvals ) )
						);
					}
				}
				?>
			</tbody>
		</table>

		<h2 style="margin-top: 24px;"><?php esc_html_e( 'Setup example: Salesforce', 'bw-lead-ai' ); ?></h2>
		<ol>
			<li><?php esc_html_e( 'Add a Hidden field to your form, set default value to {bw:source_medium}', 'bw-lead-ai' ); ?></li>
			<li><?php esc_html_e( 'Add another Hidden field, set default value to {bw:summary}', 'bw-lead-ai' ); ?></li>
			<li><?php esc_html_e( 'Map both to your Salesforce fields in the GF Salesforce add-on.', 'bw-lead-ai' ); ?></li>
		</ol>

		<h2 style="margin-top: 24px;"><?php esc_html_e( 'Non-Gravity-Forms plugins', 'bw-lead-ai' ); ?></h2>
		<p><?php esc_html_e( 'Use the Form Fields tab to target hidden fields by id, class, name, or CSS selector. This works with any form plugin that renders standard HTML inputs.', 'bw-lead-ai' ); ?></p>

		<h2 style="margin-top: 24px;"><?php esc_html_e( 'How attribution works', 'bw-lead-ai' ); ?></h2>
		<p><?php esc_html_e( 'The plugin tracks three levels of attribution:', 'bw-lead-ai' ); ?></p>
		<ul class="ul-disc" style="margin-left: 2em;">
			<li><strong><?php esc_html_e( 'First touch', 'bw-lead-ai' ); ?></strong> — <?php esc_html_e( 'the very first interaction that brought the visitor to your site ({bw:first_source}, {bw:first_medium}, {bw:first_page}). Never overwritten.', 'bw-lead-ai' ); ?></li>
			<li><strong><?php esc_html_e( 'Last touch', 'bw-lead-ai' ); ?></strong> — <?php esc_html_e( 'the most recent campaign click ({bw:source}, {bw:medium}, etc.). Updated whenever the visitor returns with new UTM parameters or a click ID.', 'bw-lead-ai' ); ?></li>
			<li><strong><?php esc_html_e( 'Full journey', 'bw-lead-ai' ); ?></strong> — <?php esc_html_e( 'all touchpoints stored in the visit history ({bw:summary}). Useful for multi-touch attribution reporting.', 'bw-lead-ai' ); ?></li>
		</ul>
		<?php
	}
}
