<?php
/**
 * 247ChatMate — Frontend Render
 * BASELINE RESTORE — SCROLL SAFE (LOCKED)
 * + LICENSE & VERTICAL ENFORCEMENT (SERVER AUTHORITY)
 * + FULL i18n SYSTEM COPY (NO HARDCODED STRINGS)
 * + AUTOMATIC RTL DETECTION (LIGHTWEIGHT)
 * + TASK 2.2 — CHIP LABEL SPAN FOR TWO-LINE CLAMP
 * + MIN FIX — CHIP LABELS USE CATALOG AUTHORITY WHEN AVAILABLE
 * + FRONTEND BUTTON LINE BREAK MIRROR
 */

defined( 'ABSPATH' ) || exit;

// Render once only.
static $matewa_rendered = false;
if ( $matewa_rendered ) {
	return;
}
$matewa_rendered = true;

// Data.
$matewa_phone = preg_replace( '/[^0-9]/', '', get_option( 'matewa_number', '447900000000' ) );
$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;
$matewa_site  = wp_parse_url( home_url(), PHP_URL_HOST );
$matewa_site  = is_string( $matewa_site ) ? $matewa_site : '';

// Language + Direction.
$matewa_lang = function_exists( 'matewa_resolve_language' )
	? matewa_resolve_language()
	: 'en';

$matewa_is_rtl = in_array( substr( $matewa_lang, 0, 2 ), array( 'ar', 'he', 'fa', 'ur' ), true );

// Intro copy.
$matewa_intro_1 = matewa_get_i18n_label( 'intro.line_1' );
$matewa_intro_2 = matewa_get_i18n_label( 'intro.line_2' );
$matewa_intro_3 = matewa_get_i18n_label( 'intro.line_3' );

/* ======================================================
   LICENSE + VERTICAL ENFORCEMENT
====================================================== */

$matewa_vertical = function_exists( 'matewa_get_active_vertical' )
	? (array) matewa_get_active_vertical()
	: array();

$matewa_vertical_key = function_exists( 'matewa_get_active_vertical_key' )
	? matewa_get_active_vertical_key()
	: 'general';

$matewa_chips = is_array( $matewa_vertical['chips'] ?? null )
	? array_values( $matewa_vertical['chips'] )
	: array();

if ( empty( $matewa_chips ) ) {
	$matewa_chips = array( 'intent.other' );
}

$matewa_chip_labels = function_exists( 'matewa_get_active_vertical_chip_labels' )
	? (array) matewa_get_active_vertical_chip_labels()
	: array();

if ( count( $matewa_chip_labels ) !== count( $matewa_chips ) ) {
	$matewa_chip_labels = function_exists( 'matewa_get_effective_vertical_chip_labels' )
		? (array) matewa_get_effective_vertical_chip_labels( $matewa_vertical_key )
		: array();
}

if ( count( $matewa_chip_labels ) !== count( $matewa_chips ) ) {
	$matewa_chip_labels = array();

	foreach ( $matewa_chips as $matewa_chip_key ) {
		$matewa_chip_labels[] = function_exists( 'matewa_catalog_resolve_intent_label' )
			? matewa_catalog_resolve_intent_label( (string) $matewa_chip_key )
			: matewa_get_i18n_label( (string) $matewa_chip_key );
	}
}


/*
 * LICENCEVALIDATEFALLBACK1:
 * Free/expired sites should fall back to the simple public widget contract:
 * 4 visible chips total (3 standard choices + final "other" chip).
 * Pro, Trial and Master retain the full selected business-type chip set.
 */
$matewa_current_mode = function_exists( 'matewa_get_mode' )
	? matewa_get_mode()
	: ( defined( 'MATEWA_MODE_FREE' ) ? MATEWA_MODE_FREE : 'free' );

$matewa_free_like_mode = in_array(
	$matewa_current_mode,
	array(
		defined( 'MATEWA_MODE_FREE' ) ? MATEWA_MODE_FREE : 'free',
		defined( 'MATEWA_MODE_TRIAL_EXPIRED' ) ? MATEWA_MODE_TRIAL_EXPIRED : 'trial_expired',
	),
	true
);

if ( $matewa_free_like_mode ) {
	/*
	 * FALLBACKCHIPFITLOCK1:
	 * Free / trial-expired / invalid-licence mode must use the fixed public
	 * fallback chip contract and must not inherit old Pro/custom shortened labels.
	 */
	$matewa_chips = array(
		'intent.quote',
		'intent.pricing',
		'intent.availability',
		'intent.other',
	);

	$matewa_chip_labels = array(
		'Get a quote',
		'Pricing',
		'Availability',
		'Something else',
	);
}

/**
 * Return a safe i18n label, but prevent unresolved placeholder-like
 * values from leaking into the live frontend for critical UI strings.
 */
