/**
 * AIEO Google One Tap — recognise-only loader (runtime copy; keep in sync with
 * the core plugin's assets/js/aieo-one-tap.js).
 *
 * Fires the One Tap "Continue as…" prompt for logged-out visitors who have
 * granted the `personalize` consent — on page load for returning consenters,
 * AND the instant they grant it in the consent banner (aieo:personalize-granted),
 * so the prompt appearing is the confirmation. On tap it POSTs the Google ID
 * token to the recognise-only endpoint, which binds the verified identity to
 * this browser's push subscription — no login, no account. FedCM-ready.
 */
( function () {
	var cfg = window.aieoOneTap || {};
	if ( ! cfg.clientId || ! cfg.endpoint ) { return; }

	// Skip logged-in WP users (cache-safe: per-browser cookie, not server-rendered).
	if ( /(?:^|;\s*)wordpress_logged_in_/.test( document.cookie ) ) { return; }

	// Consent gate — the `personalize` flag in the first-party consent cookie.
	function consentOk() {
		try {
			var m = document.cookie.match( /(?:^|;\s*)aieo_consent=([^;]*)/ );
			if ( ! m ) { return false; }
			var o = JSON.parse( decodeURIComponent( m[ 1 ] ) );
			return !! ( o && o.personalize );
		} catch ( e ) { return false; }
	}

	function onCredential( resp ) {
		if ( ! resp || ! resp.credential ) { return; }
		try { sessionStorage.setItem( 'aieo_ot', '1' ); } catch ( e ) {}
		var fd = new FormData();
		fd.append( 'id_token', resp.credential );
		// credentials:'same-origin' so the aieo_push_session cookie is sent — the
		// server binds the identity to THIS browser's push subscription.
		fetch( cfg.endpoint, { method: 'POST', credentials: 'same-origin', body: fd } ).catch( function () {} );
	}

	var fired = false;
	function doPrompt() {
		if ( ! window.google || ! google.accounts || ! google.accounts.id ) { return; }
		try {
			google.accounts.id.initialize( {
				client_id: cfg.clientId,
				callback: onCredential,
				context: 'use',
				auto_select: false,
				cancel_on_tap_outside: true,
				use_fedcm_for_prompt: true
			} );
			google.accounts.id.prompt();
		} catch ( e ) {}
	}
	function loadAndPrompt() {
		if ( window.google && google.accounts && google.accounts.id ) { doPrompt(); return; }
		var s = document.createElement( 'script' );
		s.src = 'https://accounts.google.com/gsi/client';
		s.async = true;
		s.defer = true;
		s.onload = doPrompt;
		( document.head || document.documentElement ).appendChild( s );
	}
	function maybeFire() {
		if ( fired ) { return; }
		try { if ( sessionStorage.getItem( 'aieo_ot' ) === '1' ) { return; } } catch ( e ) {}
		if ( ! consentOk() ) { return; }
		fired = true;
		loadAndPrompt();
	}

	maybeFire(); // returning visitor who already consented
	// Fire the instant the shopper grants personalisation in the consent banner.
	document.addEventListener( 'aieo:personalize-granted', maybeFire );
} )();
