/**
 * Biscotti CMP — Terms (AGB) Questionnaire (local admin script)
 *
 * Evaluates each question's/category's conditional-visibility rule against the
 * current answers + context, collects all answers into a single object and
 * persists them via the save-agb-data proxy (stored in legalEntity.agbData).
 *
 * Condition grammar (matches the server catalog):
 *   "always" | "field==value" | "field!=value" | "field.includes(value)" |
 *   "field.startsWith(prefix)" | combined with " && " / " || ".
 * Fields may be question IDs or context keys (businessType, targetAudience, jurisdiction).
 *
 * @package Biscotti_CMP
 */
( function ( $ ) {
	'use strict';

	var cfg = window.biscottiAdmin || {};
	var i18n = cfg.i18n || {};
	function t( k, f ) { return i18n[ k ] || f; }

	var CONTEXT = {};
	try {
		var el = document.getElementById( 'biscotti-agb-context' );
		if ( el ) { CONTEXT = JSON.parse( el.textContent || '{}' ); }
	} catch ( e ) { /* ignore */ }

	// Read current value of a question by id (from the rendered inputs).
	function currentValue( qid ) {
		if ( CONTEXT && Object.prototype.hasOwnProperty.call( CONTEXT, qid ) ) {
			return CONTEXT[ qid ];
		}
		var multi = document.querySelectorAll( '.biscotti-agb-multi[data-qid="' + qid + '"]' );
		if ( multi.length ) {
			return Array.prototype.filter.call( multi, function ( c ) { return c.checked; } ).map( function ( c ) { return c.value; } );
		}
		var input = document.querySelector( '.biscotti-agb-input[data-qid="' + qid + '"]' );
		if ( ! input ) { return undefined; }
		if ( input.type === 'checkbox' ) { return input.checked; }
		return input.value;
	}

	// Evaluate a single atomic condition like "field==value".
	function evalAtom( atom ) {
		atom = atom.trim();
		if ( ! atom || atom === 'always' ) { return true; }
		var m;
		// field.includes(value)
		m = atom.match( /^([\w.]+)\.includes\(([^)]*)\)$/ );
		if ( m ) {
			var v = currentValue( m[1] );
			return Array.isArray( v ) ? v.indexOf( m[2] ) !== -1 : String( v == null ? '' : v ).indexOf( m[2] ) !== -1;
		}
		// field.startsWith(prefix)
		m = atom.match( /^([\w.]+)\.startsWith\(([^)]*)\)$/ );
		if ( m ) {
			var sv = currentValue( m[1] );
			return String( sv == null ? '' : sv ).indexOf( m[2] ) === 0;
		}
		// field!=value
		m = atom.match( /^([\w.]+)!=(.*)$/ );
		if ( m ) {
			return String( normalize( currentValue( m[1] ) ) ) !== m[2].trim();
		}
		// field==value
		m = atom.match( /^([\w.]+)==(.*)$/ );
		if ( m ) {
			return String( normalize( currentValue( m[1] ) ) ) === m[2].trim();
		}
		// bare field → truthy
		return !! currentValue( atom );
	}

	function normalize( v ) {
		if ( v === true ) { return 'true'; }
		if ( v === false ) { return 'false'; }
		return v == null ? '' : v;
	}

	// Evaluate a full condition expression with && and ||.
	function evalCondition( expr ) {
		if ( ! expr || expr === 'always' ) { return true; }
		// OR has lower precedence than AND.
		return expr.split( '||' ).some( function ( orPart ) {
			return orPart.split( '&&' ).every( function ( andPart ) { return evalAtom( andPart ); } );
		} );
	}

	function applyConditions() {
		document.querySelectorAll( '.biscotti-agb-q' ).forEach( function ( q ) {
			var cond = q.getAttribute( 'data-condition' ) || 'always';
			q.style.display = evalCondition( cond ) ? '' : 'none';
		} );
		document.querySelectorAll( '.biscotti-agb-cat' ).forEach( function ( cat ) {
			var cond = cat.getAttribute( 'data-condition' ) || 'always';
			// Hide category only if its own condition fails or all its questions are hidden.
			var ownVisible = evalCondition( cond );
			var anyVisible = Array.prototype.some.call( cat.querySelectorAll( '.biscotti-agb-q' ), function ( q ) { return q.style.display !== 'none'; } );
			cat.style.display = ( ownVisible && anyVisible ) ? '' : 'none';
		} );
	}

	function collectAnswers() {
		var out = {};
		document.querySelectorAll( '.biscotti-agb-q' ).forEach( function ( q ) {
			if ( q.style.display === 'none' ) { return; } // only persist visible/applicable answers
			var qid = q.getAttribute( 'data-question-id' );
			var type = q.getAttribute( 'data-type' );
			if ( type === 'multiselect' ) {
				out[ qid ] = Array.prototype.filter.call( q.querySelectorAll( '.biscotti-agb-multi' ), function ( c ) { return c.checked; } ).map( function ( c ) { return c.value; } );
			} else {
				var v = currentValue( qid );
				if ( type === 'number' ) { v = v === '' || v == null ? null : parseInt( v, 10 ); }
				out[ qid ] = v;
			}
		} );
		return out;
	}

	// Exposed so the Legal Wizard's single Save can persist the AGB answers
	// alongside the legal entity. The Contract step renders this catalog inline
	// (the standalone "Terms Questionnaire" page is gone), so there is no separate
	// AGB save button anymore — legal-wizard.js calls this on Save/Next.
	window.biscottiAgbCollectAnswers = collectAnswers;
	window.biscottiAgbHasForm = function () { return !! document.getElementById( 'biscotti-agb-form' ); };

	$( function () {
		if ( ! document.getElementById( 'biscotti-agb-form' ) ) { return; }
		applyConditions();
		$( document ).on( 'change', '.biscotti-agb-input, .biscotti-agb-multi', applyConditions );
	} );
} )( jQuery );