if ( ! function_exists( 'matewa_safe_i18n_label' ) ) {
	function matewa_safe_i18n_label( $key, $fallback ) {
		if ( ! function_exists( 'matewa_get_i18n_label' ) ) {
			return $fallback;
		}

		$value = matewa_get_i18n_label( $key );

		if ( ! is_string( $value ) || '' === trim( $value ) ) {
			return $fallback;
		}

		$normalized_value = trim( $value );
		$placeholder_forms = array(
			'Header Title',
			'Branding Powered_by',
		);

		if ( in_array( $normalized_value, $placeholder_forms, true ) ) {
			return $fallback;
		}

		return $normalized_value;
	}
}

if ( ! function_exists( 'matewa_get_widget_plan_status_label' ) ) {
	function matewa_get_widget_plan_status_label( $mode ) {
		$mode = sanitize_key( (string) $mode );

		$trial_modes = array(
			defined( 'MATEWA_MODE_TRIAL' ) ? MATEWA_MODE_TRIAL : 'trial_active',
			'trial',
		);

		$pro_modes = array(
			defined( 'MATEWA_MODE_PRO' ) ? MATEWA_MODE_PRO : 'pro',
			defined( 'MATEWA_MODE_MASTER' ) ? MATEWA_MODE_MASTER : 'master',
		);

		$global_modes = array(
			defined( 'MATEWA_MODE_GLOBAL' ) ? MATEWA_MODE_GLOBAL : 'global',
			'global',
			'global_active',
			'pro_global',
			'agency_global',
		);

		if ( in_array( $mode, $global_modes, true ) ) {
			$label = 'Global';
		} elseif ( in_array( $mode, $pro_modes, true ) ) {
			$label = 'Pro';
		} elseif ( in_array( $mode, $trial_modes, true ) ) {
			$label = 'Trial';
		} else {
			$label = 'Freemium';
		}

		$label = apply_filters( 'matewa_widget_plan_status_label', $label, $mode );

		return '' !== trim( (string) $label ) ? sanitize_text_field( (string) $label ) : 'Freemium';
	}
}

$matewa_launcher_aria       = matewa_safe_i18n_label( 'launcher.aria_label', 'Open chat' );
$matewa_header_title        = matewa_safe_i18n_label( 'header.title', 'Chat with us' );
$matewa_close_aria          = matewa_safe_i18n_label( 'close.aria_label', 'Close chat' );
$matewa_widget_status_label = matewa_get_widget_plan_status_label( $matewa_current_mode );
$matewa_brand_label         = sprintf( 'Powered by 247ChatMate %s', $matewa_widget_status_label );
?>

<div id="matewa-wrapper" dir="<?php echo esc_attr( $matewa_is_rtl ? 'rtl' : 'ltr' ); ?>">

	<button
		id="matewa-launcher"
		type="button"
		aria-label="<?php echo esc_attr( $matewa_launcher_aria ); ?>"
	></button>

	<div
		id="matewa-widget"
		class="matewa-widget"
		role="dialog"
		aria-labelledby="matewa-header-title"
		aria-hidden="true"
		data-phone="<?php echo esc_attr( $matewa_phone ); ?>"
		data-site="<?php echo esc_attr( $matewa_site ); ?>"
		data-mode="<?php echo esc_attr( $matewa_current_mode ); ?>"
		data-widget-language="<?php echo esc_attr( $matewa_lang ); ?>"
	>

		<!-- HEADER -->
		<div class="matewa-header">
			<div id="matewa-header-title" class="matewa-header-title"><?php echo esc_html( $matewa_header_title ); ?></div>
			<button
				type="button"
				class="matewa-close"
				aria-label="<?php echo esc_attr( $matewa_close_aria ); ?>"
			>×</button>
		</div>

		<!-- SCROLL BODY -->
		<div class="matewa-bubbles">
			<div class="matewa-stream">

				<!-- INTRO -->
				<div class="matewa-intro">
					<div class="matewa-bubble"><?php echo esc_html( $matewa_intro_1 ); ?></div>
					<div class="matewa-bubble matewa-muted"><?php echo esc_html( $matewa_intro_2 ); ?></div>
				</div>

			</div>
		</div>

		<!-- CTA -->
		<div class="matewa-cta" role="group" aria-label="WhatsApp chat actions" aria-live="polite" aria-hidden="true"></div>

		<!-- BRAND -->
		<div class="matewa-branding">
			<a
				href="<?php echo esc_url( 'https://247chatmate.com' ); ?>"
				target="_blank"
				rel="noopener noreferrer"
			>
				<?php echo esc_html( $matewa_brand_label ); ?>
			</a>
		</div>

	</div>
</div>

<!-- ======================================================
	 TASK TEMPLATES
====================================================== -->

