/**
 * @file assets/js/adminjs/mbs-admin-shortcodes.js
 * Shortcode and block-comment builder with copy-to-clipboard on Settings → Blocks & Shortcodes.
 * @package MyBookShowroom
 * @since   1.0.0
 */
( function () {
	'use strict';
	var __ = wp.i18n.__;

	// ── Shortcode assembly ───────────────────────────────────────────────────

	function buildShortcode( form ) {
		var tag    = form.dataset.shortcode;
		var fields = form.querySelectorAll( '[data-attr]' );
		var parts  = [];

		fields.forEach( function ( field ) {
			var attr     = field.dataset.attr;
			var def      = field.dataset.default !== undefined ? field.dataset.default : '';
			var required = field.dataset.required === 'true';
			var val      = field.value.trim();

			// Always include required attrs (even if empty).
			if ( required ) {
				parts.push( attr + '="' + val + '"' );
				return;
			}
			// Skip if value matches default or is empty.
			if ( val === def || val === '' ) {
				return;
			}
			parts.push( attr + '="' + val + '"' );
		} );

		return '[' + tag + ( parts.length ? ' ' + parts.join( ' ' ) : '' ) + ']';
	}

	// ── Block assembly ───────────────────────────────────────────────────────

	function buildBlock( form ) {
		var blockName = form.dataset.block;
		var fields    = form.querySelectorAll( '[data-attr]' );
		var attrs     = {};

		fields.forEach( function ( field ) {
			var attr = field.dataset.attr;
			var type = field.dataset.type || 'string';
			var val  = field.value.trim();

			if ( type === 'number' ) {
				attrs[ attr ] = parseInt( val, 10 ) || 0;
			} else if ( type === 'bool' ) {
				attrs[ attr ] = val === '1' || val === 'true';
			} else {
				attrs[ attr ] = val;
			}
		} );

		return '<!-- wp:' + blockName + ' ' + JSON.stringify( attrs ) + ' /-->';
	}

	// ── Wire a single builder form ───────────────────────────────────────────

	function attachBuilder( form ) {
		var output  = form.querySelector( '.mbs-builder-output' );
		if ( ! output ) {
			return;
		}
		var isBlock = !! form.dataset.block;

		function update() {
			output.textContent = isBlock ? buildBlock( form ) : buildShortcode( form );
		}

		form.querySelectorAll( '[data-attr]' ).forEach( function ( field ) {
			field.addEventListener( 'input',  update );
			field.addEventListener( 'change', update );
		} );

		update(); // seed the preview on load
	}

	// ── Copy button ──────────────────────────────────────────────────────────

	function attachCopy( btn ) {
		btn.addEventListener( 'click', function () {
			// Walk up to the nearest preview container then find the output.
			var container = btn.closest( '.mbs-builder-preview' );
			var output    = container ? container.querySelector( '.mbs-builder-output' ) : null;
			if ( ! output ) {
				return;
			}
			var text = output.textContent;

			if ( navigator.clipboard ) {
				navigator.clipboard.writeText( text ).then( function () {
					flashCopied( btn );
				} ).catch( function () {
					fallbackCopy( text, btn );
				} );
			} else {
				fallbackCopy( text, btn );
			}
		} );
	}

	function fallbackCopy( text, btn ) {
		var ta = document.createElement( 'textarea' );
		ta.value = text;
		ta.style.position = 'fixed';
		ta.style.opacity  = '0';
		document.body.appendChild( ta );
		ta.select();
		try {
			document.execCommand( 'copy' );
			flashCopied( btn );
		} catch ( e ) {
			// Silent fail — browser too restricted.
		}
		document.body.removeChild( ta );
	}

	function flashCopied( btn ) {
		var orig = btn.textContent;
		btn.textContent = __( 'Copied!', 'my-book-showroom' );
		setTimeout( function () { btn.textContent = orig; }, 1800 );
	}

	// ── Dismissible callout ──────────────────────────────────────────────────

	function attachCalloutDismiss() {
		var btn = document.querySelector( '.mbs-callout-dismiss' );
		if ( ! btn ) {
			return;
		}

		btn.addEventListener( 'click', function () {
			var callout = document.getElementById( 'mbs-add-to-pages-callout' );
			var nonce   = btn.dataset.nonce || '';

			// Hide immediately — don't wait for the AJAX round-trip.
			if ( callout ) {
				callout.style.display = 'none';
			}

			// Persist the dismissal so it doesn't reappear on next page load.
			var data = new URLSearchParams();
			data.append( 'action', 'mbs_dismiss_callout' );
			data.append( 'nonce',  nonce );

			fetch( window.ajaxurl, {
				method:      'POST',
				credentials: 'same-origin',
				body:        data,
			} );
		} );
	}

	// ── Init ─────────────────────────────────────────────────────────────────

	document.addEventListener( 'DOMContentLoaded', function () {
		document.querySelectorAll( '.mbs-builder' ).forEach( attachBuilder );
		document.querySelectorAll( '.mbs-copy-btn' ).forEach( attachCopy );
		attachCalloutDismiss();
	} );

} )();
