<?php
/**
 * 247ChatMate — Frontend Assets + Render
 * • SPEED PASS 4 — RECOVERY FIX
 * • Restores matewa-intent-actions.js to upfront enqueue
 * • Keeps flow stack stable
 * • Leaves deferred map in place
 * • Exposes resolved plan mode to frontend JS
 */

defined( 'ABSPATH' ) || exit;

/* =========================================================
   ENABLE WIDGET GUARD
========================================================= */

$matewa_widget_settings = get_option( 'matewa_widget_settings', array( 'enabled' => '1' ) );
$matewa_widget_enabled  = ( ( $matewa_widget_settings['enabled'] ?? '1' ) === '1' );

if ( ! $matewa_widget_enabled ) {
	return;
}

/* =========================================================
   ENQUEUE ASSETS (DIRECT — NO HOOK)
========================================================= */

$matewa_base = plugin_dir_url( MATEWA_MAIN_FILE ) . 'public/';
$matewa_mode = function_exists( 'matewa_get_mode' ) ? matewa_get_mode() : 'free';
$matewa_phone_widget_settings = get_option( 'matewa_widget_settings', array() );
$matewa_phone_widget_settings = is_array( $matewa_phone_widget_settings ) ? $matewa_phone_widget_settings : array();
$matewa_show_country_selector = array_key_exists( 'show_country_selector', $matewa_phone_widget_settings )
	? ( '1' === (string) $matewa_phone_widget_settings['show_country_selector'] )
	: true;

/* -----------------------------
   Styles
----------------------------- */

wp_enqueue_style(
	'matewa-widget',
	$matewa_base . 'css/matewa-widget.css',
	array(),
	MATEWA_VERSION
);

/* -----------------------------
   Widget UI Bootstrap (STATIC ONLY)
----------------------------- */