<!-- INTENT -->
<template id="matewa-task-intent-template">
	<div class="matewa-task matewa-task-intent" data-task="intent">

		<div class="matewa-bubble">
			<?php echo esc_html( $matewa_intro_3 ); ?>
		</div>

		<div class="matewa-chip-group">
			<?php foreach ( $matewa_chips as $matewa_index => $matewa_chip_key ) : ?>

				<?php
				$matewa_intent = str_replace( 'intent.', '', $matewa_chip_key );

				$matewa_label = isset( $matewa_chip_labels[ $matewa_index ] ) && '' !== trim( (string) $matewa_chip_labels[ $matewa_index ] )
					? (string) $matewa_chip_labels[ $matewa_index ]
					: (
						function_exists( 'matewa_catalog_resolve_intent_label' )
							? matewa_catalog_resolve_intent_label( (string) $matewa_chip_key )
							: matewa_get_i18n_label( (string) $matewa_chip_key )
					);

				$matewa_is_other = ( 'other' === $matewa_intent );
				?>

				<button
					type="button"
					class="matewa-chip<?php echo esc_attr( $matewa_is_other ? ' matewa-chip-other' : '' ); ?>"
					data-intent="<?php echo esc_attr( $matewa_intent ); ?>"
					aria-pressed="false"
				>
					<span class="matewa-chip-label" style="white-space: pre-line;"><?php echo esc_html( $matewa_label ); ?></span>
				</button>

			<?php endforeach; ?>
		</div>

	</div>
</template>

<!-- NOTES -->
<template id="matewa-task-notes-template">
	<div class="matewa-notes" data-task="notes">

		<div class="matewa-bubble">
			<?php echo esc_html( matewa_get_i18n_label( 'notes.label' ) ); ?>
		</div>

		<textarea
			class="matewa-notes-textarea"
			rows="4"
			maxlength="140"
			aria-label="<?php echo esc_attr( matewa_get_i18n_label( 'notes.label' ) ); ?>"
			aria-describedby="matewa-notes-counter"
			placeholder="<?php echo esc_attr( matewa_get_i18n_label( 'notes.placeholder' ) ); ?>"
		></textarea>

		<div id="matewa-notes-counter" class="matewa-char-counter" aria-live="polite" aria-atomic="true">0 / 140</div>

	</div>
</template>

<!-- PHONE -->
<template id="matewa-task-phone-template">
	<div class="matewa-phone" data-task="phone">

		<div class="matewa-bubble">
			<?php echo esc_html( matewa_get_i18n_label( 'phone.prompt' ) ); ?>
		</div>

		<div class="matewa-phone-field<?php echo $matewa_show_country_selector ? '' : ' matewa-phone-field--no-country-selector'; ?>">
			<div class="matewa-phone-country-picker<?php echo $matewa_show_country_selector ? '' : ' is-hidden'; ?>">
				<select class="matewa-phone-country" aria-label="Phone country code" tabindex="-1" aria-hidden="true">
					<option value="gb" data-dial-prefix="44" selected>🇬🇧 +44</option>
				</select>
				<button type="button" class="matewa-phone-code matewa-phone-country-button" aria-label="Choose phone country" aria-haspopup="listbox" aria-expanded="false" aria-controls="matewa-phone-country-menu">
					<span class="matewa-phone-country-flag">🇬🇧</span>
					<span class="matewa-phone-country-dial">+44</span>
				</button>
				<div id="matewa-phone-country-menu" class="matewa-phone-country-menu" role="listbox" aria-label="Phone country options" hidden></div>
			</div>
			<input
				type="tel"
				class="matewa-phone-input"
				aria-label="Mobile/cell number"
				aria-describedby="matewa-phone-helper"
				autocomplete="tel"
				placeholder="<?php echo esc_attr( matewa_get_i18n_label( 'phone.placeholder' ) ); ?>"
			/>
		</div>

		<div id="matewa-phone-helper" class="matewa-char-counter" aria-live="polite" aria-atomic="true">
			<?php echo esc_html( matewa_get_i18n_label( 'phone.mobile_only_hint' ) ); ?>
		</div>

	</div>
</template>

<!-- CONTACT -->
<template id="matewa-task-contact-template">
	<div class="matewa-contact" data-task="contact">

		<div class="matewa-bubble">
			<?php echo esc_html( matewa_get_i18n_label( 'contact.prompt' ) ); ?>
		</div>

		<input
			type="text"
			class="matewa-contact-name"
			aria-label="<?php echo esc_attr( matewa_get_i18n_label( 'contact.name_placeholder' ) ); ?>"
			aria-describedby="matewa-contact-name-hint"
			autocomplete="name"
			placeholder="<?php echo esc_attr( matewa_get_i18n_label( 'contact.name_placeholder' ) ); ?>"
		/>

		<div id="matewa-contact-name-hint" class="matewa-soft-hint">
			<?php echo esc_html( matewa_get_i18n_label( 'contact.optional' ) ); ?>
		</div>

		<input
			type="email"
			class="matewa-contact-email"
			aria-label="<?php echo esc_attr( matewa_get_i18n_label( 'contact.email_placeholder' ) ); ?>"
			aria-describedby="matewa-contact-email-hint"
			autocomplete="email"
			placeholder="<?php echo esc_attr( matewa_get_i18n_label( 'contact.email_placeholder' ) ); ?>"
		/>

		<div id="matewa-contact-email-hint" class="matewa-soft-hint">
			<?php echo esc_html( matewa_get_i18n_label( 'contact.optional' ) ); ?>
		</div>

	</div>
</template>