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

/**
 * Frontend: enqueues the capture script and passes config.
 */
class BW_Lead_AI_Frontend {

	private static $instance = null;

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

	public function register() {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
		add_action( 'wp_head', array( $this, 'hide_tracking_fields' ), 100 );
	}

	public function enqueue() {
		if ( is_admin() ) {
			return;
		}
		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', $this->client_config() );
		wp_enqueue_script( 'bw-lead-ai-capture' );

		// The interaction-event engine is a separate file loaded only when at
		// least one event type is switched on, so sites that don't use it pay
		// nothing — no extra request, no listeners, no third-party video APIs.
		$settings = BW_Lead_AI_Settings::get();
		if ( ! empty( BW_Lead_AI_Settings::parse_event_types( $settings['event_types'] ) ) ) {
			wp_enqueue_script(
				'bw-lead-ai-events',
				BW_LEAD_AI_URL . 'assets/js/events.js',
				array( 'bw-lead-ai-capture' ),
				BW_LEAD_AI_VERSION,
				true
			);
		}

		// Same rule for handoff: nothing is downloaded unless it is switched on
		// and there is somewhere configured to hand off to.
		if ( BW_Lead_AI_Settings::handoff_enabled( $settings ) ) {
			wp_enqueue_script(
				'bw-lead-ai-handoff',
				BW_LEAD_AI_URL . 'assets/js/handoff.js',
				array( 'bw-lead-ai-capture' ),
				BW_LEAD_AI_VERSION,
				true
			);
		}
	}

	public function client_config() {
		$settings = BW_Lead_AI_Settings::get();

		$targets = array();
		foreach ( $settings['field_targets'] as $key => $row ) {
			$targets[ $key ] = array(
				'attr' => isset( $row['attr'] ) ? (string) $row['attr'] : '',
				'val'  => isset( $row['val'] ) ? (string) $row['val'] : '',
			);
		}

		$aliases = BW_Lead_AI_Settings::parse_parameter_aliases( $settings['parameter_aliases'] );

		return array(
			'version'               => BW_LEAD_AI_VERSION,
			'debug'                 => ! empty( $settings['debug'] ),
			'dimensions'            => $aliases['standard'],
			'customDimensions'      => $aliases['custom'],
			'clickIds'              => BW_Lead_AI_Settings::parse_click_ids( $settings['click_ids'] ),
			'channels'              => BW_Lead_AI_Settings::parse_channels( $settings['channels'] ),
			'referrerClasses'       => BW_Lead_AI_Settings::parse_referrer_classification( $settings['referrer_classification'] ),
			'sourceMediumSeparator' => (string) $settings['source_medium_separator'],
			'captureGaClientId'     => ! empty( $settings['capture_ga_client_id'] ),
			'targets'               => $targets,
			'handoff'               => BW_Lead_AI_Settings::handoff_enabled( $settings )
				? array(
					'endpoint'   => rest_url( BW_Lead_AI_Handoff_REST::NAMESPACE_V1 . '/handoff' ),
					'param'      => (string) $settings['handoff_param'],
					'domains'    => BW_Lead_AI_Settings::parse_handoff_domains( $settings ),
					'datapoints' => BW_Lead_AI_Settings::parse_handoff_datapoints( $settings ),
				)
				: null,
			'events'                => array(
				'enabled'     => BW_Lead_AI_Settings::parse_event_types( $settings['event_types'] ),
				'downloads'   => BW_Lead_AI_Settings::parse_csv_list( $settings['event_downloads'] ),
				'socialHosts' => BW_Lead_AI_Settings::parse_csv_list( $settings['event_social_hosts'] ),
				'videoMarks'  => BW_Lead_AI_Settings::parse_percent_list( $settings['event_video_milestones'] ),
				'scrollMarks' => BW_Lead_AI_Settings::parse_percent_list( $settings['event_scroll_thresholds'] ),
				'custom'      => BW_Lead_AI_Settings::parse_custom_events( $settings['event_custom_selectors'] ),
			),
		);
	}

	public function hide_tracking_fields() {
		if ( is_admin() ) {
			return;
		}
		$settings = BW_Lead_AI_Settings::get();
		$show     = current_user_can( 'manage_options' ) && ! empty( $settings['debug'] );
		$display  = $show ? 'block' : 'none';

		$selectors = array();
		foreach ( $settings['field_targets'] as $row ) {
			if ( empty( $row['attr'] ) || empty( $row['val'] ) ) {
				continue;
			}
			$attr = $row['attr'];
			$val  = $row['val'];
			if ( 'id' === $attr ) {
				$selectors[] = '#' . $val;
			} elseif ( 'class' === $attr ) {
				$selectors[] = '.' . $val;
			} elseif ( 'name' === $attr ) {
				$selectors[] = '[name="' . $val . '"]';
			} elseif ( 'selector' === $attr ) {
				$selectors[] = $val;
			}
		}
		if ( empty( $selectors ) ) {
			return;
		}
		// Sanitize each selector before output.
		$safe = array();
		foreach ( $selectors as $sel ) {
			// Allow a permissive but CSS-only character set.
			$sel = preg_replace( '/[^a-zA-Z0-9_\-\.\#\[\]\=\"\' :\(\),\*>~\+]/', '', $sel );
			if ( '' !== $sel ) {
				$safe[] = $sel;
			}
		}
		if ( empty( $safe ) ) {
			return;
		}
		echo '<style id="bw-lead-ai-hide">' . esc_html( implode( ', ', $safe ) ) . ' { display: ' . esc_html( $display ) . "; }</style>\n";
	}
}