wp_enqueue_script(
	'matewa-widget',
	$matewa_base . 'js/matewa-widget.js',
	array(),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   Tempo (Timing Constants)
----------------------------- */

wp_enqueue_script(
	'matewa-tempo',
	$matewa_base . 'js/matewa-tempo.js',
	array(),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   Intro Controller
----------------------------- */

wp_enqueue_script(
	'matewa-intro',
	$matewa_base . 'js/matewa-intro.js',
	array( 'matewa-tempo' ),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   Scroll Controller
----------------------------- */

wp_enqueue_script(
	'matewa-scroll',
	$matewa_base . 'js/matewa-scroll.js',
	array( 'matewa-tempo' ),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   SINGLE OPEN / CLOSE AUTHORITY
----------------------------- */

wp_enqueue_script(
	'matewa-launcher',
	$matewa_base . 'js/matewa-launcher.js',
	array(),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   FLOW CONTROLLER
----------------------------- */

wp_enqueue_script(
	'matewa-flow',
	$matewa_base . 'js/matewa-flow.js',
	array( 'matewa-tempo' ),
	MATEWA_VERSION,
	true
);

wp_localize_script(
	'matewa-flow',
	'MATEWA_PHONE_COUNTRIES',
	array(
		'remoteUrl'         => 'https://247trademate.pro/247chatmate/phone-country-pack.v1.min.json',
		'localUrl'          => $matewa_base . 'data/phone-country-pack.v1.min.json',
		'defaultCountry'    => 'gb',
		'defaultDialPrefix' => '44',
		'showSelector'      => $matewa_show_country_selector,
	)
);

/* -----------------------------
   Intent Gate
----------------------------- */

wp_enqueue_script(
	'matewa-intent-gate',
	$matewa_base . 'js/matewa-intent-gate.js',
	array( 'matewa-flow' ),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   Pro Lead Routing (Pro-only, local email only)
----------------------------- */

$matewa_pro_lead_routing_enabled = function_exists( 'matewa_pro_lead_routing_can_load_frontend' ) && matewa_pro_lead_routing_can_load_frontend();
$matewa_intent_actions_deps      = array( 'matewa-intent-gate' );

if ( $matewa_pro_lead_routing_enabled ) {
	wp_enqueue_script(
		'matewa-pro-lead-routing',
		$matewa_base . 'js/matewa-lead-routing.js',
		array( 'matewa-intent-gate' ),
		MATEWA_VERSION,
		true
	);

	wp_localize_script(
		'matewa-pro-lead-routing',
		'MATEWA_PRO_LEAD',
		array(
			'enabled'  => true,
			'ajaxUrl'  => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'matewa_pro_lead_routing' ),
			'action'   => 'matewa_send_pro_lead',
			'phoneOnlyAction' => 'matewa_send_phone_only_lead',
			'widgetOpenAction' => 'matewa_record_widget_open',
			'phoneOnlyDelayMs' => 45000,
			'siteHost' => wp_parse_url( home_url(), PHP_URL_HOST ),
		)
	);

	$matewa_intent_actions_deps[] = 'matewa-pro-lead-routing';
}

/* -----------------------------
   Intent Actions (WhatsApp composer)
----------------------------- */

wp_enqueue_script(
	'matewa-intent-actions',
	$matewa_base . 'js/matewa-intent-actions.js',
	$matewa_intent_actions_deps,
	MATEWA_VERSION,
	true
);

/* -----------------------------
   CTA Controller (Last Step Only)
----------------------------- */

wp_enqueue_script(
	'matewa-cta',
	$matewa_base . 'js/cta.js',
	array( 'matewa-flow' ),
	MATEWA_VERSION,
	true
);

/* -----------------------------
   Deferred Asset Map
----------------------------- */

wp_localize_script(
	'matewa-launcher',
	'MATEWA_DEFERRED',
	array(
		'version' => MATEWA_VERSION,
		'scripts' => array(
			'tempo'         => $matewa_base . 'js/matewa-tempo.js',
			'intro'         => $matewa_base . 'js/matewa-intro.js',
			'scroll'        => $matewa_base . 'js/matewa-scroll.js',
			'flow'          => $matewa_base . 'js/matewa-flow.js',
			'intentGate'    => $matewa_base . 'js/matewa-intent-gate.js',
			'intentActions' => $matewa_base . 'js/matewa-intent-actions.js',
			'cta'           => $matewa_base . 'js/cta.js',
		),
	)
);

/* -----------------------------
   Frontend Settings / Copy
   Exposed on launcher so deferred-loaded
   intent-actions can still read them later.
----------------------------- */

wp_localize_script(
	'matewa-launcher',
	'MATEWA_SETTINGS',
	array(
		'mode'             => $matewa_mode,
		'leadLanguageMode' => 'english',
		'siteLang'         => get_locale(),
		'businessName'     => get_bloginfo( 'name' ),
	)
);

wp_localize_script(
	'matewa-launcher',
	'MATEWA_PREBUILT',
	array(
		'en' => array(
			'greeting' => 'Hi,',
			'reached'  => 'You’ve reached us via {site}.',
			'reason'   => 'Reason for contacting:',
			'notes'    => 'Additional notes:',
			'closing'  => 'We’ll get back to you shortly.',
		),
	)
);

/* =========================================================
   RENDER WIDGET (SINGLE INSTANCE)
   FRONTENDRENDERHOOKFIX1
   Uses wp_body_open first, with wp_footer as a safe fallback for
   themes/builders that do not fire wp_body_open reliably.
========================================================= */

if ( ! function_exists( 'matewa_include_frontend_widget_markup' ) ) {
	function matewa_include_frontend_widget_markup() {
		static $matewa_markup_included = false;

		if ( $matewa_markup_included ) {
			return;
		}

		if ( is_admin() ) {
			return;
		}

		if ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) {
			return;
		}

		if ( function_exists( 'wp_is_json_request' ) && wp_is_json_request() ) {
			return;
		}

		$matewa_file = MATEWA_PLUGIN_DIR . 'public/matewa-render.php';
		if ( is_readable( $matewa_file ) ) {
			$matewa_markup_included = true;
			include $matewa_file;
		}
	}
}

add_action( 'wp_body_open', 'matewa_include_frontend_widget_markup', 10 );
add_action( 'wp_footer', 'matewa_include_frontend_widget_markup', 5 );
