/**
 * Frontierline Forms - 条件分岐 (Conditional Logic)
 *
 * 書式（HTML属性ベース・最短実装）:
 *   data-cf7mp-show-if="フィールド名"
 *   data-cf7mp-show-value="値"            // 完全一致
 *   data-cf7mp-show-contains="部分文字列" // 部分一致
 *   data-cf7mp-show-op="eq|ne|contains|not-contains|filled|empty"
 *
 * 例:
 *   <div data-cf7mp-show-if="contact-type" data-cf7mp-show-value="estimate">見積関連</div>
 *
 * JSON書式（後方互換）:
 *   form data-cf7mp-conditional='[{field,target,action,operator,value}]'
 *
 * ルール数は無制限
 *
 * @package CF7MasterPro
 */

( function () {
	'use strict';

	class CF7MPConditional {
		constructor( form ) {
			this.form = form;
			this.cfg = window.cf7mpFrontend || {};
			this.rules = this.collectRules();
			this.jsonRules = this.loadJsonRules();
			if ( ! this.rules.length && ! this.jsonRules.length ) {
				return;
			}
			this.bindEvents();
			this.evaluate();
		}

		/**
		 * HTML属性ベースのルール収集
		 */
		collectRules() {
			const targets = this.form.querySelectorAll( '[data-cf7mp-show-if]' );
			return Array.from( targets ).map( ( el ) => ( {
				el,
				field: el.dataset.cf7mpShowIf,
				op: el.dataset.cf7mpShowOp ||
					( el.dataset.cf7mpShowContains ? 'contains' : 'eq' ),
				value: el.dataset.cf7mpShowValue ||
					el.dataset.cf7mpShowContains || '',
			} ) );
		}

		/**
		 * JSONベースのルール（管理画面UI向け将来拡張）
		 */
		loadJsonRules() {
			const data = this.form.dataset.cf7mpConditional;
			try {
				const arr = data ? JSON.parse( data ) : [];
				return Array.isArray( arr ) ? arr : [];
			} catch ( e ) {
				return [];
			}
		}

		bindEvents() {
			this.form.addEventListener( 'input', () => this.evaluate() );
			this.form.addEventListener( 'change', () => this.evaluate() );
		}

		evaluate() {
			// HTML属性ルール
			this.rules.forEach( ( rule ) => {
				const match = this.matchRule( rule );
				rule.el.classList.toggle( 'cf7mp-conditional__hidden', ! match );
				this.toggleInputs( rule.el, match );
			} );

			// JSONルール
			this.jsonRules.forEach( ( rule ) => {
				const target = this.form.querySelector(
					'[data-cf7mp-field="' + rule.target + '"]'
				);
				if ( ! target ) {
					return;
				}
				const fields = this.form.querySelectorAll(
					'[name="' + rule.field + '"], [name="' + rule.field + '[]"]'
				);
				if ( ! fields.length ) {
					return;
				}
				const value = this.getFieldValue( fields );
				const match = this.matchCondition( value, rule );
				const shouldHide = 'show' === rule.action ? ! match : match;
				target.classList.toggle( 'cf7mp-conditional__hidden', shouldHide );
				this.toggleInputs( target, ! shouldHide );
			} );
		}

		matchRule( rule ) {
			const fields = this.form.querySelectorAll(
				'[name="' + rule.field + '"], [name="' + rule.field + '[]"]'
			);
			if ( ! fields.length ) {
				return true;
			}
			const value = this.getFieldValue( fields );
			return this.compare( value, rule.op, rule.value );
		}

		compare( value, op, expected ) {
			switch ( op ) {
				case 'ne':
				case 'not_equals':
					return value !== expected;
				case 'contains':
					return value.indexOf( expected ) >= 0;
				case 'not-contains':
					return value.indexOf( expected ) < 0;
				case 'filled':
				case 'not_empty':
					return '' !== value.trim();
				case 'empty':
					return '' === value.trim();
				case 'eq':
				case 'equals':
				default:
					if ( '' === expected ) {
						return '' !== value.trim();
					}
					return value === expected;
			}
		}

		matchCondition( value, rule ) {
			return this.compare( value, rule.operator, rule.value );
		}

		getFieldValue( fields ) {
			const first = fields[ 0 ];
			if ( 'checkbox' === first.type || 'radio' === first.type ) {
				const checked = Array.from( fields ).filter( ( f ) => f.checked );
				return checked.map( ( f ) => f.value ).join( ',' );
			}
			if ( 'SELECT' === first.tagName ) {
				return Array.from( first.selectedOptions ).map( ( o ) => o.value ).join( ',' );
			}
			return first.value;
		}

		toggleInputs( wrapper, enabled ) {
			const inputs = wrapper.querySelectorAll( 'input, textarea, select' );
			inputs.forEach( ( inp ) => {
				inp.disabled = ! enabled;
			} );
		}
	}

	document.addEventListener( 'DOMContentLoaded', () => {
		document.querySelectorAll( '.wpcf7-form' ).forEach( ( form ) => {
			if (
				form.querySelector( '[data-cf7mp-show-if]' ) ||
				form.dataset.cf7mpConditional
			) {
				new CF7MPConditional( form );
			}
		} );
	} );
} )();
