( function () {
	'use strict';

	var cfg = window.PlatformHelmSchema || {};

	function addRow( containerId, templateId ) {
		var container = document.getElementById( containerId );
		var tpl = document.getElementById( templateId );
		if ( ! container || ! tpl ) { return; }
		var node = tpl.content ? tpl.content.cloneNode( true ) : null;
		if ( node ) { container.appendChild( node ); }
	}

	function setVal( name, val ) {
		var el = document.querySelector( '[name="' + name + '"]' );
		if ( el ) { el.value = val || ''; }
	}

	function fillRows( containerId, templateId, items, k1, k2 ) {
		var container = document.getElementById( containerId );
		var tpl = document.getElementById( templateId );
		if ( ! container || ! tpl || ! tpl.content ) { return; }
		container.innerHTML = '';
		if ( ! items || ! items.length ) {
			container.appendChild( tpl.content.cloneNode( true ) );
			return;
		}
		items.forEach( function ( item ) {
			var node = tpl.content.cloneNode( true );
			var input = node.querySelector( 'input[type="text"]' );
			var textarea = node.querySelector( 'textarea' );
			if ( input ) { input.value = item[ k1 ] || ''; }
			if ( textarea ) { textarea.value = item[ k2 ] || ''; }
			container.appendChild( node );
		} );
	}

	function getPostId() {
		try {
			if ( window.wp && wp.data && wp.data.select( 'core/editor' ) ) {
				var id = wp.data.select( 'core/editor' ).getCurrentPostId();
				if ( id ) { return id; }
			}
		} catch ( e ) {}
		var el = document.getElementById( 'post_ID' );
		return el ? el.value : '';
	}

	function doGenerate( btn ) {
		var msg = document.getElementById( 'ph-schema-gen-msg' );
		var id = getPostId();
		if ( ! id ) {
			if ( msg ) { msg.textContent = 'Save the post once so it has an ID, then try again.'; }
			return;
		}
		btn.disabled = true;
		var label = btn.textContent;
		btn.textContent = 'Reading the article…';
		if ( msg ) { msg.textContent = ''; }

		var body = new URLSearchParams();
		body.append( 'action', cfg.action );
		body.append( 'nonce', cfg.nonce );
		body.append( 'post_id', id );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( res ) {
				btn.disabled = false; btn.textContent = label;
				if ( ! res || res.success !== true || ! res.data ) {
					if ( msg ) { msg.textContent = ( res && res.data && res.data.message ) ? res.data.message : 'Could not generate.'; }
					return;
				}
				var d = res.data;
				var howto = d.howto || {};
				setVal( 'topla_howto_name', howto.name );
				setVal( 'topla_howto_description', howto.description );
				fillRows( 'ph-howto-steps', 'ph-step-tpl', howto.steps || [], 'name', 'text' );
				fillRows( 'ph-faq-rows', 'ph-faq-tpl', d.faq || [], 'q', 'a' );
				var nSteps = ( howto.steps || [] ).length;
				var nFaq = ( d.faq || [] ).length;
				if ( msg ) { msg.textContent = 'Drafted ' + nSteps + ' step(s) and ' + nFaq + ' FAQ(s). Review, edit, then Update the post to save.'; }
			} )
			.catch( function () {
				btn.disabled = false; btn.textContent = label;
				if ( msg ) { msg.textContent = 'Request failed — try again.'; }
			} );
	}

	document.addEventListener( 'click', function ( e ) {
		var t = e.target;
		if ( ! t ) { return; }
		if ( t.id === 'ph-add-step' ) { e.preventDefault(); addRow( 'ph-howto-steps', 'ph-step-tpl' ); }
		if ( t.id === 'ph-add-faq' ) { e.preventDefault(); addRow( 'ph-faq-rows', 'ph-faq-tpl' ); }
		if ( t.id === 'ph-schema-generate' ) { e.preventDefault(); doGenerate( t ); }
		if ( t.classList && t.classList.contains( 'ph-schema-remove' ) ) {
			e.preventDefault();
			var row = t.closest( '.ph-schema-row' );
			if ( row ) { row.parentNode.removeChild( row ); }
		}
	} );
}() );
