/**
 * AI Sales Assistant — frontend attribution capture.
 *
 * Listens for postMessage events from the widget iframe and stores the
 * conversation_id + chat_timestamp in a cookie and sessionStorage so the
 * checkout flow can attribute orders back to the chat that drove them.
 *
 * Widget origin is passed in via `kwiroSalesTracker.widgetOrigin`
 * (wp_localize_script) so we can validate every incoming message.
 *
 * @package KwiroAISalesAgent
 */

/* global kwiroSalesTracker */
(function () {
	'use strict';

	var widgetOrigin = ( window.kwiroSalesTracker && window.kwiroSalesTracker.widgetOrigin ) || '';
	var kwiroConvId = '';
	var kwiroTimestamp = '';

	// Read existing attribution from cookie (persists across pages).
	try {
		var cookieMatch = document.cookie.match( /kwiro_conv=([^;]+)/ );
		if ( cookieMatch ) {
			var parts = cookieMatch[ 1 ].split( '|' );
			kwiroConvId   = parts[ 0 ] || '';
			kwiroTimestamp = parts[ 1 ] || '';
		}
	} catch ( e ) {
		/* sessionStorage / cookies may be disabled — silently fall back */
	}

	window.addEventListener( 'message', function ( event ) {
		// SECURITY: only accept attribution events from the widget iframe.
		// Without an origin check, any third-party iframe on the storefront
		// could plant a fake conversation_id on outgoing orders, claiming
		// AI-attribution credit it didn't earn.
		if ( ! widgetOrigin || event.origin !== widgetOrigin ) {
			return;
		}
		var iframe = document.getElementById( 'kwiro-chat-widget' );
		if ( ! iframe || event.source !== iframe.contentWindow ) {
			return;
		}
		if ( ! event.data || event.data.type !== 'kwiro_attribution' ) {
			return;
		}
		// Validate the conversation_id shape — must be a UUID. Anything
		// else is a malformed message we should drop on the floor.
		var convId = event.data.conversationId;
		if ( typeof convId !== 'string' || ! /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( convId ) ) {
			return;
		}

		kwiroConvId = convId;
		// Always normalize to seconds-since-epoch (PHP `time()` is seconds, but
		// `Date.now()` and `event.data.timestamp` are milliseconds — see get_attribution()
		// for the legacy-rescaling counterpart on the read side).
		var rawTs = Number( event.data.timestamp ) || Date.now();
		kwiroTimestamp = String( Math.floor( rawTs / 1000 ) );

		// Store in cookie (24h TTL) — persists across ALL pages until checkout.
		var expires = new Date( Date.now() + 86400000 ).toUTCString();
		document.cookie = 'kwiro_conv=' + kwiroConvId + '|' + kwiroTimestamp + '; expires=' + expires + '; path=/; SameSite=Lax';

		// Also store in sessionStorage for block checkout.
		try {
			sessionStorage.setItem( 'kwiro_conversation_id', kwiroConvId );
			sessionStorage.setItem( 'kwiro_chat_timestamp', kwiroTimestamp );
		} catch ( e ) {
			/* private mode — ignore */
		}
	} );

	function injectField( form, name, value ) {
		var input = form.querySelector( 'input[name="' + name + '"]' );
		if ( ! input ) {
			input = document.createElement( 'input' );
			input.type = 'hidden';
			input.name = name;
			form.appendChild( input );
		}
		input.value = value;
	}

	// On checkout page: inject attribution into the form.
	var checkoutForm = document.querySelector( 'form.checkout, form#order_review' );
	if ( checkoutForm && kwiroConvId ) {
		injectField( checkoutForm, '_kwiro_conversation_id', kwiroConvId );
		injectField( checkoutForm, '_kwiro_chat_timestamp', kwiroTimestamp );
	}
	// Also watch for dynamically loaded checkout forms.
	var observer = new MutationObserver( function () {
		var form = document.querySelector( 'form.checkout, form#order_review' );
		if ( form && kwiroConvId ) {
			injectField( form, '_kwiro_conversation_id', kwiroConvId );
			injectField( form, '_kwiro_chat_timestamp', kwiroTimestamp );
		}
	} );
	observer.observe( document.body, { childList: true, subtree: true } );

	// Block checkout: intercept the Store API checkout request to attach attribution.
	var origFetch = window.fetch;
	window.fetch = function ( url, opts ) {
		if ( typeof url === 'string' && url.indexOf( '/wc/store/v1/checkout' ) !== -1 && opts && opts.method === 'POST' ) {
			var convId = '';
			try {
				convId = sessionStorage.getItem( 'kwiro_conversation_id' ) || '';
			} catch ( e ) {
				/* ignore */
			}
			if ( convId && opts.body ) {
				try {
					var body = JSON.parse( opts.body );
					if ( ! body.extensions ) {
						body.extensions = {};
					}
					body.extensions.kwiro_attribution = {
						conversation_id: convId,
						chat_timestamp: sessionStorage.getItem( 'kwiro_chat_timestamp' ) || ''
					};
					opts.body = JSON.stringify( body );
				} catch ( e ) {
					/* malformed body — leave it alone */
				}
			}
		}
		return origFetch.apply( this, arguments );
	};
})();
